@self-review/core 1.45.0 → 2.0.3

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
@@ -1,22 +1,118 @@
1
1
  import {
2
- parseDiff
3
- } from "./chunk-OQRS7NDT.js";
4
- import {
2
+ BINARY_SNIFF_BYTES,
3
+ DEFAULT_SOURCE_BUDGETS,
4
+ MAX_GIT_DIFF_OUTPUT_BYTES,
5
+ MAX_GUIDE_BYTES,
6
+ MAX_IMAGE_BYTES,
7
+ MAX_RESUME_ATTACHMENTS,
8
+ MAX_RESUME_XML_BYTES,
9
+ MAX_SOURCE_ENTRIES,
10
+ MAX_SOURCE_FILE_BYTES,
11
+ MAX_SOURCE_TOTAL_BYTES,
12
+ PARSER_COMPATIBLE_DIFF_FLAGS,
13
+ PARSER_COMPATIBLE_GIT_CONFIG,
14
+ READ_FLAGS,
15
+ formatBytes,
5
16
  generateSyntheticDiffs,
6
17
  generateUntrackedDiffs,
7
- getRepoRoot,
8
18
  getRepoRootAsync,
9
19
  getUntrackedFilesAsync,
10
- runGitDiff,
20
+ isOutputLimitError,
21
+ loadSyntheticFiles,
22
+ readDescriptorWithinBudget,
23
+ readFileWithinBudget,
24
+ readFileWithinBudgetSync,
25
+ resolveSourceBudgets,
11
26
  runGitDiffAsync,
12
27
  stripTrailingNewline,
13
- validateGitAvailable
14
- } from "./chunk-A7A5ZFT3.js";
28
+ withParserCompatibleDiffArgs
29
+ } from "./chunk-QHS36X6T.js";
30
+ import {
31
+ parseDiff,
32
+ parseDiffWithDiagnostics
33
+ } from "./chunk-4YO2MI6B.js";
15
34
 
16
35
  // src/xml-serializer.ts
17
36
  import * as path from "path";
18
- import * as fs from "fs";
19
37
  import { validateXML } from "xmllint-wasm";
38
+
39
+ // src/xml-errors.ts
40
+ var ReviewXmlError = class extends Error {
41
+ constructor(code, message, options) {
42
+ super(message);
43
+ this.name = "ReviewXmlError";
44
+ this.code = code;
45
+ this.details = options?.details ?? [];
46
+ if (options?.cause !== void 0) this.cause = options.cause;
47
+ }
48
+ };
49
+ var XmlIllegalCharacterError = class extends ReviewXmlError {
50
+ constructor(codePoint, location) {
51
+ super("xml-illegal-character", describeIllegalCharacter(codePoint, location));
52
+ this.name = "XmlIllegalCharacterError";
53
+ this.codePoint = codePoint;
54
+ this.field = location.field;
55
+ this.filePath = location.filePath;
56
+ this.commentId = location.commentId;
57
+ this.replyId = location.replyId;
58
+ }
59
+ };
60
+ function describeIllegalCharacter(codePoint, location) {
61
+ const hex = codePoint.toString(16).toUpperCase().padStart(4, "0");
62
+ const where = [
63
+ location.filePath !== void 0 ? `file "${location.filePath}"` : null,
64
+ location.commentId !== void 0 ? `comment ${location.commentId}` : null,
65
+ location.replyId !== void 0 ? `reply ${location.replyId}` : null
66
+ ].filter((part) => part !== null).join(", ");
67
+ return `Cannot write review XML: ${location.field}${where ? ` of ${where}` : ""} contains U+${hex}, which XML 1.0 cannot represent. Remove the character and save again.`;
68
+ }
69
+
70
+ // src/xml-text.ts
71
+ function isLegalXmlCodePoint(cp) {
72
+ return cp === 9 || cp === 10 || cp === 13 || cp >= 32 && cp <= 55295 || cp >= 57344 && cp <= 65533 || cp >= 65536 && cp <= 1114111;
73
+ }
74
+ function findIllegalXmlCharacter(str) {
75
+ for (let i = 0; i < str.length; i++) {
76
+ const unit = str.charCodeAt(i);
77
+ if (unit >= 55296 && unit <= 56319) {
78
+ const low = i + 1 < str.length ? str.charCodeAt(i + 1) : 0;
79
+ if (low >= 56320 && low <= 57343) {
80
+ i++;
81
+ continue;
82
+ }
83
+ return { codePoint: unit, index: i };
84
+ }
85
+ if (!isLegalXmlCodePoint(unit)) {
86
+ return { codePoint: unit, index: i };
87
+ }
88
+ }
89
+ return null;
90
+ }
91
+ function escapeXmlText(str) {
92
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/\r/g, "&#13;");
93
+ }
94
+ function escapeXmlAttribute(str) {
95
+ return escapeXmlText(str).replace(/\n/g, "&#10;").replace(/\t/g, "&#9;");
96
+ }
97
+ var PREDEFINED = {
98
+ lt: "<",
99
+ gt: ">",
100
+ amp: "&",
101
+ quot: '"',
102
+ apos: "'"
103
+ };
104
+ function decodeXmlEntities(raw) {
105
+ return raw.replace(
106
+ /&(lt|gt|amp|quot|apos|#\d{1,8}|#x[0-9a-fA-F]{1,8});/g,
107
+ (match, ref) => {
108
+ if (ref[0] !== "#") return PREDEFINED[ref];
109
+ const cp = ref[1] === "x" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);
110
+ return isLegalXmlCodePoint(cp) ? String.fromCodePoint(cp) : match;
111
+ }
112
+ );
113
+ }
114
+
115
+ // src/xml-serializer.ts
20
116
  var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
21
117
  <xs:schema
22
118
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
@@ -182,7 +278,7 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
182
278
  <xs:attribute name="change-type" type="sr:ChangeTypeEnum" use="required">
183
279
  <xs:annotation>
184
280
  <xs:documentation>
185
- The type of change: added, modified, deleted, or renamed.
281
+ The type of change: added, modified, deleted, renamed, or copied.
186
282
  </xs:documentation>
187
283
  </xs:annotation>
188
284
  </xs:attribute>
@@ -526,6 +622,11 @@ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
526
622
  <xs:documentation>File was moved or renamed, with or without content changes.</xs:documentation>
527
623
  </xs:annotation>
528
624
  </xs:enumeration>
625
+ <xs:enumeration value="copied">
626
+ <xs:annotation>
627
+ <xs:documentation>File was copied from another path (git copy detection), with or without content changes.</xs:documentation>
628
+ </xs:annotation>
629
+ </xs:enumeration>
529
630
  </xs:restriction>
530
631
  </xs:simpleType>
531
632
 
