@self-review/core 1.42.0 → 1.43.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/dist/index.cjs CHANGED
@@ -30,12 +30,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ ForgeCliUnavailableError: () => ForgeCliUnavailableError,
33
34
  GUIDE_XSD_SCHEMA: () => GUIDE_XSD_SCHEMA,
34
35
  IMPLICIT_GUIDE_GROUP_NAME: () => IMPLICIT_GUIDE_GROUP_NAME,
36
+ REVIEW_LEVEL_FILE_PATH: () => REVIEW_LEVEL_FILE_PATH,
35
37
  checkWritability: () => checkWritability,
36
38
  computePayloadStats: () => computePayloadStats,
37
39
  countTotalLines: () => countTotalLines,
40
+ createGitHubProvider: () => createGitHubProvider,
41
+ createGitLabProvider: () => createGitLabProvider,
38
42
  createIgnoreFilter: () => createIgnoreFilter,
43
+ defaultGitRunner: () => defaultGitRunner,
39
44
  generateSyntheticDiffs: () => generateSyntheticDiffs,
40
45
  generateUntrackedDiffs: () => generateUntrackedDiffs,
41
46
  getGitDiffStats: () => getGitDiffStats,
@@ -50,11 +55,15 @@ __export(index_exports, {
50
55
  isPreviewableRenderedText: () => isPreviewableRenderedText,
51
56
  isPreviewableSvg: () => isPreviewableSvg,
52
57
  loadConfig: () => loadConfig,
58
+ mapThreadsToReviewComments: () => mapThreadsToReviewComments,
59
+ materialize: () => materialize,
53
60
  parseDiff: () => parseDiff,
61
+ parseForgeUrl: () => parseForgeUrl,
54
62
  parseGuideXml: () => parseGuideXml,
55
63
  parseReviewXml: () => parseReviewXml,
56
64
  parseReviewXmlString: () => parseReviewXmlString,
57
65
  reconcileGuide: () => reconcileGuide,
66
+ resolveRemoteDefaultBranch: () => resolveRemoteDefaultBranch,
58
67
  runGitDiff: () => runGitDiff,
59
68
  runGitDiffAsync: () => runGitDiffAsync,
60
69
  scanDirectory: () => scanDirectory,
@@ -112,13 +121,13 @@ function parseDiff(rawDiff) {
112
121
  continue;
113
122
  }
114
123
  if (line.startsWith("--- ")) {
115
- const path2 = line.substring(4);
116
- currentFile.oldPath = path2 === "/dev/null" ? "" : stripPrefix(path2);
124
+ const path3 = line.substring(4);
125
+ currentFile.oldPath = path3 === "/dev/null" ? "" : stripPrefix(path3);
117
126
  continue;
118
127
  }
119
128
  if (line.startsWith("+++ ")) {
120
- const path2 = line.substring(4);
121
- currentFile.newPath = path2 === "/dev/null" ? "" : stripPrefix(path2);
129
+ const path3 = line.substring(4);
130
+ currentFile.newPath = path3 === "/dev/null" ? "" : stripPrefix(path3);
122
131
  continue;
123
132
  }
124
133
  if (line.startsWith("Binary files ")) {
@@ -203,11 +212,11 @@ function parseDiff(rawDiff) {
203
212
  }
204
213
  return files;
205
214
  }
206
- function stripPrefix(path2) {
207
- if (path2.length > 2 && path2[1] === "/") {
208
- return path2.substring(2);
215
+ function stripPrefix(path3) {
216
+ if (path3.length > 2 && path3[1] === "/") {
217
+ return path3.substring(2);
209
218
  }
210
- return path2;
219
+ return path3;
211
220
  }
212
221
  function parseGitDiffHeader(line) {
213
222
  const withoutPrefix = line.substring("diff --git ".length);
@@ -266,6 +275,14 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
266
275
  - <comment> gained an optional, unbounded <reply> child, so a finding
267
276
  and the responses to it form a single legible thread instead of a
268
277
  set of disconnected assertions. See ReplyType.
278
+
279
+ Amended in place (still v3):
280
+ - The review root gained optional remote-url, remote-base-sha,
281
+ remote-head-sha and remote-forge attributes, and <comment> and
282
+ <reply> gained an optional remote-id attribute, so a review taken
283
+ against a remote pull/merge request records its provenance. Purely
284
+ additive: a document carrying none of them is unchanged. See
285
+ ReviewType.
269
286
  -->
270
287
 
271
288
  <!-- ===== Root element ===== -->
@@ -317,6 +334,51 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
317
334
  </xs:documentation>
318
335
  </xs:annotation>
319
336
  </xs:attribute>
337
+ <xs:attribute name="remote-url" type="xs:string" use="optional">
338
+ <xs:annotation>
339
+ <xs:documentation>
340
+ URL of the remote pull/merge request this review was taken
341
+ against. Example: "https://github.com/owner/repo/pull/42".
342
+ Present only when reviewing a remote PR/MR.
343
+
344
+ The remote-* attributes form a third source shape alongside
345
+ git-diff-args/repository (local git diff) and source-path
346
+ (directory review). The three shapes are mutually exclusive;
347
+ XSD 1.0 cannot express that constraint, so it is enforced by
348
+ the application.
349
+ </xs:documentation>
350
+ </xs:annotation>
351
+ </xs:attribute>
352
+ <xs:attribute name="remote-base-sha" type="xs:string" use="optional">
353
+ <xs:annotation>
354
+ <xs:documentation>
355
+ Commit SHA the remote diff was computed from (the base of the
356
+ PR/MR at fetch time). Together with remote-head-sha it pins the
357
+ review to the exact diff it was written against, so a consumer
358
+ can detect drift when the remote branch moves.
359
+ Present only when reviewing a remote PR/MR.
360
+ </xs:documentation>
361
+ </xs:annotation>
362
+ </xs:attribute>
363
+ <xs:attribute name="remote-head-sha" type="xs:string" use="optional">
364
+ <xs:annotation>
365
+ <xs:documentation>
366
+ Commit SHA of the head of the remote PR/MR branch at fetch time.
367
+ See remote-base-sha for how the pair supports drift detection.
368
+ Present only when reviewing a remote PR/MR.
369
+ </xs:documentation>
370
+ </xs:annotation>
371
+ </xs:attribute>
372
+ <xs:attribute name="remote-forge" type="sr:RemoteForgeEnum" use="optional">
373
+ <xs:annotation>
374
+ <xs:documentation>
375
+ Which forge hosts the remote PR/MR. Names the id space of the
376
+ remote-id attributes on comments and replies, and selects the
377
+ API machinery a future posting feature would use.
378
+ Present only when reviewing a remote PR/MR.
379
+ </xs:documentation>
380
+ </xs:annotation>
381
+ </xs:attribute>
320
382
  </xs:complexType>
321
383
 
322
384
  <xs:complexType name="FileType">
@@ -510,6 +572,19 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
510
572
  </xs:documentation>
511
573
  </xs:annotation>
512
574
  </xs:attribute>
575
+ <xs:attribute name="remote-id" type="xs:string" use="optional">
576
+ <xs:annotation>
577
+ <xs:documentation>
578
+ Identifier of the remote discussion thread or comment this
579
+ comment was fetched from, in the id space of the forge named by
580
+ remote-forge on the review root. Provenance and forward
581
+ machinery: it lets a consumer trace the finding back to its
582
+ origin, and a future posting feature reply to the existing
583
+ thread instead of opening a new one. Absent on comments
584
+ authored locally.
585
+ </xs:documentation>
586
+ </xs:annotation>
587
+ </xs:attribute>
513
588
  </xs:complexType>
514
589
 
515
590
  <xs:complexType name="ReplyType">
@@ -578,6 +653,19 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
578
653
  </xs:documentation>
579
654
  </xs:annotation>
580
655
  </xs:attribute>
656
+ <xs:attribute name="remote-id" type="xs:string" use="optional">
657
+ <xs:annotation>
658
+ <xs:documentation>
659
+ Identifier of the remote comment this reply was fetched from,
660
+ with the same semantics as CommentType/@remote-id: an id in the
661
+ forge's own id space, kept for provenance and for a future
662
+ posting feature. Absent on replies authored locally.
663
+
664
+ A remote-id is not an ordering signal. Document order remains
665
+ conversation order, exactly as rule 1 above states.
666
+ </xs:documentation>
667
+ </xs:annotation>
668
+ </xs:attribute>
581
669
  </xs:complexType>
582
670
 
583
671
  <xs:complexType name="SuggestionType">
@@ -748,6 +836,26 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
748
836
  </xs:restriction>
749
837
  </xs:simpleType>
750
838
 
839
+ <xs:simpleType name="RemoteForgeEnum">
840
+ <xs:annotation>
841
+ <xs:documentation>
842
+ The forge hosting a remote pull/merge request.
843
+ </xs:documentation>
844
+ </xs:annotation>
845
+ <xs:restriction base="xs:string">
846
+ <xs:enumeration value="github">
847
+ <xs:annotation>
848
+ <xs:documentation>A GitHub pull request.</xs:documentation>
849
+ </xs:annotation>
850
+ </xs:enumeration>
851
+ <xs:enumeration value="gitlab">
852
+ <xs:annotation>
853
+ <xs:documentation>A GitLab merge request.</xs:documentation>
854
+ </xs:annotation>
855
+ </xs:enumeration>
856
+ </xs:restriction>
857
+ </xs:simpleType>
858
+
751
859
  </xs:schema>`;
752
860
  function extFromMediaType(mediaType) {
753
861
  const map = {
@@ -842,12 +950,29 @@ function buildSourceAttributes(state) {
842
950
  }
843
951
  return "";
844
952
  }
953
+ function buildRemoteAttributes(state) {
954
+ const attrs = [];
955
+ if (state.remoteUrl) {
956
+ attrs.push(`remote-url="${escapeXml(state.remoteUrl)}"`);
957
+ }
958
+ if (state.remoteBaseSha) {
959
+ attrs.push(`remote-base-sha="${escapeXml(state.remoteBaseSha)}"`);
960
+ }
961
+ if (state.remoteHeadSha) {
962
+ attrs.push(`remote-head-sha="${escapeXml(state.remoteHeadSha)}"`);
963
+ }
964
+ if (state.remoteForge) {
965
+ attrs.push(`remote-forge="${state.remoteForge}"`);
966
+ }
967
+ return attrs.length > 0 ? " " + attrs.join(" ") : "";
968
+ }
845
969
  function buildXml(state) {
846
970
  const lines = [];
847
971
  lines.push('<?xml version="1.0" encoding="UTF-8"?>');
848
972
  const sourceAttrs = buildSourceAttributes(state);
973
+ const remoteAttrs = buildRemoteAttributes(state);
849
974
  lines.push(
850
- `<review xmlns="urn:self-review:v3" timestamp="${escapeXml(state.timestamp)}"${sourceAttrs}>`
975
+ `<review xmlns="urn:self-review:v3" timestamp="${escapeXml(state.timestamp)}"${sourceAttrs}${remoteAttrs}>`
851
976
  );
852
977
  for (const file of state.files) {
853
978
  lines.push(...buildFileXml(file));
@@ -893,6 +1018,9 @@ function buildCommentXml(comment) {
893
1018
  if (comment.confidence) {
894
1019
  attrs.push(`confidence="${comment.confidence}"`);
895
1020
  }
1021
+ if (comment.remoteId) {
1022
+ attrs.push(`remote-id="${escapeXml(comment.remoteId)}"`);
1023
+ }
896
1024
  const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
897
1025
  lines.push(` <comment${attrStr}>`);
898
1026
  lines.push(` <body>${escapeXml(comment.body)}</body>`);
@@ -921,7 +1049,14 @@ function buildAttachmentXml(attachments, indent) {
921
1049
  );
922
1050
  }
923
1051
  function buildReplyXml(reply) {
924
- const attrStr = reply.author ? ` author="${escapeXml(reply.author)}"` : "";
1052
+ const attrs = [];
1053
+ if (reply.author) {
1054
+ attrs.push(`author="${escapeXml(reply.author)}"`);
1055
+ }
1056
+ if (reply.remoteId) {
1057
+ attrs.push(`remote-id="${escapeXml(reply.remoteId)}"`);
1058
+ }
1059
+ const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
925
1060
  return [
926
1061
  ` <reply${attrStr}>`,
927
1062
  ` <body>${escapeXml(reply.body)}</body>`,
@@ -938,6 +1073,7 @@ var import_fs = require("fs");
938
1073
  var import_fast_xml_parser = require("fast-xml-parser");
939
1074
  var SEVERITY_VALUES = ["critical", "major", "minor", "info"];
940
1075
  var CONFIDENCE_VALUES = ["high", "medium", "low"];
1076
+ var REMOTE_FORGE_VALUES = ["github", "gitlab"];
941
1077
  function parseReviewXml(xmlPath) {
942
1078
  try {
943
1079
  const xmlContent = (0, import_fs.readFileSync)(xmlPath, "utf-8");
@@ -971,7 +1107,7 @@ function parseReviewXmlString(xmlContent) {
971
1107
  const files = toChildArray(review.file);
972
1108
  for (const file of files) {
973
1109
  const rawPath = file["@_path"];
974
- if (!rawPath) continue;
1110
+ if (rawPath === void 0 || rawPath === null) continue;
975
1111
  const filePath = String(rawPath);
976
1112
  if (parseViewed(file["@_viewed"])) {
977
1113
  viewedFiles.push(filePath);
@@ -987,7 +1123,8 @@ function parseReviewXmlString(xmlContent) {
987
1123
  suggestion: parseSuggestion(comment),
988
1124
  author: comment["@_author"] ? String(comment["@_author"]) : void 0,
989
1125
  severity: parseEnumAttribute(comment["@_severity"], SEVERITY_VALUES),
990
- confidence: parseEnumAttribute(comment["@_confidence"], CONFIDENCE_VALUES)
1126
+ confidence: parseEnumAttribute(comment["@_confidence"], CONFIDENCE_VALUES),
1127
+ remoteId: parseStringAttribute(comment["@_remote-id"])
991
1128
  };
992
1129
  const attachments = parseAttachments(comment, reviewComment.id);
993
1130
  if (attachments) reviewComment.attachments = attachments;
@@ -996,7 +1133,16 @@ function parseReviewXmlString(xmlContent) {
996
1133
  comments.push(reviewComment);
997
1134
  }
998
1135
  }
999
- return { comments, viewedFiles, gitDiffArgs, source };
1136
+ return {
1137
+ comments,
1138
+ viewedFiles,
1139
+ gitDiffArgs,
1140
+ source,
1141
+ remoteUrl: parseStringAttribute(review["@_remote-url"]),
1142
+ remoteBaseSha: parseStringAttribute(review["@_remote-base-sha"]),
1143
+ remoteHeadSha: parseStringAttribute(review["@_remote-head-sha"]),
1144
+ remoteForge: parseEnumAttribute(review["@_remote-forge"], REMOTE_FORGE_VALUES)
1145
+ };
1000
1146
  } catch (error) {
1001
1147
  if (error instanceof Error) {
1002
1148
  console.error(`Error parsing XML: ${error.message}`);
@@ -1011,6 +1157,9 @@ function parseEnumAttribute(raw, allowed) {
1011
1157
  const value = String(raw);
1012
1158
  return allowed.includes(value) ? value : void 0;
1013
1159
  }
1160
+ function parseStringAttribute(raw) {
1161
+ return raw === void 0 || raw === null ? void 0 : String(raw);
1162
+ }
1014
1163
  function parseViewed(raw) {
1015
1164
  return raw === true || String(raw) === "true";
1016
1165
  }
@@ -1081,7 +1230,8 @@ function parseReplies(comment) {
1081
1230
  const reply = {
1082
1231
  id,
1083
1232
  body: node.body !== void 0 ? String(node.body) : "",
1084
- author: node["@_author"] ? String(node["@_author"]) : void 0
1233
+ author: node["@_author"] ? String(node["@_author"]) : void 0,
1234
+ remoteId: parseStringAttribute(node["@_remote-id"])
1085
1235
  };
1086
1236
  const attachments = parseAttachments(node, id);
1087
1237
  if (attachments) reply.attachments = attachments;
@@ -1375,12 +1525,12 @@ function reconcileGuide(guide, diffFilePaths) {
1375
1525
  });
1376
1526
  }
1377
1527
  }
1378
- const leftover = diffFilePaths.filter((path2) => !claimed.has(path2));
1528
+ const leftover = diffFilePaths.filter((path3) => !claimed.has(path3));
1379
1529
  if (leftover.length > 0) {
1380
1530
  resolved.push({
1381
1531
  name: IMPLICIT_GUIDE_GROUP_NAME,
1382
1532
  implicit: true,
1383
- files: leftover.map((path2) => ({ path: path2 }))
1533
+ files: leftover.map((path3) => ({ path: path3 }))
1384
1534
  });
1385
1535
  }
1386
1536
  return resolved;
@@ -1559,6 +1709,50 @@ function generateUntrackedDiffs(paths, repoRoot) {
1559
1709
  return generateSyntheticDiffs(paths, repoRoot);
1560
1710
  }
1561
1711
 
1712
+ // src/forge-provider.ts
1713
+ var ForgeCliUnavailableError = class extends Error {
1714
+ constructor(forge, cli, message) {
1715
+ super(message);
1716
+ this.name = "ForgeCliUnavailableError";
1717
+ this.forge = forge;
1718
+ this.cli = cli;
1719
+ }
1720
+ };
1721
+ var GITHUB_PR_PATH = /^\/([^/]+)\/([^/]+)\/pull\/(\d+)(?=\/|$)/;
1722
+ var GITLAB_MR_PATH = /^\/(.+)\/([^/]+)\/-\/merge_requests\/(\d+)(?=\/|$)/;
1723
+ function parseForgeUrl(url) {
1724
+ let parsed;
1725
+ try {
1726
+ parsed = new URL(url);
1727
+ } catch {
1728
+ return null;
1729
+ }
1730
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1731
+ return null;
1732
+ }
1733
+ const gitlab = GITLAB_MR_PATH.exec(parsed.pathname);
1734
+ if (gitlab) {
1735
+ return {
1736
+ forge: "gitlab",
1737
+ host: parsed.host,
1738
+ owner: gitlab[1],
1739
+ repo: gitlab[2],
1740
+ number: Number.parseInt(gitlab[3], 10)
1741
+ };
1742
+ }
1743
+ const github = GITHUB_PR_PATH.exec(parsed.pathname);
1744
+ if (github) {
1745
+ return {
1746
+ forge: "github",
1747
+ host: parsed.host,
1748
+ owner: github[1],
1749
+ repo: github[2],
1750
+ number: Number.parseInt(github[3], 10)
1751
+ };
1752
+ }
1753
+ return null;
1754
+ }
1755
+
1562
1756
  // src/directory-scanner.ts
1563
1757
  var import_promises = require("fs/promises");
1564
1758
  var import_path = require("path");
@@ -1757,8 +1951,8 @@ function loadConfig() {
1757
1951
  }
1758
1952
  return config;
1759
1953
  }
1760
- function loadYamlConfig(path2) {
1761
- const content = (0, import_fs3.readFileSync)(path2, "utf-8");
1954
+ function loadYamlConfig(path3) {
1955
+ const content = (0, import_fs3.readFileSync)(path3, "utf-8");
1762
1956
  const raw = (0, import_yaml.parse)(content);
1763
1957
  if (raw === null || raw === void 0) {
1764
1958
  return {};
@@ -1998,14 +2192,533 @@ function getLanguageFromPath(filePath) {
1998
2192
  }
1999
2193
  return langMap[ext] || "plaintext";
2000
2194
  }
2195
+
2196
+ // src/github-provider.ts
2197
+ var GH_CLI = "gh";
2198
+ async function runGh(runCommand, args) {
2199
+ let result;
2200
+ try {
2201
+ result = await runCommand(GH_CLI, args);
2202
+ } catch (error) {
2203
+ const detail = error instanceof Error ? error.message : String(error);
2204
+ throw new ForgeCliUnavailableError(
2205
+ "github",
2206
+ GH_CLI,
2207
+ `Failed to run the gh CLI: ${detail}`
2208
+ );
2209
+ }
2210
+ if (result.exitCode !== 0) {
2211
+ const detail = result.stderr.trim() || `exit code ${result.exitCode}`;
2212
+ throw new ForgeCliUnavailableError(
2213
+ "github",
2214
+ GH_CLI,
2215
+ `gh exited with code ${result.exitCode}: ${detail}`
2216
+ );
2217
+ }
2218
+ return result.stdout;
2219
+ }
2220
+ function parseGhJson(stdout, context) {
2221
+ try {
2222
+ return JSON.parse(stdout);
2223
+ } catch {
2224
+ throw new ForgeCliUnavailableError(
2225
+ "github",
2226
+ GH_CLI,
2227
+ `gh returned unparseable JSON for ${context}`
2228
+ );
2229
+ }
2230
+ }
2231
+ function toAnchor(comment) {
2232
+ const outdated = comment.line === null || comment.line === void 0;
2233
+ const endLine = outdated ? comment.original_line ?? null : comment.line;
2234
+ const startLine = outdated ? comment.original_start_line ?? comment.original_line ?? null : comment.start_line ?? comment.line;
2235
+ const hasLines = startLine !== null && endLine !== null;
2236
+ return {
2237
+ filePath: comment.path,
2238
+ // Side is meaningless without usable lines; the contract says 'new'.
2239
+ side: hasLines && comment.side === "LEFT" ? "old" : "new",
2240
+ startLine: hasLines ? startLine : null,
2241
+ endLine: hasLines ? endLine : null,
2242
+ outdated
2243
+ };
2244
+ }
2245
+ function toTurn(comment) {
2246
+ return {
2247
+ remoteId: String(comment.id),
2248
+ author: comment.user?.login ?? "ghost",
2249
+ body: comment.body
2250
+ };
2251
+ }
2252
+ function groupIntoThreads(comments) {
2253
+ const threads = [];
2254
+ const threadByCommentId = /* @__PURE__ */ new Map();
2255
+ for (const comment of comments) {
2256
+ const parentThread = comment.in_reply_to_id === null || comment.in_reply_to_id === void 0 ? void 0 : threadByCommentId.get(comment.in_reply_to_id);
2257
+ if (parentThread) {
2258
+ parentThread.replies.push(toTurn(comment));
2259
+ threadByCommentId.set(comment.id, parentThread);
2260
+ } else {
2261
+ const thread = {
2262
+ root: toTurn(comment),
2263
+ replies: [],
2264
+ anchor: toAnchor(comment)
2265
+ };
2266
+ threads.push(thread);
2267
+ threadByCommentId.set(comment.id, thread);
2268
+ }
2269
+ }
2270
+ return threads;
2271
+ }
2272
+ function createGitHubProvider(runCommand) {
2273
+ return {
2274
+ forge: "github",
2275
+ async fetchBaseBranch(url) {
2276
+ const stdout = await runGh(runCommand, [
2277
+ "pr",
2278
+ "view",
2279
+ String(url.number),
2280
+ "--repo",
2281
+ `${url.host}/${url.owner}/${url.repo}`,
2282
+ "--json",
2283
+ "baseRefName"
2284
+ ]);
2285
+ const parsed = parseGhJson(stdout, "pr view");
2286
+ if (typeof parsed?.baseRefName !== "string" || parsed.baseRefName === "") {
2287
+ throw new ForgeCliUnavailableError(
2288
+ "github",
2289
+ GH_CLI,
2290
+ "gh pr view returned no baseRefName"
2291
+ );
2292
+ }
2293
+ return parsed.baseRefName;
2294
+ },
2295
+ // The REST review-comment list carries no resolution state, so
2296
+ // `options.includeResolved` is deliberately ignored: GitHub fetch
2297
+ // returns all review threads (resolved-state filtering is a GitLab
2298
+ // concern).
2299
+ async fetchThreads(url, _options) {
2300
+ const stdout = await runGh(runCommand, [
2301
+ "api",
2302
+ `repos/${url.owner}/${url.repo}/pulls/${url.number}/comments`,
2303
+ "--hostname",
2304
+ url.host,
2305
+ "--paginate",
2306
+ "--slurp"
2307
+ ]);
2308
+ const pages = parseGhJson(stdout, "pull request comments");
2309
+ if (!Array.isArray(pages)) {
2310
+ throw new ForgeCliUnavailableError(
2311
+ "github",
2312
+ GH_CLI,
2313
+ "gh api returned an unexpected payload shape for pull request comments"
2314
+ );
2315
+ }
2316
+ const comments = pages.flat(1);
2317
+ return groupIntoThreads(comments);
2318
+ }
2319
+ };
2320
+ }
2321
+
2322
+ // src/thread-mapper.ts
2323
+ var REVIEW_LEVEL_FILE_PATH = "";
2324
+ function mapAnchorToLineRange(anchor) {
2325
+ if (anchor.outdated) {
2326
+ return null;
2327
+ }
2328
+ const { startLine, endLine } = anchor;
2329
+ if (startLine === null || endLine === null) {
2330
+ return null;
2331
+ }
2332
+ if (startLine < 1 || endLine < 1) {
2333
+ return null;
2334
+ }
2335
+ return {
2336
+ side: anchor.side,
2337
+ start: Math.min(startLine, endLine),
2338
+ end: Math.max(startLine, endLine)
2339
+ };
2340
+ }
2341
+ function internalId(turn) {
2342
+ return `remote-${turn.remoteId}`;
2343
+ }
2344
+ function mapReply(turn) {
2345
+ return {
2346
+ id: internalId(turn),
2347
+ body: turn.body,
2348
+ author: turn.author,
2349
+ remoteId: turn.remoteId
2350
+ };
2351
+ }
2352
+ function mapThreadsToReviewComments(threads) {
2353
+ return threads.map((thread) => {
2354
+ const comment = {
2355
+ id: internalId(thread.root),
2356
+ filePath: thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH,
2357
+ lineRange: thread.anchor ? mapAnchorToLineRange(thread.anchor) : null,
2358
+ body: thread.root.body,
2359
+ category: "",
2360
+ suggestion: null,
2361
+ author: thread.root.author,
2362
+ remoteId: thread.root.remoteId
2363
+ };
2364
+ if (thread.replies.length > 0) {
2365
+ comment.replies = thread.replies.map(mapReply);
2366
+ }
2367
+ return comment;
2368
+ });
2369
+ }
2370
+
2371
+ // src/gitlab-provider.ts
2372
+ var GLAB_CLI = "glab";
2373
+ function encodeProjectPath(url) {
2374
+ return encodeURIComponent(`${url.owner}/${url.repo}`);
2375
+ }
2376
+ function unavailable(message) {
2377
+ return new ForgeCliUnavailableError("gitlab", GLAB_CLI, message);
2378
+ }
2379
+ async function runGlabApi(runCommand, url, endpoint, extraArgs = []) {
2380
+ const args = ["api", endpoint, "--hostname", url.host, ...extraArgs];
2381
+ let result;
2382
+ try {
2383
+ result = await runCommand(GLAB_CLI, args);
2384
+ } catch (error) {
2385
+ const detail = error instanceof Error ? error.message : String(error);
2386
+ throw unavailable(`glab CLI could not be spawned: ${detail}`);
2387
+ }
2388
+ if (result.exitCode !== 0) {
2389
+ const detail = result.stderr.trim() || `exit code ${result.exitCode}`;
2390
+ throw unavailable(`glab api ${endpoint} failed: ${detail}`);
2391
+ }
2392
+ return result.stdout;
2393
+ }
2394
+ function parseJsonDocuments(text) {
2395
+ const documents = [];
2396
+ let depth = 0;
2397
+ let inString = false;
2398
+ let escaped = false;
2399
+ let start = -1;
2400
+ for (let i = 0; i < text.length; i++) {
2401
+ const ch = text[i];
2402
+ if (inString) {
2403
+ if (escaped) {
2404
+ escaped = false;
2405
+ } else if (ch === "\\") {
2406
+ escaped = true;
2407
+ } else if (ch === '"') {
2408
+ inString = false;
2409
+ }
2410
+ continue;
2411
+ }
2412
+ if (ch === '"') {
2413
+ inString = true;
2414
+ } else if (ch === "[" || ch === "{") {
2415
+ if (depth === 0) start = i;
2416
+ depth += 1;
2417
+ } else if (ch === "]" || ch === "}") {
2418
+ depth -= 1;
2419
+ if (depth === 0 && start >= 0) {
2420
+ documents.push(JSON.parse(text.slice(start, i + 1)));
2421
+ start = -1;
2422
+ }
2423
+ }
2424
+ }
2425
+ if (depth !== 0 || inString) {
2426
+ throw new Error("truncated JSON document");
2427
+ }
2428
+ return documents;
2429
+ }
2430
+ function toTurn2(note) {
2431
+ return {
2432
+ remoteId: String(note.id),
2433
+ author: note.author?.username ?? "unknown",
2434
+ body: note.body ?? ""
2435
+ };
2436
+ }
2437
+ function isDiscussionResolved(notes) {
2438
+ const resolvable = notes.filter((note) => note.resolvable === true);
2439
+ return resolvable.length > 0 && resolvable.every((note) => note.resolved === true);
2440
+ }
2441
+ function toAnchor2(position) {
2442
+ if (!position) return null;
2443
+ const side = typeof position.old_line === "number" && typeof position.new_line !== "number" ? "old" : "new";
2444
+ const pathForSide = side === "old" ? position.old_path : position.new_path;
2445
+ const filePath = pathForSide ?? position.new_path ?? position.old_path;
2446
+ if (!filePath) return null;
2447
+ const lineOf = (edge) => {
2448
+ const value = side === "old" ? edge?.old_line : edge?.new_line;
2449
+ return typeof value === "number" ? value : null;
2450
+ };
2451
+ const positionLine = lineOf(position);
2452
+ const startLine = lineOf(position.line_range?.start) ?? positionLine;
2453
+ const endLine = lineOf(position.line_range?.end) ?? positionLine;
2454
+ return { filePath, side, startLine, endLine, outdated: false };
2455
+ }
2456
+ function toThread(discussion) {
2457
+ const notes = (discussion.notes ?? []).filter((note) => note.system !== true);
2458
+ if (notes.length === 0) return null;
2459
+ const [rootNote, ...replyNotes] = notes;
2460
+ return {
2461
+ root: toTurn2(rootNote),
2462
+ replies: replyNotes.map(toTurn2),
2463
+ anchor: toAnchor2(rootNote.position)
2464
+ };
2465
+ }
2466
+ function createGitLabProvider(runCommand) {
2467
+ return {
2468
+ forge: "gitlab",
2469
+ async fetchBaseBranch(url) {
2470
+ const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}`;
2471
+ const stdout = await runGlabApi(runCommand, url, endpoint);
2472
+ let mr;
2473
+ try {
2474
+ mr = JSON.parse(stdout);
2475
+ } catch {
2476
+ throw unavailable(`glab api ${endpoint} returned unparseable JSON`);
2477
+ }
2478
+ const targetBranch = mr?.target_branch;
2479
+ if (typeof targetBranch !== "string" || targetBranch.length === 0) {
2480
+ throw unavailable(`glab api ${endpoint} returned no target_branch`);
2481
+ }
2482
+ return targetBranch;
2483
+ },
2484
+ async fetchThreads(url, options) {
2485
+ const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}/discussions`;
2486
+ const stdout = await runGlabApi(runCommand, url, endpoint, ["--paginate"]);
2487
+ let discussions;
2488
+ try {
2489
+ const pages = parseJsonDocuments(stdout);
2490
+ if (pages.length === 0 && stdout.trim() !== "") {
2491
+ throw new Error("no JSON documents in output");
2492
+ }
2493
+ discussions = pages.flatMap(
2494
+ (page) => Array.isArray(page) ? page : []
2495
+ );
2496
+ } catch {
2497
+ throw unavailable(`glab api ${endpoint} returned unparseable JSON`);
2498
+ }
2499
+ const includeResolved = options?.includeResolved === true;
2500
+ const threads = [];
2501
+ for (const discussion of discussions) {
2502
+ const notes = discussion.notes ?? [];
2503
+ if (!includeResolved && isDiscussionResolved(notes)) continue;
2504
+ const thread = toThread(discussion);
2505
+ if (thread) threads.push(thread);
2506
+ }
2507
+ return threads;
2508
+ }
2509
+ };
2510
+ }
2511
+
2512
+ // src/materializer.ts
2513
+ var import_child_process3 = require("child_process");
2514
+ var fs2 = __toESM(require("fs"), 1);
2515
+ var os = __toESM(require("os"), 1);
2516
+ var path2 = __toESM(require("path"), 1);
2517
+ var LOCAL_BASE_REF = "refs/self-review/base";
2518
+ var LOCAL_HEAD_REF = "refs/self-review/head";
2519
+ var AUTH_HINT = "Hint: if this repository is private or requires authentication, run `gh auth setup-git` (GitHub) or `glab auth git-credential` (GitLab) to wire your CLI credentials into git.";
2520
+ var defaultGitRunner = (command, args) => new Promise((resolve, reject) => {
2521
+ (0, import_child_process3.execFile)(
2522
+ command,
2523
+ args,
2524
+ { maxBuffer: 50 * 1024 * 1024 },
2525
+ (error, stdout, stderr) => {
2526
+ const spawnCode = error?.code;
2527
+ if (error && typeof spawnCode === "string") {
2528
+ reject(error);
2529
+ return;
2530
+ }
2531
+ resolve({
2532
+ stdout: stdout ?? "",
2533
+ stderr: stderr ?? "",
2534
+ exitCode: error ? typeof spawnCode === "number" ? spawnCode : 1 : 0
2535
+ });
2536
+ }
2537
+ );
2538
+ });
2539
+ function headRefFor(url) {
2540
+ return url.forge === "github" ? `refs/pull/${url.number}/head` : `refs/merge-requests/${url.number}/head`;
2541
+ }
2542
+ function cloneUrlFor(url) {
2543
+ return `https://${url.host}/${url.owner}/${url.repo}.git`;
2544
+ }
2545
+ function gitFailure(what, result, withAuthHint) {
2546
+ const stderr = result.stderr.trim();
2547
+ const lines = [
2548
+ `git ${what} failed (exit code ${result.exitCode})${stderr ? `:
2549
+ ${stderr}` : ""}`
2550
+ ];
2551
+ if (withAuthHint) {
2552
+ lines.push("", AUTH_HINT);
2553
+ }
2554
+ return new Error(lines.join("\n"));
2555
+ }
2556
+ function stripRepoPath(repoPath) {
2557
+ return repoPath.replace(/\/+$/, "").replace(/\.git$/i, "");
2558
+ }
2559
+ function normalizeRemoteUrl(raw) {
2560
+ const trimmed = raw.trim();
2561
+ if (trimmed.includes("://")) {
2562
+ try {
2563
+ const parsed = new URL(trimmed);
2564
+ return {
2565
+ host: parsed.host.toLowerCase(),
2566
+ path: stripRepoPath(parsed.pathname.replace(/^\/+/, "")).toLowerCase()
2567
+ };
2568
+ } catch {
2569
+ return null;
2570
+ }
2571
+ }
2572
+ const scp = /^(?:[^@\s]+@)?([^:/\s]+):(.+)$/.exec(trimmed);
2573
+ if (scp) {
2574
+ return {
2575
+ host: scp[1].toLowerCase(),
2576
+ path: stripRepoPath(scp[2].replace(/^\/+/, "")).toLowerCase()
2577
+ };
2578
+ }
2579
+ return null;
2580
+ }
2581
+ function findMatchingRemote(remoteVOutput, url) {
2582
+ const wantedHost = url.host.toLowerCase();
2583
+ const wantedPath = `${url.owner}/${url.repo}`.toLowerCase();
2584
+ for (const line of remoteVOutput.split("\n")) {
2585
+ const match = /^(\S+)\t(.+?)\s+\(fetch\)$/.exec(line.trim());
2586
+ if (!match) continue;
2587
+ const normalized = normalizeRemoteUrl(match[2]);
2588
+ if (normalized && normalized.host === wantedHost && normalized.path === wantedPath) {
2589
+ return match[1];
2590
+ }
2591
+ }
2592
+ return null;
2593
+ }
2594
+ async function revParse(runner, repoPath, ref) {
2595
+ const result = await runner("git", ["-C", repoPath, "rev-parse", ref]);
2596
+ if (result.exitCode !== 0) {
2597
+ throw gitFailure(`rev-parse ${ref}`, result, false);
2598
+ }
2599
+ return result.stdout.trim();
2600
+ }
2601
+ async function detectExistingClone(runner, cwd, url) {
2602
+ const toplevel = await runner("git", ["-C", cwd, "rev-parse", "--show-toplevel"]);
2603
+ if (toplevel.exitCode !== 0) {
2604
+ return null;
2605
+ }
2606
+ const repoPath = toplevel.stdout.trim();
2607
+ const remotes = await runner("git", ["-C", repoPath, "remote", "-v"]);
2608
+ if (remotes.exitCode !== 0) {
2609
+ return null;
2610
+ }
2611
+ const remoteName = findMatchingRemote(remotes.stdout, url);
2612
+ return remoteName === null ? null : { repoPath, remoteName };
2613
+ }
2614
+ async function materializeIntoExistingClone(runner, url, baseBranch, repoPath, remoteName) {
2615
+ console.error(
2616
+ `self-review: reusing existing clone at ${repoPath} (remote "${remoteName}")`
2617
+ );
2618
+ const fetch = await runner("git", [
2619
+ "-C",
2620
+ repoPath,
2621
+ "fetch",
2622
+ remoteName,
2623
+ `+refs/heads/${baseBranch}:${LOCAL_BASE_REF}`,
2624
+ `+${headRefFor(url)}:${LOCAL_HEAD_REF}`
2625
+ ]);
2626
+ if (fetch.exitCode !== 0) {
2627
+ throw gitFailure(`fetch from remote "${remoteName}"`, fetch, true);
2628
+ }
2629
+ return {
2630
+ repoPath,
2631
+ baseSha: await revParse(runner, repoPath, LOCAL_BASE_REF),
2632
+ headSha: await revParse(runner, repoPath, LOCAL_HEAD_REF),
2633
+ mode: "existing-clone",
2634
+ cleanup: () => {
2635
+ }
2636
+ };
2637
+ }
2638
+ async function materializeIntoTempClone(runner, url, baseBranch) {
2639
+ const tempDir = fs2.mkdtempSync(path2.join(os.tmpdir(), "self-review-"));
2640
+ let removed = false;
2641
+ const cleanup = () => {
2642
+ if (removed) return;
2643
+ removed = true;
2644
+ fs2.rmSync(tempDir, { recursive: true, force: true });
2645
+ };
2646
+ try {
2647
+ console.error(
2648
+ `self-review: created temporary blobless clone at ${tempDir}`
2649
+ );
2650
+ const cloneUrl = cloneUrlFor(url);
2651
+ const clone = await runner("git", [
2652
+ "clone",
2653
+ "--filter=blob:none",
2654
+ cloneUrl,
2655
+ tempDir
2656
+ ]);
2657
+ if (clone.exitCode !== 0) {
2658
+ throw gitFailure(`clone of ${cloneUrl}`, clone, true);
2659
+ }
2660
+ const fetch = await runner("git", [
2661
+ "-C",
2662
+ tempDir,
2663
+ "fetch",
2664
+ "origin",
2665
+ `+${headRefFor(url)}:${LOCAL_HEAD_REF}`
2666
+ ]);
2667
+ if (fetch.exitCode !== 0) {
2668
+ throw gitFailure(`fetch of ${headRefFor(url)}`, fetch, true);
2669
+ }
2670
+ return {
2671
+ repoPath: tempDir,
2672
+ baseSha: await revParse(runner, tempDir, `origin/${baseBranch}`),
2673
+ headSha: await revParse(runner, tempDir, LOCAL_HEAD_REF),
2674
+ mode: "temp-clone",
2675
+ cleanup
2676
+ };
2677
+ } catch (error) {
2678
+ cleanup();
2679
+ throw error;
2680
+ }
2681
+ }
2682
+ async function materialize(url, baseBranch, cwd, runner = defaultGitRunner) {
2683
+ const existing = await detectExistingClone(runner, cwd, url);
2684
+ if (existing) {
2685
+ return materializeIntoExistingClone(
2686
+ runner,
2687
+ url,
2688
+ baseBranch,
2689
+ existing.repoPath,
2690
+ existing.remoteName
2691
+ );
2692
+ }
2693
+ return materializeIntoTempClone(runner, url, baseBranch);
2694
+ }
2695
+ async function resolveRemoteDefaultBranch(url, runner = defaultGitRunner) {
2696
+ const cloneUrl = cloneUrlFor(url);
2697
+ const result = await runner("git", ["ls-remote", "--symref", cloneUrl, "HEAD"]);
2698
+ if (result.exitCode !== 0) {
2699
+ throw gitFailure(`ls-remote of ${cloneUrl}`, result, true);
2700
+ }
2701
+ const match = /^ref:\s+refs\/heads\/(\S+)\s+HEAD$/m.exec(result.stdout);
2702
+ if (!match) {
2703
+ throw new Error(
2704
+ `Failed to resolve the default branch of ${cloneUrl}: git ls-remote returned no HEAD symref.`
2705
+ );
2706
+ }
2707
+ return match[1];
2708
+ }
2001
2709
  // Annotate the CommonJS export names for ESM import in node:
2002
2710
  0 && (module.exports = {
2711
+ ForgeCliUnavailableError,
2003
2712
  GUIDE_XSD_SCHEMA,
2004
2713
  IMPLICIT_GUIDE_GROUP_NAME,
2714
+ REVIEW_LEVEL_FILE_PATH,
2005
2715
  checkWritability,
2006
2716
  computePayloadStats,
2007
2717
  countTotalLines,
2718
+ createGitHubProvider,
2719
+ createGitLabProvider,
2008
2720
  createIgnoreFilter,
2721
+ defaultGitRunner,
2009
2722
  generateSyntheticDiffs,
2010
2723
  generateUntrackedDiffs,
2011
2724
  getGitDiffStats,
@@ -2020,11 +2733,15 @@ function getLanguageFromPath(filePath) {
2020
2733
  isPreviewableRenderedText,
2021
2734
  isPreviewableSvg,
2022
2735
  loadConfig,
2736
+ mapThreadsToReviewComments,
2737
+ materialize,
2023
2738
  parseDiff,
2739
+ parseForgeUrl,
2024
2740
  parseGuideXml,
2025
2741
  parseReviewXml,
2026
2742
  parseReviewXmlString,
2027
2743
  reconcileGuide,
2744
+ resolveRemoteDefaultBranch,
2028
2745
  runGitDiff,
2029
2746
  runGitDiffAsync,
2030
2747
  scanDirectory,