@self-review/core 1.43.3 → 1.43.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +3 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/diff-parser.ts","../src/xml-serializer.ts","../src/xml-parser.ts","../src/guide-schema.ts","../src/guide-parser.ts","../src/git.ts","../src/synthetic-diff.ts","../src/forge-provider.ts","../src/directory-scanner.ts","../src/ignore-filter.ts","../src/config.ts","../src/payload-sizing.ts","../src/fs-utils.ts","../src/file-type-utils.ts","../src/github-provider.ts","../src/thread-mapper.ts","../src/gitlab-provider.ts","../src/materializer.ts"],"sourcesContent":["// src/main/diff-parser.ts\n// Parse unified diff output into DiffFile[]\n\nimport { DiffFile, DiffHunk, ChangeType } from './types';\n\nexport function parseDiff(rawDiff: string): DiffFile[] {\n if (!rawDiff.trim()) {\n return [];\n }\n\n const lines = rawDiff.split('\\n');\n const files: DiffFile[] = [];\n let currentFile: Partial<DiffFile> | null = null;\n let currentHunk: Partial<DiffHunk> | null = null;\n let oldLineNumber = 0;\n let newLineNumber = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Start of a new file\n if (line.startsWith('diff --git ')) {\n // Flush the pending hunk into the current file before saving\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n currentHunk = null;\n }\n\n // Save previous file if exists and has actual changes\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n // Extract paths from \"diff --git a/<old> b/<new>\" as fallback\n // for binary files that lack --- / +++ lines\n const gitPaths = parseGitDiffHeader(line);\n\n // Initialize new file\n currentFile = {\n oldPath: gitPaths.oldPath,\n newPath: gitPaths.newPath,\n changeType: 'modified' as ChangeType,\n isBinary: false,\n hunks: [],\n };\n currentHunk = null;\n continue;\n }\n\n if (!currentFile) continue;\n\n // Detect file mode changes\n if (line.startsWith('new file mode')) {\n currentFile.changeType = 'added';\n continue;\n }\n\n if (line.startsWith('deleted file mode')) {\n currentFile.changeType = 'deleted';\n continue;\n }\n\n if (line.startsWith('rename from ')) {\n currentFile.changeType = 'renamed';\n continue;\n }\n\n // Parse old file path\n if (line.startsWith('--- ')) {\n const path = line.substring(4);\n currentFile.oldPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Parse new file path\n if (line.startsWith('+++ ')) {\n const path = line.substring(4);\n currentFile.newPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Detect binary files\n if (line.startsWith('Binary files ')) {\n currentFile.isBinary = true;\n continue;\n }\n\n // Parse hunk header\n if (line.startsWith('@@')) {\n // Save previous hunk if exists\n if (currentHunk && currentHunk.header) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n\n // Parse hunk header: @@ -oldStart,oldLines +newStart,newLines @@ context\n const match = line.match(\n /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(.*)$/\n );\n if (match) {\n const oldStart = parseInt(match[1], 10);\n const oldLines = match[2] ? parseInt(match[2], 10) : 1;\n const newStart = parseInt(match[3], 10);\n const newLines = match[4] ? parseInt(match[4], 10) : 1;\n const _context = match[5];\n\n currentHunk = {\n header: line,\n oldStart,\n oldLines,\n newStart,\n newLines,\n lines: [],\n };\n\n oldLineNumber = oldStart;\n newLineNumber = newStart;\n }\n continue;\n }\n\n // Parse diff lines (must have a current hunk)\n if (currentHunk && currentHunk.lines) {\n if (line.startsWith('+')) {\n // Addition\n currentHunk.lines.push({\n type: 'addition',\n oldLineNumber: null,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n newLineNumber++;\n } else if (line.startsWith('-')) {\n // Deletion\n currentHunk.lines.push({\n type: 'deletion',\n oldLineNumber: oldLineNumber,\n newLineNumber: null,\n content: line.substring(1),\n });\n oldLineNumber++;\n } else if (line.startsWith(' ')) {\n // Context line\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n oldLineNumber++;\n newLineNumber++;\n } else if (line.startsWith('\\\\')) {\n // \"\\" - ignore\n continue;\n } else {\n // Some other line (could be empty or malformed), treat as context\n if (currentHunk.lines.length > 0) {\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line,\n });\n oldLineNumber++;\n newLineNumber++;\n }\n }\n }\n }\n\n // Save the last hunk and file\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n return files;\n}\n\nfunction stripPrefix(path: string): string {\n // Remove single-character prefix (a/, b/, c/, i/, w/, etc.)\n // Git uses a/b by default, but mnemonicPrefix uses c/i/w/o\n if (path.length > 2 && path[1] === '/') {\n return path.substring(2);\n }\n return path;\n}\n\nfunction parseGitDiffHeader(line: string): {\n oldPath: string;\n newPath: string;\n} {\n // Format: \"diff --git a/<old> b/<new>\"\n // With diff.mnemonicPrefix, git uses i/ w/ c/ o/ instead of a/ b/.\n // Paths may contain spaces, so we find the \" X/\" separator where X is a\n // single-letter prefix.\n const withoutPrefix = line.substring('diff --git '.length);\n\n // Find \" X/\" — the boundary between old and new paths.\n // Try common prefixes: b/ (default), w/ i/ c/ o/ (mnemonic)\n let bIdx = -1;\n for (const prefix of [' b/', ' w/', ' i/', ' c/', ' o/']) {\n bIdx = withoutPrefix.indexOf(prefix);\n if (bIdx !== -1) break;\n }\n\n if (bIdx === -1) {\n return { oldPath: '', newPath: '' };\n }\n\n const oldPath = stripPrefix(withoutPrefix.substring(0, bIdx));\n const newPath = stripPrefix(withoutPrefix.substring(bIdx + 1));\n return { oldPath, newPath };\n}\n","// src/main/xml-serializer.ts\n// Serialize ReviewState to XML and validate against XSD\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { ReviewState, FileReviewState, ReviewComment, Reply, Attachment } from './types';\nimport { validateXML } from 'xmllint-wasm';\n\n// Embed the XSD schema for validation.\n// This MUST stay byte-identical to the on-disk canonical copy\n// (.agents/skills/self-review-apply/assets/self-review-v3.xsd);\n// the sync test in xsd-schema.test.ts enforces it.\nexport const XSD_SCHEMA = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sr=\"urn:self-review:v3\"\n targetNamespace=\"urn:self-review:v3\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review XML Schema v3\n =========================\n Defines the output format for the self-review application.\n This schema is designed to be both machine-validated and\n fed to an LLM so it can understand the structure of review feedback.\n\n Key concepts:\n - A <review> contains one <file> per file in the diff.\n - A <file> contains zero or more <comment> elements.\n - A <comment> with no line attributes is a file-level comment.\n - A <comment> with old-line-start/old-line-end refers to lines\n in the pre-change version of the file (typically deleted lines).\n - A <comment> with new-line-start/new-line-end refers to lines\n in the post-change version of the file (added or context lines).\n - Exactly one pair (old-line-* or new-line-*) should be present\n for line-level comments. This constraint cannot be expressed in\n XSD 1.0 and is enforced by the application.\n - A <comment> may carry an ordered list of <reply> children, which\n are turns in a conversation about that comment.\n\n Changes from v1:\n - <comment> gained two optional attributes, severity and confidence,\n so an automated consumer can threshold on findings instead of\n applying all of them or none of them. See CommentType.\n\n Changes from v2:\n - <comment> gained an optional, unbounded <reply> child, so a finding\n and the responses to it form a single legible thread instead of a\n set of disconnected assertions. See ReplyType.\n\n Amended in place (still v3):\n - The review root gained optional remote-url, remote-base-sha,\n remote-head-sha and remote-forge attributes, and <comment> and\n <reply> gained an optional remote-id attribute, so a review taken\n against a remote pull/merge request records its provenance. Purely\n additive: a document carrying none of them is unchanged. See\n ReviewType.\n -->\n\n <!-- ===== Root element ===== -->\n\n <xs:element name=\"review\" type=\"sr:ReviewType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review output file. Contains one file element\n per file in the git diff, including files with no comments.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <!-- ===== Complex types ===== -->\n\n <xs:complexType name=\"ReviewType\">\n <xs:sequence>\n <xs:element name=\"file\" type=\"sr:FileType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the review was completed (window closed).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments that were passed to self-review on the CLI.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root where self-review was invoked.\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"source-path\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the directory being reviewed.\n Present only when reviewing a directory (non-git mode).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-url\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n URL of the remote pull/merge request this review was taken\n against. Example: \"https://github.com/owner/repo/pull/42\".\n Present only when reviewing a remote PR/MR.\n\n The remote-* attributes form a third source shape alongside\n git-diff-args/repository (local git diff) and source-path\n (directory review). The three shapes are mutually exclusive;\n XSD 1.0 cannot express that constraint, so it is enforced by\n the application.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-base-sha\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Commit SHA the remote diff was computed from (the base of the\n PR/MR at fetch time). Together with remote-head-sha it pins the\n review to the exact diff it was written against, so a consumer\n can detect drift when the remote branch moves.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-head-sha\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Commit SHA of the head of the remote PR/MR branch at fetch time.\n See remote-base-sha for how the pair supports drift detection.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-forge\" type=\"sr:RemoteForgeEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Which forge hosts the remote PR/MR. Names the id space of the\n remote-id attributes on comments and replies, and selects the\n API machinery a future posting feature would use.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileType\">\n <xs:annotation>\n <xs:documentation>\n Represents a single file in the diff. Files with no comments\n appear as empty elements. The path is relative to the repository root.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"comment\" type=\"sr:CommentType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root. For renamed files,\n this is the new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"change-type\" type=\"sr:ChangeTypeEnum\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n The type of change: added, modified, deleted, or renamed.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"viewed\" type=\"xs:boolean\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Whether the reviewer marked this file as reviewed.\n true = the reviewer looked at this file.\n false = the reviewer did not mark this file as viewed.\n This helps an AI agent distinguish \"reviewed with no comments\"\n from \"not yet reviewed.\"\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"CommentType\">\n <xs:annotation>\n <xs:documentation>\n A review comment. Three forms:\n\n 1. File-level comment: no line attributes present.\n Applies to the file as a whole.\n\n 2. Comment on new/added/context lines: new-line-start and\n new-line-end are present. These reference line numbers in the\n post-change version of the file.\n\n 3. Comment on old/deleted lines: old-line-start and old-line-end\n are present. These reference line numbers in the pre-change\n version of the file.\n\n For single-line comments, start and end are equal.\n Exactly one pair (old or new) should be present for line-level\n comments. Both pairs absent = file-level comment.\n\n The category child says what kind of finding this is. The severity\n and confidence attributes say how much weight to put on it: severity\n is how consequential the finding is if it is real, confidence is how\n sure the author is that it is real. They are independent, and an\n automated consumer is expected to threshold on both.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The comment text. May contain markdown formatting.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"category\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n Required category tag for this comment (e.g., \"bug\", \"style\",\n \"nit\", \"question\", \"security\"). Categories are defined in the\n project-level .self-review.yaml configuration. Every comment\n must have a category to help AI agents prioritize and triage\n feedback.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"suggestion\" type=\"sr:SuggestionType\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Optional code replacement proposal. When present, the AI agent\n should replace the original-code with the proposed-code at the\n referenced line range.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment. The path attribute references an image file\n stored in the .self-review-assets/ directory alongside the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"reply\" type=\"sr:ReplyType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional ordered list of replies to this comment. The comment\n itself is the root of the thread; each reply is a later turn in\n the conversation about it.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"old-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the pre-change (old) version of the file.\n Use for comments on deleted lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"old-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the pre-change (old) version.\n Must be >= old-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the post-change (new) version of the file.\n Use for comments on added or context (unchanged) lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the post-change (new) version.\n Must be >= new-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"author\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The author of this comment. When present, indicates the comment\n was generated by a bot or LLM (e.g., \"Claude Sonnet 4.6\").\n When absent, the comment is assumed to be authored by the human\n reviewer.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"severity\" type=\"sr:SeverityEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n How consequential this finding is if it turns out to be real.\n Judge the impact of the problem, not how confident you are that\n the problem exists, and not how much work the fix is.\n\n This attribute has no schema default on purpose. When it is\n absent, a consumer must treat the comment as falling below any\n severity floor it applies, i.e. absent never satisfies a\n threshold. Comments written by a human in the self-review UI\n normally carry no severity.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"confidence\" type=\"sr:ConfidenceEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n How sure the author is that this finding is real, i.e. that it\n describes an actual defect in the code as written rather than a\n hypothetical one.\n\n Confidence is about the evidence, not about how strongly the\n comment is worded. A finding whose argument depends on a\n constraint that is not visible in the diff, on a caller that was\n not read, or on a failure scenario that was imagined rather than\n traced, is low confidence however plausible its prose sounds.\n LLM reviewers systematically overstate certainty here; a\n consumer thresholding on this attribute is relying on it being\n lowered honestly.\n\n This attribute has no schema default on purpose. When it is\n absent, a consumer must treat the comment as falling below any\n confidence floor it applies, i.e. absent never satisfies a\n threshold.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-id\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Identifier of the remote discussion thread or comment this\n comment was fetched from, in the id space of the forge named by\n remote-forge on the review root. Provenance and forward\n machinery: it lets a consumer trace the finding back to its\n origin, and a future posting feature reply to the existing\n thread instead of opening a new one. Absent on comments\n authored locally.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"ReplyType\">\n <xs:annotation>\n <xs:documentation>\n A reply to a review comment. Replies turn a finding into a\n conversation: the comment asserts something, a reply answers it, a\n later reply answers that.\n\n Four rules govern replies. Only the first is beyond what XSD 1.0\n can express, and it is enforced by the application and by the\n skills that author these documents. Rules 2 to 4 are enforced by\n the content model below; they are spelled out anyway, because the\n reason for a constraint is what an author needs in order to write\n a good reply, and a validator only ever reports the constraint:\n\n 1. Replies are ordered. Document order is conversation order, and\n it is the only ordering signal. There are no timestamps and no\n identifiers: the earlier reply is the earlier turn.\n\n 2. Replies are flat. A reply is never nested inside another reply.\n A reply that addresses an earlier reply says so in its body.\n\n 3. A reply carries no thresholding metadata. There is no category,\n no severity and no confidence on a reply. Those are properties\n of the finding, and the finding is the root comment, whose\n severity and confidence govern the whole thread.\n\n 4. A reply carries no suggestion. A concrete counter-proposal goes\n in the reply body as a fenced code block. Allowing a suggestion\n on both the root and a reply would force every consumer to\n invent its own precedence rule.\n\n When a machine consumes a thread, the last human turn is the\n tie-breaker over any earlier machine assertion.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The reply text. May contain markdown formatting, including\n fenced code blocks, which is where a counter-proposal goes\n since replies carry no suggestion element.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment, identical in form and semantics to\n a comment attachment. The path attribute references an image\n file stored in the .self-review-assets/ directory alongside\n the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"author\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The author of this reply, with the same semantics as\n CommentType/@author. When present, the reply was generated by a\n bot or LLM (e.g., \"Claude Opus 5\"). When absent, the reply is\n the human reviewer's.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-id\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Identifier of the remote comment this reply was fetched from,\n with the same semantics as CommentType/@remote-id: an id in the\n forge's own id space, kept for provenance and for a future\n posting feature. Absent on replies authored locally.\n\n A remote-id is not an ordering signal. Document order remains\n conversation order, exactly as rule 1 above states.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"SuggestionType\">\n <xs:annotation>\n <xs:documentation>\n A code replacement proposal. The original-code is the literal text\n currently at the referenced lines. The proposed-code is what the\n reviewer suggests it should be replaced with. The AI agent can apply\n this by performing a text substitution.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"original-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The existing code at the referenced line range, copied verbatim\n from the diff. Used by the AI agent to locate the replacement\n target via text matching.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"proposed-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The replacement code proposed by the reviewer. The AI agent\n should substitute original-code with this text.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n\n <xs:complexType name=\"AttachmentType\">\n <xs:annotation>\n <xs:documentation>\n Reference to an image file attached to a review comment. The file is stored\n alongside the XML output in the .self-review-assets/ directory.\n </xs:documentation>\n </xs:annotation>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>Relative path from the XML file to the image file.</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"media-type\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>MIME type of the image (e.g., image/png, image/jpeg).</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <!-- ===== Simple types ===== -->\n\n <xs:simpleType name=\"ChangeTypeEnum\">\n <xs:annotation>\n <xs:documentation>\n The type of change a file underwent in the diff.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"added\">\n <xs:annotation>\n <xs:documentation>New file that did not exist before.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"modified\">\n <xs:annotation>\n <xs:documentation>Existing file with content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"deleted\">\n <xs:annotation>\n <xs:documentation>File was removed.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"renamed\">\n <xs:annotation>\n <xs:documentation>File was moved or renamed, with or without content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"SeverityEnum\">\n <xs:annotation>\n <xs:documentation>\n How consequential a finding is if it is real. Ordered from most to\n least consequential: critical, major, minor, info.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"critical\">\n <xs:annotation>\n <xs:documentation>\n Causes data loss, a security hole, or a crash or corruption on a\n path that real usage reaches. Shipping this is not acceptable.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"major\">\n <xs:annotation>\n <xs:documentation>\n Produces wrong behaviour, or breaks a documented contract, on a\n path that real usage reaches. The code does not do what it is\n supposed to do, but nothing is destroyed and there is no security\n impact.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"minor\">\n <xs:annotation>\n <xs:documentation>\n Real but bounded: a mishandled edge case that is unlikely to be\n hit, a missing test, a leak of something cheap, or a maintenance\n hazard that will cost time later. Behaviour is correct today.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"info\">\n <xs:annotation>\n <xs:documentation>\n No defect. Style, naming, phrasing, a question for the author, or\n a note recorded for context. Nothing is wrong if this is never\n acted on.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"ConfidenceEnum\">\n <xs:annotation>\n <xs:documentation>\n How sure the author is that a finding is real. Ordered from most to\n least sure: high, medium, low.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"high\">\n <xs:annotation>\n <xs:documentation>\n The evidence is in the code that was read. The failure can be\n traced from the diff itself, and no assumption about unseen code,\n unseen callers, or unstated requirements is needed to reach it.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"medium\">\n <xs:annotation>\n <xs:documentation>\n Likely real, but it rests on one assumption that was not verified,\n such as how a caller behaves, what a dependency guarantees, or\n what the intended requirement was. Stating that assumption in the\n body is expected at this level.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"low\">\n <xs:annotation>\n <xs:documentation>\n Speculative. The failure scenario was imagined rather than traced,\n or the finding depends on a constraint the author invented, or the\n author could not tell intent from the code. Worth a human's eyes,\n not worth acting on unattended.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"RemoteForgeEnum\">\n <xs:annotation>\n <xs:documentation>\n The forge hosting a remote pull/merge request.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"github\">\n <xs:annotation>\n <xs:documentation>A GitHub pull request.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"gitlab\">\n <xs:annotation>\n <xs:documentation>A GitLab merge request.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n</xs:schema>`;\n\nfunction extFromMediaType(mediaType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\n/**\n * Copies one attachment list's in-memory blobs into the asset directory and\n * returns the list with each fileName rewritten to its on-disk location and the\n * data buffer stripped.\n *\n * Shared by the comment walk and the reply walk. Serialization emits the\n * fileName it is given without checking that anything was written, so an\n * attachment list that misses this function produces a document that validates\n * against the schema while pointing at a file that does not exist. That failure\n * has no error surface, which is why both walks go through here.\n *\n * The idPrefix names the resulting files. Comments pass their own id, so\n * existing asset names are unchanged; replies pass a prefix that cannot collide\n * with a comment's.\n */\nfunction persistAttachments(\n attachments: Attachment[] | undefined,\n idPrefix: string,\n assetDir: string,\n onWrite: () => void\n): Attachment[] | undefined {\n if (!attachments?.length) return attachments;\n\n return attachments.map((att, index) => {\n if (!att.data) return att;\n onWrite();\n\n const ext = extFromMediaType(att.mediaType);\n const fileName = `${idPrefix}-${index}.${ext}`;\n const relativePath = `.self-review-assets/${fileName}`;\n\n if (!fs.existsSync(assetDir)) {\n fs.mkdirSync(assetDir, { recursive: true });\n }\n fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));\n\n return { ...att, fileName: relativePath, data: undefined };\n });\n}\n\nfunction writeAttachments(state: ReviewState, outputFilePath: string): ReviewState {\n const assetDir = path.join(path.dirname(outputFilePath), '.self-review-assets');\n let hasAttachments = false;\n const markWritten = () => {\n hasAttachments = true;\n };\n\n const updatedFiles = state.files.map(file => ({\n ...file,\n // Every comment is walked, including one with no attachments of its own:\n // its replies may carry attachments, and short-circuiting on the comment's\n // own list would drop those blobs without a word.\n comments: file.comments.map(comment => ({\n ...comment,\n attachments: persistAttachments(comment.attachments, comment.id, assetDir, markWritten),\n ...(comment.replies\n ? {\n replies: comment.replies.map(reply => ({\n ...reply,\n attachments: persistAttachments(\n reply.attachments,\n `${comment.id}-r-${reply.id}`,\n assetDir,\n markWritten\n ),\n })),\n }\n : {}),\n })),\n }));\n\n if (hasAttachments) {\n console.error(`[main] Wrote attachment files to ${assetDir}`);\n }\n\n return { ...state, files: updatedFiles };\n}\n\nexport async function serializeReview(state: ReviewState, outputFilePath: string): Promise<string> {\n const processedState = writeAttachments(state, outputFilePath);\n const xml = buildXml(processedState);\n\n // Validate the XML against the XSD\n try {\n const validationResult = await validateXML({\n xml: [{ fileName: 'review.xml', contents: xml }],\n schema: [{ fileName: 'self-review-v3.xsd', contents: XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const errors = validationResult.errors || [];\n console.error('XML validation failed:');\n errors.forEach((err: unknown) => console.error(` ${err}`));\n throw new Error('Generated XML does not conform to schema');\n }\n } catch (error) {\n // Re-throw if it's a schema validation failure (our own throw above)\n if (error instanceof Error && error.message === 'Generated XML does not conform to schema') {\n throw error;\n }\n // Infrastructure failure (e.g. WASM load): log warning and return XML anyway\n if (error instanceof Error) {\n console.error(`[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`);\n } else {\n console.error('[main] XML validation infrastructure failed - emitting XML without validation');\n }\n return xml;\n }\n\n return xml;\n}\n\nfunction buildSourceAttributes(state: ReviewState): string {\n const source = state.source;\n if (source.type === 'git') {\n return ` git-diff-args=\"${escapeXml(source.gitDiffArgs)}\" repository=\"${escapeXml(source.repository)}\"`;\n }\n if (source.type === 'directory' || source.type === 'file') {\n return ` source-path=\"${escapeXml(source.sourcePath)}\"`;\n }\n // welcome mode: no source attributes\n return '';\n}\n\n/**\n * Remote provenance attributes on the review root. Like severity and\n * confidence on a comment, absent means \"not a remote review\", so each\n * attribute is emitted only when its field is set: a purely local review\n * serializes byte-identically to a document written before these existed.\n */\nfunction buildRemoteAttributes(state: ReviewState): string {\n const attrs: string[] = [];\n\n if (state.remoteUrl) {\n attrs.push(`remote-url=\"${escapeXml(state.remoteUrl)}\"`);\n }\n if (state.remoteBaseSha) {\n attrs.push(`remote-base-sha=\"${escapeXml(state.remoteBaseSha)}\"`);\n }\n if (state.remoteHeadSha) {\n attrs.push(`remote-head-sha=\"${escapeXml(state.remoteHeadSha)}\"`);\n }\n if (state.remoteForge) {\n attrs.push(`remote-forge=\"${state.remoteForge}\"`);\n }\n\n return attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n}\n\nfunction buildXml(state: ReviewState): string {\n const lines: string[] = [];\n\n // XML declaration\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n\n // Root element with namespace\n const sourceAttrs = buildSourceAttributes(state);\n const remoteAttrs = buildRemoteAttributes(state);\n lines.push(\n `<review xmlns=\"urn:self-review:v3\" timestamp=\"${escapeXml(state.timestamp)}\"${sourceAttrs}${remoteAttrs}>`\n );\n\n // Files\n for (const file of state.files) {\n lines.push(...buildFileXml(file));\n }\n\n // Close root element\n lines.push('</review>');\n\n return lines.join('\\n');\n}\n\nfunction buildFileXml(file: FileReviewState): string[] {\n const lines: string[] = [];\n\n if (file.comments.length === 0) {\n // Self-closing tag for files with no comments\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\" />`\n );\n } else {\n // Opening tag\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\">`\n );\n\n // Comments\n for (const comment of file.comments) {\n lines.push(...buildCommentXml(comment));\n }\n\n // Closing tag\n lines.push(' </file>');\n }\n\n return lines;\n}\n\nfunction buildCommentXml(comment: ReviewComment): string[] {\n const lines: string[] = [];\n const attrs: string[] = [];\n\n // Add line attributes\n if (comment.lineRange) {\n if (comment.lineRange.side === 'old') {\n attrs.push(`old-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`old-line-end=\"${comment.lineRange.end}\"`);\n } else {\n attrs.push(`new-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`new-line-end=\"${comment.lineRange.end}\"`);\n }\n }\n\n if (comment.author) {\n attrs.push(`author=\"${escapeXml(comment.author)}\"`);\n }\n\n // Thresholding signals. Absent means \"below any floor\", so they are omitted\n // rather than defaulted when the author did not take a position.\n if (comment.severity) {\n attrs.push(`severity=\"${comment.severity}\"`);\n }\n\n if (comment.confidence) {\n attrs.push(`confidence=\"${comment.confidence}\"`);\n }\n\n // Remote provenance. Absent means locally authored, so it is omitted\n // rather than defaulted, exactly like the signals above.\n if (comment.remoteId) {\n attrs.push(`remote-id=\"${escapeXml(comment.remoteId)}\"`);\n }\n\n const attrStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n\n // Opening tag\n lines.push(` <comment${attrStr}>`);\n\n // Body (preserve whitespace and newlines)\n lines.push(` <body>${escapeXml(comment.body)}</body>`);\n\n // Category (required)\n lines.push(` <category>${escapeXml(comment.category)}</category>`);\n\n // Suggestion\n if (comment.suggestion) {\n lines.push(' <suggestion>');\n lines.push(\n ` <original-code>${escapeXml(comment.suggestion.originalCode)}</original-code>`\n );\n lines.push(\n ` <proposed-code>${escapeXml(comment.suggestion.proposedCode)}</proposed-code>`\n );\n lines.push(' </suggestion>');\n }\n\n // Attachments\n lines.push(...buildAttachmentXml(comment.attachments, ' '));\n\n // Replies, in array order: document order is conversation order, and it is\n // the only ordering signal a reply has.\n for (const reply of comment.replies ?? []) {\n lines.push(...buildReplyXml(reply));\n }\n\n // Closing tag\n lines.push(' </comment>');\n\n return lines;\n}\n\n/**\n * Attachment elements are identical in form and meaning under a comment and\n * under a reply, so both call sites emit them from here.\n */\nfunction buildAttachmentXml(attachments: Attachment[] | undefined, indent: string): string[] {\n if (!attachments?.length) return [];\n\n return attachments.map(\n att =>\n `${indent}<attachment path=\"${escapeXml(att.fileName)}\" media-type=\"${escapeXml(att.mediaType)}\" />`\n );\n}\n\n/**\n * A reply is a flat turn in the thread: a body, optional attachments and an\n * optional author. It carries no category, severity, confidence, suggestion or\n * nested replies — those belong to the root comment, which owns the finding.\n * See ReplyType in the XSD for the reasoning.\n */\nfunction buildReplyXml(reply: Reply): string[] {\n const attrs: string[] = [];\n\n if (reply.author) {\n attrs.push(`author=\"${escapeXml(reply.author)}\"`);\n }\n if (reply.remoteId) {\n attrs.push(`remote-id=\"${escapeXml(reply.remoteId)}\"`);\n }\n\n const attrStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n\n return [\n ` <reply${attrStr}>`,\n ` <body>${escapeXml(reply.body)}</body>`,\n ...buildAttachmentXml(reply.attachments, ' '),\n ' </reply>',\n ];\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n","// src/main/xml-parser.ts\n// Parse XML review file back into ReviewComment[]\n\nimport { readFileSync } from 'fs';\nimport { XMLParser } from 'fast-xml-parser';\nimport {\n ReviewComment,\n Suggestion,\n LineRange,\n DiffSource,\n CommentSeverity,\n CommentConfidence,\n RemoteForge,\n Attachment,\n Reply,\n} from './types';\n\nconst SEVERITY_VALUES: readonly CommentSeverity[] = ['critical', 'major', 'minor', 'info'];\nconst CONFIDENCE_VALUES: readonly CommentConfidence[] = ['high', 'medium', 'low'];\nconst REMOTE_FORGE_VALUES: readonly RemoteForge[] = ['github', 'gitlab'];\n\nexport interface ParsedReview {\n comments: ReviewComment[];\n /** Paths of files the previous review marked as done (`viewed=\"true\"`). */\n viewedFiles: string[];\n gitDiffArgs: string;\n source: DiffSource;\n // Remote provenance, read tolerantly off the review root. Undefined when\n // the document carries no remote attributes, i.e. every pre-remote and\n // purely local review.\n remoteUrl?: string;\n remoteBaseSha?: string;\n remoteHeadSha?: string;\n remoteForge?: RemoteForge;\n}\n\nexport function parseReviewXml(xmlPath: string): ParsedReview {\n try {\n const xmlContent = readFileSync(xmlPath, 'utf-8');\n return parseReviewXmlString(xmlContent);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error reading XML file: ${error.message}`);\n } else {\n console.error('Error reading XML file: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function parseReviewXmlString(xmlContent: string): ParsedReview {\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n allowBooleanAttributes: true,\n trimValues: false,\n });\n\n try {\n const result = parser.parse(xmlContent);\n\n if (!result.review) {\n throw new Error('Invalid XML: missing <review> root element');\n }\n\n const review = result.review;\n const gitDiffArgs = review['@_git-diff-args'] || '';\n const source = parseSource(review);\n const comments: ReviewComment[] = [];\n const viewedFiles: string[] = [];\n\n // Handle files array\n const files = toChildArray(review.file);\n\n for (const file of files) {\n // Skip only when the attribute is genuinely absent: the empty string\n // is the review-level sentinel path (REVIEW_LEVEL_FILE_PATH) used by\n // fetch-comments for threads with no file anchor, and must round-trip.\n const rawPath = file['@_path'];\n if (rawPath === undefined || rawPath === null) continue;\n const filePath = String(rawPath);\n\n if (parseViewed(file['@_viewed'])) {\n viewedFiles.push(filePath);\n }\n\n // Handle comments array\n const fileComments = toChildArray(file.comment);\n\n for (const comment of fileComments) {\n const reviewComment: ReviewComment = {\n id: generateId(),\n filePath,\n lineRange: parseLineRange(comment),\n body: comment.body !== undefined ? String(comment.body) : '',\n category: comment.category !== undefined ? String(comment.category) : '',\n suggestion: parseSuggestion(comment),\n author: comment['@_author'] ? String(comment['@_author']) : undefined,\n severity: parseEnumAttribute(comment['@_severity'], SEVERITY_VALUES),\n confidence: parseEnumAttribute(comment['@_confidence'], CONFIDENCE_VALUES),\n remoteId: parseStringAttribute(comment['@_remote-id']),\n };\n\n const attachments = parseAttachments(comment, reviewComment.id);\n if (attachments) reviewComment.attachments = attachments;\n\n const replies = parseReplies(comment);\n if (replies) reviewComment.replies = replies;\n\n comments.push(reviewComment);\n }\n }\n\n return {\n comments,\n viewedFiles,\n gitDiffArgs,\n source,\n remoteUrl: parseStringAttribute(review['@_remote-url']),\n remoteBaseSha: parseStringAttribute(review['@_remote-base-sha']),\n remoteHeadSha: parseStringAttribute(review['@_remote-head-sha']),\n remoteForge: parseEnumAttribute(review['@_remote-forge'], REMOTE_FORGE_VALUES),\n };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error parsing XML: ${error.message}`);\n } else {\n console.error('Error parsing XML: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Read an enumerated attribute, dropping values the schema does not define.\n *\n * An unrecognised value becomes undefined rather than being passed through:\n * undefined is the fail-safe reading (below every threshold floor), and it\n * keeps a resumed review serializable, since the serializer validates its\n * output against the XSD before writing.\n */\nfunction parseEnumAttribute<T extends string>(\n raw: unknown,\n allowed: readonly T[]\n): T | undefined {\n if (raw === undefined || raw === null) return undefined;\n const value = String(raw);\n return allowed.includes(value as T) ? (value as T) : undefined;\n}\n\n/**\n * Read an optional free-form string attribute, leaving absent as undefined.\n * Values are taken as-is: the remote attributes are provenance the app never\n * interprets, so there is nothing to validate on read.\n */\nfunction parseStringAttribute(raw: unknown): string | undefined {\n return raw === undefined || raw === null ? undefined : String(raw);\n}\n\n/**\n * Read the `viewed` attribute of a <file> element.\n *\n * Anything other than an explicit true reads as not viewed: the attribute is\n * optional, and treating an unknown value as \"already reviewed\" would silently\n * hide files from the resumed review.\n */\nfunction parseViewed(raw: unknown): boolean {\n return raw === true || String(raw) === 'true';\n}\n\nfunction parseSource(review: Record<string, unknown>): DiffSource {\n const sourcePath = review['@_source-path'];\n if (sourcePath) {\n return { type: 'directory', sourcePath: String(sourcePath) };\n }\n\n const gitDiffArgs = review['@_git-diff-args'];\n const repository = review['@_repository'];\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: String(gitDiffArgs || ''),\n repository: String(repository || ''),\n };\n }\n\n return { type: 'welcome' };\n}\n\nfunction parseLineRange(comment: Record<string, unknown>): LineRange | null {\n const hasOld =\n comment['@_old-line-start'] !== undefined &&\n comment['@_old-line-end'] !== undefined;\n const hasNew =\n comment['@_new-line-start'] !== undefined &&\n comment['@_new-line-end'] !== undefined;\n\n if (hasOld) {\n return {\n side: 'old',\n start: parseInt(String(comment['@_old-line-start']), 10),\n end: parseInt(String(comment['@_old-line-end']), 10),\n };\n }\n\n if (hasNew) {\n return {\n side: 'new',\n start: parseInt(String(comment['@_new-line-start']), 10),\n end: parseInt(String(comment['@_new-line-end']), 10),\n };\n }\n\n return null; // File-level comment\n}\n\nfunction parseSuggestion(comment: Record<string, unknown>): Suggestion | null {\n if (!comment.suggestion) {\n return null;\n }\n\n const suggestion = comment.suggestion as Record<string, unknown>;\n return {\n originalCode: String(suggestion['original-code'] || ''),\n proposedCode: String(suggestion['proposed-code'] || ''),\n };\n}\n\n/**\n * Normalize a repeatable child element into an array.\n *\n * fast-xml-parser collapses a single occurrence into a bare object and only\n * produces an array from two or more, so every repeatable child in this file\n * has to be widened before it can be iterated. An absent child yields an empty\n * array.\n */\nfunction toChildArray(raw: unknown): Record<string, unknown>[] {\n if (Array.isArray(raw)) return raw as Record<string, unknown>[];\n if (raw === undefined || raw === null) return [];\n return [raw as Record<string, unknown>];\n}\n\n/**\n * Read `<attachment>` children of a comment or a reply.\n *\n * Attachment ids are synthetic: nothing in the document names them, so they are\n * derived from the id of their owner, which is why the prefix is a parameter\n * rather than read off the node. Returns undefined rather than [] when there\n * are none, matching the optional field on the type.\n */\nfunction parseAttachments(\n node: Record<string, unknown>,\n idPrefix: string\n): Attachment[] | undefined {\n const raw = toChildArray(node.attachment);\n if (raw.length === 0) return undefined;\n\n return raw.map((att, i) => ({\n id: `${idPrefix}-att-${i}`,\n fileName: String(att['@_path'] || ''),\n mediaType: String(att['@_media-type'] || 'image/png'),\n }));\n}\n\n/**\n * Read `<reply>` children in document order.\n *\n * Document order is conversation order: a reply carries no timestamp and no\n * identifier, so the order of this array is the only ordering signal a thread\n * ever has. Returns undefined rather than [] when there are none, so a\n * reply-free comment keeps exactly the shape it had before threads existed.\n */\nfunction parseReplies(comment: Record<string, unknown>): Reply[] | undefined {\n const raw = toChildArray(comment.reply);\n if (raw.length === 0) return undefined;\n\n return raw.map(node => {\n const id = generateId();\n const reply: Reply = {\n id,\n body: node.body !== undefined ? String(node.body) : '',\n author: node['@_author'] ? String(node['@_author']) : undefined,\n remoteId: parseStringAttribute(node['@_remote-id']),\n };\n\n const attachments = parseAttachments(node, id);\n if (attachments) reply.attachments = attachments;\n\n return reply;\n });\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// packages/core/src/guide-schema.ts\n// Embedded copy of the walkthrough guide XSD for validation.\n\n// This MUST stay byte-identical to the on-disk copy at\n// .agents/skills/self-review-guide/assets/self-review-guide-v1.xsd;\n// the sync test in xsd-schema.test.ts enforces it.\nexport const GUIDE_XSD_SCHEMA = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sg=\"urn:self-review-guide:v1\"\n targetNamespace=\"urn:self-review-guide:v1\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review guide XML Schema v1\n ===============================\n Defines the walkthrough guide sidecar for the self-review application.\n This schema is designed to be both machine-validated and fed to an LLM\n so it can author valid guide documents from the schema alone.\n\n Key concepts:\n - A <guide> is a read-only orientation aid generated BEFORE a review\n starts. It lives next to the review output file and is discovered by\n convention; it is never written by the review UI.\n - The optional <overview> is short Markdown prose shown before the\n first file, orienting the reviewer to the change as a whole.\n - Each <group> names a set of files that belong together (for example\n \"Core change\", \"Tests\", \"Generated/mechanical\") and explains, in one\n line, why they are grouped and where they sit in the reading order.\n - Each <file> inside a group points at one diff file by its\n repository-relative path and carries a one-line description of the\n role that file plays in the change.\n\n Ordering:\n - Document order IS the reading order. Groups are presented in the\n order they appear, and files within a group are presented in the\n order they appear. There are no explicit ordering attributes; to\n reorder, reorder the elements.\n\n Presentation only, never suppression:\n - This vocabulary labels and orders content; it cannot hide it. There\n is deliberately no element or attribute that hides, collapses, or\n marks a file as skippable, and none may be added to v1. Files in the\n diff that no group mentions remain fully visible in an implicit\n \"Everything else\" group; files mentioned here but absent from the\n diff are silently ignored.\n\n Tolerance:\n - A missing, stale, or invalid guide degrades the consumer to its\n normal ungrouped view. A guide can therefore never block or fail a\n review, but an invalid guide is silently useless, so authors should\n validate against this schema before writing the file.\n -->\n\n <!-- ===== Root element ===== -->\n\n <xs:element name=\"guide\" type=\"sg:GuideType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review walkthrough guide sidecar. Contains\n an optional overview followed by zero or more ordered groups.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <!-- ===== Complex types ===== -->\n\n <xs:complexType name=\"GuideType\">\n <xs:annotation>\n <xs:documentation>\n The whole walkthrough guide. The optional metadata attributes\n mirror the review schema's provenance attributes so a consumer can\n sanity-check that the guide was generated for the diff it is being\n shown next to; none of them are required and none affect\n presentation.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"overview\" type=\"xs:string\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Review-level orientation prose shown before the first file.\n Markdown formatting is allowed, including fenced code blocks;\n a fenced code block labelled \"mermaid\" may be used for a\n diagram of the change.\n Keep it short: a few sentences saying what the change does and\n where to start reading, not a restatement of every file.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"group\" type=\"sg:GroupType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Ordered reading groups. The first group should hold the files\n the reviewer must understand first (the core of the change);\n later groups hold consequences, tests, and mechanical fallout.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the guide was generated.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments the guide was generated against.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when the guide describes a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root the guide was generated in.\n Present only when the guide describes a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"GroupType\">\n <xs:annotation>\n <xs:documentation>\n A named set of related files with a one-line rationale. Groups are\n labels for orientation, never suppressions: a consumer shows every\n group and every file in it. Position in the document is position\n in the reading order.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"rationale\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n One line explaining why these files form a group and what the\n reviewer should look for in them (e.g., \"The retry wrapper\n everything else calls; read this first\"). Plain text, a single\n sentence; no Markdown, no line breaks.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"file\" type=\"sg:FileEntryType\" minOccurs=\"1\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n The files in this group, in reading order. A group must list\n at least one file; do not author empty placeholder groups.\n Every file in the diff may appear in at most one group, and\n files omitted from every group are not hidden — the consumer\n shows them in an implicit trailing \"Everything else\" group.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Short display name for the group, e.g. \"Core change\", \"Tests\",\n \"Generated/mechanical\". Shown as the group heading in the file\n tree; keep it to a few words.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileEntryType\">\n <xs:annotation>\n <xs:documentation>\n One file in a group. The path must match a file in the diff being\n reviewed; entries whose path matches nothing in the diff are\n silently dropped by the consumer, so a stale guide degrades\n instead of erroring.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"description\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n One line describing the role this file plays in the change\n (e.g., \"Adds the retry wrapper that everything else calls\").\n Plain text, a single sentence; no Markdown, no line breaks.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root, using the same\n convention as review.xml file paths. For renamed files, use the\n new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n</xs:schema>`;\n","// packages/core/src/guide-parser.ts\n// Parse a walkthrough guide XML string into a typed ReviewGuide, and\n// reconcile a guide with the diff's file list into resolved display groups.\n//\n// Tolerance contract (binding, from docs/intent/llm-review-guide.md): the\n// guide is orientation garnish on a deterministic tool. A missing, stale, or\n// invalid guide degrades the consumer to its flat view — parsing problems\n// are failure VALUES the caller can log and ignore, never exceptions.\n\nimport { XMLParser } from 'fast-xml-parser';\nimport { validateXML } from 'xmllint-wasm';\nimport type {\n GuideFileEntry,\n GuideGroup,\n ResolvedGuideGroup,\n ResolvedGuideFile,\n ReviewGuide,\n} from './types';\nimport { GUIDE_XSD_SCHEMA } from './guide-schema';\n\n/** Display name given to the derived trailing group of unmentioned files. */\nexport const IMPLICIT_GUIDE_GROUP_NAME = 'Everything else';\n\nexport type GuideParseResult =\n | { ok: true; guide: ReviewGuide }\n | { ok: false; reason: string };\n\n/**\n * Parse and validate a guide XML string.\n *\n * The document is validated against the embedded self-review-guide-v1 XSD\n * (same xmllint-wasm tooling the review serializer uses) before being read,\n * so a successful result is structurally guaranteed by the schema. Any\n * defect — non-XML input, schema violations, validator failure — comes back\n * as `{ ok: false, reason }`; this function never throws on bad input.\n */\nexport async function parseGuideXml(xmlContent: string): Promise<GuideParseResult> {\n try {\n const validationResult = await validateXML({\n xml: [{ fileName: 'guide.xml', contents: xmlContent }],\n schema: [\n { fileName: 'self-review-guide-v1.xsd', contents: GUIDE_XSD_SCHEMA },\n ],\n });\n\n if (!validationResult.valid) {\n const details = (validationResult.errors || [])\n .map(err => (typeof err === 'string' ? err : err.message))\n .join('; ');\n return {\n ok: false,\n reason: `Guide XML does not conform to self-review-guide-v1 schema${details ? `: ${details}` : ''}`,\n };\n }\n\n return { ok: true, guide: readGuide(xmlContent) };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, reason: `Failed to parse guide XML: ${message}` };\n }\n}\n\n/**\n * Extract the typed guide from a document that already passed XSD\n * validation. Values are still string-coerced defensively, but structural\n * guarantees (required attributes/elements, at least one file per group)\n * come from the schema.\n */\nfunction readGuide(xmlContent: string): ReviewGuide {\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n // Keep values verbatim: a description like \"007\" or an overview of\n // \"true\" must stay a string, not become a number or boolean.\n parseTagValue: false,\n parseAttributeValue: false,\n // A prefixed form (<sg:guide xmlns:sg=\"urn:self-review-guide:v1\">) is\n // schema-valid, so reading must accept it too; without this the lookup\n // of `.guide` below finds nothing.\n removeNSPrefix: true,\n });\n\n const root = parser.parse(xmlContent).guide as Record<string, unknown>;\n\n const guide: ReviewGuide = { groups: asArray(root.group).map(readGroup) };\n\n const overview = root.overview;\n if (typeof overview === 'string' && overview !== '') {\n guide.overview = overview;\n }\n\n return guide;\n}\n\nfunction readGroup(raw: unknown): GuideGroup {\n const group = raw as Record<string, unknown>;\n return {\n name: String(group['@_name']),\n rationale: String(group.rationale ?? ''),\n files: asArray(group.file).map(readFileEntry),\n };\n}\n\nfunction readFileEntry(raw: unknown): GuideFileEntry {\n const file = raw as Record<string, unknown>;\n return {\n path: String(file['@_path']),\n description: String(file.description ?? ''),\n };\n}\n\n/** fast-xml-parser yields a bare object for singular elements; normalize. */\nfunction asArray(value: unknown): unknown[] {\n if (value === undefined || value === null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Merge a parsed guide with the diff's file list into resolved display\n * groups, tolerantly:\n *\n * - Guide entries whose path is not in the diff are dropped (stale guide);\n * a group left with no surviving files is dropped entirely.\n * - A file referenced by more than one group appears only in the first.\n * - Diff files no group mentions land in a terminal implicit\n * \"Everything else\" group, preserving the diff's file order, marked\n * `implicit: true` so the UI can label it.\n * - Guide group order and in-group file order are preserved.\n */\nexport function reconcileGuide(\n guide: ReviewGuide,\n diffFilePaths: string[]\n): ResolvedGuideGroup[] {\n const diffPaths = new Set(diffFilePaths);\n const claimed = new Set<string>();\n const resolved: ResolvedGuideGroup[] = [];\n\n for (const group of guide.groups) {\n const files: ResolvedGuideFile[] = [];\n for (const file of group.files) {\n if (!diffPaths.has(file.path) || claimed.has(file.path)) continue;\n claimed.add(file.path);\n files.push({ path: file.path, description: file.description });\n }\n if (files.length > 0) {\n resolved.push({\n name: group.name,\n rationale: group.rationale,\n implicit: false,\n files,\n });\n }\n }\n\n const leftover = diffFilePaths.filter(path => !claimed.has(path));\n if (leftover.length > 0) {\n resolved.push({\n name: IMPLICIT_GUIDE_GROUP_NAME,\n implicit: true,\n files: leftover.map(path => ({ path })),\n });\n }\n\n return resolved;\n}\n","// src/main/git.ts\n// Git command execution\n\nimport { execSync, exec, execFile } from 'child_process';\nimport { promisify } from 'util';\nimport { generateSyntheticDiffs } from './synthetic-diff';\n\nconst execAsync = promisify(exec);\n\nexport function runGitDiff(args: string[]): string {\n try {\n // Check if git is available\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n // Check if we're in a git repository\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n\n // Run git diff with the provided arguments\n const result = execSync(`git diff ${args.join(' ')}`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large diffs\n });\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function getRepoRoot(): string {\n try {\n const result = execSync('git rev-parse --show-toplevel', {\n encoding: 'utf-8',\n });\n return result.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Lightweight sync validation - checks if git is available and we're in a repo.\n * Called BEFORE Electron initialization for early exit path.\n */\nexport function validateGitAvailable(): void {\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n}\n\n/**\n * Async version of getRepoRoot - called AFTER app.whenReady().\n */\nexport async function getRepoRootAsync(cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync('git rev-parse --show-toplevel', {\n timeout: 10000, // 10 second timeout\n cwd,\n });\n return stdout.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Async version of runGitDiff - called AFTER app.whenReady().\n * Uses timeout to prevent hanging in CI environments.\n */\nexport async function runGitDiffAsync(args: string[], cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`git diff ${args.join(' ')}`, {\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer\n timeout: 30000, // 30 second timeout\n cwd,\n });\n return stdout;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Read a blob from a git object spec (`<sha>:<path>`) as raw bytes.\n * Remote mode reads reviewed content at the fetched head SHA — a temporary\n * clone's working tree stays on the default branch and never reflects the\n * PR/MR head.\n */\nexport async function readGitBlobAsync(\n repoPath: string,\n spec: string\n): Promise<Buffer> {\n return await new Promise<Buffer>((resolve, reject) => {\n execFile(\n 'git',\n ['-C', repoPath, 'show', spec],\n { encoding: 'buffer', maxBuffer: 50 * 1024 * 1024, timeout: 30000 },\n (error, stdout) => {\n if (error) {\n reject(error);\n } else {\n resolve(stdout);\n }\n }\n );\n });\n}\n\n/**\n * Get list of untracked files (respects .gitignore).\n */\nexport async function getUntrackedFilesAsync(cwd?: string): Promise<string[]> {\n try {\n const { stdout } = await execAsync(\n 'git ls-files --others --exclude-standard',\n {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 10000,\n cwd,\n }\n );\n return stdout\n .trim()\n .split('\\n')\n .filter(line => line.length > 0);\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Warning: Failed to list untracked files: ${error.message}`\n );\n } else {\n console.error('Warning: Failed to list untracked files: unknown error');\n }\n return [];\n }\n}\n\n/**\n * Generate synthetic unified diffs for untracked files so they can be\n * parsed by the existing diff parser.\n *\n * Delegates to the reusable generateSyntheticDiffs module.\n */\nexport function generateUntrackedDiffs(\n paths: string[],\n repoRoot: string\n): string {\n return generateSyntheticDiffs(paths, repoRoot);\n}\n","// src/main/synthetic-diff.ts\n// Generates synthetic unified diffs for files that aren't tracked by git.\n// Reusable by both git untracked file handling and directory-based scanning.\n\nimport { readFileSync } from 'fs';\n\n/**\n * Generate synthetic unified diffs for a list of file paths so they can be\n * parsed by the existing diff parser. Each file is treated as a new addition.\n *\n * @param paths - Relative file paths (e.g. \"src/foo.ts\")\n * @param rootDir - Absolute path to the root directory containing the files\n * @returns A unified diff string covering all provided files\n */\nexport function generateSyntheticDiffs(\n paths: string[],\n rootDir: string\n): string {\n const diffs: string[] = [];\n\n for (const filePath of paths) {\n const fullPath = `${rootDir}/${filePath}`;\n let content: Buffer;\n try {\n content = readFileSync(fullPath);\n } catch {\n // File may have been deleted between listing and reading\n continue;\n }\n\n // Detect binary files by checking for null bytes in the first 8KB\n const sample = content.subarray(0, 8192);\n const isBinary = sample.includes(0);\n\n if (isBinary) {\n diffs.push(\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `Binary files /dev/null and b/${filePath} differ`\n );\n continue;\n }\n\n const text = content.toString('utf-8');\n const lines = text.split('\\n');\n\n // Remove trailing empty string from split if file ends with newline\n if (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n\n const lineCount = lines.length;\n const addedLines = lines.map(line => `+${line}`).join('\\n');\n\n let diff =\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `--- /dev/null\\n` +\n `+++ b/${filePath}\\n` +\n `@@ -0,0 +1,${lineCount} @@\\n` +\n addedLines;\n\n // Indicate missing newline at end of file\n if (text.length > 0 && !text.endsWith('\\n')) {\n diff += '\\n\\\';\n }\n\n diffs.push(diff);\n }\n\n return diffs.join('\\n');\n}\n","// forge-provider.ts\n// Conversation-plane forge abstraction: URL parsing with forge detection by\n// path shape, the ForgeProvider interface (base-branch lookup + thread fetch),\n// and the forge-neutral normalized thread types produced by every provider.\n//\n// This module is pure code: no I/O, no child processes. Provider\n// implementations (github-provider.ts, gitlab-provider.ts) do the CLI work\n// through an injectable command runner so they stay unit-testable.\n\n/** Forges the app knows how to talk to. */\nexport type ForgeName = 'github' | 'gitlab';\n\n/**\n * A parsed pull-request / merge-request web URL.\n *\n * Detection is by URL path shape only (`/pull/N` → GitHub,\n * `/-/merge_requests/N` → GitLab) on any host, so self-hosted instances such\n * as git.drupalcode.org work with zero configuration.\n */\nexport interface ForgeUrl {\n forge: ForgeName;\n /** Host as it appears in the URL, including a port when present. */\n host: string;\n /**\n * Repository owner. For GitLab this is the full namespace path and may\n * contain slashes (subgroups, e.g. `group/subgroup`); for GitHub it is a\n * single segment.\n */\n owner: string;\n /** Repository name (final path segment before the PR/MR marker). */\n repo: string;\n /** Pull-request number / merge-request IID. */\n number: number;\n}\n\n/** Which side of the diff a thread anchor points at. */\nexport type ForgeAnchorSide = 'old' | 'new';\n\n/**\n * Forge-neutral anchor of a discussion thread onto the diff.\n *\n * The mapper consumes this shape without forge-conditional logic:\n * - `startLine`/`endLine` are equal for single-line anchors.\n * - `startLine`/`endLine` are `null` when the forge supplies a file path but\n * no usable line information (the mapper degrades to a file-level comment;\n * `side` is meaningless in that case and providers should set `'new'`).\n * - `outdated: true` means the forge reports the anchor no longer applies to\n * the current head (e.g. GitHub outdated review comments); the line fields\n * then hold the historic anchor and the mapper degrades to file-level.\n */\nexport interface ForgeThreadAnchor {\n filePath: string;\n side: ForgeAnchorSide;\n startLine: number | null;\n endLine: number | null;\n outdated: boolean;\n}\n\n/** One turn (root comment or reply) in a forge discussion thread. */\nexport interface ForgeThreadTurn {\n /** Forge-assigned comment/note ID, kept as a string verbatim. */\n remoteId: string;\n /** Forge username of the turn's author. */\n author: string;\n /** Markdown body, passed through verbatim. */\n body: string;\n}\n\n/**\n * A normalized discussion thread: an ordered root + flat replies.\n *\n * The root turn owns the anchor. `anchor` is `null` for threads with no file\n * association at all (e.g. GitLab non-diff discussions); the mapper turns\n * those into its review-level representation. `replies` preserve the forge's\n * document order — nothing else sorts them.\n */\nexport interface ForgeThread {\n root: ForgeThreadTurn;\n replies: ForgeThreadTurn[];\n anchor: ForgeThreadAnchor | null;\n}\n\n/** Options for {@link ForgeProvider.fetchThreads}. */\nexport interface FetchThreadsOptions {\n /**\n * Include threads the forge marks resolved. Defaults to false where the\n * forge tracks resolution (GitLab); providers without a comparable concept\n * on the fetch path (GitHub REST review comments) may ignore it.\n */\n includeResolved?: boolean;\n}\n\n/**\n * Result of running a forge CLI command through {@link ForgeCommandRunner}.\n */\nexport interface ForgeCommandResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n}\n\n/**\n * Injectable command runner used by provider implementations, mirroring how\n * `git.ts` keeps child-process execution testable. Resolves with the exit\n * code on any completed run (including non-zero); rejects only when the\n * binary cannot be spawned at all (e.g. ENOENT when the CLI is absent).\n */\nexport type ForgeCommandRunner = (\n command: string,\n args: string[]\n) => Promise<ForgeCommandResult>;\n\n/**\n * The conversation plane of a forge. Exactly two capabilities: base-branch\n * lookup and discussion-thread fetching. No diff fetching, no blob fetching,\n * no posting — those concerns live elsewhere.\n *\n * Implementations throw {@link ForgeCliUnavailableError} when their CLI is\n * absent or unauthenticated so callers can degrade cleanly.\n */\nexport interface ForgeProvider {\n readonly forge: ForgeName;\n /** Resolve the PR/MR base (target) branch name. */\n fetchBaseBranch(url: ForgeUrl): Promise<string>;\n /** Fetch the PR/MR discussion threads in normalized form. */\n fetchThreads(\n url: ForgeUrl,\n options?: FetchThreadsOptions\n ): Promise<ForgeThread[]>;\n}\n\n/**\n * Thrown by providers when their CLI is missing (spawn ENOENT) or exits\n * non-zero due to authentication/API failure. Callers catch this to degrade\n * (print to stderr, continue without threads) instead of crashing.\n */\nexport class ForgeCliUnavailableError extends Error {\n readonly forge: ForgeName;\n readonly cli: string;\n\n constructor(forge: ForgeName, cli: string, message: string) {\n super(message);\n this.name = 'ForgeCliUnavailableError';\n this.forge = forge;\n this.cli = cli;\n }\n}\n\n// Path-shape matchers. The number must terminate its path segment so\n// `/pull/12x` does not parse as PR 12; anything after the number segment\n// (trailing slash, sub-pages like /files) still identifies the same PR/MR.\n// Numbered groups (owner, repo, number in order): the app tsconfig targets\n// ES6, which predates named capture groups.\nconst GITHUB_PR_PATH = /^\\/([^/]+)\\/([^/]+)\\/pull\\/(\\d+)(?=\\/|$)/;\nconst GITLAB_MR_PATH = /^\\/(.+)\\/([^/]+)\\/-\\/merge_requests\\/(\\d+)(?=\\/|$)/;\n\n/**\n * Parse a forge web URL into a {@link ForgeUrl}, or return `null` for\n * anything that is not a PR/MR URL. Detection is by path shape only, on any\n * http(s) host. Query strings and fragments are ignored.\n */\nexport function parseForgeUrl(url: string): ForgeUrl | null {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return null;\n }\n\n // GitLab first: `/-/merge_requests/` is the more specific marker.\n const gitlab = GITLAB_MR_PATH.exec(parsed.pathname);\n if (gitlab) {\n return {\n forge: 'gitlab',\n host: parsed.host,\n owner: gitlab[1],\n repo: gitlab[2],\n number: Number.parseInt(gitlab[3], 10),\n };\n }\n\n const github = GITHUB_PR_PATH.exec(parsed.pathname);\n if (github) {\n return {\n forge: 'github',\n host: parsed.host,\n owner: github[1],\n repo: github[2],\n number: Number.parseInt(github[3], 10),\n };\n }\n\n return null;\n}\n","// src/main/directory-scanner.ts\n// Recursively scans a directory and produces DiffFile[] treating all files as new additions.\n\nimport { readdir, stat } from 'fs/promises';\nimport { join, relative, basename, dirname } from 'path';\nimport { DiffFile } from './types';\nimport { generateSyntheticDiffs } from './synthetic-diff';\nimport { parseDiff } from './diff-parser';\nimport { createIgnoreFilter } from './ignore-filter';\n\n/**\n * Recursively scan a directory and return DiffFile[] with every file\n * treated as a new addition (changeType: 'added').\n *\n * @param directoryPath - Absolute path to the directory to scan\n * @param ignorePatterns - Optional gitignore-compatible patterns to exclude files\n * @returns Parsed DiffFile array for all files in the directory\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = []\n): Promise<DiffFile[]> {\n // Verify the path is a directory\n try {\n const dirStat = await stat(directoryPath);\n if (!dirStat.isDirectory()) {\n console.error(\n `Error: \"${directoryPath}\" is not a directory`\n );\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error accessing directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error accessing directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n const filePaths: string[] = [];\n\n try {\n const entries = await readdir(directoryPath, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n\n // Build the full path from the entry's parentPath (or path) and name\n const parentDir = entry.parentPath ?? entry.path;\n const fullPath = join(parentDir, entry.name);\n const relativePath = relative(directoryPath, fullPath);\n filePaths.push(relativePath);\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error reading directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error reading directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n // Sort for deterministic output\n filePaths.sort();\n\n // Apply ignore patterns\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredPaths = filePaths.filter(p => shouldKeep(p));\n\n if (filteredPaths.length === 0) {\n return [];\n }\n\n const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);\n return parseDiff(diffText);\n}\n\n/**\n * Scan a single file and return DiffFile[] with the file treated as a new addition.\n *\n * @param filePath - Absolute path to the file to scan\n * @returns Parsed DiffFile array (single element)\n */\nexport async function scanFile(filePath: string): Promise<DiffFile[]> {\n try {\n const fileStat = await stat(filePath);\n if (!fileStat.isFile()) {\n console.error(`Error: \"${filePath}\" is not a file`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing file \"${filePath}\": ${error.message}`);\n } else {\n console.error(`Error accessing file \"${filePath}\": unknown error`);\n }\n return [];\n }\n\n const fileName = basename(filePath);\n const rootDir = dirname(filePath);\n const diffText = generateSyntheticDiffs([fileName], rootDir);\n return parseDiff(diffText);\n}\n","// src/main/ignore-filter.ts\n// Gitignore-compatible file path filtering using the `ignore` package.\n\nimport ignore from 'ignore';\n\n/**\n * Create a filter function from gitignore-compatible patterns.\n *\n * @param patterns - Array of gitignore-compatible glob patterns\n * @returns A predicate that returns `true` if the path should be kept (not ignored)\n */\nexport function createIgnoreFilter(\n patterns: string[]\n): (path: string) => boolean {\n if (patterns.length === 0) return () => true;\n const ig = ignore().add(patterns);\n return (filePath: string) => !ig.ignores(filePath);\n}\n","// src/main/config.ts\n// YAML configuration loading and merging\n\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { parse as parseYaml } from 'yaml';\nimport { AppConfig } from './types';\n\nconst defaults: AppConfig = {\n theme: 'system',\n diffView: 'split',\n fontSize: 14,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: [\n '.git',\n 'node_modules',\n 'vendor',\n '.vendor',\n '__pycache__',\n '.venv',\n 'venv',\n '.env',\n 'dist',\n 'build',\n '.next',\n '.nuxt',\n '.svelte-kit',\n 'target',\n '*.min.js',\n '*.min.css',\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Gemfile.lock',\n 'Cargo.lock',\n 'poetry.lock',\n 'go.sum',\n ],\n categories: [\n {\n name: 'question',\n description: 'Clarification needed — not necessarily a problem',\n color: '#805ad5',\n },\n {\n name: 'bug',\n description: 'Likely defect or incorrect behavior',\n color: '#e53e3e',\n },\n {\n name: 'security',\n description: 'Security vulnerability or concern',\n color: '#dd6b20',\n },\n {\n name: 'style',\n description: 'Code style, naming, or formatting issue',\n color: '#3182ce',\n },\n {\n name: 'task',\n description: 'Action item or follow-up task',\n color: '#38a169',\n },\n {\n name: 'nit',\n description: 'Minor nitpick, low priority',\n color: '#718096',\n },\n ],\n defaultDiffArgs: '',\n showUntracked: true,\n showUntrackedExplicit: false,\n wordWrap: true,\n maxFiles: 500,\n maxTotalLines: 100000,\n};\n\nexport function loadConfig(): AppConfig {\n let config = { ...defaults };\n\n // Load user-level config\n const userConfigPath = join(\n homedir(),\n '.config',\n 'self-review',\n 'config.yaml'\n );\n if (existsSync(userConfigPath)) {\n try {\n const userConfig = loadYamlConfig(userConfigPath);\n config = mergeConfig(config, userConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load user config from ${userConfigPath}: ${error}`\n );\n }\n }\n\n // Load project-level config\n const projectConfigPath = join(process.cwd(), '.self-review.yaml');\n if (existsSync(projectConfigPath)) {\n try {\n const projectConfig = loadYamlConfig(projectConfigPath);\n config = mergeConfig(config, projectConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load project config from ${projectConfigPath}: ${error}`\n );\n }\n }\n\n return config;\n}\n\nfunction loadYamlConfig(path: string): Partial<AppConfig> {\n const content = readFileSync(path, 'utf-8');\n const raw = parseYaml(content);\n\n // An empty file (or one containing only `null`) is a valid \"use defaults\" state.\n if (raw === null || raw === undefined) {\n return {};\n }\n\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error('Invalid YAML format');\n }\n\n // Map kebab-case keys to camelCase\n const config: Partial<AppConfig> = {};\n\n if ('theme' in raw) {\n if (['light', 'dark', 'system'].includes(raw.theme)) {\n config.theme = raw.theme;\n } else {\n console.error(\n `Warning: Invalid theme value \"${raw.theme}\", using default`\n );\n }\n }\n\n if ('diff-view' in raw) {\n if (['split', 'unified'].includes(raw['diff-view'])) {\n config.diffView = raw['diff-view'];\n } else {\n console.error(\n `Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`\n );\n }\n }\n\n if ('font-size' in raw && typeof raw['font-size'] === 'number') {\n config.fontSize = raw['font-size'];\n }\n\n if ('output-format' in raw && typeof raw['output-format'] === 'string') {\n config.outputFormat = raw['output-format'];\n }\n\n if ('ignore' in raw && Array.isArray(raw.ignore)) {\n config.ignore = raw.ignore.filter(\n (item: unknown) => typeof item === 'string'\n );\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n config.categories = raw.categories.filter(\n (cat: unknown): cat is { name: string; description: string; color: string } =>\n cat !== null &&\n typeof cat === 'object' &&\n typeof (cat as Record<string, unknown>).name === 'string' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n }\n\n if (\n 'default-diff-args' in raw &&\n typeof raw['default-diff-args'] === 'string'\n ) {\n config.defaultDiffArgs = raw['default-diff-args'];\n }\n\n if ('show-untracked' in raw && typeof raw['show-untracked'] === 'boolean') {\n config.showUntracked = raw['show-untracked'];\n config.showUntrackedExplicit = true;\n }\n\n if ('word-wrap' in raw && typeof raw['word-wrap'] === 'boolean') {\n config.wordWrap = raw['word-wrap'];\n }\n\n if ('max-files' in raw && typeof raw['max-files'] === 'number') {\n config.maxFiles = raw['max-files'] >= 0 ? raw['max-files'] : defaults.maxFiles;\n }\n\n if ('max-total-lines' in raw && typeof raw['max-total-lines'] === 'number') {\n config.maxTotalLines = raw['max-total-lines'] >= 0 ? raw['max-total-lines'] : defaults.maxTotalLines;\n }\n\n if (\n 'output-file' in raw &&\n typeof raw['output-file'] === 'string' &&\n raw['output-file'].length > 0\n ) {\n config.outputFile = raw['output-file'];\n }\n\n if (\n 'guide-file' in raw &&\n typeof raw['guide-file'] === 'string' &&\n raw['guide-file'].length > 0\n ) {\n config.guideFile = raw['guide-file'];\n }\n\n return config;\n}\n\nfunction mergeConfig(base: AppConfig, override: Partial<AppConfig>): AppConfig {\n return {\n ...base,\n ...override,\n // Arrays are replaced, not merged\n ignore: override.ignore !== undefined ? override.ignore : base.ignore,\n categories:\n override.categories !== undefined ? override.categories : base.categories,\n };\n}\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execAsync = promisify(exec);\n\n/**\n * Compute payload statistics and check against configured thresholds.\n * A maxFiles or maxTotalLines value of 0 disables that guard.\n */\nexport function computePayloadStats(\n fileCount: number,\n totalLines: number,\n config: AppConfig\n): PayloadStats {\n const maxFiles = config.maxFiles;\n const maxTotalLines = config.maxTotalLines;\n const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;\n const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;\n return {\n fileCount,\n totalLines,\n exceedsFiles,\n exceedsLines,\n exceedsAny: exceedsFiles || exceedsLines,\n };\n}\n\n/**\n * Count total diff lines across all files and hunks.\n */\nexport function countTotalLines(files: DiffFile[]): number {\n let total = 0;\n for (const file of files) {\n for (const hunk of file.hunks) {\n total += hunk.lines.length;\n }\n }\n return total;\n}\n\n/**\n * Get git diff stats cheaply using --numstat (avoids full diff parsing).\n * Each output line is \"added\\tremoved\\tfilename\".\n * Returns file count and total changed lines (added + removed).\n */\nexport async function getGitDiffStats(\n args: string[],\n repoRoot: string\n): Promise<{ fileCount: number; totalLines: number }> {\n try {\n const { stdout } = await execAsync(`git diff --numstat ${args.join(' ')}`, {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 15000,\n cwd: repoRoot,\n });\n\n let fileCount = 0;\n let totalLines = 0;\n\n for (const line of stdout.trim().split('\\n')) {\n if (!line) continue;\n const parts = line.split('\\t');\n if (parts.length < 3) continue;\n\n fileCount++;\n // Binary files show '-' for added/removed\n const added = parts[0] === '-' ? 0 : parseInt(parts[0], 10);\n const removed = parts[1] === '-' ? 0 : parseInt(parts[1], 10);\n totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);\n }\n\n return { fileCount, totalLines };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);\n } else {\n console.error('[payload-sizing] Failed to get git diff stats: unknown error');\n }\n // Return zeros so the guard does not block on failure\n return { fileCount: 0, totalLines: 0 };\n }\n}\n","// src/main/fs-utils.ts\n// Filesystem utility functions for the main process.\n\nimport { accessSync, constants as fsConstants } from 'fs';\nimport { dirname } from 'path';\n\n/**\n * Check if a file's parent directory is writable.\n * Returns true if the directory exists and the process has write permission,\n * false otherwise (including non-existent directories).\n */\nexport function checkWritability(filePath: string): boolean {\n try {\n const dir = dirname(filePath);\n accessSync(dir, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * File-type detection utilities.\n *\n * NOTE: This file is intentionally duplicated in packages/react/src/utils/file-type-utils.ts.\n * @self-review/core has Node-only dependencies, so @self-review/react cannot safely import\n * from this package. Both copies must be kept in sync.\n */\n\nconst RASTER_IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.ico', '.bmp']);\nconst MARKDOWN_EXTENSIONS = new Set(['.md', '.markdown']);\nconst HTML_EXTENSIONS = new Set(['.html', '.htm']);\n\nexport type RenderedTextMode = 'markdown' | 'html';\n\nfunction getExtension(filePath: string): string {\n const lastDot = filePath.lastIndexOf('.');\n if (lastDot === -1 || lastDot === filePath.length - 1) return '';\n return filePath.slice(lastDot).toLowerCase();\n}\n\nexport function isPreviewableImage(filePath: string): boolean {\n return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isPreviewableSvg(filePath: string): boolean {\n return getExtension(filePath) === '.svg';\n}\n\nexport function isMarkdownFile(filePath: string): boolean {\n return MARKDOWN_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isHtmlFile(filePath: string): boolean {\n return HTML_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function getRenderedTextMode(filePath: string): RenderedTextMode | null {\n if (isMarkdownFile(filePath)) return 'markdown';\n if (isHtmlFile(filePath)) return 'html';\n return null;\n}\n\nexport function isPreviewableRenderedText(filePath: string): boolean {\n return getRenderedTextMode(filePath) !== null;\n}\n\nexport function getLanguageFromPath(filePath: string): string {\n const ext = filePath.split('.').pop()?.toLowerCase() || '';\n const langMap: Record<string, string> = {\n ts: 'typescript',\n tsx: 'tsx',\n js: 'javascript',\n jsx: 'jsx',\n py: 'python',\n css: 'css',\n json: 'json',\n md: 'markdown',\n markdown: 'markdown',\n sh: 'bash',\n bash: 'bash',\n yml: 'yaml',\n yaml: 'yaml',\n java: 'java',\n go: 'go',\n rs: 'rust',\n sql: 'sql',\n html: 'markup',\n htm: 'markup',\n xml: 'markup',\n rb: 'ruby',\n php: 'php',\n twig: 'twig',\n c: 'c',\n cpp: 'cpp',\n h: 'c',\n hpp: 'cpp',\n // Config and data formats\n ini: 'ini',\n toml: 'toml',\n csv: 'csv',\n diff: 'diff',\n patch: 'diff',\n // Web and infrastructure\n scss: 'scss',\n sass: 'sass',\n graphql: 'graphql',\n gql: 'graphql',\n conf: 'nginx',\n // Database\n mongodb: 'mongodb',\n // Tooling\n makefile: 'makefile',\n mk: 'makefile',\n mak: 'makefile',\n vim: 'vim',\n vimrc: 'vim',\n };\n\n // Check for special filenames without extensions\n const filename = filePath.split('/').pop()?.toLowerCase() || '';\n if (filename === 'dockerfile' || filename.startsWith('dockerfile.')) {\n return 'docker';\n }\n if (filename === 'makefile' || filename.startsWith('makefile.')) {\n return 'makefile';\n }\n if (filename.startsWith('.git')) {\n return 'git';\n }\n if (filename === '.vimrc' || filename.startsWith('.vim')) {\n return 'vim';\n }\n\n return langMap[ext] || 'plaintext';\n}\n","// github-provider.ts\n// GitHub implementation of the ForgeProvider interface, backed entirely by\n// the `gh` CLI through an injectable command runner (never the network\n// directly). Read-only: only `gh pr view` and `gh api` GET calls.\n//\n// GitHub Enterprise-style hosts are honored by passing the URL's host (which\n// may include a port) verbatim to gh: as the HOST/OWNER/REPO form for\n// `pr view --repo` and as `--hostname` for `gh api`. gh's own host handling\n// takes it from there (auth per host, API base URL).\n\nimport {\n ForgeCliUnavailableError,\n type FetchThreadsOptions,\n type ForgeCommandResult,\n type ForgeCommandRunner,\n type ForgeProvider,\n type ForgeThread,\n type ForgeThreadAnchor,\n type ForgeUrl,\n} from './forge-provider';\n\n/** Relevant subset of a GitHub REST pull-request review comment. */\ninterface GitHubReviewComment {\n id: number;\n in_reply_to_id?: number | null;\n /** `null` for deleted user accounts. */\n user: { login: string } | null;\n body: string;\n path: string;\n side?: 'LEFT' | 'RIGHT' | null;\n line: number | null;\n start_line?: number | null;\n original_line?: number | null;\n original_start_line?: number | null;\n}\n\nconst GH_CLI = 'gh';\n\n/**\n * Run a gh command, translating both failure modes into the typed\n * unavailable error: a runner rejection means the CLI could not be spawned\n * (e.g. ENOENT when gh is absent), a non-zero exit means gh ran but failed\n * (unauthenticated, API error). Callers degrade on this error, never crash.\n */\nasync function runGh(\n runCommand: ForgeCommandRunner,\n args: string[]\n): Promise<string> {\n let result: ForgeCommandResult;\n try {\n result = await runCommand(GH_CLI, args);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `Failed to run the gh CLI: ${detail}`\n );\n }\n if (result.exitCode !== 0) {\n const detail = result.stderr.trim() || `exit code ${result.exitCode}`;\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `gh exited with code ${result.exitCode}: ${detail}`\n );\n }\n return result.stdout;\n}\n\n/**\n * Parse gh JSON output, surfacing malformed output as the typed unavailable\n * error so callers keep a single degradation path.\n */\nfunction parseGhJson(stdout: string, context: string): unknown {\n try {\n return JSON.parse(stdout);\n } catch {\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `gh returned unparseable JSON for ${context}`\n );\n }\n}\n\n/**\n * Normalize one review comment's anchor. GitHub reports `line: null` when\n * the comment no longer applies to the head diff (outdated); the\n * `original_*` fields then retain the historic anchor.\n */\nfunction toAnchor(comment: GitHubReviewComment): ForgeThreadAnchor {\n const outdated = comment.line === null || comment.line === undefined;\n const endLine = outdated ? (comment.original_line ?? null) : comment.line;\n const startLine = outdated\n ? (comment.original_start_line ?? comment.original_line ?? null)\n : (comment.start_line ?? comment.line);\n const hasLines = startLine !== null && endLine !== null;\n return {\n filePath: comment.path,\n // Side is meaningless without usable lines; the contract says 'new'.\n side: hasLines && comment.side === 'LEFT' ? 'old' : 'new',\n startLine: hasLines ? startLine : null,\n endLine: hasLines ? endLine : null,\n outdated,\n };\n}\n\n/** GitHub shows deleted user accounts as \"ghost\"; mirror that. */\nfunction toTurn(comment: GitHubReviewComment) {\n return {\n remoteId: String(comment.id),\n author: comment.user?.login ?? 'ghost',\n body: comment.body,\n };\n}\n\n/**\n * Group flat review comments into threads. A comment without\n * `in_reply_to_id` roots a thread; a reply attaches to the thread containing\n * the comment it replies to (root or any member). An orphan reply whose\n * parent is unknown degrades to a thread root of its own. Document order is\n * preserved throughout — nothing sorts.\n */\nfunction groupIntoThreads(comments: GitHubReviewComment[]): ForgeThread[] {\n const threads: ForgeThread[] = [];\n const threadByCommentId = new Map<number, ForgeThread>();\n for (const comment of comments) {\n const parentThread =\n comment.in_reply_to_id === null || comment.in_reply_to_id === undefined\n ? undefined\n : threadByCommentId.get(comment.in_reply_to_id);\n if (parentThread) {\n parentThread.replies.push(toTurn(comment));\n threadByCommentId.set(comment.id, parentThread);\n } else {\n const thread: ForgeThread = {\n root: toTurn(comment),\n replies: [],\n anchor: toAnchor(comment),\n };\n threads.push(thread);\n threadByCommentId.set(comment.id, thread);\n }\n }\n return threads;\n}\n\n/**\n * Create the GitHub {@link ForgeProvider} backed by an injected command\n * runner, mirroring how `git.ts` keeps child-process execution testable.\n */\nexport function createGitHubProvider(\n runCommand: ForgeCommandRunner\n): ForgeProvider {\n return {\n forge: 'github',\n\n async fetchBaseBranch(url: ForgeUrl): Promise<string> {\n const stdout = await runGh(runCommand, [\n 'pr',\n 'view',\n String(url.number),\n '--repo',\n `${url.host}/${url.owner}/${url.repo}`,\n '--json',\n 'baseRefName',\n ]);\n const parsed = parseGhJson(stdout, 'pr view') as {\n baseRefName?: unknown;\n };\n if (typeof parsed?.baseRefName !== 'string' || parsed.baseRefName === '') {\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n 'gh pr view returned no baseRefName'\n );\n }\n return parsed.baseRefName;\n },\n\n // The REST review-comment list carries no resolution state, so\n // `options.includeResolved` is deliberately ignored: GitHub fetch\n // returns all review threads (resolved-state filtering is a GitLab\n // concern).\n async fetchThreads(\n url: ForgeUrl,\n _options?: FetchThreadsOptions\n ): Promise<ForgeThread[]> {\n const stdout = await runGh(runCommand, [\n 'api',\n `repos/${url.owner}/${url.repo}/pulls/${url.number}/comments`,\n '--hostname',\n url.host,\n '--paginate',\n '--slurp',\n ]);\n // `--paginate --slurp` wraps each response page in an outer array:\n // [[...page1], [...page2]]. Flatten one level to the comment list.\n const pages = parseGhJson(stdout, 'pull request comments');\n if (!Array.isArray(pages)) {\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n 'gh api returned an unexpected payload shape for pull request comments'\n );\n }\n const comments = pages.flat(1) as GitHubReviewComment[];\n return groupIntoThreads(comments);\n },\n };\n}\n","// thread-mapper.ts\n// Deterministic mapper from forge-neutral discussion threads to the v3\n// ReviewComment model. Pure code: no I/O, no randomness, no timestamps —\n// the same input always yields byte-identical output, and it contains no\n// forge-conditional logic (anything forge-specific belongs in the\n// providers). Fetch direction only.\n\nimport type { ForgeThread, ForgeThreadAnchor, ForgeThreadTurn } from './forge-provider';\nimport type { LineRange, Reply, ReviewComment } from './types';\n\n/**\n * Sentinel `filePath` for review-level threads (threads with no file\n * association at all, e.g. GitLab non-diff discussions).\n *\n * The v3 schema has no review-level comment element — every `<comment>`\n * lives inside a `<file path>` — so the mapper degrades these threads to\n * file-level comments on this sentinel path, the closest legal shape.\n * The empty string can never collide with a repository-relative diff path,\n * so consumers (the fetch-comments orchestrator, the app's remote mode)\n * detect review-level comments by comparing against this constant and\n * decide their placement (e.g. a synthetic review-level file entry).\n */\nexport const REVIEW_LEVEL_FILE_PATH = '';\n\n/**\n * Map an anchor to the model's line range, honoring the exactly-one-pair\n * rule: the single `LineRange.side` selects which pair the serializer\n * emits (`'new'` → `new-line-*`, `'old'` → `old-line-*`), so a comment can\n * never carry both.\n *\n * Returns `null` (file-level) when the anchor is outdated, has no usable\n * line information, or carries non-positive lines (the XSD requires\n * `xs:positiveInteger`, and the serializer must never receive an\n * unserializable range). Reversed bounds are normalized rather than\n * rejected so a defective provider payload still maps deterministically.\n */\nfunction mapAnchorToLineRange(anchor: ForgeThreadAnchor): LineRange | null {\n if (anchor.outdated) {\n return null;\n }\n const { startLine, endLine } = anchor;\n if (startLine === null || endLine === null) {\n return null;\n }\n if (startLine < 1 || endLine < 1) {\n return null;\n }\n return {\n side: anchor.side,\n start: Math.min(startLine, endLine),\n end: Math.max(startLine, endLine),\n };\n}\n\n/**\n * Internal ids are in-memory render keys the app normally generates\n * randomly on parse. The mapper must be deterministic, so it derives them\n * from the forge-assigned ids instead.\n */\nfunction internalId(turn: ForgeThreadTurn): string {\n return `remote-${turn.remoteId}`;\n}\n\nfunction mapReply(turn: ForgeThreadTurn): Reply {\n return {\n id: internalId(turn),\n body: turn.body,\n author: turn.author,\n remoteId: turn.remoteId,\n };\n}\n\n/**\n * Convert normalized forge threads into v3 `ReviewComment` threads.\n *\n * - The root turn becomes the root comment and owns the anchor; subsequent\n * turns become flat replies in document order (nothing sorts them).\n * - Forge usernames land in `author`, forge thread/comment ids in\n * `remoteId`, markdown bodies pass through verbatim.\n * - Outdated or line-less anchors degrade to file-level comments\n * (`lineRange: null`); anchor-less threads degrade to file-level\n * comments on {@link REVIEW_LEVEL_FILE_PATH}. The degradation is\n * structural, never textual.\n * - Mapped comments carry no category, severity or confidence: forge\n * threads have none, and absent means below every threshold. The empty\n * `category` matches how the XML parser represents a missing category.\n *\n * Output order is input order. The input is never mutated.\n */\nexport function mapThreadsToReviewComments(\n threads: ForgeThread[]\n): ReviewComment[] {\n return threads.map((thread) => {\n const comment: ReviewComment = {\n id: internalId(thread.root),\n filePath: thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH,\n lineRange: thread.anchor ? mapAnchorToLineRange(thread.anchor) : null,\n body: thread.root.body,\n category: '',\n suggestion: null,\n author: thread.root.author,\n remoteId: thread.root.remoteId,\n };\n if (thread.replies.length > 0) {\n comment.replies = thread.replies.map(mapReply);\n }\n return comment;\n });\n}\n","// gitlab-provider.ts\n// ForgeProvider implementation for GitLab (gitlab.com and self-hosted) backed\n// by the read-only `glab` CLI. All child-process execution goes through an\n// injected ForgeCommandRunner so the provider stays unit-testable and no real\n// `glab` calls happen in tests. Only GET-style commands are issued (`glab\n// api`); nothing is ever posted.\n\nimport {\n ForgeCliUnavailableError,\n type FetchThreadsOptions,\n type ForgeAnchorSide,\n type ForgeCommandRunner,\n type ForgeProvider,\n type ForgeThread,\n type ForgeThreadAnchor,\n type ForgeThreadTurn,\n type ForgeUrl,\n} from './forge-provider';\n\nconst GLAB_CLI = 'glab';\n\n// --- Minimal shapes of the GitLab API payloads we consume ---------------\n\ninterface GitLabLineRangeEdge {\n old_line?: number | null;\n new_line?: number | null;\n}\n\ninterface GitLabPosition {\n old_path?: string | null;\n new_path?: string | null;\n old_line?: number | null;\n new_line?: number | null;\n line_range?: {\n start?: GitLabLineRangeEdge | null;\n end?: GitLabLineRangeEdge | null;\n } | null;\n}\n\ninterface GitLabNote {\n id: number | string;\n body?: string;\n author?: { username?: string } | null;\n system?: boolean;\n resolvable?: boolean;\n resolved?: boolean;\n position?: GitLabPosition | null;\n}\n\ninterface GitLabDiscussion {\n id: string;\n notes?: GitLabNote[];\n}\n\n// --- CLI plumbing -------------------------------------------------------\n\n/** URL-encode the full project path; subgroup slashes become %2F. */\nfunction encodeProjectPath(url: ForgeUrl): string {\n return encodeURIComponent(`${url.owner}/${url.repo}`);\n}\n\nfunction unavailable(message: string): ForgeCliUnavailableError {\n return new ForgeCliUnavailableError('gitlab', GLAB_CLI, message);\n}\n\n/**\n * Run `glab api <endpoint>` against the URL's host and return raw stdout.\n * Spawn failures (ENOENT) and non-zero exits (unauthenticated, API errors)\n * both surface as {@link ForgeCliUnavailableError}.\n */\nasync function runGlabApi(\n runCommand: ForgeCommandRunner,\n url: ForgeUrl,\n endpoint: string,\n extraArgs: string[] = []\n): Promise<string> {\n const args = ['api', endpoint, '--hostname', url.host, ...extraArgs];\n let result;\n try {\n result = await runCommand(GLAB_CLI, args);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw unavailable(`glab CLI could not be spawned: ${detail}`);\n }\n if (result.exitCode !== 0) {\n const detail = result.stderr.trim() || `exit code ${result.exitCode}`;\n throw unavailable(`glab api ${endpoint} failed: ${detail}`);\n }\n return result.stdout;\n}\n\n/**\n * Parse stdout that may contain several concatenated top-level JSON\n * documents, as `glab api --paginate` emits one array per page. A simple\n * bracket/string scanner keeps `][` sequences inside note bodies from\n * breaking the split.\n */\nfunction parseJsonDocuments(text: string): unknown[] {\n const documents: unknown[] = [];\n let depth = 0;\n let inString = false;\n let escaped = false;\n let start = -1;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === '\\\\') {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (ch === '\"') {\n inString = true;\n } else if (ch === '[' || ch === '{') {\n if (depth === 0) start = i;\n depth += 1;\n } else if (ch === ']' || ch === '}') {\n depth -= 1;\n if (depth === 0 && start >= 0) {\n documents.push(JSON.parse(text.slice(start, i + 1)));\n start = -1;\n }\n }\n }\n if (depth !== 0 || inString) {\n throw new Error('truncated JSON document');\n }\n return documents;\n}\n\n// --- Normalization ------------------------------------------------------\n\nfunction toTurn(note: GitLabNote): ForgeThreadTurn {\n return {\n remoteId: String(note.id),\n author: note.author?.username ?? 'unknown',\n body: note.body ?? '',\n };\n}\n\n/**\n * A discussion counts as resolved when it has at least one resolvable note\n * and every resolvable note is resolved. Discussions with no resolvable\n * notes (non-diff discussions) are never \"resolved\".\n */\nfunction isDiscussionResolved(notes: GitLabNote[]): boolean {\n const resolvable = notes.filter((note) => note.resolvable === true);\n return resolvable.length > 0 && resolvable.every((note) => note.resolved === true);\n}\n\n/**\n * Build the neutral anchor from a GitLab position object, or `null` when the\n * note has no position (non-diff discussion) or the position carries no\n * usable file path.\n *\n * Side selection: `new_line` present → `'new'` (using `new_path`), otherwise\n * `old_line` present → `'old'` (using `old_path`). A position with a path\n * but neither line (e.g. `position_type: \"file\"`) becomes a file-level\n * anchor with null lines and side `'new'`, per the neutral shape's contract.\n * Multi-line `line_range` edges are read on the side chosen above, falling\n * back to the single-line position when an edge lacks that side's line.\n *\n * GitLab has no per-note outdated flag (positions on older heads stay valid\n * positions), so `outdated` is always `false`; drift detection downstream\n * informs the reviewer instead.\n */\nfunction toAnchor(position: GitLabPosition | null | undefined): ForgeThreadAnchor | null {\n if (!position) return null;\n\n const side: ForgeAnchorSide =\n typeof position.old_line === 'number' && typeof position.new_line !== 'number'\n ? 'old'\n : 'new';\n const pathForSide = side === 'old' ? position.old_path : position.new_path;\n const filePath = pathForSide ?? position.new_path ?? position.old_path;\n if (!filePath) return null;\n\n const lineOf = (edge: GitLabLineRangeEdge | null | undefined): number | null => {\n const value = side === 'old' ? edge?.old_line : edge?.new_line;\n return typeof value === 'number' ? value : null;\n };\n\n const positionLine = lineOf(position);\n const startLine = lineOf(position.line_range?.start) ?? positionLine;\n const endLine = lineOf(position.line_range?.end) ?? positionLine;\n\n return { filePath, side, startLine, endLine, outdated: false };\n}\n\n/**\n * Normalize one GitLab discussion into the forge-neutral thread shape, or\n * `null` when nothing user-authored remains after dropping system notes.\n * The first surviving note roots the thread and owns the anchor; the rest\n * are ordered replies (GitLab document order is preserved verbatim).\n */\nfunction toThread(discussion: GitLabDiscussion): ForgeThread | null {\n const notes = (discussion.notes ?? []).filter((note) => note.system !== true);\n if (notes.length === 0) return null;\n const [rootNote, ...replyNotes] = notes;\n return {\n root: toTurn(rootNote),\n replies: replyNotes.map(toTurn),\n anchor: toAnchor(rootNote.position),\n };\n}\n\n// --- Provider -----------------------------------------------------------\n\n/**\n * Create the GitLab {@link ForgeProvider} backed by the `glab` CLI.\n *\n * The URL's host is forwarded via `--hostname`, so self-hosted instances\n * (e.g. git.drupalcode.org) work with zero configuration beyond `glab auth`.\n * Resolved discussions are excluded unless `includeResolved` is set.\n */\nexport function createGitLabProvider(runCommand: ForgeCommandRunner): ForgeProvider {\n return {\n forge: 'gitlab',\n\n async fetchBaseBranch(url: ForgeUrl): Promise<string> {\n const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}`;\n const stdout = await runGlabApi(runCommand, url, endpoint);\n let mr: unknown;\n try {\n mr = JSON.parse(stdout);\n } catch {\n throw unavailable(`glab api ${endpoint} returned unparseable JSON`);\n }\n const targetBranch = (mr as { target_branch?: unknown })?.target_branch;\n if (typeof targetBranch !== 'string' || targetBranch.length === 0) {\n throw unavailable(`glab api ${endpoint} returned no target_branch`);\n }\n return targetBranch;\n },\n\n async fetchThreads(url: ForgeUrl, options?: FetchThreadsOptions): Promise<ForgeThread[]> {\n const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}/discussions`;\n const stdout = await runGlabApi(runCommand, url, endpoint, ['--paginate']);\n\n let discussions: GitLabDiscussion[];\n try {\n const pages = parseJsonDocuments(stdout);\n if (pages.length === 0 && stdout.trim() !== '') {\n throw new Error('no JSON documents in output');\n }\n discussions = pages.flatMap((page) =>\n Array.isArray(page) ? (page as GitLabDiscussion[]) : []\n );\n } catch {\n throw unavailable(`glab api ${endpoint} returned unparseable JSON`);\n }\n\n const includeResolved = options?.includeResolved === true;\n const threads: ForgeThread[] = [];\n for (const discussion of discussions) {\n const notes = discussion.notes ?? [];\n if (!includeResolved && isDiscussionResolved(notes)) continue;\n const thread = toThread(discussion);\n if (thread) threads.push(thread);\n }\n return threads;\n },\n };\n}\n","// materializer.ts\n// Clone-aware diff materializer: turns a parsed forge URL into a local git\n// context. Reuses an existing matching clone (fetch only, no working-tree\n// changes) or creates a disposable blobless clone under the OS temp root,\n// then reports the resolved base/head SHAs so downstream code can run the\n// existing local git-mode pipeline over `baseSha...headSha`.\n//\n// All git interaction goes through an injectable command runner (the same\n// shape providers use) so unit tests never spawn real git. This module never\n// talks to a forge API: head refs come from the forges' well-known git refs\n// (`refs/pull/N/head`, `refs/merge-requests/N/head`) over plain git.\n\nimport { execFile } from 'child_process';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport type {\n ForgeCommandResult,\n ForgeCommandRunner,\n ForgeUrl,\n} from './forge-provider';\n\n/** How the local git context was obtained. */\nexport type MaterializeMode = 'existing-clone' | 'temp-clone';\n\n/** Result of materializing a forge URL into a local git context. */\nexport interface MaterializeResult {\n /** Root of the git repository to run the diff pipeline in. */\n repoPath: string;\n /** Resolved SHA of the PR/MR base branch tip. */\n baseSha: string;\n /** Resolved SHA of the PR/MR head (the live remote head). */\n headSha: string;\n mode: MaterializeMode;\n /**\n * Removes the temp clone directory when one was created this run; a no-op\n * for the existing-clone mode. Safe to call more than once. Only ever\n * deletes a directory this materializer created.\n */\n cleanup: () => void;\n}\n\n/** A local clone whose fetch remote matches the requested forge repository. */\nexport interface ExistingClone {\n repoPath: string;\n remoteName: string;\n}\n\n/** Local namespaced refs the materializer fetches into (never branches). */\nconst LOCAL_BASE_REF = 'refs/self-review/base';\nconst LOCAL_HEAD_REF = 'refs/self-review/head';\n\nconst AUTH_HINT =\n 'Hint: if this repository is private or requires authentication, run ' +\n '`gh auth setup-git` (GitHub) or `glab auth git-credential` (GitLab) to ' +\n 'wire your CLI credentials into git.';\n\n/**\n * Default runner: spawns real git. Resolves with the exit code on any\n * completed run (including non-zero); rejects only when git cannot be\n * spawned at all (e.g. ENOENT).\n */\nexport const defaultGitRunner: ForgeCommandRunner = (command, args) =>\n new Promise<ForgeCommandResult>((resolve, reject) => {\n execFile(\n command,\n args,\n { maxBuffer: 50 * 1024 * 1024 },\n (error, stdout, stderr) => {\n const spawnCode = (error as NodeJS.ErrnoException | null)?.code;\n if (error && typeof spawnCode === 'string') {\n reject(error);\n return;\n }\n resolve({\n stdout: stdout ?? '',\n stderr: stderr ?? '',\n exitCode: error ? (typeof spawnCode === 'number' ? spawnCode : 1) : 0,\n });\n }\n );\n });\n\n/** Well-known git ref for the PR/MR head on each forge. */\nfunction headRefFor(url: ForgeUrl): string {\n return url.forge === 'github'\n ? `refs/pull/${url.number}/head`\n : `refs/merge-requests/${url.number}/head`;\n}\n\n/**\n * HTTPS clone URL for the forge repository. Git's credential machinery\n * (helpers, `gh auth setup-git`) handles auth; no transport selection here.\n */\nfunction cloneUrlFor(url: ForgeUrl): string {\n return `https://${url.host}/${url.owner}/${url.repo}.git`;\n}\n\nfunction gitFailure(\n what: string,\n result: ForgeCommandResult,\n withAuthHint: boolean\n): Error {\n const stderr = result.stderr.trim();\n const lines = [\n `git ${what} failed (exit code ${result.exitCode})${stderr ? `:\\n${stderr}` : ''}`,\n ];\n if (withAuthHint) {\n lines.push('', AUTH_HINT);\n }\n return new Error(lines.join('\\n'));\n}\n\n/** Strip a trailing `.git` and trailing slashes from a repo path. */\nfunction stripRepoPath(repoPath: string): string {\n return repoPath.replace(/\\/+$/, '').replace(/\\.git$/i, '');\n}\n\n/**\n * Normalize a git remote URL (SSH scp-style, ssh://, http(s)://) into a\n * comparable `{ host, path }` pair, or `null` when unrecognized.\n */\nfunction normalizeRemoteUrl(\n raw: string\n): { host: string; path: string } | null {\n const trimmed = raw.trim();\n if (trimmed.includes('://')) {\n try {\n const parsed = new URL(trimmed);\n return {\n host: parsed.host.toLowerCase(),\n path: stripRepoPath(parsed.pathname.replace(/^\\/+/, '')).toLowerCase(),\n };\n } catch {\n return null;\n }\n }\n // scp-style: [user@]host:path\n const scp = /^(?:[^@\\s]+@)?([^:/\\s]+):(.+)$/.exec(trimmed);\n if (scp) {\n return {\n host: scp[1].toLowerCase(),\n path: stripRepoPath(scp[2].replace(/^\\/+/, '')).toLowerCase(),\n };\n }\n return null;\n}\n\n/**\n * Parse `git remote -v` output and return the name of the first remote whose\n * fetch URL matches the forge URL's host and owner/repo, or `null`.\n */\nfunction findMatchingRemote(remoteVOutput: string, url: ForgeUrl): string | null {\n const wantedHost = url.host.toLowerCase();\n const wantedPath = `${url.owner}/${url.repo}`.toLowerCase();\n for (const line of remoteVOutput.split('\\n')) {\n const match = /^(\\S+)\\t(.+?)\\s+\\(fetch\\)$/.exec(line.trim());\n if (!match) continue;\n const normalized = normalizeRemoteUrl(match[2]);\n if (normalized && normalized.host === wantedHost && normalized.path === wantedPath) {\n return match[1];\n }\n }\n return null;\n}\n\nasync function revParse(\n runner: ForgeCommandRunner,\n repoPath: string,\n ref: string\n): Promise<string> {\n const result = await runner('git', ['-C', repoPath, 'rev-parse', ref]);\n if (result.exitCode !== 0) {\n throw gitFailure(`rev-parse ${ref}`, result, false);\n }\n return result.stdout.trim();\n}\n\n/**\n * Detect an existing clone: when `cwd` is inside a git repository with a\n * remote matching the forge URL, return `{ repoPath, remoteName }`.\n */\nexport async function detectExistingClone(\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner = defaultGitRunner\n): Promise<ExistingClone | null> {\n const toplevel = await runner('git', ['-C', cwd, 'rev-parse', '--show-toplevel']);\n if (toplevel.exitCode !== 0) {\n return null;\n }\n const repoPath = toplevel.stdout.trim();\n const remotes = await runner('git', ['-C', repoPath, 'remote', '-v']);\n if (remotes.exitCode !== 0) {\n return null;\n }\n const remoteName = findMatchingRemote(remotes.stdout, url);\n return remoteName === null ? null : { repoPath, remoteName };\n}\n\nasync function materializeIntoExistingClone(\n runner: ForgeCommandRunner,\n url: ForgeUrl,\n baseBranch: string,\n repoPath: string,\n remoteName: string\n): Promise<MaterializeResult> {\n console.error(\n `self-review: reusing existing clone at ${repoPath} (remote \"${remoteName}\")`\n );\n // Fetch into namespaced local refs only: no checkout, no branch creation,\n // no working-tree change. Forced refspecs are fine — these refs are ours.\n const fetch = await runner('git', [\n '-C',\n repoPath,\n 'fetch',\n remoteName,\n `+refs/heads/${baseBranch}:${LOCAL_BASE_REF}`,\n `+${headRefFor(url)}:${LOCAL_HEAD_REF}`,\n ]);\n if (fetch.exitCode !== 0) {\n throw gitFailure(`fetch from remote \"${remoteName}\"`, fetch, true);\n }\n return {\n repoPath,\n baseSha: await revParse(runner, repoPath, LOCAL_BASE_REF),\n headSha: await revParse(runner, repoPath, LOCAL_HEAD_REF),\n mode: 'existing-clone',\n cleanup: () => {},\n };\n}\n\nasync function materializeIntoTempClone(\n runner: ForgeCommandRunner,\n url: ForgeUrl,\n baseBranch: string\n): Promise<MaterializeResult> {\n // This run creates the directory, so cleanup may only ever remove it.\n const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'self-review-'));\n let removed = false;\n const cleanup = () => {\n if (removed) return;\n removed = true;\n fs.rmSync(tempDir, { recursive: true, force: true });\n };\n\n try {\n console.error(\n `self-review: created temporary blobless clone at ${tempDir}`\n );\n const cloneUrl = cloneUrlFor(url);\n // Blobless, never shallow: --depth would break merge-base computation.\n const clone = await runner('git', [\n 'clone',\n '--filter=blob:none',\n cloneUrl,\n tempDir,\n ]);\n if (clone.exitCode !== 0) {\n throw gitFailure(`clone of ${cloneUrl}`, clone, true);\n }\n const fetch = await runner('git', [\n '-C',\n tempDir,\n 'fetch',\n 'origin',\n `+${headRefFor(url)}:${LOCAL_HEAD_REF}`,\n ]);\n if (fetch.exitCode !== 0) {\n throw gitFailure(`fetch of ${headRefFor(url)}`, fetch, true);\n }\n return {\n repoPath: tempDir,\n baseSha: await revParse(runner, tempDir, `origin/${baseBranch}`),\n headSha: await revParse(runner, tempDir, LOCAL_HEAD_REF),\n mode: 'temp-clone',\n cleanup,\n };\n } catch (error) {\n cleanup();\n throw error;\n }\n}\n\n/**\n * Materialize a forge PR/MR into a local git context.\n *\n * When `cwd` is inside a git repository with a remote matching the forge\n * URL (SSH and HTTPS forms recognized, `.git` suffix tolerated), the base\n * branch and PR/MR head refs are fetched into that clone under\n * `refs/self-review/*` — read-only for the working tree. Otherwise a\n * blobless clone is created in a unique directory under the OS temp root\n * and `cleanup()` removes exactly that directory. Callers that already\n * detected a clone may pass it to avoid repeating the git probes.\n *\n * The returned `headSha` is the live remote head, so callers can compare it\n * against a recorded `remote-head-sha` for drift detection.\n */\nexport async function materialize(\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner = defaultGitRunner,\n existingClone?: ExistingClone | null\n): Promise<MaterializeResult> {\n const existing =\n existingClone === undefined\n ? await detectExistingClone(url, cwd, runner)\n : existingClone;\n if (existing) {\n return materializeIntoExistingClone(\n runner,\n url,\n baseBranch,\n existing.repoPath,\n existing.remoteName\n );\n }\n return materializeIntoTempClone(runner, url, baseBranch);\n}\n\n/**\n * Git-only fallback for the base branch when no forge CLI is available:\n * resolves the remote's default branch from its HEAD symref via\n * `git ls-remote --symref <remote> HEAD`. When an existing matching clone\n * is supplied, the configured remote is used so its SSH/HTTPS transport\n * and credentials are preserved. Otherwise the forge HTTPS URL is used.\n * No forge API involved.\n */\nexport async function resolveRemoteDefaultBranch(\n url: ForgeUrl,\n runner: ForgeCommandRunner = defaultGitRunner,\n existing: ExistingClone | null = null\n): Promise<string> {\n const cloneUrl = cloneUrlFor(url);\n const remote = existing?.remoteName ?? cloneUrl;\n // Errors must identify the repository; a bare alias such as \"origin\"\n // does not say which repository the lookup was made against.\n const label = existing ? `${remote} (${cloneUrl})` : cloneUrl;\n const args = existing\n ? ['-C', existing.repoPath, 'ls-remote', '--symref', remote, 'HEAD']\n : ['ls-remote', '--symref', remote, 'HEAD'];\n const result = await runner('git', args);\n if (result.exitCode !== 0) {\n throw gitFailure(`ls-remote of ${label}`, result, true);\n }\n const match = /^ref:\\s+refs\\/heads\\/(\\S+)\\s+HEAD$/m.exec(result.stdout);\n if (!match) {\n throw new Error(\n `Failed to resolve the default branch of ${label}: ` +\n 'git ls-remote returned no HEA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;AAAA,MACA;AAAA,MACA;AAAA,MACA,SAAS;AAAA,MACT,SAAS;AAAA,IACX;AAAA,EACF;AACA,SAAO,yBAAyB,QAAQ,KAAK,UAAU;AACzD;AAUA,eAAsB,2BACpB,KACA,SAA6B,kBAC7B,WAAiC,MAChB;AACjB,QAAM,WAAW,YAAY,GAAG;AAChC,QAAM,SAAS,UAAU,cAAc;AAGvC,QAAM,QAAQ,WAAW,GAAG,MAAM,KAAK,QAAQ,MAAM;AACrD,QAAM,OAAO,WACT,CAAC,MAAM,SAAS,UAAU,aAAa,YAAY,QAAQ,MAAM,IACjE,CAAC,aAAa,YAAY,QAAQ,MAAM;AAC5C,QAAM,SAAS,MAAM,OAAO,OAAO,IAAI;AACvC,MAAI,OAAO,aAAa,GAAG;AACzB,UAAM,WAAW,gBAAgB,KAAK,IAAI,QAAQ,IAAI;AAAA,EACxD;AACA,QAAM,QAAQ,sCAAsC,KAAK,OAAO,MAAM;AACtE,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR,2CAA2C,KAAK;AAAA,IAElD;AAAA,EACF;AACA,SAAO,MAAM,CAAC;AAChB;","names":["path","XMLParser","validateXML","validateXML","XMLParser","path","readFileSync","join","dirname","join","dirname","readFileSync","existsSync","join","path","exec","promisify","execAsync","dirname","toTurn","toAnchor","execFile","fs","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/diff-parser.ts","../src/xml-serializer.ts","../src/xml-parser.ts","../src/guide-schema.ts","../src/guide-parser.ts","../src/git.ts","../src/synthetic-diff.ts","../src/forge-provider.ts","../src/directory-scanner.ts","../src/ignore-filter.ts","../src/config.ts","../src/payload-sizing.ts","../src/fs-utils.ts","../src/file-type-utils.ts","../src/github-provider.ts","../src/thread-mapper.ts","../src/gitlab-provider.ts","../src/materializer.ts"],"sourcesContent":["// src/main/diff-parser.ts\n// Parse unified diff output into DiffFile[]\n\nimport { DiffFile, DiffHunk, ChangeType } from './types';\n\nexport function parseDiff(rawDiff: string): DiffFile[] {\n if (!rawDiff.trim()) {\n return [];\n }\n\n const lines = rawDiff.split('\\n');\n const files: DiffFile[] = [];\n let currentFile: Partial<DiffFile> | null = null;\n let currentHunk: Partial<DiffHunk> | null = null;\n let oldLineNumber = 0;\n let newLineNumber = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Start of a new file\n if (line.startsWith('diff --git ')) {\n // Flush the pending hunk into the current file before saving\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n currentHunk = null;\n }\n\n // Save previous file if exists and has actual changes\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n // Extract paths from \"diff --git a/<old> b/<new>\" as fallback\n // for binary files that lack --- / +++ lines\n const gitPaths = parseGitDiffHeader(line);\n\n // Initialize new file\n currentFile = {\n oldPath: gitPaths.oldPath,\n newPath: gitPaths.newPath,\n changeType: 'modified' as ChangeType,\n isBinary: false,\n hunks: [],\n };\n currentHunk = null;\n continue;\n }\n\n if (!currentFile) continue;\n\n // Detect file mode changes\n if (line.startsWith('new file mode')) {\n currentFile.changeType = 'added';\n continue;\n }\n\n if (line.startsWith('deleted file mode')) {\n currentFile.changeType = 'deleted';\n continue;\n }\n\n if (line.startsWith('rename from ')) {\n currentFile.changeType = 'renamed';\n continue;\n }\n\n // Parse old file path\n if (line.startsWith('--- ')) {\n const path = line.substring(4);\n currentFile.oldPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Parse new file path\n if (line.startsWith('+++ ')) {\n const path = line.substring(4);\n currentFile.newPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Detect binary files\n if (line.startsWith('Binary files ')) {\n currentFile.isBinary = true;\n continue;\n }\n\n // Parse hunk header\n if (line.startsWith('@@')) {\n // Save previous hunk if exists\n if (currentHunk && currentHunk.header) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n\n // Parse hunk header: @@ -oldStart,oldLines +newStart,newLines @@ context\n const match = line.match(\n /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(.*)$/\n );\n if (match) {\n const oldStart = parseInt(match[1], 10);\n const oldLines = match[2] ? parseInt(match[2], 10) : 1;\n const newStart = parseInt(match[3], 10);\n const newLines = match[4] ? parseInt(match[4], 10) : 1;\n const _context = match[5];\n\n currentHunk = {\n header: line,\n oldStart,\n oldLines,\n newStart,\n newLines,\n lines: [],\n };\n\n oldLineNumber = oldStart;\n newLineNumber = newStart;\n }\n continue;\n }\n\n // Parse diff lines (must have a current hunk)\n if (currentHunk && currentHunk.lines) {\n if (line.startsWith('+')) {\n // Addition\n currentHunk.lines.push({\n type: 'addition',\n oldLineNumber: null,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n newLineNumber++;\n } else if (line.startsWith('-')) {\n // Deletion\n currentHunk.lines.push({\n type: 'deletion',\n oldLineNumber: oldLineNumber,\n newLineNumber: null,\n content: line.substring(1),\n });\n oldLineNumber++;\n } else if (line.startsWith(' ')) {\n // Context line\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n oldLineNumber++;\n newLineNumber++;\n } else if (line.startsWith('\\\\')) {\n // \"\\" - ignore\n continue;\n } else {\n // Some other line (could be empty or malformed), treat as context\n if (currentHunk.lines.length > 0) {\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line,\n });\n oldLineNumber++;\n newLineNumber++;\n }\n }\n }\n }\n\n // Save the last hunk and file\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n return files;\n}\n\nfunction stripPrefix(path: string): string {\n // Remove single-character prefix (a/, b/, c/, i/, w/, etc.)\n // Git uses a/b by default, but mnemonicPrefix uses c/i/w/o\n if (path.length > 2 && path[1] === '/') {\n return path.substring(2);\n }\n return path;\n}\n\nfunction parseGitDiffHeader(line: string): {\n oldPath: string;\n newPath: string;\n} {\n // Format: \"diff --git a/<old> b/<new>\"\n // With diff.mnemonicPrefix, git uses i/ w/ c/ o/ instead of a/ b/.\n // Paths may contain spaces, so we find the \" X/\" separator where X is a\n // single-letter prefix.\n const withoutPrefix = line.substring('diff --git '.length);\n\n // Find \" X/\" — the boundary between old and new paths.\n // Try common prefixes: b/ (default), w/ i/ c/ o/ (mnemonic)\n let bIdx = -1;\n for (const prefix of [' b/', ' w/', ' i/', ' c/', ' o/']) {\n bIdx = withoutPrefix.indexOf(prefix);\n if (bIdx !== -1) break;\n }\n\n if (bIdx === -1) {\n return { oldPath: '', newPath: '' };\n }\n\n const oldPath = stripPrefix(withoutPrefix.substring(0, bIdx));\n const newPath = stripPrefix(withoutPrefix.substring(bIdx + 1));\n return { oldPath, newPath };\n}\n","// src/main/xml-serializer.ts\n// Serialize ReviewState to XML and validate against XSD\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { ReviewState, FileReviewState, ReviewComment, Reply, Attachment } from './types';\nimport { validateXML } from 'xmllint-wasm';\n\n// Embed the XSD schema for validation.\n// This MUST stay byte-identical to the on-disk canonical copy\n// (.agents/skills/self-review-apply/assets/self-review-v3.xsd);\n// the sync test in xsd-schema.test.ts enforces it.\nexport const XSD_SCHEMA = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sr=\"urn:self-review:v3\"\n targetNamespace=\"urn:self-review:v3\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review XML Schema v3\n =========================\n Defines the output format for the self-review application.\n This schema is designed to be both machine-validated and\n fed to an LLM so it can understand the structure of review feedback.\n\n Key concepts:\n - A <review> contains one <file> per file in the diff.\n - A <file> contains zero or more <comment> elements.\n - A <comment> with no line attributes is a file-level comment.\n - A <comment> with old-line-start/old-line-end refers to lines\n in the pre-change version of the file (typically deleted lines).\n - A <comment> with new-line-start/new-line-end refers to lines\n in the post-change version of the file (added or context lines).\n - Exactly one pair (old-line-* or new-line-*) should be present\n for line-level comments. This constraint cannot be expressed in\n XSD 1.0 and is enforced by the application.\n - A <comment> may carry an ordered list of <reply> children, which\n are turns in a conversation about that comment.\n\n Changes from v1:\n - <comment> gained two optional attributes, severity and confidence,\n so an automated consumer can threshold on findings instead of\n applying all of them or none of them. See CommentType.\n\n Changes from v2:\n - <comment> gained an optional, unbounded <reply> child, so a finding\n and the responses to it form a single legible thread instead of a\n set of disconnected assertions. See ReplyType.\n\n Amended in place (still v3):\n - The review root gained optional remote-url, remote-base-sha,\n remote-head-sha and remote-forge attributes, and <comment> and\n <reply> gained an optional remote-id attribute, so a review taken\n against a remote pull/merge request records its provenance. Purely\n additive: a document carrying none of them is unchanged. See\n ReviewType.\n -->\n\n <!-- ===== Root element ===== -->\n\n <xs:element name=\"review\" type=\"sr:ReviewType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review output file. Contains one file element\n per file in the git diff, including files with no comments.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <!-- ===== Complex types ===== -->\n\n <xs:complexType name=\"ReviewType\">\n <xs:sequence>\n <xs:element name=\"file\" type=\"sr:FileType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the review was completed (window closed).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments that were passed to self-review on the CLI.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root where self-review was invoked.\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"source-path\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the directory being reviewed.\n Present only when reviewing a directory (non-git mode).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-url\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n URL of the remote pull/merge request this review was taken\n against. Example: \"https://github.com/owner/repo/pull/42\".\n Present only when reviewing a remote PR/MR.\n\n The remote-* attributes form a third source shape alongside\n git-diff-args/repository (local git diff) and source-path\n (directory review). The three shapes are mutually exclusive;\n XSD 1.0 cannot express that constraint, so it is enforced by\n the application.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-base-sha\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Commit SHA the remote diff was computed from (the base of the\n PR/MR at fetch time). Together with remote-head-sha it pins the\n review to the exact diff it was written against, so a consumer\n can detect drift when the remote branch moves.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-head-sha\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Commit SHA of the head of the remote PR/MR branch at fetch time.\n See remote-base-sha for how the pair supports drift detection.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-forge\" type=\"sr:RemoteForgeEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Which forge hosts the remote PR/MR. Names the id space of the\n remote-id attributes on comments and replies, and selects the\n API machinery a future posting feature would use.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileType\">\n <xs:annotation>\n <xs:documentation>\n Represents a single file in the diff. Files with no comments\n appear as empty elements. The path is relative to the repository root.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"comment\" type=\"sr:CommentType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root. For renamed files,\n this is the new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"change-type\" type=\"sr:ChangeTypeEnum\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n The type of change: added, modified, deleted, or renamed.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"viewed\" type=\"xs:boolean\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Whether the reviewer marked this file as reviewed.\n true = the reviewer looked at this file.\n false = the reviewer did not mark this file as viewed.\n This helps an AI agent distinguish \"reviewed with no comments\"\n from \"not yet reviewed.\"\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"CommentType\">\n <xs:annotation>\n <xs:documentation>\n A review comment. Three forms:\n\n 1. File-level comment: no line attributes present.\n Applies to the file as a whole.\n\n 2. Comment on new/added/context lines: new-line-start and\n new-line-end are present. These reference line numbers in the\n post-change version of the file.\n\n 3. Comment on old/deleted lines: old-line-start and old-line-end\n are present. These reference line numbers in the pre-change\n version of the file.\n\n For single-line comments, start and end are equal.\n Exactly one pair (old or new) should be present for line-level\n comments. Both pairs absent = file-level comment.\n\n The category child says what kind of finding this is. The severity\n and confidence attributes say how much weight to put on it: severity\n is how consequential the finding is if it is real, confidence is how\n sure the author is that it is real. They are independent, and an\n automated consumer is expected to threshold on both.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The comment text. May contain markdown formatting.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"category\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n Required category tag for this comment (e.g., \"bug\", \"style\",\n \"nit\", \"question\", \"security\"). Categories are defined in the\n project-level .self-review.yaml configuration. Every comment\n must have a category to help AI agents prioritize and triage\n feedback.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"suggestion\" type=\"sr:SuggestionType\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Optional code replacement proposal. When present, the AI agent\n should replace the original-code with the proposed-code at the\n referenced line range.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment. The path attribute references an image file\n stored in the .self-review-assets/ directory alongside the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"reply\" type=\"sr:ReplyType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional ordered list of replies to this comment. The comment\n itself is the root of the thread; each reply is a later turn in\n the conversation about it.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"old-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the pre-change (old) version of the file.\n Use for comments on deleted lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"old-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the pre-change (old) version.\n Must be >= old-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the post-change (new) version of the file.\n Use for comments on added or context (unchanged) lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the post-change (new) version.\n Must be >= new-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"author\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The author of this comment. When present, indicates the comment\n was generated by a bot or LLM (e.g., \"Claude Sonnet 4.6\").\n When absent, the comment is assumed to be authored by the human\n reviewer.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"severity\" type=\"sr:SeverityEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n How consequential this finding is if it turns out to be real.\n Judge the impact of the problem, not how confident you are that\n the problem exists, and not how much work the fix is.\n\n This attribute has no schema default on purpose. When it is\n absent, a consumer must treat the comment as falling below any\n severity floor it applies, i.e. absent never satisfies a\n threshold. Comments written by a human in the self-review UI\n normally carry no severity.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"confidence\" type=\"sr:ConfidenceEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n How sure the author is that this finding is real, i.e. that it\n describes an actual defect in the code as written rather than a\n hypothetical one.\n\n Confidence is about the evidence, not about how strongly the\n comment is worded. A finding whose argument depends on a\n constraint that is not visible in the diff, on a caller that was\n not read, or on a failure scenario that was imagined rather than\n traced, is low confidence however plausible its prose sounds.\n LLM reviewers systematically overstate certainty here; a\n consumer thresholding on this attribute is relying on it being\n lowered honestly.\n\n This attribute has no schema default on purpose. When it is\n absent, a consumer must treat the comment as falling below any\n confidence floor it applies, i.e. absent never satisfies a\n threshold.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-id\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Identifier of the remote discussion thread or comment this\n comment was fetched from, in the id space of the forge named by\n remote-forge on the review root. Provenance and forward\n machinery: it lets a consumer trace the finding back to its\n origin, and a future posting feature reply to the existing\n thread instead of opening a new one. Absent on comments\n authored locally.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"ReplyType\">\n <xs:annotation>\n <xs:documentation>\n A reply to a review comment. Replies turn a finding into a\n conversation: the comment asserts something, a reply answers it, a\n later reply answers that.\n\n Four rules govern replies. Only the first is beyond what XSD 1.0\n can express, and it is enforced by the application and by the\n skills that author these documents. Rules 2 to 4 are enforced by\n the content model below; they are spelled out anyway, because the\n reason for a constraint is what an author needs in order to write\n a good reply, and a validator only ever reports the constraint:\n\n 1. Replies are ordered. Document order is conversation order, and\n it is the only ordering signal. There are no timestamps and no\n identifiers: the earlier reply is the earlier turn.\n\n 2. Replies are flat. A reply is never nested inside another reply.\n A reply that addresses an earlier reply says so in its body.\n\n 3. A reply carries no thresholding metadata. There is no category,\n no severity and no confidence on a reply. Those are properties\n of the finding, and the finding is the root comment, whose\n severity and confidence govern the whole thread.\n\n 4. A reply carries no suggestion. A concrete counter-proposal goes\n in the reply body as a fenced code block. Allowing a suggestion\n on both the root and a reply would force every consumer to\n invent its own precedence rule.\n\n When a machine consumes a thread, the last human turn is the\n tie-breaker over any earlier machine assertion.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The reply text. May contain markdown formatting, including\n fenced code blocks, which is where a counter-proposal goes\n since replies carry no suggestion element.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment, identical in form and semantics to\n a comment attachment. The path attribute references an image\n file stored in the .self-review-assets/ directory alongside\n the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"author\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The author of this reply, with the same semantics as\n CommentType/@author. When present, the reply was generated by a\n bot or LLM (e.g., \"Claude Opus 5\"). When absent, the reply is\n the human reviewer's.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-id\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Identifier of the remote comment this reply was fetched from,\n with the same semantics as CommentType/@remote-id: an id in the\n forge's own id space, kept for provenance and for a future\n posting feature. Absent on replies authored locally.\n\n A remote-id is not an ordering signal. Document order remains\n conversation order, exactly as rule 1 above states.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"SuggestionType\">\n <xs:annotation>\n <xs:documentation>\n A code replacement proposal. The original-code is the literal text\n currently at the referenced lines. The proposed-code is what the\n reviewer suggests it should be replaced with. The AI agent can apply\n this by performing a text substitution.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"original-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The existing code at the referenced line range, copied verbatim\n from the diff. Used by the AI agent to locate the replacement\n target via text matching.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"proposed-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The replacement code proposed by the reviewer. The AI agent\n should substitute original-code with this text.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n\n <xs:complexType name=\"AttachmentType\">\n <xs:annotation>\n <xs:documentation>\n Reference to an image file attached to a review comment. The file is stored\n alongside the XML output in the .self-review-assets/ directory.\n </xs:documentation>\n </xs:annotation>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>Relative path from the XML file to the image file.</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"media-type\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>MIME type of the image (e.g., image/png, image/jpeg).</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <!-- ===== Simple types ===== -->\n\n <xs:simpleType name=\"ChangeTypeEnum\">\n <xs:annotation>\n <xs:documentation>\n The type of change a file underwent in the diff.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"added\">\n <xs:annotation>\n <xs:documentation>New file that did not exist before.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"modified\">\n <xs:annotation>\n <xs:documentation>Existing file with content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"deleted\">\n <xs:annotation>\n <xs:documentation>File was removed.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"renamed\">\n <xs:annotation>\n <xs:documentation>File was moved or renamed, with or without content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"SeverityEnum\">\n <xs:annotation>\n <xs:documentation>\n How consequential a finding is if it is real. Ordered from most to\n least consequential: critical, major, minor, info.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"critical\">\n <xs:annotation>\n <xs:documentation>\n Causes data loss, a security hole, or a crash or corruption on a\n path that real usage reaches. Shipping this is not acceptable.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"major\">\n <xs:annotation>\n <xs:documentation>\n Produces wrong behaviour, or breaks a documented contract, on a\n path that real usage reaches. The code does not do what it is\n supposed to do, but nothing is destroyed and there is no security\n impact.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"minor\">\n <xs:annotation>\n <xs:documentation>\n Real but bounded: a mishandled edge case that is unlikely to be\n hit, a missing test, a leak of something cheap, or a maintenance\n hazard that will cost time later. Behaviour is correct today.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"info\">\n <xs:annotation>\n <xs:documentation>\n No defect. Style, naming, phrasing, a question for the author, or\n a note recorded for context. Nothing is wrong if this is never\n acted on.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"ConfidenceEnum\">\n <xs:annotation>\n <xs:documentation>\n How sure the author is that a finding is real. Ordered from most to\n least sure: high, medium, low.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"high\">\n <xs:annotation>\n <xs:documentation>\n The evidence is in the code that was read. The failure can be\n traced from the diff itself, and no assumption about unseen code,\n unseen callers, or unstated requirements is needed to reach it.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"medium\">\n <xs:annotation>\n <xs:documentation>\n Likely real, but it rests on one assumption that was not verified,\n such as how a caller behaves, what a dependency guarantees, or\n what the intended requirement was. Stating that assumption in the\n body is expected at this level.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"low\">\n <xs:annotation>\n <xs:documentation>\n Speculative. The failure scenario was imagined rather than traced,\n or the finding depends on a constraint the author invented, or the\n author could not tell intent from the code. Worth a human's eyes,\n not worth acting on unattended.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"RemoteForgeEnum\">\n <xs:annotation>\n <xs:documentation>\n The forge hosting a remote pull/merge request.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"github\">\n <xs:annotation>\n <xs:documentation>A GitHub pull request.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"gitlab\">\n <xs:annotation>\n <xs:documentation>A GitLab merge request.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n</xs:schema>`;\n\nfunction extFromMediaType(mediaType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\n/**\n * Copies one attachment list's in-memory blobs into the asset directory and\n * returns the list with each fileName rewritten to its on-disk location and the\n * data buffer stripped.\n *\n * Shared by the comment walk and the reply walk. Serialization emits the\n * fileName it is given without checking that anything was written, so an\n * attachment list that misses this function produces a document that validates\n * against the schema while pointing at a file that does not exist. That failure\n * has no error surface, which is why both walks go through here.\n *\n * The idPrefix names the resulting files. Comments pass their own id, so\n * existing asset names are unchanged; replies pass a prefix that cannot collide\n * with a comment's.\n */\nfunction persistAttachments(\n attachments: Attachment[] | undefined,\n idPrefix: string,\n assetDir: string,\n onWrite: () => void\n): Attachment[] | undefined {\n if (!attachments?.length) return attachments;\n\n return attachments.map((att, index) => {\n if (!att.data) return att;\n onWrite();\n\n const ext = extFromMediaType(att.mediaType);\n const fileName = `${idPrefix}-${index}.${ext}`;\n const relativePath = `.self-review-assets/${fileName}`;\n\n if (!fs.existsSync(assetDir)) {\n fs.mkdirSync(assetDir, { recursive: true });\n }\n fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));\n\n return { ...att, fileName: relativePath, data: undefined };\n });\n}\n\nfunction writeAttachments(state: ReviewState, outputFilePath: string): ReviewState {\n const assetDir = path.join(path.dirname(outputFilePath), '.self-review-assets');\n let hasAttachments = false;\n const markWritten = () => {\n hasAttachments = true;\n };\n\n const updatedFiles = state.files.map(file => ({\n ...file,\n // Every comment is walked, including one with no attachments of its own:\n // its replies may carry attachments, and short-circuiting on the comment's\n // own list would drop those blobs without a word.\n comments: file.comments.map(comment => ({\n ...comment,\n attachments: persistAttachments(comment.attachments, comment.id, assetDir, markWritten),\n ...(comment.replies\n ? {\n replies: comment.replies.map(reply => ({\n ...reply,\n attachments: persistAttachments(\n reply.attachments,\n `${comment.id}-r-${reply.id}`,\n assetDir,\n markWritten\n ),\n })),\n }\n : {}),\n })),\n }));\n\n if (hasAttachments) {\n console.error(`[main] Wrote attachment files to ${assetDir}`);\n }\n\n return { ...state, files: updatedFiles };\n}\n\nexport async function serializeReview(state: ReviewState, outputFilePath: string): Promise<string> {\n const processedState = writeAttachments(state, outputFilePath);\n const xml = buildXml(processedState);\n\n // Validate the XML against the XSD\n try {\n const validationResult = await validateXML({\n xml: [{ fileName: 'review.xml', contents: xml }],\n schema: [{ fileName: 'self-review-v3.xsd', contents: XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const errors = validationResult.errors || [];\n console.error('XML validation failed:');\n errors.forEach((err: unknown) => console.error(` ${err}`));\n throw new Error('Generated XML does not conform to schema');\n }\n } catch (error) {\n // Re-throw if it's a schema validation failure (our own throw above)\n if (error instanceof Error && error.message === 'Generated XML does not conform to schema') {\n throw error;\n }\n // Infrastructure failure (e.g. WASM load): log warning and return XML anyway\n if (error instanceof Error) {\n console.error(`[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`);\n } else {\n console.error('[main] XML validation infrastructure failed - emitting XML without validation');\n }\n return xml;\n }\n\n return xml;\n}\n\nfunction buildSourceAttributes(state: ReviewState): string {\n const source = state.source;\n if (source.type === 'git') {\n return ` git-diff-args=\"${escapeXml(source.gitDiffArgs)}\" repository=\"${escapeXml(source.repository)}\"`;\n }\n if (source.type === 'directory' || source.type === 'file') {\n return ` source-path=\"${escapeXml(source.sourcePath)}\"`;\n }\n // welcome mode: no source attributes\n return '';\n}\n\n/**\n * Remote provenance attributes on the review root. Like severity and\n * confidence on a comment, absent means \"not a remote review\", so each\n * attribute is emitted only when its field is set: a purely local review\n * serializes byte-identically to a document written before these existed.\n */\nfunction buildRemoteAttributes(state: ReviewState): string {\n const attrs: string[] = [];\n\n if (state.remoteUrl) {\n attrs.push(`remote-url=\"${escapeXml(state.remoteUrl)}\"`);\n }\n if (state.remoteBaseSha) {\n attrs.push(`remote-base-sha=\"${escapeXml(state.remoteBaseSha)}\"`);\n }\n if (state.remoteHeadSha) {\n attrs.push(`remote-head-sha=\"${escapeXml(state.remoteHeadSha)}\"`);\n }\n if (state.remoteForge) {\n attrs.push(`remote-forge=\"${state.remoteForge}\"`);\n }\n\n return attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n}\n\nfunction buildXml(state: ReviewState): string {\n const lines: string[] = [];\n\n // XML declaration\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n\n // Root element with namespace\n const sourceAttrs = buildSourceAttributes(state);\n const remoteAttrs = buildRemoteAttributes(state);\n lines.push(\n `<review xmlns=\"urn:self-review:v3\" timestamp=\"${escapeXml(state.timestamp)}\"${sourceAttrs}${remoteAttrs}>`\n );\n\n // Files\n for (const file of state.files) {\n lines.push(...buildFileXml(file));\n }\n\n // Close root element\n lines.push('</review>');\n\n return lines.join('\\n');\n}\n\nfunction buildFileXml(file: FileReviewState): string[] {\n const lines: string[] = [];\n\n if (file.comments.length === 0) {\n // Self-closing tag for files with no comments\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\" />`\n );\n } else {\n // Opening tag\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\">`\n );\n\n // Comments\n for (const comment of file.comments) {\n lines.push(...buildCommentXml(comment));\n }\n\n // Closing tag\n lines.push(' </file>');\n }\n\n return lines;\n}\n\nfunction buildCommentXml(comment: ReviewComment): string[] {\n const lines: string[] = [];\n const attrs: string[] = [];\n\n // Add line attributes\n if (comment.lineRange) {\n if (comment.lineRange.side === 'old') {\n attrs.push(`old-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`old-line-end=\"${comment.lineRange.end}\"`);\n } else {\n attrs.push(`new-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`new-line-end=\"${comment.lineRange.end}\"`);\n }\n }\n\n if (comment.author) {\n attrs.push(`author=\"${escapeXml(comment.author)}\"`);\n }\n\n // Thresholding signals. Absent means \"below any floor\", so they are omitted\n // rather than defaulted when the author did not take a position.\n if (comment.severity) {\n attrs.push(`severity=\"${comment.severity}\"`);\n }\n\n if (comment.confidence) {\n attrs.push(`confidence=\"${comment.confidence}\"`);\n }\n\n // Remote provenance. Absent means locally authored, so it is omitted\n // rather than defaulted, exactly like the signals above.\n if (comment.remoteId) {\n attrs.push(`remote-id=\"${escapeXml(comment.remoteId)}\"`);\n }\n\n const attrStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n\n // Opening tag\n lines.push(` <comment${attrStr}>`);\n\n // Body (preserve whitespace and newlines)\n lines.push(` <body>${escapeXml(comment.body)}</body>`);\n\n // Category (required)\n lines.push(` <category>${escapeXml(comment.category)}</category>`);\n\n // Suggestion\n if (comment.suggestion) {\n lines.push(' <suggestion>');\n lines.push(\n ` <original-code>${escapeXml(comment.suggestion.originalCode)}</original-code>`\n );\n lines.push(\n ` <proposed-code>${escapeXml(comment.suggestion.proposedCode)}</proposed-code>`\n );\n lines.push(' </suggestion>');\n }\n\n // Attachments\n lines.push(...buildAttachmentXml(comment.attachments, ' '));\n\n // Replies, in array order: document order is conversation order, and it is\n // the only ordering signal a reply has.\n for (const reply of comment.replies ?? []) {\n lines.push(...buildReplyXml(reply));\n }\n\n // Closing tag\n lines.push(' </comment>');\n\n return lines;\n}\n\n/**\n * Attachment elements are identical in form and meaning under a comment and\n * under a reply, so both call sites emit them from here.\n */\nfunction buildAttachmentXml(attachments: Attachment[] | undefined, indent: string): string[] {\n if (!attachments?.length) return [];\n\n return attachments.map(\n att =>\n `${indent}<attachment path=\"${escapeXml(att.fileName)}\" media-type=\"${escapeXml(att.mediaType)}\" />`\n );\n}\n\n/**\n * A reply is a flat turn in the thread: a body, optional attachments and an\n * optional author. It carries no category, severity, confidence, suggestion or\n * nested replies — those belong to the root comment, which owns the finding.\n * See ReplyType in the XSD for the reasoning.\n */\nfunction buildReplyXml(reply: Reply): string[] {\n const attrs: string[] = [];\n\n if (reply.author) {\n attrs.push(`author=\"${escapeXml(reply.author)}\"`);\n }\n if (reply.remoteId) {\n attrs.push(`remote-id=\"${escapeXml(reply.remoteId)}\"`);\n }\n\n const attrStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n\n return [\n ` <reply${attrStr}>`,\n ` <body>${escapeXml(reply.body)}</body>`,\n ...buildAttachmentXml(reply.attachments, ' '),\n ' </reply>',\n ];\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n","// src/main/xml-parser.ts\n// Parse XML review file back into ReviewComment[]\n\nimport { readFileSync } from 'fs';\nimport { XMLParser } from 'fast-xml-parser';\nimport {\n ReviewComment,\n Suggestion,\n LineRange,\n DiffSource,\n CommentSeverity,\n CommentConfidence,\n RemoteForge,\n Attachment,\n Reply,\n} from './types';\n\nconst SEVERITY_VALUES: readonly CommentSeverity[] = ['critical', 'major', 'minor', 'info'];\nconst CONFIDENCE_VALUES: readonly CommentConfidence[] = ['high', 'medium', 'low'];\nconst REMOTE_FORGE_VALUES: readonly RemoteForge[] = ['github', 'gitlab'];\n\nexport interface ParsedReview {\n comments: ReviewComment[];\n /** Paths of files the previous review marked as done (`viewed=\"true\"`). */\n viewedFiles: string[];\n gitDiffArgs: string;\n source: DiffSource;\n // Remote provenance, read tolerantly off the review root. Undefined when\n // the document carries no remote attributes, i.e. every pre-remote and\n // purely local review.\n remoteUrl?: string;\n remoteBaseSha?: string;\n remoteHeadSha?: string;\n remoteForge?: RemoteForge;\n}\n\nexport function parseReviewXml(xmlPath: string): ParsedReview {\n try {\n const xmlContent = readFileSync(xmlPath, 'utf-8');\n return parseReviewXmlString(xmlContent);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error reading XML file: ${error.message}`);\n } else {\n console.error('Error reading XML file: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function parseReviewXmlString(xmlContent: string): ParsedReview {\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n allowBooleanAttributes: true,\n trimValues: false,\n });\n\n try {\n const result = parser.parse(xmlContent);\n\n if (!result.review) {\n throw new Error('Invalid XML: missing <review> root element');\n }\n\n const review = result.review;\n const gitDiffArgs = review['@_git-diff-args'] || '';\n const source = parseSource(review);\n const comments: ReviewComment[] = [];\n const viewedFiles: string[] = [];\n\n // Handle files array\n const files = toChildArray(review.file);\n\n for (const file of files) {\n // Skip only when the attribute is genuinely absent: the empty string\n // is the review-level sentinel path (REVIEW_LEVEL_FILE_PATH) used by\n // fetch-comments for threads with no file anchor, and must round-trip.\n const rawPath = file['@_path'];\n if (rawPath === undefined || rawPath === null) continue;\n const filePath = String(rawPath);\n\n if (parseViewed(file['@_viewed'])) {\n viewedFiles.push(filePath);\n }\n\n // Handle comments array\n const fileComments = toChildArray(file.comment);\n\n for (const comment of fileComments) {\n const reviewComment: ReviewComment = {\n id: generateId(),\n filePath,\n lineRange: parseLineRange(comment),\n body: comment.body !== undefined ? String(comment.body) : '',\n category: comment.category !== undefined ? String(comment.category) : '',\n suggestion: parseSuggestion(comment),\n author: comment['@_author'] ? String(comment['@_author']) : undefined,\n severity: parseEnumAttribute(comment['@_severity'], SEVERITY_VALUES),\n confidence: parseEnumAttribute(comment['@_confidence'], CONFIDENCE_VALUES),\n remoteId: parseStringAttribute(comment['@_remote-id']),\n };\n\n const attachments = parseAttachments(comment, reviewComment.id);\n if (attachments) reviewComment.attachments = attachments;\n\n const replies = parseReplies(comment);\n if (replies) reviewComment.replies = replies;\n\n comments.push(reviewComment);\n }\n }\n\n return {\n comments,\n viewedFiles,\n gitDiffArgs,\n source,\n remoteUrl: parseStringAttribute(review['@_remote-url']),\n remoteBaseSha: parseStringAttribute(review['@_remote-base-sha']),\n remoteHeadSha: parseStringAttribute(review['@_remote-head-sha']),\n remoteForge: parseEnumAttribute(review['@_remote-forge'], REMOTE_FORGE_VALUES),\n };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error parsing XML: ${error.message}`);\n } else {\n console.error('Error parsing XML: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Read an enumerated attribute, dropping values the schema does not define.\n *\n * An unrecognised value becomes undefined rather than being passed through:\n * undefined is the fail-safe reading (below every threshold floor), and it\n * keeps a resumed review serializable, since the serializer validates its\n * output against the XSD before writing.\n */\nfunction parseEnumAttribute<T extends string>(\n raw: unknown,\n allowed: readonly T[]\n): T | undefined {\n if (raw === undefined || raw === null) return undefined;\n const value = String(raw);\n return allowed.includes(value as T) ? (value as T) : undefined;\n}\n\n/**\n * Read an optional free-form string attribute, leaving absent as undefined.\n * Values are taken as-is: the remote attributes are provenance the app never\n * interprets, so there is nothing to validate on read.\n */\nfunction parseStringAttribute(raw: unknown): string | undefined {\n return raw === undefined || raw === null ? undefined : String(raw);\n}\n\n/**\n * Read the `viewed` attribute of a <file> element.\n *\n * Anything other than an explicit true reads as not viewed: the attribute is\n * optional, and treating an unknown value as \"already reviewed\" would silently\n * hide files from the resumed review.\n */\nfunction parseViewed(raw: unknown): boolean {\n return raw === true || String(raw) === 'true';\n}\n\nfunction parseSource(review: Record<string, unknown>): DiffSource {\n const sourcePath = review['@_source-path'];\n if (sourcePath) {\n return { type: 'directory', sourcePath: String(sourcePath) };\n }\n\n const gitDiffArgs = review['@_git-diff-args'];\n const repository = review['@_repository'];\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: String(gitDiffArgs || ''),\n repository: String(repository || ''),\n };\n }\n\n return { type: 'welcome' };\n}\n\nfunction parseLineRange(comment: Record<string, unknown>): LineRange | null {\n const hasOld =\n comment['@_old-line-start'] !== undefined &&\n comment['@_old-line-end'] !== undefined;\n const hasNew =\n comment['@_new-line-start'] !== undefined &&\n comment['@_new-line-end'] !== undefined;\n\n if (hasOld) {\n return {\n side: 'old',\n start: parseInt(String(comment['@_old-line-start']), 10),\n end: parseInt(String(comment['@_old-line-end']), 10),\n };\n }\n\n if (hasNew) {\n return {\n side: 'new',\n start: parseInt(String(comment['@_new-line-start']), 10),\n end: parseInt(String(comment['@_new-line-end']), 10),\n };\n }\n\n return null; // File-level comment\n}\n\nfunction parseSuggestion(comment: Record<string, unknown>): Suggestion | null {\n if (!comment.suggestion) {\n return null;\n }\n\n const suggestion = comment.suggestion as Record<string, unknown>;\n return {\n originalCode: String(suggestion['original-code'] || ''),\n proposedCode: String(suggestion['proposed-code'] || ''),\n };\n}\n\n/**\n * Normalize a repeatable child element into an array.\n *\n * fast-xml-parser collapses a single occurrence into a bare object and only\n * produces an array from two or more, so every repeatable child in this file\n * has to be widened before it can be iterated. An absent child yields an empty\n * array.\n */\nfunction toChildArray(raw: unknown): Record<string, unknown>[] {\n if (Array.isArray(raw)) return raw as Record<string, unknown>[];\n if (raw === undefined || raw === null) return [];\n return [raw as Record<string, unknown>];\n}\n\n/**\n * Read `<attachment>` children of a comment or a reply.\n *\n * Attachment ids are synthetic: nothing in the document names them, so they are\n * derived from the id of their owner, which is why the prefix is a parameter\n * rather than read off the node. Returns undefined rather than [] when there\n * are none, matching the optional field on the type.\n */\nfunction parseAttachments(\n node: Record<string, unknown>,\n idPrefix: string\n): Attachment[] | undefined {\n const raw = toChildArray(node.attachment);\n if (raw.length === 0) return undefined;\n\n return raw.map((att, i) => ({\n id: `${idPrefix}-att-${i}`,\n fileName: String(att['@_path'] || ''),\n mediaType: String(att['@_media-type'] || 'image/png'),\n }));\n}\n\n/**\n * Read `<reply>` children in document order.\n *\n * Document order is conversation order: a reply carries no timestamp and no\n * identifier, so the order of this array is the only ordering signal a thread\n * ever has. Returns undefined rather than [] when there are none, so a\n * reply-free comment keeps exactly the shape it had before threads existed.\n */\nfunction parseReplies(comment: Record<string, unknown>): Reply[] | undefined {\n const raw = toChildArray(comment.reply);\n if (raw.length === 0) return undefined;\n\n return raw.map(node => {\n const id = generateId();\n const reply: Reply = {\n id,\n body: node.body !== undefined ? String(node.body) : '',\n author: node['@_author'] ? String(node['@_author']) : undefined,\n remoteId: parseStringAttribute(node['@_remote-id']),\n };\n\n const attachments = parseAttachments(node, id);\n if (attachments) reply.attachments = attachments;\n\n return reply;\n });\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// packages/core/src/guide-schema.ts\n// Embedded copy of the walkthrough guide XSD for validation.\n\n// This MUST stay byte-identical to the on-disk copy at\n// .agents/skills/self-review-guide/assets/self-review-guide-v1.xsd;\n// the sync test in xsd-schema.test.ts enforces it.\nexport const GUIDE_XSD_SCHEMA = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sg=\"urn:self-review-guide:v1\"\n targetNamespace=\"urn:self-review-guide:v1\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review guide XML Schema v1\n ===============================\n Defines the walkthrough guide sidecar for the self-review application.\n This schema is designed to be both machine-validated and fed to an LLM\n so it can author valid guide documents from the schema alone.\n\n Key concepts:\n - A <guide> is a read-only orientation aid generated BEFORE a review\n starts. It lives next to the review output file and is discovered by\n convention; it is never written by the review UI.\n - The optional <overview> is short Markdown prose shown before the\n first file, orienting the reviewer to the change as a whole.\n - Each <group> names a set of files that belong together (for example\n \"Core change\", \"Tests\", \"Generated/mechanical\") and explains, in one\n line, why they are grouped and where they sit in the reading order.\n - Each <file> inside a group points at one diff file by its\n repository-relative path and carries a one-line description of the\n role that file plays in the change.\n\n Ordering:\n - Document order IS the reading order. Groups are presented in the\n order they appear, and files within a group are presented in the\n order they appear. There are no explicit ordering attributes; to\n reorder, reorder the elements.\n\n Presentation only, never suppression:\n - This vocabulary labels and orders content; it cannot hide it. There\n is deliberately no element or attribute that hides, collapses, or\n marks a file as skippable, and none may be added to v1. Files in the\n diff that no group mentions remain fully visible in an implicit\n \"Everything else\" group; files mentioned here but absent from the\n diff are silently ignored.\n\n Tolerance:\n - A missing, stale, or invalid guide degrades the consumer to its\n normal ungrouped view. A guide can therefore never block or fail a\n review, but an invalid guide is silently useless, so authors should\n validate against this schema before writing the file.\n -->\n\n <!-- ===== Root element ===== -->\n\n <xs:element name=\"guide\" type=\"sg:GuideType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review walkthrough guide sidecar. Contains\n an optional overview followed by zero or more ordered groups.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <!-- ===== Complex types ===== -->\n\n <xs:complexType name=\"GuideType\">\n <xs:annotation>\n <xs:documentation>\n The whole walkthrough guide. The optional metadata attributes\n mirror the review schema's provenance attributes so a consumer can\n sanity-check that the guide was generated for the diff it is being\n shown next to; none of them are required and none affect\n presentation.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"overview\" type=\"xs:string\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Review-level orientation prose shown before the first file.\n Markdown formatting is allowed, including fenced code blocks;\n a fenced code block labelled \"mermaid\" may be used for a\n diagram of the change.\n Keep it short: a few sentences saying what the change does and\n where to start reading, not a restatement of every file.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"group\" type=\"sg:GroupType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Ordered reading groups. The first group should hold the files\n the reviewer must understand first (the core of the change);\n later groups hold consequences, tests, and mechanical fallout.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the guide was generated.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments the guide was generated against.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when the guide describes a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root the guide was generated in.\n Present only when the guide describes a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"GroupType\">\n <xs:annotation>\n <xs:documentation>\n A named set of related files with a one-line rationale. Groups are\n labels for orientation, never suppressions: a consumer shows every\n group and every file in it. Position in the document is position\n in the reading order.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"rationale\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n One line explaining why these files form a group and what the\n reviewer should look for in them (e.g., \"The retry wrapper\n everything else calls; read this first\"). Plain text, a single\n sentence; no Markdown, no line breaks.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"file\" type=\"sg:FileEntryType\" minOccurs=\"1\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n The files in this group, in reading order. A group must list\n at least one file; do not author empty placeholder groups.\n Every file in the diff may appear in at most one group, and\n files omitted from every group are not hidden — the consumer\n shows them in an implicit trailing \"Everything else\" group.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Short display name for the group, e.g. \"Core change\", \"Tests\",\n \"Generated/mechanical\". Shown as the group heading in the file\n tree; keep it to a few words.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileEntryType\">\n <xs:annotation>\n <xs:documentation>\n One file in a group. The path must match a file in the diff being\n reviewed; entries whose path matches nothing in the diff are\n silently dropped by the consumer, so a stale guide degrades\n instead of erroring.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"description\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n One line describing the role this file plays in the change\n (e.g., \"Adds the retry wrapper that everything else calls\").\n Plain text, a single sentence; no Markdown, no line breaks.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root, using the same\n convention as review.xml file paths. For renamed files, use the\n new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n</xs:schema>`;\n","// packages/core/src/guide-parser.ts\n// Parse a walkthrough guide XML string into a typed ReviewGuide, and\n// reconcile a guide with the diff's file list into resolved display groups.\n//\n// Tolerance contract (binding, from docs/intent/llm-review-guide.md): the\n// guide is orientation garnish on a deterministic tool. A missing, stale, or\n// invalid guide degrades the consumer to its flat view — parsing problems\n// are failure VALUES the caller can log and ignore, never exceptions.\n\nimport { XMLParser } from 'fast-xml-parser';\nimport { validateXML } from 'xmllint-wasm';\nimport type {\n GuideFileEntry,\n GuideGroup,\n ResolvedGuideGroup,\n ResolvedGuideFile,\n ReviewGuide,\n} from './types';\nimport { GUIDE_XSD_SCHEMA } from './guide-schema';\n\n/** Display name given to the derived trailing group of unmentioned files. */\nexport const IMPLICIT_GUIDE_GROUP_NAME = 'Everything else';\n\nexport type GuideParseResult =\n | { ok: true; guide: ReviewGuide }\n | { ok: false; reason: string };\n\n/**\n * Parse and validate a guide XML string.\n *\n * The document is validated against the embedded self-review-guide-v1 XSD\n * (same xmllint-wasm tooling the review serializer uses) before being read,\n * so a successful result is structurally guaranteed by the schema. Any\n * defect — non-XML input, schema violations, validator failure — comes back\n * as `{ ok: false, reason }`; this function never throws on bad input.\n */\nexport async function parseGuideXml(xmlContent: string): Promise<GuideParseResult> {\n try {\n const validationResult = await validateXML({\n xml: [{ fileName: 'guide.xml', contents: xmlContent }],\n schema: [\n { fileName: 'self-review-guide-v1.xsd', contents: GUIDE_XSD_SCHEMA },\n ],\n });\n\n if (!validationResult.valid) {\n const details = (validationResult.errors || [])\n .map(err => (typeof err === 'string' ? err : err.message))\n .join('; ');\n return {\n ok: false,\n reason: `Guide XML does not conform to self-review-guide-v1 schema${details ? `: ${details}` : ''}`,\n };\n }\n\n return { ok: true, guide: readGuide(xmlContent) };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, reason: `Failed to parse guide XML: ${message}` };\n }\n}\n\n/**\n * Extract the typed guide from a document that already passed XSD\n * validation. Values are still string-coerced defensively, but structural\n * guarantees (required attributes/elements, at least one file per group)\n * come from the schema.\n */\nfunction readGuide(xmlContent: string): ReviewGuide {\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n // Keep values verbatim: a description like \"007\" or an overview of\n // \"true\" must stay a string, not become a number or boolean.\n parseTagValue: false,\n parseAttributeValue: false,\n // A prefixed form (<sg:guide xmlns:sg=\"urn:self-review-guide:v1\">) is\n // schema-valid, so reading must accept it too; without this the lookup\n // of `.guide` below finds nothing.\n removeNSPrefix: true,\n });\n\n const root = parser.parse(xmlContent).guide as Record<string, unknown>;\n\n const guide: ReviewGuide = { groups: asArray(root.group).map(readGroup) };\n\n const overview = root.overview;\n if (typeof overview === 'string' && overview !== '') {\n guide.overview = overview;\n }\n\n return guide;\n}\n\nfunction readGroup(raw: unknown): GuideGroup {\n const group = raw as Record<string, unknown>;\n return {\n name: String(group['@_name']),\n rationale: String(group.rationale ?? ''),\n files: asArray(group.file).map(readFileEntry),\n };\n}\n\nfunction readFileEntry(raw: unknown): GuideFileEntry {\n const file = raw as Record<string, unknown>;\n return {\n path: String(file['@_path']),\n description: String(file.description ?? ''),\n };\n}\n\n/** fast-xml-parser yields a bare object for singular elements; normalize. */\nfunction asArray(value: unknown): unknown[] {\n if (value === undefined || value === null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Merge a parsed guide with the diff's file list into resolved display\n * groups, tolerantly:\n *\n * - Guide entries whose path is not in the diff are dropped (stale guide);\n * a group left with no surviving files is dropped entirely.\n * - A file referenced by more than one group appears only in the first.\n * - Diff files no group mentions land in a terminal implicit\n * \"Everything else\" group, preserving the diff's file order, marked\n * `implicit: true` so the UI can label it.\n * - Guide group order and in-group file order are preserved.\n */\nexport function reconcileGuide(\n guide: ReviewGuide,\n diffFilePaths: string[]\n): ResolvedGuideGroup[] {\n const diffPaths = new Set(diffFilePaths);\n const claimed = new Set<string>();\n const resolved: ResolvedGuideGroup[] = [];\n\n for (const group of guide.groups) {\n const files: ResolvedGuideFile[] = [];\n for (const file of group.files) {\n if (!diffPaths.has(file.path) || claimed.has(file.path)) continue;\n claimed.add(file.path);\n files.push({ path: file.path, description: file.description });\n }\n if (files.length > 0) {\n resolved.push({\n name: group.name,\n rationale: group.rationale,\n implicit: false,\n files,\n });\n }\n }\n\n const leftover = diffFilePaths.filter(path => !claimed.has(path));\n if (leftover.length > 0) {\n resolved.push({\n name: IMPLICIT_GUIDE_GROUP_NAME,\n implicit: true,\n files: leftover.map(path => ({ path })),\n });\n }\n\n return resolved;\n}\n","// src/main/git.ts\n// Git command execution\n\nimport { execSync, exec, execFile, execFileSync } from 'child_process';\nimport { promisify } from 'util';\nimport { generateSyntheticDiffs } from './synthetic-diff';\n\nconst execAsync = promisify(exec);\nconst execFileAsync = promisify(execFile);\n\nexport function runGitDiff(args: string[]): string {\n try {\n // Check if git is available\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n // Check if we're in a git repository\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n\n // Run git diff with the provided arguments\n const result = execFileSync('git', ['diff', ...args], {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large diffs\n });\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function getRepoRoot(): string {\n try {\n const result = execSync('git rev-parse --show-toplevel', {\n encoding: 'utf-8',\n });\n return result.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Lightweight sync validation - checks if git is available and we're in a repo.\n * Called BEFORE Electron initialization for early exit path.\n */\nexport function validateGitAvailable(): void {\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n}\n\n/**\n * Async version of getRepoRoot - called AFTER app.whenReady().\n */\nexport async function getRepoRootAsync(cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync('git rev-parse --show-toplevel', {\n timeout: 10000, // 10 second timeout\n cwd,\n });\n return stdout.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Async version of runGitDiff - called AFTER app.whenReady().\n * Uses timeout to prevent hanging in CI environments.\n */\nexport async function runGitDiffAsync(args: string[], cwd?: string): Promise<string> {\n try {\n const { stdout } = await execFileAsync('git', ['diff', ...args], {\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer\n timeout: 30000, // 30 second timeout\n cwd,\n });\n return stdout;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Read a blob from a git object spec (`<sha>:<path>`) as raw bytes.\n * Remote mode reads reviewed content at the fetched head SHA — a temporary\n * clone's working tree stays on the default branch and never reflects the\n * PR/MR head.\n */\nexport async function readGitBlobAsync(\n repoPath: string,\n spec: string\n): Promise<Buffer> {\n return await new Promise<Buffer>((resolve, reject) => {\n execFile(\n 'git',\n ['-C', repoPath, 'show', spec],\n { encoding: 'buffer', maxBuffer: 50 * 1024 * 1024, timeout: 30000 },\n (error, stdout) => {\n if (error) {\n reject(error);\n } else {\n resolve(stdout);\n }\n }\n );\n });\n}\n\n/**\n * Get list of untracked files (respects .gitignore).\n */\nexport async function getUntrackedFilesAsync(cwd?: string): Promise<string[]> {\n try {\n const { stdout } = await execAsync(\n 'git ls-files --others --exclude-standard',\n {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 10000,\n cwd,\n }\n );\n return stdout\n .trim()\n .split('\\n')\n .filter(line => line.length > 0);\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Warning: Failed to list untracked files: ${error.message}`\n );\n } else {\n console.error('Warning: Failed to list untracked files: unknown error');\n }\n return [];\n }\n}\n\n/**\n * Generate synthetic unified diffs for untracked files so they can be\n * parsed by the existing diff parser.\n *\n * Delegates to the reusable generateSyntheticDiffs module.\n */\nexport function generateUntrackedDiffs(\n paths: string[],\n repoRoot: string\n): string {\n return generateSyntheticDiffs(paths, repoRoot);\n}\n","// src/main/synthetic-diff.ts\n// Generates synthetic unified diffs for files that aren't tracked by git.\n// Reusable by both git untracked file handling and directory-based scanning.\n\nimport { readFileSync } from 'fs';\n\n/**\n * Generate synthetic unified diffs for a list of file paths so they can be\n * parsed by the existing diff parser. Each file is treated as a new addition.\n *\n * @param paths - Relative file paths (e.g. \"src/foo.ts\")\n * @param rootDir - Absolute path to the root directory containing the files\n * @returns A unified diff string covering all provided files\n */\nexport function generateSyntheticDiffs(\n paths: string[],\n rootDir: string\n): string {\n const diffs: string[] = [];\n\n for (const filePath of paths) {\n const fullPath = `${rootDir}/${filePath}`;\n let content: Buffer;\n try {\n content = readFileSync(fullPath);\n } catch {\n // File may have been deleted between listing and reading\n continue;\n }\n\n // Detect binary files by checking for null bytes in the first 8KB\n const sample = content.subarray(0, 8192);\n const isBinary = sample.includes(0);\n\n if (isBinary) {\n diffs.push(\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `Binary files /dev/null and b/${filePath} differ`\n );\n continue;\n }\n\n const text = content.toString('utf-8');\n const lines = text.split('\\n');\n\n // Remove trailing empty string from split if file ends with newline\n if (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n\n const lineCount = lines.length;\n const addedLines = lines.map(line => `+${line}`).join('\\n');\n\n let diff =\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `--- /dev/null\\n` +\n `+++ b/${filePath}\\n` +\n `@@ -0,0 +1,${lineCount} @@\\n` +\n addedLines;\n\n // Indicate missing newline at end of file\n if (text.length > 0 && !text.endsWith('\\n')) {\n diff += '\\n\\\';\n }\n\n diffs.push(diff);\n }\n\n return diffs.join('\\n');\n}\n","// forge-provider.ts\n// Conversation-plane forge abstraction: URL parsing with forge detection by\n// path shape, the ForgeProvider interface (base-branch lookup + thread fetch),\n// and the forge-neutral normalized thread types produced by every provider.\n//\n// This module is pure code: no I/O, no child processes. Provider\n// implementations (github-provider.ts, gitlab-provider.ts) do the CLI work\n// through an injectable command runner so they stay unit-testable.\n\n/** Forges the app knows how to talk to. */\nexport type ForgeName = 'github' | 'gitlab';\n\n/**\n * A parsed pull-request / merge-request web URL.\n *\n * Detection is by URL path shape only (`/pull/N` → GitHub,\n * `/-/merge_requests/N` → GitLab) on any host, so self-hosted instances such\n * as git.drupalcode.org work with zero configuration.\n */\nexport interface ForgeUrl {\n forge: ForgeName;\n /** Host as it appears in the URL, including a port when present. */\n host: string;\n /**\n * Repository owner. For GitLab this is the full namespace path and may\n * contain slashes (subgroups, e.g. `group/subgroup`); for GitHub it is a\n * single segment.\n */\n owner: string;\n /** Repository name (final path segment before the PR/MR marker). */\n repo: string;\n /** Pull-request number / merge-request IID. */\n number: number;\n}\n\n/** Which side of the diff a thread anchor points at. */\nexport type ForgeAnchorSide = 'old' | 'new';\n\n/**\n * Forge-neutral anchor of a discussion thread onto the diff.\n *\n * The mapper consumes this shape without forge-conditional logic:\n * - `startLine`/`endLine` are equal for single-line anchors.\n * - `startLine`/`endLine` are `null` when the forge supplies a file path but\n * no usable line information (the mapper degrades to a file-level comment;\n * `side` is meaningless in that case and providers should set `'new'`).\n * - `outdated: true` means the forge reports the anchor no longer applies to\n * the current head (e.g. GitHub outdated review comments); the line fields\n * then hold the historic anchor and the mapper degrades to file-level.\n */\nexport interface ForgeThreadAnchor {\n filePath: string;\n side: ForgeAnchorSide;\n startLine: number | null;\n endLine: number | null;\n outdated: boolean;\n}\n\n/** One turn (root comment or reply) in a forge discussion thread. */\nexport interface ForgeThreadTurn {\n /** Forge-assigned comment/note ID, kept as a string verbatim. */\n remoteId: string;\n /** Forge username of the turn's author. */\n author: string;\n /** Markdown body, passed through verbatim. */\n body: string;\n}\n\n/**\n * A normalized discussion thread: an ordered root + flat replies.\n *\n * The root turn owns the anchor. `anchor` is `null` for threads with no file\n * association at all (e.g. GitLab non-diff discussions); the mapper turns\n * those into its review-level representation. `replies` preserve the forge's\n * document order — nothing else sorts them.\n */\nexport interface ForgeThread {\n root: ForgeThreadTurn;\n replies: ForgeThreadTurn[];\n anchor: ForgeThreadAnchor | null;\n}\n\n/** Options for {@link ForgeProvider.fetchThreads}. */\nexport interface FetchThreadsOptions {\n /**\n * Include threads the forge marks resolved. Defaults to false where the\n * forge tracks resolution (GitLab); providers without a comparable concept\n * on the fetch path (GitHub REST review comments) may ignore it.\n */\n includeResolved?: boolean;\n}\n\n/**\n * Result of running a forge CLI command through {@link ForgeCommandRunner}.\n */\nexport interface ForgeCommandResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n}\n\n/**\n * Injectable command runner used by provider implementations, mirroring how\n * `git.ts` keeps child-process execution testable. Resolves with the exit\n * code on any completed run (including non-zero); rejects only when the\n * binary cannot be spawned at all (e.g. ENOENT when the CLI is absent).\n */\nexport type ForgeCommandRunner = (\n command: string,\n args: string[]\n) => Promise<ForgeCommandResult>;\n\n/**\n * The conversation plane of a forge. Exactly two capabilities: base-branch\n * lookup and discussion-thread fetching. No diff fetching, no blob fetching,\n * no posting — those concerns live elsewhere.\n *\n * Implementations throw {@link ForgeCliUnavailableError} when their CLI is\n * absent or unauthenticated so callers can degrade cleanly.\n */\nexport interface ForgeProvider {\n readonly forge: ForgeName;\n /** Resolve the PR/MR base (target) branch name. */\n fetchBaseBranch(url: ForgeUrl): Promise<string>;\n /** Fetch the PR/MR discussion threads in normalized form. */\n fetchThreads(\n url: ForgeUrl,\n options?: FetchThreadsOptions\n ): Promise<ForgeThread[]>;\n}\n\n/**\n * Thrown by providers when their CLI is missing (spawn ENOENT) or exits\n * non-zero due to authentication/API failure. Callers catch this to degrade\n * (print to stderr, continue without threads) instead of crashing.\n */\nexport class ForgeCliUnavailableError extends Error {\n readonly forge: ForgeName;\n readonly cli: string;\n\n constructor(forge: ForgeName, cli: string, message: string) {\n super(message);\n this.name = 'ForgeCliUnavailableError';\n this.forge = forge;\n this.cli = cli;\n }\n}\n\n// Path-shape matchers. The number must terminate its path segment so\n// `/pull/12x` does not parse as PR 12; anything after the number segment\n// (trailing slash, sub-pages like /files) still identifies the same PR/MR.\n// Numbered groups (owner, repo, number in order): the app tsconfig targets\n// ES6, which predates named capture groups.\nconst GITHUB_PR_PATH = /^\\/([^/]+)\\/([^/]+)\\/pull\\/(\\d+)(?=\\/|$)/;\nconst GITLAB_MR_PATH = /^\\/(.+)\\/([^/]+)\\/-\\/merge_requests\\/(\\d+)(?=\\/|$)/;\n\n/**\n * Parse a forge web URL into a {@link ForgeUrl}, or return `null` for\n * anything that is not a PR/MR URL. Detection is by path shape only, on any\n * http(s) host. Query strings and fragments are ignored.\n */\nexport function parseForgeUrl(url: string): ForgeUrl | null {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return null;\n }\n\n // GitLab first: `/-/merge_requests/` is the more specific marker.\n const gitlab = GITLAB_MR_PATH.exec(parsed.pathname);\n if (gitlab) {\n return {\n forge: 'gitlab',\n host: parsed.host,\n owner: gitlab[1],\n repo: gitlab[2],\n number: Number.parseInt(gitlab[3], 10),\n };\n }\n\n const github = GITHUB_PR_PATH.exec(parsed.pathname);\n if (github) {\n return {\n forge: 'github',\n host: parsed.host,\n owner: github[1],\n repo: github[2],\n number: Number.parseInt(github[3], 10),\n };\n }\n\n return null;\n}\n","// src/main/directory-scanner.ts\n// Recursively scans a directory and produces DiffFile[] treating all files as new additions.\n\nimport { readdir, stat } from 'fs/promises';\nimport { join, relative, basename, dirname } from 'path';\nimport { DiffFile } from './types';\nimport { generateSyntheticDiffs } from './synthetic-diff';\nimport { parseDiff } from './diff-parser';\nimport { createIgnoreFilter } from './ignore-filter';\n\n/**\n * Recursively scan a directory and return DiffFile[] with every file\n * treated as a new addition (changeType: 'added').\n *\n * @param directoryPath - Absolute path to the directory to scan\n * @param ignorePatterns - Optional gitignore-compatible patterns to exclude files\n * @returns Parsed DiffFile array for all files in the directory\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = []\n): Promise<DiffFile[]> {\n // Verify the path is a directory\n try {\n const dirStat = await stat(directoryPath);\n if (!dirStat.isDirectory()) {\n console.error(\n `Error: \"${directoryPath}\" is not a directory`\n );\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error accessing directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error accessing directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n const filePaths: string[] = [];\n\n try {\n const entries = await readdir(directoryPath, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n\n // Build the full path from the entry's parentPath (or path) and name\n const parentDir = entry.parentPath ?? entry.path;\n const fullPath = join(parentDir, entry.name);\n const relativePath = relative(directoryPath, fullPath);\n filePaths.push(relativePath);\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error reading directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error reading directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n // Sort for deterministic output\n filePaths.sort();\n\n // Apply ignore patterns\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredPaths = filePaths.filter(p => shouldKeep(p));\n\n if (filteredPaths.length === 0) {\n return [];\n }\n\n const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);\n return parseDiff(diffText);\n}\n\n/**\n * Scan a single file and return DiffFile[] with the file treated as a new addition.\n *\n * @param filePath - Absolute path to the file to scan\n * @returns Parsed DiffFile array (single element)\n */\nexport async function scanFile(filePath: string): Promise<DiffFile[]> {\n try {\n const fileStat = await stat(filePath);\n if (!fileStat.isFile()) {\n console.error(`Error: \"${filePath}\" is not a file`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing file \"${filePath}\": ${error.message}`);\n } else {\n console.error(`Error accessing file \"${filePath}\": unknown error`);\n }\n return [];\n }\n\n const fileName = basename(filePath);\n const rootDir = dirname(filePath);\n const diffText = generateSyntheticDiffs([fileName], rootDir);\n return parseDiff(diffText);\n}\n","// src/main/ignore-filter.ts\n// Gitignore-compatible file path filtering using the `ignore` package.\n\nimport ignore from 'ignore';\n\n/**\n * Create a filter function from gitignore-compatible patterns.\n *\n * @param patterns - Array of gitignore-compatible glob patterns\n * @returns A predicate that returns `true` if the path should be kept (not ignored)\n */\nexport function createIgnoreFilter(\n patterns: string[]\n): (path: string) => boolean {\n if (patterns.length === 0) return () => true;\n const ig = ignore().add(patterns);\n return (filePath: string) => !ig.ignores(filePath);\n}\n","// src/main/config.ts\n// YAML configuration loading and merging\n\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { parse as parseYaml } from 'yaml';\nimport { AppConfig } from './types';\n\nconst defaults: AppConfig = {\n theme: 'system',\n diffView: 'split',\n fontSize: 14,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: [\n '.git',\n 'node_modules',\n 'vendor',\n '.vendor',\n '__pycache__',\n '.venv',\n 'venv',\n '.env',\n 'dist',\n 'build',\n '.next',\n '.nuxt',\n '.svelte-kit',\n 'target',\n '*.min.js',\n '*.min.css',\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Gemfile.lock',\n 'Cargo.lock',\n 'poetry.lock',\n 'go.sum',\n ],\n categories: [\n {\n name: 'question',\n description: 'Clarification needed — not necessarily a problem',\n color: '#805ad5',\n },\n {\n name: 'bug',\n description: 'Likely defect or incorrect behavior',\n color: '#e53e3e',\n },\n {\n name: 'security',\n description: 'Security vulnerability or concern',\n color: '#dd6b20',\n },\n {\n name: 'style',\n description: 'Code style, naming, or formatting issue',\n color: '#3182ce',\n },\n {\n name: 'task',\n description: 'Action item or follow-up task',\n color: '#38a169',\n },\n {\n name: 'nit',\n description: 'Minor nitpick, low priority',\n color: '#718096',\n },\n ],\n defaultDiffArgs: '',\n showUntracked: true,\n showUntrackedExplicit: false,\n wordWrap: true,\n maxFiles: 500,\n maxTotalLines: 100000,\n};\n\nexport function loadConfig(): AppConfig {\n let config = { ...defaults };\n\n // Load user-level config\n const userConfigPath = join(\n homedir(),\n '.config',\n 'self-review',\n 'config.yaml'\n );\n if (existsSync(userConfigPath)) {\n try {\n const userConfig = loadYamlConfig(userConfigPath);\n config = mergeConfig(config, userConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load user config from ${userConfigPath}: ${error}`\n );\n }\n }\n\n // Load project-level config\n const projectConfigPath = join(process.cwd(), '.self-review.yaml');\n if (existsSync(projectConfigPath)) {\n try {\n const projectConfig = loadYamlConfig(projectConfigPath);\n config = mergeConfig(config, projectConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load project config from ${projectConfigPath}: ${error}`\n );\n }\n }\n\n return config;\n}\n\nfunction loadYamlConfig(path: string): Partial<AppConfig> {\n const content = readFileSync(path, 'utf-8');\n const raw = parseYaml(content);\n\n // An empty file (or one containing only `null`) is a valid \"use defaults\" state.\n if (raw === null || raw === undefined) {\n return {};\n }\n\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error('Invalid YAML format');\n }\n\n // Map kebab-case keys to camelCase\n const config: Partial<AppConfig> = {};\n\n if ('theme' in raw) {\n if (['light', 'dark', 'system'].includes(raw.theme)) {\n config.theme = raw.theme;\n } else {\n console.error(\n `Warning: Invalid theme value \"${raw.theme}\", using default`\n );\n }\n }\n\n if ('diff-view' in raw) {\n if (['split', 'unified'].includes(raw['diff-view'])) {\n config.diffView = raw['diff-view'];\n } else {\n console.error(\n `Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`\n );\n }\n }\n\n if ('font-size' in raw && typeof raw['font-size'] === 'number') {\n config.fontSize = raw['font-size'];\n }\n\n if ('output-format' in raw && typeof raw['output-format'] === 'string') {\n config.outputFormat = raw['output-format'];\n }\n\n if ('ignore' in raw && Array.isArray(raw.ignore)) {\n config.ignore = raw.ignore.filter(\n (item: unknown) => typeof item === 'string'\n );\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n config.categories = raw.categories.filter(\n (cat: unknown): cat is { name: string; description: string; color: string } =>\n cat !== null &&\n typeof cat === 'object' &&\n typeof (cat as Record<string, unknown>).name === 'string' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n }\n\n if (\n 'default-diff-args' in raw &&\n typeof raw['default-diff-args'] === 'string'\n ) {\n config.defaultDiffArgs = raw['default-diff-args'];\n }\n\n if ('show-untracked' in raw && typeof raw['show-untracked'] === 'boolean') {\n config.showUntracked = raw['show-untracked'];\n config.showUntrackedExplicit = true;\n }\n\n if ('word-wrap' in raw && typeof raw['word-wrap'] === 'boolean') {\n config.wordWrap = raw['word-wrap'];\n }\n\n if ('max-files' in raw && typeof raw['max-files'] === 'number') {\n config.maxFiles = raw['max-files'] >= 0 ? raw['max-files'] : defaults.maxFiles;\n }\n\n if ('max-total-lines' in raw && typeof raw['max-total-lines'] === 'number') {\n config.maxTotalLines = raw['max-total-lines'] >= 0 ? raw['max-total-lines'] : defaults.maxTotalLines;\n }\n\n if (\n 'output-file' in raw &&\n typeof raw['output-file'] === 'string' &&\n raw['output-file'].length > 0\n ) {\n config.outputFile = raw['output-file'];\n }\n\n if (\n 'guide-file' in raw &&\n typeof raw['guide-file'] === 'string' &&\n raw['guide-file'].length > 0\n ) {\n config.guideFile = raw['guide-file'];\n }\n\n return config;\n}\n\nfunction mergeConfig(base: AppConfig, override: Partial<AppConfig>): AppConfig {\n return {\n ...base,\n ...override,\n // Arrays are replaced, not merged\n ignore: override.ignore !== undefined ? override.ignore : base.ignore,\n categories:\n override.categories !== undefined ? override.categories : base.categories,\n };\n}\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execAsync = promisify(exec);\n\n/**\n * Compute payload statistics and check against configured thresholds.\n * A maxFiles or maxTotalLines value of 0 disables that guard.\n */\nexport function computePayloadStats(\n fileCount: number,\n totalLines: number,\n config: AppConfig\n): PayloadStats {\n const maxFiles = config.maxFiles;\n const maxTotalLines = config.maxTotalLines;\n const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;\n const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;\n return {\n fileCount,\n totalLines,\n exceedsFiles,\n exceedsLines,\n exceedsAny: exceedsFiles || exceedsLines,\n };\n}\n\n/**\n * Count total diff lines across all files and hunks.\n */\nexport function countTotalLines(files: DiffFile[]): number {\n let total = 0;\n for (const file of files) {\n for (const hunk of file.hunks) {\n total += hunk.lines.length;\n }\n }\n return total;\n}\n\n/**\n * Get git diff stats cheaply using --numstat (avoids full diff parsing).\n * Each output line is \"added\\tremoved\\tfilename\".\n * Returns file count and total changed lines (added + removed).\n */\nexport async function getGitDiffStats(\n args: string[],\n repoRoot: string\n): Promise<{ fileCount: number; totalLines: number }> {\n try {\n const { stdout } = await execAsync(`git diff --numstat ${args.join(' ')}`, {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 15000,\n cwd: repoRoot,\n });\n\n let fileCount = 0;\n let totalLines = 0;\n\n for (const line of stdout.trim().split('\\n')) {\n if (!line) continue;\n const parts = line.split('\\t');\n if (parts.length < 3) continue;\n\n fileCount++;\n // Binary files show '-' for added/removed\n const added = parts[0] === '-' ? 0 : parseInt(parts[0], 10);\n const removed = parts[1] === '-' ? 0 : parseInt(parts[1], 10);\n totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);\n }\n\n return { fileCount, totalLines };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);\n } else {\n console.error('[payload-sizing] Failed to get git diff stats: unknown error');\n }\n // Return zeros so the guard does not block on failure\n return { fileCount: 0, totalLines: 0 };\n }\n}\n","// src/main/fs-utils.ts\n// Filesystem utility functions for the main process.\n\nimport { accessSync, constants as fsConstants } from 'fs';\nimport { dirname } from 'path';\n\n/**\n * Check if a file's parent directory is writable.\n * Returns true if the directory exists and the process has write permission,\n * false otherwise (including non-existent directories).\n */\nexport function checkWritability(filePath: string): boolean {\n try {\n const dir = dirname(filePath);\n accessSync(dir, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * File-type detection utilities.\n *\n * NOTE: This file is intentionally duplicated in packages/react/src/utils/file-type-utils.ts.\n * @self-review/core has Node-only dependencies, so @self-review/react cannot safely import\n * from this package. Both copies must be kept in sync.\n */\n\nconst RASTER_IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.ico', '.bmp']);\nconst MARKDOWN_EXTENSIONS = new Set(['.md', '.markdown']);\nconst HTML_EXTENSIONS = new Set(['.html', '.htm']);\n\nexport type RenderedTextMode = 'markdown' | 'html';\n\nfunction getExtension(filePath: string): string {\n const lastDot = filePath.lastIndexOf('.');\n if (lastDot === -1 || lastDot === filePath.length - 1) return '';\n return filePath.slice(lastDot).toLowerCase();\n}\n\nexport function isPreviewableImage(filePath: string): boolean {\n return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isPreviewableSvg(filePath: string): boolean {\n return getExtension(filePath) === '.svg';\n}\n\nexport function isMarkdownFile(filePath: string): boolean {\n return MARKDOWN_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isHtmlFile(filePath: string): boolean {\n return HTML_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function getRenderedTextMode(filePath: string): RenderedTextMode | null {\n if (isMarkdownFile(filePath)) return 'markdown';\n if (isHtmlFile(filePath)) return 'html';\n return null;\n}\n\nexport function isPreviewableRenderedText(filePath: string): boolean {\n return getRenderedTextMode(filePath) !== null;\n}\n\nexport function getLanguageFromPath(filePath: string): string {\n const ext = filePath.split('.').pop()?.toLowerCase() || '';\n const langMap: Record<string, string> = {\n ts: 'typescript',\n tsx: 'tsx',\n js: 'javascript',\n jsx: 'jsx',\n py: 'python',\n css: 'css',\n json: 'json',\n md: 'markdown',\n markdown: 'markdown',\n sh: 'bash',\n bash: 'bash',\n yml: 'yaml',\n yaml: 'yaml',\n java: 'java',\n go: 'go',\n rs: 'rust',\n sql: 'sql',\n html: 'markup',\n htm: 'markup',\n xml: 'markup',\n rb: 'ruby',\n php: 'php',\n twig: 'twig',\n c: 'c',\n cpp: 'cpp',\n h: 'c',\n hpp: 'cpp',\n // Config and data formats\n ini: 'ini',\n toml: 'toml',\n csv: 'csv',\n diff: 'diff',\n patch: 'diff',\n // Web and infrastructure\n scss: 'scss',\n sass: 'sass',\n graphql: 'graphql',\n gql: 'graphql',\n conf: 'nginx',\n // Database\n mongodb: 'mongodb',\n // Tooling\n makefile: 'makefile',\n mk: 'makefile',\n mak: 'makefile',\n vim: 'vim',\n vimrc: 'vim',\n };\n\n // Check for special filenames without extensions\n const filename = filePath.split('/').pop()?.toLowerCase() || '';\n if (filename === 'dockerfile' || filename.startsWith('dockerfile.')) {\n return 'docker';\n }\n if (filename === 'makefile' || filename.startsWith('makefile.')) {\n return 'makefile';\n }\n if (filename.startsWith('.git')) {\n return 'git';\n }\n if (filename === '.vimrc' || filename.startsWith('.vim')) {\n return 'vim';\n }\n\n return langMap[ext] || 'plaintext';\n}\n","// github-provider.ts\n// GitHub implementation of the ForgeProvider interface, backed entirely by\n// the `gh` CLI through an injectable command runner (never the network\n// directly). Read-only: only `gh pr view` and `gh api` GET calls.\n//\n// GitHub Enterprise-style hosts are honored by passing the URL's host (which\n// may include a port) verbatim to gh: as the HOST/OWNER/REPO form for\n// `pr view --repo` and as `--hostname` for `gh api`. gh's own host handling\n// takes it from there (auth per host, API base URL).\n\nimport {\n ForgeCliUnavailableError,\n type FetchThreadsOptions,\n type ForgeCommandResult,\n type ForgeCommandRunner,\n type ForgeProvider,\n type ForgeThread,\n type ForgeThreadAnchor,\n type ForgeUrl,\n} from './forge-provider';\n\n/** Relevant subset of a GitHub REST pull-request review comment. */\ninterface GitHubReviewComment {\n id: number;\n in_reply_to_id?: number | null;\n /** `null` for deleted user accounts. */\n user: { login: string } | null;\n body: string;\n path: string;\n side?: 'LEFT' | 'RIGHT' | null;\n line: number | null;\n start_line?: number | null;\n original_line?: number | null;\n original_start_line?: number | null;\n}\n\nconst GH_CLI = 'gh';\n\n/**\n * Run a gh command, translating both failure modes into the typed\n * unavailable error: a runner rejection means the CLI could not be spawned\n * (e.g. ENOENT when gh is absent), a non-zero exit means gh ran but failed\n * (unauthenticated, API error). Callers degrade on this error, never crash.\n */\nasync function runGh(\n runCommand: ForgeCommandRunner,\n args: string[]\n): Promise<string> {\n let result: ForgeCommandResult;\n try {\n result = await runCommand(GH_CLI, args);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `Failed to run the gh CLI: ${detail}`\n );\n }\n if (result.exitCode !== 0) {\n const detail = result.stderr.trim() || `exit code ${result.exitCode}`;\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `gh exited with code ${result.exitCode}: ${detail}`\n );\n }\n return result.stdout;\n}\n\n/**\n * Parse gh JSON output, surfacing malformed output as the typed unavailable\n * error so callers keep a single degradation path.\n */\nfunction parseGhJson(stdout: string, context: string): unknown {\n try {\n return JSON.parse(stdout);\n } catch {\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `gh returned unparseable JSON for ${context}`\n );\n }\n}\n\n/**\n * Normalize one review comment's anchor. GitHub reports `line: null` when\n * the comment no longer applies to the head diff (outdated); the\n * `original_*` fields then retain the historic anchor.\n */\nfunction toAnchor(comment: GitHubReviewComment): ForgeThreadAnchor {\n const outdated = comment.line === null || comment.line === undefined;\n const endLine = outdated ? (comment.original_line ?? null) : comment.line;\n const startLine = outdated\n ? (comment.original_start_line ?? comment.original_line ?? null)\n : (comment.start_line ?? comment.line);\n const hasLines = startLine !== null && endLine !== null;\n return {\n filePath: comment.path,\n // Side is meaningless without usable lines; the contract says 'new'.\n side: hasLines && comment.side === 'LEFT' ? 'old' : 'new',\n startLine: hasLines ? startLine : null,\n endLine: hasLines ? endLine : null,\n outdated,\n };\n}\n\n/** GitHub shows deleted user accounts as \"ghost\"; mirror that. */\nfunction toTurn(comment: GitHubReviewComment) {\n return {\n remoteId: String(comment.id),\n author: comment.user?.login ?? 'ghost',\n body: comment.body,\n };\n}\n\n/**\n * Group flat review comments into threads. A comment without\n * `in_reply_to_id` roots a thread; a reply attaches to the thread containing\n * the comment it replies to (root or any member). An orphan reply whose\n * parent is unknown degrades to a thread root of its own. Document order is\n * preserved throughout — nothing sorts.\n */\nfunction groupIntoThreads(comments: GitHubReviewComment[]): ForgeThread[] {\n const threads: ForgeThread[] = [];\n const threadByCommentId = new Map<number, ForgeThread>();\n for (const comment of comments) {\n const parentThread =\n comment.in_reply_to_id === null || comment.in_reply_to_id === undefined\n ? undefined\n : threadByCommentId.get(comment.in_reply_to_id);\n if (parentThread) {\n parentThread.replies.push(toTurn(comment));\n threadByCommentId.set(comment.id, parentThread);\n } else {\n const thread: ForgeThread = {\n root: toTurn(comment),\n replies: [],\n anchor: toAnchor(comment),\n };\n threads.push(thread);\n threadByCommentId.set(comment.id, thread);\n }\n }\n return threads;\n}\n\n/**\n * Create the GitHub {@link ForgeProvider} backed by an injected command\n * runner, mirroring how `git.ts` keeps child-process execution testable.\n */\nexport function createGitHubProvider(\n runCommand: ForgeCommandRunner\n): ForgeProvider {\n return {\n forge: 'github',\n\n async fetchBaseBranch(url: ForgeUrl): Promise<string> {\n const stdout = await runGh(runCommand, [\n 'pr',\n 'view',\n String(url.number),\n '--repo',\n `${url.host}/${url.owner}/${url.repo}`,\n '--json',\n 'baseRefName',\n ]);\n const parsed = parseGhJson(stdout, 'pr view') as {\n baseRefName?: unknown;\n };\n if (typeof parsed?.baseRefName !== 'string' || parsed.baseRefName === '') {\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n 'gh pr view returned no baseRefName'\n );\n }\n return parsed.baseRefName;\n },\n\n // The REST review-comment list carries no resolution state, so\n // `options.includeResolved` is deliberately ignored: GitHub fetch\n // returns all review threads (resolved-state filtering is a GitLab\n // concern).\n async fetchThreads(\n url: ForgeUrl,\n _options?: FetchThreadsOptions\n ): Promise<ForgeThread[]> {\n const stdout = await runGh(runCommand, [\n 'api',\n `repos/${url.owner}/${url.repo}/pulls/${url.number}/comments`,\n '--hostname',\n url.host,\n '--paginate',\n '--slurp',\n ]);\n // `--paginate --slurp` wraps each response page in an outer array:\n // [[...page1], [...page2]]. Flatten one level to the comment list.\n const pages = parseGhJson(stdout, 'pull request comments');\n if (!Array.isArray(pages)) {\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n 'gh api returned an unexpected payload shape for pull request comments'\n );\n }\n const comments = pages.flat(1) as GitHubReviewComment[];\n return groupIntoThreads(comments);\n },\n };\n}\n","// thread-mapper.ts\n// Deterministic mapper from forge-neutral discussion threads to the v3\n// ReviewComment model. Pure code: no I/O, no randomness, no timestamps —\n// the same input always yields byte-identical output, and it contains no\n// forge-conditional logic (anything forge-specific belongs in the\n// providers). Fetch direction only.\n\nimport type { ForgeThread, ForgeThreadAnchor, ForgeThreadTurn } from './forge-provider';\nimport type { LineRange, Reply, ReviewComment } from './types';\n\n/**\n * Sentinel `filePath` for review-level threads (threads with no file\n * association at all, e.g. GitLab non-diff discussions).\n *\n * The v3 schema has no review-level comment element — every `<comment>`\n * lives inside a `<file path>` — so the mapper degrades these threads to\n * file-level comments on this sentinel path, the closest legal shape.\n * The empty string can never collide with a repository-relative diff path,\n * so consumers (the fetch-comments orchestrator, the app's remote mode)\n * detect review-level comments by comparing against this constant and\n * decide their placement (e.g. a synthetic review-level file entry).\n */\nexport const REVIEW_LEVEL_FILE_PATH = '';\n\n/**\n * Map an anchor to the model's line range, honoring the exactly-one-pair\n * rule: the single `LineRange.side` selects which pair the serializer\n * emits (`'new'` → `new-line-*`, `'old'` → `old-line-*`), so a comment can\n * never carry both.\n *\n * Returns `null` (file-level) when the anchor is outdated, has no usable\n * line information, or carries non-positive lines (the XSD requires\n * `xs:positiveInteger`, and the serializer must never receive an\n * unserializable range). Reversed bounds are normalized rather than\n * rejected so a defective provider payload still maps deterministically.\n */\nfunction mapAnchorToLineRange(anchor: ForgeThreadAnchor): LineRange | null {\n if (anchor.outdated) {\n return null;\n }\n const { startLine, endLine } = anchor;\n if (startLine === null || endLine === null) {\n return null;\n }\n if (startLine < 1 || endLine < 1) {\n return null;\n }\n return {\n side: anchor.side,\n start: Math.min(startLine, endLine),\n end: Math.max(startLine, endLine),\n };\n}\n\n/**\n * Internal ids are in-memory render keys the app normally generates\n * randomly on parse. The mapper must be deterministic, so it derives them\n * from the forge-assigned ids instead.\n */\nfunction internalId(turn: ForgeThreadTurn): string {\n return `remote-${turn.remoteId}`;\n}\n\nfunction mapReply(turn: ForgeThreadTurn): Reply {\n return {\n id: internalId(turn),\n body: turn.body,\n author: turn.author,\n remoteId: turn.remoteId,\n };\n}\n\n/**\n * Convert normalized forge threads into v3 `ReviewComment` threads.\n *\n * - The root turn becomes the root comment and owns the anchor; subsequent\n * turns become flat replies in document order (nothing sorts them).\n * - Forge usernames land in `author`, forge thread/comment ids in\n * `remoteId`, markdown bodies pass through verbatim.\n * - Outdated or line-less anchors degrade to file-level comments\n * (`lineRange: null`); anchor-less threads degrade to file-level\n * comments on {@link REVIEW_LEVEL_FILE_PATH}. The degradation is\n * structural, never textual.\n * - Mapped comments carry no category, severity or confidence: forge\n * threads have none, and absent means below every threshold. The empty\n * `category` matches how the XML parser represents a missing category.\n *\n * Output order is input order. The input is never mutated.\n */\nexport function mapThreadsToReviewComments(\n threads: ForgeThread[]\n): ReviewComment[] {\n return threads.map((thread) => {\n const comment: ReviewComment = {\n id: internalId(thread.root),\n filePath: thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH,\n lineRange: thread.anchor ? mapAnchorToLineRange(thread.anchor) : null,\n body: thread.root.body,\n category: '',\n suggestion: null,\n author: thread.root.author,\n remoteId: thread.root.remoteId,\n };\n if (thread.replies.length > 0) {\n comment.replies = thread.replies.map(mapReply);\n }\n return comment;\n });\n}\n","// gitlab-provider.ts\n// ForgeProvider implementation for GitLab (gitlab.com and self-hosted) backed\n// by the read-only `glab` CLI. All child-process execution goes through an\n// injected ForgeCommandRunner so the provider stays unit-testable and no real\n// `glab` calls happen in tests. Only GET-style commands are issued (`glab\n// api`); nothing is ever posted.\n\nimport {\n ForgeCliUnavailableError,\n type FetchThreadsOptions,\n type ForgeAnchorSide,\n type ForgeCommandRunner,\n type ForgeProvider,\n type ForgeThread,\n type ForgeThreadAnchor,\n type ForgeThreadTurn,\n type ForgeUrl,\n} from './forge-provider';\n\nconst GLAB_CLI = 'glab';\n\n// --- Minimal shapes of the GitLab API payloads we consume ---------------\n\ninterface GitLabLineRangeEdge {\n old_line?: number | null;\n new_line?: number | null;\n}\n\ninterface GitLabPosition {\n old_path?: string | null;\n new_path?: string | null;\n old_line?: number | null;\n new_line?: number | null;\n line_range?: {\n start?: GitLabLineRangeEdge | null;\n end?: GitLabLineRangeEdge | null;\n } | null;\n}\n\ninterface GitLabNote {\n id: number | string;\n body?: string;\n author?: { username?: string } | null;\n system?: boolean;\n resolvable?: boolean;\n resolved?: boolean;\n position?: GitLabPosition | null;\n}\n\ninterface GitLabDiscussion {\n id: string;\n notes?: GitLabNote[];\n}\n\n// --- CLI plumbing -------------------------------------------------------\n\n/** URL-encode the full project path; subgroup slashes become %2F. */\nfunction encodeProjectPath(url: ForgeUrl): string {\n return encodeURIComponent(`${url.owner}/${url.repo}`);\n}\n\nfunction unavailable(message: string): ForgeCliUnavailableError {\n return new ForgeCliUnavailableError('gitlab', GLAB_CLI, message);\n}\n\n/**\n * Run `glab api <endpoint>` against the URL's host and return raw stdout.\n * Spawn failures (ENOENT) and non-zero exits (unauthenticated, API errors)\n * both surface as {@link ForgeCliUnavailableError}.\n */\nasync function runGlabApi(\n runCommand: ForgeCommandRunner,\n url: ForgeUrl,\n endpoint: string,\n extraArgs: string[] = []\n): Promise<string> {\n const args = ['api', endpoint, '--hostname', url.host, ...extraArgs];\n let result;\n try {\n result = await runCommand(GLAB_CLI, args);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw unavailable(`glab CLI could not be spawned: ${detail}`);\n }\n if (result.exitCode !== 0) {\n const detail = result.stderr.trim() || `exit code ${result.exitCode}`;\n throw unavailable(`glab api ${endpoint} failed: ${detail}`);\n }\n return result.stdout;\n}\n\n/**\n * Parse stdout that may contain several concatenated top-level JSON\n * documents, as `glab api --paginate` emits one array per page. A simple\n * bracket/string scanner keeps `][` sequences inside note bodies from\n * breaking the split.\n */\nfunction parseJsonDocuments(text: string): unknown[] {\n const documents: unknown[] = [];\n let depth = 0;\n let inString = false;\n let escaped = false;\n let start = -1;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === '\\\\') {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (ch === '\"') {\n inString = true;\n } else if (ch === '[' || ch === '{') {\n if (depth === 0) start = i;\n depth += 1;\n } else if (ch === ']' || ch === '}') {\n depth -= 1;\n if (depth === 0 && start >= 0) {\n documents.push(JSON.parse(text.slice(start, i + 1)));\n start = -1;\n }\n }\n }\n if (depth !== 0 || inString) {\n throw new Error('truncated JSON document');\n }\n return documents;\n}\n\n// --- Normalization ------------------------------------------------------\n\nfunction toTurn(note: GitLabNote): ForgeThreadTurn {\n return {\n remoteId: String(note.id),\n author: note.author?.username ?? 'unknown',\n body: note.body ?? '',\n };\n}\n\n/**\n * A discussion counts as resolved when it has at least one resolvable note\n * and every resolvable note is resolved. Discussions with no resolvable\n * notes (non-diff discussions) are never \"resolved\".\n */\nfunction isDiscussionResolved(notes: GitLabNote[]): boolean {\n const resolvable = notes.filter((note) => note.resolvable === true);\n return resolvable.length > 0 && resolvable.every((note) => note.resolved === true);\n}\n\n/**\n * Build the neutral anchor from a GitLab position object, or `null` when the\n * note has no position (non-diff discussion) or the position carries no\n * usable file path.\n *\n * Side selection: `new_line` present → `'new'` (using `new_path`), otherwise\n * `old_line` present → `'old'` (using `old_path`). A position with a path\n * but neither line (e.g. `position_type: \"file\"`) becomes a file-level\n * anchor with null lines and side `'new'`, per the neutral shape's contract.\n * Multi-line `line_range` edges are read on the side chosen above, falling\n * back to the single-line position when an edge lacks that side's line.\n *\n * GitLab has no per-note outdated flag (positions on older heads stay valid\n * positions), so `outdated` is always `false`; drift detection downstream\n * informs the reviewer instead.\n */\nfunction toAnchor(position: GitLabPosition | null | undefined): ForgeThreadAnchor | null {\n if (!position) return null;\n\n const side: ForgeAnchorSide =\n typeof position.old_line === 'number' && typeof position.new_line !== 'number'\n ? 'old'\n : 'new';\n const pathForSide = side === 'old' ? position.old_path : position.new_path;\n const filePath = pathForSide ?? position.new_path ?? position.old_path;\n if (!filePath) return null;\n\n const lineOf = (edge: GitLabLineRangeEdge | null | undefined): number | null => {\n const value = side === 'old' ? edge?.old_line : edge?.new_line;\n return typeof value === 'number' ? value : null;\n };\n\n const positionLine = lineOf(position);\n const startLine = lineOf(position.line_range?.start) ?? positionLine;\n const endLine = lineOf(position.line_range?.end) ?? positionLine;\n\n return { filePath, side, startLine, endLine, outdated: false };\n}\n\n/**\n * Normalize one GitLab discussion into the forge-neutral thread shape, or\n * `null` when nothing user-authored remains after dropping system notes.\n * The first surviving note roots the thread and owns the anchor; the rest\n * are ordered replies (GitLab document order is preserved verbatim).\n */\nfunction toThread(discussion: GitLabDiscussion): ForgeThread | null {\n const notes = (discussion.notes ?? []).filter((note) => note.system !== true);\n if (notes.length === 0) return null;\n const [rootNote, ...replyNotes] = notes;\n return {\n root: toTurn(rootNote),\n replies: replyNotes.map(toTurn),\n anchor: toAnchor(rootNote.position),\n };\n}\n\n// --- Provider -----------------------------------------------------------\n\n/**\n * Create the GitLab {@link ForgeProvider} backed by the `glab` CLI.\n *\n * The URL's host is forwarded via `--hostname`, so self-hosted instances\n * (e.g. git.drupalcode.org) work with zero configuration beyond `glab auth`.\n * Resolved discussions are excluded unless `includeResolved` is set.\n */\nexport function createGitLabProvider(runCommand: ForgeCommandRunner): ForgeProvider {\n return {\n forge: 'gitlab',\n\n async fetchBaseBranch(url: ForgeUrl): Promise<string> {\n const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}`;\n const stdout = await runGlabApi(runCommand, url, endpoint);\n let mr: unknown;\n try {\n mr = JSON.parse(stdout);\n } catch {\n throw unavailable(`glab api ${endpoint} returned unparseable JSON`);\n }\n const targetBranch = (mr as { target_branch?: unknown })?.target_branch;\n if (typeof targetBranch !== 'string' || targetBranch.length === 0) {\n throw unavailable(`glab api ${endpoint} returned no target_branch`);\n }\n return targetBranch;\n },\n\n async fetchThreads(url: ForgeUrl, options?: FetchThreadsOptions): Promise<ForgeThread[]> {\n const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}/discussions`;\n const stdout = await runGlabApi(runCommand, url, endpoint, ['--paginate']);\n\n let discussions: GitLabDiscussion[];\n try {\n const pages = parseJsonDocuments(stdout);\n if (pages.length === 0 && stdout.trim() !== '') {\n throw new Error('no JSON documents in output');\n }\n discussions = pages.flatMap((page) =>\n Array.isArray(page) ? (page as GitLabDiscussion[]) : []\n );\n } catch {\n throw unavailable(`glab api ${endpoint} returned unparseable JSON`);\n }\n\n const includeResolved = options?.includeResolved === true;\n const threads: ForgeThread[] = [];\n for (const discussion of discussions) {\n const notes = discussion.notes ?? [];\n if (!includeResolved && isDiscussionResolved(notes)) continue;\n const thread = toThread(discussion);\n if (thread) threads.push(thread);\n }\n return threads;\n },\n };\n}\n","// materializer.ts\n// Clone-aware diff materializer: turns a parsed forge URL into a local git\n// context. Reuses an existing matching clone (fetch only, no working-tree\n// changes) or creates a disposable blobless clone under the OS temp root,\n// then reports the resolved base/head SHAs so downstream code can run the\n// existing local git-mode pipeline over `baseSha...headSha`.\n//\n// All git interaction goes through an injectable command runner (the same\n// shape providers use) so unit tests never spawn real git. This module never\n// talks to a forge API: head refs come from the forges' well-known git refs\n// (`refs/pull/N/head`, `refs/merge-requests/N/head`) over plain git.\n\nimport { execFile } from 'child_process';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport type {\n ForgeCommandResult,\n ForgeCommandRunner,\n ForgeUrl,\n} from './forge-provider';\n\n/** How the local git context was obtained. */\nexport type MaterializeMode = 'existing-clone' | 'temp-clone';\n\n/** Result of materializing a forge URL into a local git context. */\nexport interface MaterializeResult {\n /** Root of the git repository to run the diff pipeline in. */\n repoPath: string;\n /** Resolved SHA of the PR/MR base branch tip. */\n baseSha: string;\n /** Resolved SHA of the PR/MR head (the live remote head). */\n headSha: string;\n mode: MaterializeMode;\n /**\n * Removes the temp clone directory when one was created this run; a no-op\n * for the existing-clone mode. Safe to call more than once. Only ever\n * deletes a directory this materializer created.\n */\n cleanup: () => void;\n}\n\n/** A local clone whose fetch remote matches the requested forge repository. */\nexport interface ExistingClone {\n repoPath: string;\n remoteName: string;\n}\n\n/** Local namespaced refs the materializer fetches into (never branches). */\nconst LOCAL_BASE_REF = 'refs/self-review/base';\nconst LOCAL_HEAD_REF = 'refs/self-review/head';\n\nconst AUTH_HINT =\n 'Hint: if this repository is private or requires authentication, run ' +\n '`gh auth setup-git` (GitHub) or `glab auth git-credential` (GitLab) to ' +\n 'wire your CLI credentials into git.';\n\n/**\n * Default runner: spawns real git. Resolves with the exit code on any\n * completed run (including non-zero); rejects only when git cannot be\n * spawned at all (e.g. ENOENT).\n */\nexport const defaultGitRunner: ForgeCommandRunner = (command, args) =>\n new Promise<ForgeCommandResult>((resolve, reject) => {\n execFile(\n command,\n args,\n { maxBuffer: 50 * 1024 * 1024 },\n (error, stdout, stderr) => {\n const spawnCode = (error as NodeJS.ErrnoException | null)?.code;\n if (error && typeof spawnCode === 'string') {\n reject(error);\n return;\n }\n resolve({\n stdout: stdout ?? '',\n stderr: stderr ?? '',\n exitCode: error ? (typeof spawnCode === 'number' ? spawnCode : 1) : 0,\n });\n }\n );\n });\n\n/** Well-known git ref for the PR/MR head on each forge. */\nfunction headRefFor(url: ForgeUrl): string {\n return url.forge === 'github'\n ? `refs/pull/${url.number}/head`\n : `refs/merge-requests/${url.number}/head`;\n}\n\n/**\n * HTTPS clone URL for the forge repository. Git's credential machinery\n * (helpers, `gh auth setup-git`) handles auth; no transport selection here.\n */\nfunction cloneUrlFor(url: ForgeUrl): string {\n return `https://${url.host}/${url.owner}/${url.repo}.git`;\n}\n\nfunction gitFailure(\n what: string,\n result: ForgeCommandResult,\n withAuthHint: boolean\n): Error {\n const stderr = result.stderr.trim();\n const lines = [\n `git ${what} failed (exit code ${result.exitCode})${stderr ? `:\\n${stderr}` : ''}`,\n ];\n if (withAuthHint) {\n lines.push('', AUTH_HINT);\n }\n return new Error(lines.join('\\n'));\n}\n\n/** Strip a trailing `.git` and trailing slashes from a repo path. */\nfunction stripRepoPath(repoPath: string): string {\n return repoPath.replace(/\\/+$/, '').replace(/\\.git$/i, '');\n}\n\n/**\n * Normalize a git remote URL (SSH scp-style, ssh://, http(s)://) into a\n * comparable `{ host, path }` pair, or `null` when unrecognized.\n */\nfunction normalizeRemoteUrl(\n raw: string\n): { host: string; path: string } | null {\n const trimmed = raw.trim();\n if (trimmed.includes('://')) {\n try {\n const parsed = new URL(trimmed);\n return {\n host: parsed.host.toLowerCase(),\n path: stripRepoPath(parsed.pathname.replace(/^\\/+/, '')).toLowerCase(),\n };\n } catch {\n return null;\n }\n }\n // scp-style: [user@]host:path\n const scp = /^(?:[^@\\s]+@)?([^:/\\s]+):(.+)$/.exec(trimmed);\n if (scp) {\n return {\n host: scp[1].toLowerCase(),\n path: stripRepoPath(scp[2].replace(/^\\/+/, '')).toLowerCase(),\n };\n }\n return null;\n}\n\n/**\n * Parse `git remote -v` output and return the name of the first remote whose\n * fetch URL matches the forge URL's host and owner/repo, or `null`.\n */\nfunction findMatchingRemote(remoteVOutput: string, url: ForgeUrl): string | null {\n const wantedHost = url.host.toLowerCase();\n const wantedPath = `${url.owner}/${url.repo}`.toLowerCase();\n for (const line of remoteVOutput.split('\\n')) {\n const match = /^(\\S+)\\t(.+?)\\s+\\(fetch\\)$/.exec(line.trim());\n if (!match) continue;\n const normalized = normalizeRemoteUrl(match[2]);\n if (normalized && normalized.host === wantedHost && normalized.path === wantedPath) {\n return match[1];\n }\n }\n return null;\n}\n\nasync function revParse(\n runner: ForgeCommandRunner,\n repoPath: string,\n ref: string\n): Promise<string> {\n const result = await runner('git', ['-C', repoPath, 'rev-parse', ref]);\n if (result.exitCode !== 0) {\n throw gitFailure(`rev-parse ${ref}`, result, false);\n }\n return result.stdout.trim();\n}\n\n/**\n * Detect an existing clone: when `cwd` is inside a git repository with a\n * remote matching the forge URL, return `{ repoPath, remoteName }`.\n */\nexport async function detectExistingClone(\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner = defaultGitRunner\n): Promise<ExistingClone | null> {\n const toplevel = await runner('git', ['-C', cwd, 'rev-parse', '--show-toplevel']);\n if (toplevel.exitCode !== 0) {\n return null;\n }\n const repoPath = toplevel.stdout.trim();\n const remotes = await runner('git', ['-C', repoPath, 'remote', '-v']);\n if (remotes.exitCode !== 0) {\n return null;\n }\n const remoteName = findMatchingRemote(remotes.stdout, url);\n return remoteName === null ? null : { repoPath, remoteName };\n}\n\nasync function materializeIntoExistingClone(\n runner: ForgeCommandRunner,\n url: ForgeUrl,\n baseBranch: string,\n repoPath: string,\n remoteName: string\n): Promise<MaterializeResult> {\n console.error(\n `self-review: reusing existing clone at ${repoPath} (remote \"${remoteName}\")`\n );\n // Fetch into namespaced local refs only: no checkout, no branch creation,\n // no working-tree change. Forced refspecs are fine — these refs are ours.\n const fetch = await runner('git', [\n '-C',\n repoPath,\n 'fetch',\n remoteName,\n `+refs/heads/${baseBranch}:${LOCAL_BASE_REF}`,\n `+${headRefFor(url)}:${LOCAL_HEAD_REF}`,\n ]);\n if (fetch.exitCode !== 0) {\n throw gitFailure(`fetch from remote \"${remoteName}\"`, fetch, true);\n }\n return {\n repoPath,\n baseSha: await revParse(runner, repoPath, LOCAL_BASE_REF),\n headSha: await revParse(runner, repoPath, LOCAL_HEAD_REF),\n mode: 'existing-clone',\n cleanup: () => {},\n };\n}\n\nasync function materializeIntoTempClone(\n runner: ForgeCommandRunner,\n url: ForgeUrl,\n baseBranch: string\n): Promise<MaterializeResult> {\n // This run creates the directory, so cleanup may only ever remove it.\n const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'self-review-'));\n let removed = false;\n const cleanup = () => {\n if (removed) return;\n removed = true;\n fs.rmSync(tempDir, { recursive: true, force: true });\n };\n\n try {\n console.error(\n `self-review: created temporary blobless clone at ${tempDir}`\n );\n const cloneUrl = cloneUrlFor(url);\n // Blobless, never shallow: --depth would break merge-base computation.\n const clone = await runner('git', [\n 'clone',\n '--filter=blob:none',\n cloneUrl,\n tempDir,\n ]);\n if (clone.exitCode !== 0) {\n throw gitFailure(`clone of ${cloneUrl}`, clone, true);\n }\n const fetch = await runner('git', [\n '-C',\n tempDir,\n 'fetch',\n 'origin',\n `+${headRefFor(url)}:${LOCAL_HEAD_REF}`,\n ]);\n if (fetch.exitCode !== 0) {\n throw gitFailure(`fetch of ${headRefFor(url)}`, fetch, true);\n }\n return {\n repoPath: tempDir,\n baseSha: await revParse(runner, tempDir, `origin/${baseBranch}`),\n headSha: await revParse(runner, tempDir, LOCAL_HEAD_REF),\n mode: 'temp-clone',\n cleanup,\n };\n } catch (error) {\n cleanup();\n throw error;\n }\n}\n\n/**\n * Materialize a forge PR/MR into a local git context.\n *\n * When `cwd` is inside a git repository with a remote matching the forge\n * URL (SSH and HTTPS forms recognized, `.git` suffix tolerated), the base\n * branch and PR/MR head refs are fetched into that clone under\n * `refs/self-review/*` — read-only for the working tree. Otherwise a\n * blobless clone is created in a unique directory under the OS temp root\n * and `cleanup()` removes exactly that directory. Callers that already\n * detected a clone may pass it to avoid repeating the git probes.\n *\n * The returned `headSha` is the live remote head, so callers can compare it\n * against a recorded `remote-head-sha` for drift detection.\n */\nexport async function materialize(\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner = defaultGitRunner,\n existingClone?: ExistingClone | null\n): Promise<MaterializeResult> {\n const existing =\n existingClone === undefined\n ? await detectExistingClone(url, cwd, runner)\n : existingClone;\n if (existing) {\n return materializeIntoExistingClone(\n runner,\n url,\n baseBranch,\n existing.repoPath,\n existing.remoteName\n );\n }\n return materializeIntoTempClone(runner, url, baseBranch);\n}\n\n/**\n * Git-only fallback for the base branch when no forge CLI is available:\n * resolves the remote's default branch from its HEAD symref via\n * `git ls-remote --symref <remote> HEAD`. When an existing matching clone\n * is supplied, the configured remote is used so its SSH/HTTPS transport\n * and credentials are preserved. Otherwise the forge HTTPS URL is used.\n * No forge API involved.\n */\nexport async function resolveRemoteDefaultBranch(\n url: ForgeUrl,\n runner: ForgeCommandRunner = defaultGitRunner,\n existing: ExistingClone | null = null\n): Promise<string> {\n const cloneUrl = cloneUrlFor(url);\n const remote = existing?.remoteName ?? cloneUrl;\n // Errors must identify the repository; a bare alias such as \"origin\"\n // does not say which repository the lookup was made against.\n const label = existing ? `${remote} (${cloneUrl})` : cloneUrl;\n const args = existing\n ? ['-C', existing.repoPath, 'ls-remote', '--symref', remote, 'HEAD']\n : ['ls-remote', '--symref', remote, 'HEAD'];\n const result = await runner('git', args);\n if (result.exitCode !== 0) {\n throw gitFailure(`ls-remote of ${label}`, result, true);\n }\n const match = /^ref:\\s+refs\\/heads\\/(\\S+)\\s+HEAD$/m.exec(result.stdout);\n if (!match) {\n throw new Error(\n `Failed to resolve the default branch of ${label}: ` +\n 'git ls-remote returned no HEAD symref.'\n );\n }\n return match[1];\n}\n"],"mappings":";AAKO,SAAS,UAAU,SAA6B;AACrD,MAAI,CAAC,QAAQ,KAAK,GAAG;AACnB,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,QAAQ,QAAQ,MAAM,IAAI;AAChC,QAAM,QAAoB,CAAC;AAC3B,MAAI,cAAwC;AAC5C,MAAI,cAAwC;AAC5C,MAAI,gBAAgB;AACpB,MAAI,gBAAgB;AAEpB,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,UAAM,OAAO,MAAM,CAAC;AAGpB,QAAI,KAAK,WAAW,aAAa,GAAG;AAElC,UAAI,eAAe,YAAY,UAAU,aAAa;AACpD,oBAAY,MAAO,KAAK,WAAuB;AAC/C,sBAAc;AAAA,MAChB;AAGA,UACE,eACA,YAAY,YAAY,UACxB,YAAY,YAAY,QACxB;AAEA,YACE,YAAY,YACX,YAAY,SAAS,YAAY,MAAM,SAAS,KACjD,YAAY,eAAe,SAC3B;AACA,gBAA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M;AACtE,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR,2CAA2C,KAAK;AAAA,IAElD;AAAA,EACF;AACA,SAAO,MAAM,CAAC;AAChB;","names":["path","XMLParser","validateXML","validateXML","XMLParser","path","readFileSync","join","dirname","join","dirname","readFileSync","existsSync","join","path","exec","promisify","execAsync","dirname","toTurn","toAnchor","execFile","fs","path"]}
|