@@ -649,31 +750,26 @@ function extFromMediaType(mediaType) {
649
750
  function assetNameComponent(idPrefix) {
650
751
  return String(idPrefix ?? "").replace(/[^A-Za-z0-9_-]/g, "_");
651
752
  }
652
- function persistAttachments(attachments, idPrefix, assetDir, onWrite) {
753
+ var ASSET_DIR_NAME = ".self-review-assets";
754
+ var defaultAssetName = (idPrefix, index, ext) => `${idPrefix}-${index}.${ext}`;
755
+ function stageAttachmentList(attachments, idPrefix, assetDir, assetName, assets) {
653
756
  if (!attachments?.length) return attachments;
654
757
  return attachments.map((att, index) => {
655
758
  if (!att.data) return att;
656
- onWrite();
657
759
  const ext = extFromMediaType(att.mediaType);
658
- const fileName = `${assetNameComponent(idPrefix)}-${index}.${ext}`;
659
- const relativePath = `.self-review-assets/${fileName}`;
660
- const target = path.join(assetDir, fileName);
661
- if (path.dirname(path.resolve(target)) !== path.resolve(assetDir)) {
760
+ const fileName = assetName(assetNameComponent(idPrefix), index, ext);
761
+ const relativePath = `${ASSET_DIR_NAME}/${fileName}`;
762
+ const absolutePath = path.join(assetDir, fileName);
763
+ if (path.dirname(path.resolve(absolutePath)) !== path.resolve(assetDir)) {
662
764
  throw new Error(`Refusing to write an attachment outside ${assetDir}: ${fileName}`);
663
765
  }
664
- if (!fs.existsSync(assetDir)) {
665
- fs.mkdirSync(assetDir, { recursive: true });
666
- }
667
- fs.writeFileSync(target, Buffer.from(att.data));
766
+ assets.push({ relativePath, absolutePath, data: att.data });
668
767
  return { ...att, fileName: relativePath, data: void 0 };
669
768
  });
670
769
  }
671
- function writeAttachments(state, outputFilePath) {
672
- const assetDir = path.join(path.dirname(outputFilePath), ".self-review-assets");
673
- let hasAttachments = false;
674
- const markWritten = () => {
675
- hasAttachments = true;
676
- };
770
+ function stageAttachments(state, outputFilePath, assetName) {
771
+ const assetDir = path.join(path.dirname(outputFilePath), ASSET_DIR_NAME);
772
+ const assets = [];
677
773
  const updatedFiles = state.files.map((file) => ({
678
774
  ...file,
679
775
  // Every comment is walked, including one with no attachments of its own:
@@ -681,43 +777,43 @@ function writeAttachments(state, outputFilePath) {
681
777
  // own list would drop those blobs without a word.
682
778
  comments: file.comments.map((comment) => ({
683
779
  ...comment,
684
- attachments: persistAttachments(comment.attachments, comment.id, assetDir, markWritten),
780
+ attachments: stageAttachmentList(
781
+ comment.attachments,
782
+ comment.id,
783
+ assetDir,
784
+ assetName,
785
+ assets
786
+ ),
685
787
  ...comment.replies ? {
686
788
  replies: comment.replies.map((reply) => ({
687
789
  ...reply,
688
- attachments: persistAttachments(
790
+ attachments: stageAttachmentList(
689
791
  reply.attachments,
690
792
  `${comment.id}-r-${reply.id}`,
691
793
  assetDir,
692
- markWritten
794
+ assetName,
795
+ assets
693
796
  )
694
797
  }))
695
798
  } : {}
696
799
  }))
697
800
  }));
698
- if (hasAttachments) {
699
- console.error(`[main] Wrote attachment files to ${assetDir}`);
700
- }
701
- return { ...state, files: updatedFiles };
801
+ return { state: { ...state, files: updatedFiles }, assets };
702
802
  }
703
- async function serializeReview(state, outputFilePath) {
704
- const processedState = writeAttachments(state, outputFilePath);
705
- const xml = buildXml(processedState);
803
+ async function serializeReview(state, outputFilePath, options = {}) {
804
+ const staged = stageAttachments(state, outputFilePath, options.assetName ?? defaultAssetName);
805
+ const xml = buildXml(staged.state);
806
+ await validateAgainstSchema(xml);
807
+ return { xml, assets: staged.assets };
808
+ }
809
+ async function validateAgainstSchema(xml) {
810
+ let validationResult;
706
811
  try {
707
- const validationResult = await validateXML({
812
+ validationResult = await validateXML({
708
813
  xml: [{ fileName: "review.xml", contents: xml }],
709
814
  schema: [{ fileName: "self-review-v3.xsd", contents: XSD_SCHEMA }]
710
815
  });
711
- if (!validationResult.valid) {
712
- const errors = validationResult.errors || [];
713
- console.error("XML validation failed:");
714
- errors.forEach((err) => console.error(` ${err}`));
715
- throw new Error("Generated XML does not conform to schema");
716
- }
717
816
  } catch (error) {
718
- if (error instanceof Error && error.message === "Generated XML does not conform to schema") {
719
- throw error;
720
- }
721
817
  if (error instanceof Error) {
722
818
  console.error(
723
819
  `[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`
@@ -727,30 +823,49 @@ async function serializeReview(state, outputFilePath) {
727
823
  "[main] XML validation infrastructure failed - emitting XML without validation"
728
824
  );
729
825
  }
730
- return xml;
826
+ return;
827
+ }
828
+ if (!validationResult.valid) {
829
+ const details = (validationResult.errors || []).map(formatSchemaError);
830
+ console.error("XML validation failed:");
831
+ details.forEach((detail) => console.error(` ${detail}`));
832
+ throw new ReviewXmlError(
833
+ "schema-invalid",
834
+ `Generated XML does not conform to schema${details.length ? `: ${details.join("; ")}` : ""}`,
835
+ { details }
836
+ );
731
837
  }
732
- return xml;
838
+ }
839
+ function formatSchemaError(err) {
840
+ if (typeof err === "string") return err;
841
+ if (err && typeof err === "object") {
842
+ const { message, loc } = err;
843
+ const text3 = typeof message === "string" ? message : JSON.stringify(err);
844
+ const line = loc && typeof loc === "object" ? loc.lineNumber : void 0;
845
+ return typeof line === "number" ? `line ${line}: ${text3}` : text3;
846
+ }
847
+ return String(err);
733
848
  }
734
849
  function buildSourceAttributes(state) {
735
850
  const source = state.source;
736
851
  if (source.type === "git") {
737
- return ` git-diff-args="${escapeXml(source.gitDiffArgs)}" repository="${escapeXml(source.repository)}"`;
852
+ return ` git-diff-args="${attr(source.gitDiffArgs, { field: "git-diff-args" })}" repository="${attr(source.repository, { field: "repository" })}"`;
738
853
  }
739
854
  if (source.type === "directory" || source.type === "file") {
740
- return ` source-path="${escapeXml(source.sourcePath)}"`;
855
+ return ` source-path="${attr(source.sourcePath, { field: "source-path" })}"`;
741
856
  }
742
857
  return "";
743
858
  }
744
859
  function buildRemoteAttributes(state) {
745
860
  const attrs = [];
746
861
  if (state.remoteUrl) {
747
- attrs.push(`remote-url="${escapeXml(state.remoteUrl)}"`);
862
+ attrs.push(`remote-url="${attr(state.remoteUrl, { field: "remote-url" })}"`);
748
863
  }
749
864
  if (state.remoteBaseSha) {
750
- attrs.push(`remote-base-sha="${escapeXml(state.remoteBaseSha)}"`);
865
+ attrs.push(`remote-base-sha="${attr(state.remoteBaseSha, { field: "remote-base-sha" })}"`);
751
866
  }
752
867
  if (state.remoteHeadSha) {
753
- attrs.push(`remote-head-sha="${escapeXml(state.remoteHeadSha)}"`);
868
+ attrs.push(`remote-head-sha="${attr(state.remoteHeadSha, { field: "remote-head-sha" })}"`);
754
869
  }
755
870
  if (state.remoteForge) {
756
871
  attrs.push(`remote-forge="${state.remoteForge}"`);
@@ -763,7 +878,7 @@ function buildXml(state) {
763
878
  const sourceAttrs = buildSourceAttributes(state);
764
879
  const remoteAttrs = buildRemoteAttributes(state);
765
880
  lines.push(
766
- `<review xmlns="urn:self-review:v3" timestamp="${escapeXml(state.timestamp)}"${sourceAttrs}${remoteAttrs}>`
881
+ `<review xmlns="urn:self-review:v3" timestamp="${attr(state.timestamp, { field: "timestamp" })}"${sourceAttrs}${remoteAttrs}>`
767
882
  );
768
883
  for (const file of state.files) {
769
884
  lines.push(...buildFileXml(file));
@@ -773,24 +888,30 @@ function buildXml(state) {
773
888
  }
774
889
  function buildFileXml(file) {
775
890
  const lines = [];
891
+ const pathAttr = attr(file.path, { field: "path", filePath: file.path });
776
892
  if (file.comments.length === 0) {
777
893
  lines.push(
778
- ` <file path="${escapeXml(file.path)}" change-type="${file.changeType}" viewed="${file.viewed}" />`
894
+ ` <file path="${pathAttr}" change-type="${file.changeType}" viewed="${file.viewed}" />`
779
895
  );
780
896
  } else {
781
897
  lines.push(
782
- ` <file path="${escapeXml(file.path)}" change-type="${file.changeType}" viewed="${file.viewed}">`
898
+ ` <file path="${pathAttr}" change-type="${file.changeType}" viewed="${file.viewed}">`
783
899
  );
784
900
  for (const comment of file.comments) {
785
- lines.push(...buildCommentXml(comment));
901
+ lines.push(...buildCommentXml(comment, file.path));
786
902
  }
787
903
  lines.push(" </file>");
788
904
  }
789
905
  return lines;
790
906
  }
791
- function buildCommentXml(comment) {
907
+ function buildCommentXml(comment, filePath) {
792
908
  const lines = [];
793
909
  const attrs = [];
910
+ const at = (field) => ({
911
+ field,
912
+ filePath,
913
+ commentId: comment.id
914
+ });
794
915
  if (comment.lineRange) {
795
916
  if (comment.lineRange.side === "old") {
796
917
  attrs.push(`old-line-start="${comment.lineRange.start}"`);
@@ -801,7 +922,7 @@ function buildCommentXml(comment) {
801
922
  }
802
923
  }
803
924
  if (comment.author) {
804
- attrs.push(`author="${escapeXml(comment.author)}"`);
925
+ attrs.push(`author="${attr(comment.author, at("author"))}"`);
805
926
  }
806
927
  if (comment.severity) {
807
928
  attrs.push(`severity="${comment.severity}"`);
@@ -810,195 +931,354 @@ function buildCommentXml(comment) {
810
931
  attrs.push(`confidence="${comment.confidence}"`);
811
932
  }
812
933
  if (comment.remoteId) {
813
- attrs.push(`remote-id="${escapeXml(comment.remoteId)}"`);
934
+ attrs.push(`remote-id="${attr(comment.remoteId, at("remote-id"))}"`);
814
935
  }
815
936
  const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
816
937
  lines.push(` <comment${attrStr}>`);
817
- lines.push(` <body>${escapeXml(comment.body)}</body>`);
818
- lines.push(` <category>${escapeXml(comment.category)}</category>`);
938
+ lines.push(` <body>${text(comment.body, at("body"))}</body>`);
939
+ lines.push(` <category>${text(comment.category, at("category"))}</category>`);
819
940
  if (comment.suggestion) {
820
941
  lines.push(" <suggestion>");
821
942
  lines.push(
822
- ` <original-code>${escapeXml(comment.suggestion.originalCode)}</original-code>`
943
+ ` <original-code>${text(comment.suggestion.originalCode, at("original-code"))}</original-code>`
823
944
  );
824
945
  lines.push(
825
- ` <proposed-code>${escapeXml(comment.suggestion.proposedCode)}</proposed-code>`
946
+ ` <proposed-code>${text(comment.suggestion.proposedCode, at("proposed-code"))}</proposed-code>`
826
947
  );
827
948
  lines.push(" </suggestion>");
828
949
  }
829
- lines.push(...buildAttachmentXml(comment.attachments, " "));
950
+ lines.push(...buildAttachmentXml(comment.attachments, " ", at("attachment")));
830
951
  for (const reply of comment.replies ?? []) {
831
- lines.push(...buildReplyXml(reply));
952
+ lines.push(...buildReplyXml(reply, filePath, comment.id));
832
953
  }
833
954
  lines.push(" </comment>");
834
955
  return lines;
835
956
  }
836
- function buildAttachmentXml(attachments, indent) {
957
+ function buildAttachmentXml(attachments, indent, owner) {
837
958
  if (!attachments?.length) return [];
838
959
  return attachments.map(
839
- (att) => `${indent}<attachment path="${escapeXml(att.fileName)}" media-type="${escapeXml(att.mediaType)}" />`
960
+ (att) => `${indent}<attachment path="${attr(att.fileName, { ...owner, field: "attachment path" })}" media-type="${attr(att.mediaType, { ...owner, field: "attachment media-type" })}" />`
840
961
  );
841
962
  }
842
- function buildReplyXml(reply) {
963
+ function buildReplyXml(reply, filePath, commentId) {
843
964
  const attrs = [];
965
+ const at = (field) => ({
966
+ field,
967
+ filePath,
968
+ commentId,
969
+ replyId: reply.id
970
+ });
844
971
  if (reply.author) {
845
- attrs.push(`author="${escapeXml(reply.author)}"`);
972
+ attrs.push(`author="${attr(reply.author, at("author"))}"`);
846
973
  }
847
974
  if (reply.remoteId) {
848
- attrs.push(`remote-id="${escapeXml(reply.remoteId)}"`);
975
+ attrs.push(`remote-id="${attr(reply.remoteId, at("remote-id"))}"`);
849
976
  }
850
977
  const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
851
978
  return [
852
979
  ` <reply${attrStr}>`,
853
- ` <body>${escapeXml(reply.body)}</body>`,
854
- ...buildAttachmentXml(reply.attachments, " "),
980
+ ` <body>${text(reply.body, at("body"))}</body>`,
981
+ ...buildAttachmentXml(reply.attachments, " ", at("attachment")),
855
982
  " </reply>"
856
983
  ];
857
984
  }
858
- function escapeXml(str) {
859
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
985
+ function text(value, location) {
986
+ return escapeXmlText(checked(value, location));
987
+ }
988
+ function attr(value, location) {
989
+ return escapeXmlAttribute(checked(value, location));
990
+ }
991
+ function checked(value, location) {
992
+ const illegal = findIllegalXmlCharacter(value);
993
+ if (illegal) throw new XmlIllegalCharacterError(illegal.codePoint, location);
994
+ return value;
995
+ }
996
+
997
+ // src/xml-parser.ts
998
+ import { XMLParser, XMLValidator } from "fast-xml-parser";
999
+
1000
+ // src/anchor-validation.ts
1001
+ function validateLineAnchor(fields, maxLine) {
1002
+ const old = sideFields("old", fields.oldLineStart, fields.oldLineEnd);
1003
+ const next = sideFields("new", fields.newLineStart, fields.newLineEnd);
1004
+ if (!old.present && !next.present) return null;
1005
+ if (old.present && next.present) {
1006
+ return { ok: false, reason: "carries both old and new line ranges" };
1007
+ }
1008
+ const side = old.present ? old : next;
1009
+ if (side.start === void 0 || side.end === void 0) {
1010
+ return { ok: false, reason: `${side.name}-line range is incomplete (start and end required)` };
1011
+ }
1012
+ const start = toPositiveSafeInteger(side.start);
1013
+ if (start === null) {
1014
+ return {
1015
+ ok: false,
1016
+ reason: `${side.name}-line-start is not a positive integer (${describe(side.start)})`
1017
+ };
1018
+ }
1019
+ const end = toPositiveSafeInteger(side.end);
1020
+ if (end === null) {
1021
+ return {
1022
+ ok: false,
1023
+ reason: `${side.name}-line-end is not a positive integer (${describe(side.end)})`
1024
+ };
1025
+ }
1026
+ return checkRange({ side: side.name, start, end }, maxLine);
1027
+ }
1028
+ function validateLineRange(range, maxLine) {
1029
+ const start = toPositiveSafeInteger(range.start);
1030
+ if (start === null) {
1031
+ return {
1032
+ ok: false,
1033
+ reason: `${range.side}-line-start is not a positive integer (${describe(range.start)})`
1034
+ };
1035
+ }
1036
+ const end = toPositiveSafeInteger(range.end);
1037
+ if (end === null) {
1038
+ return {
1039
+ ok: false,
1040
+ reason: `${range.side}-line-end is not a positive integer (${describe(range.end)})`
1041
+ };
1042
+ }
1043
+ return checkRange({ side: range.side, start, end }, maxLine);
1044
+ }
1045
+ function checkRange(anchor, maxLine) {
1046
+ if (anchor.start > anchor.end) {
1047
+ return {
1048
+ ok: false,
1049
+ reason: `${anchor.side}-line range is reversed (${anchor.start} > ${anchor.end})`
1050
+ };
1051
+ }
1052
+ if (maxLine !== void 0 && anchor.end > maxLine) {
1053
+ return {
1054
+ ok: false,
1055
+ reason: `${anchor.side}-line range ends beyond line ${maxLine} (${anchor.end})`
1056
+ };
1057
+ }
1058
+ return { ok: true, anchor };
1059
+ }
1060
+ function sideFields(name, start, end) {
1061
+ const s = isAbsent(start) ? void 0 : start;
1062
+ const e = isAbsent(end) ? void 0 : end;
1063
+ return { name, present: s !== void 0 || e !== void 0, start: s, end: e };
1064
+ }
1065
+ function isAbsent(value) {
1066
+ return value === void 0 || value === null;
1067
+ }
1068
+ function toPositiveSafeInteger(value) {
1069
+ let n;
1070
+ if (typeof value === "number") {
1071
+ n = value;
1072
+ } else if (typeof value === "string" && /^\d+$/.test(value)) {
1073
+ n = Number(value);
1074
+ } else {
1075
+ return null;
1076
+ }
1077
+ return Number.isSafeInteger(n) && n > 0 ? n : null;
1078
+ }
1079
+ function describe(value) {
1080
+ return typeof value === "string" ? JSON.stringify(value) : String(value);
860
1081
  }
861
1082
 
862
1083
  // src/xml-parser.ts
863
- import { readFileSync } from "fs";
864
- import { XMLParser } from "fast-xml-parser";
865
1084
  var SEVERITY_VALUES = ["critical", "major", "minor", "info"];
866
1085
  var CONFIDENCE_VALUES = ["high", "medium", "low"];
867
1086
  var REMOTE_FORGE_VALUES = ["github", "gitlab"];
868
1087
  function parseReviewXml(xmlPath) {
1088
+ let read;
869
1089
  try {
870
- const xmlContent = readFileSync(xmlPath, "utf-8");
871
- return parseReviewXmlString(xmlContent);
1090
+ read = readFileWithinBudgetSync(xmlPath, MAX_RESUME_XML_BYTES);
872
1091
  } catch (error) {
873
- if (error instanceof Error) {
874
- console.error(`Error reading XML file: ${error.message}`);
875
- } else {
876
- console.error("Error reading XML file: unknown error");
877
- }
878
- process.exit(1);
1092
+ throw new ReviewXmlError("read-failed", `Could not read ${xmlPath}: ${messageOf(error)}`, {
1093
+ cause: error
1094
+ });
1095
+ }
1096
+ if (read.kind === "not-regular") {
1097
+ throw new ReviewXmlError("read-failed", `Could not read ${xmlPath}: not a regular file`);
1098
+ }
1099
+ if (read.kind === "too-large") {
1100
+ throw new ReviewXmlError(
1101
+ "input-too-large",
1102
+ `Could not read ${xmlPath}: it is ${formatBytes(read.size)}, over the ${formatBytes(MAX_RESUME_XML_BYTES)} limit for a review document`
1103
+ );
879
1104
  }
1105
+ return parseReviewXmlString(read.content.toString("utf-8"));
880
1106
  }
881
1107
  function parseReviewXmlString(xmlContent) {
882
1108
  const parser = new XMLParser({
883
1109
  ignoreAttributes: false,
884
1110
  attributeNamePrefix: "@_",
885
1111
  allowBooleanAttributes: true,
886
- trimValues: false
1112
+ trimValues: false,
1113
+ // Lossless: `00123`, `1e3` and `false` stay text, and decodeXmlEntities is the only decoding.
1114
+ parseTagValue: false,
1115
+ parseAttributeValue: false,
1116
+ processEntities: false
887
1117
  });
1118
+ const wellFormed = XMLValidator.validate(xmlContent);
1119
+ if (wellFormed !== true) {
1120
+ const { msg, line, col } = wellFormed.err;
1121
+ const where = col !== void 0 ? `line ${line}, column ${col}` : `line ${line}`;
1122
+ throw new ReviewXmlError("parse-failed", `Invalid XML: ${msg} (${where})`);
1123
+ }
1124
+ let result;
888
1125
  try {
889
- const result = parser.parse(xmlContent);
890
- if (!result.review) {
891
- throw new Error("Invalid XML: missing <review> root element");
892
- }
893
- const review = result.review;
894
- const gitDiffArgs = review["@_git-diff-args"] || "";
895
- const source = parseSource(review);
896
- const comments = [];
897
- const viewedFiles = [];
898
- const files = toChildArray(review.file);
899
- for (const file of files) {
900
- const rawPath = file["@_path"];
901
- if (rawPath === void 0 || rawPath === null) continue;
902
- const filePath = String(rawPath);
903
- if (parseViewed(file["@_viewed"])) {
904
- viewedFiles.push(filePath);
905
- }
906
- const fileComments = toChildArray(file.comment);
907
- for (const comment of fileComments) {
908
- const reviewComment = {
909
- id: generateId(),
910
- filePath,
911
- lineRange: parseLineRange(comment),
912
- body: comment.body !== void 0 ? String(comment.body) : "",
913
- category: comment.category !== void 0 ? String(comment.category) : "",
914
- suggestion: parseSuggestion(comment),
915
- author: comment["@_author"] ? String(comment["@_author"]) : void 0,
916
- severity: parseEnumAttribute(comment["@_severity"], SEVERITY_VALUES),
917
- confidence: parseEnumAttribute(comment["@_confidence"], CONFIDENCE_VALUES),
918
- remoteId: parseStringAttribute(comment["@_remote-id"])
919
- };
920
- const attachments = parseAttachments(comment, reviewComment.id);
921
- if (attachments) reviewComment.attachments = attachments;
922
- const replies = parseReplies(comment);
923
- if (replies) reviewComment.replies = replies;
924
- comments.push(reviewComment);
925
- }
1126
+ result = parser.parse(xmlContent);
1127
+ } catch (error) {
1128
+ throw new ReviewXmlError("parse-failed", `Invalid XML: ${messageOf(error)}`, { cause: error });
1129
+ }
1130
+ const review = result.review;
1131
+ if (!review || typeof review !== "object") {
1132
+ throw new ReviewXmlError("missing-root", "Invalid XML: missing <review> root element");
1133
+ }
1134
+ const gitDiffArgs = attribute(review, "@_git-diff-args") ?? "";
1135
+ const source = parseSource(review);
1136
+ const comments = [];
1137
+ const viewedFiles = [];
1138
+ const importDiagnostics = [];
1139
+ for (const file of toChildArray(review.file)) {
1140
+ const filePath = attribute(file, "@_path");
1141
+ if (filePath === void 0) continue;
1142
+ if (parseViewed(file["@_viewed"])) {
1143
+ viewedFiles.push(filePath);
926
1144
  }
1145
+ toChildArray(file.comment).forEach((comment, index) => {
1146
+ comments.push(parseComment(comment, filePath, index + 1, importDiagnostics));
1147
+ });
1148
+ }
1149
+ const attachmentCount = countAttachments(comments);
1150
+ if (attachmentCount > MAX_RESUME_ATTACHMENTS) {
1151
+ throw new ReviewXmlError(
1152
+ "input-too-large",
1153
+ `The review document carries ${attachmentCount} attachments, over the limit of ${MAX_RESUME_ATTACHMENTS} for a review document`
1154
+ );
1155
+ }
1156
+ return {
1157
+ comments,
1158
+ viewedFiles,
1159
+ gitDiffArgs,
1160
+ source,
1161
+ importDiagnostics,
1162
+ remoteUrl: attribute(review, "@_remote-url"),
1163
+ remoteBaseSha: attribute(review, "@_remote-base-sha"),
1164
+ remoteHeadSha: attribute(review, "@_remote-head-sha"),
1165
+ remoteForge: parseEnumAttribute(review["@_remote-forge"], REMOTE_FORGE_VALUES)
1166
+ };
1167
+ }
1168
+ function parseComment(comment, filePath, ordinal, diagnostics) {
1169
+ const anchor = validateLineAnchor({
1170
+ oldLineStart: attribute(comment, "@_old-line-start"),
1171
+ oldLineEnd: attribute(comment, "@_old-line-end"),
1172
+ newLineStart: attribute(comment, "@_new-line-start"),
1173
+ newLineEnd: attribute(comment, "@_new-line-end")
1174
+ });
1175
+ const lineRange = anchor?.ok ? anchor.anchor : null;
1176
+ const suggestion = parseSuggestion(comment, lineRange);
1177
+ let body = text2(comment, "body") ?? "";
1178
+ let reason = null;
1179
+ if (anchor && !anchor.ok) {
1180
+ reason = anchor.reason;
1181
+ } else if (suggestion && !suggestion.ok) {
1182
+ reason = suggestion.reason;
1183
+ }
1184
+ if (reason !== null) {
1185
+ if (suggestion) body = foldSuggestionIntoBody(body, suggestion.text, reason);
1186
+ const remoteId = attribute(comment, "@_remote-id");
1187
+ const label = remoteId !== void 0 ? `comment ${ordinal} (remote-id ${remoteId})` : `comment ${ordinal}`;
1188
+ diagnostics.push(`${filePath}: ${label} anchor ${reason}; kept as file-level feedback`);
1189
+ }
1190
+ const reviewComment = {
1191
+ id: generateId(),
1192
+ filePath,
1193
+ lineRange,
1194
+ body,
1195
+ category: text2(comment, "category") ?? "",
1196
+ suggestion: suggestion?.ok ? suggestion.suggestion : null,
1197
+ author: optionalAuthor(comment),
1198
+ severity: parseEnumAttribute(comment["@_severity"], SEVERITY_VALUES),
1199
+ confidence: parseEnumAttribute(comment["@_confidence"], CONFIDENCE_VALUES),
1200
+ remoteId: attribute(comment, "@_remote-id")
1201
+ };
1202
+ const attachments = parseAttachments(comment, reviewComment.id);
1203
+ if (attachments) reviewComment.attachments = attachments;
1204
+ const replies = parseReplies(comment);
1205
+ if (replies) reviewComment.replies = replies;
1206
+ return reviewComment;
1207
+ }
1208
+ function parseSuggestion(comment, lineRange) {
1209
+ const raw = comment.suggestion;
1210
+ if (raw === void 0 || raw === null) return null;
1211
+ const node = typeof raw === "object" ? raw : {};
1212
+ const original = text2(node, "original-code");
1213
+ const proposed = text2(node, "proposed-code");
1214
+ const text_ = { original, proposed };
1215
+ if ("original-code" in node && original === void 0) {
1216
+ return { ok: false, reason: "suggestion original-code is not plain text", text: text_ };
1217
+ }
1218
+ if ("proposed-code" in node && proposed === void 0) {
1219
+ return { ok: false, reason: "suggestion proposed-code is not plain text", text: text_ };
1220
+ }
1221
+ if (original === void 0 || proposed === void 0) {
927
1222
  return {
928
- comments,
929
- viewedFiles,
930
- gitDiffArgs,
931
- source,
932
- remoteUrl: parseStringAttribute(review["@_remote-url"]),
933
- remoteBaseSha: parseStringAttribute(review["@_remote-base-sha"]),
934
- remoteHeadSha: parseStringAttribute(review["@_remote-head-sha"]),
935
- remoteForge: parseEnumAttribute(review["@_remote-forge"], REMOTE_FORGE_VALUES)
1223
+ ok: false,
1224
+ reason: "suggestion is missing original-code or proposed-code",
1225
+ text: text_
936
1226
  };
937
- } catch (error) {
938
- if (error instanceof Error) {
939
- console.error(`Error parsing XML: ${error.message}`);
940
- } else {
941
- console.error("Error parsing XML: unknown error");
942
- }
943
- process.exit(1);
944
1227
  }
1228
+ if (lineRange === null) {
1229
+ return { ok: false, reason: "suggestion has no line anchor", text: text_ };
1230
+ }
1231
+ return { ok: true, suggestion: { originalCode: original, proposedCode: proposed }, text: text_ };
1232
+ }
1233
+ function foldSuggestionIntoBody(body, code, reason) {
1234
+ const parts = [body, "", `_Imported suggestion could not be anchored (${reason})._`];
1235
+ if (code.original !== void 0) parts.push("Original:", ...fenced(code.original));
1236
+ if (code.proposed !== void 0) parts.push("Proposed:", ...fenced(code.proposed));
1237
+ return parts.join("\n");
1238
+ }
1239
+ function fenced(code) {
1240
+ const longestRun = Math.max(0, ...(code.match(/`+/g) ?? []).map((run) => run.length));
1241
+ const fence = "`".repeat(Math.max(3, longestRun + 1));
1242
+ return [fence, code, fence];
945
1243
  }
946
1244
  function parseEnumAttribute(raw, allowed) {
947
1245
  if (raw === void 0 || raw === null) return void 0;
948
- const value = String(raw);
1246
+ const value = decodeXmlEntities(String(raw));
949
1247
  return allowed.includes(value) ? value : void 0;
950
1248
  }
951
- function parseStringAttribute(raw) {
952
- return raw === void 0 || raw === null ? void 0 : String(raw);
1249
+ function attribute(node, key) {
1250
+ const raw = node[key];
1251
+ if (raw === void 0 || raw === null) return void 0;
1252
+ return decodeXmlEntities(typeof raw === "string" ? raw : String(raw));
1253
+ }
1254
+ function text2(node, key) {
1255
+ const raw = node[key];
1256
+ if (typeof raw === "string") return decodeXmlEntities(raw);
1257
+ return void 0;
1258
+ }
1259
+ function optionalAuthor(node) {
1260
+ const author = attribute(node, "@_author");
1261
+ return author === void 0 || author === "" ? void 0 : author;
953
1262
  }
954
1263
  function parseViewed(raw) {
955
1264
  return raw === true || String(raw) === "true";
956
1265
  }
957
1266
  function parseSource(review) {
958
- const sourcePath = review["@_source-path"];
1267
+ const sourcePath = attribute(review, "@_source-path");
959
1268
  if (sourcePath) {
960
- return { type: "directory", sourcePath: String(sourcePath) };
1269
+ return { type: "directory", sourcePath };
961
1270
  }
962
- const gitDiffArgs = review["@_git-diff-args"];
963
- const repository = review["@_repository"];
1271
+ const gitDiffArgs = attribute(review, "@_git-diff-args");
1272
+ const repository = attribute(review, "@_repository");
964
1273
  if (gitDiffArgs !== void 0 || repository !== void 0) {
965
1274
  return {
966
1275
  type: "git",
967
- gitDiffArgs: String(gitDiffArgs || ""),
968
- repository: String(repository || "")
1276
+ gitDiffArgs: gitDiffArgs ?? "",
1277
+ repository: repository ?? ""
969
1278
  };
970
1279
  }
971
1280
  return { type: "welcome" };
972
1281
  }
973
- function parseLineRange(comment) {
974
- const hasOld = comment["@_old-line-start"] !== void 0 && comment["@_old-line-end"] !== void 0;
975
- const hasNew = comment["@_new-line-start"] !== void 0 && comment["@_new-line-end"] !== void 0;
976
- if (hasOld) {
977
- return {
978
- side: "old",
979
- start: parseInt(String(comment["@_old-line-start"]), 10),
980
- end: parseInt(String(comment["@_old-line-end"]), 10)
981
- };
982
- }
983
- if (hasNew) {
984
- return {
985
- side: "new",
986
- start: parseInt(String(comment["@_new-line-start"]), 10),
987
- end: parseInt(String(comment["@_new-line-end"]), 10)
988
- };
989
- }
990
- return null;
991
- }
992
- function parseSuggestion(comment) {
993
- if (!comment.suggestion) {
994
- return null;
995
- }
996
- const suggestion = comment.suggestion;
997
- return {
998
- originalCode: String(suggestion["original-code"] || ""),
999
- proposedCode: String(suggestion["proposed-code"] || "")
1000
- };
1001
- }
1002
1282
  function toChildArray(raw) {
1003
1283
  if (Array.isArray(raw)) return raw;
1004
1284
  if (raw === void 0 || raw === null) return [];
@@ -1009,8 +1289,8 @@ function parseAttachments(node, idPrefix) {
1009
1289
  if (raw.length === 0) return void 0;
1010
1290
  return raw.map((att, i) => ({
1011
1291
  id: `${idPrefix}-att-${i}`,
1012
- fileName: String(att["@_path"] || ""),
1013
- mediaType: String(att["@_media-type"] || "image/png")
1292
+ fileName: attribute(att, "@_path") ?? "",
1293
+ mediaType: attribute(att, "@_media-type") ?? "image/png"
1014
1294
  }));
1015
1295
  }
1016
1296
  function parseReplies(comment) {
@@ -1020,136 +1300,1269 @@ function parseReplies(comment) {
1020
1300
  const id = generateId();
1021
1301
  const reply = {
1022
1302
  id,
1023
- body: node.body !== void 0 ? String(node.body) : "",
1024
- author: node["@_author"] ? String(node["@_author"]) : void 0,
1025
- remoteId: parseStringAttribute(node["@_remote-id"])
1303
+ body: text2(node, "body") ?? "",
1304
+ author: optionalAuthor(node),
1305
+ remoteId: attribute(node, "@_remote-id")
1026
1306
  };
1027
1307
  const attachments = parseAttachments(node, id);
1028
1308
  if (attachments) reply.attachments = attachments;
1029
1309
  return reply;
1030
1310
  });
1031
1311
  }
1312
+ function countAttachments(comments) {
1313
+ let count = 0;
1314
+ for (const comment of comments) {
1315
+ count += comment.attachments?.length ?? 0;
1316
+ for (const reply of comment.replies ?? []) {
1317
+ count += reply.attachments?.length ?? 0;
1318
+ }
1319
+ }
1320
+ return count;
1321
+ }
1322
+ function messageOf(error) {
1323
+ if (error instanceof Error) return error.message;
1324
+ return typeof error === "string" ? error : JSON.stringify(error);
1325
+ }
1032
1326
  function generateId() {
1033
1327
  return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
1034
1328
  }
1035
1329
 
1036
- // src/guide-schema.ts
1037
- var GUIDE_XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
1038
- <xs:schema
1039
- xmlns:xs="http://www.w3.org/2001/XMLSchema"
1040
- xmlns:sg="urn:self-review-guide:v1"
1041
- targetNamespace="urn:self-review-guide:v1"
1042
- elementFormDefault="qualified"
1043
- >
1044
-
1045
- <!--
1046
- self-review guide XML Schema v1
1047
- ===============================
1048
- Defines the walkthrough guide sidecar for the self-review application.
1049
- This schema is designed to be both machine-validated and fed to an LLM
1050
- so it can author valid guide documents from the schema alone.
1051
-
1052
- Key concepts:
1053
- - A <guide> is a read-only orientation aid generated BEFORE a review
1054
- starts. It lives next to the review output file and is discovered by
1055
- convention; it is never written by the review UI.
1056
- - The optional <overview> is short Markdown prose shown before the
1057
- first file, orienting the reviewer to the change as a whole.
1058
- - Each <group> names a set of files that belong together (for example
1059
- "Core change", "Tests", "Generated/mechanical") and explains, in one
1060
- line, why they are grouped and where they sit in the reading order.
1061
- - Each <file> inside a group points at one diff file by its
1062
- repository-relative path and carries a one-line description of the
1063
- role that file plays in the change.
1064
-
1065
- Ordering:
1066
- - Document order IS the reading order. Groups are presented in the
1067
- order they appear, and files within a group are presented in the
1068
- order they appear. There are no explicit ordering attributes; to
1069
- reorder, reorder the elements.
1070
-
1071
- Presentation only, never suppression:
1072
- - This vocabulary labels and orders content; it cannot hide it. There
1073
- is deliberately no element or attribute that hides, collapses, or
1074
- marks a file as skippable, and none may be added to v1. Files in the
1075
- diff that no group mentions remain fully visible in an implicit
1076
- "Everything else" group; files mentioned here but absent from the
1077
- diff are silently ignored.
1078
-
1079
- Tolerance:
1080
- - A missing, stale, or invalid guide degrades the consumer to its
1081
- normal ungrouped view. A guide can therefore never block or fail a
1082
- review, but an invalid guide is silently useless, so authors should
1083
- validate against this schema before writing the file.
1084
- -->
1085
-
1086
- <!-- ===== Root element ===== -->
1087
-
1088
- <xs:element name="guide" type="sg:GuideType">
1089
- <xs:annotation>
1090
- <xs:documentation>
1091
- Root element of a self-review walkthrough guide sidecar. Contains
1092
- an optional overview followed by zero or more ordered groups.
1093
- </xs:documentation>
1094
- </xs:annotation>
1095
- </xs:element>
1330
+ // src/review-publisher.ts
1331
+ import * as path5 from "path";
1096
1332
 
1097
- <!-- ===== Complex types ===== -->
1333
+ // src/fs-utils.ts
1334
+ import { accessSync, constants as fsConstants } from "fs";
1335
+ import { dirname as dirname2 } from "path";
1336
+ function checkWritability(filePath) {
1337
+ try {
1338
+ const dir = dirname2(filePath);
1339
+ accessSync(dir, fsConstants.W_OK);
1340
+ return true;
1341
+ } catch {
1342
+ return false;
1343
+ }
1344
+ }
1098
1345
 
1099
- <xs:complexType name="GuideType">
1100
- <xs:annotation>
1101
- <xs:documentation>
1102
- The whole walkthrough guide. The optional metadata attributes
1103
- mirror the review schema's provenance attributes so a consumer can
1104
- sanity-check that the guide was generated for the diff it is being
1105
- shown next to; none of them are required and none affect
1106
- presentation.
1107
- </xs:documentation>
1108
- </xs:annotation>
1109
- <xs:sequence>
1110
- <xs:element name="overview" type="xs:string" minOccurs="0">
1111
- <xs:annotation>
1112
- <xs:documentation>
1113
- Review-level orientation prose shown before the first file.
1114
- Markdown formatting is allowed, including fenced code blocks;
1115
- a fenced code block labelled "mermaid" may be used for a
1116
- diagram of the change.
1117
- Keep it short: a few sentences saying what the change does and
1118
- where to start reading, not a restatement of every file.
1119
- </xs:documentation>
1120
- </xs:annotation>
1121
- </xs:element>
1122
- <xs:element name="group" type="sg:GroupType" minOccurs="0" maxOccurs="unbounded">
1123
- <xs:annotation>
1124
- <xs:documentation>
1125
- Ordered reading groups. The first group should hold the files
1126
- the reviewer must understand first (the core of the change);
1127
- later groups hold consequences, tests, and mechanical fallout.
1128
- </xs:documentation>
1129
- </xs:annotation>
1130
- </xs:element>
1131
- </xs:sequence>
1132
- <xs:attribute name="timestamp" type="xs:dateTime" use="optional">
1133
- <xs:annotation>
1134
- <xs:documentation>
1135
- ISO 8601 timestamp of when the guide was generated.
1136
- </xs:documentation>
1137
- </xs:annotation>
1138
- </xs:attribute>
1139
- <xs:attribute name="git-diff-args" type="xs:string" use="optional">
1140
- <xs:annotation>
1141
- <xs:documentation>
1142
- The git diff arguments the guide was generated against.
1143
- Example: "--staged", "main..feature-branch", "HEAD~3".
1144
- Present only when the guide describes a git diff.
1145
- </xs:documentation>
1146
- </xs:annotation>
1147
- </xs:attribute>
1148
- <xs:attribute name="repository" type="xs:string" use="optional">
1149
- <xs:annotation>
1150
- <xs:documentation>
1151
- Absolute path to the repository root the guide was generated in.
1152
- Present only when the guide describes a git diff.
1346
+ // src/safe-fs.ts
1347
+ import * as nodeFs from "fs";
1348
+ import { randomBytes } from "crypto";
1349
+ import * as path2 from "path";
1350
+ var SafeFsError = class extends Error {
1351
+ constructor(code, path10, message, cause) {
1352
+ super(message);
1353
+ this.name = "SafeFsError";
1354
+ this.code = code;
1355
+ this.path = path10;
1356
+ if (cause !== void 0) this.cause = cause;
1357
+ }
1358
+ };
1359
+ var nodeFsLayer = {
1360
+ openSync: (p, flags, mode) => nodeFs.openSync(p, flags, mode),
1361
+ writeSync: (fd, buffer) => nodeFs.writeSync(fd, buffer),
1362
+ fsyncSync: (fd) => nodeFs.fsyncSync(fd),
1363
+ fchmodSync: (fd, mode) => nodeFs.fchmodSync(fd, mode),
1364
+ fchownSync: (fd, uid, gid) => nodeFs.fchownSync(fd, uid, gid),
1365
+ closeSync: (fd) => nodeFs.closeSync(fd),
1366
+ renameSync: (from, to) => nodeFs.renameSync(from, to),
1367
+ unlinkSync: (p) => nodeFs.unlinkSync(p),
1368
+ lstatSync: (p) => nodeFs.lstatSync(p),
1369
+ fstatSync: (fd) => nodeFs.fstatSync(fd),
1370
+ readFileSync: (fd) => nodeFs.readFileSync(fd),
1371
+ mkdirSync: (p, mode) => {
1372
+ nodeFs.mkdirSync(p, { mode });
1373
+ },
1374
+ realpathSync: (p) => nodeFs.realpathSync(p)
1375
+ };
1376
+ var { O_WRONLY, O_CREAT, O_EXCL, O_NOFOLLOW, O_RDONLY } = nodeFs.constants;
1377
+ function snapshotIdentity(stats) {
1378
+ return {
1379
+ dev: stats.dev,
1380
+ ino: stats.ino,
1381
+ mode: stats.mode & 4095,
1382
+ nlink: stats.nlink,
1383
+ size: stats.size,
1384
+ mtimeMs: stats.mtimeMs,
1385
+ uid: stats.uid,
1386
+ gid: stats.gid
1387
+ };
1388
+ }
1389
+ function sameFile(a, b) {
1390
+ return a.dev === b.dev && a.ino === b.ino;
1391
+ }
1392
+ function sameStamp(a, b) {
1393
+ return a.size === b.size && a.mtimeMs === b.mtimeMs;
1394
+ }
1395
+ var ERRNO_CODES = /* @__PURE__ */ new Map([
1396
+ ["ENOENT", "not-found"],
1397
+ ["ENOTDIR", "not-found"],
1398
+ ["EISDIR", "output-is-directory"],
1399
+ ["EACCES", "permission-denied"],
1400
+ ["EPERM", "permission-denied"],
1401
+ ["EROFS", "permission-denied"],
1402
+ ["ENOSPC", "no-space"],
1403
+ ["EDQUOT", "no-space"],
1404
+ ["ELOOP", "unsafe-link"]
1405
+ ]);
1406
+ function classifyFsError(error) {
1407
+ return ERRNO_CODES.get(errnoOf(error) ?? "") ?? "io-error";
1408
+ }
1409
+ function errnoOf(error) {
1410
+ if (error && typeof error === "object" && "code" in error) {
1411
+ const code = error.code;
1412
+ return typeof code === "string" ? code : void 0;
1413
+ }
1414
+ return void 0;
1415
+ }
1416
+ function toSafeFsError(error, filePath, action) {
1417
+ if (error instanceof SafeFsError) return error;
1418
+ const reason = error instanceof Error ? error.message : String(error);
1419
+ return new SafeFsError(
1420
+ classifyFsError(error),
1421
+ filePath,
1422
+ `Cannot ${action} ${filePath}: ${reason}`,
1423
+ error
1424
+ );
1425
+ }
1426
+ function guarded(filePath, action, fn) {
1427
+ try {
1428
+ return fn();
1429
+ } catch (error) {
1430
+ throw toSafeFsError(error, filePath, action);
1431
+ }
1432
+ }
1433
+ function quietly(fn) {
1434
+ try {
1435
+ fn();
1436
+ } catch {
1437
+ }
1438
+ }
1439
+ function lstatOrNull(filePath, fs3 = nodeFsLayer) {
1440
+ try {
1441
+ return fs3.lstatSync(filePath);
1442
+ } catch (error) {
1443
+ if (errnoOf(error) === "ENOENT") return null;
1444
+ throw toSafeFsError(error, filePath, "inspect");
1445
+ }
1446
+ }
1447
+ function assertNoSymlinkAncestors(root, rel, fs3 = nodeFsLayer) {
1448
+ const normalized = path2.normalize(rel);
1449
+ if (path2.isAbsolute(normalized) || normalized === ".." || normalized.startsWith(`..${path2.sep}`)) {
1450
+ throw new SafeFsError(
1451
+ "unsupported-target",
1452
+ path2.join(root, rel),
1453
+ `Refusing ${rel}: it does not stay under ${root}`
1454
+ );
1455
+ }
1456
+ let current = root;
1457
+ for (const segment of path2.dirname(normalized).split(path2.sep)) {
1458
+ if (!segment || segment === ".") continue;
1459
+ current = path2.join(current, segment);
1460
+ const stats = lstatOrNull(current, fs3);
1461
+ if (stats === null) return;
1462
+ if (stats.isSymbolicLink()) {
1463
+ throw new SafeFsError(
1464
+ "unsafe-link",
1465
+ current,
1466
+ `Refusing to go through ${current}: it is a symbolic link`
1467
+ );
1468
+ }
1469
+ }
1470
+ }
1471
+ function openContainedFile(root, rel, fs3 = nodeFsLayer) {
1472
+ assertNoSymlinkAncestors(root, rel, fs3);
1473
+ const target = path2.join(root, rel);
1474
+ const fd = guarded(target, "open", () => fs3.openSync(target, READ_FLAGS | O_NOFOLLOW));
1475
+ try {
1476
+ const stats = fs3.fstatSync(fd);
1477
+ if (stats.isDirectory()) {
1478
+ throw new SafeFsError("output-is-directory", target, `${target} is a directory`);
1479
+ }
1480
+ if (!stats.isFile()) {
1481
+ throw new SafeFsError("not-regular", target, `${target} is not a regular file`);
1482
+ }
1483
+ if (!sameFile(fs3.lstatSync(target), stats) || fs3.realpathSync(target) !== path2.join(fs3.realpathSync(root), rel)) {
1484
+ throw new SafeFsError("unsafe-link", target, `${target} changed while it was being opened`);
1485
+ }
1486
+ return { fd, stats };
1487
+ } catch (error) {
1488
+ quietly(() => fs3.closeSync(fd));
1489
+ throw toSafeFsError(error, target, "open");
1490
+ }
1491
+ }
1492
+ async function readContainedFile(root, rel, maxBytes) {
1493
+ const { fd, stats } = openContainedFile(root, rel);
1494
+ const target = path2.join(root, rel);
1495
+ try {
1496
+ const read = await readDescriptorWithinBudget(fd, stats, maxBytes);
1497
+ if (read.kind === "ok") return read.content;
1498
+ throw new SafeFsError(
1499
+ "too-large",
1500
+ target,
1501
+ `The file is ${formatBytes(read.size)}, over the ${formatBytes(maxBytes)} limit`
1502
+ );
1503
+ } catch (error) {
1504
+ throw toSafeFsError(error, target, "read");
1505
+ } finally {
1506
+ nodeFs.closeSync(fd);
1507
+ }
1508
+ }
1509
+ function writeExclusiveNoFollow(filePath, bytes, options = {}) {
1510
+ const fs3 = options.fs ?? nodeFsLayer;
1511
+ let fd;
1512
+ try {
1513
+ fd = fs3.openSync(filePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, options.mode ?? 438);
1514
+ } catch (error) {
1515
+ if (errnoOf(error) === "EEXIST" && isSymlink(filePath, fs3)) {
1516
+ throw new SafeFsError(
1517
+ "unsafe-link",
1518
+ filePath,
1519
+ `Refusing to write ${filePath}: a symbolic link already sits at that name`
1520
+ );
1521
+ }
1522
+ throw toSafeFsError(error, filePath, "create");
1523
+ }
1524
+ try {
1525
+ let offset = 0;
1526
+ while (offset < bytes.length) {
1527
+ const written = fs3.writeSync(fd, bytes.subarray(offset));
1528
+ if (written <= 0) {
1529
+ throw new SafeFsError(
1530
+ "io-error",
1531
+ filePath,
1532
+ `Cannot write ${filePath}: write made no progress`
1533
+ );
1534
+ }
1535
+ offset += written;
1536
+ }
1537
+ if (options.exactMode !== void 0) fs3.fchmodSync(fd, options.exactMode);
1538
+ if (options.exactOwner !== void 0) {
1539
+ const { uid, gid } = options.exactOwner;
1540
+ try {
1541
+ fs3.fchownSync(fd, uid, gid);
1542
+ } catch (error) {
1543
+ throw new SafeFsError(
1544
+ "unsupported-target",
1545
+ filePath,
1546
+ `Cannot give ${filePath} its owner (uid ${uid}, gid ${gid})`,
1547
+ error
1548
+ );
1549
+ }
1550
+ }
1551
+ fs3.fsyncSync(fd);
1552
+ const identity = snapshotIdentity(fs3.fstatSync(fd));
1553
+ fs3.closeSync(fd);
1554
+ return identity;
1555
+ } catch (error) {
1556
+ quietly(() => fs3.closeSync(fd));
1557
+ unlinkQuietly(filePath, fs3);
1558
+ throw toSafeFsError(error, filePath, "write");
1559
+ }
1560
+ }
1561
+ function atomicReplace(target, bytes, options = {}) {
1562
+ const fs3 = options.fs ?? nodeFsLayer;
1563
+ const existing = inspectReplaceTarget(target, fs3);
1564
+ const expected = options.expectedIdentity;
1565
+ if (expected && (!existing || !sameFile(existing, expected))) {
1566
+ throw new SafeFsError(
1567
+ "identity-changed",
1568
+ target,
1569
+ `Refusing to replace ${target}: it is no longer the file that was checked`
1570
+ );
1571
+ }
1572
+ if (expected && options.expectUnmodified && existing && !sameStamp(existing, expected)) {
1573
+ throw new SafeFsError(
1574
+ "identity-changed",
1575
+ target,
1576
+ `Refusing to replace ${target}: it was modified after it was checked`
1577
+ );
1578
+ }
1579
+ const exactOwner = options.preserveOwner && existing ? ownerToRestore(target, existing) : void 0;
1580
+ const random = options.randomName ?? defaultRandomName;
1581
+ const temp = path2.join(path2.dirname(target), `.${path2.basename(target)}.${random()}.tmp`);
1582
+ try {
1583
+ writeExclusiveNoFollow(temp, bytes, {
1584
+ fs: fs3,
1585
+ exactMode: options.preserveMode && existing ? existing.mode : void 0,
1586
+ exactOwner
1587
+ });
1588
+ } catch (error) {
1589
+ if (error instanceof SafeFsError && error.code === "unsupported-target") {
1590
+ throw new SafeFsError(
1591
+ "unsupported-target",
1592
+ target,
1593
+ `Refusing to replace ${target}: its owner could not be preserved on the replacement`,
1594
+ error.cause
1595
+ );
1596
+ }
1597
+ if (error instanceof SafeFsError && error.code !== "unsafe-link" && error.cause !== void 0) {
1598
+ throw toSafeFsError(error.cause, target, "write");
1599
+ }
1600
+ throw error;
1601
+ }
1602
+ return { identity: finishReplace(temp, target, fs3), replaced: existing !== null };
1603
+ }
1604
+ function ownerToRestore(target, existing) {
1605
+ if (typeof process.geteuid !== "function" || typeof process.getegid !== "function")
1606
+ return void 0;
1607
+ const me = { uid: process.geteuid(), gid: process.getegid() };
1608
+ if (existing.uid === me.uid && existing.gid === me.gid) return void 0;
1609
+ if (existing.uid !== me.uid && me.uid !== 0) {
1610
+ throw new SafeFsError(
1611
+ "unsupported-target",
1612
+ target,
1613
+ `Refusing to replace ${target}: it is owned by another user (uid ${existing.uid}), and replacing it would change its owner`
1614
+ );
1615
+ }
1616
+ return { uid: existing.uid, gid: existing.gid };
1617
+ }
1618
+ function finishReplace(temp, target, fs3) {
1619
+ try {
1620
+ fs3.renameSync(temp, target);
1621
+ } catch (error) {
1622
+ unlinkQuietly(temp, fs3);
1623
+ throw toSafeFsError(error, target, "replace");
1624
+ }
1625
+ syncDirectoryQuietly(path2.dirname(target), fs3);
1626
+ return guarded(target, "inspect", () => snapshotIdentity(fs3.lstatSync(target)));
1627
+ }
1628
+ function inspectReplaceTarget(target, fs3 = nodeFsLayer) {
1629
+ const stats = lstatOrNull(target, fs3);
1630
+ if (stats === null) return null;
1631
+ if (stats.isSymbolicLink()) {
1632
+ throw new SafeFsError(
1633
+ "unsafe-link",
1634
+ target,
1635
+ `Refusing to write ${target}: it is a symbolic link, and this program does not follow links when saving`
1636
+ );
1637
+ }
1638
+ if (stats.isDirectory()) {
1639
+ throw new SafeFsError(
1640
+ "output-is-directory",
1641
+ target,
1642
+ `Cannot write ${target}: it is a directory`
1643
+ );
1644
+ }
1645
+ if (!stats.isFile()) {
1646
+ throw new SafeFsError(
1647
+ "unsupported-target",
1648
+ target,
1649
+ `Cannot write ${target}: it exists but is not a regular file`
1650
+ );
1651
+ }
1652
+ if (stats.nlink > 1) {
1653
+ throw new SafeFsError(
1654
+ "unsupported-target",
1655
+ target,
1656
+ `Refusing to replace ${target}: it has ${stats.nlink} hard links, and replacing it would silently detach the others`
1657
+ );
1658
+ }
1659
+ return snapshotIdentity(stats);
1660
+ }
1661
+ function defaultRandomName() {
1662
+ return randomBytes(6).toString("hex");
1663
+ }
1664
+ function isSymlink(filePath, fs3) {
1665
+ try {
1666
+ return fs3.lstatSync(filePath).isSymbolicLink();
1667
+ } catch {
1668
+ return false;
1669
+ }
1670
+ }
1671
+ function unlinkQuietly(filePath, fs3 = nodeFsLayer) {
1672
+ quietly(() => fs3.unlinkSync(filePath));
1673
+ }
1674
+ function syncDirectoryQuietly(dir, fs3) {
1675
+ quietly(() => {
1676
+ const fd = fs3.openSync(dir, O_RDONLY);
1677
+ try {
1678
+ fs3.fsyncSync(fd);
1679
+ } finally {
1680
+ quietly(() => fs3.closeSync(fd));
1681
+ }
1682
+ });
1683
+ }
1684
+
1685
+ // src/attachment-origins.ts
1686
+ import * as path4 from "path";
1687
+
1688
+ // src/source-identity.ts
1689
+ import { execFile } from "child_process";
1690
+ import { realpathSync as realpathSync2 } from "fs";
1691
+ import * as path3 from "path";
1692
+ import { promisify } from "util";
1693
+
1694
+ // src/git-diff-args.ts
1695
+ import { existsSync } from "fs";
1696
+ import { resolve as resolve2 } from "path";
1697
+ var OPTIONS_WITH_SEPARATE_VALUES = /* @__PURE__ */ new Set([
1698
+ "--output",
1699
+ "--src-prefix",
1700
+ "--dst-prefix",
1701
+ "--line-prefix",
1702
+ "--output-indicator-new",
1703
+ "--output-indicator-old",
1704
+ "--output-indicator-context",
1705
+ "--inter-hunk-context",
1706
+ "--stat-width",
1707
+ "--stat-name-width",
1708
+ "--stat-graph-width",
1709
+ "--stat-count",
1710
+ "--diff-algorithm",
1711
+ "--word-diff-regex",
1712
+ "--ignore-matching-lines",
1713
+ "--anchored",
1714
+ "--diff-filter",
1715
+ "--find-object",
1716
+ "--rotate-to",
1717
+ "--skip-to",
1718
+ "--ws-error-highlight",
1719
+ "--color-moved-ws"
1720
+ ]);
1721
+ var SHORT_OPTIONS_WITH_REQUIRED_VALUES = "SGOIl";
1722
+ var SHORT_OPTIONS_WITH_OPTIONAL_VALUES = "UBMC";
1723
+ function consumesNextArgument(arg) {
1724
+ if (arg.startsWith("--")) return OPTIONS_WITH_SEPARATE_VALUES.has(arg);
1725
+ if (!arg.startsWith("-")) return false;
1726
+ for (let i = 1; i < arg.length; i++) {
1727
+ if (SHORT_OPTIONS_WITH_REQUIRED_VALUES.includes(arg[i])) return i === arg.length - 1;
1728
+ if (SHORT_OPTIONS_WITH_OPTIONAL_VALUES.includes(arg[i])) return false;
1729
+ }
1730
+ return false;
1731
+ }
1732
+ var CONTEXT_OPTIONS = /* @__PURE__ */ new Set(["--unified", "--function-context", "--no-function-context"]);
1733
+ var FILE_ORDER_OPTIONS = /* @__PURE__ */ new Set(["--rotate-to", "--skip-to"]);
1734
+ function isDroppedLongOption(arg) {
1735
+ const name = arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg;
1736
+ return CONTEXT_OPTIONS.has(name) || FILE_ORDER_OPTIONS.has(name);
1737
+ }
1738
+ function withoutDroppedShortOptions(arg) {
1739
+ let kept = "";
1740
+ for (let i = 1; i < arg.length; i++) {
1741
+ const option = arg[i];
1742
+ if (option === "U" || option === "O") break;
1743
+ if (option === "W") continue;
1744
+ if (SHORT_OPTIONS_WITH_REQUIRED_VALUES.includes(option) || SHORT_OPTIONS_WITH_OPTIONAL_VALUES.includes(option)) {
1745
+ kept += arg.slice(i);
1746
+ break;
1747
+ }
1748
+ kept += option;
1749
+ }
1750
+ return kept === "" ? null : `-${kept}`;
1751
+ }
1752
+ function describeDiffPathRelativity(args) {
1753
+ let relative4 = { kind: "root" };
1754
+ for (let i = 0; i < args.length; i++) {
1755
+ const arg = args[i];
1756
+ if (arg === "--") break;
1757
+ if (arg === "--relative") relative4 = { kind: "cwd" };
1758
+ else if (arg.startsWith("--relative="))
1759
+ relative4 = { kind: "directory", directory: arg.slice("--relative=".length) };
1760
+ else if (arg === "--no-relative") relative4 = { kind: "root" };
1761
+ else if (consumesNextArgument(arg)) i++;
1762
+ }
1763
+ return relative4;
1764
+ }
1765
+ function singleFileRediffArgs(args) {
1766
+ const kept = [];
1767
+ for (let i = 0; i < args.length; i++) {
1768
+ const arg = args[i];
1769
+ if (arg === "--") break;
1770
+ if (arg === "--relative" || arg.startsWith("--relative=") || arg === "--no-relative") {
1771
+ continue;
1772
+ }
1773
+ const takesNext = consumesNextArgument(arg) && i + 1 < args.length;
1774
+ let option = arg;
1775
+ let keepValue = true;
1776
+ if (arg.startsWith("--")) {
1777
+ if (isDroppedLongOption(arg)) option = null;
1778
+ keepValue = option !== null;
1779
+ } else if (arg.startsWith("-") && arg.length > 1) {
1780
+ option = withoutDroppedShortOptions(arg);
1781
+ keepValue = !arg.endsWith("O");
1782
+ }
1783
+ if (option !== null) kept.push(option);
1784
+ if (takesNext) {
1785
+ i++;
1786
+ if (keepValue) kept.push(args[i]);
1787
+ }
1788
+ }
1789
+ return { args: kept, relative: describeDiffPathRelativity(args) };
1790
+ }
1791
+ var WRITE_CAPABLE_OPTIONS = /* @__PURE__ */ new Set(["--output", "--ext-diff", "--textconv"]);
1792
+ function findWriteCapableGitDiffOptions(args) {
1793
+ const offending = [];
1794
+ for (let i = 0; i < args.length; i++) {
1795
+ const arg = args[i];
1796
+ if (arg === "--") break;
1797
+ const name = arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg;
1798
+ if (WRITE_CAPABLE_OPTIONS.has(name)) offending.push(arg);
1799
+ if (consumesNextArgument(arg)) i++;
1800
+ }
1801
+ return offending;
1802
+ }
1803
+ var UNSUPPORTED_OUTPUT_OPTIONS = /* @__PURE__ */ new Set([
1804
+ "--stat",
1805
+ "--numstat",
1806
+ "--shortstat",
1807
+ "--dirstat",
1808
+ "--dirstat-by-file",
1809
+ "--cumulative",
1810
+ "--summary",
1811
+ "--name-only",
1812
+ "--name-status",
1813
+ "--raw",
1814
+ "--patch-with-stat",
1815
+ "--patch-with-raw",
1816
+ "--compact-summary",
1817
+ "--word-diff",
1818
+ "--word-diff-regex",
1819
+ "--color-words",
1820
+ "--color-moved",
1821
+ "--color-moved-ws",
1822
+ "--no-patch",
1823
+ "-s",
1824
+ "--exit-code",
1825
+ "--quiet",
1826
+ "--output",
1827
+ "--line-prefix",
1828
+ "--output-indicator-new",
1829
+ "--output-indicator-old",
1830
+ "--output-indicator-context",
1831
+ "--check"
1832
+ ]);
1833
+ var UNSUPPORTED_OUTPUT_OPTION_PREFIXES = [
1834
+ "--stat=",
1835
+ "--stat-width=",
1836
+ "--stat-name-width=",
1837
+ "--stat-graph-width=",
1838
+ "--stat-count=",
1839
+ "--dirstat=",
1840
+ "--dirstat-by-file=",
1841
+ "--word-diff=",
1842
+ "--word-diff-regex=",
1843
+ "--color-words=",
1844
+ "--color-moved=",
1845
+ "--color-moved-ws=",
1846
+ "--output=",
1847
+ "--line-prefix=",
1848
+ "--output-indicator-new=",
1849
+ "--output-indicator-old=",
1850
+ "--output-indicator-context="
1851
+ ];
1852
+ function isUnsupportedOutputOption(arg) {
1853
+ return UNSUPPORTED_OUTPUT_OPTIONS.has(arg) || UNSUPPORTED_OUTPUT_OPTION_PREFIXES.some((prefix) => arg.startsWith(prefix));
1854
+ }
1855
+ function findUnsupportedGitDiffOptions(args) {
1856
+ const offending = [];
1857
+ for (let i = 0; i < args.length; i++) {
1858
+ const arg = args[i];
1859
+ if (arg === "--") break;
1860
+ if (isUnsupportedOutputOption(arg)) {
1861
+ offending.push(arg);
1862
+ }
1863
+ if (consumesNextArgument(arg)) i++;
1864
+ }
1865
+ return offending;
1866
+ }
1867
+ function classifyGitDiffArgs(args) {
1868
+ const positionalIndices = [];
1869
+ let hasSeparator = false;
1870
+ for (let i = 0; i < args.length; i++) {
1871
+ const arg = args[i];
1872
+ if (!hasSeparator) {
1873
+ if (arg === "--") {
1874
+ hasSeparator = true;
1875
+ continue;
1876
+ }
1877
+ if (consumesNextArgument(arg)) {
1878
+ i++;
1879
+ continue;
1880
+ }
1881
+ if (arg.startsWith("-")) continue;
1882
+ }
1883
+ positionalIndices.push(i);
1884
+ }
1885
+ return { positionalIndices, hasSeparator };
1886
+ }
1887
+ function normalizeGitDiffArgs(args, cwd = process.cwd()) {
1888
+ const { positionalIndices, hasSeparator } = classifyGitDiffArgs(args);
1889
+ if (hasSeparator) return args;
1890
+ for (const i of positionalIndices) {
1891
+ const arg = args[i];
1892
+ if (existsSync(resolve2(cwd, arg))) {
1893
+ return [...args.slice(0, i), "--", ...args.slice(i)];
1894
+ }
1895
+ }
1896
+ return args;
1897
+ }
1898
+ function tokenizeGitDiffArgs(value) {
1899
+ const args = [];
1900
+ let current = "";
1901
+ let started = false;
1902
+ let quote = null;
1903
+ for (let i = 0; i < value.length; i++) {
1904
+ const char = value[i];
1905
+ if (quote === "'") {
1906
+ if (char === "'") quote = null;
1907
+ else current += char;
1908
+ continue;
1909
+ }
1910
+ if (quote === '"') {
1911
+ if (char === "\\" && (value[i + 1] === '"' || value[i + 1] === "\\")) {
1912
+ current += value[++i];
1913
+ } else if (char === '"') {
1914
+ quote = null;
1915
+ } else {
1916
+ current += char;
1917
+ }
1918
+ continue;
1919
+ }
1920
+ if (char === "'" || char === '"') {
1921
+ quote = char;
1922
+ started = true;
1923
+ continue;
1924
+ }
1925
+ if (char === "\\" && i + 1 < value.length) {
1926
+ current += value[++i];
1927
+ started = true;
1928
+ continue;
1929
+ }
1930
+ if (/\s/.test(char)) {
1931
+ if (started) {
1932
+ args.push(current);
1933
+ current = "";
1934
+ started = false;
1935
+ }
1936
+ continue;
1937
+ }
1938
+ current += char;
1939
+ started = true;
1940
+ }
1941
+ if (started) args.push(current);
1942
+ return args;
1943
+ }
1944
+ function needsQuoting(arg) {
1945
+ return arg.length === 0 || /[\s'"\\]/.test(arg);
1946
+ }
1947
+ function formatGitDiffArgs(args) {
1948
+ return args.map((arg) => needsQuoting(arg) ? `'${arg.replace(/'/g, "'\\''")}'` : arg).join(" ");
1949
+ }
1950
+
1951
+ // src/source-identity.ts
1952
+ var execFileAsync = promisify(execFile);
1953
+ var WORKING_TREE = { kind: "working-tree" };
1954
+ var INDEX = { kind: "index" };
1955
+ var HEAD = { kind: "revision", rev: "HEAD", implicit: true };
1956
+ function revision(rev) {
1957
+ return rev === "" ? HEAD : { kind: "revision", rev, implicit: false };
1958
+ }
1959
+ function mergeBase(left, right) {
1960
+ return { kind: "merge-base", left: left || "HEAD", right: right || "HEAD" };
1961
+ }
1962
+ function unknownSides(reason) {
1963
+ return { oldSide: { kind: "unknown", reason }, newSide: { kind: "unknown", reason } };
1964
+ }
1965
+ function describeGitDiffSides(argv) {
1966
+ const separator = argv.indexOf("--");
1967
+ const end = separator === -1 ? argv.length : separator;
1968
+ const positional = new Set(
1969
+ classifyGitDiffArgs([...argv]).positionalIndices.filter((index) => index < end)
1970
+ );
1971
+ let cached = false;
1972
+ let reverse = false;
1973
+ let useMergeBase = false;
1974
+ const revs = [];
1975
+ for (let i = 0; i < end; i++) {
1976
+ const arg = argv[i];
1977
+ if (positional.has(i)) {
1978
+ revs.push(arg);
1979
+ continue;
1980
+ }
1981
+ if (consumesNextArgument(arg)) {
1982
+ i++;
1983
+ continue;
1984
+ }
1985
+ if (arg === "--cached" || arg === "--staged") cached = true;
1986
+ else if (arg === "-R") reverse = true;
1987
+ else if (arg === "--merge-base") useMergeBase = true;
1988
+ else if (arg === "--no-index") return unknownSides("--no-index compares paths, not snapshots");
1989
+ }
1990
+ const sides = describeRevisionSides(revs, cached, useMergeBase);
1991
+ return reverse ? { oldSide: sides.newSide, newSide: sides.oldSide } : sides;
1992
+ }
1993
+ function describeRevisionSides(revs, cached, useMergeBase) {
1994
+ if (revs.length === 0) {
1995
+ return cached ? { oldSide: HEAD, newSide: INDEX } : { oldSide: INDEX, newSide: WORKING_TREE };
1996
+ }
1997
+ if (revs.length === 1) {
1998
+ const rev = revs[0];
1999
+ const symmetric = rev.indexOf("...");
2000
+ if (symmetric !== -1) {
2001
+ if (cached) return unknownSides("--cached does not accept a revision range");
2002
+ const left = rev.slice(0, symmetric);
2003
+ const right = rev.slice(symmetric + 3);
2004
+ return { oldSide: mergeBase(left, right), newSide: revision(right) };
2005
+ }
2006
+ const range = rev.indexOf("..");
2007
+ if (range !== -1) {
2008
+ if (cached) return unknownSides("--cached does not accept a revision range");
2009
+ return { oldSide: revision(rev.slice(0, range)), newSide: revision(rev.slice(range + 2)) };
2010
+ }
2011
+ const oldSide = useMergeBase ? mergeBase(rev, "HEAD") : revision(rev);
2012
+ return { oldSide, newSide: cached ? INDEX : WORKING_TREE };
2013
+ }
2014
+ if (revs.length === 2) {
2015
+ if (cached) return unknownSides("--cached does not accept two revisions");
2016
+ const [left, right] = revs;
2017
+ return {
2018
+ oldSide: useMergeBase ? mergeBase(left, right) : revision(left),
2019
+ newSide: revision(right)
2020
+ };
2021
+ }
2022
+ return unknownSides(`a combined diff of ${revs.length} revisions has no single old side`);
2023
+ }
2024
+ async function gitOutput(repository, args) {
2025
+ try {
2026
+ const { stdout } = await execFileAsync("git", args, {
2027
+ cwd: repository,
2028
+ timeout: 1e4,
2029
+ maxBuffer: 1024 * 1024
2030
+ });
2031
+ return stdout.replace(/\r?\n$/, "");
2032
+ } catch {
2033
+ return null;
2034
+ }
2035
+ }
2036
+ var SHA_PATTERN = /^[0-9a-f]{40,64}$/;
2037
+ async function resolveCommit(repository, rev) {
2038
+ const sha = await gitOutput(repository, [
2039
+ "rev-parse",
2040
+ "--verify",
2041
+ "--quiet",
2042
+ "--end-of-options",
2043
+ `${rev}^{commit}`
2044
+ ]);
2045
+ return sha !== null && SHA_PATTERN.test(sha) ? sha : null;
2046
+ }
2047
+ async function resolveSide(repository, spec) {
2048
+ switch (spec.kind) {
2049
+ case "working-tree":
2050
+ case "index":
2051
+ case "unknown":
2052
+ return spec;
2053
+ case "revision": {
2054
+ const sha = await resolveCommit(repository, spec.rev);
2055
+ if (sha !== null) return { kind: "commit", sha };
2056
+ if (spec.implicit) return { kind: "none" };
2057
+ return { kind: "unknown", reason: `${spec.rev} does not name a commit` };
2058
+ }
2059
+ case "merge-base": {
2060
+ const sha = await gitOutput(repository, ["merge-base", spec.left, spec.right]);
2061
+ if (sha !== null && SHA_PATTERN.test(sha)) return { kind: "commit", sha };
2062
+ return {
2063
+ kind: "unknown",
2064
+ reason: `no merge base between ${spec.left} and ${spec.right}`
2065
+ };
2066
+ }
2067
+ }
2068
+ }
2069
+ function canonicalSourcePath(target) {
2070
+ try {
2071
+ return realpathSync2(target);
2072
+ } catch {
2073
+ return path3.resolve(target);
2074
+ }
2075
+ }
2076
+ function resolveReviewedPathPrefix(gitDiffArgv, sourceRoot, invocationCwd) {
2077
+ const relative4 = describeDiffPathRelativity(gitDiffArgv);
2078
+ switch (relative4.kind) {
2079
+ case "root":
2080
+ return "";
2081
+ case "directory":
2082
+ return relative4.directory.replace(/\/+$/, "");
2083
+ case "cwd": {
2084
+ const fromRoot = path3.relative(
2085
+ canonicalSourcePath(sourceRoot),
2086
+ canonicalSourcePath(invocationCwd)
2087
+ );
2088
+ if (fromRoot === "" || fromRoot.startsWith("..") || path3.isAbsolute(fromRoot)) return "";
2089
+ return fromRoot.split(path3.sep).join("/");
2090
+ }
2091
+ }
2092
+ }
2093
+ function rootRelativeReviewedPath(identity, filePath) {
2094
+ return identity.pathPrefix === "" ? filePath : `${identity.pathPrefix}/${filePath}`;
2095
+ }
2096
+ async function resolveGitSourceIdentity(options) {
2097
+ const sides = describeGitDiffSides(options.gitDiffArgv);
2098
+ const repository = options.repository;
2099
+ const [oldSide, newSide] = await Promise.all([
2100
+ resolveSide(repository, sides.oldSide),
2101
+ resolveSide(repository, sides.newSide)
2102
+ ]);
2103
+ const sourceRoot = canonicalSourcePath(repository);
2104
+ const invocationCwd = options.invocationCwd ?? process.cwd();
2105
+ return {
2106
+ mode: options.mode ?? "git",
2107
+ sourceRoot,
2108
+ invocationCwd,
2109
+ gitDiffArgv: [...options.gitDiffArgv],
2110
+ pathPrefix: resolveReviewedPathPrefix(options.gitDiffArgv, sourceRoot, invocationCwd),
2111
+ oldSide,
2112
+ newSide
2113
+ };
2114
+ }
2115
+ function resolveLocalSourceIdentity(options) {
2116
+ const invocationCwd = options.invocationCwd ?? process.cwd();
2117
+ if (options.type === "directory") {
2118
+ return {
2119
+ mode: "directory",
2120
+ sourceRoot: canonicalSourcePath(options.sourcePath),
2121
+ invocationCwd,
2122
+ gitDiffArgv: [],
2123
+ pathPrefix: "",
2124
+ oldSide: { kind: "none" },
2125
+ newSide: { kind: "directory" }
2126
+ };
2127
+ }
2128
+ return {
2129
+ mode: "file",
2130
+ sourceRoot: canonicalSourcePath(path3.dirname(options.sourcePath)),
2131
+ invocationCwd,
2132
+ gitDiffArgv: [],
2133
+ pathPrefix: "",
2134
+ oldSide: { kind: "none" },
2135
+ newSide: { kind: "file", path: canonicalSourcePath(options.sourcePath) }
2136
+ };
2137
+ }
2138
+
2139
+ // src/attachment-origins.ts
2140
+ function parseAttachmentReference(reference) {
2141
+ if (typeof reference !== "string") return null;
2142
+ const prefix = `${ASSET_DIR_NAME}/`;
2143
+ if (!reference.startsWith(prefix)) return null;
2144
+ const name = reference.slice(prefix.length);
2145
+ if (name === "" || name === "." || name === "..") return null;
2146
+ if (/[/\\\0]/.test(name)) return null;
2147
+ return name;
2148
+ }
2149
+ function* attachmentLists(comments) {
2150
+ for (const comment of comments) {
2151
+ if (comment.attachments) yield { comment, attachments: comment.attachments };
2152
+ for (const reply of comment.replies ?? []) {
2153
+ if (reply.attachments) yield { comment, attachments: reply.attachments };
2154
+ }
2155
+ }
2156
+ }
2157
+ function resolveAttachmentOrigins(comments, resumeDocumentPath) {
2158
+ const assetDir = path4.join(
2159
+ canonicalSourcePath(path4.dirname(path4.resolve(resumeDocumentPath))),
2160
+ ASSET_DIR_NAME
2161
+ );
2162
+ const origins = /* @__PURE__ */ new Map();
2163
+ const diagnostics = [];
2164
+ for (const { comment, attachments } of attachmentLists(comments)) {
2165
+ for (const attachment of attachments) {
2166
+ const name = parseAttachmentReference(attachment.fileName);
2167
+ if (name === null) {
2168
+ diagnostics.push(
2169
+ `${comment.filePath || "(review)"}: attachment "${attachment.fileName}" is not in the document's ${ASSET_DIR_NAME} directory; it will not be loaded`
2170
+ );
2171
+ continue;
2172
+ }
2173
+ origins.set(attachment.fileName, path4.join(assetDir, name));
2174
+ }
2175
+ }
2176
+ return { origins, diagnostics };
2177
+ }
2178
+ var READ_FAILURES = {
2179
+ "not-found": "not-found",
2180
+ "unsafe-link": "unsafe-link",
2181
+ "output-is-directory": "not-regular",
2182
+ "not-regular": "not-regular",
2183
+ "too-large": "too-large"
2184
+ };
2185
+ async function readAssetFile(assetPath) {
2186
+ const assetDir = path4.dirname(assetPath);
2187
+ const rel = path4.join(path4.basename(assetDir), path4.basename(assetPath));
2188
+ try {
2189
+ const content = await readContainedFile(path4.dirname(assetDir), rel, MAX_IMAGE_BYTES);
2190
+ const data = content.buffer.slice(content.byteOffset, content.byteOffset + content.byteLength);
2191
+ return { ok: true, data };
2192
+ } catch (error) {
2193
+ const fsError = toSafeFsError(error, assetPath, "read");
2194
+ return {
2195
+ ok: false,
2196
+ reason: READ_FAILURES[fsError.code] ?? "io-error",
2197
+ message: fsError.message
2198
+ };
2199
+ }
2200
+ }
2201
+ function authorizeAttachmentReference(reference, origins, currentAssetDir) {
2202
+ const name = parseAttachmentReference(reference);
2203
+ if (name === null) return null;
2204
+ const origin = origins.get(reference);
2205
+ if (origin !== void 0) return origin;
2206
+ return currentAssetDir ? path4.join(currentAssetDir, name) : null;
2207
+ }
2208
+ var AttachmentRelocationError = class extends Error {
2209
+ constructor(reference, origin, reason, detail) {
2210
+ super(
2211
+ `Attachment ${reference} from the resumed review could not be copied beside the new output: ${detail}. Save next to the resumed review, or remove that attachment, and save again.`
2212
+ );
2213
+ this.name = "AttachmentRelocationError";
2214
+ this.reference = reference;
2215
+ this.origin = origin;
2216
+ this.reason = reason;
2217
+ }
2218
+ };
2219
+ async function relocateAttachments(state, origins, outputPath) {
2220
+ if (origins.size === 0) return state;
2221
+ const targetAssetDir = path4.join(
2222
+ canonicalSourcePath(path4.dirname(path4.resolve(outputPath))),
2223
+ ASSET_DIR_NAME
2224
+ );
2225
+ const read = /* @__PURE__ */ new Map();
2226
+ const relocate = async (attachments) => {
2227
+ const result = [];
2228
+ for (const attachment of attachments) {
2229
+ const origin = attachment.data ? void 0 : origins.get(attachment.fileName);
2230
+ if (origin === void 0 || path4.dirname(origin) === targetAssetDir) {
2231
+ result.push(attachment);
2232
+ continue;
2233
+ }
2234
+ let data = read.get(origin);
2235
+ if (data === void 0) {
2236
+ const outcome = await readAssetFile(origin);
2237
+ if (!outcome.ok) {
2238
+ throw new AttachmentRelocationError(
2239
+ attachment.fileName,
2240
+ origin,
2241
+ outcome.reason,
2242
+ outcome.message
2243
+ );
2244
+ }
2245
+ data = outcome.data;
2246
+ read.set(origin, data);
2247
+ }
2248
+ result.push({ ...attachment, data });
2249
+ }
2250
+ return result;
2251
+ };
2252
+ const files = [];
2253
+ for (const file of state.files) {
2254
+ const comments = [];
2255
+ for (const comment of file.comments) {
2256
+ const next = { ...comment };
2257
+ if (comment.attachments) next.attachments = await relocate(comment.attachments);
2258
+ if (comment.replies) {
2259
+ next.replies = [];
2260
+ for (const reply of comment.replies) {
2261
+ next.replies.push(
2262
+ reply.attachments ? { ...reply, attachments: await relocate(reply.attachments) } : reply
2263
+ );
2264
+ }
2265
+ }
2266
+ comments.push(next);
2267
+ }
2268
+ files.push({ ...file, comments });
2269
+ }
2270
+ return { ...state, files };
2271
+ }
2272
+
2273
+ // src/review-publisher.ts
2274
+ var ReviewPublishError = class extends Error {
2275
+ constructor(code, path10, message, options = {}) {
2276
+ super(message);
2277
+ this.name = "ReviewPublishError";
2278
+ this.code = code;
2279
+ this.path = path10;
2280
+ this.details = options.details ?? [];
2281
+ if (options.cause !== void 0) this.cause = options.cause;
2282
+ }
2283
+ };
2284
+ async function publishReview(state, outputPath, options) {
2285
+ const fs3 = options.fs ?? nodeFsLayer;
2286
+ const randomName = options.randomName ?? defaultRandomName;
2287
+ const target = path5.resolve(outputPath);
2288
+ const outputDir = path5.dirname(target);
2289
+ const assetDir = path5.join(outputDir, ASSET_DIR_NAME);
2290
+ let xml;
2291
+ let assets;
2292
+ try {
2293
+ const publishable = options.attachmentOrigins ? await relocateAttachments(state, options.attachmentOrigins, target) : state;
2294
+ const namer = uniqueAssetNamer(assetDir, fs3, randomName);
2295
+ ({ xml, assets } = await serializeReview(publishable, target, { assetName: namer }));
2296
+ checkOutputPolicy(target, options, fs3);
2297
+ } catch (error) {
2298
+ throw toPublishError(error, target);
2299
+ }
2300
+ const staged = [];
2301
+ try {
2302
+ if (assets.length > 0) {
2303
+ ensureAssetDirectory(outputDir, fs3);
2304
+ for (const asset of assets) {
2305
+ writeExclusiveNoFollow(asset.absolutePath, new Uint8Array(asset.data), { fs: fs3 });
2306
+ staged.push(asset.absolutePath);
2307
+ }
2308
+ }
2309
+ atomicReplace(target, Buffer.from(xml + "\n", "utf-8"), {
2310
+ fs: fs3,
2311
+ preserveMode: true,
2312
+ randomName
2313
+ });
2314
+ } catch (error) {
2315
+ for (const file of staged) unlinkQuietly(file, fs3);
2316
+ throw toPublishError(error, target);
2317
+ }
2318
+ if (staged.length > 0) {
2319
+ console.error(`[main] Wrote ${staged.length} attachment file(s) to ${assetDir}`);
2320
+ }
2321
+ return { outputPath: target, assetPaths: staged };
2322
+ }
2323
+ function inspectOutputPath(outputPath, options) {
2324
+ const fs3 = options.fs ?? nodeFsLayer;
2325
+ const target = path5.resolve(outputPath);
2326
+ try {
2327
+ checkOutputPolicy(target, options, fs3);
2328
+ } catch (error) {
2329
+ return toPublishError(error, target);
2330
+ }
2331
+ if (!checkWritability(target)) {
2332
+ const dir = path5.dirname(target);
2333
+ return new ReviewPublishError(
2334
+ "permission-denied",
2335
+ target,
2336
+ `Cannot write ${target}: ${dir} does not exist or is not writable`
2337
+ );
2338
+ }
2339
+ return null;
2340
+ }
2341
+ function uniqueAssetNamer(assetDir, fs3, randomName) {
2342
+ const chosen = /* @__PURE__ */ new Set();
2343
+ return (idPrefix, _index, ext) => {
2344
+ for (let attempt = 0; attempt < 16; attempt++) {
2345
+ const name = `${idPrefix}-${randomName()}.${ext}`;
2346
+ if (chosen.has(name)) continue;
2347
+ const candidate = path5.join(assetDir, name);
2348
+ const stats = lstatOrNull(candidate, fs3);
2349
+ if (stats?.isSymbolicLink()) {
2350
+ throw new SafeFsError(
2351
+ "unsafe-link",
2352
+ candidate,
2353
+ `Refusing to write attachment ${candidate}: a symbolic link already sits at that name`
2354
+ );
2355
+ }
2356
+ if (stats === null) {
2357
+ chosen.add(name);
2358
+ return name;
2359
+ }
2360
+ }
2361
+ throw new SafeFsError(
2362
+ "io-error",
2363
+ assetDir,
2364
+ `Could not find a free attachment name under ${assetDir} after 16 attempts`
2365
+ );
2366
+ };
2367
+ }
2368
+ function checkOutputPolicy(target, options, fs3) {
2369
+ if (options.outputOrigin === "inherited") {
2370
+ const base = path5.resolve(options.baseDir);
2371
+ const outputDir = path5.dirname(target);
2372
+ const physicalBase = guarded(base, "resolve", () => fs3.realpathSync(base));
2373
+ const physicalDir = guarded(outputDir, "resolve", () => fs3.realpathSync(outputDir));
2374
+ const rel = path5.relative(physicalBase, physicalDir);
2375
+ if (rel.startsWith("..") || path5.isAbsolute(rel)) {
2376
+ throw new SafeFsError(
2377
+ "unsafe-link",
2378
+ target,
2379
+ `Refusing to write ${target}: the configured output directory resolves to ${physicalDir}, outside ${physicalBase}. Choose the output path explicitly to save there.`
2380
+ );
2381
+ }
2382
+ }
2383
+ inspectReplaceTarget(target, fs3);
2384
+ }
2385
+ function ensureAssetDirectory(outputDir, fs3) {
2386
+ const assetDir = path5.join(outputDir, ASSET_DIR_NAME);
2387
+ let stats = lstatOrNull(assetDir, fs3);
2388
+ if (stats === null) {
2389
+ guarded(assetDir, "create attachment directory", () => fs3.mkdirSync(assetDir, 493));
2390
+ stats = guarded(assetDir, "inspect", () => fs3.lstatSync(assetDir));
2391
+ }
2392
+ if (stats.isSymbolicLink()) {
2393
+ throw new SafeFsError(
2394
+ "unsafe-link",
2395
+ assetDir,
2396
+ `Refusing to write attachments through ${assetDir}: it is a symbolic link`
2397
+ );
2398
+ }
2399
+ if (!stats.isDirectory()) {
2400
+ throw new SafeFsError(
2401
+ "unsupported-target",
2402
+ assetDir,
2403
+ `Cannot write attachments: ${assetDir} exists but is not a directory`
2404
+ );
2405
+ }
2406
+ const uid = typeof process.getuid === "function" ? process.getuid() : void 0;
2407
+ if (uid !== void 0 && stats.uid !== uid) {
2408
+ throw new SafeFsError(
2409
+ "unsupported-target",
2410
+ assetDir,
2411
+ `Refusing to write attachments into ${assetDir}: it is owned by another user`
2412
+ );
2413
+ }
2414
+ }
2415
+ var SAFE_FS_TO_PUBLISH = {
2416
+ "output-is-directory": "output-is-directory",
2417
+ "permission-denied": "permission-denied",
2418
+ "no-space": "no-space",
2419
+ "unsafe-link": "unsafe-link",
2420
+ "unsupported-target": "unsupported-target"
2421
+ };
2422
+ function toPublishError(error, target) {
2423
+ if (error instanceof ReviewPublishError) return error;
2424
+ if (error instanceof AttachmentRelocationError) {
2425
+ return new ReviewPublishError("attachment-unavailable", error.origin, error.message, {
2426
+ details: [error.message],
2427
+ cause: error
2428
+ });
2429
+ }
2430
+ if (error instanceof XmlIllegalCharacterError) {
2431
+ return new ReviewPublishError("xml-illegal-character", target, error.message, {
2432
+ details: [error.message],
2433
+ cause: error
2434
+ });
2435
+ }
2436
+ if (error instanceof ReviewXmlError) {
2437
+ return new ReviewPublishError("validation-failed", target, error.message, {
2438
+ details: error.details,
2439
+ cause: error
2440
+ });
2441
+ }
2442
+ const fsError = toSafeFsError(error, target, "write");
2443
+ const code = SAFE_FS_TO_PUBLISH[fsError.code] ?? "io-error";
2444
+ return new ReviewPublishError(code, fsError.path, fsError.message, {
2445
+ cause: fsError.cause ?? fsError
2446
+ });
2447
+ }
2448
+
2449
+ // src/guide-schema.ts
2450
+ var GUIDE_XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
2451
+ <xs:schema
2452
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
2453
+ xmlns:sg="urn:self-review-guide:v1"
2454
+ targetNamespace="urn:self-review-guide:v1"
2455
+ elementFormDefault="qualified"
2456
+ >
2457
+
2458
+ <!--
2459
+ self-review guide XML Schema v1
2460
+ ===============================
2461
+ Defines the walkthrough guide sidecar for the self-review application.
2462
+ This schema is designed to be both machine-validated and fed to an LLM
2463
+ so it can author valid guide documents from the schema alone.
2464
+
2465
+ Key concepts:
2466
+ - A <guide> is a read-only orientation aid generated BEFORE a review
2467
+ starts. It lives next to the review output file and is discovered by
2468
+ convention; it is never written by the review UI.
2469
+ - The optional <overview> is short Markdown prose shown before the
2470
+ first file, orienting the reviewer to the change as a whole.
2471
+ - Each <group> names a set of files that belong together (for example
2472
+ "Core change", "Tests", "Generated/mechanical") and explains, in one
2473
+ line, why they are grouped and where they sit in the reading order.
2474
+ - Each <file> inside a group points at one diff file by its
2475
+ repository-relative path and carries a one-line description of the
2476
+ role that file plays in the change.
2477
+
2478
+ Ordering:
2479
+ - Document order IS the reading order. Groups are presented in the
2480
+ order they appear, and files within a group are presented in the
2481
+ order they appear. There are no explicit ordering attributes; to
2482
+ reorder, reorder the elements.
2483
+
2484
+ Presentation only, never suppression:
2485
+ - This vocabulary labels and orders content; it cannot hide it. There
2486
+ is deliberately no element or attribute that hides, collapses, or
2487
+ marks a file as skippable, and none may be added to v1. Files in the
2488
+ diff that no group mentions remain fully visible in an implicit
2489
+ "Everything else" group; files mentioned here but absent from the
2490
+ diff are silently ignored.
2491
+
2492
+ Tolerance:
2493
+ - A missing, stale, or invalid guide degrades the consumer to its
2494
+ normal ungrouped view. A guide can therefore never block or fail a
2495
+ review, but an invalid guide is silently useless, so authors should
2496
+ validate against this schema before writing the file.
2497
+ -->
2498
+
2499
+ <!-- ===== Root element ===== -->
2500
+
2501
+ <xs:element name="guide" type="sg:GuideType">
2502
+ <xs:annotation>
2503
+ <xs:documentation>
2504
+ Root element of a self-review walkthrough guide sidecar. Contains
2505
+ an optional overview followed by zero or more ordered groups.
2506
+ </xs:documentation>
2507
+ </xs:annotation>
2508
+ </xs:element>
2509
+
2510
+ <!-- ===== Complex types ===== -->
2511
+
2512
+ <xs:complexType name="GuideType">
2513
+ <xs:annotation>
2514
+ <xs:documentation>
2515
+ The whole walkthrough guide. The optional metadata attributes
2516
+ mirror the review schema's provenance attributes so a consumer can
2517
+ sanity-check that the guide was generated for the diff it is being
2518
+ shown next to; none of them are required and none affect
2519
+ presentation.
2520
+ </xs:documentation>
2521
+ </xs:annotation>
2522
+ <xs:sequence>
2523
+ <xs:element name="overview" type="xs:string" minOccurs="0">
2524
+ <xs:annotation>
2525
+ <xs:documentation>
2526
+ Review-level orientation prose shown before the first file.
2527
+ Markdown formatting is allowed, including fenced code blocks;
2528
+ a fenced code block labelled "mermaid" may be used for a
2529
+ diagram of the change.
2530
+ Keep it short: a few sentences saying what the change does and
2531
+ where to start reading, not a restatement of every file.
2532
+ </xs:documentation>
2533
+ </xs:annotation>
2534
+ </xs:element>
2535
+ <xs:element name="group" type="sg:GroupType" minOccurs="0" maxOccurs="unbounded">
2536
+ <xs:annotation>
2537
+ <xs:documentation>
2538
+ Ordered reading groups. The first group should hold the files
2539
+ the reviewer must understand first (the core of the change);
2540
+ later groups hold consequences, tests, and mechanical fallout.
2541
+ </xs:documentation>
2542
+ </xs:annotation>
2543
+ </xs:element>
2544
+ </xs:sequence>
2545
+ <xs:attribute name="timestamp" type="xs:dateTime" use="optional">
2546
+ <xs:annotation>
2547
+ <xs:documentation>
2548
+ ISO 8601 timestamp of when the guide was generated.
2549
+ </xs:documentation>
2550
+ </xs:annotation>
2551
+ </xs:attribute>
2552
+ <xs:attribute name="git-diff-args" type="xs:string" use="optional">
2553
+ <xs:annotation>
2554
+ <xs:documentation>
2555
+ The git diff arguments the guide was generated against.
2556
+ Example: "--staged", "main..feature-branch", "HEAD~3".
2557
+ Present only when the guide describes a git diff.
2558
+ </xs:documentation>
2559
+ </xs:annotation>
2560
+ </xs:attribute>
2561
+ <xs:attribute name="repository" type="xs:string" use="optional">
2562
+ <xs:annotation>
2563
+ <xs:documentation>
2564
+ Absolute path to the repository root the guide was generated in.
2565
+ Present only when the guide describes a git diff.
1153
2566
  </xs:documentation>
1154
2567
  </xs:annotation>
1155
2568
  </xs:attribute>
@@ -1314,18 +2727,32 @@ function reconcileGuide(guide, diffFilePaths) {
1314
2727
  });
1315
2728
  }
1316
2729
  }
1317
- const leftover = diffFilePaths.filter((path4) => !claimed.has(path4));
2730
+ const leftover = diffFilePaths.filter((path10) => !claimed.has(path10));
1318
2731
  if (leftover.length > 0) {
1319
2732
  resolved.push({
1320
2733
  name: IMPLICIT_GUIDE_GROUP_NAME,
1321
2734
  implicit: true,
1322
- files: leftover.map((path4) => ({ path: path4 }))
2735
+ files: leftover.map((path10) => ({ path: path10 }))
1323
2736
  });
1324
2737
  }
1325
2738
  return resolved;
1326
2739
  }
1327
2740
 
1328
2741
  // src/forge-provider.ts
2742
+ var CommandCancelledError = class extends Error {
2743
+ constructor(reason, command, args) {
2744
+ super(
2745
+ reason === "timeout" ? `${command} ${args.join(" ")} timed out and was killed` : `${command} ${args.join(" ")} was cancelled`
2746
+ );
2747
+ this.name = "CommandCancelledError";
2748
+ this.reason = reason;
2749
+ this.command = command;
2750
+ this.args = args;
2751
+ }
2752
+ };
2753
+ function isCommandCancelled(error) {
2754
+ return error instanceof CommandCancelledError || error instanceof Error && error.name === "CommandCancelledError";
2755
+ }
1329
2756
  var ForgeCliUnavailableError = class extends Error {
1330
2757
  constructor(forge, cli, message) {
1331
2758
  super(message);
@@ -1370,8 +2797,8 @@ function parseForgeUrl(url) {
1370
2797
  }
1371
2798
 
1372
2799
  // src/directory-scanner.ts
1373
- import { readdir, stat } from "fs/promises";
1374
- import { join as join2, relative, basename, dirname as dirname2 } from "path";
2800
+ import { opendir, stat } from "fs/promises";
2801
+ import { basename as basename3, dirname as dirname7, join as join5 } from "path";
1375
2802
 
1376
2803
  // src/ignore-filter.ts
1377
2804
  import ignore from "ignore";
@@ -1382,174 +2809,323 @@ function createIgnoreFilter(patterns) {
1382
2809
  }
1383
2810
 
1384
2811
  // src/directory-scanner.ts
1385
- async function scanDirectory(directoryPath, ignorePatterns = []) {
2812
+ async function scanDirectory(directoryPath, ignorePatterns = [], options = {}) {
2813
+ const budgets = resolveSourceBudgets(options.budgets);
1386
2814
  try {
1387
2815
  const dirStat = await stat(directoryPath);
1388
2816
  if (!dirStat.isDirectory()) {
1389
- console.error(`Error: "${directoryPath}" is not a directory`);
1390
- return [];
2817
+ return failed(`Cannot review "${directoryPath}": it is not a directory.`);
1391
2818
  }
1392
2819
  } catch (error) {
1393
- if (error instanceof Error) {
1394
- console.error(`Error accessing directory "${directoryPath}": ${error.message}`);
1395
- } else {
1396
- console.error(`Error accessing directory "${directoryPath}": unknown error`);
1397
- }
1398
- return [];
2820
+ return failed(`Cannot read directory "${directoryPath}": ${messageOf2(error)}`);
1399
2821
  }
1400
- const filePaths = [];
2822
+ const shouldKeep = createIgnoreFilter(ignorePatterns);
2823
+ let walk;
1401
2824
  try {
1402
- const entries = await readdir(directoryPath, {
1403
- recursive: true,
1404
- withFileTypes: true
1405
- });
1406
- for (const entry of entries) {
1407
- if (!entry.isFile()) {
1408
- continue;
1409
- }
1410
- const parentDir = entry.parentPath ?? entry.path;
1411
- const fullPath = join2(parentDir, entry.name);
1412
- const relativePath = relative(directoryPath, fullPath);
1413
- filePaths.push(relativePath);
1414
- }
2825
+ walk = await walkDirectory(directoryPath, shouldKeep, budgets.maxEntries);
1415
2826
  } catch (error) {
1416
- if (error instanceof Error) {
1417
- console.error(`Error reading directory "${directoryPath}": ${error.message}`);
1418
- } else {
1419
- console.error(`Error reading directory "${directoryPath}": unknown error`);
1420
- }
1421
- return [];
2827
+ return failed(`Cannot read directory "${directoryPath}": ${messageOf2(error)}`);
1422
2828
  }
1423
- filePaths.sort();
1424
- const shouldKeep = createIgnoreFilter(ignorePatterns);
1425
- const filteredPaths = filePaths.filter((p) => shouldKeep(p));
1426
- if (filteredPaths.length === 0) {
1427
- return [];
2829
+ if (walk.limitExceeded) {
2830
+ console.error(`[scan] Stopped scanning ${directoryPath} after ${budgets.maxEntries} entries`);
2831
+ return {
2832
+ files: [],
2833
+ diagnostics: [
2834
+ `"${directoryPath}" has more than ${budgets.maxEntries.toLocaleString("en-US")} entries outside ignored directories, so it was not loaded. Review a subdirectory, or add ignore patterns (the \`ignore\` config key) for build output and dependency folders.`
2835
+ ],
2836
+ entryLimitExceeded: true
2837
+ };
2838
+ }
2839
+ walk.files.sort();
2840
+ if (walk.files.length === 0) {
2841
+ return { files: [], diagnostics: [], entryLimitExceeded: false };
1428
2842
  }
1429
- const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);
1430
- return parseDiff(diffText);
2843
+ const { files, diagnostics } = loadSyntheticFiles(walk.files, directoryPath, {
2844
+ budgets: options.budgets
2845
+ });
2846
+ return { files, diagnostics, entryLimitExceeded: false };
1431
2847
  }
1432
- async function scanFile(filePath) {
2848
+ async function scanFile(filePath, options = {}) {
1433
2849
  try {
1434
2850
  const fileStat = await stat(filePath);
1435
2851
  if (!fileStat.isFile()) {
1436
- console.error(`Error: "${filePath}" is not a file`);
1437
- return [];
2852
+ return failed(`Cannot review "${filePath}": it is not a regular file.`);
1438
2853
  }
1439
2854
  } catch (error) {
1440
- if (error instanceof Error) {
1441
- console.error(`Error accessing file "${filePath}": ${error.message}`);
1442
- } else {
1443
- console.error(`Error accessing file "${filePath}": unknown error`);
2855
+ return failed(`Cannot read file "${filePath}": ${messageOf2(error)}`);
2856
+ }
2857
+ const { files, diagnostics } = loadSyntheticFiles([basename3(filePath)], dirname7(filePath), {
2858
+ followSymlinks: true,
2859
+ budgets: options.budgets
2860
+ });
2861
+ return { files, diagnostics, entryLimitExceeded: false };
2862
+ }
2863
+ async function walkDirectory(root, shouldKeep, maxEntries) {
2864
+ const files = [];
2865
+ const pending = [""];
2866
+ let examined = 0;
2867
+ while (pending.length > 0) {
2868
+ const relativeDir = pending.pop();
2869
+ const dir = await opendir(relativeDir === "" ? root : join5(root, relativeDir));
2870
+ try {
2871
+ for await (const entry of dir) {
2872
+ examined++;
2873
+ if (examined > maxEntries) return { files, limitExceeded: true };
2874
+ const relativePath = relativeDir === "" ? entry.name : `${relativeDir}/${entry.name}`;
2875
+ if (entry.isDirectory()) {
2876
+ if (shouldKeep(`${relativePath}/`)) pending.push(relativePath);
2877
+ } else if (entry.isFile()) {
2878
+ if (shouldKeep(relativePath)) files.push(relativePath);
2879
+ }
2880
+ }
2881
+ } finally {
2882
+ await dir.close().catch(() => {
2883
+ });
1444
2884
  }
1445
- return [];
1446
2885
  }
1447
- const fileName = basename(filePath);
1448
- const rootDir = dirname2(filePath);
1449
- const diffText = generateSyntheticDiffs([fileName], rootDir);
1450
- return parseDiff(diffText);
2886
+ return { files, limitExceeded: false };
2887
+ }
2888
+ function failed(message) {
2889
+ console.error(`[scan] ${message}`);
2890
+ return { files: [], diagnostics: [message], entryLimitExceeded: false };
2891
+ }
2892
+ function messageOf2(error) {
2893
+ return error instanceof Error ? error.message : String(error);
1451
2894
  }
1452
2895
 
1453
- // src/config.ts
1454
- import { readFileSync as readFileSync2, existsSync as existsSync2 } from "fs";
1455
- import { join as join3 } from "path";
1456
- import { homedir } from "os";
1457
- import { parse as parseYaml } from "yaml";
1458
- var defaults = {
1459
- theme: "system",
1460
- diffView: "split",
1461
- fontSize: 14,
1462
- outputFormat: "xml",
1463
- outputFile: "./review.xml",
1464
- ignore: [
1465
- ".git",
1466
- "node_modules",
1467
- "vendor",
1468
- ".vendor",
1469
- "__pycache__",
1470
- ".venv",
1471
- "venv",
1472
- ".env",
1473
- "dist",
1474
- "build",
1475
- ".next",
1476
- ".nuxt",
1477
- ".svelte-kit",
1478
- "target",
1479
- "*.min.js",
1480
- "*.min.css",
1481
- "package-lock.json",
1482
- "yarn.lock",
1483
- "pnpm-lock.yaml",
1484
- "composer.lock",
1485
- "Gemfile.lock",
1486
- "Cargo.lock",
1487
- "poetry.lock",
1488
- "go.sum"
1489
- ],
1490
- categories: [
1491
- {
1492
- name: "question",
1493
- description: "Clarification needed \u2014 not necessarily a problem",
1494
- color: "#805ad5"
1495
- },
1496
- {
1497
- name: "bug",
1498
- description: "Likely defect or incorrect behavior",
1499
- color: "#e53e3e"
1500
- },
1501
- {
1502
- name: "security",
1503
- description: "Security vulnerability or concern",
1504
- color: "#dd6b20"
1505
- },
1506
- {
1507
- name: "style",
1508
- description: "Code style, naming, or formatting issue",
1509
- color: "#3182ce"
1510
- },
1511
- {
1512
- name: "task",
1513
- description: "Action item or follow-up task",
1514
- color: "#38a169"
1515
- },
1516
- {
1517
- name: "nit",
1518
- description: "Minor nitpick, low priority",
1519
- color: "#718096"
2896
+ // src/snapshot-reader.ts
2897
+ import { execFile as execFile2 } from "child_process";
2898
+ import * as path6 from "path";
2899
+ function authorizeReviewedPath(source, filePath) {
2900
+ const identity = source.sourceIdentity;
2901
+ if (identity === null) {
2902
+ return { ok: false, reason: "no-source", message: "No review has been loaded." };
2903
+ }
2904
+ const invalid = {
2905
+ ok: false,
2906
+ reason: "invalid-path",
2907
+ message: "This path does not stay inside the reviewed source."
2908
+ };
2909
+ if (normalizeReviewedPath(filePath) === null) return invalid;
2910
+ if (!source.reviewedPaths.has(filePath)) {
2911
+ return {
2912
+ ok: false,
2913
+ reason: "not-reviewed",
2914
+ message: "This file is not part of the reviewed diff."
2915
+ };
2916
+ }
2917
+ const relativePath = normalizeReviewedPath(rootRelativeReviewedPath(identity, filePath));
2918
+ if (relativePath === null) return invalid;
2919
+ return { ok: true, relativePath, sourceRoot: identity.sourceRoot };
2920
+ }
2921
+ function normalizeReviewedPath(filePath) {
2922
+ if (filePath === "" || filePath.includes("\0") || path6.posix.isAbsolute(filePath)) return null;
2923
+ const normalized = path6.posix.normalize(filePath);
2924
+ if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
2925
+ if (normalized.split("/").includes("..")) return null;
2926
+ return normalized;
2927
+ }
2928
+ function failure(reason, message) {
2929
+ return { ok: false, reason, message };
2930
+ }
2931
+ async function readReviewedContent(source, filePath, side, options = {}) {
2932
+ const authorized = authorizeReviewedPath(source, filePath);
2933
+ if (!authorized.ok) return failure(authorized.reason, authorized.message);
2934
+ const identity = source.sourceIdentity;
2935
+ const descriptor = side === "old" ? identity.oldSide : identity.newSide;
2936
+ const maxBytes = options.maxBytes ?? MAX_SOURCE_FILE_BYTES;
2937
+ return readSide(descriptor, authorized.sourceRoot, authorized.relativePath, maxBytes);
2938
+ }
2939
+ async function readSide(descriptor, sourceRoot, relativePath, maxBytes) {
2940
+ switch (descriptor.kind) {
2941
+ case "working-tree":
2942
+ case "directory":
2943
+ return readPhysicalFile(sourceRoot, relativePath, maxBytes);
2944
+ case "file": {
2945
+ const fsRoot = path6.parse(descriptor.path).root;
2946
+ return readPhysicalFile(fsRoot, path6.relative(fsRoot, descriptor.path), maxBytes);
1520
2947
  }
1521
- ],
2948
+ case "index":
2949
+ return readGitBlob(sourceRoot, `:0:${relativePath}`, maxBytes);
2950
+ case "commit":
2951
+ return readGitBlob(sourceRoot, `${descriptor.sha}:${relativePath}`, maxBytes);
2952
+ case "none":
2953
+ return failure("side-unavailable", "This side of the review has no content.");
2954
+ case "unknown":
2955
+ return failure(
2956
+ "side-unavailable",
2957
+ `This side of the review could not be identified: ${descriptor.reason}.`
2958
+ );
2959
+ }
2960
+ }
2961
+ async function readPhysicalFile(root, relativePath, maxBytes) {
2962
+ try {
2963
+ return { ok: true, content: await readContainedFile(root, relativePath, maxBytes) };
2964
+ } catch (error) {
2965
+ const fsError = toSafeFsError(error, relativePath, "read");
2966
+ const [reason, message = fsError.message] = FS_FAILURES[fsError.code] ?? ["read-failed"];
2967
+ return failure(reason, message);
2968
+ }
2969
+ }
2970
+ var FS_FAILURES = {
2971
+ "not-found": ["not-found", "The file does not exist on this side of the review."],
2972
+ "unsafe-link": ["unsafe-link", "The path goes through a symbolic link."],
2973
+ "output-is-directory": ["not-regular", "The path is a directory."],
2974
+ "not-regular": ["not-regular", "The path is not a regular file."],
2975
+ "unsupported-target": ["invalid-path", "This path does not stay inside the reviewed source."],
2976
+ "too-large": ["too-large"]
2977
+ };
2978
+ function readGitBlob(root, spec, maxBytes) {
2979
+ return new Promise((resolve10) => {
2980
+ execFile2(
2981
+ "git",
2982
+ ["cat-file", "blob", spec],
2983
+ { cwd: root, encoding: "buffer", maxBuffer: maxBytes + 1, timeout: 3e4 },
2984
+ (error, stdout, stderr) => {
2985
+ if (error) {
2986
+ if (errnoOf(error) === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
2987
+ resolve10(failure("too-large", `The blob is over the ${maxBytes}-byte limit.`));
2988
+ return;
2989
+ }
2990
+ const detail = stderr.toString("utf-8").trim();
2991
+ if (/does not exist|not a valid object name|invalid object name|not a blob/i.test(detail)) {
2992
+ resolve10(failure("not-found", "The file does not exist on this side of the review."));
2993
+ return;
2994
+ }
2995
+ resolve10(failure("read-failed", `git cat-file failed: ${detail || error.message}`));
2996
+ return;
2997
+ }
2998
+ if (stdout.length > maxBytes) {
2999
+ resolve10(failure("too-large", `The blob is over the ${maxBytes}-byte limit.`));
3000
+ return;
3001
+ }
3002
+ resolve10({ ok: true, content: stdout });
3003
+ }
3004
+ );
3005
+ });
3006
+ }
3007
+
3008
+ // src/config.ts
3009
+ import { readFileSync as readFileSync2, existsSync as existsSync2 } from "fs";
3010
+ import { join as join6 } from "path";
3011
+ import { homedir } from "os";
3012
+ import { parse as parseYaml } from "yaml";
3013
+
3014
+ // ../react/src/config-defaults.ts
3015
+ var DEFAULT_CATEGORIES = [
3016
+ {
3017
+ name: "question",
3018
+ description: "Clarification needed \u2014 not necessarily a problem",
3019
+ color: "#805ad5"
3020
+ },
3021
+ {
3022
+ name: "bug",
3023
+ description: "Likely defect or incorrect behavior",
3024
+ color: "#e53e3e"
3025
+ },
3026
+ {
3027
+ name: "security",
3028
+ description: "Security vulnerability or concern",
3029
+ color: "#dd6b20"
3030
+ },
3031
+ {
3032
+ name: "style",
3033
+ description: "Code style, naming, or formatting issue",
3034
+ color: "#3182ce"
3035
+ },
3036
+ {
3037
+ name: "task",
3038
+ description: "Action item or follow-up task",
3039
+ color: "#38a169"
3040
+ },
3041
+ {
3042
+ name: "nit",
3043
+ description: "Minor nitpick, low priority",
3044
+ color: "#718096"
3045
+ }
3046
+ ];
3047
+ var DEFAULT_IGNORE_PATTERNS = [
3048
+ ".git",
3049
+ "node_modules",
3050
+ "vendor",
3051
+ ".vendor",
3052
+ "__pycache__",
3053
+ ".venv",
3054
+ "venv",
3055
+ ".env",
3056
+ "dist",
3057
+ "build",
3058
+ ".next",
3059
+ ".nuxt",
3060
+ ".svelte-kit",
3061
+ "target",
3062
+ "*.min.js",
3063
+ "*.min.css",
3064
+ "package-lock.json",
3065
+ "yarn.lock",
3066
+ "pnpm-lock.yaml",
3067
+ "composer.lock",
3068
+ "Gemfile.lock",
3069
+ "Cargo.lock",
3070
+ "poetry.lock",
3071
+ "go.sum"
3072
+ ];
3073
+ var DEFAULT_FONT_SIZE = 14;
3074
+ var DEFAULT_MAX_FILES = 500;
3075
+ var DEFAULT_MAX_TOTAL_LINES = 1e5;
3076
+ var DEFAULT_CONFIG = {
3077
+ theme: "system",
3078
+ diffView: "split",
3079
+ fontSize: DEFAULT_FONT_SIZE,
3080
+ outputFormat: "xml",
3081
+ outputFile: "./review.xml",
3082
+ ignore: [...DEFAULT_IGNORE_PATTERNS],
3083
+ categories: [...DEFAULT_CATEGORIES],
1522
3084
  defaultDiffArgs: "",
1523
3085
  showUntracked: true,
1524
3086
  showUntrackedExplicit: false,
1525
3087
  wordWrap: true,
1526
- maxFiles: 500,
1527
- maxTotalLines: 1e5
3088
+ maxFiles: DEFAULT_MAX_FILES,
3089
+ maxTotalLines: DEFAULT_MAX_TOTAL_LINES
1528
3090
  };
1529
- function loadConfig() {
3091
+
3092
+ // src/config.ts
3093
+ var defaults = DEFAULT_CONFIG;
3094
+ var CONFIG_KEYS = Object.keys(defaults);
3095
+ function loadConfigWithProvenance(options = {}) {
1530
3096
  let config = { ...defaults };
1531
- const userConfigPath = join3(homedir(), ".config", "self-review", "config.yaml");
1532
- if (existsSync2(userConfigPath)) {
1533
- try {
1534
- const userConfig = loadYamlConfig(userConfigPath);
1535
- config = mergeConfig(config, userConfig);
1536
- } catch (error) {
1537
- console.error(`Warning: Failed to load user config from ${userConfigPath}: ${error}`);
1538
- }
1539
- }
1540
- const projectConfigPath = join3(process.cwd(), ".self-review.yaml");
1541
- if (existsSync2(projectConfigPath)) {
3097
+ const provenance = Object.fromEntries(CONFIG_KEYS.map((key) => [key, "default"]));
3098
+ provenance.guideFile = "default";
3099
+ const sources = [];
3100
+ const files = [
3101
+ {
3102
+ origin: "user",
3103
+ path: join6(options.homeDir ?? homedir(), ".config", "self-review", "config.yaml")
3104
+ },
3105
+ { origin: "project", path: join6(options.cwd ?? process.cwd(), ".self-review.yaml") }
3106
+ ];
3107
+ for (const source of files) {
3108
+ if (!existsSync2(source.path)) continue;
1542
3109
  try {
1543
- const projectConfig = loadYamlConfig(projectConfigPath);
1544
- config = mergeConfig(config, projectConfig);
3110
+ const override = loadYamlConfig(source.path);
3111
+ config = mergeConfig(config, override);
3112
+ for (const key of Object.keys(override)) {
3113
+ provenance[key] = source.origin;
3114
+ }
3115
+ sources.push(source);
1545
3116
  } catch (error) {
1546
- console.error(`Warning: Failed to load project config from ${projectConfigPath}: ${error}`);
3117
+ console.error(
3118
+ `Warning: Failed to load ${source.origin} config from ${source.path}: ${error}`
3119
+ );
1547
3120
  }
1548
3121
  }
1549
- return config;
3122
+ return { config, provenance, sources };
1550
3123
  }
1551
- function loadYamlConfig(path4) {
1552
- const content = readFileSync2(path4, "utf-8");
3124
+ function loadConfig(options = {}) {
3125
+ return loadConfigWithProvenance(options).config;
3126
+ }
3127
+ function loadYamlConfig(path10) {
3128
+ const content = readFileSync2(path10, "utf-8");
1553
3129
  const raw = parseYaml(content);
1554
3130
  if (raw === null || raw === void 0) {
1555
3131
  return {};
@@ -1628,9 +3204,9 @@ function mergeConfig(base, override) {
1628
3204
  }
1629
3205
 
1630
3206
  // src/payload-sizing.ts
1631
- import { execFile } from "child_process";
1632
- import { promisify } from "util";
1633
- var execFileAsync = promisify(execFile);
3207
+ import { execFile as execFile3 } from "child_process";
3208
+ import { promisify as promisify2 } from "util";
3209
+ var execFileAsync2 = promisify2(execFile3);
1634
3210
  function computePayloadStats(fileCount, totalLines, config) {
1635
3211
  const maxFiles = config.maxFiles;
1636
3212
  const maxTotalLines = config.maxTotalLines;
@@ -1655,7 +3231,7 @@ function countTotalLines(files) {
1655
3231
  }
1656
3232
  async function getGitDiffStats(args, repoRoot) {
1657
3233
  try {
1658
- const { stdout } = await execFileAsync("git", ["diff", "--numstat", ...args], {
3234
+ const { stdout } = await execFileAsync2("git", ["diff", "--numstat", ...args], {
1659
3235
  maxBuffer: 10 * 1024 * 1024,
1660
3236
  timeout: 15e3,
1661
3237
  cwd: repoRoot
@@ -1682,27 +3258,47 @@ async function getGitDiffStats(args, repoRoot) {
1682
3258
  }
1683
3259
  }
1684
3260
 
1685
- // src/fs-utils.ts
1686
- import { accessSync, constants as fsConstants } from "fs";
1687
- import { dirname as dirname3 } from "path";
1688
- function checkWritability(filePath) {
1689
- try {
1690
- const dir = dirname3(filePath);
1691
- accessSync(dir, fsConstants.W_OK);
1692
- return true;
1693
- } catch {
1694
- return false;
1695
- }
1696
- }
1697
-
1698
3261
  // src/apply-suggestion.ts
1699
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
1700
- import { isAbsolute, relative as relative2, resolve as resolve2, sep } from "path";
3262
+ import * as path7 from "path";
3263
+ function isRepositoryControlPath(filePath) {
3264
+ return filePath.split(/[\\/]+/).some((segment) => segment.toLowerCase() === ".git");
3265
+ }
1701
3266
  function refuse(filePath, reason, detail) {
1702
3267
  return { status: "refused", filePath, reason, detail };
1703
3268
  }
1704
- function errorCode(error) {
1705
- return error?.code;
3269
+ var FS_REFUSALS = {
3270
+ "not-found": ["file-missing", "The file is not in the destination directory."],
3271
+ "unsafe-link": [
3272
+ "unsafe-target",
3273
+ "The path goes through a symbolic link, and this program does not write through links."
3274
+ ],
3275
+ "not-regular": ["unsafe-target", "The path is not a regular file."],
3276
+ "output-is-directory": ["file-unreadable", "The path is a directory, not a file."],
3277
+ "unsupported-target": [
3278
+ "unsupported-target",
3279
+ "The file is owned by another user, and replacing it would change its owner."
3280
+ ],
3281
+ "identity-changed": [
3282
+ "file-changed",
3283
+ "The file changed on disk after it was read, so nothing was written."
3284
+ ]
3285
+ };
3286
+ function refuseFsError(filePath, error, fallback) {
3287
+ const fsError = toSafeFsError(error, filePath, "access");
3288
+ const [reason, detail] = FS_REFUSALS[fsError.code] ?? [
3289
+ fallback,
3290
+ `The file could not be ${fallback === "write-failed" ? "written" : "read"} (${errnoOf(fsError.cause) ?? "unknown"}).`
3291
+ ];
3292
+ return refuse(filePath, reason, detail);
3293
+ }
3294
+ function relativeWithinRoot(filePath) {
3295
+ if (filePath === "" || path7.posix.isAbsolute(filePath) || path7.win32.isAbsolute(filePath)) {
3296
+ return null;
3297
+ }
3298
+ if (filePath.split("/").some((segment) => segment === "..")) return null;
3299
+ const normalized = path7.posix.normalize(filePath);
3300
+ if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
3301
+ return normalized;
1706
3302
  }
1707
3303
  function splitLines(content) {
1708
3304
  if (content === "") return [];
@@ -1710,11 +3306,43 @@ function splitLines(content) {
1710
3306
  if (lines[lines.length - 1] === "") lines.pop();
1711
3307
  return lines;
1712
3308
  }
3309
+ function proposalLines(proposedCode) {
3310
+ if (proposedCode === "") return [];
3311
+ const body = proposedCode.endsWith("\r\n") ? proposedCode.slice(0, -2) : proposedCode.endsWith("\n") ? proposedCode.slice(0, -1) : proposedCode;
3312
+ return body.split("\n");
3313
+ }
1713
3314
  function isCrlfRegion(anchored) {
1714
3315
  return anchored.length > 0 && anchored.every((line) => line.endsWith("\r"));
1715
3316
  }
1716
- function applySuggestion(request) {
3317
+ function openAndRead(realRoot, rel, filePath, fs3) {
3318
+ let opened;
3319
+ try {
3320
+ opened = openContainedFile(realRoot, rel, fs3);
3321
+ } catch (error) {
3322
+ return refuseFsError(filePath, error, "file-unreadable");
3323
+ }
3324
+ const { fd, stats } = opened;
3325
+ try {
3326
+ if (stats.nlink > 1) {
3327
+ return refuse(
3328
+ filePath,
3329
+ "unsafe-target",
3330
+ `The file has ${stats.nlink} hard links, and replacing it would silently detach the others.`
3331
+ );
3332
+ }
3333
+ return { identity: snapshotIdentity(stats), buffer: fs3.readFileSync(fd) };
3334
+ } catch (error) {
3335
+ return refuseFsError(filePath, error, "file-unreadable");
3336
+ } finally {
3337
+ try {
3338
+ fs3.closeSync(fd);
3339
+ } catch {
3340
+ }
3341
+ }
3342
+ }
3343
+ function applySuggestion(request, options = {}) {
1717
3344
  const { destinationRoot, filePath, lineRange, suggestion } = request;
3345
+ const fs3 = options.fs ?? nodeFsLayer;
1718
3346
  if (!lineRange) {
1719
3347
  return refuse(
1720
3348
  filePath,
@@ -1729,44 +3357,60 @@ function applySuggestion(request) {
1729
3357
  "This suggestion is anchored to deleted lines, which are not in the working file."
1730
3358
  );
1731
3359
  }
1732
- if (!isAbsolute(destinationRoot)) {
3360
+ if (lineRange.side !== "new") {
3361
+ return refuse(filePath, "invalid-anchor", "The anchor does not name a side of the diff.");
3362
+ }
3363
+ const anchor = validateLineRange(lineRange);
3364
+ if (!anchor.ok) {
3365
+ return refuse(
3366
+ filePath,
3367
+ "invalid-anchor",
3368
+ `The anchor is not a usable range: ${anchor.reason}.`
3369
+ );
3370
+ }
3371
+ const { start, end } = anchor.anchor;
3372
+ if (!path7.isAbsolute(destinationRoot)) {
1733
3373
  return refuse(
1734
3374
  filePath,
1735
3375
  "destination-not-absolute",
1736
3376
  "The destination directory must be an absolute path."
1737
3377
  );
1738
3378
  }
1739
- const root = resolve2(destinationRoot);
1740
- const absolutePath = resolve2(root, filePath);
1741
- const rel = relative2(root, absolutePath);
1742
- if (isAbsolute(filePath) || rel === "" || rel === ".." || rel.startsWith(`..${sep}`)) {
3379
+ const rel = relativeWithinRoot(filePath);
3380
+ if (rel === null) {
1743
3381
  return refuse(
1744
3382
  filePath,
1745
3383
  "path-escapes-destination",
1746
3384
  "The file path resolves outside the destination directory."
1747
3385
  );
1748
3386
  }
1749
- let buffer;
3387
+ if (isRepositoryControlPath(rel)) {
3388
+ return refuse(
3389
+ filePath,
3390
+ "control-file",
3391
+ "The path is repository metadata (.git), which is never part of a review."
3392
+ );
3393
+ }
3394
+ let realRoot;
1750
3395
  try {
1751
- buffer = readFileSync3(absolutePath);
3396
+ realRoot = fs3.realpathSync(path7.resolve(destinationRoot));
1752
3397
  } catch (error) {
1753
- const code = errorCode(error);
1754
- if (code === "ENOENT" || code === "ENOTDIR") {
1755
- return refuse(filePath, "file-missing", "The file is not in the destination directory.");
1756
- }
1757
3398
  return refuse(
1758
3399
  filePath,
1759
- "file-unreadable",
1760
- `The file could not be read (${code ?? "unknown"}).`
3400
+ "destination-missing",
3401
+ `The destination directory could not be resolved (${errnoOf(error) ?? "unknown"}).`
1761
3402
  );
1762
3403
  }
3404
+ const absolutePath = path7.join(realRoot, rel);
3405
+ const opened = openAndRead(realRoot, rel, filePath, fs3);
3406
+ if ("status" in opened) return opened;
3407
+ const { identity, buffer } = opened;
1763
3408
  const content = buffer.toString("utf8");
1764
3409
  if (!Buffer.from(content, "utf8").equals(buffer)) {
1765
3410
  return refuse(filePath, "file-not-utf8", "The file is not valid UTF-8 text.");
1766
3411
  }
1767
3412
  const lines = splitLines(content);
1768
- const { start, end } = lineRange;
1769
- if (start < 1 || end < start || end > lines.length) {
3413
+ if (end > lines.length) {
1770
3414
  return refuse(
1771
3415
  filePath,
1772
3416
  "anchor-out-of-range",
@@ -1781,18 +3425,21 @@ function applySuggestion(request) {
1781
3425
  `Lines ${start}-${end} no longer match the code this suggestion was written against.`
1782
3426
  );
1783
3427
  }
1784
- const proposed = suggestion.proposedCode.split("\n");
3428
+ const proposed = proposalLines(suggestion.proposedCode);
1785
3429
  const replacement = isCrlfRegion(anchored) ? proposed.map((line) => line.endsWith("\r") ? line : `${line}\r`) : proposed;
1786
3430
  const updated = [...lines.slice(0, start - 1), ...replacement, ...lines.slice(end)];
1787
- const output = updated.join("\n") + (content.endsWith("\n") ? "\n" : "");
3431
+ const output = updated.length === 0 ? "" : updated.join("\n") + (content.endsWith("\n") ? "\n" : "");
1788
3432
  try {
1789
- writeFileSync2(absolutePath, output, "utf8");
3433
+ atomicReplace(absolutePath, Buffer.from(output, "utf8"), {
3434
+ fs: fs3,
3435
+ preserveMode: true,
3436
+ preserveOwner: true,
3437
+ expectedIdentity: identity,
3438
+ expectUnmodified: true,
3439
+ randomName: options.randomName
3440
+ });
1790
3441
  } catch (error) {
1791
- return refuse(
1792
- filePath,
1793
- "write-failed",
1794
- `The file could not be written (${errorCode(error) ?? "unknown"}).`
1795
- );
3442
+ return refuseFsError(filePath, error, "write-failed");
1796
3443
  }
1797
3444
  return { status: "applied", filePath, absolutePath, replacedLines: anchored.length };
1798
3445
  }
@@ -1900,6 +3547,7 @@ async function runGh(runCommand, args) {
1900
3547
  try {
1901
3548
  result = await runCommand(GH_CLI, args);
1902
3549
  } catch (error) {
3550
+ if (isCommandCancelled(error)) throw error;
1903
3551
  const detail = error instanceof Error ? error.message : String(error);
1904
3552
  throw new ForgeCliUnavailableError("github", GH_CLI, `Failed to run the gh CLI: ${detail}`);
1905
3553
  }
@@ -2013,8 +3661,18 @@ function createGitHubProvider(runCommand) {
2013
3661
 
2014
3662
  // src/thread-mapper.ts
2015
3663
  var REVIEW_LEVEL_FILE_PATH = "";
2016
- function mapAnchorToLineRange(anchor) {
2017
- if (anchor.outdated) {
3664
+ function classifyAnchor(anchor, reviewedHeadSha) {
3665
+ if (anchor.outdated === true) {
3666
+ return "outdated";
3667
+ }
3668
+ if (anchor.headSha !== void 0) {
3669
+ if (reviewedHeadSha === void 0) return "unverified";
3670
+ return anchor.headSha === reviewedHeadSha ? "verified" : "outdated";
3671
+ }
3672
+ return anchor.outdated === false ? "verified" : "unverified";
3673
+ }
3674
+ function mapAnchorToLineRange(anchor, status) {
3675
+ if (status === "outdated") {
2018
3676
  return null;
2019
3677
  }
2020
3678
  const { startLine, endLine } = anchor;
@@ -2088,8 +3746,8 @@ function readAnchoredLines(diffFiles, filePath, range) {
2088
3746
  }
2089
3747
  return found.length === range.end - range.start + 1 ? found.join("\n") : null;
2090
3748
  }
2091
- function extractSuggestion(body, filePath, range, diffFiles) {
2092
- if (!range) return null;
3749
+ function extractSuggestion(body, filePath, range, status, diffFiles) {
3750
+ if (!range || status !== "verified") return null;
2093
3751
  const blocks = findSuggestionBlocks(body);
2094
3752
  if (blocks.length !== 1) return null;
2095
3753
  const originalCode = readAnchoredLines(diffFiles, filePath, range);
@@ -2104,17 +3762,18 @@ function mapReply(turn) {
2104
3762
  remoteId: turn.remoteId
2105
3763
  };
2106
3764
  }
2107
- function mapThreadsToReviewComments(threads, diffFiles = []) {
3765
+ function mapThreadsToReviewComments(threads, diffFiles = [], reviewedHeadSha) {
2108
3766
  return threads.map((thread) => {
2109
3767
  const filePath = thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH;
2110
- const lineRange = thread.anchor ? mapAnchorToLineRange(thread.anchor) : null;
3768
+ const status = thread.anchor ? classifyAnchor(thread.anchor, reviewedHeadSha) : "unverified";
3769
+ const lineRange = thread.anchor ? mapAnchorToLineRange(thread.anchor, status) : null;
2111
3770
  const comment = {
2112
3771
  id: internalId(thread.root),
2113
3772
  filePath,
2114
3773
  lineRange,
2115
3774
  body: thread.root.body,
2116
3775
  category: "",
2117
- suggestion: extractSuggestion(thread.root.body, filePath, lineRange, diffFiles),
3776
+ suggestion: extractSuggestion(thread.root.body, filePath, lineRange, status, diffFiles),
2118
3777
  author: thread.root.author,
2119
3778
  remoteId: thread.root.remoteId
2120
3779
  };
@@ -2139,6 +3798,7 @@ async function runGlabApi(runCommand, url, endpoint, extraArgs = []) {
2139
3798
  try {
2140
3799
  result = await runCommand(GLAB_CLI, args);
2141
3800
  } catch (error) {
3801
+ if (isCommandCancelled(error)) throw error;
2142
3802
  const detail = error instanceof Error ? error.message : String(error);
2143
3803
  throw unavailable(`glab CLI could not be spawned: ${detail}`);
2144
3804
  }
@@ -2148,14 +3808,14 @@ async function runGlabApi(runCommand, url, endpoint, extraArgs = []) {
2148
3808
  }
2149
3809
  return result.stdout;
2150
3810
  }
2151
- function parseJsonDocuments(text) {
3811
+ function parseJsonDocuments(text3) {
2152
3812
  const documents = [];
2153
3813
  let depth = 0;
2154
3814
  let inString = false;
2155
3815
  let escaped = false;
2156
3816
  let start = -1;
2157
- for (let i = 0; i < text.length; i++) {
2158
- const ch = text[i];
3817
+ for (let i = 0; i < text3.length; i++) {
3818
+ const ch = text3[i];
2159
3819
  if (inString) {
2160
3820
  if (escaped) {
2161
3821
  escaped = false;
@@ -2174,7 +3834,7 @@ function parseJsonDocuments(text) {
2174
3834
  } else if (ch === "]" || ch === "}") {
2175
3835
  depth -= 1;
2176
3836
  if (depth === 0 && start >= 0) {
2177
- documents.push(JSON.parse(text.slice(start, i + 1)));
3837
+ documents.push(JSON.parse(text3.slice(start, i + 1)));
2178
3838
  start = -1;
2179
3839
  }
2180
3840
  }
@@ -2208,7 +3868,11 @@ function toAnchor2(position) {
2208
3868
  const positionLine = lineOf(position);
2209
3869
  const startLine = lineOf(position.line_range?.start) ?? positionLine;
2210
3870
  const endLine = lineOf(position.line_range?.end) ?? positionLine;
2211
- return { filePath, side, startLine, endLine, outdated: false };
3871
+ const anchor = { filePath, side, startLine, endLine };
3872
+ if (typeof position.head_sha === "string" && position.head_sha.length > 0) {
3873
+ anchor.headSha = position.head_sha;
3874
+ }
3875
+ return anchor;
2212
3876
  }
2213
3877
  function toThread(discussion) {
2214
3878
  const notes = (discussion.notes ?? []).filter((note) => note.system !== true);
@@ -2267,26 +3931,100 @@ function createGitLabProvider(runCommand) {
2267
3931
  }
2268
3932
 
2269
3933
  // src/materializer.ts
2270
- import { execFile as execFile2 } from "child_process";
2271
- import * as fs2 from "fs";
3934
+ import { spawn } from "child_process";
3935
+ import { randomUUID } from "crypto";
3936
+ import * as fs from "fs";
2272
3937
  import * as os from "os";
2273
- import * as path2 from "path";
2274
- var LOCAL_BASE_REF = "refs/self-review/base";
2275
- var LOCAL_HEAD_REF = "refs/self-review/head";
3938
+ import * as path8 from "path";
3939
+ var DEFAULT_GIT_COMMAND_TIMEOUT_MS = 10 * 60 * 1e3;
3940
+ var CLEANUP_COMMAND_TIMEOUT_MS = 15e3;
3941
+ var KILL_GRACE_MS = 2e3;
3942
+ var MAX_OUTPUT_BYTES = 50 * 1024 * 1024;
2276
3943
  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.";
2277
- var defaultGitRunner = (command, args) => new Promise((resolve7, reject) => {
2278
- execFile2(command, args, { maxBuffer: 50 * 1024 * 1024 }, (error, stdout, stderr) => {
2279
- const spawnCode = error?.code;
2280
- if (error && typeof spawnCode === "string") {
2281
- reject(error);
3944
+ var defaultGitRunner = (command, args, options = {}) => new Promise((resolve10, reject) => {
3945
+ const { signal, timeoutMs } = options;
3946
+ if (signal?.aborted) {
3947
+ reject(new CommandCancelledError("aborted", command, args));
3948
+ return;
3949
+ }
3950
+ const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
3951
+ const stdout = [];
3952
+ const stderr = [];
3953
+ let outputBytes = 0;
3954
+ let settled = false;
3955
+ let cancelled = null;
3956
+ let overflowed = false;
3957
+ let killTimer;
3958
+ let timeoutTimer;
3959
+ const killChild = () => {
3960
+ child.kill("SIGTERM");
3961
+ killTimer = setTimeout(() => {
3962
+ if (!settled) child.kill("SIGKILL");
3963
+ }, KILL_GRACE_MS);
3964
+ };
3965
+ const cancel = (reason) => {
3966
+ if (settled || cancelled !== null) return;
3967
+ cancelled = reason;
3968
+ killChild();
3969
+ };
3970
+ const onAbort = () => cancel("aborted");
3971
+ signal?.addEventListener("abort", onAbort, { once: true });
3972
+ if (timeoutMs !== void 0 && timeoutMs > 0) {
3973
+ timeoutTimer = setTimeout(() => cancel("timeout"), timeoutMs);
3974
+ }
3975
+ const settle = (outcome) => {
3976
+ if (settled) return;
3977
+ settled = true;
3978
+ if (killTimer) clearTimeout(killTimer);
3979
+ if (timeoutTimer) clearTimeout(timeoutTimer);
3980
+ signal?.removeEventListener("abort", onAbort);
3981
+ outcome();
3982
+ };
3983
+ const collect = (sink) => (chunk) => {
3984
+ outputBytes += chunk.length;
3985
+ if (outputBytes > MAX_OUTPUT_BYTES) {
3986
+ if (!overflowed) {
3987
+ overflowed = true;
3988
+ killChild();
3989
+ }
2282
3990
  return;
2283
3991
  }
2284
- resolve7({
2285
- stdout: stdout ?? "",
2286
- stderr: stderr ?? "",
2287
- exitCode: error ? typeof spawnCode === "number" ? spawnCode : 1 : 0
2288
- });
3992
+ sink.push(chunk);
3993
+ };
3994
+ child.stdout?.on("data", collect(stdout));
3995
+ child.stderr?.on("data", collect(stderr));
3996
+ child.on("error", (error) => settle(() => reject(error)));
3997
+ child.on("exit", () => {
3998
+ if (cancelled !== null || overflowed) {
3999
+ child.stdout?.destroy();
4000
+ child.stderr?.destroy();
4001
+ }
2289
4002
  });
4003
+ child.on(
4004
+ "close",
4005
+ (code, exitSignal) => settle(() => {
4006
+ if (cancelled !== null) {
4007
+ reject(new CommandCancelledError(cancelled, command, args));
4008
+ return;
4009
+ }
4010
+ if (overflowed) {
4011
+ reject(
4012
+ new Error(`${command} ${args.join(" ")} produced more than ${MAX_OUTPUT_BYTES} bytes`)
4013
+ );
4014
+ return;
4015
+ }
4016
+ let stderrText = Buffer.concat(stderr).toString("utf-8");
4017
+ if (code === null && exitSignal) {
4018
+ stderrText += `${stderrText.endsWith("\n") || stderrText === "" ? "" : "\n"}(killed by ${exitSignal})
4019
+ `;
4020
+ }
4021
+ resolve10({
4022
+ stdout: Buffer.concat(stdout).toString("utf-8"),
4023
+ stderr: stderrText,
4024
+ exitCode: code ?? 1
4025
+ });
4026
+ })
4027
+ );
2290
4028
  });
2291
4029
  function headRefFor(url) {
2292
4030
  return url.forge === "github" ? `refs/pull/${url.number}/head` : `refs/merge-requests/${url.number}/head`;
@@ -2294,6 +4032,25 @@ function headRefFor(url) {
2294
4032
  function cloneUrlFor(url) {
2295
4033
  return `https://${url.host}/${url.owner}/${url.repo}.git`;
2296
4034
  }
4035
+ function sessionRefs() {
4036
+ const session = randomUUID();
4037
+ return {
4038
+ base: `refs/self-review/${session}/base`,
4039
+ head: `refs/self-review/${session}/head`
4040
+ };
4041
+ }
4042
+ function bindGit(runner, options) {
4043
+ const commandOptions = {
4044
+ signal: options.signal,
4045
+ timeoutMs: options.commandTimeoutMs ?? DEFAULT_GIT_COMMAND_TIMEOUT_MS
4046
+ };
4047
+ return (args) => {
4048
+ if (options.signal?.aborted) {
4049
+ return Promise.reject(new CommandCancelledError("aborted", "git", args));
4050
+ }
4051
+ return runner("git", args, commandOptions);
4052
+ };
4053
+ }
2297
4054
  function gitFailure(what, result, withAuthHint) {
2298
4055
  const stderr = result.stderr.trim();
2299
4056
  const lines = [
@@ -2343,104 +4100,140 @@ function findMatchingRemote(remoteVOutput, url) {
2343
4100
  }
2344
4101
  return null;
2345
4102
  }
2346
- async function revParse(runner, repoPath, ref) {
2347
- const result = await runner("git", ["-C", repoPath, "rev-parse", ref]);
4103
+ async function revParse(git, repoPath, ref) {
4104
+ const result = await git(["-C", repoPath, "rev-parse", ref]);
2348
4105
  if (result.exitCode !== 0) {
2349
4106
  throw gitFailure(`rev-parse ${ref}`, result, false);
2350
4107
  }
2351
4108
  return result.stdout.trim();
2352
4109
  }
2353
- async function detectExistingClone(url, cwd, runner = defaultGitRunner) {
2354
- const toplevel = await runner("git", ["-C", cwd, "rev-parse", "--show-toplevel"]);
4110
+ async function fetchSnapshot(git, repoPath, remote, url, baseBranch, refs, failureLabel) {
4111
+ const fetch = await git([
4112
+ "-C",
4113
+ repoPath,
4114
+ "fetch",
4115
+ remote,
4116
+ `+refs/heads/${baseBranch}:${refs.base}`,
4117
+ `+${headRefFor(url)}:${refs.head}`
4118
+ ]);
4119
+ if (fetch.exitCode !== 0) {
4120
+ throw gitFailure(failureLabel, fetch, true);
4121
+ }
4122
+ return {
4123
+ baseSha: await revParse(git, repoPath, refs.base),
4124
+ headSha: await revParse(git, repoPath, refs.head)
4125
+ };
4126
+ }
4127
+ async function detectExistingClone(url, cwd, runner = defaultGitRunner, options = {}) {
4128
+ const git = bindGit(runner, options);
4129
+ const toplevel = await git(["-C", cwd, "rev-parse", "--show-toplevel"]);
2355
4130
  if (toplevel.exitCode !== 0) {
2356
4131
  return null;
2357
4132
  }
2358
4133
  const repoPath = stripTrailingNewline(toplevel.stdout);
2359
- const remotes = await runner("git", ["-C", repoPath, "remote", "-v"]);
4134
+ const remotes = await git(["-C", repoPath, "remote", "-v"]);
2360
4135
  if (remotes.exitCode !== 0) {
2361
4136
  return null;
2362
4137
  }
2363
4138
  const remoteName = findMatchingRemote(remotes.stdout, url);
2364
4139
  return remoteName === null ? null : { repoPath, remoteName };
2365
4140
  }
2366
- async function materializeIntoExistingClone(runner, url, baseBranch, repoPath, remoteName) {
4141
+ async function materializeIntoExistingClone(runner, options, url, baseBranch, repoPath, remoteName) {
2367
4142
  console.error(`self-review: reusing existing clone at ${repoPath} (remote "${remoteName}")`);
2368
- const fetch = await runner("git", [
2369
- "-C",
2370
- repoPath,
2371
- "fetch",
2372
- remoteName,
2373
- `+refs/heads/${baseBranch}:${LOCAL_BASE_REF}`,
2374
- `+${headRefFor(url)}:${LOCAL_HEAD_REF}`
2375
- ]);
2376
- if (fetch.exitCode !== 0) {
2377
- throw gitFailure(`fetch from remote "${remoteName}"`, fetch, true);
2378
- }
2379
- return {
2380
- repoPath,
2381
- baseSha: await revParse(runner, repoPath, LOCAL_BASE_REF),
2382
- headSha: await revParse(runner, repoPath, LOCAL_HEAD_REF),
2383
- mode: "existing-clone",
2384
- cleanup: () => {
4143
+ const git = bindGit(runner, options);
4144
+ const refs = sessionRefs();
4145
+ const ownedRefs = [refs.base, refs.head];
4146
+ let released = false;
4147
+ const cleanup = async () => {
4148
+ if (released) return;
4149
+ released = true;
4150
+ for (const ref of ownedRefs) {
4151
+ try {
4152
+ const result = await runner("git", ["-C", repoPath, "update-ref", "-d", ref], {
4153
+ timeoutMs: CLEANUP_COMMAND_TIMEOUT_MS
4154
+ });
4155
+ if (result.exitCode !== 0) {
4156
+ console.error(
4157
+ `self-review: could not delete ${ref} in ${repoPath}: ${result.stderr.trim()}`
4158
+ );
4159
+ }
4160
+ } catch (error) {
4161
+ const message = error instanceof Error ? error.message : String(error);
4162
+ console.error(`self-review: could not delete ${ref} in ${repoPath}: ${message}`);
4163
+ }
2385
4164
  }
2386
4165
  };
4166
+ try {
4167
+ const { baseSha, headSha } = await fetchSnapshot(
4168
+ git,
4169
+ repoPath,
4170
+ remoteName,
4171
+ url,
4172
+ baseBranch,
4173
+ refs,
4174
+ `fetch from remote "${remoteName}"`
4175
+ );
4176
+ return { repoPath, baseSha, headSha, mode: "existing-clone", ownedRefs, cleanup };
4177
+ } catch (error) {
4178
+ await cleanup();
4179
+ throw error;
4180
+ }
2387
4181
  }
2388
- async function materializeIntoTempClone(runner, url, baseBranch) {
2389
- const tempDir = fs2.mkdtempSync(path2.join(os.tmpdir(), "self-review-"));
4182
+ async function materializeIntoTempClone(runner, options, url, baseBranch) {
4183
+ const git = bindGit(runner, options);
4184
+ const tempDir = fs.mkdtempSync(path8.join(os.tmpdir(), "self-review-"));
2390
4185
  let removed = false;
2391
- const cleanup = () => {
4186
+ const cleanup = async () => {
2392
4187
  if (removed) return;
2393
4188
  removed = true;
2394
- fs2.rmSync(tempDir, { recursive: true, force: true });
4189
+ fs.rmSync(tempDir, { recursive: true, force: true });
2395
4190
  };
2396
4191
  try {
2397
4192
  console.error(`self-review: created temporary blobless clone at ${tempDir}`);
2398
4193
  const cloneUrl = cloneUrlFor(url);
2399
- const clone = await runner("git", ["clone", "--filter=blob:none", cloneUrl, tempDir]);
4194
+ const clone = await git(["clone", "--filter=blob:none", cloneUrl, tempDir]);
2400
4195
  if (clone.exitCode !== 0) {
2401
4196
  throw gitFailure(`clone of ${cloneUrl}`, clone, true);
2402
4197
  }
2403
- const fetch = await runner("git", [
2404
- "-C",
4198
+ const { baseSha, headSha } = await fetchSnapshot(
4199
+ git,
2405
4200
  tempDir,
2406
- "fetch",
2407
4201
  "origin",
2408
- `+${headRefFor(url)}:${LOCAL_HEAD_REF}`
2409
- ]);
2410
- if (fetch.exitCode !== 0) {
2411
- throw gitFailure(`fetch of ${headRefFor(url)}`, fetch, true);
2412
- }
2413
- return {
2414
- repoPath: tempDir,
2415
- baseSha: await revParse(runner, tempDir, `origin/${baseBranch}`),
2416
- headSha: await revParse(runner, tempDir, LOCAL_HEAD_REF),
2417
- mode: "temp-clone",
2418
- cleanup
2419
- };
4202
+ url,
4203
+ baseBranch,
4204
+ sessionRefs(),
4205
+ `fetch of ${headRefFor(url)}`
4206
+ );
4207
+ return { repoPath: tempDir, baseSha, headSha, mode: "temp-clone", ownedRefs: [], cleanup };
2420
4208
  } catch (error) {
2421
- cleanup();
4209
+ await cleanup();
2422
4210
  throw error;
2423
4211
  }
2424
4212
  }
2425
- async function materialize(url, baseBranch, cwd, runner = defaultGitRunner, existingClone) {
2426
- const existing = existingClone === void 0 ? await detectExistingClone(url, cwd, runner) : existingClone;
4213
+ async function materialize(url, baseBranch, cwd, runner = defaultGitRunner, existingClone, options = {}) {
4214
+ if (options.signal?.aborted) {
4215
+ throw new CommandCancelledError("aborted", "git", ["materialize", cloneUrlFor(url)]);
4216
+ }
4217
+ const existing = existingClone === void 0 ? await detectExistingClone(url, cwd, runner, options) : existingClone;
2427
4218
  if (existing) {
2428
4219
  return materializeIntoExistingClone(
2429
4220
  runner,
4221
+ options,
2430
4222
  url,
2431
4223
  baseBranch,
2432
4224
  existing.repoPath,
2433
4225
  existing.remoteName
2434
4226
  );
2435
4227
  }
2436
- return materializeIntoTempClone(runner, url, baseBranch);
4228
+ return materializeIntoTempClone(runner, options, url, baseBranch);
2437
4229
  }
2438
- async function resolveRemoteDefaultBranch(url, runner = defaultGitRunner, existing = null) {
4230
+ async function resolveRemoteDefaultBranch(url, runner = defaultGitRunner, existing = null, options = {}) {
4231
+ const git = bindGit(runner, options);
2439
4232
  const cloneUrl = cloneUrlFor(url);
2440
4233
  const remote = existing?.remoteName ?? cloneUrl;
2441
4234
  const label = existing ? `${remote} (${cloneUrl})` : cloneUrl;
2442
4235
  const args = existing ? ["-C", existing.repoPath, "ls-remote", "--symref", remote, "HEAD"] : ["ls-remote", "--symref", remote, "HEAD"];
2443
- const result = await runner("git", args);
4236
+ const result = await git(args);
2444
4237
  if (result.exitCode !== 0) {
2445
4238
  throw gitFailure(`ls-remote of ${label}`, result, true);
2446
4239
  }
@@ -2454,130 +4247,8 @@ async function resolveRemoteDefaultBranch(url, runner = defaultGitRunner, existi
2454
4247
  }
2455
4248
 
2456
4249
  // src/review-handlers.ts
2457
- import * as fs3 from "fs";
2458
- import path3 from "path";
2459
-
2460
- // src/git-diff-args.ts
2461
- import { existsSync as existsSync3 } from "fs";
2462
- import { resolve as resolve3 } from "path";
2463
- var OPTIONS_WITH_SEPARATE_VALUES = /* @__PURE__ */ new Set([
2464
- "--output",
2465
- "--src-prefix",
2466
- "--dst-prefix",
2467
- "--line-prefix",
2468
- "--output-indicator-new",
2469
- "--output-indicator-old",
2470
- "--output-indicator-context",
2471
- "--inter-hunk-context",
2472
- "--stat-width",
2473
- "--stat-name-width",
2474
- "--stat-graph-width",
2475
- "--stat-count",
2476
- "--diff-algorithm",
2477
- "--word-diff-regex",
2478
- "--ignore-matching-lines",
2479
- "--anchored",
2480
- "--diff-filter",
2481
- "--find-object",
2482
- "--rotate-to",
2483
- "--skip-to",
2484
- "--ws-error-highlight",
2485
- "--color-moved-ws"
2486
- ]);
2487
- function consumesNextArgument(arg) {
2488
- if (arg.startsWith("--")) return OPTIONS_WITH_SEPARATE_VALUES.has(arg);
2489
- if (!arg.startsWith("-")) return false;
2490
- for (let i = 1; i < arg.length; i++) {
2491
- if ("SGOIl".includes(arg[i])) return i === arg.length - 1;
2492
- if ("UBMC".includes(arg[i])) return false;
2493
- }
2494
- return false;
2495
- }
2496
- function classifyGitDiffArgs(args) {
2497
- const positionalIndices = [];
2498
- let hasSeparator = false;
2499
- for (let i = 0; i < args.length; i++) {
2500
- const arg = args[i];
2501
- if (!hasSeparator) {
2502
- if (arg === "--") {
2503
- hasSeparator = true;
2504
- continue;
2505
- }
2506
- if (consumesNextArgument(arg)) {
2507
- i++;
2508
- continue;
2509
- }
2510
- if (arg.startsWith("-")) continue;
2511
- }
2512
- positionalIndices.push(i);
2513
- }
2514
- return { positionalIndices, hasSeparator };
2515
- }
2516
- function normalizeGitDiffArgs(args, cwd = process.cwd()) {
2517
- const { positionalIndices, hasSeparator } = classifyGitDiffArgs(args);
2518
- if (hasSeparator) return args;
2519
- for (const i of positionalIndices) {
2520
- const arg = args[i];
2521
- if (existsSync3(resolve3(cwd, arg))) {
2522
- return [...args.slice(0, i), "--", ...args.slice(i)];
2523
- }
2524
- }
2525
- return args;
2526
- }
2527
- function tokenizeGitDiffArgs(value) {
2528
- const args = [];
2529
- let current = "";
2530
- let started = false;
2531
- let quote = null;
2532
- for (let i = 0; i < value.length; i++) {
2533
- const char = value[i];
2534
- if (quote === "'") {
2535
- if (char === "'") quote = null;
2536
- else current += char;
2537
- continue;
2538
- }
2539
- if (quote === '"') {
2540
- if (char === "\\" && (value[i + 1] === '"' || value[i + 1] === "\\")) {
2541
- current += value[++i];
2542
- } else if (char === '"') {
2543
- quote = null;
2544
- } else {
2545
- current += char;
2546
- }
2547
- continue;
2548
- }
2549
- if (char === "'" || char === '"') {
2550
- quote = char;
2551
- started = true;
2552
- continue;
2553
- }
2554
- if (char === "\\" && i + 1 < value.length) {
2555
- current += value[++i];
2556
- started = true;
2557
- continue;
2558
- }
2559
- if (/\s/.test(char)) {
2560
- if (started) {
2561
- args.push(current);
2562
- current = "";
2563
- started = false;
2564
- }
2565
- continue;
2566
- }
2567
- current += char;
2568
- started = true;
2569
- }
2570
- if (started) args.push(current);
2571
- return args;
2572
- }
2573
- function needsQuoting(arg) {
2574
- return arg.length === 0 || /[\s'"\\]/.test(arg);
2575
- }
2576
- function formatGitDiffArgs(args) {
2577
- return args.map((arg) => needsQuoting(arg) ? `'${arg.replace(/'/g, "'\\''")}'` : arg).join(" ");
2578
- }
2579
-
2580
- // src/review-handlers.ts
4250
+ import * as fs2 from "fs";
4251
+ import path9 from "path";
2581
4252
  function createReviewSession() {
2582
4253
  return {
2583
4254
  reviewState: null,
@@ -2588,9 +4259,48 @@ function createReviewSession() {
2588
4259
  resumeComments: [],
2589
4260
  resumeViewedFiles: [],
2590
4261
  resumeRemoteDrift: null,
2591
- applyDestinationRoot: null
4262
+ resumeImportDiagnostics: [],
4263
+ applyDestinationRoot: null,
4264
+ reviewedPaths: emptyReviewedPaths(),
4265
+ sourceIdentity: null,
4266
+ attachmentOrigins: /* @__PURE__ */ new Map()
2592
4267
  };
2593
4268
  }
4269
+ function emptyReviewedPaths() {
4270
+ return freezeSet(/* @__PURE__ */ new Set());
4271
+ }
4272
+ function freezeSet(set) {
4273
+ const frozen = () => {
4274
+ throw new TypeError("reviewedPaths is captured when the diff is committed and cannot change");
4275
+ };
4276
+ Object.defineProperties(set, {
4277
+ add: { value: frozen },
4278
+ delete: { value: frozen },
4279
+ clear: { value: frozen }
4280
+ });
4281
+ return Object.freeze(set);
4282
+ }
4283
+ function reviewedPathsOf(files) {
4284
+ const paths = /* @__PURE__ */ new Set();
4285
+ for (const file of files) {
4286
+ if (file.newPath) paths.add(file.newPath);
4287
+ if (file.oldPath) paths.add(file.oldPath);
4288
+ }
4289
+ return freezeSet(paths);
4290
+ }
4291
+ function commitDiffData(session, payload, identity) {
4292
+ session.diffData = payload;
4293
+ session.reviewedPaths = reviewedPathsOf(payload.files);
4294
+ session.sourceIdentity = identity;
4295
+ }
4296
+ function locateReviewedFile(session, filePath) {
4297
+ const files = session.diffData?.files ?? [];
4298
+ const byNewPath = files.find((f) => f.newPath !== "" && f.newPath === filePath);
4299
+ if (byNewPath) return { file: byNewPath, side: "new" };
4300
+ const byOldPath = files.find((f) => f.oldPath !== "" && f.oldPath === filePath);
4301
+ if (byOldPath) return { file: byOldPath, side: "old" };
4302
+ return null;
4303
+ }
2594
4304
  function preparePayload(payload) {
2595
4305
  if (payload.isLargePayload) {
2596
4306
  return {
@@ -2613,57 +4323,55 @@ function getDiffLoad(session) {
2613
4323
  };
2614
4324
  }
2615
4325
  function resolveSourceBaseDir(session) {
2616
- const source = session.diffData?.source;
2617
- if (!source) return null;
2618
- if (source.type === "git") return source.repository;
2619
- if (source.type === "directory") return source.sourcePath;
2620
- if (source.type === "file") return path3.dirname(source.sourcePath);
2621
- return null;
2622
- }
4326
+ return session.sourceIdentity?.sourceRoot ?? null;
4327
+ }
4328
+ var IMAGE_MIME_TYPES = {
4329
+ ".jpg": "image/jpeg",
4330
+ ".jpeg": "image/jpeg",
4331
+ ".png": "image/png",
4332
+ ".gif": "image/gif",
4333
+ ".webp": "image/webp",
4334
+ ".ico": "image/x-icon",
4335
+ ".bmp": "image/bmp"
4336
+ };
2623
4337
  async function loadImage(session, filePath) {
2624
- const MIME_MAP = {
2625
- ".jpg": "image/jpeg",
2626
- ".jpeg": "image/jpeg",
2627
- ".png": "image/png",
2628
- ".gif": "image/gif",
2629
- ".webp": "image/webp",
2630
- ".ico": "image/x-icon",
2631
- ".bmp": "image/bmp",
2632
- ".svg": "image/svg+xml"
2633
- };
2634
- const MAX_SIZE = 10 * 1024 * 1024;
2635
- const baseDir = resolveSourceBaseDir(session) ?? process.cwd();
2636
- const resolved = path3.isAbsolute(filePath) ? filePath : path3.resolve(baseDir, filePath);
2637
- const ext = path3.extname(filePath).toLowerCase();
2638
- const mimeType = MIME_MAP[ext] ?? "application/octet-stream";
2639
- const remote = session.diffData?.remote;
2640
- if (remote && session.diffData?.source.type === "git") {
2641
- try {
2642
- const { readGitBlobAsync } = await import("./git-E7WZPKRC.js");
2643
- const data = await readGitBlobAsync(
2644
- session.diffData.source.repository,
2645
- `${remote.remoteHeadSha}:${filePath}`
2646
- );
2647
- if (data.length > MAX_SIZE) {
2648
- return { error: "File too large to preview (>10 MB)" };
2649
- }
2650
- return { dataUri: `data:${mimeType};base64,${data.toString("base64")}` };
2651
- } catch {
2652
- return {
2653
- error: "Image preview unavailable \u2014 blob not found at the reviewed commit."
2654
- };
2655
- }
4338
+ if (!session.reviewedPaths.has(filePath)) {
4339
+ return { error: "Image preview unavailable \u2014 this file is not part of the reviewed diff." };
2656
4340
  }
2657
- try {
2658
- const stat2 = await fs3.promises.stat(resolved);
2659
- if (stat2.size > MAX_SIZE) {
4341
+ if (!isPreviewableImage(filePath)) {
4342
+ return { error: "Image preview unavailable \u2014 this file is not a previewable image." };
4343
+ }
4344
+ const located = locateReviewedFile(session, filePath);
4345
+ const side = located?.side ?? "new";
4346
+ const result = await readReviewedContent(session, filePath, side, { maxBytes: MAX_IMAGE_BYTES });
4347
+ if (!result.ok) {
4348
+ if (result.reason === "too-large") {
2660
4349
  return { error: "File too large to preview (>10 MB)" };
2661
4350
  }
2662
- const data = await fs3.promises.readFile(resolved);
2663
- return { dataUri: `data:${mimeType};base64,${data.toString("base64")}` };
2664
- } catch {
2665
- return { error: "Image preview unavailable \u2014 file not found on disk." };
4351
+ console.error(`[review] Image preview unavailable for ${filePath}: ${result.message}`);
4352
+ return { error: `Image preview unavailable \u2014 ${result.message}` };
2666
4353
  }
4354
+ const mimeType = IMAGE_MIME_TYPES[path9.posix.extname(filePath).toLowerCase()];
4355
+ return { dataUri: `data:${mimeType};base64,${result.content.toString("base64")}` };
4356
+ }
4357
+ async function countReviewedLines(session, file) {
4358
+ const side = file.newPath ? "new" : "old";
4359
+ const filePath = side === "new" ? file.newPath : file.oldPath;
4360
+ const result = await readReviewedContent(session, filePath, side, {
4361
+ maxBytes: MAX_GIT_DIFF_OUTPUT_BYTES
4362
+ });
4363
+ if (!result.ok) {
4364
+ console.error(`[review] Line count unavailable for ${filePath}: ${result.message}`);
4365
+ return 0;
4366
+ }
4367
+ return countLines(result.content);
4368
+ }
4369
+ function countLines(content) {
4370
+ let newlines = 0;
4371
+ for (const byte of content) {
4372
+ if (byte === 10) newlines++;
4373
+ }
4374
+ return content.length > 0 && content[content.length - 1] === 10 ? newlines : newlines + 1;
2667
4375
  }
2668
4376
  function getFileHunks(session, filePath) {
2669
4377
  if (!session.diffData) return null;
@@ -2704,7 +4412,8 @@ function resolveApplyDestination(session) {
2704
4412
  }
2705
4413
  function applySuggestionForSession(session, request) {
2706
4414
  const destinationRoot = resolveApplyDestination(session);
2707
- if (!destinationRoot) {
4415
+ const identity = session.sourceIdentity;
4416
+ if (!destinationRoot || identity === null) {
2708
4417
  const temporary = isTemporaryCloneSession(session);
2709
4418
  return {
2710
4419
  status: "refused",
@@ -2713,9 +4422,18 @@ function applySuggestionForSession(session, request) {
2713
4422
  detail: temporary ? "This pull request was cloned into a temporary directory that is deleted when the review ends. Choose a destination directory to apply into." : "This review has no working directory to write into."
2714
4423
  };
2715
4424
  }
4425
+ if (!session.reviewedPaths.has(request.filePath)) {
4426
+ console.error(`[suggestion:apply] ${request.filePath}: refused (not-reviewed)`);
4427
+ return {
4428
+ status: "refused",
4429
+ filePath: request.filePath,
4430
+ reason: "not-reviewed",
4431
+ detail: "This file is not part of the reviewed diff, so nothing was written."
4432
+ };
4433
+ }
2716
4434
  const result = applySuggestion({
2717
4435
  destinationRoot,
2718
- filePath: request.filePath,
4436
+ filePath: rootRelativeReviewedPath(identity, request.filePath),
2719
4437
  lineRange: request.lineRange,
2720
4438
  suggestion: request.suggestion
2721
4439
  });
@@ -2725,28 +4443,46 @@ function applySuggestionForSession(session, request) {
2725
4443
  if (result.status === "applied") {
2726
4444
  return {
2727
4445
  status: "applied",
2728
- filePath: result.filePath,
4446
+ filePath: request.filePath,
2729
4447
  replacedLines: result.replacedLines
2730
4448
  };
2731
4449
  }
2732
4450
  return {
2733
4451
  status: "refused",
2734
- filePath: result.filePath,
4452
+ filePath: request.filePath,
2735
4453
  reason: result.reason,
2736
4454
  detail: result.detail
2737
4455
  };
2738
4456
  }
2739
- async function readAttachment(filePath) {
2740
- try {
2741
- const buffer = await fs3.promises.readFile(filePath);
2742
- return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
2743
- } catch {
2744
- console.error(`[attachment:read] Failed to read file: ${filePath}`);
2745
- return null;
4457
+ function recordResumedAttachments(session, comments, resumeDocumentPath) {
4458
+ const { origins, diagnostics } = resolveAttachmentOrigins(comments, resumeDocumentPath);
4459
+ session.attachmentOrigins = origins;
4460
+ return diagnostics;
4461
+ }
4462
+ async function readAttachment(session, reference) {
4463
+ const outputPath = session.outputPathInfo?.resolvedOutputPath;
4464
+ const currentAssetDir = outputPath ? path9.join(path9.dirname(outputPath), ASSET_DIR_NAME) : null;
4465
+ const assetPath = authorizeAttachmentReference(
4466
+ reference,
4467
+ session.attachmentOrigins,
4468
+ currentAssetDir
4469
+ );
4470
+ if (assetPath === null) {
4471
+ console.error(`[attachment:read] Refused: ${JSON.stringify(reference)}`);
4472
+ return {
4473
+ ok: false,
4474
+ reason: "not-authorized",
4475
+ message: `Attachments are read only from the review's ${ASSET_DIR_NAME} directory`
4476
+ };
4477
+ }
4478
+ const result = await readAssetFile(assetPath);
4479
+ if (!result.ok) {
4480
+ console.error(`[attachment:read] ${result.reason}: ${result.message}`);
2746
4481
  }
4482
+ return result;
2747
4483
  }
2748
4484
  function getResumeLoad(session) {
2749
- if (session.resumeComments.length > 0 || session.resumeViewedFiles.length > 0 || session.resumeRemoteDrift !== null) {
4485
+ if (session.resumeComments.length > 0 || session.resumeViewedFiles.length > 0 || session.resumeRemoteDrift !== null || session.resumeImportDiagnostics.length > 0) {
2750
4486
  const payload = {
2751
4487
  comments: session.resumeComments,
2752
4488
  viewedFiles: session.resumeViewedFiles
@@ -2754,61 +4490,56 @@ function getResumeLoad(session) {
2754
4490
  if (session.resumeRemoteDrift !== null) {
2755
4491
  payload.remoteDrift = session.resumeRemoteDrift;
2756
4492
  }
4493
+ if (session.resumeImportDiagnostics.length > 0) {
4494
+ payload.importDiagnostics = session.resumeImportDiagnostics;
4495
+ }
2757
4496
  return payload;
2758
4497
  }
2759
4498
  return null;
2760
4499
  }
2761
4500
  async function expandContext(session, request) {
2762
4501
  const diffData = session.diffData;
2763
- if (!diffData || diffData.source.type !== "git") {
4502
+ const identity = session.sourceIdentity;
4503
+ if (!diffData || diffData.source.type !== "git" || identity === null) {
4504
+ return null;
4505
+ }
4506
+ if (identity.mode !== "git" && identity.mode !== "remote") {
4507
+ return null;
4508
+ }
4509
+ if (!Number.isSafeInteger(request.contextLines) || request.contextLines < 0) {
4510
+ return null;
4511
+ }
4512
+ const target = diffData.files.find(
4513
+ (f) => !f.isUntracked && (f.newPath || f.oldPath) === request.filePath
4514
+ );
4515
+ if (!target) {
2764
4516
  return null;
2765
4517
  }
2766
4518
  try {
2767
- const { runGitDiffAsync: runGitDiffAsync2 } = await import("./git-E7WZPKRC.js");
2768
- const { parseDiff: parseDiff2 } = await import("./diff-parser-2JM4CZR3.js");
2769
- const source = diffData.source;
2770
- const originalArgs = tokenizeGitDiffArgs(source.gitDiffArgs);
2771
- const filteredArgs = [];
2772
- for (let i = 0; i < originalArgs.length; i++) {
2773
- const arg = originalArgs[i];
2774
- if (arg.match(/^-U\d+$/) || arg.match(/^--unified=\d+$/)) {
2775
- continue;
2776
- }
2777
- if (arg === "-U" || arg === "--unified") {
2778
- i++;
2779
- continue;
2780
- }
2781
- if (arg === "--") {
2782
- break;
2783
- }
2784
- filteredArgs.push(arg);
2785
- }
2786
- const expandArgs = [...filteredArgs, `-U${request.contextLines}`, "--", request.filePath];
2787
- const rawDiff = await runGitDiffAsync2(expandArgs, source.repository);
2788
- const parsedFiles = parseDiff2(rawDiff);
2789
- if (parsedFiles.length === 0) {
4519
+ const { runGitDiffAsync: runGitDiffAsync2 } = await import("./git-N5HVNPKQ.js");
4520
+ const { parseDiff: parseDiff2 } = await import("./diff-parser-B6S3KG5T.js");
4521
+ const rediff = singleFileRediffArgs(identity.gitDiffArgv);
4522
+ const prefix = identity.pathPrefix;
4523
+ const paths = [...new Set([target.oldPath, target.newPath].filter((p) => p !== ""))];
4524
+ const expandArgs = [
4525
+ ...rediff.args,
4526
+ ...prefix === "" ? [] : [`--relative=${prefix}`],
4527
+ `-U${request.contextLines}`,
4528
+ "--",
4529
+ ...paths.map((p) => `:(top,literal)${rootRelativeReviewedPath(identity, p)}`)
4530
+ ];
4531
+ const rawDiff = await runGitDiffAsync2(expandArgs, identity.sourceRoot);
4532
+ const expandedFile = parseDiff2(rawDiff).find(
4533
+ (f) => f.oldPath === target.oldPath && f.newPath === target.newPath
4534
+ );
4535
+ if (!expandedFile) {
4536
+ console.error(`[review] Expanded diff for ${request.filePath} did not contain the file`);
2790
4537
  return null;
2791
4538
  }
2792
- const expandedFile = parsedFiles[0];
2793
- let totalLines = 0;
2794
- try {
2795
- const content = await fs3.promises.readFile(
2796
- path3.resolve(source.repository, request.filePath),
2797
- "utf-8"
2798
- );
2799
- totalLines = content.split("\n").length;
2800
- if (content.endsWith("\n")) totalLines--;
2801
- } catch {
2802
- }
4539
+ const totalLines = await countReviewedLines(session, target);
2803
4540
  session.diffData = {
2804
4541
  ...diffData,
2805
- files: diffData.files.map((f) => {
2806
- const fPath = f.newPath || f.oldPath;
2807
- if (fPath === request.filePath) {
2808
- return { ...f, hunks: expandedFile.hunks };
2809
- }
2810
- return f;
2811
- })
4542
+ files: diffData.files.map((f) => f === target ? { ...f, hunks: expandedFile.hunks } : f)
2812
4543
  };
2813
4544
  return { hunks: expandedFile.hunks, totalLines };
2814
4545
  } catch (error) {
@@ -2820,94 +4551,315 @@ async function prepareDirectoryReview(session, directoryPath) {
2820
4551
  console.error("[review] Starting directory review for:", directoryPath);
2821
4552
  let isFile = false;
2822
4553
  try {
2823
- isFile = fs3.statSync(directoryPath).isFile();
4554
+ isFile = fs2.statSync(directoryPath).isFile();
2824
4555
  } catch {
2825
4556
  }
2826
- let payload;
2827
- if (isFile) {
2828
- const files = await scanFile(directoryPath);
2829
- payload = {
2830
- files,
2831
- source: { type: "file", sourcePath: directoryPath }
2832
- };
2833
- } else {
2834
- const ignorePatterns = session.config?.ignore ?? [];
2835
- const files = await scanDirectory(directoryPath, ignorePatterns);
2836
- payload = {
2837
- files,
2838
- source: { type: "directory", sourcePath: directoryPath }
2839
- };
2840
- }
4557
+ const scan = isFile ? await scanFile(directoryPath) : await scanDirectory(directoryPath, session.config?.ignore ?? []);
4558
+ const type = isFile ? "file" : "directory";
4559
+ const payload = {
4560
+ files: scan.files,
4561
+ source: { type, sourcePath: directoryPath },
4562
+ ...scan.diagnostics.length > 0 ? { diagnostics: scan.diagnostics } : {}
4563
+ };
4564
+ const identity = resolveLocalSourceIdentity({ type, sourcePath: directoryPath });
2841
4565
  if (!session.config) {
2842
- return { payload, stats: null, exceedsThresholds: false };
4566
+ return { payload, identity, stats: null, exceedsThresholds: false };
2843
4567
  }
2844
4568
  const stats = computePayloadStats(
2845
4569
  payload.files.length,
2846
4570
  countTotalLines(payload.files),
2847
4571
  session.config
2848
4572
  );
2849
- return { payload, stats, exceedsThresholds: stats.exceedsAny };
4573
+ return { payload, identity, stats, exceedsThresholds: stats.exceedsAny };
2850
4574
  }
2851
- function commitReviewStart(session, payload) {
2852
- session.diffData = payload;
4575
+ function commitReviewStart(session, payload, identity) {
4576
+ commitDiffData(session, payload, identity);
2853
4577
  return preparePayload(payload);
2854
4578
  }
2855
4579
 
2856
4580
  // src/startup-mode.ts
2857
- import { existsSync as existsSync4, statSync as statSync2 } from "fs";
4581
+ import { existsSync as existsSync3, statSync as statSync2 } from "fs";
2858
4582
  import { execFileSync, execSync } from "child_process";
2859
- import { resolve as resolve4 } from "path";
2860
- function isInGitRepo() {
4583
+ import { resolve as resolve7 } from "path";
4584
+ function isInGitRepo(cwd) {
2861
4585
  try {
2862
- execSync("git rev-parse --git-dir", { stdio: "ignore" });
4586
+ execSync("git rev-parse --git-dir", { stdio: "ignore", cwd });
2863
4587
  return true;
2864
4588
  } catch {
2865
4589
  return false;
2866
4590
  }
2867
4591
  }
2868
- function isGitTracked(filePath) {
4592
+ function isGitTracked(filePath, cwd) {
2869
4593
  try {
2870
4594
  execFileSync("git", ["ls-files", "--error-unmatch", "--", filePath], {
2871
- stdio: "ignore"
4595
+ stdio: "ignore",
4596
+ cwd
2872
4597
  });
2873
4598
  return true;
2874
4599
  } catch {
2875
4600
  return false;
2876
4601
  }
2877
4602
  }
4603
+ function resolveStartupSource(gitDiffArgs, cwd = process.cwd()) {
4604
+ const { positionalIndices } = classifyGitDiffArgs([...gitDiffArgs]);
4605
+ const firstPositional = positionalIndices.length > 0 ? gitDiffArgs[positionalIndices[0]] : void 0;
4606
+ const candidate = firstPositional ? resolve7(cwd, firstPositional) : null;
4607
+ if (candidate && firstPositional && isExisting(candidate, "file")) {
4608
+ if (isInGitRepo(cwd)) {
4609
+ return isGitTracked(firstPositional, cwd) ? { mode: "git" } : { mode: "file", sourcePath: candidate };
4610
+ }
4611
+ return { mode: "file", sourcePath: candidate };
4612
+ }
4613
+ if (isInGitRepo(cwd)) {
4614
+ return { mode: "git" };
4615
+ }
4616
+ if (candidate && isExisting(candidate, "directory")) {
4617
+ return { mode: "directory", sourcePath: candidate };
4618
+ }
4619
+ return { mode: "welcome" };
4620
+ }
4621
+ function isExisting(candidate, kind) {
4622
+ try {
4623
+ if (!existsSync3(candidate)) return false;
4624
+ const stats = statSync2(candidate);
4625
+ return kind === "file" ? stats.isFile() : stats.isDirectory();
4626
+ } catch {
4627
+ return false;
4628
+ }
4629
+ }
2878
4630
  function determineMode(gitDiffArgs) {
2879
- const { positionalIndices } = classifyGitDiffArgs(gitDiffArgs);
2880
- const firstPositional = gitDiffArgs[positionalIndices[0]];
2881
- if (firstPositional) {
2882
- const candidate = resolve4(process.cwd(), firstPositional);
2883
- try {
2884
- if (existsSync4(candidate) && statSync2(candidate).isFile()) {
2885
- if (isInGitRepo()) {
2886
- return isGitTracked(firstPositional) ? "git" : "file";
2887
- }
2888
- return "file";
4631
+ return resolveStartupSource(gitDiffArgs).mode;
4632
+ }
4633
+
4634
+ // src/startup.ts
4635
+ import { resolve as resolve8 } from "path";
4636
+
4637
+ // src/staged-untracked.ts
4638
+ function applyStagedUntrackedDefault(config, gitDiffArgs) {
4639
+ const stagedMode = gitDiffArgs.includes("--staged") || gitDiffArgs.includes("--cached");
4640
+ if (!stagedMode) return config;
4641
+ const userExplicitOptIn = config.showUntrackedExplicit && config.showUntracked;
4642
+ if (userExplicitOptIn) return config;
4643
+ return { ...config, showUntracked: false };
4644
+ }
4645
+
4646
+ // src/git-diff-loader.ts
4647
+ function entryPath(file) {
4648
+ return file.newPath || file.oldPath;
4649
+ }
4650
+ function dedupeUntrackedByPath(tracked, untracked) {
4651
+ const seen = new Set(tracked.map(entryPath));
4652
+ return untracked.filter((file) => !seen.has(entryPath(file)));
4653
+ }
4654
+ async function loadGitDiffWithUntracked(gitDiffArgs, cwd, options = {}) {
4655
+ const { includeUntracked = true } = options;
4656
+ const budgets = resolveSourceBudgets(options.budgets);
4657
+ const repository = await getRepoRootAsync(cwd);
4658
+ const identity = await resolveGitSourceIdentity({
4659
+ repository,
4660
+ gitDiffArgv: gitDiffArgs,
4661
+ invocationCwd: cwd ?? process.cwd()
4662
+ });
4663
+ const unsupported = findUnsupportedGitDiffOptions(gitDiffArgs);
4664
+ if (unsupported.length > 0) {
4665
+ return {
4666
+ files: [],
4667
+ repository,
4668
+ identity,
4669
+ diagnostics: unsupported.map(
4670
+ (flag) => `Unsupported git diff option ${flag}: self-review reads patch output only; remove it to review the changes.`
4671
+ )
4672
+ };
4673
+ }
4674
+ let rawDiff;
4675
+ try {
4676
+ rawDiff = await runGitDiffAsync(gitDiffArgs, cwd, budgets.maxGitDiffOutputBytes);
4677
+ } catch (error) {
4678
+ if (!isOutputLimitError(error)) throw error;
4679
+ return {
4680
+ files: [],
4681
+ repository,
4682
+ identity,
4683
+ diagnostics: [
4684
+ `git diff produced more than ${formatBytes(budgets.maxGitDiffOutputBytes)} of output, the most self-review reads from one diff, so nothing was loaded. Narrow the diff with a pathspec (for example \`-- src/\`) or a smaller revision range.`
4685
+ ]
4686
+ };
4687
+ }
4688
+ const { files, diagnostics } = parseDiffWithDiagnostics(rawDiff);
4689
+ if (!includeUntracked) {
4690
+ return { files, repository, identity, diagnostics };
4691
+ }
4692
+ const untrackedPaths = await getUntrackedFilesAsync(repository);
4693
+ if (untrackedPaths.length > budgets.maxEntries) {
4694
+ diagnostics.push(
4695
+ `${untrackedPaths.length.toLocaleString("en-US")} untracked files exceed the ${budgets.maxEntries.toLocaleString("en-US")}-file limit, so none of them were loaded; only tracked changes are shown. Ignore build output and dependency folders in .gitignore, or stage the files you mean to review.`
4696
+ );
4697
+ return { files, repository, identity, diagnostics };
4698
+ }
4699
+ let allFiles = files;
4700
+ if (untrackedPaths.length > 0) {
4701
+ const untracked = loadSyntheticFiles(untrackedPaths, repository, {
4702
+ followSymlinks: false,
4703
+ budgets: options.budgets
4704
+ });
4705
+ diagnostics.push(...untracked.diagnostics);
4706
+ const untrackedFiles = dedupeUntrackedByPath(files, untracked.files);
4707
+ for (const file of untrackedFiles) {
4708
+ file.isUntracked = true;
4709
+ }
4710
+ allFiles = [...files, ...untrackedFiles];
4711
+ }
4712
+ return { files: allFiles, repository, identity, diagnostics };
4713
+ }
4714
+
4715
+ // src/startup.ts
4716
+ function resolveOutputTarget(explicitPath, loaded, cwd) {
4717
+ if (explicitPath !== null) {
4718
+ return { path: resolve8(cwd, explicitPath), origin: "explicit" };
4719
+ }
4720
+ const path10 = resolve8(cwd, loaded.config.outputFile);
4721
+ if (loaded.provenance.outputFile === "user") {
4722
+ return { path: path10, origin: "explicit" };
4723
+ }
4724
+ return { path: path10, origin: "inherited", baseDir: cwd };
4725
+ }
4726
+ function publishOptionsFor(target, attachmentOrigins) {
4727
+ return target.origin === "explicit" ? { outputOrigin: "explicit", attachmentOrigins } : { outputOrigin: "inherited", baseDir: target.baseDir, attachmentOrigins };
4728
+ }
4729
+ var ConfiguredDiffArgsError = class extends Error {
4730
+ constructor(options, configPath) {
4731
+ super(
4732
+ `Refusing default-diff-args from ${configPath}: ${options.join(" ")} would make git write a file or run an external program. A committed project configuration may not supply such options; pass them on the command line instead.`
4733
+ );
4734
+ this.name = "ConfiguredDiffArgsError";
4735
+ this.options = [...options];
4736
+ this.configPath = configPath;
4737
+ }
4738
+ };
4739
+ function resolveStartupDiffArgs(cliGitDiffArgs, loaded, cwd) {
4740
+ let gitDiffArgs = [...cliGitDiffArgs];
4741
+ let origin = "cli";
4742
+ if (gitDiffArgs.length === 0 && loaded.config.defaultDiffArgs) {
4743
+ gitDiffArgs = tokenizeGitDiffArgs(loaded.config.defaultDiffArgs);
4744
+ origin = loaded.provenance.defaultDiffArgs;
4745
+ if (origin === "project") {
4746
+ const offending = findWriteCapableGitDiffOptions(gitDiffArgs);
4747
+ if (offending.length > 0) {
4748
+ const source = loaded.sources.find((s) => s.origin === "project");
4749
+ throw new ConfiguredDiffArgsError(offending, source?.path ?? ".self-review.yaml");
2889
4750
  }
2890
- } catch {
2891
4751
  }
2892
4752
  }
2893
- if (isInGitRepo()) {
2894
- return "git";
4753
+ gitDiffArgs = normalizeGitDiffArgs(gitDiffArgs, cwd);
4754
+ return {
4755
+ gitDiffArgs,
4756
+ origin,
4757
+ config: applyStagedUntrackedDefault(loaded.config, gitDiffArgs)
4758
+ };
4759
+ }
4760
+ async function loadLocalReview(source, gitDiffArgs, config, cwd, log) {
4761
+ if (source.mode === "git") {
4762
+ const { files, repository, diagnostics, identity } = await loadGitDiffWithUntracked(
4763
+ [...gitDiffArgs],
4764
+ cwd
4765
+ );
4766
+ for (const diagnostic of diagnostics) log(`Diff diagnostic: ${diagnostic}`);
4767
+ const shouldKeep = createIgnoreFilter(config.ignore);
4768
+ return {
4769
+ payload: {
4770
+ files: files.filter((f) => shouldKeep(f.newPath || f.oldPath)),
4771
+ source: {
4772
+ type: "git",
4773
+ // Quoted so the argv is recoverable exactly from the document's git-diff-args.
4774
+ gitDiffArgs: formatGitDiffArgs([...gitDiffArgs]),
4775
+ repository
4776
+ },
4777
+ ...diagnostics.length > 0 ? { diagnostics } : {}
4778
+ },
4779
+ identity
4780
+ };
2895
4781
  }
2896
- if (firstPositional) {
2897
- const candidate = resolve4(process.cwd(), firstPositional);
2898
- try {
2899
- if (existsSync4(candidate) && statSync2(candidate).isDirectory()) {
2900
- return "directory";
4782
+ if (source.mode === "file" || source.mode === "directory") {
4783
+ const scan = source.mode === "file" ? await scanFile(source.sourcePath) : await scanDirectory(source.sourcePath, config.ignore);
4784
+ for (const diagnostic of scan.diagnostics) log(`Diff diagnostic: ${diagnostic}`);
4785
+ return {
4786
+ payload: {
4787
+ files: scan.files,
4788
+ source: { type: source.mode, sourcePath: source.sourcePath },
4789
+ ...scan.diagnostics.length > 0 ? { diagnostics: scan.diagnostics } : {}
4790
+ },
4791
+ identity: resolveLocalSourceIdentity({ type: source.mode, sourcePath: source.sourcePath })
4792
+ };
4793
+ }
4794
+ return { payload: { files: [], source: { type: "welcome" } }, identity: null };
4795
+ }
4796
+ function loadResumeDocument(session, resumePath) {
4797
+ const parsed = parseReviewXml(resumePath);
4798
+ session.resumeComments = parsed.comments;
4799
+ session.resumeViewedFiles = parsed.viewedFiles;
4800
+ session.resumeImportDiagnostics = [
4801
+ ...parsed.importDiagnostics,
4802
+ ...recordResumedAttachments(session, parsed.comments, resumePath)
4803
+ ];
4804
+ return parsed;
4805
+ }
4806
+
4807
+ // src/cli-options.ts
4808
+ var ApplicationOptionError = class extends Error {
4809
+ constructor(flag) {
4810
+ super(`${flag} requires a file path argument`);
4811
+ this.name = "ApplicationOptionError";
4812
+ this.flag = flag;
4813
+ }
4814
+ };
4815
+ function extractApplicationOptions(argv, spec) {
4816
+ const values = Object.fromEntries(
4817
+ Object.values(spec.valueFlags).map((field) => [field, null])
4818
+ );
4819
+ const flags = Object.fromEntries(
4820
+ Object.values(spec.booleanFlags ?? {}).map((field) => [field, false])
4821
+ );
4822
+ const rest = [];
4823
+ for (let i = 0; i < argv.length; i++) {
4824
+ const arg = argv[i];
4825
+ if (arg === "--") {
4826
+ rest.push(...argv.slice(i));
4827
+ break;
4828
+ }
4829
+ const booleanField = spec.booleanFlags?.[arg];
4830
+ if (booleanField !== void 0) {
4831
+ flags[booleanField] = true;
4832
+ continue;
4833
+ }
4834
+ const valueField = spec.valueFlags[arg];
4835
+ if (valueField !== void 0) {
4836
+ if (i + 1 >= argv.length) throw new ApplicationOptionError(arg);
4837
+ values[valueField] = requireValue(arg, argv[i + 1]);
4838
+ i++;
4839
+ continue;
4840
+ }
4841
+ const equals = arg.indexOf("=");
4842
+ if (arg.startsWith("--") && equals > 0) {
4843
+ const equalsField = spec.valueFlags[arg.slice(0, equals)];
4844
+ if (equalsField !== void 0) {
4845
+ values[equalsField] = requireValue(arg.slice(0, equals), arg.slice(equals + 1));
4846
+ continue;
2901
4847
  }
2902
- } catch {
4848
+ }
4849
+ rest.push(arg);
4850
+ if (consumesNextArgument(arg) && i + 1 < argv.length) {
4851
+ rest.push(argv[++i]);
2903
4852
  }
2904
4853
  }
2905
- return "welcome";
4854
+ return { values, flags, rest };
4855
+ }
4856
+ function requireValue(flag, value) {
4857
+ if (value === "") throw new ApplicationOptionError(flag);
4858
+ return value;
2906
4859
  }
2907
4860
 
2908
4861
  // src/guide-loader.ts
2909
- import { readFile } from "fs/promises";
2910
- import { extname, resolve as resolve5 } from "path";
4862
+ import { extname, resolve as resolve9 } from "path";
2911
4863
  function deriveGuidePath(outputPath) {
2912
4864
  const ext = extname(outputPath);
2913
4865
  const base = ext ? outputPath.slice(0, -ext.length) : outputPath;
@@ -2915,7 +4867,7 @@ function deriveGuidePath(outputPath) {
2915
4867
  }
2916
4868
  function resolveGuidePath(outputPath, config) {
2917
4869
  if (config.guideFile) {
2918
- return resolve5(process.cwd(), config.guideFile);
4870
+ return resolve9(process.cwd(), config.guideFile);
2919
4871
  }
2920
4872
  return deriveGuidePath(outputPath);
2921
4873
  }
@@ -2929,7 +4881,18 @@ async function loadGuide(outputPath, config, diffFilePaths) {
2929
4881
  try {
2930
4882
  let content;
2931
4883
  try {
2932
- content = await readFile(guidePath, "utf-8");
4884
+ const read = await readFileWithinBudget(guidePath, MAX_GUIDE_BYTES);
4885
+ if (read.kind === "too-large") {
4886
+ console.error(
4887
+ `[guide] Ignoring guide at ${guidePath}: too large (${formatBytes(read.size)}, over the ${formatBytes(MAX_GUIDE_BYTES)} guide budget)`
4888
+ );
4889
+ return null;
4890
+ }
4891
+ if (read.kind === "not-regular") {
4892
+ console.error(`[guide] Ignoring guide at ${guidePath}: unreadable (not a regular file)`);
4893
+ return null;
4894
+ }
4895
+ content = read.content.toString("utf-8");
2933
4896
  } catch (error) {
2934
4897
  const code = error.code;
2935
4898
  if (code === "ENOENT") {
@@ -2959,44 +4922,28 @@ async function loadGuide(outputPath, config, diffFilePaths) {
2959
4922
  }
2960
4923
  }
2961
4924
 
2962
- // src/git-diff-loader.ts
2963
- async function loadGitDiffWithUntracked(gitDiffArgs, cwd, options = {}) {
2964
- const { includeUntracked = true } = options;
2965
- const repository = await getRepoRootAsync(cwd);
2966
- const rawDiff = await runGitDiffAsync(gitDiffArgs, cwd);
2967
- const files = parseDiff(rawDiff);
2968
- if (!includeUntracked) {
2969
- return { files, repository };
2970
- }
2971
- const untrackedPaths = await getUntrackedFilesAsync(repository);
2972
- let allFiles = files;
2973
- if (untrackedPaths.length > 0) {
2974
- const untrackedDiffStr = generateUntrackedDiffs(untrackedPaths, repository);
2975
- if (untrackedDiffStr.length > 0) {
2976
- const untrackedFiles = parseDiff(untrackedDiffStr);
2977
- for (const file of untrackedFiles) {
2978
- file.isUntracked = true;
2979
- }
2980
- allFiles = [...files, ...untrackedFiles];
2981
- }
2982
- }
2983
- return { files: allFiles, repository };
2984
- }
2985
-
2986
- // src/staged-untracked.ts
2987
- function applyStagedUntrackedDefault(config, gitDiffArgs) {
2988
- const stagedMode = gitDiffArgs.includes("--staged") || gitDiffArgs.includes("--cached");
2989
- if (!stagedMode) return config;
2990
- const userExplicitOptIn = config.showUntrackedExplicit && config.showUntracked;
2991
- if (userExplicitOptIn) return config;
2992
- return { ...config, showUntracked: false };
2993
- }
2994
-
2995
4925
  // src/remote-mode.ts
2996
4926
  function defaultCreateProvider(forge, runner) {
2997
4927
  return forge === "github" ? createGitHubProvider(runner) : createGitLabProvider(runner);
2998
4928
  }
2999
- var defaultDeps = {
4929
+ function bindSessionRunner(runner, signal) {
4930
+ return (command, args, options) => {
4931
+ if (signal?.aborted) {
4932
+ return Promise.reject(new CommandCancelledError("aborted", command, args));
4933
+ }
4934
+ return runner(command, args, {
4935
+ signal,
4936
+ timeoutMs: DEFAULT_GIT_COMMAND_TIMEOUT_MS,
4937
+ ...options
4938
+ });
4939
+ };
4940
+ }
4941
+ function throwIfAborted(signal, stage) {
4942
+ if (signal?.aborted) {
4943
+ throw new CommandCancelledError("aborted", "self-review", [stage]);
4944
+ }
4945
+ }
4946
+ var defaultRemoteSessionDeps = {
3000
4947
  createProvider: defaultCreateProvider,
3001
4948
  detectExistingClone,
3002
4949
  materialize,
@@ -3008,13 +4955,20 @@ var defaultDeps = {
3008
4955
  loadGitDiffWithUntracked(gitDiffArgs, cwd, { includeUntracked: false })
3009
4956
  )
3010
4957
  };
3011
- async function startRemoteSession(url, cwd, deps = {}) {
3012
- const d = { ...defaultDeps, ...deps };
4958
+ async function startRemoteSession(url, cwd, deps = {}, options = {}) {
4959
+ const d = { ...defaultRemoteSessionDeps, ...deps };
4960
+ const threadsRequired = options.threads === "required";
4961
+ const { signal } = options;
4962
+ const lifetime = { signal };
4963
+ throwIfAborted(signal, "start");
3013
4964
  const forgeUrl = parseForgeUrl(url);
3014
4965
  if (!forgeUrl) {
3015
- throw new Error(`Not a recognized pull-request or merge-request URL: ${url}`);
4966
+ throw new Error(
4967
+ `Not a recognized pull-request or merge-request URL: ${url}
4968
+ Expected a GitHub PR URL (\u2026/pull/N) or a GitLab MR URL (\u2026/-/merge_requests/N).`
4969
+ );
3016
4970
  }
3017
- const provider = d.createProvider(forgeUrl.forge, d.runner);
4971
+ const provider = d.createProvider(forgeUrl.forge, bindSessionRunner(d.runner, signal));
3018
4972
  let cliAvailable = true;
3019
4973
  let baseBranch;
3020
4974
  let existingClone;
@@ -3028,17 +4982,37 @@ async function startRemoteSession(url, cwd, deps = {}) {
3028
4982
  console.error(
3029
4983
  `[remote] Forge CLI unavailable (${error.cli}): ${error.message} \u2014 falling back to the remote default branch via git.`
3030
4984
  );
3031
- existingClone = await d.detectExistingClone(forgeUrl, cwd, d.runner);
3032
- baseBranch = await d.resolveRemoteDefaultBranch(forgeUrl, d.runner, existingClone);
4985
+ existingClone = await d.detectExistingClone(forgeUrl, cwd, d.runner, lifetime);
4986
+ baseBranch = await d.resolveRemoteDefaultBranch(forgeUrl, d.runner, existingClone, lifetime);
3033
4987
  }
3034
- const materialized = await d.materialize(forgeUrl, baseBranch, cwd, d.runner, existingClone);
4988
+ console.error(`[remote] Base branch: ${baseBranch}`);
4989
+ const materialized = await d.materialize(
4990
+ forgeUrl,
4991
+ baseBranch,
4992
+ cwd,
4993
+ d.runner,
4994
+ existingClone,
4995
+ lifetime
4996
+ );
3035
4997
  let fetchedThreads = [];
3036
4998
  let threadSyncAvailable = false;
3037
- if (cliAvailable) {
4999
+ if (cliAvailable || threadsRequired) {
3038
5000
  try {
3039
- fetchedThreads = await provider.fetchThreads(forgeUrl);
5001
+ fetchedThreads = await provider.fetchThreads(forgeUrl, {
5002
+ includeResolved: options.includeResolved ?? false
5003
+ });
3040
5004
  threadSyncAvailable = true;
3041
5005
  } catch (error) {
5006
+ if (threadsRequired || isCommandCancelled(error)) {
5007
+ await materialized.cleanup();
5008
+ if (error instanceof ForgeCliUnavailableError) {
5009
+ throw new Error(
5010
+ `Cannot fetch discussion threads: ${error.message}
5011
+ This requires the ${error.cli} CLI to be installed and authenticated.`
5012
+ );
5013
+ }
5014
+ throw error;
5015
+ }
3042
5016
  const message = error instanceof Error ? error.message : String(error);
3043
5017
  console.error(
3044
5018
  `[remote] thread sync unavailable \u2014 continuing without forge threads: ${message}`
@@ -3049,6 +5023,10 @@ async function startRemoteSession(url, cwd, deps = {}) {
3049
5023
  "[remote] thread sync unavailable \u2014 forge CLI missing, continuing without forge threads."
3050
5024
  );
3051
5025
  }
5026
+ if (signal?.aborted) {
5027
+ await materialized.cleanup();
5028
+ throwIfAborted(signal, "threads");
5029
+ }
3052
5030
  return {
3053
5031
  forgeUrl,
3054
5032
  repoPath: materialized.repoPath,
@@ -3065,41 +5043,70 @@ async function startRemoteSession(url, cwd, deps = {}) {
3065
5043
  // into it; the front end needs the fact, not the path.
3066
5044
  temporaryClone: materialized.mode === "temp-clone"
3067
5045
  },
3068
- fetchedComments: mapThreadsToReviewComments(fetchedThreads),
3069
5046
  fetchedThreads
3070
5047
  };
3071
5048
  }
3072
- async function bootstrapRemoteDiff(url, cwd, ignorePatterns, deps = {}) {
3073
- const d = { ...defaultDeps, ...deps };
3074
- const started = await startRemoteSession(url, cwd, d);
3075
- let files;
3076
- let repository;
3077
- try {
3078
- ({ files, repository } = await d.loadDiff(started.gitDiffArgs, started.repoPath));
3079
- } catch (error) {
3080
- started.cleanup();
3081
- throw error;
3082
- }
5049
+ async function loadRemoteReview(session, ignorePatterns, loadDiff = defaultRemoteSessionDeps.loadDiff, options = {}) {
5050
+ throwIfAborted(options.signal, "load");
5051
+ const { files, repository, diagnostics, identity } = await loadDiff(
5052
+ session.gitDiffArgs,
5053
+ session.repoPath
5054
+ );
5055
+ throwIfAborted(options.signal, "load");
3083
5056
  const shouldKeep = createIgnoreFilter(ignorePatterns);
3084
5057
  const filteredFiles = files.filter((f) => shouldKeep(f.newPath || f.oldPath));
3085
- const session = {
3086
- ...started,
3087
- fetchedComments: mapThreadsToReviewComments(started.fetchedThreads, filteredFiles)
3088
- };
3089
5058
  return {
3090
- session,
3091
- payload: {
3092
- files: filteredFiles,
3093
- source: {
3094
- type: "git",
3095
- // Same renderer the git-mode path uses, so expand-context can
3096
- // tokenize this string back into the exact argv.
3097
- gitDiffArgs: formatGitDiffArgs(session.gitDiffArgs),
3098
- repository
3099
- },
3100
- remote: session.remote
3101
- }
5059
+ files: filteredFiles,
5060
+ repository,
5061
+ diagnostics: diagnostics ?? [],
5062
+ comments: mapThreadsToReviewComments(
5063
+ session.fetchedThreads,
5064
+ filteredFiles,
5065
+ session.remote.remoteHeadSha
5066
+ ),
5067
+ ...identity ? { identity } : {}
5068
+ };
5069
+ }
5070
+ function remoteSourceIdentity(started, loaded, cwd) {
5071
+ const resolved = loaded.identity ?? {
5072
+ sourceRoot: canonicalSourcePath(loaded.repository),
5073
+ gitDiffArgv: [...started.gitDiffArgs],
5074
+ pathPrefix: "",
5075
+ oldSide: { kind: "unknown", reason: "the merge base was not resolved" },
5076
+ newSide: { kind: "commit", sha: started.remote.remoteHeadSha }
3102
5077
  };
5078
+ return { ...resolved, mode: "remote", invocationCwd: cwd };
5079
+ }
5080
+ async function bootstrapRemoteDiff(url, cwd, ignorePatterns, deps = {}, options = {}) {
5081
+ const d = { ...defaultRemoteSessionDeps, ...deps };
5082
+ const started = await startRemoteSession(url, cwd, d, { signal: options.signal });
5083
+ try {
5084
+ const loaded = await loadRemoteReview(started, ignorePatterns, d.loadDiff, options);
5085
+ for (const diagnostic of loaded.diagnostics) {
5086
+ console.error(`[remote] Diff diagnostic: ${diagnostic}`);
5087
+ }
5088
+ const session = { ...started, fetchedComments: loaded.comments };
5089
+ return {
5090
+ session,
5091
+ identity: remoteSourceIdentity(started, loaded, cwd),
5092
+ payload: {
5093
+ files: loaded.files,
5094
+ source: {
5095
+ type: "git",
5096
+ // Same renderer the git-mode path uses, so expand-context can
5097
+ // tokenize this string back into the exact argv.
5098
+ gitDiffArgs: formatGitDiffArgs(session.gitDiffArgs),
5099
+ repository: loaded.repository
5100
+ },
5101
+ remote: session.remote,
5102
+ // So the renderer never mistakes a failed load for "no changes".
5103
+ ...loaded.diagnostics.length > 0 ? { diagnostics: loaded.diagnostics } : {}
5104
+ }
5105
+ };
5106
+ } catch (error) {
5107
+ await started.cleanup();
5108
+ throw error;
5109
+ }
3103
5110
  }
3104
5111
  function mergeRemoteThreads(resumed, fetched) {
3105
5112
  const resumedRemoteIds = new Set(
@@ -3136,23 +5143,11 @@ function computeRemoteDrift(recordedHeadSha, liveHeadSha) {
3136
5143
  }
3137
5144
 
3138
5145
  // src/fetch-comments.ts
3139
- import { writeFileSync as writeFileSync3 } from "fs";
3140
- import { resolve as resolve6 } from "path";
3141
- function defaultDeps2() {
5146
+ function defaultDeps() {
3142
5147
  return {
3143
- runner: defaultGitRunner,
3144
- createProvider: (forge, runner) => forge === "github" ? createGitHubProvider(runner) : createGitLabProvider(runner),
3145
- detectExistingClone,
3146
- materialize,
3147
- resolveRemoteDefaultBranch,
3148
- loadDiffFiles: async (repoPath, baseSha, headSha) => (
3149
- // Triple-dot: diff from the merge base, matching how forges present a
3150
- // PR/MR diff. Runs inside the materialized clone.
3151
- parseDiff(await runGitDiffAsync([`${baseSha}...${headSha}`], repoPath))
3152
- ),
3153
- serialize: serializeReview,
3154
- writeFile: (path4, content) => writeFileSync3(path4, content, "utf-8"),
3155
- loadConfig,
5148
+ ...defaultRemoteSessionDeps,
5149
+ publish: publishReview,
5150
+ loadConfig: loadConfigWithProvenance,
3156
5151
  now: () => /* @__PURE__ */ new Date()
3157
5152
  };
3158
5153
  }
@@ -3169,18 +5164,18 @@ function buildRemoteReviewState(args) {
3169
5164
  const files = [];
3170
5165
  const diffPaths = /* @__PURE__ */ new Set();
3171
5166
  for (const diffFile of args.diffFiles) {
3172
- const path4 = diffFile.changeType === "deleted" ? diffFile.oldPath : diffFile.newPath;
3173
- diffPaths.add(path4);
5167
+ const path10 = diffFile.changeType === "deleted" ? diffFile.oldPath : diffFile.newPath;
5168
+ diffPaths.add(path10);
3174
5169
  files.push({
3175
- path: path4,
5170
+ path: path10,
3176
5171
  changeType: diffFile.changeType,
3177
5172
  viewed: false,
3178
- comments: commentsByPath.get(path4) ?? []
5173
+ comments: commentsByPath.get(path10) ?? []
3179
5174
  });
3180
5175
  }
3181
- for (const [path4, comments] of commentsByPath) {
3182
- if (path4 === REVIEW_LEVEL_FILE_PATH || diffPaths.has(path4)) continue;
3183
- files.push({ path: path4, changeType: "modified", viewed: false, comments });
5176
+ for (const [path10, comments] of commentsByPath) {
5177
+ if (path10 === REVIEW_LEVEL_FILE_PATH || diffPaths.has(path10)) continue;
5178
+ files.push({ path: path10, changeType: "modified", viewed: false, comments });
3184
5179
  }
3185
5180
  const reviewLevel = commentsByPath.get(REVIEW_LEVEL_FILE_PATH);
3186
5181
  if (reviewLevel && reviewLevel.length > 0) {
@@ -3202,102 +5197,103 @@ function buildRemoteReviewState(args) {
3202
5197
  };
3203
5198
  }
3204
5199
  async function runFetchComments(url, options = {}) {
3205
- const deps = { ...defaultDeps2(), ...options.deps };
5200
+ const deps = { ...defaultDeps(), ...options.deps };
3206
5201
  const cwd = options.cwd ?? process.cwd();
3207
- const forgeUrl = parseForgeUrl(url);
3208
- if (forgeUrl === null) {
3209
- throw new Error(
3210
- `Not a recognized pull/merge request URL: ${url}
3211
- Expected a GitHub PR URL (\u2026/pull/N) or a GitLab MR URL (\u2026/-/merge_requests/N).`
3212
- );
3213
- }
3214
- const provider = deps.createProvider(forgeUrl.forge, deps.runner);
3215
- let baseBranch;
3216
- let existingClone;
3217
- try {
3218
- baseBranch = await provider.fetchBaseBranch(forgeUrl);
3219
- } catch (error) {
3220
- if (!(error instanceof ForgeCliUnavailableError)) throw error;
3221
- console.error(`[fetch-comments] ${error.message}`);
3222
- console.error(
3223
- `[fetch-comments] ${error.cli} unavailable for the base-branch lookup \u2014 falling back to the remote default branch via git ls-remote.`
3224
- );
3225
- existingClone = await deps.detectExistingClone(forgeUrl, cwd, deps.runner);
3226
- baseBranch = await deps.resolveRemoteDefaultBranch(forgeUrl, deps.runner, existingClone);
3227
- }
3228
- console.error(`[fetch-comments] Base branch: ${baseBranch}`);
3229
- const materialized = await deps.materialize(
3230
- forgeUrl,
3231
- baseBranch,
3232
- cwd,
3233
- deps.runner,
3234
- existingClone
3235
- );
5202
+ const lifetime = { signal: options.signal };
5203
+ const session = await startRemoteSession(url, cwd, deps, {
5204
+ ...lifetime,
5205
+ includeResolved: options.includeResolved ?? false,
5206
+ threads: "required"
5207
+ });
3236
5208
  try {
3237
- let threads;
3238
- try {
3239
- threads = await provider.fetchThreads(forgeUrl, {
3240
- includeResolved: options.includeResolved ?? false
3241
- });
3242
- } catch (error) {
3243
- if (error instanceof ForgeCliUnavailableError) {
3244
- throw new Error(
3245
- `Cannot fetch discussion threads: ${error.message}
3246
- fetch-comments requires the ${error.cli} CLI to be installed and authenticated.`
3247
- );
3248
- }
3249
- throw error;
5209
+ console.error(`[fetch-comments] Fetched ${session.fetchedThreads.length} threads`);
5210
+ const loadedConfig = deps.loadConfig();
5211
+ const config = loadedConfig.config;
5212
+ const loaded = await loadRemoteReview(session, config.ignore ?? [], deps.loadDiff, lifetime);
5213
+ for (const diagnostic of loaded.diagnostics) {
5214
+ console.error(`[fetch-comments] Diff diagnostic: ${diagnostic}`);
3250
5215
  }
3251
- console.error(`[fetch-comments] Fetched ${threads.length} threads`);
3252
- const diffFiles = await deps.loadDiffFiles(
3253
- materialized.repoPath,
3254
- materialized.baseSha,
3255
- materialized.headSha
3256
- );
3257
- const comments = mapThreadsToReviewComments(threads, diffFiles);
3258
5216
  const state = buildRemoteReviewState({
3259
5217
  remoteUrl: url,
3260
- forge: forgeUrl.forge,
3261
- baseSha: materialized.baseSha,
3262
- headSha: materialized.headSha,
3263
- diffFiles,
3264
- comments,
5218
+ forge: session.forgeUrl.forge,
5219
+ baseSha: session.remote.remoteBaseSha,
5220
+ headSha: session.remote.remoteHeadSha,
5221
+ diffFiles: loaded.files,
5222
+ comments: loaded.comments,
3265
5223
  timestamp: deps.now().toISOString()
3266
5224
  });
3267
- const config = deps.loadConfig();
3268
- const outputPath = resolve6(cwd, config.outputFile);
3269
- const xml = await deps.serialize(state, outputPath);
3270
- deps.writeFile(outputPath, xml + "\n");
3271
- console.error(`[fetch-comments] ${comments.length} threads written to ${outputPath}`);
5225
+ const target = resolveOutputTarget(null, loadedConfig, cwd);
5226
+ await deps.publish(state, target.path, publishOptionsFor(target));
5227
+ console.error(`[fetch-comments] ${loaded.comments.length} threads written to ${target.path}`);
3272
5228
  } finally {
3273
- materialized.cleanup();
5229
+ await session.cleanup();
3274
5230
  }
3275
5231
  }
3276
5232
  export {
5233
+ ASSET_DIR_NAME,
5234
+ ApplicationOptionError,
5235
+ AttachmentRelocationError,
5236
+ BINARY_SNIFF_BYTES,
5237
+ CommandCancelledError,
5238
+ ConfiguredDiffArgsError,
5239
+ DEFAULT_GIT_COMMAND_TIMEOUT_MS,
5240
+ DEFAULT_SOURCE_BUDGETS,
3277
5241
  ForgeCliUnavailableError,
3278
5242
  GUIDE_XSD_SCHEMA,
3279
5243
  IMPLICIT_GUIDE_GROUP_NAME,
5244
+ MAX_GIT_DIFF_OUTPUT_BYTES,
5245
+ MAX_GUIDE_BYTES,
5246
+ MAX_IMAGE_BYTES,
5247
+ MAX_RESUME_ATTACHMENTS,
5248
+ MAX_RESUME_XML_BYTES,
5249
+ MAX_SOURCE_ENTRIES,
5250
+ MAX_SOURCE_FILE_BYTES,
5251
+ MAX_SOURCE_TOTAL_BYTES,
5252
+ PARSER_COMPATIBLE_DIFF_FLAGS,
5253
+ PARSER_COMPATIBLE_GIT_CONFIG,
3280
5254
  REVIEW_LEVEL_FILE_PATH,
5255
+ ReviewPublishError,
5256
+ ReviewXmlError,
5257
+ SafeFsError,
5258
+ XmlIllegalCharacterError,
3281
5259
  applyRemoteProvenance,
3282
5260
  applyStagedUntrackedDefault,
3283
5261
  applySuggestion,
3284
5262
  applySuggestionForSession,
5263
+ assertNoSymlinkAncestors,
5264
+ atomicReplace,
5265
+ authorizeAttachmentReference,
5266
+ authorizeReviewedPath,
3285
5267
  bootstrapRemoteDiff,
3286
5268
  buildRemoteReviewState,
5269
+ canonicalSourcePath,
3287
5270
  checkWritability,
5271
+ classifyFsError,
5272
+ classifyGitDiffArgs,
5273
+ commitDiffData,
3288
5274
  commitReviewStart,
3289
5275
  computePayloadStats,
3290
5276
  computeRemoteDrift,
5277
+ consumesNextArgument,
3291
5278
  countTotalLines,
3292
5279
  createGitHubProvider,
3293
5280
  createGitLabProvider,
3294
5281
  createIgnoreFilter,
3295
5282
  createReviewSession,
5283
+ dedupeUntrackedByPath,
3296
5284
  defaultGitRunner,
5285
+ defaultRemoteSessionDeps,
3297
5286
  deriveGuidePath,
5287
+ describeDiffPathRelativity,
5288
+ describeGitDiffSides,
3298
5289
  detectExistingClone,
3299
5290
  determineMode,
3300
5291
  expandContext,
5292
+ extractApplicationOptions,
5293
+ findUnsupportedGitDiffOptions,
5294
+ findWriteCapableGitDiffOptions,
5295
+ formatBytes,
5296
+ formatGitDiffArgs,
3301
5297
  generateSyntheticDiffs,
3302
5298
  generateUntrackedDiffs,
3303
5299
  getConfigLoad,
@@ -3306,45 +5302,79 @@ export {
3306
5302
  getGitDiffStats,
3307
5303
  getLanguageFromPath,
3308
5304
  getRenderedTextMode,
3309
- getRepoRoot,
3310
5305
  getRepoRootAsync,
3311
5306
  getResumeLoad,
3312
5307
  getUntrackedFilesAsync,
5308
+ inspectOutputPath,
5309
+ inspectReplaceTarget,
5310
+ isCommandCancelled,
3313
5311
  isHtmlFile,
3314
5312
  isMarkdownFile,
3315
5313
  isPreviewableImage,
3316
5314
  isPreviewableRenderedText,
3317
5315
  isPreviewableSvg,
5316
+ isRepositoryControlPath,
3318
5317
  loadConfig,
5318
+ loadConfigWithProvenance,
3319
5319
  loadGitDiffWithUntracked,
3320
5320
  loadGuide,
3321
5321
  loadImage,
5322
+ loadLocalReview,
5323
+ loadRemoteReview,
5324
+ loadResumeDocument,
5325
+ loadSyntheticFiles,
5326
+ locateReviewedFile,
3322
5327
  mapThreadsToReviewComments,
3323
5328
  materialize,
3324
5329
  mergeRemoteThreads,
5330
+ nodeFsLayer,
3325
5331
  normalizeGitDiffArgs,
5332
+ parseAttachmentReference,
3326
5333
  parseDiff,
5334
+ parseDiffWithDiagnostics,
3327
5335
  parseForgeUrl,
3328
5336
  parseGuideXml,
3329
5337
  parseReviewXml,
3330
5338
  parseReviewXmlString,
3331
5339
  prepareDirectoryReview,
3332
5340
  preparePayload,
5341
+ publishOptionsFor,
5342
+ publishReview,
5343
+ readAssetFile,
3333
5344
  readAttachment,
5345
+ readFileWithinBudget,
5346
+ readFileWithinBudgetSync,
5347
+ readReviewedContent,
3334
5348
  reconcileGuide,
5349
+ recordResumedAttachments,
5350
+ relocateAttachments,
3335
5351
  resolveApplyDestination,
5352
+ resolveAttachmentOrigins,
5353
+ resolveGitSourceIdentity,
3336
5354
  resolveGuidePath,
5355
+ resolveLocalSourceIdentity,
5356
+ resolveOutputTarget,
3337
5357
  resolveRemoteDefaultBranch,
5358
+ resolveReviewedPathPrefix,
3338
5359
  resolveSourceBaseDir,
5360
+ resolveSourceBudgets,
5361
+ resolveStartupDiffArgs,
5362
+ resolveStartupSource,
5363
+ rootRelativeReviewedPath,
3339
5364
  runFetchComments,
3340
- runGitDiff,
3341
5365
  runGitDiffAsync,
5366
+ sameFile,
3342
5367
  scanDirectory,
3343
5368
  scanFile,
3344
5369
  serializeReview,
5370
+ snapshotIdentity,
3345
5371
  startRemoteSession,
3346
5372
  submitReviewState,
3347
5373
  takeReviewState,
3348
- validateGitAvailable
5374
+ tokenizeGitDiffArgs,
5375
+ validateLineAnchor,
5376
+ validateLineRange,
5377
+ withParserCompatibleDiffArgs,
5378
+ writeExclusiveNoFollow
3349
5379
  };
3350
5380
  //# sourceMappingURL=index.js.map