@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.js CHANGED
@@ -46,13 +46,13 @@ function parseDiff(rawDiff) {
46
46
  continue;
47
47
  }
48
48
  if (line.startsWith("--- ")) {
49
- const path2 = line.substring(4);
50
- currentFile.oldPath = path2 === "/dev/null" ? "" : stripPrefix(path2);
49
+ const path3 = line.substring(4);
50
+ currentFile.oldPath = path3 === "/dev/null" ? "" : stripPrefix(path3);
51
51
  continue;
52
52
  }
53
53
  if (line.startsWith("+++ ")) {
54
- const path2 = line.substring(4);
55
- currentFile.newPath = path2 === "/dev/null" ? "" : stripPrefix(path2);
54
+ const path3 = line.substring(4);
55
+ currentFile.newPath = path3 === "/dev/null" ? "" : stripPrefix(path3);
56
56
  continue;
57
57
  }
58
58
  if (line.startsWith("Binary files ")) {
@@ -137,11 +137,11 @@ function parseDiff(rawDiff) {
137
137
  }
138
138
  return files;
139
139
  }
140
- function stripPrefix(path2) {
141
- if (path2.length > 2 && path2[1] === "/") {
142
- return path2.substring(2);
140
+ function stripPrefix(path3) {
141
+ if (path3.length > 2 && path3[1] === "/") {
142
+ return path3.substring(2);
143
143
  }
144
- return path2;
144
+ return path3;
145
145
  }
146
146
  function parseGitDiffHeader(line) {
147
147
  const withoutPrefix = line.substring("diff --git ".length);
@@ -200,6 +200,14 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
200
200
  - <comment> gained an optional, unbounded <reply> child, so a finding
201
201
  and the responses to it form a single legible thread instead of a
202
202
  set of disconnected assertions. See ReplyType.
203
+
204
+ Amended in place (still v3):
205
+ - The review root gained optional remote-url, remote-base-sha,
206
+ remote-head-sha and remote-forge attributes, and <comment> and
207
+ <reply> gained an optional remote-id attribute, so a review taken
208
+ against a remote pull/merge request records its provenance. Purely
209
+ additive: a document carrying none of them is unchanged. See
210
+ ReviewType.
203
211
  -->
204
212
 
205
213
  <!-- ===== Root element ===== -->
@@ -251,6 +259,51 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
251
259
  </xs:documentation>
252
260
  </xs:annotation>
253
261
  </xs:attribute>
262
+ <xs:attribute name="remote-url" type="xs:string" use="optional">
263
+ <xs:annotation>
264
+ <xs:documentation>
265
+ URL of the remote pull/merge request this review was taken
266
+ against. Example: "https://github.com/owner/repo/pull/42".
267
+ Present only when reviewing a remote PR/MR.
268
+
269
+ The remote-* attributes form a third source shape alongside
270
+ git-diff-args/repository (local git diff) and source-path
271
+ (directory review). The three shapes are mutually exclusive;
272
+ XSD 1.0 cannot express that constraint, so it is enforced by
273
+ the application.
274
+ </xs:documentation>
275
+ </xs:annotation>
276
+ </xs:attribute>
277
+ <xs:attribute name="remote-base-sha" type="xs:string" use="optional">
278
+ <xs:annotation>
279
+ <xs:documentation>
280
+ Commit SHA the remote diff was computed from (the base of the
281
+ PR/MR at fetch time). Together with remote-head-sha it pins the
282
+ review to the exact diff it was written against, so a consumer
283
+ can detect drift when the remote branch moves.
284
+ Present only when reviewing a remote PR/MR.
285
+ </xs:documentation>
286
+ </xs:annotation>
287
+ </xs:attribute>
288
+ <xs:attribute name="remote-head-sha" type="xs:string" use="optional">
289
+ <xs:annotation>
290
+ <xs:documentation>
291
+ Commit SHA of the head of the remote PR/MR branch at fetch time.
292
+ See remote-base-sha for how the pair supports drift detection.
293
+ Present only when reviewing a remote PR/MR.
294
+ </xs:documentation>
295
+ </xs:annotation>
296
+ </xs:attribute>
297
+ <xs:attribute name="remote-forge" type="sr:RemoteForgeEnum" use="optional">
298
+ <xs:annotation>
299
+ <xs:documentation>
300
+ Which forge hosts the remote PR/MR. Names the id space of the
301
+ remote-id attributes on comments and replies, and selects the
302
+ API machinery a future posting feature would use.
303
+ Present only when reviewing a remote PR/MR.
304
+ </xs:documentation>
305
+ </xs:annotation>
306
+ </xs:attribute>
254
307
  </xs:complexType>
255
308
 
256
309
  <xs:complexType name="FileType">
@@ -444,6 +497,19 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
444
497
  </xs:documentation>
445
498
  </xs:annotation>
446
499
  </xs:attribute>
500
+ <xs:attribute name="remote-id" type="xs:string" use="optional">
501
+ <xs:annotation>
502
+ <xs:documentation>
503
+ Identifier of the remote discussion thread or comment this
504
+ comment was fetched from, in the id space of the forge named by
505
+ remote-forge on the review root. Provenance and forward
506
+ machinery: it lets a consumer trace the finding back to its
507
+ origin, and a future posting feature reply to the existing
508
+ thread instead of opening a new one. Absent on comments
509
+ authored locally.
510
+ </xs:documentation>
511
+ </xs:annotation>
512
+ </xs:attribute>
447
513
  </xs:complexType>
448
514
 
449
515
  <xs:complexType name="ReplyType">
@@ -512,6 +578,19 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
512
578
  </xs:documentation>
513
579
  </xs:annotation>
514
580
  </xs:attribute>
581
+ <xs:attribute name="remote-id" type="xs:string" use="optional">
582
+ <xs:annotation>
583
+ <xs:documentation>
584
+ Identifier of the remote comment this reply was fetched from,
585
+ with the same semantics as CommentType/@remote-id: an id in the
586
+ forge's own id space, kept for provenance and for a future
587
+ posting feature. Absent on replies authored locally.
588
+
589
+ A remote-id is not an ordering signal. Document order remains
590
+ conversation order, exactly as rule 1 above states.
591
+ </xs:documentation>
592
+ </xs:annotation>
593
+ </xs:attribute>
515
594
  </xs:complexType>
516
595
 
517
596
  <xs:complexType name="SuggestionType">
@@ -682,6 +761,26 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
682
761
  </xs:restriction>
683
762
  </xs:simpleType>
684
763
 
764
+ <xs:simpleType name="RemoteForgeEnum">
765
+ <xs:annotation>
766
+ <xs:documentation>
767
+ The forge hosting a remote pull/merge request.
768
+ </xs:documentation>
769
+ </xs:annotation>
770
+ <xs:restriction base="xs:string">
771
+ <xs:enumeration value="github">
772
+ <xs:annotation>
773
+ <xs:documentation>A GitHub pull request.</xs:documentation>
774
+ </xs:annotation>
775
+ </xs:enumeration>
776
+ <xs:enumeration value="gitlab">
777
+ <xs:annotation>
778
+ <xs:documentation>A GitLab merge request.</xs:documentation>
779
+ </xs:annotation>
780
+ </xs:enumeration>
781
+ </xs:restriction>
782
+ </xs:simpleType>
783
+
685
784
  </xs:schema>`;
686
785
  function extFromMediaType(mediaType) {
687
786
  const map = {
@@ -776,12 +875,29 @@ function buildSourceAttributes(state) {
776
875
  }
777
876
  return "";
778
877
  }
878
+ function buildRemoteAttributes(state) {
879
+ const attrs = [];
880
+ if (state.remoteUrl) {
881
+ attrs.push(`remote-url="${escapeXml(state.remoteUrl)}"`);
882
+ }
883
+ if (state.remoteBaseSha) {
884
+ attrs.push(`remote-base-sha="${escapeXml(state.remoteBaseSha)}"`);
885
+ }
886
+ if (state.remoteHeadSha) {
887
+ attrs.push(`remote-head-sha="${escapeXml(state.remoteHeadSha)}"`);
888
+ }
889
+ if (state.remoteForge) {
890
+ attrs.push(`remote-forge="${state.remoteForge}"`);
891
+ }
892
+ return attrs.length > 0 ? " " + attrs.join(" ") : "";
893
+ }
779
894
  function buildXml(state) {
780
895
  const lines = [];
781
896
  lines.push('<?xml version="1.0" encoding="UTF-8"?>');
782
897
  const sourceAttrs = buildSourceAttributes(state);
898
+ const remoteAttrs = buildRemoteAttributes(state);
783
899
  lines.push(
784
- `<review xmlns="urn:self-review:v3" timestamp="${escapeXml(state.timestamp)}"${sourceAttrs}>`
900
+ `<review xmlns="urn:self-review:v3" timestamp="${escapeXml(state.timestamp)}"${sourceAttrs}${remoteAttrs}>`
785
901
  );
786
902
  for (const file of state.files) {
787
903
  lines.push(...buildFileXml(file));
@@ -827,6 +943,9 @@ function buildCommentXml(comment) {
827
943
  if (comment.confidence) {
828
944
  attrs.push(`confidence="${comment.confidence}"`);
829
945
  }
946
+ if (comment.remoteId) {
947
+ attrs.push(`remote-id="${escapeXml(comment.remoteId)}"`);
948
+ }
830
949
  const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
831
950
  lines.push(` <comment${attrStr}>`);
832
951
  lines.push(` <body>${escapeXml(comment.body)}</body>`);
@@ -855,7 +974,14 @@ function buildAttachmentXml(attachments, indent) {
855
974
  );
856
975
  }
857
976
  function buildReplyXml(reply) {
858
- const attrStr = reply.author ? ` author="${escapeXml(reply.author)}"` : "";
977
+ const attrs = [];
978
+ if (reply.author) {
979
+ attrs.push(`author="${escapeXml(reply.author)}"`);
980
+ }
981
+ if (reply.remoteId) {
982
+ attrs.push(`remote-id="${escapeXml(reply.remoteId)}"`);
983
+ }
984
+ const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
859
985
  return [
860
986
  ` <reply${attrStr}>`,
861
987
  ` <body>${escapeXml(reply.body)}</body>`,
@@ -872,6 +998,7 @@ import { readFileSync } from "fs";
872
998
  import { XMLParser } from "fast-xml-parser";
873
999
  var SEVERITY_VALUES = ["critical", "major", "minor", "info"];
874
1000
  var CONFIDENCE_VALUES = ["high", "medium", "low"];
1001
+ var REMOTE_FORGE_VALUES = ["github", "gitlab"];
875
1002
  function parseReviewXml(xmlPath) {
876
1003
  try {
877
1004
  const xmlContent = readFileSync(xmlPath, "utf-8");
@@ -905,7 +1032,7 @@ function parseReviewXmlString(xmlContent) {
905
1032
  const files = toChildArray(review.file);
906
1033
  for (const file of files) {
907
1034
  const rawPath = file["@_path"];
908
- if (!rawPath) continue;
1035
+ if (rawPath === void 0 || rawPath === null) continue;
909
1036
  const filePath = String(rawPath);
910
1037
  if (parseViewed(file["@_viewed"])) {
911
1038
  viewedFiles.push(filePath);
@@ -921,7 +1048,8 @@ function parseReviewXmlString(xmlContent) {
921
1048
  suggestion: parseSuggestion(comment),
922
1049
  author: comment["@_author"] ? String(comment["@_author"]) : void 0,
923
1050
  severity: parseEnumAttribute(comment["@_severity"], SEVERITY_VALUES),
924
- confidence: parseEnumAttribute(comment["@_confidence"], CONFIDENCE_VALUES)
1051
+ confidence: parseEnumAttribute(comment["@_confidence"], CONFIDENCE_VALUES),
1052
+ remoteId: parseStringAttribute(comment["@_remote-id"])
925
1053
  };
926
1054
  const attachments = parseAttachments(comment, reviewComment.id);
927
1055
  if (attachments) reviewComment.attachments = attachments;
@@ -930,7 +1058,16 @@ function parseReviewXmlString(xmlContent) {
930
1058
  comments.push(reviewComment);
931
1059
  }
932
1060
  }
933
- return { comments, viewedFiles, gitDiffArgs, source };
1061
+ return {
1062
+ comments,
1063
+ viewedFiles,
1064
+ gitDiffArgs,
1065
+ source,
1066
+ remoteUrl: parseStringAttribute(review["@_remote-url"]),
1067
+ remoteBaseSha: parseStringAttribute(review["@_remote-base-sha"]),
1068
+ remoteHeadSha: parseStringAttribute(review["@_remote-head-sha"]),
1069
+ remoteForge: parseEnumAttribute(review["@_remote-forge"], REMOTE_FORGE_VALUES)
1070
+ };
934
1071
  } catch (error) {
935
1072
  if (error instanceof Error) {
936
1073
  console.error(`Error parsing XML: ${error.message}`);
@@ -945,6 +1082,9 @@ function parseEnumAttribute(raw, allowed) {
945
1082
  const value = String(raw);
946
1083
  return allowed.includes(value) ? value : void 0;
947
1084
  }
1085
+ function parseStringAttribute(raw) {
1086
+ return raw === void 0 || raw === null ? void 0 : String(raw);
1087
+ }
948
1088
  function parseViewed(raw) {
949
1089
  return raw === true || String(raw) === "true";
950
1090
  }
@@ -1015,7 +1155,8 @@ function parseReplies(comment) {
1015
1155
  const reply = {
1016
1156
  id,
1017
1157
  body: node.body !== void 0 ? String(node.body) : "",
1018
- author: node["@_author"] ? String(node["@_author"]) : void 0
1158
+ author: node["@_author"] ? String(node["@_author"]) : void 0,
1159
+ remoteId: parseStringAttribute(node["@_remote-id"])
1019
1160
  };
1020
1161
  const attachments = parseAttachments(node, id);
1021
1162
  if (attachments) reply.attachments = attachments;
@@ -1309,19 +1450,19 @@ function reconcileGuide(guide, diffFilePaths) {
1309
1450
  });
1310
1451
  }
1311
1452
  }
1312
- const leftover = diffFilePaths.filter((path2) => !claimed.has(path2));
1453
+ const leftover = diffFilePaths.filter((path3) => !claimed.has(path3));
1313
1454
  if (leftover.length > 0) {
1314
1455
  resolved.push({
1315
1456
  name: IMPLICIT_GUIDE_GROUP_NAME,
1316
1457
  implicit: true,
1317
- files: leftover.map((path2) => ({ path: path2 }))
1458
+ files: leftover.map((path3) => ({ path: path3 }))
1318
1459
  });
1319
1460
  }
1320
1461
  return resolved;
1321
1462
  }
1322
1463
 
1323
1464
  // src/git.ts
1324
- import { execSync, exec } from "child_process";
1465
+ import { execSync, exec, execFile } from "child_process";
1325
1466
  import { promisify } from "util";
1326
1467
 
1327
1468
  // src/synthetic-diff.ts
@@ -1493,6 +1634,50 @@ function generateUntrackedDiffs(paths, repoRoot) {
1493
1634
  return generateSyntheticDiffs(paths, repoRoot);
1494
1635
  }
1495
1636
 
1637
+ // src/forge-provider.ts
1638
+ var ForgeCliUnavailableError = class extends Error {
1639
+ constructor(forge, cli, message) {
1640
+ super(message);
1641
+ this.name = "ForgeCliUnavailableError";
1642
+ this.forge = forge;
1643
+ this.cli = cli;
1644
+ }
1645
+ };
1646
+ var GITHUB_PR_PATH = /^\/([^/]+)\/([^/]+)\/pull\/(\d+)(?=\/|$)/;
1647
+ var GITLAB_MR_PATH = /^\/(.+)\/([^/]+)\/-\/merge_requests\/(\d+)(?=\/|$)/;
1648
+ function parseForgeUrl(url) {
1649
+ let parsed;
1650
+ try {
1651
+ parsed = new URL(url);
1652
+ } catch {
1653
+ return null;
1654
+ }
1655
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1656
+ return null;
1657
+ }
1658
+ const gitlab = GITLAB_MR_PATH.exec(parsed.pathname);
1659
+ if (gitlab) {
1660
+ return {
1661
+ forge: "gitlab",
1662
+ host: parsed.host,
1663
+ owner: gitlab[1],
1664
+ repo: gitlab[2],
1665
+ number: Number.parseInt(gitlab[3], 10)
1666
+ };
1667
+ }
1668
+ const github = GITHUB_PR_PATH.exec(parsed.pathname);
1669
+ if (github) {
1670
+ return {
1671
+ forge: "github",
1672
+ host: parsed.host,
1673
+ owner: github[1],
1674
+ repo: github[2],
1675
+ number: Number.parseInt(github[3], 10)
1676
+ };
1677
+ }
1678
+ return null;
1679
+ }
1680
+
1496
1681
  // src/directory-scanner.ts
1497
1682
  import { readdir, stat } from "fs/promises";
1498
1683
  import { join as join2, relative, basename, dirname as dirname2 } from "path";
@@ -1691,8 +1876,8 @@ function loadConfig() {
1691
1876
  }
1692
1877
  return config;
1693
1878
  }
1694
- function loadYamlConfig(path2) {
1695
- const content = readFileSync3(path2, "utf-8");
1879
+ function loadYamlConfig(path3) {
1880
+ const content = readFileSync3(path3, "utf-8");
1696
1881
  const raw = parseYaml(content);
1697
1882
  if (raw === null || raw === void 0) {
1698
1883
  return {};
@@ -1932,13 +2117,536 @@ function getLanguageFromPath(filePath) {
1932
2117
  }
1933
2118
  return langMap[ext] || "plaintext";
1934
2119
  }
2120
+
2121
+ // src/github-provider.ts
2122
+ var GH_CLI = "gh";
2123
+ async function runGh(runCommand, args) {
2124
+ let result;
2125
+ try {
2126
+ result = await runCommand(GH_CLI, args);
2127
+ } catch (error) {
2128
+ const detail = error instanceof Error ? error.message : String(error);
2129
+ throw new ForgeCliUnavailableError(
2130
+ "github",
2131
+ GH_CLI,
2132
+ `Failed to run the gh CLI: ${detail}`
2133
+ );
2134
+ }
2135
+ if (result.exitCode !== 0) {
2136
+ const detail = result.stderr.trim() || `exit code ${result.exitCode}`;
2137
+ throw new ForgeCliUnavailableError(
2138
+ "github",
2139
+ GH_CLI,
2140
+ `gh exited with code ${result.exitCode}: ${detail}`
2141
+ );
2142
+ }
2143
+ return result.stdout;
2144
+ }
2145
+ function parseGhJson(stdout, context) {
2146
+ try {
2147
+ return JSON.parse(stdout);
2148
+ } catch {
2149
+ throw new ForgeCliUnavailableError(
2150
+ "github",
2151
+ GH_CLI,
2152
+ `gh returned unparseable JSON for ${context}`
2153
+ );
2154
+ }
2155
+ }
2156
+ function toAnchor(comment) {
2157
+ const outdated = comment.line === null || comment.line === void 0;
2158
+ const endLine = outdated ? comment.original_line ?? null : comment.line;
2159
+ const startLine = outdated ? comment.original_start_line ?? comment.original_line ?? null : comment.start_line ?? comment.line;
2160
+ const hasLines = startLine !== null && endLine !== null;
2161
+ return {
2162
+ filePath: comment.path,
2163
+ // Side is meaningless without usable lines; the contract says 'new'.
2164
+ side: hasLines && comment.side === "LEFT" ? "old" : "new",
2165
+ startLine: hasLines ? startLine : null,
2166
+ endLine: hasLines ? endLine : null,
2167
+ outdated
2168
+ };
2169
+ }
2170
+ function toTurn(comment) {
2171
+ return {
2172
+ remoteId: String(comment.id),
2173
+ author: comment.user?.login ?? "ghost",
2174
+ body: comment.body
2175
+ };
2176
+ }
2177
+ function groupIntoThreads(comments) {
2178
+ const threads = [];
2179
+ const threadByCommentId = /* @__PURE__ */ new Map();
2180
+ for (const comment of comments) {
2181
+ const parentThread = comment.in_reply_to_id === null || comment.in_reply_to_id === void 0 ? void 0 : threadByCommentId.get(comment.in_reply_to_id);
2182
+ if (parentThread) {
2183
+ parentThread.replies.push(toTurn(comment));
2184
+ threadByCommentId.set(comment.id, parentThread);
2185
+ } else {
2186
+ const thread = {
2187
+ root: toTurn(comment),
2188
+ replies: [],
2189
+ anchor: toAnchor(comment)
2190
+ };
2191
+ threads.push(thread);
2192
+ threadByCommentId.set(comment.id, thread);
2193
+ }
2194
+ }
2195
+ return threads;
2196
+ }
2197
+ function createGitHubProvider(runCommand) {
2198
+ return {
2199
+ forge: "github",
2200
+ async fetchBaseBranch(url) {
2201
+ const stdout = await runGh(runCommand, [
2202
+ "pr",
2203
+ "view",
2204
+ String(url.number),
2205
+ "--repo",
2206
+ `${url.host}/${url.owner}/${url.repo}`,
2207
+ "--json",
2208
+ "baseRefName"
2209
+ ]);
2210
+ const parsed = parseGhJson(stdout, "pr view");
2211
+ if (typeof parsed?.baseRefName !== "string" || parsed.baseRefName === "") {
2212
+ throw new ForgeCliUnavailableError(
2213
+ "github",
2214
+ GH_CLI,
2215
+ "gh pr view returned no baseRefName"
2216
+ );
2217
+ }
2218
+ return parsed.baseRefName;
2219
+ },
2220
+ // The REST review-comment list carries no resolution state, so
2221
+ // `options.includeResolved` is deliberately ignored: GitHub fetch
2222
+ // returns all review threads (resolved-state filtering is a GitLab
2223
+ // concern).
2224
+ async fetchThreads(url, _options) {
2225
+ const stdout = await runGh(runCommand, [
2226
+ "api",
2227
+ `repos/${url.owner}/${url.repo}/pulls/${url.number}/comments`,
2228
+ "--hostname",
2229
+ url.host,
2230
+ "--paginate",
2231
+ "--slurp"
2232
+ ]);
2233
+ const pages = parseGhJson(stdout, "pull request comments");
2234
+ if (!Array.isArray(pages)) {
2235
+ throw new ForgeCliUnavailableError(
2236
+ "github",
2237
+ GH_CLI,
2238
+ "gh api returned an unexpected payload shape for pull request comments"
2239
+ );
2240
+ }
2241
+ const comments = pages.flat(1);
2242
+ return groupIntoThreads(comments);
2243
+ }
2244
+ };
2245
+ }
2246
+
2247
+ // src/thread-mapper.ts
2248
+ var REVIEW_LEVEL_FILE_PATH = "";
2249
+ function mapAnchorToLineRange(anchor) {
2250
+ if (anchor.outdated) {
2251
+ return null;
2252
+ }
2253
+ const { startLine, endLine } = anchor;
2254
+ if (startLine === null || endLine === null) {
2255
+ return null;
2256
+ }
2257
+ if (startLine < 1 || endLine < 1) {
2258
+ return null;
2259
+ }
2260
+ return {
2261
+ side: anchor.side,
2262
+ start: Math.min(startLine, endLine),
2263
+ end: Math.max(startLine, endLine)
2264
+ };
2265
+ }
2266
+ function internalId(turn) {
2267
+ return `remote-${turn.remoteId}`;
2268
+ }
2269
+ function mapReply(turn) {
2270
+ return {
2271
+ id: internalId(turn),
2272
+ body: turn.body,
2273
+ author: turn.author,
2274
+ remoteId: turn.remoteId
2275
+ };
2276
+ }
2277
+ function mapThreadsToReviewComments(threads) {
2278
+ return threads.map((thread) => {
2279
+ const comment = {
2280
+ id: internalId(thread.root),
2281
+ filePath: thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH,
2282
+ lineRange: thread.anchor ? mapAnchorToLineRange(thread.anchor) : null,
2283
+ body: thread.root.body,
2284
+ category: "",
2285
+ suggestion: null,
2286
+ author: thread.root.author,
2287
+ remoteId: thread.root.remoteId
2288
+ };
2289
+ if (thread.replies.length > 0) {
2290
+ comment.replies = thread.replies.map(mapReply);
2291
+ }
2292
+ return comment;
2293
+ });
2294
+ }
2295
+
2296
+ // src/gitlab-provider.ts
2297
+ var GLAB_CLI = "glab";
2298
+ function encodeProjectPath(url) {
2299
+ return encodeURIComponent(`${url.owner}/${url.repo}`);
2300
+ }
2301
+ function unavailable(message) {
2302
+ return new ForgeCliUnavailableError("gitlab", GLAB_CLI, message);
2303
+ }
2304
+ async function runGlabApi(runCommand, url, endpoint, extraArgs = []) {
2305
+ const args = ["api", endpoint, "--hostname", url.host, ...extraArgs];
2306
+ let result;
2307
+ try {
2308
+ result = await runCommand(GLAB_CLI, args);
2309
+ } catch (error) {
2310
+ const detail = error instanceof Error ? error.message : String(error);
2311
+ throw unavailable(`glab CLI could not be spawned: ${detail}`);
2312
+ }
2313
+ if (result.exitCode !== 0) {
2314
+ const detail = result.stderr.trim() || `exit code ${result.exitCode}`;
2315
+ throw unavailable(`glab api ${endpoint} failed: ${detail}`);
2316
+ }
2317
+ return result.stdout;
2318
+ }
2319
+ function parseJsonDocuments(text) {
2320
+ const documents = [];
2321
+ let depth = 0;
2322
+ let inString = false;
2323
+ let escaped = false;
2324
+ let start = -1;
2325
+ for (let i = 0; i < text.length; i++) {
2326
+ const ch = text[i];
2327
+ if (inString) {
2328
+ if (escaped) {
2329
+ escaped = false;
2330
+ } else if (ch === "\\") {
2331
+ escaped = true;
2332
+ } else if (ch === '"') {
2333
+ inString = false;
2334
+ }
2335
+ continue;
2336
+ }
2337
+ if (ch === '"') {
2338
+ inString = true;
2339
+ } else if (ch === "[" || ch === "{") {
2340
+ if (depth === 0) start = i;
2341
+ depth += 1;
2342
+ } else if (ch === "]" || ch === "}") {
2343
+ depth -= 1;
2344
+ if (depth === 0 && start >= 0) {
2345
+ documents.push(JSON.parse(text.slice(start, i + 1)));
2346
+ start = -1;
2347
+ }
2348
+ }
2349
+ }
2350
+ if (depth !== 0 || inString) {
2351
+ throw new Error("truncated JSON document");
2352
+ }
2353
+ return documents;
2354
+ }
2355
+ function toTurn2(note) {
2356
+ return {
2357
+ remoteId: String(note.id),
2358
+ author: note.author?.username ?? "unknown",
2359
+ body: note.body ?? ""
2360
+ };
2361
+ }
2362
+ function isDiscussionResolved(notes) {
2363
+ const resolvable = notes.filter((note) => note.resolvable === true);
2364
+ return resolvable.length > 0 && resolvable.every((note) => note.resolved === true);
2365
+ }
2366
+ function toAnchor2(position) {
2367
+ if (!position) return null;
2368
+ const side = typeof position.old_line === "number" && typeof position.new_line !== "number" ? "old" : "new";
2369
+ const pathForSide = side === "old" ? position.old_path : position.new_path;
2370
+ const filePath = pathForSide ?? position.new_path ?? position.old_path;
2371
+ if (!filePath) return null;
2372
+ const lineOf = (edge) => {
2373
+ const value = side === "old" ? edge?.old_line : edge?.new_line;
2374
+ return typeof value === "number" ? value : null;
2375
+ };
2376
+ const positionLine = lineOf(position);
2377
+ const startLine = lineOf(position.line_range?.start) ?? positionLine;
2378
+ const endLine = lineOf(position.line_range?.end) ?? positionLine;
2379
+ return { filePath, side, startLine, endLine, outdated: false };
2380
+ }
2381
+ function toThread(discussion) {
2382
+ const notes = (discussion.notes ?? []).filter((note) => note.system !== true);
2383
+ if (notes.length === 0) return null;
2384
+ const [rootNote, ...replyNotes] = notes;
2385
+ return {
2386
+ root: toTurn2(rootNote),
2387
+ replies: replyNotes.map(toTurn2),
2388
+ anchor: toAnchor2(rootNote.position)
2389
+ };
2390
+ }
2391
+ function createGitLabProvider(runCommand) {
2392
+ return {
2393
+ forge: "gitlab",
2394
+ async fetchBaseBranch(url) {
2395
+ const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}`;
2396
+ const stdout = await runGlabApi(runCommand, url, endpoint);
2397
+ let mr;
2398
+ try {
2399
+ mr = JSON.parse(stdout);
2400
+ } catch {
2401
+ throw unavailable(`glab api ${endpoint} returned unparseable JSON`);
2402
+ }
2403
+ const targetBranch = mr?.target_branch;
2404
+ if (typeof targetBranch !== "string" || targetBranch.length === 0) {
2405
+ throw unavailable(`glab api ${endpoint} returned no target_branch`);
2406
+ }
2407
+ return targetBranch;
2408
+ },
2409
+ async fetchThreads(url, options) {
2410
+ const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}/discussions`;
2411
+ const stdout = await runGlabApi(runCommand, url, endpoint, ["--paginate"]);
2412
+ let discussions;
2413
+ try {
2414
+ const pages = parseJsonDocuments(stdout);
2415
+ if (pages.length === 0 && stdout.trim() !== "") {
2416
+ throw new Error("no JSON documents in output");
2417
+ }
2418
+ discussions = pages.flatMap(
2419
+ (page) => Array.isArray(page) ? page : []
2420
+ );
2421
+ } catch {
2422
+ throw unavailable(`glab api ${endpoint} returned unparseable JSON`);
2423
+ }
2424
+ const includeResolved = options?.includeResolved === true;
2425
+ const threads = [];
2426
+ for (const discussion of discussions) {
2427
+ const notes = discussion.notes ?? [];
2428
+ if (!includeResolved && isDiscussionResolved(notes)) continue;
2429
+ const thread = toThread(discussion);
2430
+ if (thread) threads.push(thread);
2431
+ }
2432
+ return threads;
2433
+ }
2434
+ };
2435
+ }
2436
+
2437
+ // src/materializer.ts
2438
+ import { execFile as execFile2 } from "child_process";
2439
+ import * as fs2 from "fs";
2440
+ import * as os from "os";
2441
+ import * as path2 from "path";
2442
+ var LOCAL_BASE_REF = "refs/self-review/base";
2443
+ var LOCAL_HEAD_REF = "refs/self-review/head";
2444
+ 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.";
2445
+ var defaultGitRunner = (command, args) => new Promise((resolve, reject) => {
2446
+ execFile2(
2447
+ command,
2448
+ args,
2449
+ { maxBuffer: 50 * 1024 * 1024 },
2450
+ (error, stdout, stderr) => {
2451
+ const spawnCode = error?.code;
2452
+ if (error && typeof spawnCode === "string") {
2453
+ reject(error);
2454
+ return;
2455
+ }
2456
+ resolve({
2457
+ stdout: stdout ?? "",
2458
+ stderr: stderr ?? "",
2459
+ exitCode: error ? typeof spawnCode === "number" ? spawnCode : 1 : 0
2460
+ });
2461
+ }
2462
+ );
2463
+ });
2464
+ function headRefFor(url) {
2465
+ return url.forge === "github" ? `refs/pull/${url.number}/head` : `refs/merge-requests/${url.number}/head`;
2466
+ }
2467
+ function cloneUrlFor(url) {
2468
+ return `https://${url.host}/${url.owner}/${url.repo}.git`;
2469
+ }
2470
+ function gitFailure(what, result, withAuthHint) {
2471
+ const stderr = result.stderr.trim();
2472
+ const lines = [
2473
+ `git ${what} failed (exit code ${result.exitCode})${stderr ? `:
2474
+ ${stderr}` : ""}`
2475
+ ];
2476
+ if (withAuthHint) {
2477
+ lines.push("", AUTH_HINT);
2478
+ }
2479
+ return new Error(lines.join("\n"));
2480
+ }
2481
+ function stripRepoPath(repoPath) {
2482
+ return repoPath.replace(/\/+$/, "").replace(/\.git$/i, "");
2483
+ }
2484
+ function normalizeRemoteUrl(raw) {
2485
+ const trimmed = raw.trim();
2486
+ if (trimmed.includes("://")) {
2487
+ try {
2488
+ const parsed = new URL(trimmed);
2489
+ return {
2490
+ host: parsed.host.toLowerCase(),
2491
+ path: stripRepoPath(parsed.pathname.replace(/^\/+/, "")).toLowerCase()
2492
+ };
2493
+ } catch {
2494
+ return null;
2495
+ }
2496
+ }
2497
+ const scp = /^(?:[^@\s]+@)?([^:/\s]+):(.+)$/.exec(trimmed);
2498
+ if (scp) {
2499
+ return {
2500
+ host: scp[1].toLowerCase(),
2501
+ path: stripRepoPath(scp[2].replace(/^\/+/, "")).toLowerCase()
2502
+ };
2503
+ }
2504
+ return null;
2505
+ }
2506
+ function findMatchingRemote(remoteVOutput, url) {
2507
+ const wantedHost = url.host.toLowerCase();
2508
+ const wantedPath = `${url.owner}/${url.repo}`.toLowerCase();
2509
+ for (const line of remoteVOutput.split("\n")) {
2510
+ const match = /^(\S+)\t(.+?)\s+\(fetch\)$/.exec(line.trim());
2511
+ if (!match) continue;
2512
+ const normalized = normalizeRemoteUrl(match[2]);
2513
+ if (normalized && normalized.host === wantedHost && normalized.path === wantedPath) {
2514
+ return match[1];
2515
+ }
2516
+ }
2517
+ return null;
2518
+ }
2519
+ async function revParse(runner, repoPath, ref) {
2520
+ const result = await runner("git", ["-C", repoPath, "rev-parse", ref]);
2521
+ if (result.exitCode !== 0) {
2522
+ throw gitFailure(`rev-parse ${ref}`, result, false);
2523
+ }
2524
+ return result.stdout.trim();
2525
+ }
2526
+ async function detectExistingClone(url, cwd, runner = defaultGitRunner) {
2527
+ const toplevel = await runner("git", ["-C", cwd, "rev-parse", "--show-toplevel"]);
2528
+ if (toplevel.exitCode !== 0) {
2529
+ return null;
2530
+ }
2531
+ const repoPath = toplevel.stdout.trim();
2532
+ const remotes = await runner("git", ["-C", repoPath, "remote", "-v"]);
2533
+ if (remotes.exitCode !== 0) {
2534
+ return null;
2535
+ }
2536
+ const remoteName = findMatchingRemote(remotes.stdout, url);
2537
+ return remoteName === null ? null : { repoPath, remoteName };
2538
+ }
2539
+ async function materializeIntoExistingClone(runner, url, baseBranch, repoPath, remoteName) {
2540
+ console.error(
2541
+ `self-review: reusing existing clone at ${repoPath} (remote "${remoteName}")`
2542
+ );
2543
+ const fetch = await runner("git", [
2544
+ "-C",
2545
+ repoPath,
2546
+ "fetch",
2547
+ remoteName,
2548
+ `+refs/heads/${baseBranch}:${LOCAL_BASE_REF}`,
2549
+ `+${headRefFor(url)}:${LOCAL_HEAD_REF}`
2550
+ ]);
2551
+ if (fetch.exitCode !== 0) {
2552
+ throw gitFailure(`fetch from remote "${remoteName}"`, fetch, true);
2553
+ }
2554
+ return {
2555
+ repoPath,
2556
+ baseSha: await revParse(runner, repoPath, LOCAL_BASE_REF),
2557
+ headSha: await revParse(runner, repoPath, LOCAL_HEAD_REF),
2558
+ mode: "existing-clone",
2559
+ cleanup: () => {
2560
+ }
2561
+ };
2562
+ }
2563
+ async function materializeIntoTempClone(runner, url, baseBranch) {
2564
+ const tempDir = fs2.mkdtempSync(path2.join(os.tmpdir(), "self-review-"));
2565
+ let removed = false;
2566
+ const cleanup = () => {
2567
+ if (removed) return;
2568
+ removed = true;
2569
+ fs2.rmSync(tempDir, { recursive: true, force: true });
2570
+ };
2571
+ try {
2572
+ console.error(
2573
+ `self-review: created temporary blobless clone at ${tempDir}`
2574
+ );
2575
+ const cloneUrl = cloneUrlFor(url);
2576
+ const clone = await runner("git", [
2577
+ "clone",
2578
+ "--filter=blob:none",
2579
+ cloneUrl,
2580
+ tempDir
2581
+ ]);
2582
+ if (clone.exitCode !== 0) {
2583
+ throw gitFailure(`clone of ${cloneUrl}`, clone, true);
2584
+ }
2585
+ const fetch = await runner("git", [
2586
+ "-C",
2587
+ tempDir,
2588
+ "fetch",
2589
+ "origin",
2590
+ `+${headRefFor(url)}:${LOCAL_HEAD_REF}`
2591
+ ]);
2592
+ if (fetch.exitCode !== 0) {
2593
+ throw gitFailure(`fetch of ${headRefFor(url)}`, fetch, true);
2594
+ }
2595
+ return {
2596
+ repoPath: tempDir,
2597
+ baseSha: await revParse(runner, tempDir, `origin/${baseBranch}`),
2598
+ headSha: await revParse(runner, tempDir, LOCAL_HEAD_REF),
2599
+ mode: "temp-clone",
2600
+ cleanup
2601
+ };
2602
+ } catch (error) {
2603
+ cleanup();
2604
+ throw error;
2605
+ }
2606
+ }
2607
+ async function materialize(url, baseBranch, cwd, runner = defaultGitRunner, existingClone) {
2608
+ const existing = existingClone === void 0 ? await detectExistingClone(url, cwd, runner) : existingClone;
2609
+ if (existing) {
2610
+ return materializeIntoExistingClone(
2611
+ runner,
2612
+ url,
2613
+ baseBranch,
2614
+ existing.repoPath,
2615
+ existing.remoteName
2616
+ );
2617
+ }
2618
+ return materializeIntoTempClone(runner, url, baseBranch);
2619
+ }
2620
+ async function resolveRemoteDefaultBranch(url, runner = defaultGitRunner, existing = null) {
2621
+ const cloneUrl = cloneUrlFor(url);
2622
+ const remote = existing?.remoteName ?? cloneUrl;
2623
+ const label = existing ? `${remote} (${cloneUrl})` : cloneUrl;
2624
+ const args = existing ? ["-C", existing.repoPath, "ls-remote", "--symref", remote, "HEAD"] : ["ls-remote", "--symref", remote, "HEAD"];
2625
+ const result = await runner("git", args);
2626
+ if (result.exitCode !== 0) {
2627
+ throw gitFailure(`ls-remote of ${label}`, result, true);
2628
+ }
2629
+ const match = /^ref:\s+refs\/heads\/(\S+)\s+HEAD$/m.exec(result.stdout);
2630
+ if (!match) {
2631
+ throw new Error(
2632
+ `Failed to resolve the default branch of ${label}: git ls-remote returned no HEAD symref.`
2633
+ );
2634
+ }
2635
+ return match[1];
2636
+ }
1935
2637
  export {
2638
+ ForgeCliUnavailableError,
1936
2639
  GUIDE_XSD_SCHEMA,
1937
2640
  IMPLICIT_GUIDE_GROUP_NAME,
2641
+ REVIEW_LEVEL_FILE_PATH,
1938
2642
  checkWritability,
1939
2643
  computePayloadStats,
1940
2644
  countTotalLines,
2645
+ createGitHubProvider,
2646
+ createGitLabProvider,
1941
2647
  createIgnoreFilter,
2648
+ defaultGitRunner,
2649
+ detectExistingClone,
1942
2650
  generateSyntheticDiffs,
1943
2651
  generateUntrackedDiffs,
1944
2652
  getGitDiffStats,
@@ -1953,11 +2661,15 @@ export {
1953
2661
  isPreviewableRenderedText,
1954
2662
  isPreviewableSvg,
1955
2663
  loadConfig,
2664
+ mapThreadsToReviewComments,
2665
+ materialize,
1956
2666
  parseDiff,
2667
+ parseForgeUrl,
1957
2668
  parseGuideXml,
1958
2669
  parseReviewXml,
1959
2670
  parseReviewXmlString,
1960
2671
  reconcileGuide,
2672
+ resolveRemoteDefaultBranch,
1961
2673
  runGitDiff,
1962
2674
  runGitDiffAsync,
1963
2675
  scanDirectory,