@self-review/core 1.44.0 → 2.0.2

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
 
@@ -646,27 +747,29 @@ function extFromMediaType(mediaType) {
646
747
  };
647
748
  return map[mediaType] || "png";
648
749
  }
649
- function persistAttachments(attachments, idPrefix, assetDir, onWrite) {
750
+ function assetNameComponent(idPrefix) {
751
+ return String(idPrefix ?? "").replace(/[^A-Za-z0-9_-]/g, "_");
752
+ }
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) {
650
756
  if (!attachments?.length) return attachments;
651
757
  return attachments.map((att, index) => {
652
758
  if (!att.data) return att;
653
- onWrite();
654
759
  const ext = extFromMediaType(att.mediaType);
655
- const fileName = `${idPrefix}-${index}.${ext}`;
656
- const relativePath = `.self-review-assets/${fileName}`;
657
- if (!fs.existsSync(assetDir)) {
658
- fs.mkdirSync(assetDir, { recursive: true });
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)) {
764
+ throw new Error(`Refusing to write an attachment outside ${assetDir}: ${fileName}`);
659
765
  }
660
- fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));
766
+ assets.push({ relativePath, absolutePath, data: att.data });
661
767
  return { ...att, fileName: relativePath, data: void 0 };
662
768
  });
663
769
  }
