@self-review/core 1.42.0 → 1.43.1

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