664
- function writeAttachments(state, outputFilePath) {
665
- const assetDir = path.join(path.dirname(outputFilePath), ".self-review-assets");
666
- let hasAttachments = false;
667
- const markWritten = () => {
668
- hasAttachments = true;
669
- };
770
+ function stageAttachments(state, outputFilePath, assetName) {
771
+ const assetDir = path.join(path.dirname(outputFilePath), ASSET_DIR_NAME);
772
+ const assets = [];
670
773
  const updatedFiles = state.files.map((file) => ({
671
774
  ...file,
672
775
  // Every comment is walked, including one with no attachments of its own:
@@ -674,43 +777,43 @@ function writeAttachments(state, outputFilePath) {
674
777
  // own list would drop those blobs without a word.
675
778
  comments: file.comments.map((comment) => ({
676
779
  ...comment,
677
- attachments: persistAttachments(comment.attachments, comment.id, assetDir, markWritten),
780
+ attachments: stageAttachmentList(
781
+ comment.attachments,
782
+ comment.id,
783
+ assetDir,
784
+ assetName,
785
+ assets
786
+ ),
678
787
  ...comment.replies ? {
679
788
  replies: comment.replies.map((reply) => ({
680
789
  ...reply,
681
- attachments: persistAttachments(
790
+ attachments: stageAttachmentList(
682
791
  reply.attachments,
683
792
  `${comment.id}-r-${reply.id}`,
684
793
  assetDir,
685
- markWritten
794
+ assetName,
795
+ assets
686
796
  )
687
797
  }))
688
798
  } : {}
689
799
  }))
690
800
  }));
691
- if (hasAttachments) {
692
- console.error(`[main] Wrote attachment files to ${assetDir}`);
693
- }
694
- return { ...state, files: updatedFiles };
801
+ return { state: { ...state, files: updatedFiles }, assets };
695
802
  }
696
- async function serializeReview(state, outputFilePath) {
697
- const processedState = writeAttachments(state, outputFilePath);
698
- 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;
699
811
  try {
700
- const validationResult = await validateXML({
812
+ validationResult = await validateXML({
701
813
  xml: [{ fileName: "review.xml", contents: xml }],
702
814
  schema: [{ fileName: "self-review-v3.xsd", contents: XSD_SCHEMA }]
703
815
  });
704
- if (!validationResult.valid) {
705
- const errors = validationResult.errors || [];
706
- console.error("XML validation failed:");
707
- errors.forEach((err) => console.error(` ${err}`));
708
- throw new Error("Generated XML does not conform to schema");
709
- }
710
816
  } catch (error) {
711
- if (error instanceof Error && error.message === "Generated XML does not conform to schema") {
712
- throw error;
713
- }
714
817
  if (error instanceof Error) {
715
818
  console.error(
716
819
  `[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`
@@ -720,30 +823,49 @@ async function serializeReview(state, outputFilePath) {
720
823
  "[main] XML validation infrastructure failed - emitting XML without validation"
721
824
  );
722
825
  }
723
- 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
+ );
724
837
  }
725
- 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);
726
848
  }
727
849
  function buildSourceAttributes(state) {
728
850
  const source = state.source;
729
851
  if (source.type === "git") {
730
- 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" })}"`;
731
853
  }
732
854
  if (source.type === "directory" || source.type === "file") {
733
- return ` source-path="${escapeXml(source.sourcePath)}"`;
855
+ return ` source-path="${attr(source.sourcePath, { field: "source-path" })}"`;
734
856
  }
735
857
  return "";
736
858
  }
737
859
  function buildRemoteAttributes(state) {
738
860
  const attrs = [];
739
861
  if (state.remoteUrl) {
740
- attrs.push(`remote-url="${escapeXml(state.remoteUrl)}"`);
862
+ attrs.push(`remote-url="${attr(state.remoteUrl, { field: "remote-url" })}"`);
741
863
  }
742
864
  if (state.remoteBaseSha) {
743
- attrs.push(`remote-base-sha="${escapeXml(state.remoteBaseSha)}"`);
865
+ attrs.push(`remote-base-sha="${attr(state.remoteBaseSha, { field: "remote-base-sha" })}"`);
744
866
  }
745
867
  if (state.remoteHeadSha) {
746
- attrs.push(`remote-head-sha="${escapeXml(state.remoteHeadSha)}"`);
868
+ attrs.push(`remote-head-sha="${attr(state.remoteHeadSha, { field: "remote-head-sha" })}"`);
747
869
  }
748
870
  if (state.remoteForge) {
749
871
  attrs.push(`remote-forge="${state.remoteForge}"`);
@@ -756,7 +878,7 @@ function buildXml(state) {
756
878
  const sourceAttrs = buildSourceAttributes(state);
757
879
  const remoteAttrs = buildRemoteAttributes(state);
758
880
  lines.push(
759
- `<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}>`
760
882
  );
761
883
  for (const file of state.files) {
762
884
  lines.push(...buildFileXml(file));
@@ -766,24 +888,30 @@ function buildXml(state) {
766
888
  }
767
889
  function buildFileXml(file) {
768
890
  const lines = [];
891
+ const pathAttr = attr(file.path, { field: "path", filePath: file.path });
769
892
  if (file.comments.length === 0) {
770
893
  lines.push(
771
- ` <file path="${escapeXml(file.path)}" change-type="${file.changeType}" viewed="${file.viewed}" />`
894
+ ` <file path="${pathAttr}" change-type="${file.changeType}" viewed="${file.viewed}" />`
772
895
  );
773
896
  } else {
774
897
  lines.push(
775
- ` <file path="${escapeXml(file.path)}" change-type="${file.changeType}" viewed="${file.viewed}">`
898
+ ` <file path="${pathAttr}" change-type="${file.changeType}" viewed="${file.viewed}">`
776
899
  );
777
900
  for (const comment of file.comments) {
778
- lines.push(...buildCommentXml(comment));
901
+ lines.push(...buildCommentXml(comment, file.path));
779
902
  }
780
903
  lines.push(" </file>");
781
904
  }
782
905
  return lines;
783
906
  }
784
- function buildCommentXml(comment) {
907
+ function buildCommentXml(comment, filePath) {
785
908
  const lines = [];
786
909
  const attrs = [];
910
+ const at = (field) => ({
911
+ field,
912
+ filePath,
913
+ commentId: comment.id
914
+ });
787
915
  if (comment.lineRange) {
788
916
  if (comment.lineRange.side === "old") {
789
917
  attrs.push(`old-line-start="${comment.lineRange.start}"`);
@@ -794,7 +922,7 @@ function buildCommentXml(comment) {
794
922
  }
795
923
  }
796
924
  if (comment.author) {
797
- attrs.push(`author="${escapeXml(comment.author)}"`);
925
+ attrs.push(`author="${attr(comment.author, at("author"))}"`);
798
926
  }
799
927
  if (comment.severity) {
800
928
  attrs.push(`severity="${comment.severity}"`);
@@ -803,195 +931,354 @@ function buildCommentXml(comment) {
803
931
  attrs.push(`confidence="${comment.confidence}"`);
804
932
  }
805
933
  if (comment.remoteId) {
806
- attrs.push(`remote-id="${escapeXml(comment.remoteId)}"`);
934
+ attrs.push(`remote-id="${attr(comment.remoteId, at("remote-id"))}"`);
807
935
  }
808
936
  const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
809
937
  lines.push(` <comment${attrStr}>`);
810
- lines.push(` <body>${escapeXml(comment.body)}</body>`);
811
- 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>`);
812
940
  if (comment.suggestion) {
813
941
  lines.push(" <suggestion>");
814
942
  lines.push(
815
- ` <original-code>${escapeXml(comment.suggestion.originalCode)}</original-code>`
943
+ ` <original-code>${text(comment.suggestion.originalCode, at("original-code"))}</original-code>`
816
944
  );
817
945
  lines.push(
818
- ` <proposed-code>${escapeXml(comment.suggestion.proposedCode)}</proposed-code>`
946
+ ` <proposed-code>${text(comment.suggestion.proposedCode, at("proposed-code"))}</proposed-code>`
819
947
  );
820
948
  lines.push(" </suggestion>");
821
949
  }
822
- lines.push(...buildAttachmentXml(comment.attachments, " "));
950
+ lines.push(...buildAttachmentXml(comment.attachments, " ", at("attachment")));
823
951
  for (const reply of comment.replies ?? []) {
824
- lines.push(...buildReplyXml(reply));
952
+ lines.push(...buildReplyXml(reply, filePath, comment.id));
825
953
  }
826
954
  lines.push(" </comment>");
827
955
  return lines;
828
956
  }
829
- function buildAttachmentXml(attachments, indent) {
957
+ function buildAttachmentXml(attachments, indent, owner) {
830
958
  if (!attachments?.length) return [];
831
959
  return attachments.map(
832
- (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" })}" />`
833
961
  );
834
962
  }
835
- function buildReplyXml(reply) {
963
+ function buildReplyXml(reply, filePath, commentId) {
836
964
  const attrs = [];
965
+ const at = (field) => ({
966
+ field,
967
+ filePath,
968
+ commentId,
969
+ replyId: reply.id
970
+ });
837
971
  if (reply.author) {
838
- attrs.push(`author="${escapeXml(reply.author)}"`);
972
+ attrs.push(`author="${attr(reply.author, at("author"))}"`);
839
973
  }
840
974
  if (reply.remoteId) {
841
- attrs.push(`remote-id="${escapeXml(reply.remoteId)}"`);
975
+ attrs.push(`remote-id="${attr(reply.remoteId, at("remote-id"))}"`);
842
976
  }
843
977
  const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
844
978
  return [
845
979
  ` <reply${attrStr}>`,
846
- ` <body>${escapeXml(reply.body)}</body>`,
847
- ...buildAttachmentXml(reply.attachments, " "),
980
+ ` <body>${text(reply.body, at("body"))}</body>`,
981
+ ...buildAttachmentXml(reply.attachments, " ", at("attachment")),
848
982
  " </reply>"
849
983
  ];
850
984
  }
851
- function escapeXml(str) {
852
- 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);
853
1081
  }
854
1082
 
855
1083
  // src/xml-parser.ts
856
- import { readFileSync } from "fs";
857
- import { XMLParser } from "fast-xml-parser";
858
1084
  var SEVERITY_VALUES = ["critical", "major", "minor", "info"];
859
1085
  var CONFIDENCE_VALUES = ["high", "medium", "low"];
860
1086
  var REMOTE_FORGE_VALUES = ["github", "gitlab"];
861
1087
  function parseReviewXml(xmlPath) {
1088
+ let read;
862
1089
  try {
863
- const xmlContent = readFileSync(xmlPath, "utf-8");
864
- return parseReviewXmlString(xmlContent);
1090
+ read = readFileWithinBudgetSync(xmlPath, MAX_RESUME_XML_BYTES);
865
1091
  } catch (error) {
866
- if (error instanceof Error) {
867
- console.error(`Error reading XML file: ${error.message}`);
868
- } else {
869
- console.error("Error reading XML file: unknown error");
870
- }
871
- 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
+ );
872
1104
  }
1105
+ return parseReviewXmlString(read.content.toString("utf-8"));
873
1106
  }
874
1107
  function parseReviewXmlString(xmlContent) {
875
1108
  const parser = new XMLParser({
876
1109
  ignoreAttributes: false,
877
1110
  attributeNamePrefix: "@_",
878
1111
  allowBooleanAttributes: true,
879
- 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
880
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;
881
1125
  try {
882
- const result = parser.parse(xmlContent);
883
- if (!result.review) {
884
- throw new Error("Invalid XML: missing <review> root element");
885
- }
886
- const review = result.review;
887
- const gitDiffArgs = review["@_git-diff-args"] || "";
888
- const source = parseSource(review);
889
- const comments = [];
890
- const viewedFiles = [];
891
- const files = toChildArray(review.file);
892
- for (const file of files) {
893
- const rawPath = file["@_path"];
894
- if (rawPath === void 0 || rawPath === null) continue;
895
- const filePath = String(rawPath);
896
- if (parseViewed(file["@_viewed"])) {
897
- viewedFiles.push(filePath);
898
- }
899
- const fileComments = toChildArray(file.comment);
900
- for (const comment of fileComments) {
901
- const reviewComment = {
902
- id: generateId(),
903
- filePath,
904
- lineRange: parseLineRange(comment),
905
- body: comment.body !== void 0 ? String(comment.body) : "",
906
- category: comment.category !== void 0 ? String(comment.category) : "",
907
- suggestion: parseSuggestion(comment),
908
- author: comment["@_author"] ? String(comment["@_author"]) : void 0,
909
- severity: parseEnumAttribute(comment["@_severity"], SEVERITY_VALUES),
910
- confidence: parseEnumAttribute(comment["@_confidence"], CONFIDENCE_VALUES),
911
- remoteId: parseStringAttribute(comment["@_remote-id"])
912
- };
913
- const attachments = parseAttachments(comment, reviewComment.id);
914
- if (attachments) reviewComment.attachments = attachments;
915
- const replies = parseReplies(comment);
916
- if (replies) reviewComment.replies = replies;
917
- comments.push(reviewComment);
918
- }
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);
919
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) {
920
1222
  return {
921
- comments,
922
- viewedFiles,
923
- gitDiffArgs,
924
- source,
925
- remoteUrl: parseStringAttribute(review["@_remote-url"]),
926
- remoteBaseSha: parseStringAttribute(review["@_remote-base-sha"]),
927
- remoteHeadSha: parseStringAttribute(review["@_remote-head-sha"]),
928
- remoteForge: parseEnumAttribute(review["@_remote-forge"], REMOTE_FORGE_VALUES)
1223
+ ok: false,
1224
+ reason: "suggestion is missing original-code or proposed-code",
1225
+ text: text_
929
1226
  };
930
- } catch (error) {
931
- if (error instanceof Error) {
932
- console.error(`Error parsing XML: ${error.message}`);
933
- } else {
934
- console.error("Error parsing XML: unknown error");
935
- }
936
- process.exit(1);
937
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];
938
1243
  }
939
1244
  function parseEnumAttribute(raw, allowed) {
940
1245
  if (raw === void 0 || raw === null) return void 0;
941
- const value = String(raw);
1246
+ const value = decodeXmlEntities(String(raw));
942
1247
  return allowed.includes(value) ? value : void 0;
943
1248
  }
944
- function parseStringAttribute(raw) {
945
- 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;
946
1262
  }
947
1263
  function parseViewed(raw) {
948
1264
  return raw === true || String(raw) === "true";
949
1265
  }
950
1266
  function parseSource(review) {
951
- const sourcePath = review["@_source-path"];
1267
+ const sourcePath = attribute(review, "@_source-path");
952
1268
  if (sourcePath) {
953
- return { type: "directory", sourcePath: String(sourcePath) };
1269
+ return { type: "directory", sourcePath };
954
1270
  }
955
- const gitDiffArgs = review["@_git-diff-args"];
956
- const repository = review["@_repository"];
1271
+ const gitDiffArgs = attribute(review, "@_git-diff-args");
1272
+ const repository = attribute(review, "@_repository");
957
1273
  if (gitDiffArgs !== void 0 || repository !== void 0) {
958
1274
  return {
959
1275
  type: "git",
960
- gitDiffArgs: String(gitDiffArgs || ""),
961
- repository: String(repository || "")
1276
+ gitDiffArgs: gitDiffArgs ?? "",
1277
+ repository: repository ?? ""
962
1278
  };
963
1279
  }
964
1280
  return { type: "welcome" };
965
1281
  }
966
- function parseLineRange(comment) {
967
- const hasOld = comment["@_old-line-start"] !== void 0 && comment["@_old-line-end"] !== void 0;
968
- const hasNew = comment["@_new-line-start"] !== void 0 && comment["@_new-line-end"] !== void 0;
969
- if (hasOld) {
970
- return {
971
- side: "old",
972
- start: parseInt(String(comment["@_old-line-start"]), 10),
973
- end: parseInt(String(comment["@_old-line-end"]), 10)
974
- };
975
- }
976
- if (hasNew) {
977
- return {
978
- side: "new",
979
- start: parseInt(String(comment["@_new-line-start"]), 10),
980
- end: parseInt(String(comment["@_new-line-end"]), 10)
981
- };
982
- }
983
- return null;
984
- }
985
- function parseSuggestion(comment) {
986
- if (!comment.suggestion) {
987
- return null;
988
- }
989
- const suggestion = comment.suggestion;
990
- return {
991
- originalCode: String(suggestion["original-code"] || ""),
992
- proposedCode: String(suggestion["proposed-code"] || "")
993
- };
994
- }
995
1282
  function toChildArray(raw) {
996
1283
  if (Array.isArray(raw)) return raw;
997
1284
  if (raw === void 0 || raw === null) return [];
@@ -1002,8 +1289,8 @@ function parseAttachments(node, idPrefix) {
1002
1289
  if (raw.length === 0) return void 0;
1003
1290
  return raw.map((att, i) => ({
1004
1291
  id: `${idPrefix}-att-${i}`,
1005
- fileName: String(att["@_path"] || ""),
1006
- mediaType: String(att["@_media-type"] || "image/png")
1292
+ fileName: attribute(att, "@_path") ?? "",
1293
+ mediaType: attribute(att, "@_media-type") ?? "image/png"
1007
1294
  }));
1008
1295
  }
1009
1296
  function parseReplies(comment) {
@@ -1013,136 +1300,1269 @@ function parseReplies(comment) {
1013
1300
  const id = generateId();
1014
1301
  const reply = {
1015
1302
  id,
1016
- body: node.body !== void 0 ? String(node.body) : "",
1017
- author: node["@_author"] ? String(node["@_author"]) : void 0,
1018
- remoteId: parseStringAttribute(node["@_remote-id"])
1303
+ body: text2(node, "body") ?? "",
1304
+ author: optionalAuthor(node),
1305
+ remoteId: attribute(node, "@_remote-id")
1019
1306
  };
1020
1307
  const attachments = parseAttachments(node, id);
1021
1308
  if (attachments) reply.attachments = attachments;
1022
1309
  return reply;
1023
1310
  });
1024
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
+ }
1025
1326
  function generateId() {
1026
1327
  return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
1027
1328
  }
1028
1329
 
1029
- // src/guide-schema.ts
1030
- var GUIDE_XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
1031
- <xs:schema
1032
- xmlns:xs="http://www.w3.org/2001/XMLSchema"
1033
- xmlns:sg="urn:self-review-guide:v1"
1034
- targetNamespace="urn:self-review-guide:v1"
1035
- elementFormDefault="qualified"
1036
- >
1037
-
1038
- <!--
1039
- self-review guide XML Schema v1
1040
- ===============================
1041
- Defines the walkthrough guide sidecar for the self-review application.
1042
- This schema is designed to be both machine-validated and fed to an LLM
1043
- so it can author valid guide documents from the schema alone.
1044
-
1045
- Key concepts:
1046
- - A <guide> is a read-only orientation aid generated BEFORE a review
1047
- starts. It lives next to the review output file and is discovered by
1048
- convention; it is never written by the review UI.
1049
- - The optional <overview> is short Markdown prose shown before the
1050
- first file, orienting the reviewer to the change as a whole.
1051
- - Each <group> names a set of files that belong together (for example
1052
- "Core change", "Tests", "Generated/mechanical") and explains, in one
1053
- line, why they are grouped and where they sit in the reading order.
1054
- - Each <file> inside a group points at one diff file by its
1055
- repository-relative path and carries a one-line description of the
1056
- role that file plays in the change.
1057
-
1058
- Ordering:
1059
- - Document order IS the reading order. Groups are presented in the
1060
- order they appear, and files within a group are presented in the
1061
- order they appear. There are no explicit ordering attributes; to
1062
- reorder, reorder the elements.
1063
-
1064
- Presentation only, never suppression:
1065
- - This vocabulary labels and orders content; it cannot hide it. There
1066
- is deliberately no element or attribute that hides, collapses, or
1067
- marks a file as skippable, and none may be added to v1. Files in the
1068
- diff that no group mentions remain fully visible in an implicit
1069
- "Everything else" group; files mentioned here but absent from the
1070
- diff are silently ignored.
1071
-
1072
- Tolerance:
1073
- - A missing, stale, or invalid guide degrades the consumer to its
1074
- normal ungrouped view. A guide can therefore never block or fail a
1075
- review, but an invalid guide is silently useless, so authors should
1076
- validate against this schema before writing the file.
1077
- -->
1078
-
1079
- <!-- ===== Root element ===== -->
1080
-
1081
- <xs:element name="guide" type="sg:GuideType">
1082
- <xs:annotation>
1083
- <xs:documentation>
1084
- Root element of a self-review walkthrough guide sidecar. Contains
1085
- an optional overview followed by zero or more ordered groups.
1086
- </xs:documentation>
1087
- </xs:annotation>
1088
- </xs:element>
1330
+ // src/review-publisher.ts
1331
+ import * as path5 from "path";
1089
1332
 
1090
- <!-- ===== 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
+ }
1091
1345
 
1092
- <xs:complexType name="GuideType">
1093
- <xs:annotation>
1094
- <xs:documentation>
1095
- The whole walkthrough guide. The optional metadata attributes
1096
- mirror the review schema's provenance attributes so a consumer can
1097
- sanity-check that the guide was generated for the diff it is being
1098
- shown next to; none of them are required and none affect
1099
- presentation.
1100
- </xs:documentation>
1101
- </xs:annotation>
1102
- <xs:sequence>
1103
- <xs:element name="overview" type="xs:string" minOccurs="0">
1104
- <xs:annotation>
1105
- <xs:documentation>
1106
- Review-level orientation prose shown before the first file.
1107
- Markdown formatting is allowed, including fenced code blocks;
1108
- a fenced code block labelled "mermaid" may be used for a
1109
- diagram of the change.
1110
- Keep it short: a few sentences saying what the change does and
1111
- where to start reading, not a restatement of every file.
1112
- </xs:documentation>
1113
- </xs:annotation>
1114
- </xs:element>
1115
- <xs:element name="group" type="sg:GroupType" minOccurs="0" maxOccurs="unbounded">
1116
- <xs:annotation>
1117
- <xs:documentation>
1118
- Ordered reading groups. The first group should hold the files
1119
- the reviewer must understand first (the core of the change);
1120
- later groups hold consequences, tests, and mechanical fallout.
1121
- </xs:documentation>
1122
- </xs:annotation>
1123
- </xs:element>
1124
- </xs:sequence>
1125
- <xs:attribute name="timestamp" type="xs:dateTime" use="optional">
1126
- <xs:annotation>
1127
- <xs:documentation>
1128
- ISO 8601 timestamp of when the guide was generated.
1129
- </xs:documentation>
1130
- </xs:annotation>
1131
- </xs:attribute>
1132
- <xs:attribute name="git-diff-args" type="xs:string" use="optional">
1133
- <xs:annotation>
1134
- <xs:documentation>
1135
- The git diff arguments the guide was generated against.
1136
- Example: "--staged", "main..feature-branch", "HEAD~3".
1137
- Present only when the guide describes a git diff.
1138
- </xs:documentation>
1139
- </xs:annotation>
1140
- </xs:attribute>
1141
- <xs:attribute name="repository" type="xs:string" use="optional">
1142
- <xs:annotation>
1143
- <xs:documentation>
1144
- Absolute path to the repository root the guide was generated in.
1145
- 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.
1146
2566
  </xs:documentation>
1147
2567
  </xs:annotation>
1148
2568
  </xs:attribute>
@@ -1307,18 +2727,32 @@ function reconcileGuide(guide, diffFilePaths) {
1307
2727
  });
1308
2728
  }
1309
2729
  }
1310
- const leftover = diffFilePaths.filter((path4) => !claimed.has(path4));
2730
+ const leftover = diffFilePaths.filter((path10) => !claimed.has(path10));
1311
2731
  if (leftover.length > 0) {
1312
2732
  resolved.push({
1313
2733
  name: IMPLICIT_GUIDE_GROUP_NAME,
1314
2734
  implicit: true,
1315
- files: leftover.map((path4) => ({ path: path4 }))
2735
+ files: leftover.map((path10) => ({ path: path10 }))
1316
2736
  });
1317
2737
  }
1318
2738
  return resolved;
1319
2739
  }
1320
2740
 
1321
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
+ }
1322
2756
  var ForgeCliUnavailableError = class extends Error {
1323
2757
  constructor(forge, cli, message) {
1324
2758
  super(message);
@@ -1363,8 +2797,8 @@ function parseForgeUrl(url) {
1363
2797
  }
1364
2798
 
1365
2799
  // src/directory-scanner.ts
1366
- import { readdir, stat } from "fs/promises";
1367
- 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";
1368
2802
 
1369
2803
  // src/ignore-filter.ts
1370
2804
  import ignore from "ignore";
@@ -1375,174 +2809,323 @@ function createIgnoreFilter(patterns) {
1375
2809
  }
1376
2810
 
1377
2811
  // src/directory-scanner.ts
1378
- async function scanDirectory(directoryPath, ignorePatterns = []) {
2812
+ async function scanDirectory(directoryPath, ignorePatterns = [], options = {}) {
2813
+ const budgets = resolveSourceBudgets(options.budgets);
1379
2814
  try {
1380
2815
  const dirStat = await stat(directoryPath);
1381
2816
  if (!dirStat.isDirectory()) {
1382
- console.error(`Error: "${directoryPath}" is not a directory`);
1383
- return [];
2817
+ return failed(`Cannot review "${directoryPath}": it is not a directory.`);
1384
2818
  }
1385
2819
  } catch (error) {
1386
- if (error instanceof Error) {
1387
- console.error(`Error accessing directory "${directoryPath}": ${error.message}`);
1388
- } else {
1389
- console.error(`Error accessing directory "${directoryPath}": unknown error`);
1390
- }
1391
- return [];
2820
+ return failed(`Cannot read directory "${directoryPath}": ${messageOf2(error)}`);
1392
2821
  }
1393
- const filePaths = [];
2822
+ const shouldKeep = createIgnoreFilter(ignorePatterns);
2823
+ let walk;
1394
2824
  try {
1395
- const entries = await readdir(directoryPath, {
1396
- recursive: true,
1397
- withFileTypes: true
1398
- });
1399
- for (const entry of entries) {
1400
- if (!entry.isFile()) {
1401
- continue;
1402
- }
1403
- const parentDir = entry.parentPath ?? entry.path;
1404
- const fullPath = join2(parentDir, entry.name);
1405
- const relativePath = relative(directoryPath, fullPath);
1406
- filePaths.push(relativePath);
1407
- }
2825
+ walk = await walkDirectory(directoryPath, shouldKeep, budgets.maxEntries);
1408
2826
  } catch (error) {
1409
- if (error instanceof Error) {
1410
- console.error(`Error reading directory "${directoryPath}": ${error.message}`);
1411
- } else {
1412
- console.error(`Error reading directory "${directoryPath}": unknown error`);
1413
- }
1414
- return [];
2827
+ return failed(`Cannot read directory "${directoryPath}": ${messageOf2(error)}`);
1415
2828
  }
1416
- filePaths.sort();
1417
- const shouldKeep = createIgnoreFilter(ignorePatterns);
1418
- const filteredPaths = filePaths.filter((p) => shouldKeep(p));
1419
- if (filteredPaths.length === 0) {
1420
- 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
+ };
1421
2838
  }
1422
- const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);
1423
- return parseDiff(diffText);
2839
+ walk.files.sort();
2840
+ if (walk.files.length === 0) {
2841
+ return { files: [], diagnostics: [], entryLimitExceeded: false };
2842
+ }
2843
+ const { files, diagnostics } = loadSyntheticFiles(walk.files, directoryPath, {
2844
+ budgets: options.budgets
2845
+ });
2846
+ return { files, diagnostics, entryLimitExceeded: false };
1424
2847
  }
1425
- async function scanFile(filePath) {
2848
+ async function scanFile(filePath, options = {}) {
1426
2849
  try {
1427
2850
  const fileStat = await stat(filePath);
1428
2851
  if (!fileStat.isFile()) {
1429
- console.error(`Error: "${filePath}" is not a file`);
1430
- return [];
2852
+ return failed(`Cannot review "${filePath}": it is not a regular file.`);
1431
2853
  }
1432
2854
  } catch (error) {
1433
- if (error instanceof Error) {
1434
- console.error(`Error accessing file "${filePath}": ${error.message}`);
1435
- } else {
1436
- 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
+ });
1437
2884
  }
1438
- return [];
1439
2885
  }
1440
- const fileName = basename(filePath);
1441
- const rootDir = dirname2(filePath);
1442
- const diffText = generateSyntheticDiffs([fileName], rootDir);
1443
- 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);
1444
2894
  }
1445
2895
 
1446
- // src/config.ts
1447
- import { readFileSync as readFileSync2, existsSync as existsSync2 } from "fs";
1448
- import { join as join3 } from "path";
1449
- import { homedir } from "os";
1450
- import { parse as parseYaml } from "yaml";
1451
- var defaults = {
1452
- theme: "system",
1453
- diffView: "split",
1454
- fontSize: 14,
1455
- outputFormat: "xml",
1456
- outputFile: "./review.xml",
1457
- ignore: [
1458
- ".git",
1459
- "node_modules",
1460
- "vendor",
1461
- ".vendor",
1462
- "__pycache__",
1463
- ".venv",
1464
- "venv",
1465
- ".env",
1466
- "dist",
1467
- "build",
1468
- ".next",
1469
- ".nuxt",
1470
- ".svelte-kit",
1471
- "target",
1472
- "*.min.js",
1473
- "*.min.css",
1474
- "package-lock.json",
1475
- "yarn.lock",
1476
- "pnpm-lock.yaml",
1477
- "composer.lock",
1478
- "Gemfile.lock",
1479
- "Cargo.lock",
1480
- "poetry.lock",
1481
- "go.sum"
1482
- ],
1483
- categories: [
1484
- {
1485
- name: "question",
1486
- description: "Clarification needed \u2014 not necessarily a problem",
1487
- color: "#805ad5"
1488
- },
1489
- {
1490
- name: "bug",
1491
- description: "Likely defect or incorrect behavior",
1492
- color: "#e53e3e"
1493
- },
1494
- {
1495
- name: "security",
1496
- description: "Security vulnerability or concern",
1497
- color: "#dd6b20"
1498
- },
1499
- {
1500
- name: "style",
1501
- description: "Code style, naming, or formatting issue",
1502
- color: "#3182ce"
1503
- },
1504
- {
1505
- name: "task",
1506
- description: "Action item or follow-up task",
1507
- color: "#38a169"
1508
- },
1509
- {
1510
- name: "nit",
1511
- description: "Minor nitpick, low priority",
1512
- 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);
1513
2947
  }
1514
- ],
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],
1515
3084
  defaultDiffArgs: "",
1516
3085
  showUntracked: true,
1517
3086
  showUntrackedExplicit: false,
1518
3087
  wordWrap: true,
1519
- maxFiles: 500,
1520
- maxTotalLines: 1e5
3088
+ maxFiles: DEFAULT_MAX_FILES,
3089
+ maxTotalLines: DEFAULT_MAX_TOTAL_LINES
1521
3090
  };
1522
- function loadConfig() {
3091
+
3092
+ // src/config.ts
3093
+ var defaults = DEFAULT_CONFIG;
3094
+ var CONFIG_KEYS = Object.keys(defaults);
3095
+ function loadConfigWithProvenance(options = {}) {
1523
3096
  let config = { ...defaults };
1524
- const userConfigPath = join3(homedir(), ".config", "self-review", "config.yaml");
1525
- if (existsSync2(userConfigPath)) {
1526
- try {
1527
- const userConfig = loadYamlConfig(userConfigPath);
1528
- config = mergeConfig(config, userConfig);
1529
- } catch (error) {
1530
- console.error(`Warning: Failed to load user config from ${userConfigPath}: ${error}`);
1531
- }
1532
- }
1533
- const projectConfigPath = join3(process.cwd(), ".self-review.yaml");
1534
- 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;
1535
3109
  try {
1536
- const projectConfig = loadYamlConfig(projectConfigPath);
1537
- 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);
1538
3116
  } catch (error) {
1539
- 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
+ );
1540
3120
  }
1541
3121
  }
1542
- return config;
3122
+ return { config, provenance, sources };
3123
+ }
3124
+ function loadConfig(options = {}) {
3125
+ return loadConfigWithProvenance(options).config;
1543
3126
  }
1544
- function loadYamlConfig(path4) {
1545
- const content = readFileSync2(path4, "utf-8");
3127
+ function loadYamlConfig(path10) {
3128
+ const content = readFileSync2(path10, "utf-8");
1546
3129
  const raw = parseYaml(content);
1547
3130
  if (raw === null || raw === void 0) {
1548
3131
  return {};
@@ -1621,9 +3204,9 @@ function mergeConfig(base, override) {
1621
3204
  }
1622
3205
 
1623
3206
  // src/payload-sizing.ts
1624
- import { execFile } from "child_process";
1625
- import { promisify } from "util";
1626
- var execFileAsync = promisify(execFile);
3207
+ import { execFile as execFile3 } from "child_process";
3208
+ import { promisify as promisify2 } from "util";
3209
+ var execFileAsync2 = promisify2(execFile3);
1627
3210
  function computePayloadStats(fileCount, totalLines, config) {
1628
3211
  const maxFiles = config.maxFiles;
1629
3212
  const maxTotalLines = config.maxTotalLines;
@@ -1648,7 +3231,7 @@ function countTotalLines(files) {
1648
3231
  }
1649
3232
  async function getGitDiffStats(args, repoRoot) {
1650
3233
  try {
1651
- const { stdout } = await execFileAsync("git", ["diff", "--numstat", ...args], {
3234
+ const { stdout } = await execFileAsync2("git", ["diff", "--numstat", ...args], {
1652
3235
  maxBuffer: 10 * 1024 * 1024,
1653
3236
  timeout: 15e3,
1654
3237
  cwd: repoRoot
@@ -1675,27 +3258,47 @@ async function getGitDiffStats(args, repoRoot) {
1675
3258
  }
1676
3259
  }
1677
3260
 
1678
- // src/fs-utils.ts
1679
- import { accessSync, constants as fsConstants } from "fs";
1680
- import { dirname as dirname3 } from "path";
1681
- function checkWritability(filePath) {
1682
- try {
1683
- const dir = dirname3(filePath);
1684
- accessSync(dir, fsConstants.W_OK);
1685
- return true;
1686
- } catch {
1687
- return false;
1688
- }
1689
- }
1690
-
1691
3261
  // src/apply-suggestion.ts
1692
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
1693
- import { isAbsolute, relative as relative2, resolve, sep } from "path";
3262
+ import * as path7 from "path";
3263
+ function isRepositoryControlPath(filePath) {
3264
+ return filePath.split(/[\\/]+/).some((segment) => segment.toLowerCase() === ".git");
3265
+ }
1694
3266
  function refuse(filePath, reason, detail) {
1695
3267
  return { status: "refused", filePath, reason, detail };
1696
3268
  }
1697
- function errorCode(error) {
1698
- 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;
1699
3302
  }
1700
3303
  function splitLines(content) {
1701
3304
  if (content === "") return [];
@@ -1703,11 +3306,43 @@ function splitLines(content) {
1703
3306
  if (lines[lines.length - 1] === "") lines.pop();
1704
3307
  return lines;
1705
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
+ }
1706
3314
  function isCrlfRegion(anchored) {
1707
3315
  return anchored.length > 0 && anchored.every((line) => line.endsWith("\r"));
1708
3316
  }
1709
- 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 = {}) {
1710
3344
  const { destinationRoot, filePath, lineRange, suggestion } = request;
3345
+ const fs3 = options.fs ?? nodeFsLayer;
1711
3346
  if (!lineRange) {
1712
3347
  return refuse(
1713
3348
  filePath,
@@ -1722,44 +3357,60 @@ function applySuggestion(request) {
1722
3357
  "This suggestion is anchored to deleted lines, which are not in the working file."
1723
3358
  );
1724
3359
  }
1725
- 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)) {
1726
3373
  return refuse(
1727
3374
  filePath,
1728
3375
  "destination-not-absolute",
1729
3376
  "The destination directory must be an absolute path."
1730
3377
  );
1731
3378
  }
1732
- const root = resolve(destinationRoot);
1733
- const absolutePath = resolve(root, filePath);
1734
- const rel = relative2(root, absolutePath);
1735
- if (isAbsolute(filePath) || rel === "" || rel === ".." || rel.startsWith(`..${sep}`)) {
3379
+ const rel = relativeWithinRoot(filePath);
3380
+ if (rel === null) {
1736
3381
  return refuse(
1737
3382
  filePath,
1738
3383
  "path-escapes-destination",
1739
3384
  "The file path resolves outside the destination directory."
1740
3385
  );
1741
3386
  }
1742
- 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;
1743
3395
  try {
1744
- buffer = readFileSync3(absolutePath);
3396
+ realRoot = fs3.realpathSync(path7.resolve(destinationRoot));
1745
3397
  } catch (error) {
1746
- const code = errorCode(error);
1747
- if (code === "ENOENT" || code === "ENOTDIR") {
1748
- return refuse(filePath, "file-missing", "The file is not in the destination directory.");
1749
- }
1750
3398
  return refuse(
1751
3399
  filePath,
1752
- "file-unreadable",
1753
- `The file could not be read (${code ?? "unknown"}).`
3400
+ "destination-missing",
3401
+ `The destination directory could not be resolved (${errnoOf(error) ?? "unknown"}).`
1754
3402
  );
1755
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;
1756
3408
  const content = buffer.toString("utf8");
1757
3409
  if (!Buffer.from(content, "utf8").equals(buffer)) {
1758
3410
  return refuse(filePath, "file-not-utf8", "The file is not valid UTF-8 text.");
1759
3411
  }
1760
3412
  const lines = splitLines(content);
1761
- const { start, end } = lineRange;
1762
- if (start < 1 || end < start || end > lines.length) {
3413
+ if (end > lines.length) {
1763
3414
  return refuse(
1764
3415
  filePath,
1765
3416
  "anchor-out-of-range",
@@ -1774,18 +3425,21 @@ function applySuggestion(request) {
1774
3425
  `Lines ${start}-${end} no longer match the code this suggestion was written against.`
1775
3426
  );
1776
3427
  }
1777
- const proposed = suggestion.proposedCode.split("\n");
3428
+ const proposed = proposalLines(suggestion.proposedCode);
1778
3429
  const replacement = isCrlfRegion(anchored) ? proposed.map((line) => line.endsWith("\r") ? line : `${line}\r`) : proposed;
1779
3430
  const updated = [...lines.slice(0, start - 1), ...replacement, ...lines.slice(end)];
1780
- const output = updated.join("\n") + (content.endsWith("\n") ? "\n" : "");
3431
+ const output = updated.length === 0 ? "" : updated.join("\n") + (content.endsWith("\n") ? "\n" : "");
1781
3432
  try {
1782
- 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
+ });
1783
3441
  } catch (error) {
1784
- return refuse(
1785
- filePath,
1786
- "write-failed",
1787
- `The file could not be written (${errorCode(error) ?? "unknown"}).`
1788
- );
3442
+ return refuseFsError(filePath, error, "write-failed");
1789
3443
  }
1790
3444
  return { status: "applied", filePath, absolutePath, replacedLines: anchored.length };
1791
3445
  }
@@ -1893,6 +3547,7 @@ async function runGh(runCommand, args) {
1893
3547
  try {
1894
3548
  result = await runCommand(GH_CLI, args);
1895
3549
  } catch (error) {
3550
+ if (isCommandCancelled(error)) throw error;
1896
3551
  const detail = error instanceof Error ? error.message : String(error);
1897
3552
  throw new ForgeCliUnavailableError("github", GH_CLI, `Failed to run the gh CLI: ${detail}`);
1898
3553
  }
@@ -2006,8 +3661,18 @@ function createGitHubProvider(runCommand) {
2006
3661
 
2007
3662
  // src/thread-mapper.ts
2008
3663
  var REVIEW_LEVEL_FILE_PATH = "";
2009
- function mapAnchorToLineRange(anchor) {
2010
- 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") {
2011
3676
  return null;
2012
3677
  }
2013
3678
  const { startLine, endLine } = anchor;
@@ -2081,8 +3746,8 @@ function readAnchoredLines(diffFiles, filePath, range) {
2081
3746
  }
2082
3747
  return found.length === range.end - range.start + 1 ? found.join("\n") : null;
2083
3748
  }
2084
- function extractSuggestion(body, filePath, range, diffFiles) {
2085
- if (!range) return null;
3749
+ function extractSuggestion(body, filePath, range, status, diffFiles) {
3750
+ if (!range || status !== "verified") return null;
2086
3751
  const blocks = findSuggestionBlocks(body);
2087
3752
  if (blocks.length !== 1) return null;
2088
3753
  const originalCode = readAnchoredLines(diffFiles, filePath, range);
@@ -2097,17 +3762,18 @@ function mapReply(turn) {
2097
3762
  remoteId: turn.remoteId
2098
3763
  };
2099
3764
  }
2100
- function mapThreadsToReviewComments(threads, diffFiles = []) {
3765
+ function mapThreadsToReviewComments(threads, diffFiles = [], reviewedHeadSha) {
2101
3766
  return threads.map((thread) => {
2102
3767
  const filePath = thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH;
2103
- 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;
2104
3770
  const comment = {
2105
3771
  id: internalId(thread.root),
2106
3772
  filePath,
2107
3773
  lineRange,
2108
3774
  body: thread.root.body,
2109
3775
  category: "",
2110
- suggestion: extractSuggestion(thread.root.body, filePath, lineRange, diffFiles),
3776
+ suggestion: extractSuggestion(thread.root.body, filePath, lineRange, status, diffFiles),
2111
3777
  author: thread.root.author,
2112
3778
  remoteId: thread.root.remoteId
2113
3779
  };
@@ -2132,6 +3798,7 @@ async function runGlabApi(runCommand, url, endpoint, extraArgs = []) {
2132
3798
  try {
2133
3799
  result = await runCommand(GLAB_CLI, args);
2134
3800
  } catch (error) {
3801
+ if (isCommandCancelled(error)) throw error;
2135
3802
  const detail = error instanceof Error ? error.message : String(error);
2136
3803
  throw unavailable(`glab CLI could not be spawned: ${detail}`);
2137
3804
  }
@@ -2141,14 +3808,14 @@ async function runGlabApi(runCommand, url, endpoint, extraArgs = []) {
2141
3808
  }
2142
3809
  return result.stdout;
2143
3810
  }
2144
- function parseJsonDocuments(text) {
3811
+ function parseJsonDocuments(text3) {
2145
3812
  const documents = [];
2146
3813
  let depth = 0;
2147
3814
  let inString = false;
2148
3815
  let escaped = false;
2149
3816
  let start = -1;
2150
- for (let i = 0; i < text.length; i++) {
2151
- const ch = text[i];
3817
+ for (let i = 0; i < text3.length; i++) {
3818
+ const ch = text3[i];
2152
3819
  if (inString) {
2153
3820
  if (escaped) {
2154
3821
  escaped = false;
@@ -2167,7 +3834,7 @@ function parseJsonDocuments(text) {
2167
3834
  } else if (ch === "]" || ch === "}") {
2168
3835
  depth -= 1;
2169
3836
  if (depth === 0 && start >= 0) {
2170
- documents.push(JSON.parse(text.slice(start, i + 1)));
3837
+ documents.push(JSON.parse(text3.slice(start, i + 1)));
2171
3838
  start = -1;
2172
3839
  }
2173
3840
  }
@@ -2201,7 +3868,11 @@ function toAnchor2(position) {
2201
3868
  const positionLine = lineOf(position);
2202
3869
  const startLine = lineOf(position.line_range?.start) ?? positionLine;
2203
3870
  const endLine = lineOf(position.line_range?.end) ?? positionLine;
2204
- 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;
2205
3876
  }
2206
3877
  function toThread(discussion) {
2207
3878
  const notes = (discussion.notes ?? []).filter((note) => note.system !== true);
@@ -2260,26 +3931,100 @@ function createGitLabProvider(runCommand) {
2260
3931
  }
2261
3932
 
2262
3933
  // src/materializer.ts
2263
- import { execFile as execFile2 } from "child_process";
2264
- import * as fs2 from "fs";
3934
+ import { spawn } from "child_process";
3935
+ import { randomUUID } from "crypto";
3936
+ import * as fs from "fs";
2265
3937
  import * as os from "os";
2266
- import * as path2 from "path";
2267
- var LOCAL_BASE_REF = "refs/self-review/base";
2268
- 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;
2269
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.";
2270
- var defaultGitRunner = (command, args) => new Promise((resolve6, reject) => {
2271
- execFile2(command, args, { maxBuffer: 50 * 1024 * 1024 }, (error, stdout, stderr) => {
2272
- const spawnCode = error?.code;
2273
- if (error && typeof spawnCode === "string") {
2274
- 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
+ }
2275
3990
  return;
2276
3991
  }
2277
- resolve6({
2278
- stdout: stdout ?? "",
2279
- stderr: stderr ?? "",
2280
- exitCode: error ? typeof spawnCode === "number" ? spawnCode : 1 : 0
2281
- });
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
+ }
2282
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
+ );
2283
4028
  });
2284
4029
  function headRefFor(url) {
2285
4030
  return url.forge === "github" ? `refs/pull/${url.number}/head` : `refs/merge-requests/${url.number}/head`;
@@ -2287,6 +4032,25 @@ function headRefFor(url) {
2287
4032
  function cloneUrlFor(url) {
2288
4033
  return `https://${url.host}/${url.owner}/${url.repo}.git`;
2289
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
+ }
2290
4054
  function gitFailure(what, result, withAuthHint) {
2291
4055
  const stderr = result.stderr.trim();
2292
4056
  const lines = [
@@ -2336,104 +4100,140 @@ function findMatchingRemote(remoteVOutput, url) {
2336
4100
  }
2337
4101
  return null;
2338
4102
  }
2339
- async function revParse(runner, repoPath, ref) {
2340
- 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]);
2341
4105
  if (result.exitCode !== 0) {
2342
4106
  throw gitFailure(`rev-parse ${ref}`, result, false);
2343
4107
  }
2344
4108
  return result.stdout.trim();
2345
4109
  }
2346
- async function detectExistingClone(url, cwd, runner = defaultGitRunner) {
2347
- 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"]);
2348
4130
  if (toplevel.exitCode !== 0) {
2349
4131
  return null;
2350
4132
  }
2351
4133
  const repoPath = stripTrailingNewline(toplevel.stdout);
2352
- const remotes = await runner("git", ["-C", repoPath, "remote", "-v"]);
4134
+ const remotes = await git(["-C", repoPath, "remote", "-v"]);
2353
4135
  if (remotes.exitCode !== 0) {
2354
4136
  return null;
2355
4137
  }
2356
4138
  const remoteName = findMatchingRemote(remotes.stdout, url);
2357
4139
  return remoteName === null ? null : { repoPath, remoteName };
2358
4140
  }
2359
- async function materializeIntoExistingClone(runner, url, baseBranch, repoPath, remoteName) {
4141
+ async function materializeIntoExistingClone(runner, options, url, baseBranch, repoPath, remoteName) {
2360
4142
  console.error(`self-review: reusing existing clone at ${repoPath} (remote "${remoteName}")`);
2361
- const fetch = await runner("git", [
2362
- "-C",
2363
- repoPath,
2364
- "fetch",
2365
- remoteName,
2366
- `+refs/heads/${baseBranch}:${LOCAL_BASE_REF}`,
2367
- `+${headRefFor(url)}:${LOCAL_HEAD_REF}`
2368
- ]);
2369
- if (fetch.exitCode !== 0) {
2370
- throw gitFailure(`fetch from remote "${remoteName}"`, fetch, true);
2371
- }
2372
- return {
2373
- repoPath,
2374
- baseSha: await revParse(runner, repoPath, LOCAL_BASE_REF),
2375
- headSha: await revParse(runner, repoPath, LOCAL_HEAD_REF),
2376
- mode: "existing-clone",
2377
- 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
+ }
2378
4164
  }
2379
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
+ }
2380
4181
  }
2381
- async function materializeIntoTempClone(runner, url, baseBranch) {
2382
- 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-"));
2383
4185
  let removed = false;
2384
- const cleanup = () => {
4186
+ const cleanup = async () => {
2385
4187
  if (removed) return;
2386
4188
  removed = true;
2387
- fs2.rmSync(tempDir, { recursive: true, force: true });
4189
+ fs.rmSync(tempDir, { recursive: true, force: true });
2388
4190
  };
2389
4191
  try {
2390
4192
  console.error(`self-review: created temporary blobless clone at ${tempDir}`);
2391
4193
  const cloneUrl = cloneUrlFor(url);
2392
- const clone = await runner("git", ["clone", "--filter=blob:none", cloneUrl, tempDir]);
4194
+ const clone = await git(["clone", "--filter=blob:none", cloneUrl, tempDir]);
2393
4195
  if (clone.exitCode !== 0) {
2394
4196
  throw gitFailure(`clone of ${cloneUrl}`, clone, true);
2395
4197
  }
2396
- const fetch = await runner("git", [
2397
- "-C",
4198
+ const { baseSha, headSha } = await fetchSnapshot(
4199
+ git,
2398
4200
  tempDir,
2399
- "fetch",
2400
4201
  "origin",
2401
- `+${headRefFor(url)}:${LOCAL_HEAD_REF}`
2402
- ]);
2403
- if (fetch.exitCode !== 0) {
2404
- throw gitFailure(`fetch of ${headRefFor(url)}`, fetch, true);
2405
- }
2406
- return {
2407
- repoPath: tempDir,
2408
- baseSha: await revParse(runner, tempDir, `origin/${baseBranch}`),
2409
- headSha: await revParse(runner, tempDir, LOCAL_HEAD_REF),
2410
- mode: "temp-clone",
2411
- cleanup
2412
- };
4202
+ url,
4203
+ baseBranch,
4204
+ sessionRefs(),
4205
+ `fetch of ${headRefFor(url)}`
4206
+ );
4207
+ return { repoPath: tempDir, baseSha, headSha, mode: "temp-clone", ownedRefs: [], cleanup };
2413
4208
  } catch (error) {
2414
- cleanup();
4209
+ await cleanup();
2415
4210
  throw error;
2416
4211
  }
2417
4212
  }
2418
- async function materialize(url, baseBranch, cwd, runner = defaultGitRunner, existingClone) {
2419
- 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;
2420
4218
  if (existing) {
2421
4219
  return materializeIntoExistingClone(
2422
4220
  runner,
4221
+ options,
2423
4222
  url,
2424
4223
  baseBranch,
2425
4224
  existing.repoPath,
2426
4225
  existing.remoteName
2427
4226
  );
2428
4227
  }
2429
- return materializeIntoTempClone(runner, url, baseBranch);
4228
+ return materializeIntoTempClone(runner, options, url, baseBranch);
2430
4229
  }
2431
- async function resolveRemoteDefaultBranch(url, runner = defaultGitRunner, existing = null) {
4230
+ async function resolveRemoteDefaultBranch(url, runner = defaultGitRunner, existing = null, options = {}) {
4231
+ const git = bindGit(runner, options);
2432
4232
  const cloneUrl = cloneUrlFor(url);
2433
4233
  const remote = existing?.remoteName ?? cloneUrl;
2434
4234
  const label = existing ? `${remote} (${cloneUrl})` : cloneUrl;
2435
4235
  const args = existing ? ["-C", existing.repoPath, "ls-remote", "--symref", remote, "HEAD"] : ["ls-remote", "--symref", remote, "HEAD"];
2436
- const result = await runner("git", args);
4236
+ const result = await git(args);
2437
4237
  if (result.exitCode !== 0) {
2438
4238
  throw gitFailure(`ls-remote of ${label}`, result, true);
2439
4239
  }
@@ -2447,130 +4247,8 @@ async function resolveRemoteDefaultBranch(url, runner = defaultGitRunner, existi
2447
4247
  }
2448
4248
 
2449
4249
  // src/review-handlers.ts
2450
- import * as fs3 from "fs";
2451
- import path3 from "path";
2452
-
2453
- // src/git-diff-args.ts
2454
- import { existsSync as existsSync3 } from "fs";
2455
- import { resolve as resolve2 } from "path";
2456
- var OPTIONS_WITH_SEPARATE_VALUES = /* @__PURE__ */ new Set([
2457
- "--output",
2458
- "--src-prefix",
2459
- "--dst-prefix",
2460
- "--line-prefix",
2461
- "--output-indicator-new",
2462
- "--output-indicator-old",
2463
- "--output-indicator-context",
2464
- "--inter-hunk-context",
2465
- "--stat-width",
2466
- "--stat-name-width",
2467
- "--stat-graph-width",
2468
- "--stat-count",
2469
- "--diff-algorithm",
2470
- "--word-diff-regex",
2471
- "--ignore-matching-lines",
2472
- "--anchored",
2473
- "--diff-filter",
2474
- "--find-object",
2475
- "--rotate-to",
2476
- "--skip-to",
2477
- "--ws-error-highlight",
2478
- "--color-moved-ws"
2479
- ]);
2480
- function consumesNextArgument(arg) {
2481
- if (arg.startsWith("--")) return OPTIONS_WITH_SEPARATE_VALUES.has(arg);
2482
- if (!arg.startsWith("-")) return false;
2483
- for (let i = 1; i < arg.length; i++) {
2484
- if ("SGOIl".includes(arg[i])) return i === arg.length - 1;
2485
- if ("UBMC".includes(arg[i])) return false;
2486
- }
2487
- return false;
2488
- }
2489
- function classifyGitDiffArgs(args) {
2490
- const positionalIndices = [];
2491
- let hasSeparator = false;
2492
- for (let i = 0; i < args.length; i++) {
2493
- const arg = args[i];
2494
- if (!hasSeparator) {
2495
- if (arg === "--") {
2496
- hasSeparator = true;
2497
- continue;
2498
- }
2499
- if (consumesNextArgument(arg)) {
2500
- i++;
2501
- continue;
2502
- }
2503
- if (arg.startsWith("-")) continue;
2504
- }
2505
- positionalIndices.push(i);
2506
- }
2507
- return { positionalIndices, hasSeparator };
2508
- }
2509
- function normalizeGitDiffArgs(args, cwd = process.cwd()) {
2510
- const { positionalIndices, hasSeparator } = classifyGitDiffArgs(args);
2511
- if (hasSeparator) return args;
2512
- for (const i of positionalIndices) {
2513
- const arg = args[i];
2514
- if (existsSync3(resolve2(cwd, arg))) {
2515
- return [...args.slice(0, i), "--", ...args.slice(i)];
2516
- }
2517
- }
2518
- return args;
2519
- }
2520
- function tokenizeGitDiffArgs(value) {
2521
- const args = [];
2522
- let current = "";
2523
- let started = false;
2524
- let quote = null;
2525
- for (let i = 0; i < value.length; i++) {
2526
- const char = value[i];
2527
- if (quote === "'") {
2528
- if (char === "'") quote = null;
2529
- else current += char;
2530
- continue;
2531
- }
2532
- if (quote === '"') {
2533
- if (char === "\\" && (value[i + 1] === '"' || value[i + 1] === "\\")) {
2534
- current += value[++i];
2535
- } else if (char === '"') {
2536
- quote = null;
2537
- } else {
2538
- current += char;
2539
- }
2540
- continue;
2541
- }
2542
- if (char === "'" || char === '"') {
2543
- quote = char;
2544
- started = true;
2545
- continue;
2546
- }
2547
- if (char === "\\" && i + 1 < value.length) {
2548
- current += value[++i];
2549
- started = true;
2550
- continue;
2551
- }
2552
- if (/\s/.test(char)) {
2553
- if (started) {
2554
- args.push(current);
2555
- current = "";
2556
- started = false;
2557
- }
2558
- continue;
2559
- }
2560
- current += char;
2561
- started = true;
2562
- }
2563
- if (started) args.push(current);
2564
- return args;
2565
- }
2566
- function needsQuoting(arg) {
2567
- return arg.length === 0 || /[\s'"\\]/.test(arg);
2568
- }
2569
- function formatGitDiffArgs(args) {
2570
- return args.map((arg) => needsQuoting(arg) ? `'${arg.replace(/'/g, "'\\''")}'` : arg).join(" ");
2571
- }
2572
-
2573
- // src/review-handlers.ts
4250
+ import * as fs2 from "fs";
4251
+ import path9 from "path";
2574
4252
  function createReviewSession() {
2575
4253
  return {
2576
4254
  reviewState: null,
@@ -2581,9 +4259,48 @@ function createReviewSession() {
2581
4259
  resumeComments: [],
2582
4260
  resumeViewedFiles: [],
2583
4261
  resumeRemoteDrift: null,
2584
- applyDestinationRoot: null
4262
+ resumeImportDiagnostics: [],
4263
+ applyDestinationRoot: null,
4264
+ reviewedPaths: emptyReviewedPaths(),
4265
+ sourceIdentity: null,
4266
+ attachmentOrigins: /* @__PURE__ */ new Map()
2585
4267
  };
2586
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
+ }
2587
4304
  function preparePayload(payload) {
2588
4305
  if (payload.isLargePayload) {
2589
4306
  return {
@@ -2606,57 +4323,55 @@ function getDiffLoad(session) {
2606
4323
  };
2607
4324
  }
2608
4325
  function resolveSourceBaseDir(session) {
2609
- const source = session.diffData?.source;
2610
- if (!source) return null;
2611
- if (source.type === "git") return source.repository;
2612
- if (source.type === "directory") return source.sourcePath;
2613
- if (source.type === "file") return path3.dirname(source.sourcePath);
2614
- return null;
2615
- }
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
+ };
2616
4337
  async function loadImage(session, filePath) {
2617
- const MIME_MAP = {
2618
- ".jpg": "image/jpeg",
2619
- ".jpeg": "image/jpeg",
2620
- ".png": "image/png",
2621
- ".gif": "image/gif",
2622
- ".webp": "image/webp",
2623
- ".ico": "image/x-icon",
2624
- ".bmp": "image/bmp",
2625
- ".svg": "image/svg+xml"
2626
- };
2627
- const MAX_SIZE = 10 * 1024 * 1024;
2628
- const baseDir = resolveSourceBaseDir(session) ?? process.cwd();
2629
- const resolved = path3.isAbsolute(filePath) ? filePath : path3.resolve(baseDir, filePath);
2630
- const ext = path3.extname(filePath).toLowerCase();
2631
- const mimeType = MIME_MAP[ext] ?? "application/octet-stream";
2632
- const remote = session.diffData?.remote;
2633
- if (remote && session.diffData?.source.type === "git") {
2634
- try {
2635
- const { readGitBlobAsync } = await import("./git-E7WZPKRC.js");
2636
- const data = await readGitBlobAsync(
2637
- session.diffData.source.repository,
2638
- `${remote.remoteHeadSha}:${filePath}`
2639
- );
2640
- if (data.length > MAX_SIZE) {
2641
- return { error: "File too large to preview (>10 MB)" };
2642
- }
2643
- return { dataUri: `data:${mimeType};base64,${data.toString("base64")}` };
2644
- } catch {
2645
- return {
2646
- error: "Image preview unavailable \u2014 blob not found at the reviewed commit."
2647
- };
2648
- }
4338
+ if (!session.reviewedPaths.has(filePath)) {
4339
+ return { error: "Image preview unavailable \u2014 this file is not part of the reviewed diff." };
2649
4340
  }
2650
- try {
2651
- const stat2 = await fs3.promises.stat(resolved);
2652
- 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") {
2653
4349
  return { error: "File too large to preview (>10 MB)" };
2654
4350
  }
2655
- const data = await fs3.promises.readFile(resolved);
2656
- return { dataUri: `data:${mimeType};base64,${data.toString("base64")}` };
2657
- } catch {
2658
- 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}` };
2659
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;
2660
4375
  }
2661
4376
  function getFileHunks(session, filePath) {
2662
4377
  if (!session.diffData) return null;
@@ -2697,7 +4412,8 @@ function resolveApplyDestination(session) {
2697
4412
  }
2698
4413
  function applySuggestionForSession(session, request) {
2699
4414
  const destinationRoot = resolveApplyDestination(session);
2700
- if (!destinationRoot) {
4415
+ const identity = session.sourceIdentity;
4416
+ if (!destinationRoot || identity === null) {
2701
4417
  const temporary = isTemporaryCloneSession(session);
2702
4418
  return {
2703
4419
  status: "refused",
@@ -2706,9 +4422,18 @@ function applySuggestionForSession(session, request) {
2706
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."
2707
4423
  };
2708
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
+ }
2709
4434
  const result = applySuggestion({
2710
4435
  destinationRoot,
2711
- filePath: request.filePath,
4436
+ filePath: rootRelativeReviewedPath(identity, request.filePath),
2712
4437
  lineRange: request.lineRange,
2713
4438
  suggestion: request.suggestion
2714
4439
  });
@@ -2718,28 +4443,46 @@ function applySuggestionForSession(session, request) {
2718
4443
  if (result.status === "applied") {
2719
4444
  return {
2720
4445
  status: "applied",
2721
- filePath: result.filePath,
4446
+ filePath: request.filePath,
2722
4447
  replacedLines: result.replacedLines
2723
4448
  };
2724
4449
  }
2725
4450
  return {
2726
4451
  status: "refused",
2727
- filePath: result.filePath,
4452
+ filePath: request.filePath,
2728
4453
  reason: result.reason,
2729
4454
  detail: result.detail
2730
4455
  };
2731
4456
  }
2732
- async function readAttachment(filePath) {
2733
- try {
2734
- const buffer = await fs3.promises.readFile(filePath);
2735
- return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
2736
- } catch {
2737
- console.error(`[attachment:read] Failed to read file: ${filePath}`);
2738
- 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}`);
2739
4481
  }
4482
+ return result;
2740
4483
  }
2741
4484
  function getResumeLoad(session) {
2742
- 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) {
2743
4486
  const payload = {
2744
4487
  comments: session.resumeComments,
2745
4488
  viewedFiles: session.resumeViewedFiles
@@ -2747,61 +4490,56 @@ function getResumeLoad(session) {
2747
4490
  if (session.resumeRemoteDrift !== null) {
2748
4491
  payload.remoteDrift = session.resumeRemoteDrift;
2749
4492
  }
4493
+ if (session.resumeImportDiagnostics.length > 0) {
4494
+ payload.importDiagnostics = session.resumeImportDiagnostics;
4495
+ }
2750
4496
  return payload;
2751
4497
  }
2752
4498
  return null;
2753
4499
  }
2754
4500
  async function expandContext(session, request) {
2755
4501
  const diffData = session.diffData;
2756
- 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) {
2757
4516
  return null;
2758
4517
  }
2759
4518
  try {
2760
- const { runGitDiffAsync: runGitDiffAsync2 } = await import("./git-E7WZPKRC.js");
2761
- const { parseDiff: parseDiff2 } = await import("./diff-parser-2JM4CZR3.js");
2762
- const source = diffData.source;
2763
- const originalArgs = tokenizeGitDiffArgs(source.gitDiffArgs);
2764
- const filteredArgs = [];
2765
- for (let i = 0; i < originalArgs.length; i++) {
2766
- const arg = originalArgs[i];
2767
- if (arg.match(/^-U\d+$/) || arg.match(/^--unified=\d+$/)) {
2768
- continue;
2769
- }
2770
- if (arg === "-U" || arg === "--unified") {
2771
- i++;
2772
- continue;
2773
- }
2774
- if (arg === "--") {
2775
- break;
2776
- }
2777
- filteredArgs.push(arg);
2778
- }
2779
- const expandArgs = [...filteredArgs, `-U${request.contextLines}`, "--", request.filePath];
2780
- const rawDiff = await runGitDiffAsync2(expandArgs, source.repository);
2781
- const parsedFiles = parseDiff2(rawDiff);
2782
- 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`);
2783
4537
  return null;
2784
4538
  }
2785
- const expandedFile = parsedFiles[0];
2786
- let totalLines = 0;
2787
- try {
2788
- const content = await fs3.promises.readFile(
2789
- path3.resolve(source.repository, request.filePath),
2790
- "utf-8"
2791
- );
2792
- totalLines = content.split("\n").length;
2793
- if (content.endsWith("\n")) totalLines--;
2794
- } catch {
2795
- }
4539
+ const totalLines = await countReviewedLines(session, target);
2796
4540
  session.diffData = {
2797
4541
  ...diffData,
2798
- files: diffData.files.map((f) => {
2799
- const fPath = f.newPath || f.oldPath;
2800
- if (fPath === request.filePath) {
2801
- return { ...f, hunks: expandedFile.hunks };
2802
- }
2803
- return f;
2804
- })
4542
+ files: diffData.files.map((f) => f === target ? { ...f, hunks: expandedFile.hunks } : f)
2805
4543
  };
2806
4544
  return { hunks: expandedFile.hunks, totalLines };
2807
4545
  } catch (error) {
@@ -2813,94 +4551,315 @@ async function prepareDirectoryReview(session, directoryPath) {
2813
4551
  console.error("[review] Starting directory review for:", directoryPath);
2814
4552
  let isFile = false;
2815
4553
  try {
2816
- isFile = fs3.statSync(directoryPath).isFile();
4554
+ isFile = fs2.statSync(directoryPath).isFile();
2817
4555
  } catch {
2818
4556
  }
2819
- let payload;
2820
- if (isFile) {
2821
- const files = await scanFile(directoryPath);
2822
- payload = {
2823
- files,
2824
- source: { type: "file", sourcePath: directoryPath }
2825
- };
2826
- } else {
2827
- const ignorePatterns = session.config?.ignore ?? [];
2828
- const files = await scanDirectory(directoryPath, ignorePatterns);
2829
- payload = {
2830
- files,
2831
- source: { type: "directory", sourcePath: directoryPath }
2832
- };
2833
- }
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 });
2834
4565
  if (!session.config) {
2835
- return { payload, stats: null, exceedsThresholds: false };
4566
+ return { payload, identity, stats: null, exceedsThresholds: false };
2836
4567
  }
2837
4568
  const stats = computePayloadStats(
2838
4569
  payload.files.length,
2839
4570
  countTotalLines(payload.files),
2840
4571
  session.config
2841
4572
  );
2842
- return { payload, stats, exceedsThresholds: stats.exceedsAny };
4573
+ return { payload, identity, stats, exceedsThresholds: stats.exceedsAny };
2843
4574
  }
2844
- function commitReviewStart(session, payload) {
2845
- session.diffData = payload;
4575
+ function commitReviewStart(session, payload, identity) {
4576
+ commitDiffData(session, payload, identity);
2846
4577
  return preparePayload(payload);
2847
4578
  }
2848
4579
 
2849
4580
  // src/startup-mode.ts
2850
- import { existsSync as existsSync4, statSync as statSync2 } from "fs";
4581
+ import { existsSync as existsSync3, statSync as statSync2 } from "fs";
2851
4582
  import { execFileSync, execSync } from "child_process";
2852
- import { resolve as resolve3 } from "path";
2853
- function isInGitRepo() {
4583
+ import { resolve as resolve7 } from "path";
4584
+ function isInGitRepo(cwd) {
2854
4585
  try {
2855
- execSync("git rev-parse --git-dir", { stdio: "ignore" });
4586
+ execSync("git rev-parse --git-dir", { stdio: "ignore", cwd });
2856
4587
  return true;
2857
4588
  } catch {
2858
4589
  return false;
2859
4590
  }
2860
4591
  }
2861
- function isGitTracked(filePath) {
4592
+ function isGitTracked(filePath, cwd) {
2862
4593
  try {
2863
4594
  execFileSync("git", ["ls-files", "--error-unmatch", "--", filePath], {
2864
- stdio: "ignore"
4595
+ stdio: "ignore",
4596
+ cwd
2865
4597
  });
2866
4598
  return true;
2867
4599
  } catch {
2868
4600
  return false;
2869
4601
  }
2870
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
+ }
2871
4630
  function determineMode(gitDiffArgs) {
2872
- const { positionalIndices } = classifyGitDiffArgs(gitDiffArgs);
2873
- const firstPositional = gitDiffArgs[positionalIndices[0]];
2874
- if (firstPositional) {
2875
- const candidate = resolve3(process.cwd(), firstPositional);
2876
- try {
2877
- if (existsSync4(candidate) && statSync2(candidate).isFile()) {
2878
- if (isInGitRepo()) {
2879
- return isGitTracked(firstPositional) ? "git" : "file";
2880
- }
2881
- 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");
2882
4750
  }
2883
- } catch {
2884
4751
  }
2885
4752
  }
2886
- if (isInGitRepo()) {
2887
- 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
+ };
2888
4781
  }
2889
- if (firstPositional) {
2890
- const candidate = resolve3(process.cwd(), firstPositional);
2891
- try {
2892
- if (existsSync4(candidate) && statSync2(candidate).isDirectory()) {
2893
- 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;
2894
4847
  }
2895
- } catch {
4848
+ }
4849
+ rest.push(arg);
4850
+ if (consumesNextArgument(arg) && i + 1 < argv.length) {
4851
+ rest.push(argv[++i]);
2896
4852
  }
2897
4853
  }
2898
- return "welcome";
4854
+ return { values, flags, rest };
4855
+ }
4856
+ function requireValue(flag, value) {
4857
+ if (value === "") throw new ApplicationOptionError(flag);
4858
+ return value;
2899
4859
  }
2900
4860
 
2901
4861
  // src/guide-loader.ts
2902
- import { readFile } from "fs/promises";
2903
- import { extname, resolve as resolve4 } from "path";
4862
+ import { extname, resolve as resolve9 } from "path";
2904
4863
  function deriveGuidePath(outputPath) {
2905
4864
  const ext = extname(outputPath);
2906
4865
  const base = ext ? outputPath.slice(0, -ext.length) : outputPath;
@@ -2908,7 +4867,7 @@ function deriveGuidePath(outputPath) {
2908
4867
  }
2909
4868
  function resolveGuidePath(outputPath, config) {
2910
4869
  if (config.guideFile) {
2911
- return resolve4(process.cwd(), config.guideFile);
4870
+ return resolve9(process.cwd(), config.guideFile);
2912
4871
  }
2913
4872
  return deriveGuidePath(outputPath);
2914
4873
  }
@@ -2922,7 +4881,18 @@ async function loadGuide(outputPath, config, diffFilePaths) {
2922
4881
  try {
2923
4882
  let content;
2924
4883
  try {
2925
- 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");
2926
4896
  } catch (error) {
2927
4897
  const code = error.code;
2928
4898
  if (code === "ENOENT") {
@@ -2952,44 +4922,28 @@ async function loadGuide(outputPath, config, diffFilePaths) {
2952
4922
  }
2953
4923
  }
2954
4924
 
2955
- // src/git-diff-loader.ts
2956
- async function loadGitDiffWithUntracked(gitDiffArgs, cwd, options = {}) {
2957
- const { includeUntracked = true } = options;
2958
- const repository = await getRepoRootAsync(cwd);
2959
- const rawDiff = await runGitDiffAsync(gitDiffArgs, cwd);
2960
- const files = parseDiff(rawDiff);
2961
- if (!includeUntracked) {
2962
- return { files, repository };
2963
- }
2964
- const untrackedPaths = await getUntrackedFilesAsync(repository);
2965
- let allFiles = files;
2966
- if (untrackedPaths.length > 0) {
2967
- const untrackedDiffStr = generateUntrackedDiffs(untrackedPaths, repository);
2968
- if (untrackedDiffStr.length > 0) {
2969
- const untrackedFiles = parseDiff(untrackedDiffStr);
2970
- for (const file of untrackedFiles) {
2971
- file.isUntracked = true;
2972
- }
2973
- allFiles = [...files, ...untrackedFiles];
2974
- }
2975
- }
2976
- return { files: allFiles, repository };
2977
- }
2978
-
2979
- // src/staged-untracked.ts
2980
- function applyStagedUntrackedDefault(config, gitDiffArgs) {
2981
- const stagedMode = gitDiffArgs.includes("--staged") || gitDiffArgs.includes("--cached");
2982
- if (!stagedMode) return config;
2983
- const userExplicitOptIn = config.showUntrackedExplicit && config.showUntracked;
2984
- if (userExplicitOptIn) return config;
2985
- return { ...config, showUntracked: false };
2986
- }
2987
-
2988
4925
  // src/remote-mode.ts
2989
4926
  function defaultCreateProvider(forge, runner) {
2990
4927
  return forge === "github" ? createGitHubProvider(runner) : createGitLabProvider(runner);
2991
4928
  }
2992
- 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 = {
2993
4947
  createProvider: defaultCreateProvider,
2994
4948
  detectExistingClone,
2995
4949
  materialize,
@@ -3001,13 +4955,20 @@ var defaultDeps = {
3001
4955
  loadGitDiffWithUntracked(gitDiffArgs, cwd, { includeUntracked: false })
3002
4956
  )
3003
4957
  };
3004
- async function startRemoteSession(url, cwd, deps = {}) {
3005
- 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");
3006
4964
  const forgeUrl = parseForgeUrl(url);
3007
4965
  if (!forgeUrl) {
3008
- 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
+ );
3009
4970
  }
3010
- const provider = d.createProvider(forgeUrl.forge, d.runner);
4971
+ const provider = d.createProvider(forgeUrl.forge, bindSessionRunner(d.runner, signal));
3011
4972
  let cliAvailable = true;
3012
4973
  let baseBranch;
3013
4974
  let existingClone;
@@ -3021,17 +4982,37 @@ async function startRemoteSession(url, cwd, deps = {}) {
3021
4982
  console.error(
3022
4983
  `[remote] Forge CLI unavailable (${error.cli}): ${error.message} \u2014 falling back to the remote default branch via git.`
3023
4984
  );
3024
- existingClone = await d.detectExistingClone(forgeUrl, cwd, d.runner);
3025
- 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);
3026
4987
  }
3027
- 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
+ );
3028
4997
  let fetchedThreads = [];
3029
4998
  let threadSyncAvailable = false;
3030
- if (cliAvailable) {
4999
+ if (cliAvailable || threadsRequired) {
3031
5000
  try {
3032
- fetchedThreads = await provider.fetchThreads(forgeUrl);
5001
+ fetchedThreads = await provider.fetchThreads(forgeUrl, {
5002
+ includeResolved: options.includeResolved ?? false
5003
+ });
3033
5004
  threadSyncAvailable = true;
3034
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
+ }
3035
5016
  const message = error instanceof Error ? error.message : String(error);
3036
5017
  console.error(
3037
5018
  `[remote] thread sync unavailable \u2014 continuing without forge threads: ${message}`
@@ -3042,6 +5023,10 @@ async function startRemoteSession(url, cwd, deps = {}) {
3042
5023
  "[remote] thread sync unavailable \u2014 forge CLI missing, continuing without forge threads."
3043
5024
  );
3044
5025
  }
5026
+ if (signal?.aborted) {
5027
+ await materialized.cleanup();
5028
+ throwIfAborted(signal, "threads");
5029
+ }
3045
5030
  return {
3046
5031
  forgeUrl,
3047
5032
  repoPath: materialized.repoPath,
@@ -3058,41 +5043,70 @@ async function startRemoteSession(url, cwd, deps = {}) {
3058
5043
  // into it; the front end needs the fact, not the path.
3059
5044
  temporaryClone: materialized.mode === "temp-clone"
3060
5045
  },
3061
- fetchedComments: mapThreadsToReviewComments(fetchedThreads),
3062
5046
  fetchedThreads
3063
5047
  };
3064
5048
  }
3065
- async function bootstrapRemoteDiff(url, cwd, ignorePatterns, deps = {}) {
3066
- const d = { ...defaultDeps, ...deps };
3067
- const started = await startRemoteSession(url, cwd, d);
3068
- let files;
3069
- let repository;
3070
- try {
3071
- ({ files, repository } = await d.loadDiff(started.gitDiffArgs, started.repoPath));
3072
- } catch (error) {
3073
- started.cleanup();
3074
- throw error;
3075
- }
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");
3076
5056
  const shouldKeep = createIgnoreFilter(ignorePatterns);
3077
5057
  const filteredFiles = files.filter((f) => shouldKeep(f.newPath || f.oldPath));
3078
- const session = {
3079
- ...started,
3080
- fetchedComments: mapThreadsToReviewComments(started.fetchedThreads, filteredFiles)
3081
- };
3082
5058
  return {
3083
- session,
3084
- payload: {
3085
- files: filteredFiles,
3086
- source: {
3087
- type: "git",
3088
- // Same renderer the git-mode path uses, so expand-context can
3089
- // tokenize this string back into the exact argv.
3090
- gitDiffArgs: formatGitDiffArgs(session.gitDiffArgs),
3091
- repository
3092
- },
3093
- remote: session.remote
3094
- }
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 }
3095
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
+ }
3096
5110
  }
3097
5111
  function mergeRemoteThreads(resumed, fetched) {
3098
5112
  const resumedRemoteIds = new Set(
@@ -3129,23 +5143,11 @@ function computeRemoteDrift(recordedHeadSha, liveHeadSha) {
3129
5143
  }
3130
5144
 
3131
5145
  // src/fetch-comments.ts
3132
- import { writeFileSync as writeFileSync3 } from "fs";
3133
- import { resolve as resolve5 } from "path";
3134
- function defaultDeps2() {
5146
+ function defaultDeps() {
3135
5147
  return {
3136
- runner: defaultGitRunner,
3137
- createProvider: (forge, runner) => forge === "github" ? createGitHubProvider(runner) : createGitLabProvider(runner),
3138
- detectExistingClone,
3139
- materialize,
3140
- resolveRemoteDefaultBranch,
3141
- loadDiffFiles: async (repoPath, baseSha, headSha) => (
3142
- // Triple-dot: diff from the merge base, matching how forges present a
3143
- // PR/MR diff. Runs inside the materialized clone.
3144
- parseDiff(await runGitDiffAsync([`${baseSha}...${headSha}`], repoPath))
3145
- ),
3146
- serialize: serializeReview,
3147
- writeFile: (path4, content) => writeFileSync3(path4, content, "utf-8"),
3148
- loadConfig,
5148
+ ...defaultRemoteSessionDeps,
5149
+ publish: publishReview,
5150
+ loadConfig: loadConfigWithProvenance,
3149
5151
  now: () => /* @__PURE__ */ new Date()
3150
5152
  };
3151
5153
  }
@@ -3162,18 +5164,18 @@ function buildRemoteReviewState(args) {
3162
5164
  const files = [];
3163
5165
  const diffPaths = /* @__PURE__ */ new Set();
3164
5166
  for (const diffFile of args.diffFiles) {
3165
- const path4 = diffFile.changeType === "deleted" ? diffFile.oldPath : diffFile.newPath;
3166
- diffPaths.add(path4);
5167
+ const path10 = diffFile.changeType === "deleted" ? diffFile.oldPath : diffFile.newPath;
5168
+ diffPaths.add(path10);
3167
5169
  files.push({
3168
- path: path4,
5170
+ path: path10,
3169
5171
  changeType: diffFile.changeType,
3170
5172
  viewed: false,
3171
- comments: commentsByPath.get(path4) ?? []
5173
+ comments: commentsByPath.get(path10) ?? []
3172
5174
  });
3173
5175
  }
3174
- for (const [path4, comments] of commentsByPath) {
3175
- if (path4 === REVIEW_LEVEL_FILE_PATH || diffPaths.has(path4)) continue;
3176
- 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 });
3177
5179
  }
3178
5180
  const reviewLevel = commentsByPath.get(REVIEW_LEVEL_FILE_PATH);
3179
5181
  if (reviewLevel && reviewLevel.length > 0) {
@@ -3195,102 +5197,103 @@ function buildRemoteReviewState(args) {
3195
5197
  };
3196
5198
  }
3197
5199
  async function runFetchComments(url, options = {}) {
3198
- const deps = { ...defaultDeps2(), ...options.deps };
5200
+ const deps = { ...defaultDeps(), ...options.deps };
3199
5201
  const cwd = options.cwd ?? process.cwd();
3200
- const forgeUrl = parseForgeUrl(url);
3201
- if (forgeUrl === null) {
3202
- throw new Error(
3203
- `Not a recognized pull/merge request URL: ${url}
3204
- Expected a GitHub PR URL (\u2026/pull/N) or a GitLab MR URL (\u2026/-/merge_requests/N).`
3205
- );
3206
- }
3207
- const provider = deps.createProvider(forgeUrl.forge, deps.runner);
3208
- let baseBranch;
3209
- let existingClone;
3210
- try {
3211
- baseBranch = await provider.fetchBaseBranch(forgeUrl);
3212
- } catch (error) {
3213
- if (!(error instanceof ForgeCliUnavailableError)) throw error;
3214
- console.error(`[fetch-comments] ${error.message}`);
3215
- console.error(
3216
- `[fetch-comments] ${error.cli} unavailable for the base-branch lookup \u2014 falling back to the remote default branch via git ls-remote.`
3217
- );
3218
- existingClone = await deps.detectExistingClone(forgeUrl, cwd, deps.runner);
3219
- baseBranch = await deps.resolveRemoteDefaultBranch(forgeUrl, deps.runner, existingClone);
3220
- }
3221
- console.error(`[fetch-comments] Base branch: ${baseBranch}`);
3222
- const materialized = await deps.materialize(
3223
- forgeUrl,
3224
- baseBranch,
3225
- cwd,
3226
- deps.runner,
3227
- existingClone
3228
- );
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
+ });
3229
5208
  try {
3230
- let threads;
3231
- try {
3232
- threads = await provider.fetchThreads(forgeUrl, {
3233
- includeResolved: options.includeResolved ?? false
3234
- });
3235
- } catch (error) {
3236
- if (error instanceof ForgeCliUnavailableError) {
3237
- throw new Error(
3238
- `Cannot fetch discussion threads: ${error.message}
3239
- fetch-comments requires the ${error.cli} CLI to be installed and authenticated.`
3240
- );
3241
- }
3242
- 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}`);
3243
5215
  }
3244
- console.error(`[fetch-comments] Fetched ${threads.length} threads`);
3245
- const diffFiles = await deps.loadDiffFiles(
3246
- materialized.repoPath,
3247
- materialized.baseSha,
3248
- materialized.headSha
3249
- );
3250
- const comments = mapThreadsToReviewComments(threads, diffFiles);
3251
5216
  const state = buildRemoteReviewState({
3252
5217
  remoteUrl: url,
3253
- forge: forgeUrl.forge,
3254
- baseSha: materialized.baseSha,
3255
- headSha: materialized.headSha,
3256
- diffFiles,
3257
- comments,
5218
+ forge: session.forgeUrl.forge,
5219
+ baseSha: session.remote.remoteBaseSha,
5220
+ headSha: session.remote.remoteHeadSha,
5221
+ diffFiles: loaded.files,
5222
+ comments: loaded.comments,
3258
5223
  timestamp: deps.now().toISOString()
3259
5224
  });
3260
- const config = deps.loadConfig();
3261
- const outputPath = resolve5(cwd, config.outputFile);
3262
- const xml = await deps.serialize(state, outputPath);
3263
- deps.writeFile(outputPath, xml + "\n");
3264
- 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}`);
3265
5228
  } finally {
3266
- materialized.cleanup();
5229
+ await session.cleanup();
3267
5230
  }
3268
5231
  }
3269
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,
3270
5241
  ForgeCliUnavailableError,
3271
5242
  GUIDE_XSD_SCHEMA,
3272
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,
3273
5254
  REVIEW_LEVEL_FILE_PATH,
5255
+ ReviewPublishError,
5256
+ ReviewXmlError,
5257
+ SafeFsError,
5258
+ XmlIllegalCharacterError,
3274
5259
  applyRemoteProvenance,
3275
5260
  applyStagedUntrackedDefault,
3276
5261
  applySuggestion,
3277
5262
  applySuggestionForSession,
5263
+ assertNoSymlinkAncestors,
5264
+ atomicReplace,
5265
+ authorizeAttachmentReference,
5266
+ authorizeReviewedPath,
3278
5267
  bootstrapRemoteDiff,
3279
5268
  buildRemoteReviewState,
5269
+ canonicalSourcePath,
3280
5270
  checkWritability,
5271
+ classifyFsError,
5272
+ classifyGitDiffArgs,
5273
+ commitDiffData,
3281
5274
  commitReviewStart,
3282
5275
  computePayloadStats,
3283
5276
  computeRemoteDrift,
5277
+ consumesNextArgument,
3284
5278
  countTotalLines,
3285
5279
  createGitHubProvider,
3286
5280
  createGitLabProvider,
3287
5281
  createIgnoreFilter,
3288
5282
  createReviewSession,
5283
+ dedupeUntrackedByPath,
3289
5284
  defaultGitRunner,
5285
+ defaultRemoteSessionDeps,
3290
5286
  deriveGuidePath,
5287
+ describeDiffPathRelativity,
5288
+ describeGitDiffSides,
3291
5289
  detectExistingClone,
3292
5290
  determineMode,
3293
5291
  expandContext,
5292
+ extractApplicationOptions,
5293
+ findUnsupportedGitDiffOptions,
5294
+ findWriteCapableGitDiffOptions,
5295
+ formatBytes,
5296
+ formatGitDiffArgs,
3294
5297
  generateSyntheticDiffs,
3295
5298
  generateUntrackedDiffs,
3296
5299
  getConfigLoad,
@@ -3299,45 +5302,79 @@ export {
3299
5302
  getGitDiffStats,
3300
5303
  getLanguageFromPath,
3301
5304
  getRenderedTextMode,
3302
- getRepoRoot,
3303
5305
  getRepoRootAsync,
3304
5306
  getResumeLoad,
3305
5307
  getUntrackedFilesAsync,
5308
+ inspectOutputPath,
5309
+ inspectReplaceTarget,
5310
+ isCommandCancelled,
3306
5311
  isHtmlFile,
3307
5312
  isMarkdownFile,
3308
5313
  isPreviewableImage,
3309
5314
  isPreviewableRenderedText,
3310
5315
  isPreviewableSvg,
5316
+ isRepositoryControlPath,
3311
5317
  loadConfig,
5318
+ loadConfigWithProvenance,
3312
5319
  loadGitDiffWithUntracked,
3313
5320
  loadGuide,
3314
5321
  loadImage,
5322
+ loadLocalReview,
5323
+ loadRemoteReview,
5324
+ loadResumeDocument,
5325
+ loadSyntheticFiles,
5326
+ locateReviewedFile,
3315
5327
  mapThreadsToReviewComments,
3316
5328
  materialize,
3317
5329
  mergeRemoteThreads,
5330
+ nodeFsLayer,
3318
5331
  normalizeGitDiffArgs,
5332
+ parseAttachmentReference,
3319
5333
  parseDiff,
5334
+ parseDiffWithDiagnostics,
3320
5335
  parseForgeUrl,
3321
5336
  parseGuideXml,
3322
5337
  parseReviewXml,
3323
5338
  parseReviewXmlString,
3324
5339
  prepareDirectoryReview,
3325
5340
  preparePayload,
5341
+ publishOptionsFor,
5342
+ publishReview,
5343
+ readAssetFile,
3326
5344
  readAttachment,
5345
+ readFileWithinBudget,
5346
+ readFileWithinBudgetSync,
5347
+ readReviewedContent,
3327
5348
  reconcileGuide,
5349
+ recordResumedAttachments,
5350
+ relocateAttachments,
3328
5351
  resolveApplyDestination,
5352
+ resolveAttachmentOrigins,
5353
+ resolveGitSourceIdentity,
3329
5354
  resolveGuidePath,
5355
+ resolveLocalSourceIdentity,
5356
+ resolveOutputTarget,
3330
5357
  resolveRemoteDefaultBranch,
5358
+ resolveReviewedPathPrefix,
3331
5359
  resolveSourceBaseDir,
5360
+ resolveSourceBudgets,
5361
+ resolveStartupDiffArgs,
5362
+ resolveStartupSource,
5363
+ rootRelativeReviewedPath,
3332
5364
  runFetchComments,
3333
- runGitDiff,
3334
5365
  runGitDiffAsync,
5366
+ sameFile,
3335
5367
  scanDirectory,
3336
5368
  scanFile,
3337
5369
  serializeReview,
5370
+ snapshotIdentity,
3338
5371
  startRemoteSession,
3339
5372
  submitReviewState,
3340
5373
  takeReviewState,
3341
- validateGitAvailable
5374
+ tokenizeGitDiffArgs,
5375
+ validateLineAnchor,
5376
+ validateLineRange,
5377
+ withParserCompatibleDiffArgs,
5378
+ writeExclusiveNoFollow
3342
5379
  };
3343
5380
  //# sourceMappingURL=index.js.map