@self-review/core 1.45.0 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-4YO2MI6B.js +269 -0
- package/dist/chunk-4YO2MI6B.js.map +1 -0
- package/dist/chunk-QHS36X6T.js +450 -0
- package/dist/chunk-QHS36X6T.js.map +1 -0
- package/dist/diff-parser-B6S3KG5T.js +9 -0
- package/dist/git-N5HVNPKQ.js +24 -0
- package/dist/index.cjs +3489 -1111
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +948 -142
- package/dist/index.d.ts +948 -142
- package/dist/index.js +3019 -989
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-A7A5ZFT3.js +0 -233
- package/dist/chunk-A7A5ZFT3.js.map +0 -1
- package/dist/chunk-OQRS7NDT.js +0 -200
- package/dist/chunk-OQRS7NDT.js.map +0 -1
- package/dist/diff-parser-2JM4CZR3.js +0 -7
- package/dist/git-E7WZPKRC.js +0 -23
- /package/dist/{diff-parser-2JM4CZR3.js.map → diff-parser-B6S3KG5T.js.map} +0 -0
- /package/dist/{git-E7WZPKRC.js.map → git-N5HVNPKQ.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/xml-serializer.ts","../src/xml-parser.ts","../src/guide-schema.ts","../src/guide-parser.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/apply-suggestion.ts","../src/file-type-utils.ts","../src/github-provider.ts","../src/thread-mapper.ts","../src/gitlab-provider.ts","../src/materializer.ts","../src/review-handlers.ts","../src/git-diff-args.ts","../src/startup-mode.ts","../src/guide-loader.ts","../src/git-diff-loader.ts","../src/staged-untracked.ts","../src/remote-mode.ts","../src/fetch-comments.ts"],"sourcesContent":["// 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 // Same reasoning as `assetNameComponent`: anything not in the map falls\n // back to png, including a value that is not a string at all.\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 */\n/**\n * Reduce an id to something that can only ever name a file *inside* the asset\n * directory.\n *\n * A comment id is not trusted input. The desktop gets its ReviewState from its\n * own renderer, but the serve front end accepts a whole document over HTTP, so\n * `../../x` in an id would walk this function's write out of the asset\n * directory and onto an arbitrary path. Every id this app generates is a UUID,\n * so restricting the prefix to the URL-safe alphabet renames nothing in\n * practice and leaves existing asset names byte-identical.\n */\nfunction assetNameComponent(idPrefix: string): string {\n // Coerced rather than assumed: this runs before the document is validated\n // against anything, so a caller that omits an id reaches here with\n // `undefined`, and a bare `.replace` would turn that into a crash *after*\n // the review has already been taken off the session — losing it. The\n // serializer's job here is to name a file, not to police the document.\n return String(idPrefix ?? '').replace(/[^A-Za-z0-9_-]/g, '_');\n}\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 = `${assetNameComponent(idPrefix)}-${index}.${ext}`;\n const relativePath = `.self-review-assets/${fileName}`;\n const target = path.join(assetDir, fileName);\n\n // `assetNameComponent` already makes this unreachable. It stays because\n // this write happens *before* the document is validated against the XSD\n // (see `serializeReview`), so a file lands on disk even when serialization\n // goes on to fail — which makes an escape here permanent, and worth a\n // second, independent check rather than one clever regex.\n if (path.dirname(path.resolve(target)) !== path.resolve(assetDir)) {\n throw new Error(`Refusing to write an attachment outside ${assetDir}: ${fileName}`);\n }\n\n if (!fs.existsSync(assetDir)) {\n fs.mkdirSync(assetDir, { recursive: true });\n }\n fs.writeFileSync(target, 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(\n `[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`\n );\n } else {\n console.error(\n '[main] XML validation infrastructure failed - emitting XML without validation'\n );\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>(raw: unknown, allowed: readonly T[]): 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 && comment['@_old-line-end'] !== undefined;\n const hasNew =\n comment['@_new-line-start'] !== undefined && 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 = { ok: true; guide: ReviewGuide } | { 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: [{ fileName: 'self-review-guide-v1.xsd', contents: GUIDE_XSD_SCHEMA }],\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(guide: ReviewGuide, diffFilePaths: string[]): 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","// 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 = (command: string, args: string[]) => 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(url: ForgeUrl, options?: FetchThreadsOptions): 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(`Error: \"${directoryPath}\" is not a directory`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing directory \"${directoryPath}\": ${error.message}`);\n } else {\n console.error(`Error accessing directory \"${directoryPath}\": unknown error`);\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(`Error reading directory \"${directoryPath}\": ${error.message}`);\n } else {\n console.error(`Error reading directory \"${directoryPath}\": unknown error`);\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(patterns: string[]): (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(homedir(), '.config', 'self-review', 'config.yaml');\n if (existsSync(userConfigPath)) {\n try {\n const userConfig = loadYamlConfig(userConfigPath);\n config = mergeConfig(config, userConfig);\n } catch (error) {\n console.error(`Warning: Failed to load user config from ${userConfigPath}: ${error}`);\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(`Warning: Failed to load project config from ${projectConfigPath}: ${error}`);\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(`Warning: Invalid theme value \"${raw.theme}\", using default`);\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(`Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`);\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((item: unknown) => typeof item === 'string');\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n const usableCategories = 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 (cat as Record<string, unknown>).name !== '' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n\n // A `categories` list that leaves no usable entry (empty list, every entry\n // shaped wrong, or every entry named '') would silently disable commenting,\n // so it's treated the same as any other invalid value: warn and keep the default.\n if (usableCategories.length > 0) {\n config.categories = usableCategories;\n } else {\n console.error(\n 'Warning: Category configuration has no usable categories, using default categories'\n );\n }\n }\n\n if ('default-diff-args' in raw && typeof raw['default-diff-args'] === 'string') {\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 =\n 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: 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 { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execFileAsync = promisify(execFile);\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 execFileAsync('git', ['diff', '--numstat', ...args], {\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","// apply-suggestion.ts\n// Writes one anchored suggestion into one working file, or refuses and\n// writes nothing. Node-only, Electron-free, and free of process-global\n// state: the caller names the destination root, so nothing here ever\n// consults `process.cwd()`.\n//\n// The engine is deliberately narrow. It performs a byte-for-byte context\n// check and a literal line replacement — no fuzzy matching, no force flag,\n// no staging, no git. Every outcome is reported: a refusal names its reason\n// and leaves the file untouched (PRD Section 5.4.8).\n\nimport { readFileSync, writeFileSync } from 'fs';\nimport { isAbsolute, relative, resolve, sep } from 'path';\nimport type { LineRange, Suggestion } from './types';\n\n/**\n * Why an apply was refused. Every value is a structural fact about the\n * request or the file — never a fragment of the file's contents, so a\n * refusal is safe to surface in the UI and in logs.\n */\nexport type ApplyRefusalReason =\n /** The suggestion is file-level: there is nothing to replace. */\n | 'no-anchor'\n /**\n * The anchor names deleted lines (`side: 'old'`). Those lines are not in\n * the working file, and the app holds no old→new line mapping, so the\n * target is undefined rather than merely missing.\n */\n | 'old-side-anchor'\n /** `destinationRoot` is relative; resolving it would consult the cwd. */\n | 'destination-not-absolute'\n /** `filePath` resolves outside `destinationRoot`. */\n | 'path-escapes-destination'\n /** No file at the resolved path. */\n | 'file-missing'\n /** The path exists but could not be read (permissions, a directory, …). */\n | 'file-unreadable'\n /**\n * The file is not valid UTF-8. Rewriting it would round-trip its bytes\n * through a lossy decode and corrupt regions outside the anchor.\n */\n | 'file-not-utf8'\n /** The anchor falls outside the file's line count. */\n | 'anchor-out-of-range'\n /** The anchored lines no longer match `suggestion.originalCode`. */\n | 'context-mismatch'\n /** The context matched but the write itself failed. */\n | 'write-failed';\n\nexport interface ApplySuggestionRequest {\n /**\n * Absolute path of the directory the reviewed files live in. Always\n * supplied by the caller: a git-mode working tree, a directory-mode root,\n * a reused clone, or the destination the user picked for a temporary-clone\n * review. Never derived here.\n */\n destinationRoot: string;\n /** Path of the file to modify, relative to `destinationRoot`. */\n filePath: string;\n /** The comment's anchor. `null` (file-level) is refused. */\n lineRange: LineRange | null;\n suggestion: Suggestion;\n}\n\nexport interface ApplySuggestionApplied {\n status: 'applied';\n /** Echoed from the request, so a batch caller can attribute the result. */\n filePath: string;\n absolutePath: string;\n /** How many on-disk lines the proposal replaced. */\n replacedLines: number;\n}\n\nexport interface ApplySuggestionRefused {\n status: 'refused';\n filePath: string;\n reason: ApplyRefusalReason;\n /** One sentence naming the refusal, safe to show to the reviewer. */\n detail: string;\n}\n\nexport type ApplySuggestionResult = ApplySuggestionApplied | ApplySuggestionRefused;\n\nfunction refuse(\n filePath: string,\n reason: ApplyRefusalReason,\n detail: string\n): ApplySuggestionRefused {\n return { status: 'refused', filePath, reason, detail };\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return (error as NodeJS.ErrnoException | undefined)?.code;\n}\n\n/**\n * Split file text into lines, keeping each line's own bytes intact.\n *\n * The split is on `\\n` only, so a CRLF file's `\\r` stays at the end of the\n * line it terminates. That makes the comparison against `originalCode`\n * byte-exact (the diff parser hands the same `\\r` through in `DiffLine`),\n * and it means rejoining preserves mixed line endings exactly as found.\n */\nfunction splitLines(content: string): string[] {\n if (content === '') return [];\n const lines = content.split('\\n');\n // A trailing terminator produces an empty final element that is not a line.\n if (lines[lines.length - 1] === '') lines.pop();\n return lines;\n}\n\n/**\n * True when every line being replaced carries a CRLF terminator. Only then\n * is it unambiguous that a hand-typed LF proposal should be written back as\n * CRLF; a mixed or LF region takes the proposal verbatim.\n */\nfunction isCrlfRegion(anchored: string[]): boolean {\n return anchored.length > 0 && anchored.every(line => line.endsWith('\\r'));\n}\n\n/**\n * Apply one anchored suggestion to one file under `destinationRoot`.\n *\n * On a byte-for-byte match between the anchored lines and\n * `suggestion.originalCode`, the anchored lines are replaced with\n * `suggestion.proposedCode` and the file is rewritten. Lines outside the\n * anchor keep their exact bytes, including their line terminators, and the\n * file's trailing-newline state is preserved either way. Any other outcome\n * refuses with a reason and writes nothing.\n */\nexport function applySuggestion(request: ApplySuggestionRequest): ApplySuggestionResult {\n const { destinationRoot, filePath, lineRange, suggestion } = request;\n\n if (!lineRange) {\n return refuse(\n filePath,\n 'no-anchor',\n 'This suggestion is file-level, so there are no lines to replace.'\n );\n }\n if (lineRange.side === 'old') {\n return refuse(\n filePath,\n 'old-side-anchor',\n 'This suggestion is anchored to deleted lines, which are not in the working file.'\n );\n }\n if (!isAbsolute(destinationRoot)) {\n return refuse(\n filePath,\n 'destination-not-absolute',\n 'The destination directory must be an absolute path.'\n );\n }\n\n const root = resolve(destinationRoot);\n const absolutePath = resolve(root, filePath);\n const rel = relative(root, absolutePath);\n if (isAbsolute(filePath) || rel === '' || rel === '..' || rel.startsWith(`..${sep}`)) {\n return refuse(\n filePath,\n 'path-escapes-destination',\n 'The file path resolves outside the destination directory.'\n );\n }\n\n let buffer: Buffer;\n try {\n buffer = readFileSync(absolutePath);\n } catch (error) {\n const code = errorCode(error);\n if (code === 'ENOENT' || code === 'ENOTDIR') {\n return refuse(filePath, 'file-missing', 'The file is not in the destination directory.');\n }\n return refuse(\n filePath,\n 'file-unreadable',\n `The file could not be read (${code ?? 'unknown'}).`\n );\n }\n\n const content = buffer.toString('utf8');\n if (!Buffer.from(content, 'utf8').equals(buffer)) {\n return refuse(filePath, 'file-not-utf8', 'The file is not valid UTF-8 text.');\n }\n\n const lines = splitLines(content);\n const { start, end } = lineRange;\n if (start < 1 || end < start || end > lines.length) {\n return refuse(\n filePath,\n 'anchor-out-of-range',\n `Lines ${start}-${end} are outside this file, which has ${lines.length} line(s).`\n );\n }\n\n const anchored = lines.slice(start - 1, end);\n if (anchored.join('\\n') !== suggestion.originalCode) {\n return refuse(\n filePath,\n 'context-mismatch',\n `Lines ${start}-${end} no longer match the code this suggestion was written against.`\n );\n }\n\n const proposed = suggestion.proposedCode.split('\\n');\n const replacement = isCrlfRegion(anchored)\n ? proposed.map(line => (line.endsWith('\\r') ? line : `${line}\\r`))\n : proposed;\n const updated = [...lines.slice(0, start - 1), ...replacement, ...lines.slice(end)];\n const output = updated.join('\\n') + (content.endsWith('\\n') ? '\\n' : '');\n\n try {\n writeFileSync(absolutePath, output, 'utf8');\n } catch (error) {\n return refuse(\n filePath,\n 'write-failed',\n `The file could not be written (${errorCode(error) ?? 'unknown'}).`\n );\n }\n\n return { status: 'applied', filePath, absolutePath, replacedLines: anchored.length };\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(runCommand: ForgeCommandRunner, args: string[]): 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('github', GH_CLI, `Failed to run the gh CLI: ${detail}`);\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(runCommand: ForgeCommandRunner): 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('github', GH_CLI, 'gh pr view returned no baseRefName');\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(url: ForgeUrl, _options?: FetchThreadsOptions): 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 { DiffFile, LineRange, Reply, ReviewComment, Suggestion } 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\n/**\n * Opening line of a fenced code block: up to three spaces of indent, then\n * three or more backticks or tildes, then the info string. A fence indented\n * four spaces or more is an indented code block, not a fence.\n */\nconst FENCE_OPEN = /^( {0,3})(`{3,}|~{3,})(.*)$/;\n\n/** Drop a single trailing CR so a CRLF body yields LF-terminated lines. */\nfunction stripCr(line: string): string {\n return line.endsWith('\\r') ? line.slice(0, -1) : line;\n}\n\n/** Remove up to `width` leading spaces, the way CommonMark unindents a fence. */\nfunction stripIndent(line: string, width: number): string {\n let i = 0;\n while (i < width && line[i] === ' ') i++;\n return line.slice(i);\n}\n\n/** A closing fence: the same character, at least as long, nothing after it. */\nfunction isClosingFence(line: string, marker: string): boolean {\n const match = FENCE_OPEN.exec(line);\n return (\n match !== null &&\n match[2][0] === marker[0] &&\n match[2].length >= marker.length &&\n match[3].trim() === ''\n );\n}\n\n/**\n * Collect the bodies of every top-level ` ```suggestion ` block in a\n * markdown body, in document order.\n *\n * Fences are walked in order so a `suggestion` fence nested inside another\n * code block is never mistaken for a real one. The info string must be the\n * bare word `suggestion`: GitLab's range form (`suggestion:-1+2`) widens the\n * anchor by an amount this mapper cannot verify against the diff, so it is\n * deliberately not recognized and leaves the thread without a suggestion.\n */\nfunction findSuggestionBlocks(body: string): string[] {\n const lines = body.split('\\n').map(stripCr);\n const blocks: string[] = [];\n let i = 0;\n while (i < lines.length) {\n const open = FENCE_OPEN.exec(lines[i]);\n if (!open) {\n i++;\n continue;\n }\n const [, indent, marker, info] = open;\n // A backtick fence's info string may not contain a backtick.\n if (marker[0] === '`' && info.includes('`')) {\n i++;\n continue;\n }\n const content: string[] = [];\n let j = i + 1;\n for (; j < lines.length && !isClosingFence(lines[j], marker); j++) {\n content.push(stripIndent(lines[j], indent.length));\n }\n if (info.trim().toLowerCase() === 'suggestion') {\n blocks.push(content.join('\\n'));\n }\n // An unclosed fence runs to the end of the body, as GitHub renders it.\n i = j + 1;\n }\n return blocks;\n}\n\n/**\n * Read the reviewed lines the anchor points at, straight out of the diff.\n *\n * Returns `null` unless the diff covers the whole range: a partially covered\n * anchor would produce an `originalCode` that matches nothing, and the apply\n * engine's byte-for-byte check would refuse it anyway. Taking the text from\n * the diff rather than from the thread body is what makes the extracted\n * suggestion anchored rather than merely quoted.\n */\nfunction readAnchoredLines(\n diffFiles: DiffFile[],\n filePath: string,\n range: LineRange\n): string | null {\n const sidePath = (file: DiffFile) => (range.side === 'old' ? file.oldPath : file.newPath);\n const file =\n diffFiles.find(f => sidePath(f) === filePath) ??\n diffFiles.find(f => f.oldPath === filePath || f.newPath === filePath);\n if (!file) return null;\n\n const found: string[] = [];\n for (const hunk of file.hunks) {\n for (const line of hunk.lines) {\n const number = range.side === 'old' ? line.oldLineNumber : line.newLineNumber;\n if (number !== null && number >= range.start && number <= range.end) {\n found.push(line.content);\n }\n }\n }\n return found.length === range.end - range.start + 1 ? found.join('\\n') : null;\n}\n\n/**\n * Turn a `suggestion` fence in a thread's root body into an anchored\n * {@link Suggestion}, or `null` when there is nothing safe to anchor.\n *\n * `null` covers every uncertain case: no fence, more than one fence (the\n * model holds a single suggestion, and silently keeping the first would drop\n * the rest), a file-level or outdated anchor, and an anchor the reviewed\n * diff does not cover.\n */\nfunction extractSuggestion(\n body: string,\n filePath: string,\n range: LineRange | null,\n diffFiles: DiffFile[]\n): Suggestion | null {\n if (!range) return null;\n const blocks = findSuggestionBlocks(body);\n if (blocks.length !== 1) return null;\n const originalCode = readAnchoredLines(diffFiles, filePath, range);\n if (originalCode === null) return null;\n return { originalCode, proposedCode: blocks[0] };\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 * - A root body carrying a single ` ```suggestion ` fence becomes a\n * `Suggestion` anchored to the thread's line range, with `originalCode`\n * read out of `diffFiles` at that anchor. Without the reviewed diff there\n * is nothing to anchor against, so the default leaves every\n * `suggestion: null` exactly as before.\n *\n * Output order is input order. The input is never mutated.\n */\nexport function mapThreadsToReviewComments(\n threads: ForgeThread[],\n diffFiles: DiffFile[] = []\n): ReviewComment[] {\n return threads.map(thread => {\n const filePath = thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH;\n const lineRange = thread.anchor ? mapAnchorToLineRange(thread.anchor) : null;\n const comment: ReviewComment = {\n id: internalId(thread.root),\n filePath,\n lineRange,\n body: thread.root.body,\n category: '',\n suggestion: extractSuggestion(thread.root.body, filePath, lineRange, diffFiles),\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' ? 'old' : '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 { stripTrailingNewline } from './git';\nimport type { ForgeCommandResult, ForgeCommandRunner, ForgeUrl } 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(command, args, { maxBuffer: 50 * 1024 * 1024 }, (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/** 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(what: string, result: ForgeCommandResult, withAuthHint: boolean): 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(raw: string): { 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 // A blanket .trim() would eat whitespace that is part of the actual path\n // (SR-0047, same defect class as SR-0036's git.ts fix), reporting a root\n // short of what's on disk and breaking the `remote -v` call right after.\n const repoPath = stripTrailingNewline(toplevel.stdout);\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(`self-review: reusing existing clone at ${repoPath} (remote \"${remoteName}\")`);\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(`self-review: created temporary blobless clone at ${tempDir}`);\n const cloneUrl = cloneUrlFor(url);\n // Blobless, never shallow: --depth would break merge-base computation.\n const clone = await runner('git', ['clone', '--filter=blob:none', cloneUrl, tempDir]);\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 ? await detectExistingClone(url, cwd, runner) : 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","// packages/core/src/review-handlers.ts\n// Transport-agnostic review handler bodies.\n//\n// Every function here takes the session it operates on as a parameter and\n// returns a value. Nothing in this module reaches state that is not reachable\n// through that parameter, and nothing in it touches Electron: the registration\n// layer (src/main/ipc-handlers.ts) owns the transport and does the sending.\n\nimport * as fs from 'fs';\nimport path from 'path';\nimport {\n DiffLoadPayload,\n DiffHunk,\n ResumeLoadPayload,\n GuideLoadPayload,\n AppConfig,\n OutputPathInfo,\n PayloadStats,\n ReviewState,\n ReviewComment,\n ExpandContextRequest,\n ImageLoadResult,\n RemoteDriftInfo,\n SuggestionApplyRequest,\n SuggestionApplyOutcome,\n ApplyDestinationOutcome,\n} from './types';\nimport { scanDirectory, scanFile } from './directory-scanner';\nimport { tokenizeGitDiffArgs } from './git-diff-args';\nimport { computePayloadStats, countTotalLines } from './payload-sizing';\nimport { applySuggestion } from './apply-suggestion';\n\n/**\n * The state a single review session owns. One desktop application window is\n * one session; two sessions are independent and cannot observe each other.\n */\nexport interface ReviewSession {\n reviewState: ReviewState | null;\n diffData: DiffLoadPayload | null;\n guideData: GuideLoadPayload | null;\n config: AppConfig | null;\n outputPathInfo: OutputPathInfo | null;\n resumeComments: ReviewComment[];\n resumeViewedFiles: string[];\n resumeRemoteDrift: RemoteDriftInfo | null;\n /**\n * Destination directory the user named for this session's applies, or\n * null when none has been named. Only a temporary-clone remote review\n * needs one; see {@link resolveApplyDestination}.\n */\n applyDestinationRoot: string | null;\n}\n\n/** Create an empty session. */\nexport function createReviewSession(): ReviewSession {\n return {\n reviewState: null,\n diffData: null,\n guideData: null,\n config: null,\n outputPathInfo: null,\n resumeComments: [],\n resumeViewedFiles: [],\n resumeRemoteDrift: null,\n applyDestinationRoot: null,\n };\n}\n\n/**\n * Prepare a DiffLoadPayload for IPC transmission.\n * In large-payload mode, strips hunks from files to reduce initial transfer size.\n * The full data stays in the session for on-demand loading via DIFF_LOAD_FILE.\n */\nexport function preparePayload(payload: DiffLoadPayload): DiffLoadPayload {\n if (payload.isLargePayload) {\n return {\n ...payload,\n files: payload.files.map(f => ({ ...f, hunks: [] as DiffHunk[], contentLoaded: false })),\n };\n }\n return {\n ...payload,\n files: payload.files.map(f => ({ ...f, contentLoaded: true })),\n };\n}\n\n/**\n * Resolve what a diff request should deliver: the prepared diff payload and,\n * when one is loaded, the guide that rides with it. Returns null when the\n * session has no diff, so the caller sends nothing at all.\n */\nexport function getDiffLoad(\n session: ReviewSession\n): { diff: DiffLoadPayload; guide: GuideLoadPayload | null } | null {\n if (!session.diffData) {\n return null;\n }\n // The guide rides after the diff payload in both normal and\n // large-payload modes — it is metadata-only (paths, names,\n // descriptions) and never triggers eager hunk loading.\n return {\n diff: preparePayload(session.diffData),\n guide: session.guideData,\n };\n}\n\n/**\n * The directory the session's reviewed paths are relative to, or null when the\n * session has no diff yet.\n *\n * Scanner paths are relative to the reviewed directory, or to the reviewed\n * file's parent. Git paths are relative to the repository, which in remote\n * mode is the materialized clone.\n */\nexport function resolveSourceBaseDir(session: ReviewSession): string | null {\n const source = session.diffData?.source;\n if (!source) return null;\n if (source.type === 'git') return source.repository;\n if (source.type === 'directory') return source.sourcePath;\n if (source.type === 'file') return path.dirname(source.sourcePath);\n return null;\n}\n\n/**\n * Load a binary image as a base64 data URI for the rendered preview.\n */\nexport async function loadImage(\n session: ReviewSession,\n filePath: string\n): Promise<ImageLoadResult> {\n const MIME_MAP: Record<string, string> = {\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.bmp': 'image/bmp',\n '.svg': 'image/svg+xml',\n };\n const MAX_SIZE = 10 * 1024 * 1024; // 10 MB\n const baseDir = resolveSourceBaseDir(session) ?? process.cwd();\n const resolved = path.isAbsolute(filePath) ? filePath : path.resolve(baseDir, filePath);\n const ext = path.extname(filePath).toLowerCase();\n const mimeType = MIME_MAP[ext] ?? 'application/octet-stream';\n\n // In a remote session the reviewed content lives at the fetched head\n // SHA, not in the clone's working tree (a temporary clone stays on the\n // default branch), so read the blob through git instead of the fs.\n const remote = session.diffData?.remote;\n if (remote && session.diffData?.source.type === 'git') {\n try {\n const { readGitBlobAsync } = await import('./git');\n const data = await readGitBlobAsync(\n session.diffData.source.repository,\n `${remote.remoteHeadSha}:${filePath}`\n );\n if (data.length > MAX_SIZE) {\n return { error: 'File too large to preview (>10 MB)' };\n }\n return { dataUri: `data:${mimeType};base64,${data.toString('base64')}` };\n } catch {\n return {\n error: 'Image preview unavailable — blob not found at the reviewed commit.',\n };\n }\n }\n\n try {\n const stat = await fs.promises.stat(resolved);\n if (stat.size > MAX_SIZE) {\n return { error: 'File too large to preview (>10 MB)' };\n }\n const data = await fs.promises.readFile(resolved);\n return { dataUri: `data:${mimeType};base64,${data.toString('base64')}` };\n } catch {\n return { error: 'Image preview unavailable — file not found on disk.' };\n }\n}\n\n/**\n * Return a single file's hunks for lazy (large-payload) mode, or null when the\n * session has no diff or the diff has no such file.\n */\nexport function getFileHunks(session: ReviewSession, filePath: string): DiffHunk[] | null {\n if (!session.diffData) return null;\n const file = session.diffData.files.find(f => (f.newPath || f.oldPath) === filePath);\n if (!file) return null;\n return file.hunks;\n}\n\n/**\n * Resolve the config and the output path info that travel with it. Returns null\n * when the session has no config, so the caller sends nothing at all: the\n * renderer distinguishes an absent message from an empty one.\n */\nexport function getConfigLoad(\n session: ReviewSession\n): { config: AppConfig; outputPathInfo: OutputPathInfo | null } | null {\n if (!session.config) {\n return null;\n }\n return { config: session.config, outputPathInfo: session.outputPathInfo };\n}\n\n/**\n * Store a review state submitted by the front end on the session.\n */\nexport function submitReviewState(session: ReviewSession, state: ReviewState): void {\n console.error(\n '[review] Review state submitted:',\n JSON.stringify({\n timestamp: state.timestamp,\n source: state.source,\n fileCount: state.files.length,\n })\n );\n session.reviewState = state;\n}\n\n/**\n * Take the submitted review state off the session, clearing it so it is\n * consumed exactly once. Returns null when nothing has been submitted.\n */\nexport function takeReviewState(session: ReviewSession): ReviewState | null {\n const state = session.reviewState;\n session.reviewState = null;\n return state;\n}\n\n/**\n * True when this session reviews a remote PR/MR that was materialized into\n * a temporary clone. That clone is removed when the app exits, so a write\n * into it is lost the moment the review ends (PRD Section 5.4.8).\n */\nexport function isTemporaryCloneSession(session: ReviewSession): boolean {\n return session.diffData?.remote?.temporaryClone === true;\n}\n\n/** Canonical form of a path, following symlinks when the path exists. */\nfunction canonicalize(target: string): string {\n try {\n return fs.realpathSync(target);\n } catch {\n return path.resolve(target);\n }\n}\n\n/** True when `candidate` is `root` itself or sits anywhere beneath it. */\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(canonicalize(root), canonicalize(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/**\n * The directory an apply may write into for this session, or null when the\n * session has none.\n *\n * For every review whose files sit in a place the user controls — a git\n * working tree, a scanned directory, a reused remote clone — that is the\n * root the reviewed paths are relative to, and no one is asked anything.\n *\n * A temporary-clone review is the one exception. Its files live in a\n * directory the app deletes on exit, so the clone is never a destination:\n * the answer is the directory the user named, and null until they name one.\n */\nexport function resolveApplyDestination(session: ReviewSession): string | null {\n if (isTemporaryCloneSession(session)) {\n return session.applyDestinationRoot;\n }\n return resolveSourceBaseDir(session);\n}\n\n/**\n * Record the directory the user named as this session's apply destination.\n *\n * The caller supplies a path the user picked; this decides whether it can\n * be written into and stores it only if so. The temporary clone, and\n * anything inside it, is refused however it was reached — that directory\n * is gone when the review ends, which is the whole reason a destination is\n * asked for.\n */\nexport function setApplyDestination(\n session: ReviewSession,\n directoryPath: string\n): ApplyDestinationOutcome {\n if (!path.isAbsolute(directoryPath)) {\n return {\n status: 'rejected',\n reason: 'destination-not-absolute',\n detail: 'Pick a destination by its full path.',\n };\n }\n\n let isDirectory = false;\n try {\n isDirectory = fs.statSync(directoryPath).isDirectory();\n } catch {\n isDirectory = false;\n }\n if (!isDirectory) {\n return {\n status: 'rejected',\n reason: 'destination-not-a-directory',\n detail: 'That destination is not a directory that exists.',\n };\n }\n\n const clonePath = isTemporaryCloneSession(session) ? resolveSourceBaseDir(session) : null;\n if (clonePath && isWithin(clonePath, directoryPath)) {\n return {\n status: 'rejected',\n reason: 'destination-inside-temporary-clone',\n detail:\n 'That directory is inside the temporary clone, which is deleted when the review ends.',\n };\n }\n\n session.applyDestinationRoot = canonicalize(directoryPath);\n console.error(`[suggestion:apply] destination set for this session`);\n return { status: 'chosen', destinationRoot: session.applyDestinationRoot };\n}\n\n/**\n * Apply one suggestion to the reviewed working file, or refuse and write\n * nothing. The engine in `apply-suggestion.ts` does the work; this handler\n * only names the destination the session reviews, which the engine never\n * derives for itself.\n *\n * A refusal travels as a value, never as a thrown error. The front end\n * renders its `detail` next to the suggestion the attempt came from.\n */\nexport function applySuggestionForSession(\n session: ReviewSession,\n request: SuggestionApplyRequest\n): SuggestionApplyOutcome {\n const destinationRoot = resolveApplyDestination(session);\n if (!destinationRoot) {\n const temporary = isTemporaryCloneSession(session);\n return {\n status: 'refused',\n filePath: request.filePath,\n reason: temporary ? 'destination-required' : 'no-destination',\n detail: temporary\n ? 'This pull request was cloned into a temporary directory that is deleted when the review ends. Choose a destination directory to apply into.'\n : 'This review has no working directory to write into.',\n };\n }\n\n const result = applySuggestion({\n destinationRoot,\n filePath: request.filePath,\n lineRange: request.lineRange,\n suggestion: request.suggestion,\n });\n console.error(\n `[suggestion:apply] ${request.filePath}: ${\n result.status === 'applied' ? 'applied' : `refused (${result.reason})`\n }`\n );\n\n // Projected field by field rather than passed through. The engine also\n // reports the resolved absolute path, which the front end has no use for\n // and should not be handed; naming the fields here keeps the wire shape\n // exactly what SuggestionApplyOutcome declares, today and after the engine\n // grows a field.\n if (result.status === 'applied') {\n return {\n status: 'applied',\n filePath: result.filePath,\n replacedLines: result.replacedLines,\n };\n }\n return {\n status: 'refused',\n filePath: result.filePath,\n reason: result.reason,\n detail: result.detail,\n };\n}\n\n/**\n * Read an attachment file from disk, as an ArrayBuffer the front end can use.\n * Returns null when the file cannot be read.\n */\nexport async function readAttachment(filePath: string) {\n try {\n const buffer = await fs.promises.readFile(filePath);\n return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n } catch {\n console.error(`[attachment:read] Failed to read file: ${filePath}`);\n return null;\n }\n}\n\n/**\n * Resolve the resumed comments, viewed files and remote drift for a session.\n * Returns null when there is nothing to resume, so the caller sends nothing\n * at all.\n */\nexport function getResumeLoad(session: ReviewSession): ResumeLoadPayload | null {\n if (\n session.resumeComments.length > 0 ||\n session.resumeViewedFiles.length > 0 ||\n session.resumeRemoteDrift !== null\n ) {\n const payload: ResumeLoadPayload = {\n comments: session.resumeComments,\n viewedFiles: session.resumeViewedFiles,\n };\n if (session.resumeRemoteDrift !== null) {\n payload.remoteDrift = session.resumeRemoteDrift;\n }\n return payload;\n }\n return null;\n}\n\n/**\n * Expand the context of a single file by re-running git diff with more context\n * lines. The expanded hunks are written back to the session's diff data so a\n * later file load on the same session sees them. Returns null when the session\n * has no git diff, when nothing parses, or when git fails.\n */\nexport async function expandContext(\n session: ReviewSession,\n request: ExpandContextRequest\n): Promise<{ hunks: DiffHunk[]; totalLines: number } | null> {\n const diffData = session.diffData;\n if (!diffData || diffData.source.type !== 'git') {\n return null;\n }\n\n try {\n const { runGitDiffAsync } = await import('./git');\n const { parseDiff } = await import('./diff-parser');\n\n const source = diffData.source;\n // Shell-style tokenizing, the inverse of how the source string was\n // written: a search string or path with a space comes back as one\n // argument instead of several.\n const originalArgs = tokenizeGitDiffArgs(source.gitDiffArgs);\n\n // Strip -U/--unified flags. Stop at `--` — paths after it were the\n // original path restriction; the specific file is supplied below.\n const filteredArgs: string[] = [];\n for (let i = 0; i < originalArgs.length; i++) {\n const arg = originalArgs[i];\n if (arg.match(/^-U\\d+$/) || arg.match(/^--unified=\\d+$/)) {\n continue;\n }\n if (arg === '-U' || arg === '--unified') {\n i++; // skip next arg (the number)\n continue;\n }\n if (arg === '--') {\n break;\n }\n filteredArgs.push(arg);\n }\n\n const expandArgs = [...filteredArgs, `-U${request.contextLines}`, '--', request.filePath];\n\n // Run in the diff's repository root — in remote mode this is the\n // materialized clone, not the process cwd.\n const rawDiff = await runGitDiffAsync(expandArgs, source.repository);\n const parsedFiles = parseDiff(rawDiff);\n\n if (parsedFiles.length === 0) {\n return null;\n }\n\n const expandedFile = parsedFiles[0];\n\n // Count total lines in the working tree file for gap detection.\n // Diff paths are repository-relative — resolve accordingly.\n let totalLines = 0;\n try {\n const content = await fs.promises.readFile(\n path.resolve(source.repository, request.filePath),\n 'utf-8'\n );\n totalLines = content.split('\\n').length;\n // If file ends with newline, last split element is empty — don't count it\n if (content.endsWith('\\n')) totalLines--;\n } catch {\n // Can't determine line count — leave as 0 (bars will stay visible)\n }\n\n // Update the session's diff data\n session.diffData = {\n ...diffData,\n files: diffData.files.map(f => {\n const fPath = f.newPath || f.oldPath;\n if (fPath === request.filePath) {\n return { ...f, hunks: expandedFile.hunks };\n }\n return f;\n }),\n };\n\n return { hunks: expandedFile.hunks, totalLines };\n } catch (error) {\n console.error(`[review] Failed to expand context for ${request.filePath}:`, error);\n return null;\n }\n}\n\n/**\n * What a review start produced: the payload built from the scanned path, the\n * stats it was measured against (null when the session has no config, in which\n * case no thresholds apply), and whether those stats exceeded a threshold.\n *\n * The payload is deliberately *not* stored on the session: the caller may still\n * need to abandon it (a user declining a large review keeps the review they\n * were already looking at), so committing it is the caller's decision.\n */\nexport interface ReviewStartResult {\n payload: DiffLoadPayload;\n stats: PayloadStats | null;\n exceedsThresholds: boolean;\n}\n\n/**\n * Scan a picked path and build the diff payload for a directory (or single\n * file) review, measured against the session's large-payload thresholds.\n * Nothing is stored on the session — see `ReviewStartResult`.\n */\nexport async function prepareDirectoryReview(\n session: ReviewSession,\n directoryPath: string\n): Promise<ReviewStartResult> {\n console.error('[review] Starting directory review for:', directoryPath);\n\n // Check if the path is a file (not a directory)\n let isFile = false;\n try {\n isFile = fs.statSync(directoryPath).isFile();\n } catch {\n // Failed to stat — proceed as directory\n }\n\n let payload: DiffLoadPayload;\n if (isFile) {\n const files = await scanFile(directoryPath);\n payload = {\n files,\n source: { type: 'file', sourcePath: directoryPath },\n };\n } else {\n // Directory mode: scan all files as new additions\n const ignorePatterns = session.config?.ignore ?? [];\n const files = await scanDirectory(directoryPath, ignorePatterns);\n payload = {\n files,\n source: { type: 'directory', sourcePath: directoryPath },\n };\n }\n\n // Large payload guard — skipped entirely when there is no config.\n if (!session.config) {\n return { payload, stats: null, exceedsThresholds: false };\n }\n const stats = computePayloadStats(\n payload.files.length,\n countTotalLines(payload.files),\n session.config\n );\n return { payload, stats, exceedsThresholds: stats.exceedsAny };\n}\n\n/**\n * Commit a prepared review payload to the session, once the caller has decided\n * it should proceed. Returns the payload to hand to the transport.\n */\nexport function commitReviewStart(\n session: ReviewSession,\n payload: DiffLoadPayload\n): DiffLoadPayload {\n session.diffData = payload;\n return preparePayload(payload);\n}\n","// packages/core/src/git-diff-args.ts\n// Normalization of pass-through git diff arguments.\n\nimport { existsSync } from 'fs';\nimport { resolve } from 'path';\n\n// Only options whose bare spelling consumes the next argument belong here.\n// Optional values (for example --color, --relative and -U) must be attached.\nconst OPTIONS_WITH_SEPARATE_VALUES = new Set([\n '--output',\n '--src-prefix',\n '--dst-prefix',\n '--line-prefix',\n '--output-indicator-new',\n '--output-indicator-old',\n '--output-indicator-context',\n '--inter-hunk-context',\n '--stat-width',\n '--stat-name-width',\n '--stat-graph-width',\n '--stat-count',\n '--diff-algorithm',\n '--word-diff-regex',\n '--ignore-matching-lines',\n '--anchored',\n '--diff-filter',\n '--find-object',\n '--rotate-to',\n '--skip-to',\n '--ws-error-highlight',\n '--color-moved-ws',\n]);\n\nfunction consumesNextArgument(arg: string): boolean {\n if (arg.startsWith('--')) return OPTIONS_WITH_SEPARATE_VALUES.has(arg);\n if (!arg.startsWith('-')) return false;\n // Git accepts short-option groups, such as -pS pattern. Once an option\n // takes a value, the rest of that token is its attached value, if present.\n for (let i = 1; i < arg.length; i++) {\n if ('SGOIl'.includes(arg[i])) return i === arg.length - 1;\n if ('UBMC'.includes(arg[i])) return false; // optional, attached values\n }\n return false;\n}\n\n/** Identify positional arguments without mistaking option values for paths. */\nexport function classifyGitDiffArgs(args: string[]): {\n positionalIndices: number[];\n hasSeparator: boolean;\n} {\n const positionalIndices: number[] = [];\n let hasSeparator = false;\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (!hasSeparator) {\n if (arg === '--') {\n hasSeparator = true;\n continue;\n }\n if (consumesNextArgument(arg)) {\n i++;\n continue;\n }\n if (arg.startsWith('-')) continue;\n }\n positionalIndices.push(i);\n }\n return { positionalIndices, hasSeparator };\n}\n\n/**\n * Insert `--` before the first non-flag positional arg that exists as a\n * filesystem path. This makes the args unambiguous so downstream code\n * (expand-context) never confuses a path for a revision.\n *\n * Idempotent: an explicit `--` separator leaves the args unchanged.\n */\nexport function normalizeGitDiffArgs(args: string[], cwd: string = process.cwd()): string[] {\n const { positionalIndices, hasSeparator } = classifyGitDiffArgs(args);\n if (hasSeparator) return args;\n for (const i of positionalIndices) {\n const arg = args[i];\n // Only positional args can be filesystem paths.\n if (existsSync(resolve(cwd, arg))) {\n return [...args.slice(0, i), '--', ...args.slice(i)];\n }\n }\n return args;\n}\n\n/**\n * Split a configured argument string into argv the way a shell would, so a\n * quoted path or search string survives as one argument.\n *\n * Two callers rely on this: `default-diff-args` from YAML, which people write\n * with shell quoting, and the `git-diff-args` string carried on a git diff\n * source, which `formatGitDiffArgs` writes in the same syntax. Unquoted input\n * splits on whitespace exactly as a plain split did, so older config and older\n * review documents keep parsing identically.\n *\n * Malformed input never throws. An unterminated quote closes at end of input:\n * a broken config line degrades to a best-effort argument list instead of\n * taking startup down with it.\n */\nexport function tokenizeGitDiffArgs(value: string): string[] {\n const args: string[] = [];\n let current = '';\n let started = false;\n let quote: \"'\" | '\"' | null = null;\n\n for (let i = 0; i < value.length; i++) {\n const char = value[i];\n\n if (quote === \"'\") {\n if (char === \"'\") quote = null;\n else current += char;\n continue;\n }\n\n if (quote === '\"') {\n // Inside double quotes only the quote and the backslash are escapable;\n // every other backslash is a literal character, as in POSIX shells.\n if (char === '\\\\' && (value[i + 1] === '\"' || value[i + 1] === '\\\\')) {\n current += value[++i];\n } else if (char === '\"') {\n quote = null;\n } else {\n current += char;\n }\n continue;\n }\n\n if (char === \"'\" || char === '\"') {\n quote = char;\n started = true;\n continue;\n }\n if (char === '\\\\' && i + 1 < value.length) {\n current += value[++i];\n started = true;\n continue;\n }\n if (/\\s/.test(char)) {\n if (started) {\n args.push(current);\n current = '';\n started = false;\n }\n continue;\n }\n current += char;\n started = true;\n }\n\n if (started) args.push(current);\n return args;\n}\n\n/** True when rendering this argument bare would lose its boundary. */\nfunction needsQuoting(arg: string): boolean {\n return arg.length === 0 || /[\\s'\"\\\\]/.test(arg);\n}\n\n/**\n * Render argv as the single string a git diff source carries, such that\n * `tokenizeGitDiffArgs` recovers the exact argument list.\n *\n * Arguments that survive a bare round trip are written bare, so ordinary\n * invocations produce byte-identical output to a plain join and the\n * `git-diff-args` XML attribute does not change shape for them.\n */\nexport function formatGitDiffArgs(args: string[]): string {\n return args.map(arg => (needsQuoting(arg) ? `'${arg.replace(/'/g, \"'\\\\''\")}'` : arg)).join(' ');\n}\n","// packages/core/src/startup-mode.ts\n// Startup mode detection: what the app should review, from the CLI args and the CWD.\n\nimport { existsSync, statSync } from 'fs';\nimport { execFileSync, execSync } from 'child_process';\nimport { resolve } from 'path';\nimport { classifyGitDiffArgs } from './git-diff-args';\n\n/**\n * Check if the current working directory is inside a git repository.\n */\nfunction isInGitRepo(): boolean {\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file is tracked by git (known to the index).\n */\nfunction isGitTracked(filePath: string): boolean {\n try {\n execFileSync('git', ['ls-files', '--error-unmatch', '--', filePath], {\n stdio: 'ignore',\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Determine the startup mode based on git availability and CLI arguments.\n * Returns the DiffSource type to use.\n */\nexport function determineMode(gitDiffArgs: string[]): 'git' | 'directory' | 'file' | 'welcome' {\n const { positionalIndices } = classifyGitDiffArgs(gitDiffArgs);\n const firstPositional = gitDiffArgs[positionalIndices[0]];\n\n // Check if first positional arg is an existing file\n if (firstPositional) {\n const candidate = resolve(process.cwd(), firstPositional);\n try {\n if (existsSync(candidate) && statSync(candidate).isFile()) {\n if (isInGitRepo()) {\n // In git repo: tracked files go through git diff, untracked use file mode\n return isGitTracked(firstPositional) ? 'git' : 'file';\n }\n return 'file';\n }\n } catch {\n // Failed to stat — fall through\n }\n }\n\n if (isInGitRepo()) {\n return 'git';\n }\n\n // Not in a git repo — check if first positional arg is an existing directory\n if (firstPositional) {\n const candidate = resolve(process.cwd(), firstPositional);\n try {\n if (existsSync(candidate) && statSync(candidate).isDirectory()) {\n return 'directory';\n }\n } catch {\n // Failed to stat — fall through to welcome\n }\n }\n\n return 'welcome';\n}\n","// packages/core/src/guide-loader.ts\n// Discovery + tolerant loading of the walkthrough guide sidecar.\n//\n// The guide is orientation garnish on a deterministic tool (see\n// docs/intent/llm-review-guide.md): a missing file is a silent no-op, and\n// an unreadable or invalid one produces exactly one stderr warning and no\n// guide. Nothing in this module may throw out of it — every failure mode\n// resolves to null.\n//\n// Note on startup cost: loadGuide IS awaited before window creation\n// (main.ts Phase 5b), deliberately — `guide:load` piggybacks on the\n// DIFF_REQUEST handler, so the payload must be cached via setGuideData\n// before the renderer's first request arrives. When a guide exists, the\n// xmllint-wasm init and validation delay window paint by a few hundred ms;\n// when none exists the cost is a single failed stat.\n//\n// Discovery is one-shot: the guide is resolved from the startup output\n// path. Changing the output path at runtime does not re-discover.\n\nimport { readFile } from 'fs/promises';\nimport { extname, resolve } from 'path';\nimport { parseGuideXml, reconcileGuide } from './guide-parser';\nimport { AppConfig, GuideLoadPayload } from './types';\n\n/**\n * Derive the guide sidecar path from the resolved output path: strip the\n * last extension and append `.guide.xml` (`review.xml` →\n * `review.guide.xml`). An output filename with no extension gets\n * `.guide.xml` appended verbatim.\n */\nexport function deriveGuidePath(outputPath: string): string {\n const ext = extname(outputPath);\n const base = ext ? outputPath.slice(0, -ext.length) : outputPath;\n return `${base}.guide.xml`;\n}\n\n/**\n * Resolve where to look for the guide: the `guide-file` config override\n * (resolved against cwd, like `output-file`) when set, otherwise the path\n * derived from the resolved output path.\n */\nexport function resolveGuidePath(outputPath: string, config: Pick<AppConfig, 'guideFile'>): string {\n if (config.guideFile) {\n return resolve(process.cwd(), config.guideFile);\n }\n return deriveGuidePath(outputPath);\n}\n\n/**\n * Discover, read, parse, validate, and reconcile the guide sidecar.\n *\n * Returns the display-ready payload, or null when there is no usable\n * guide. Missing file: silent. Unreadable or invalid file: exactly one\n * `console.error()` line (guide path + reason class). Never throws.\n */\nexport async function loadGuide(\n outputPath: string,\n config: Pick<AppConfig, 'guideFile'>,\n diffFilePaths: string[]\n): Promise<GuideLoadPayload | null> {\n let guidePath: string;\n try {\n guidePath = resolveGuidePath(outputPath, config);\n } catch {\n return null;\n }\n\n try {\n let content: string;\n try {\n content = await readFile(guidePath, 'utf-8');\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n // No sidecar next to the output path — the normal case.\n return null;\n }\n console.error(\n `[guide] Ignoring guide at ${guidePath}: unreadable (${code ?? 'unknown error'})`\n );\n return null;\n }\n\n const result = await parseGuideXml(content);\n // Explicit comparison: with strictNullChecks off (see tsconfig),\n // truthiness alone does not narrow the discriminated union.\n if (result.ok === false) {\n console.error(`[guide] Ignoring guide at ${guidePath}: invalid (${result.reason})`);\n return null;\n }\n\n const payload: GuideLoadPayload = {\n groups: reconcileGuide(result.guide, diffFilePaths),\n };\n if (result.guide.overview !== undefined) {\n payload.overview = result.guide.overview;\n }\n return payload;\n } catch (error) {\n // Belt and braces: no failure mode of the guide loader may escape.\n const message = error instanceof Error ? error.message : String(error);\n console.error(`[guide] Ignoring guide at ${guidePath}: invalid (${message})`);\n return null;\n }\n}\n","import type { DiffFile } from './types';\nimport {\n runGitDiffAsync,\n getRepoRootAsync,\n getUntrackedFilesAsync,\n generateUntrackedDiffs,\n} from './git';\nimport { parseDiff } from './diff-parser';\n\nexport interface LoadGitDiffOptions {\n /**\n * Include untracked working-tree files as synthetic additions. Defaults\n * to true (local git mode). Remote mode passes false: a base...head diff\n * of a PR/MR must never pick up unrelated local untracked files.\n */\n includeUntracked?: boolean;\n}\n\nexport async function loadGitDiffWithUntracked(\n gitDiffArgs: string[],\n cwd?: string,\n options: LoadGitDiffOptions = {}\n): Promise<{ files: DiffFile[]; repository: string }> {\n const { includeUntracked = true } = options;\n const repository = await getRepoRootAsync(cwd);\n const rawDiff = await runGitDiffAsync(gitDiffArgs, cwd);\n const files = parseDiff(rawDiff);\n\n if (!includeUntracked) {\n return { files, repository };\n }\n\n // Enumerate at the repository root. `git diff` reports root-relative paths\n // for the whole repository, while `git ls-files` reports cwd-relative paths\n // for the cwd subtree only. Read those cwd-relative names against the root\n // and a nested file resolves to its same-named root neighbour, or to\n // nothing at all.\n const untrackedPaths = await getUntrackedFilesAsync(repository);\n let allFiles = files;\n if (untrackedPaths.length > 0) {\n const untrackedDiffStr = generateUntrackedDiffs(untrackedPaths, repository);\n if (untrackedDiffStr.length > 0) {\n const untrackedFiles = parseDiff(untrackedDiffStr);\n for (const file of untrackedFiles) {\n file.isUntracked = true;\n }\n allFiles = [...files, ...untrackedFiles];\n }\n }\n\n return { files: allFiles, repository };\n}\n","// packages/core/src/staged-untracked.ts\n// Initial-config adjustment for staged-mode reviews.\n\nimport type { AppConfig } from './types';\n\n/**\n * In staged-mode reviews (--staged / --cached), untracked files are not\n * part of the index and should be hidden by default. If the user has\n * explicitly opted in via `show-untracked: true` in their YAML config,\n * respect that choice.\n *\n * Untracked files are still preloaded by the backend so that the toolbar\n * toggle can reveal them instantly without re-running git.\n */\nexport function applyStagedUntrackedDefault(config: AppConfig, gitDiffArgs: string[]): AppConfig {\n const stagedMode = gitDiffArgs.includes('--staged') || gitDiffArgs.includes('--cached');\n if (!stagedMode) return config;\n\n const userExplicitOptIn = config.showUntrackedExplicit && config.showUntracked;\n if (userExplicitOptIn) return config;\n\n return { ...config, showUntracked: false };\n}\n","// packages/core/src/remote-mode.ts\n// Remote PR/MR session bootstrap for the main process.\n//\n// Binding rule: after materialization, remote mode *is* git mode. This\n// module turns a forge URL into the inputs the existing git-mode pipeline\n// already understands — a repo path and a `baseSha...headSha` range — plus\n// the fetched discussion threads (mapped to ReviewComments for the\n// resume:load path) and the remote provenance the serializer records.\n//\n// Reused by both the CLI URL path (main.ts startup) and the splash-screen\n// URL entry (the remote:open-url IPC handler). Every external effect goes\n// through an injectable dependency so unit tests never spawn git/gh/glab.\n\nimport {\n parseForgeUrl,\n ForgeCliUnavailableError,\n createGitHubProvider,\n createGitLabProvider,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n defaultGitRunner,\n mapThreadsToReviewComments,\n createIgnoreFilter,\n} from './index';\nimport type {\n ForgeCommandRunner,\n ForgeName,\n ForgeProvider,\n ForgeThread,\n ForgeUrl,\n ExistingClone,\n MaterializeMode,\n MaterializeResult,\n} from './index';\nimport type {\n DiffFile,\n DiffLoadPayload,\n RemoteDriftInfo,\n RemoteSessionInfo,\n ReviewComment,\n ReviewState,\n} from './types';\nimport { loadGitDiffWithUntracked } from './git-diff-loader';\nimport { formatGitDiffArgs } from './git-diff-args';\n\n/** A materialized remote PR/MR session, ready for the git-mode pipeline. */\nexport interface RemoteSession {\n forgeUrl: ForgeUrl;\n /** Root of the materialized clone; the pipeline's repo path. */\n repoPath: string;\n /** Arguments for the existing git-diff machinery: `[base...head]`. */\n gitDiffArgs: string[];\n mode: MaterializeMode;\n /** Removes the temp clone when one was created; idempotent no-op otherwise. */\n cleanup: () => void;\n /** Provenance + thread-sync status for payloads and the saved review. */\n remote: RemoteSessionInfo;\n /**\n * Forge discussion threads mapped to ReviewComments. Empty when the forge\n * CLI is unavailable. Review-level threads keep the mapper's sentinel\n * `filePath: ''` (REVIEW_LEVEL_FILE_PATH).\n *\n * Mapped here without the reviewed diff, which is not loaded yet, so a\n * `suggestion` fence stays plain body text. {@link bootstrapRemoteDiff}\n * replaces these with the same threads mapped against the loaded files.\n */\n fetchedComments: ReviewComment[];\n /**\n * The threads behind `fetchedComments`, verbatim. Carried so the caller\n * that loads the diff can map them again with it (SR-0063).\n */\n fetchedThreads: ForgeThread[];\n}\n\n/** Injectable seams; defaults are the real core APIs. */\nexport interface RemoteSessionDeps {\n createProvider: (forge: ForgeName, runner: ForgeCommandRunner) => ForgeProvider;\n materialize: (\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner,\n existingClone?: ExistingClone | null\n ) => Promise<MaterializeResult>;\n detectExistingClone: (\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner\n ) => Promise<ExistingClone | null>;\n resolveRemoteDefaultBranch: (\n url: ForgeUrl,\n runner: ForgeCommandRunner,\n existing?: ExistingClone | null\n ) => Promise<string>;\n runner: ForgeCommandRunner;\n /** Loads the diff from the clone. Untracked files are never included. */\n loadDiff: (\n gitDiffArgs: string[],\n cwd: string\n ) => Promise<{ files: DiffFile[]; repository: string }>;\n}\n\nfunction defaultCreateProvider(forge: ForgeName, runner: ForgeCommandRunner): ForgeProvider {\n return forge === 'github' ? createGitHubProvider(runner) : createGitLabProvider(runner);\n}\n\nconst defaultDeps: RemoteSessionDeps = {\n createProvider: defaultCreateProvider,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n runner: defaultGitRunner,\n loadDiff: (gitDiffArgs, cwd) =>\n // A base...head diff of a remote PR/MR must never pick up local\n // untracked files (an existing clone may have unrelated ones).\n loadGitDiffWithUntracked(gitDiffArgs, cwd, { includeUntracked: false }),\n};\n\n/**\n * Materialize a forge PR/MR URL into a local git context and fetch its\n * discussion threads.\n *\n * Fatal failures (unrecognizable URL, materialization errors, base-branch\n * lookup failures other than a missing CLI) throw — callers surface them\n * like any other startup git error. Forge-CLI unavailability is never\n * fatal: the base branch falls back to the git-only default-branch lookup\n * and thread sync degrades to an empty list with a single stderr note.\n */\nexport async function startRemoteSession(\n url: string,\n cwd: string,\n deps: Partial<RemoteSessionDeps> = {}\n): Promise<RemoteSession> {\n const d: RemoteSessionDeps = { ...defaultDeps, ...deps };\n\n const forgeUrl = parseForgeUrl(url);\n if (!forgeUrl) {\n throw new Error(`Not a recognized pull-request or merge-request URL: ${url}`);\n }\n\n const provider = d.createProvider(forgeUrl.forge, d.runner);\n\n let cliAvailable = true;\n let baseBranch: string;\n let existingClone: ExistingClone | null | undefined;\n try {\n baseBranch = await provider.fetchBaseBranch(forgeUrl);\n } catch (error) {\n if (!(error instanceof ForgeCliUnavailableError)) {\n throw error;\n }\n cliAvailable = false;\n console.error(\n `[remote] Forge CLI unavailable (${error.cli}): ${error.message} — ` +\n 'falling back to the remote default branch via git.'\n );\n existingClone = await d.detectExistingClone(forgeUrl, cwd, d.runner);\n baseBranch = await d.resolveRemoteDefaultBranch(forgeUrl, d.runner, existingClone);\n }\n\n const materialized = await d.materialize(forgeUrl, baseBranch, cwd, d.runner, existingClone);\n\n let fetchedThreads: ForgeThread[] = [];\n let threadSyncAvailable = false;\n if (cliAvailable) {\n try {\n fetchedThreads = await provider.fetchThreads(forgeUrl);\n threadSyncAvailable = true;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(\n `[remote] thread sync unavailable — continuing without forge threads: ${message}`\n );\n }\n } else {\n console.error(\n '[remote] thread sync unavailable — forge CLI missing, continuing without forge threads.'\n );\n }\n\n return {\n forgeUrl,\n repoPath: materialized.repoPath,\n gitDiffArgs: [`${materialized.baseSha}...${materialized.headSha}`],\n mode: materialized.mode,\n cleanup: materialized.cleanup,\n remote: {\n remoteUrl: url,\n remoteBaseSha: materialized.baseSha,\n remoteHeadSha: materialized.headSha,\n remoteForge: forgeUrl.forge,\n threadSyncAvailable,\n // A temporary clone is deleted on exit, so nothing may be written\n // into it; the front end needs the fact, not the path.\n temporaryClone: materialized.mode === 'temp-clone',\n },\n fetchedComments: mapThreadsToReviewComments(fetchedThreads),\n fetchedThreads,\n };\n}\n\n/** A remote session plus the ready-to-send git-mode diff payload. */\nexport interface RemoteBootstrapResult {\n session: RemoteSession;\n payload: DiffLoadPayload;\n}\n\n/**\n * Full remote bootstrap: materialize the session, load the diff from the\n * clone through the existing git-diff machinery, apply the ignore filter,\n * map the fetched threads against those files, and shape the git-mode\n * `DiffLoadPayload` (with `remote` provenance attached). Shared by the CLI\n * URL startup path and the splash-screen `remote:open-url` handler.\n */\nexport async function bootstrapRemoteDiff(\n url: string,\n cwd: string,\n ignorePatterns: string[],\n deps: Partial<RemoteSessionDeps> = {}\n): Promise<RemoteBootstrapResult> {\n const d: RemoteSessionDeps = { ...defaultDeps, ...deps };\n const started = await startRemoteSession(url, cwd, d);\n\n // From here on the session may own a temporary clone; if anything below\n // fails the caller never receives the cleanup handle, so release it here.\n let files: DiffFile[];\n let repository: string;\n try {\n ({ files, repository } = await d.loadDiff(started.gitDiffArgs, started.repoPath));\n } catch (error) {\n started.cleanup();\n throw error;\n }\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredFiles = files.filter(f => shouldKeep(f.newPath || f.oldPath));\n\n // The reviewed diff exists only now, and the mapper needs it to anchor a\n // `suggestion` fence. Mapping against the filtered files keeps the\n // comments consistent with the payload the renderer receives.\n const session: RemoteSession = {\n ...started,\n fetchedComments: mapThreadsToReviewComments(started.fetchedThreads, filteredFiles),\n };\n\n return {\n session,\n payload: {\n files: filteredFiles,\n source: {\n type: 'git',\n // Same renderer the git-mode path uses, so expand-context can\n // tokenize this string back into the exact argv.\n gitDiffArgs: formatGitDiffArgs(session.gitDiffArgs),\n repository,\n },\n remote: session.remote,\n },\n };\n}\n\n/**\n * Merge fetched forge threads into a resumed document's comments. The\n * resumed document wins: a fetched thread whose root `remoteId` already\n * appears in the resumed comments is skipped (the resumed copy may carry\n * the user's added replies). Order: resumed comments first, then the\n * non-duplicate fetched threads in fetch order. Inputs are not mutated.\n */\nexport function mergeRemoteThreads(\n resumed: ReviewComment[],\n fetched: ReviewComment[]\n): ReviewComment[] {\n const resumedRemoteIds = new Set(\n resumed.map(c => c.remoteId).filter((id): id is string => id !== undefined)\n );\n return [\n ...resumed,\n ...fetched.filter(c => c.remoteId === undefined || !resumedRemoteIds.has(c.remoteId)),\n ];\n}\n\n/**\n * Return a copy of the state carrying this session's remote provenance, so\n * \"Finish Review\" writes the `remote-*` root attributes. Always records the\n * live session values: the saved document describes the diff that was\n * actually reviewed.\n */\nexport function applyRemoteProvenance(state: ReviewState, remote: RemoteSessionInfo): ReviewState {\n return {\n ...state,\n // The three source shapes are mutually exclusive in the document: the\n // remote-* attributes ARE the source, so the in-session git source\n // (the materialized clone) must not leak into the saved review. The\n // welcome source emits no source attributes, mirroring fetch-comments.\n source: { type: 'welcome' },\n remoteUrl: remote.remoteUrl,\n remoteBaseSha: remote.remoteBaseSha,\n remoteHeadSha: remote.remoteHeadSha,\n remoteForge: remote.remoteForge,\n };\n}\n\n/**\n * Compare a resumed document's recorded `remote-head-sha` with the live\n * head from materialization. Returns `null` when the document recorded no\n * head SHA (nothing to compare).\n */\nexport function computeRemoteDrift(\n recordedHeadSha: string | undefined,\n liveHeadSha: string\n): RemoteDriftInfo | null {\n if (recordedHeadSha === undefined) {\n return null;\n }\n return {\n recordedHeadSha,\n liveHeadSha,\n drifted: recordedHeadSha !== liveHeadSha,\n };\n}\n","// packages/core/src/fetch-comments.ts\n// Headless orchestrator for `self-review fetch-comments <URL>`: materialize\n// the PR/MR, fetch and map its discussion threads, and write a v3 review.xml\n// with remote provenance — no window, nothing on stdout, all logging on\n// stderr. Every collaborator is injectable so the flow is unit-testable; the\n// CLI entry in main.ts stays thin.\n\nimport { writeFileSync } from 'fs';\nimport { resolve } from 'path';\nimport { ForgeCliUnavailableError, parseForgeUrl } from './forge-provider';\nimport type { ForgeCommandRunner, ForgeName, ForgeProvider, ForgeUrl } from './forge-provider';\nimport { createGitHubProvider } from './github-provider';\nimport { createGitLabProvider } from './gitlab-provider';\nimport {\n defaultGitRunner,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n} from './materializer';\nimport type { ExistingClone, MaterializeResult } from './materializer';\nimport { mapThreadsToReviewComments, REVIEW_LEVEL_FILE_PATH } from './thread-mapper';\nimport { parseDiff } from './diff-parser';\nimport { runGitDiffAsync } from './git';\nimport { serializeReview } from './xml-serializer';\nimport { loadConfig } from './config';\nimport type {\n AppConfig,\n DiffFile,\n FileReviewState,\n RemoteForge,\n ReviewComment,\n ReviewState,\n} from './types';\n\n/**\n * Injectable seams for the orchestration. Defaults spawn real processes and\n * touch the real filesystem; tests replace them wholesale.\n */\nexport interface FetchCommentsDeps {\n /** Command runner shared by git, gh and glab invocations. */\n runner: ForgeCommandRunner;\n createProvider: (forge: ForgeName, runner: ForgeCommandRunner) => ForgeProvider;\n materialize: (\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner,\n existingClone?: ExistingClone | null\n ) => Promise<MaterializeResult>;\n detectExistingClone: (\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner\n ) => Promise<ExistingClone | null>;\n resolveRemoteDefaultBranch: (\n url: ForgeUrl,\n runner: ForgeCommandRunner,\n existing?: ExistingClone | null\n ) => Promise<string>;\n loadDiffFiles: (repoPath: string, baseSha: string, headSha: string) => Promise<DiffFile[]>;\n serialize: (state: ReviewState, outputPath: string) => Promise<string>;\n writeFile: (path: string, content: string) => void;\n loadConfig: () => AppConfig;\n now: () => Date;\n}\n\nfunction defaultDeps(): FetchCommentsDeps {\n return {\n runner: defaultGitRunner,\n createProvider: (forge, runner) =>\n forge === 'github' ? createGitHubProvider(runner) : createGitLabProvider(runner),\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n loadDiffFiles: async (repoPath, baseSha, headSha) =>\n // Triple-dot: diff from the merge base, matching how forges present a\n // PR/MR diff. Runs inside the materialized clone.\n parseDiff(await runGitDiffAsync([`${baseSha}...${headSha}`], repoPath)),\n serialize: serializeReview,\n writeFile: (path, content) => writeFileSync(path, content, 'utf-8'),\n loadConfig,\n now: () => new Date(),\n };\n}\n\nexport interface BuildRemoteReviewStateArgs {\n remoteUrl: string;\n forge: RemoteForge;\n baseSha: string;\n headSha: string;\n diffFiles: DiffFile[];\n comments: ReviewComment[];\n timestamp: string;\n}\n\n/**\n * Assemble the ReviewState for a fetched remote review. Pure and\n * deterministic: same inputs, same state.\n *\n * Placement rules:\n * - Every diff file gets a file entry in diff order; fetched threads land on\n * their files, in thread order.\n * - Comments whose path is not in the diff (e.g. outdated anchors on files\n * no longer touched) get a synthetic entry with change-type \"modified\" —\n * the schema requires the attribute and \"modified\" is the least-claiming\n * value for a file we cannot classify.\n * - Review-level threads (sentinel {@link REVIEW_LEVEL_FILE_PATH}) are\n * folded into a single trailing file entry with the sentinel path: the v3\n * schema requires every <comment> inside a <file path>, and the empty\n * path can never collide with a real diff path, so consumers detect these\n * by comparing against the constant. Omitted when there are none.\n * - Every file is viewed=\"false\": fetch-comments reviews nothing, and a\n * viewed mark claims a human looked at the file. A subsequent\n * --resume-from session therefore starts with the full file list pending.\n * - `source` is `{ type: 'welcome' }`: the remote-* root attributes are the\n * review's source shape, and the three shapes (git, directory, remote)\n * are mutually exclusive by contract, so no local source attributes are\n * serialized.\n */\nexport function buildRemoteReviewState(args: BuildRemoteReviewStateArgs): ReviewState {\n const commentsByPath = new Map<string, ReviewComment[]>();\n for (const comment of args.comments) {\n const list = commentsByPath.get(comment.filePath);\n if (list) {\n list.push(comment);\n } else {\n commentsByPath.set(comment.filePath, [comment]);\n }\n }\n\n const files: FileReviewState[] = [];\n const diffPaths = new Set<string>();\n for (const diffFile of args.diffFiles) {\n const path = diffFile.changeType === 'deleted' ? diffFile.oldPath : diffFile.newPath;\n diffPaths.add(path);\n files.push({\n path,\n changeType: diffFile.changeType,\n viewed: false,\n comments: commentsByPath.get(path) ?? [],\n });\n }\n\n // Synthetic entries for anchored comments whose file is not in the diff,\n // in first-appearance order.\n for (const [path, comments] of commentsByPath) {\n if (path === REVIEW_LEVEL_FILE_PATH || diffPaths.has(path)) continue;\n files.push({ path, changeType: 'modified', viewed: false, comments });\n }\n\n const reviewLevel = commentsByPath.get(REVIEW_LEVEL_FILE_PATH);\n if (reviewLevel && reviewLevel.length > 0) {\n files.push({\n path: REVIEW_LEVEL_FILE_PATH,\n changeType: 'modified',\n viewed: false,\n comments: reviewLevel,\n });\n }\n\n return {\n timestamp: args.timestamp,\n source: { type: 'welcome' },\n files,\n remoteUrl: args.remoteUrl,\n remoteBaseSha: args.baseSha,\n remoteHeadSha: args.headSha,\n remoteForge: args.forge,\n };\n}\n\nexport interface FetchCommentsOptions {\n /** Include threads the forge marks resolved (GitLab). Default false. */\n includeResolved?: boolean;\n /** Working directory for clone detection and output resolution. */\n cwd?: string;\n /** Test seams; every omitted member falls back to the real default. */\n deps?: Partial<FetchCommentsDeps>;\n}\n\n/**\n * Run the headless fetch-comments flow end to end. Throws on any failure\n * (the caller prints the message to stderr and exits 1); the temporary\n * clone, when one was created, is removed on both success and failure.\n */\nexport async function runFetchComments(\n url: string,\n options: FetchCommentsOptions = {}\n): Promise<void> {\n const deps: FetchCommentsDeps = { ...defaultDeps(), ...options.deps };\n const cwd = options.cwd ?? process.cwd();\n\n const forgeUrl = parseForgeUrl(url);\n if (forgeUrl === null) {\n throw new Error(\n `Not a recognized pull/merge request URL: ${url}\\n` +\n 'Expected a GitHub PR URL (…/pull/N) or a GitLab MR URL ' +\n '(…/-/merge_requests/N).'\n );\n }\n\n const provider = deps.createProvider(forgeUrl.forge, deps.runner);\n\n let baseBranch: string;\n let existingClone: ExistingClone | null | undefined;\n try {\n baseBranch = await provider.fetchBaseBranch(forgeUrl);\n } catch (error) {\n if (!(error instanceof ForgeCliUnavailableError)) throw error;\n console.error(`[fetch-comments] ${error.message}`);\n console.error(\n `[fetch-comments] ${error.cli} unavailable for the base-branch lookup — ` +\n 'falling back to the remote default branch via git ls-remote.'\n );\n existingClone = await deps.detectExistingClone(forgeUrl, cwd, deps.runner);\n baseBranch = await deps.resolveRemoteDefaultBranch(forgeUrl, deps.runner, existingClone);\n }\n console.error(`[fetch-comments] Base branch: ${baseBranch}`);\n\n const materialized = await deps.materialize(\n forgeUrl,\n baseBranch,\n cwd,\n deps.runner,\n existingClone\n );\n try {\n let threads;\n try {\n threads = await provider.fetchThreads(forgeUrl, {\n includeResolved: options.includeResolved ?? false,\n });\n } catch (error) {\n if (error instanceof ForgeCliUnavailableError) {\n // Fetching comments is this subcommand's entire purpose: no\n // degradation, fail with a clear error.\n throw new Error(\n `Cannot fetch discussion threads: ${error.message}\\n` +\n `fetch-comments requires the ${error.cli} CLI to be installed ` +\n 'and authenticated.'\n );\n }\n throw error;\n }\n console.error(`[fetch-comments] Fetched ${threads.length} threads`);\n\n const diffFiles = await deps.loadDiffFiles(\n materialized.repoPath,\n materialized.baseSha,\n materialized.headSha\n );\n // The diff is what anchors a `suggestion` fence: without it the mapper\n // cannot read the original code a fence proposes to replace.\n const comments = mapThreadsToReviewComments(threads, diffFiles);\n\n const state = buildRemoteReviewState({\n remoteUrl: url,\n forge: forgeUrl.forge,\n baseSha: materialized.baseSha,\n headSha: materialized.headSha,\n diffFiles,\n comments,\n timestamp: deps.now().toISOString(),\n });\n\n const config = deps.loadConfig();\n const outputPath = resolve(cwd, config.outputFile);\n const xml = await deps.serialize(state, outputPath);\n deps.writeFile(outputPath, xml + '\\n');\n console.error(`[fetch-comments] ${comments.length} threads written to ${outputPath}`);\n } finally {\n materialized.cleanup();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAGA,YAAY,UAAU;AACtB,YAAY,QAAQ;AAEpB,SAAS,mBAAmB;AAMrB,IAAM,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAQ,MAAM,iCAAiC,UAAU,EAAE;AAE3D,QAAM,eAAe,MAAM,KAAK;AAAA,IAC9B;AAAA,IACA;AAAA,IACA;AAAA,IACA,KAAK;AAAA,IACL;AAAA,EACF;AACA,MAAI;AACF,QAAI;AACJ,QAAI;AACF,gBAAU,MAAM,SAAS,aAAa,UAAU;AAAA,QAC9C,iBAAiB,QAAQ,mBAAmB;AAAA,MAC9C,CAAC;AAAA,IACH,SAAS,OAAO;AACd,UAAI,iBAAiB,0BAA0B;AAG7C,cAAM,IAAI;AAAA,UACR,oCAAoC,MAAM,OAAO;AAAA,8BAChB,MAAM,GAAG;AAAA,QAE5C;AAAA,MACF;AACA,YAAM;AAAA,IACR;AACA,YAAQ,MAAM,4BAA4B,QAAQ,MAAM,UAAU;AAElE,UAAM,YAAY,MAAM,KAAK;AAAA,MAC3B,aAAa;AAAA,MACb,aAAa;AAAA,MACb,aAAa;AAAA,IACf;AAGA,UAAM,WAAW,2BAA2B,SAAS,SAAS;AAE9D,UAAM,QAAQ,uBAAuB;AAAA,MACnC,WAAW;AAAA,MACX,OAAO,SAAS;AAAA,MAChB,SAAS,aAAa;AAAA,MACtB,SAAS,aAAa;AAAA,MACtB;AAAA,MACA;AAAA,MACA,WAAW,KAAK,IAAI,EAAE,YAAY;AAAA,IACpC,CAAC;AAED,UAAM,SAAS,KAAK,WAAW;AAC/B,UAAM,aAAaG,SAAQ,KAAK,OAAO,UAAU;AACjD,UAAM,MAAM,MAAM,KAAK,UAAU,OAAO,UAAU;AAClD,SAAK,UAAU,YAAY,MAAM,IAAI;AACrC,YAAQ,MAAM,oBAAoB,SAAS,MAAM,uBAAuB,UAAU,EAAE;AAAA,EACtF,UAAE;AACA,iBAAa,QAAQ;AAAA,EACvB;AACF;","names":["XMLParser","validateXML","validateXML","XMLParser","path","join","dirname","join","dirname","readFileSync","existsSync","join","path","dirname","readFileSync","writeFileSync","relative","resolve","file","toTurn","toAnchor","execFile","fs","path","resolve","execFile","fs","path","existsSync","resolve","path","stat","runGitDiffAsync","parseDiff","path","existsSync","statSync","resolve","resolve","existsSync","statSync","resolve","resolve","writeFileSync","resolve","defaultDeps","path","writeFileSync","resolve"]}
|
|
1
|
+
{"version":3,"sources":["../src/xml-serializer.ts","../src/xml-errors.ts","../src/xml-text.ts","../src/xml-parser.ts","../src/anchor-validation.ts","../src/review-publisher.ts","../src/fs-utils.ts","../src/safe-fs.ts","../src/attachment-origins.ts","../src/source-identity.ts","../src/git-diff-args.ts","../src/guide-schema.ts","../src/guide-parser.ts","../src/forge-provider.ts","../src/directory-scanner.ts","../src/ignore-filter.ts","../src/snapshot-reader.ts","../src/config.ts","../../react/src/config-defaults.ts","../src/payload-sizing.ts","../src/apply-suggestion.ts","../src/file-type-utils.ts","../src/github-provider.ts","../src/thread-mapper.ts","../src/gitlab-provider.ts","../src/materializer.ts","../src/review-handlers.ts","../src/startup-mode.ts","../src/startup.ts","../src/staged-untracked.ts","../src/git-diff-loader.ts","../src/cli-options.ts","../src/guide-loader.ts","../src/remote-mode.ts","../src/fetch-comments.ts"],"sourcesContent":["// src/main/xml-serializer.ts\n// Serialize ReviewState to XML and validate against XSD\n\nimport * as path from 'path';\nimport { ReviewState, FileReviewState, ReviewComment, Reply, Attachment } from './types';\nimport { validateXML } from 'xmllint-wasm';\nimport {\n ReviewXmlError,\n XmlIllegalCharacterError,\n XmlIllegalCharacterLocation,\n} from './xml-errors';\nimport { escapeXmlAttribute, escapeXmlText, findIllegalXmlCharacter } from './xml-text';\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, renamed, or copied.\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:enumeration value=\"copied\">\n <xs:annotation>\n <xs:documentation>File was copied from another path (git copy detection), 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 // Same reasoning as `assetNameComponent`: anything not in the map falls\n // back to png, including a value that is not a string at all.\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 * Reduce an id to something that can only ever name a file *inside* the asset\n * directory.\n *\n * A comment id is not trusted input. The desktop gets its ReviewState from its\n * own renderer, but the serve front end accepts a whole document over HTTP, so\n * `../../x` in an id would walk this function's write out of the asset\n * directory and onto an arbitrary path. Every id this app generates is a UUID,\n * so restricting the prefix to the URL-safe alphabet renames nothing in\n * practice and leaves existing asset names byte-identical.\n */\nfunction assetNameComponent(idPrefix: string): string {\n // Coerced rather than assumed: this runs before the document is validated\n // against anything, so a caller that omits an id reaches here with\n // `undefined`, and a bare `.replace` would turn that into a crash *after*\n // the review has already been taken off the session — losing it. The\n // serializer's job here is to name a file, not to police the document.\n return String(idPrefix ?? '').replace(/[^A-Za-z0-9_-]/g, '_');\n}\n\nexport const ASSET_DIR_NAME = '.self-review-assets';\n\nexport interface PlannedAsset {\n /** As emitted in the document: `.self-review-assets/<name>`. */\n relativePath: string;\n absolutePath: string;\n data: ArrayBuffer;\n}\n\n/**\n * `idPrefix` is already URL-safe; the result must be a bare file name. The publisher injects unique\n * names so a new document never overwrites an asset the previous one references.\n */\nexport type AssetNamer = (idPrefix: string, index: number, ext: string) => string;\n\nexport interface SerializeOptions {\n assetName?: AssetNamer;\n}\n\nexport interface SerializedReview {\n /** Validated, without a trailing newline. */\n xml: string;\n /** Blobs the document references that nothing has written yet. */\n assets: PlannedAsset[];\n}\n\nconst defaultAssetName: AssetNamer = (idPrefix, index, ext) => `${idPrefix}-${index}.${ext}`;\n\n/**\n * Rewrites fileNames to their on-disk locations, strips the data buffers and collects each\n * blob as a planned asset. Both the comment and reply walks must go through here: a list that\n * skips it validates against the schema while pointing at a file that does not exist.\n * Replies pass an `idPrefix` that cannot collide with a comment's.\n */\nfunction stageAttachmentList(\n attachments: Attachment[] | undefined,\n idPrefix: string,\n assetDir: string,\n assetName: AssetNamer,\n assets: PlannedAsset[]\n): Attachment[] | undefined {\n if (!attachments?.length) return attachments;\n\n return attachments.map((att, index) => {\n if (!att.data) return att;\n\n const ext = extFromMediaType(att.mediaType);\n const fileName = assetName(assetNameComponent(idPrefix), index, ext);\n const relativePath = `${ASSET_DIR_NAME}/${fileName}`;\n const absolutePath = path.join(assetDir, fileName);\n\n // Unreachable for the default namer; an independent second check, since an escape is a write to\n // an arbitrary path.\n if (path.dirname(path.resolve(absolutePath)) !== path.resolve(assetDir)) {\n throw new Error(`Refusing to write an attachment outside ${assetDir}: ${fileName}`);\n }\n\n assets.push({ relativePath, absolutePath, data: att.data });\n return { ...att, fileName: relativePath, data: undefined };\n });\n}\n\n/** Plans the writes without performing them; the publisher decides after validation. */\nfunction stageAttachments(\n state: ReviewState,\n outputFilePath: string,\n assetName: AssetNamer\n): { state: ReviewState; assets: PlannedAsset[] } {\n const assetDir = path.join(path.dirname(outputFilePath), ASSET_DIR_NAME);\n const assets: PlannedAsset[] = [];\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: stageAttachmentList(\n comment.attachments,\n comment.id,\n assetDir,\n assetName,\n assets\n ),\n ...(comment.replies\n ? {\n replies: comment.replies.map(reply => ({\n ...reply,\n attachments: stageAttachmentList(\n reply.attachments,\n `${comment.id}-r-${reply.id}`,\n assetDir,\n assetName,\n assets\n ),\n })),\n }\n : {}),\n })),\n }));\n\n return { state: { ...state, files: updatedFiles }, assets };\n}\n\n/**\n * Pure: touches no disk (`publishReview` writes). Built before validation, so an\n * unrepresentable value is refused first.\n *\n * @throws XmlIllegalCharacterError naming the comment/reply and field.\n * @throws ReviewXmlError `schema-invalid`, one violation per `details` line. A validator\n * that fails to load is deliberately not fatal: unvalidated XML after a stderr warning.\n */\nexport async function serializeReview(\n state: ReviewState,\n outputFilePath: string,\n options: SerializeOptions = {}\n): Promise<SerializedReview> {\n const staged = stageAttachments(state, outputFilePath, options.assetName ?? defaultAssetName);\n const xml = buildXml(staged.state);\n await validateAgainstSchema(xml);\n return { xml, assets: staged.assets };\n}\n\nasync function validateAgainstSchema(xml: string): Promise<void> {\n let validationResult: Awaited<ReturnType<typeof validateXML>>;\n try {\n validationResult = await validateXML({\n xml: [{ fileName: 'review.xml', contents: xml }],\n schema: [{ fileName: 'self-review-v3.xsd', contents: XSD_SCHEMA }],\n });\n } catch (error) {\n // Infrastructure failure (e.g. WASM load): losing a finished review is the worse outcome.\n if (error instanceof Error) {\n console.error(\n `[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`\n );\n } else {\n console.error(\n '[main] XML validation infrastructure failed - emitting XML without validation'\n );\n }\n return;\n }\n\n if (!validationResult.valid) {\n const details = (validationResult.errors || []).map(formatSchemaError);\n console.error('XML validation failed:');\n details.forEach(detail => console.error(` ${detail}`));\n throw new ReviewXmlError(\n 'schema-invalid',\n `Generated XML does not conform to schema${details.length ? `: ${details.join('; ')}` : ''}`,\n { details }\n );\n }\n}\n\nfunction formatSchemaError(err: unknown): string {\n if (typeof err === 'string') return err;\n if (err && typeof err === 'object') {\n const { message, loc } = err as { message?: unknown; loc?: { lineNumber?: unknown } | null };\n const text = typeof message === 'string' ? message : JSON.stringify(err);\n const line = loc && typeof loc === 'object' ? loc.lineNumber : undefined;\n return typeof line === 'number' ? `line ${line}: ${text}` : text;\n }\n return String(err);\n}\n\nfunction buildSourceAttributes(state: ReviewState): string {\n const source = state.source;\n if (source.type === 'git') {\n return ` git-diff-args=\"${attr(source.gitDiffArgs, { field: 'git-diff-args' })}\" repository=\"${attr(source.repository, { field: 'repository' })}\"`;\n }\n if (source.type === 'directory' || source.type === 'file') {\n return ` source-path=\"${attr(source.sourcePath, { field: 'source-path' })}\"`;\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=\"${attr(state.remoteUrl, { field: 'remote-url' })}\"`);\n }\n if (state.remoteBaseSha) {\n attrs.push(`remote-base-sha=\"${attr(state.remoteBaseSha, { field: 'remote-base-sha' })}\"`);\n }\n if (state.remoteHeadSha) {\n attrs.push(`remote-head-sha=\"${attr(state.remoteHeadSha, { field: 'remote-head-sha' })}\"`);\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=\"${attr(state.timestamp, { field: '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 const pathAttr = attr(file.path, { field: 'path', filePath: file.path });\n\n if (file.comments.length === 0) {\n // Self-closing tag for files with no comments\n lines.push(\n ` <file path=\"${pathAttr}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\" />`\n );\n } else {\n // Opening tag\n lines.push(\n ` <file path=\"${pathAttr}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\">`\n );\n\n // Comments\n for (const comment of file.comments) {\n lines.push(...buildCommentXml(comment, file.path));\n }\n\n // Closing tag\n lines.push(' </file>');\n }\n\n return lines;\n}\n\nfunction buildCommentXml(comment: ReviewComment, filePath: string): string[] {\n const lines: string[] = [];\n const attrs: string[] = [];\n const at = (field: string): XmlIllegalCharacterLocation => ({\n field,\n filePath,\n commentId: comment.id,\n });\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=\"${attr(comment.author, at('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=\"${attr(comment.remoteId, at('remote-id'))}\"`);\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>${text(comment.body, at('body'))}</body>`);\n\n // Category (required)\n lines.push(` <category>${text(comment.category, at('category'))}</category>`);\n\n // Suggestion\n if (comment.suggestion) {\n lines.push(' <suggestion>');\n lines.push(\n ` <original-code>${text(comment.suggestion.originalCode, at('original-code'))}</original-code>`\n );\n lines.push(\n ` <proposed-code>${text(comment.suggestion.proposedCode, at('proposed-code'))}</proposed-code>`\n );\n lines.push(' </suggestion>');\n }\n\n // Attachments\n lines.push(...buildAttachmentXml(comment.attachments, ' ', at('attachment')));\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, filePath, comment.id));\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(\n attachments: Attachment[] | undefined,\n indent: string,\n owner: XmlIllegalCharacterLocation\n): string[] {\n if (!attachments?.length) return [];\n\n return attachments.map(\n att =>\n `${indent}<attachment path=\"${attr(att.fileName, { ...owner, field: 'attachment path' })}\" media-type=\"${attr(att.mediaType, { ...owner, field: 'attachment media-type' })}\" />`\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, filePath: string, commentId: string): string[] {\n const attrs: string[] = [];\n const at = (field: string): XmlIllegalCharacterLocation => ({\n field,\n filePath,\n commentId,\n replyId: reply.id,\n });\n\n if (reply.author) {\n attrs.push(`author=\"${attr(reply.author, at('author'))}\"`);\n }\n if (reply.remoteId) {\n attrs.push(`remote-id=\"${attr(reply.remoteId, at('remote-id'))}\"`);\n }\n\n const attrStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n\n return [\n ` <reply${attrStr}>`,\n ` <body>${text(reply.body, at('body'))}</body>`,\n ...buildAttachmentXml(reply.attachments, ' ', at('attachment')),\n ' </reply>',\n ];\n}\n\n/** Escapes for element content, refusing what XML cannot carry (contract in xml-text.ts). */\nfunction text(value: string, location: XmlIllegalCharacterLocation): string {\n return escapeXmlText(checked(value, location));\n}\n\n/** Escape a value for an attribute, refusing one XML cannot carry. */\nfunction attr(value: string, location: XmlIllegalCharacterLocation): string {\n return escapeXmlAttribute(checked(value, location));\n}\n\nfunction checked(value: string, location: XmlIllegalCharacterLocation): string {\n const illegal = findIllegalXmlCharacter(value);\n if (illegal) throw new XmlIllegalCharacterError(illegal.codePoint, location);\n return value;\n}\n","// Typed failures of review XML reading and writing. Library code throws, hosts print\n// `.message` and choose their exit; nothing here calls `process.exit`.\n\nexport type ReviewXmlErrorCode =\n | 'read-failed'\n /** Over a safety budget (input-budgets.ts): byte size or attachment count. */\n | 'input-too-large'\n | 'parse-failed'\n /** Well-formed, but with no `<review>` root element. */\n | 'missing-root'\n /** The generated document does not validate against the v3 XSD. */\n | 'schema-invalid'\n | 'xml-illegal-character';\n\nexport class ReviewXmlError extends Error {\n readonly code: ReviewXmlErrorCode;\n readonly cause?: unknown;\n /** One rendered line per problem (e.g. a schema violation with its line number). */\n readonly details: readonly string[];\n\n constructor(\n code: ReviewXmlErrorCode,\n message: string,\n options?: { cause?: unknown; details?: readonly string[] }\n ) {\n // Assigned, not passed to `super`: the app's tsconfig lib lacks `ErrorOptions`.\n super(message);\n this.name = 'ReviewXmlError';\n this.code = code;\n this.details = options?.details ?? [];\n if (options?.cause !== undefined) this.cause = options.cause;\n }\n}\n\nexport interface XmlIllegalCharacterLocation {\n /** e.g. `body`, `original-code`, `path`, `author`. */\n field: string;\n filePath?: string;\n commentId?: string;\n replyId?: string;\n}\n\n/**\n * Thrown before anything is written: no escaped form exists, and dropping the character would\n * change the reviewer's text or a suggestion's code.\n */\nexport class XmlIllegalCharacterError extends ReviewXmlError {\n readonly codePoint: number;\n readonly field: string;\n readonly filePath?: string;\n readonly commentId?: string;\n readonly replyId?: string;\n\n constructor(codePoint: number, location: XmlIllegalCharacterLocation) {\n super('xml-illegal-character', describeIllegalCharacter(codePoint, location));\n this.name = 'XmlIllegalCharacterError';\n this.codePoint = codePoint;\n this.field = location.field;\n this.filePath = location.filePath;\n this.commentId = location.commentId;\n this.replyId = location.replyId;\n }\n}\n\nfunction describeIllegalCharacter(\n codePoint: number,\n location: XmlIllegalCharacterLocation\n): string {\n const hex = codePoint.toString(16).toUpperCase().padStart(4, '0');\n const where = [\n location.filePath !== undefined ? `file \"${location.filePath}\"` : null,\n location.commentId !== undefined ? `comment ${location.commentId}` : null,\n location.replyId !== undefined ? `reply ${location.replyId}` : null,\n ]\n .filter((part): part is string => part !== null)\n .join(', ');\n return (\n `Cannot write review XML: ${location.field}${where ? ` of ${where}` : ''} contains ` +\n `U+${hex}, which XML 1.0 cannot represent. Remove the character and save again.`\n );\n}\n","// The one encode/decode contract for review XML text. A conformant parser turns a raw CR(LF)\n// in content into LF (XML 1.0 s2.11) and a raw LF or TAB in an attribute into a space (s3.3.3),\n// so the serializer writes those as character references and the parser decodes them back,\n// once: a single pass over the five predefined entities and numeric references, never its own\n// output. Typed ` ` is written `&#13;` and returns as ` `. The library parser's\n// entity processing is off.\n\nexport interface IllegalXmlCharacter {\n codePoint: number;\n /** UTF-16 index of the offending code unit. */\n index: number;\n}\n\n/** XML 1.0 `Char`; everything else has no serialization, escaped or not. */\nfunction isLegalXmlCodePoint(cp: number): boolean {\n return (\n cp === 0x9 ||\n cp === 0xa ||\n cp === 0xd ||\n (cp >= 0x20 && cp <= 0xd7ff) ||\n (cp >= 0xe000 && cp <= 0xfffd) ||\n (cp >= 0x10000 && cp <= 0x10ffff)\n );\n}\n\n/**\n * The first character XML cannot carry, or `null`. A well-formed surrogate pair passes; a lone one\n * is reported.\n */\nexport function findIllegalXmlCharacter(str: string): IllegalXmlCharacter | null {\n for (let i = 0; i < str.length; i++) {\n const unit = str.charCodeAt(i);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const low = i + 1 < str.length ? str.charCodeAt(i + 1) : 0;\n if (low >= 0xdc00 && low <= 0xdfff) {\n i++;\n continue;\n }\n return { codePoint: unit, index: i };\n }\n if (!isLegalXmlCodePoint(unit)) {\n return { codePoint: unit, index: i };\n }\n }\n return null;\n}\n\n/** LF and TAB stay raw: content normalization preserves them. */\nexport function escapeXmlText(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/\\r/g, ' ');\n}\n\n/**\n * Also escapes LF and TAB, which attribute normalization turns into spaces (git filenames can\n * contain them).\n */\nexport function escapeXmlAttribute(str: string): string {\n return escapeXmlText(str).replace(/\\n/g, ' ').replace(/\\t/g, '	');\n}\n\nconst PREDEFINED: Record<string, string> = {\n lt: '<',\n gt: '>',\n amp: '&',\n quot: '\"',\n apos: \"'\",\n};\n\n/** A reference to a forbidden code point stays literal. */\nexport function decodeXmlEntities(raw: string): string {\n return raw.replace(\n /&(lt|gt|amp|quot|apos|#\\d{1,8}|#x[0-9a-fA-F]{1,8});/g,\n (match, ref: string) => {\n if (ref[0] !== '#') return PREDEFINED[ref];\n const cp = ref[1] === 'x' ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);\n return isLegalXmlCodePoint(cp) ? String.fromCodePoint(cp) : match;\n }\n );\n}\n","// Parse an XML review file back into ReviewComment[]. Text is lossless (no coercion, one\n// decoding pass, see xml-text.ts). An unreadable document throws ReviewXmlError; a comment\n// with an unusable anchor or suggestion is kept as file-level feedback and reported in\n// `importDiagnostics`.\n\nimport { XMLParser, XMLValidator } from 'fast-xml-parser';\nimport { readFileWithinBudgetSync } from './bounded-read';\nimport { formatBytes, MAX_RESUME_ATTACHMENTS, MAX_RESUME_XML_BYTES } from './input-budgets';\nimport {\n ReviewComment,\n Suggestion,\n LineRange,\n DiffSource,\n CommentSeverity,\n CommentConfidence,\n RemoteForge,\n Attachment,\n Reply,\n} from './types';\nimport { validateLineAnchor } from './anchor-validation';\nimport { ReviewXmlError } from './xml-errors';\nimport { decodeXmlEntities } from './xml-text';\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 /**\n * One line per comment downgraded to file-level feedback, with its suggestion text folded into\n * the body.\n */\n importDiagnostics: string[];\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\n/**\n * Sized before it is read, so an oversized document or a FIFO is refused unread.\n *\n * @throws ReviewXmlError `read-failed`, `input-too-large`, or what\n * {@link parseReviewXmlString} throws.\n */\nexport function parseReviewXml(xmlPath: string): ParsedReview {\n let read: ReturnType<typeof readFileWithinBudgetSync>;\n try {\n read = readFileWithinBudgetSync(xmlPath, MAX_RESUME_XML_BYTES);\n } catch (error) {\n throw new ReviewXmlError('read-failed', `Could not read ${xmlPath}: ${messageOf(error)}`, {\n cause: error,\n });\n }\n if (read.kind === 'not-regular') {\n throw new ReviewXmlError('read-failed', `Could not read ${xmlPath}: not a regular file`);\n }\n if (read.kind === 'too-large') {\n throw new ReviewXmlError(\n 'input-too-large',\n `Could not read ${xmlPath}: it is ${formatBytes(read.size)}, over the ` +\n `${formatBytes(MAX_RESUME_XML_BYTES)} limit for a review document`\n );\n }\n return parseReviewXmlString(read.content.toString('utf-8'));\n}\n\n/**\n * Namespace-blind by design: v1, v2 and v3 documents read identically.\n *\n * @throws ReviewXmlError `parse-failed`, `missing-root`, or `input-too-large`\n * (over `MAX_RESUME_ATTACHMENTS`).\n */\nexport function parseReviewXmlString(xmlContent: string): ParsedReview {\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n allowBooleanAttributes: true,\n trimValues: false,\n // Lossless: `00123`, `1e3` and `false` stay text, and decodeXmlEntities is the only decoding.\n parseTagValue: false,\n parseAttributeValue: false,\n processEntities: false,\n });\n\n // The parser is lenient (garbage still yields an object), so check well-formedness first for a\n // located message.\n const wellFormed = XMLValidator.validate(xmlContent);\n if (wellFormed !== true) {\n const { msg, line, col } = wellFormed.err;\n const where = col !== undefined ? `line ${line}, column ${col}` : `line ${line}`;\n throw new ReviewXmlError('parse-failed', `Invalid XML: ${msg} (${where})`);\n }\n\n let result: Record<string, unknown>;\n try {\n result = parser.parse(xmlContent) as Record<string, unknown>;\n } catch (error) {\n throw new ReviewXmlError('parse-failed', `Invalid XML: ${messageOf(error)}`, { cause: error });\n }\n\n const review = result.review as Record<string, unknown> | undefined;\n if (!review || typeof review !== 'object') {\n throw new ReviewXmlError('missing-root', 'Invalid XML: missing <review> root element');\n }\n\n const gitDiffArgs = attribute(review, '@_git-diff-args') ?? '';\n const source = parseSource(review);\n const comments: ReviewComment[] = [];\n const viewedFiles: string[] = [];\n const importDiagnostics: string[] = [];\n\n for (const file of toChildArray(review.file)) {\n // Only a missing attribute skips: the empty string is the review-level sentinel path and must\n // round-trip.\n const filePath = attribute(file, '@_path');\n if (filePath === undefined) continue;\n\n if (parseViewed(file['@_viewed'])) {\n viewedFiles.push(filePath);\n }\n\n toChildArray(file.comment).forEach((comment, index) => {\n comments.push(parseComment(comment, filePath, index + 1, importDiagnostics));\n });\n }\n\n // Bounds the reads one document can ask for; refuse rather than drop attachments.\n const attachmentCount = countAttachments(comments);\n if (attachmentCount > MAX_RESUME_ATTACHMENTS) {\n throw new ReviewXmlError(\n 'input-too-large',\n `The review document carries ${attachmentCount} attachments, over the limit of ` +\n `${MAX_RESUME_ATTACHMENTS} for a review document`\n );\n }\n\n return {\n comments,\n viewedFiles,\n gitDiffArgs,\n source,\n importDiagnostics,\n remoteUrl: attribute(review, '@_remote-url'),\n remoteBaseSha: attribute(review, '@_remote-base-sha'),\n remoteHeadSha: attribute(review, '@_remote-head-sha'),\n remoteForge: parseEnumAttribute(review['@_remote-forge'], REMOTE_FORGE_VALUES),\n };\n}\n\n/**\n * A comment whose anchor or suggestion cannot be honoured is downgraded to file-level\n * feedback, not dropped: its suggestion text is folded into the body so it is readable but\n * never an Apply target. The diagnostic names it by ordinal (and remote-id) within the file.\n */\nfunction parseComment(\n comment: Record<string, unknown>,\n filePath: string,\n ordinal: number,\n diagnostics: string[]\n): ReviewComment {\n const anchor = validateLineAnchor({\n oldLineStart: attribute(comment, '@_old-line-start'),\n oldLineEnd: attribute(comment, '@_old-line-end'),\n newLineStart: attribute(comment, '@_new-line-start'),\n newLineEnd: attribute(comment, '@_new-line-end'),\n });\n const lineRange: LineRange | null = anchor?.ok ? anchor.anchor : null;\n const suggestion = parseSuggestion(comment, lineRange);\n\n let body = text(comment, 'body') ?? '';\n let reason: string | null = null;\n if (anchor && !anchor.ok) {\n reason = anchor.reason;\n } else if (suggestion && !suggestion.ok) {\n reason = suggestion.reason;\n }\n if (reason !== null) {\n if (suggestion) body = foldSuggestionIntoBody(body, suggestion.text, reason);\n const remoteId = attribute(comment, '@_remote-id');\n const label =\n remoteId !== undefined ? `comment ${ordinal} (remote-id ${remoteId})` : `comment ${ordinal}`;\n diagnostics.push(`${filePath}: ${label} anchor ${reason}; kept as file-level feedback`);\n }\n\n const reviewComment: ReviewComment = {\n id: generateId(),\n filePath,\n lineRange,\n body,\n category: text(comment, 'category') ?? '',\n suggestion: suggestion?.ok ? suggestion.suggestion : null,\n author: optionalAuthor(comment),\n severity: parseEnumAttribute(comment['@_severity'], SEVERITY_VALUES),\n confidence: parseEnumAttribute(comment['@_confidence'], CONFIDENCE_VALUES),\n remoteId: attribute(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 return reviewComment;\n}\n\ntype SuggestionRead =\n | { ok: true; suggestion: Suggestion; text: SuggestionText }\n | { ok: false; reason: string; text: SuggestionText };\n\ninterface SuggestionText {\n original?: string;\n proposed?: string;\n}\n\n/**\n * Usable only with both code elements as plain text and a valid anchor (Apply replaces the anchored\n * lines). Other shapes report whatever text they carried.\n */\nfunction parseSuggestion(\n comment: Record<string, unknown>,\n lineRange: LineRange | null\n): SuggestionRead | null {\n const raw = comment.suggestion;\n if (raw === undefined || raw === null) return null;\n\n const node = typeof raw === 'object' ? (raw as Record<string, unknown>) : {};\n const original = text(node, 'original-code');\n const proposed = text(node, 'proposed-code');\n const text_: SuggestionText = { original, proposed };\n\n if ('original-code' in node && original === undefined) {\n return { ok: false, reason: 'suggestion original-code is not plain text', text: text_ };\n }\n if ('proposed-code' in node && proposed === undefined) {\n return { ok: false, reason: 'suggestion proposed-code is not plain text', text: text_ };\n }\n if (original === undefined || proposed === undefined) {\n return {\n ok: false,\n reason: 'suggestion is missing original-code or proposed-code',\n text: text_,\n };\n }\n if (lineRange === null) {\n return { ok: false, reason: 'suggestion has no line anchor', text: text_ };\n }\n return { ok: true, suggestion: { originalCode: original, proposedCode: proposed }, text: text_ };\n}\n\n/**\n * The fence is one backtick longer than the longest run in the code, so nested fences render\n * intact.\n */\nfunction foldSuggestionIntoBody(body: string, code: SuggestionText, reason: string): string {\n const parts = [body, '', `_Imported suggestion could not be anchored (${reason})._`];\n if (code.original !== undefined) parts.push('Original:', ...fenced(code.original));\n if (code.proposed !== undefined) parts.push('Proposed:', ...fenced(code.proposed));\n return parts.join('\\n');\n}\n\nfunction fenced(code: string): string[] {\n const longestRun = Math.max(0, ...(code.match(/`+/g) ?? []).map(run => run.length));\n const fence = '`'.repeat(Math.max(3, longestRun + 1));\n return [fence, code, fence];\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>(raw: unknown, allowed: readonly T[]): T | undefined {\n if (raw === undefined || raw === null) return undefined;\n const value = decodeXmlEntities(String(raw));\n return allowed.includes(value as T) ? (value as T) : undefined;\n}\n\n/** Decoded text, or undefined when absent; the empty string is a value. */\nfunction attribute(node: Record<string, unknown>, key: string): string | undefined {\n const raw = node[key];\n if (raw === undefined || raw === null) return undefined;\n // A boolean attribute (`<file viewed>`) parses as `true`.\n return decodeXmlEntities(typeof raw === 'string' ? raw : String(raw));\n}\n\n/** Decoded child text, or undefined when absent or not plain text. */\nfunction text(node: Record<string, unknown>, key: string): string | undefined {\n const raw = node[key];\n if (typeof raw === 'string') return decodeXmlEntities(raw);\n return undefined;\n}\n\n/** Absent means human, so an empty author reads as absent. */\nfunction optionalAuthor(node: Record<string, unknown>): string | undefined {\n const author = attribute(node, '@_author');\n return author === undefined || author === '' ? undefined : author;\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 = attribute(review, '@_source-path');\n if (sourcePath) {\n return { type: 'directory', sourcePath };\n }\n\n const gitDiffArgs = attribute(review, '@_git-diff-args');\n const repository = attribute(review, '@_repository');\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: gitDiffArgs ?? '',\n repository: repository ?? '',\n };\n }\n\n return { type: 'welcome' };\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: attribute(att, '@_path') ?? '',\n mediaType: attribute(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: text(node, 'body') ?? '',\n author: optionalAuthor(node),\n remoteId: attribute(node, '@_remote-id'),\n };\n\n const attachments = parseAttachments(node, id);\n if (attachments) reply.attachments = attachments;\n\n return reply;\n });\n}\n\n/** Attachment references across every comment and reply. */\nfunction countAttachments(comments: ReviewComment[]): number {\n let count = 0;\n for (const comment of comments) {\n count += comment.attachments?.length ?? 0;\n for (const reply of comment.replies ?? []) {\n count += reply.attachments?.length ?? 0;\n }\n }\n return count;\n}\n\nfunction messageOf(error: unknown): string {\n if (error instanceof Error) return error.message;\n return typeof error === 'string' ? error : JSON.stringify(error);\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// Line-anchor validation shared by the resume importer and Apply, both untrusted input.\n\nimport type { LineRange } from './types';\n\nexport type AnchorSide = 'old' | 'new';\n\nexport interface LineAnchor {\n side: AnchorSide;\n start: number;\n end: number;\n}\n\nexport type AnchorCheck = { ok: true; anchor: LineAnchor } | { ok: false; reason: string };\n\n/** The four raw line fields; `unknown` because XML gives strings and JSON gives anything. */\nexport interface AnchorFields {\n oldLineStart?: unknown;\n oldLineEnd?: unknown;\n newLineStart?: unknown;\n newLineEnd?: unknown;\n}\n\n/**\n * Returns `null` when no field is present (a file-level comment), else the first\n * rule broken: positive safe integers (digit strings accepted), exactly one\n * complete side, start <= end, end <= `maxLine`. `reason` is embedded in diagnostics.\n */\nexport function validateLineAnchor(fields: AnchorFields, maxLine?: number): AnchorCheck | null {\n const old = sideFields('old', fields.oldLineStart, fields.oldLineEnd);\n const next = sideFields('new', fields.newLineStart, fields.newLineEnd);\n\n if (!old.present && !next.present) return null;\n if (old.present && next.present) {\n return { ok: false, reason: 'carries both old and new line ranges' };\n }\n\n const side = old.present ? old : next;\n if (side.start === undefined || side.end === undefined) {\n return { ok: false, reason: `${side.name}-line range is incomplete (start and end required)` };\n }\n\n const start = toPositiveSafeInteger(side.start);\n if (start === null) {\n return {\n ok: false,\n reason: `${side.name}-line-start is not a positive integer (${describe(side.start)})`,\n };\n }\n const end = toPositiveSafeInteger(side.end);\n if (end === null) {\n return {\n ok: false,\n reason: `${side.name}-line-end is not a positive integer (${describe(side.end)})`,\n };\n }\n\n return checkRange({ side: side.name, start, end }, maxLine);\n}\n\n/**\n * Same rules as {@link validateLineAnchor} for a typed range; `NaN`, `0`, `1.5` and `Infinity` are\n * still numbers.\n */\nexport function validateLineRange(range: LineRange, maxLine?: number): AnchorCheck {\n const start = toPositiveSafeInteger(range.start);\n if (start === null) {\n return {\n ok: false,\n reason: `${range.side}-line-start is not a positive integer (${describe(range.start)})`,\n };\n }\n const end = toPositiveSafeInteger(range.end);\n if (end === null) {\n return {\n ok: false,\n reason: `${range.side}-line-end is not a positive integer (${describe(range.end)})`,\n };\n }\n return checkRange({ side: range.side, start, end }, maxLine);\n}\n\nfunction checkRange(anchor: LineAnchor, maxLine: number | undefined): AnchorCheck {\n if (anchor.start > anchor.end) {\n return {\n ok: false,\n reason: `${anchor.side}-line range is reversed (${anchor.start} > ${anchor.end})`,\n };\n }\n if (maxLine !== undefined && anchor.end > maxLine) {\n return {\n ok: false,\n reason: `${anchor.side}-line range ends beyond line ${maxLine} (${anchor.end})`,\n };\n }\n return { ok: true, anchor };\n}\n\ninterface SideFields {\n name: AnchorSide;\n present: boolean;\n start: unknown;\n end: unknown;\n}\n\nfunction sideFields(name: AnchorSide, start: unknown, end: unknown): SideFields {\n const s = isAbsent(start) ? undefined : start;\n const e = isAbsent(end) ? undefined : end;\n return { name, present: s !== undefined || e !== undefined, start: s, end: e };\n}\n\nfunction isAbsent(value: unknown): boolean {\n return value === undefined || value === null;\n}\n\n/**\n * A positive safe integer from a number or decimal digit string; anything else (`1e3`, `NaN`,\n * booleans) is `null`.\n */\nfunction toPositiveSafeInteger(value: unknown): number | null {\n let n: number;\n if (typeof value === 'number') {\n n = value;\n } else if (typeof value === 'string' && /^\\d+$/.test(value)) {\n n = Number(value);\n } else {\n return null;\n }\n return Number.isSafeInteger(n) && n > 0 ? n : null;\n}\n\nfunction describe(value: unknown): string {\n return typeof value === 'string' ? JSON.stringify(value) : String(value);\n}\n","// packages/core/src/review-publisher.ts\n// The one way a review document reaches the disk. Order is the contract: build and validate,\n// stage new assets, then rename the XML into place; a failure before the rename leaves the old files.\n\nimport * as path from 'node:path';\nimport { ReviewXmlError, XmlIllegalCharacterError } from './xml-errors';\nimport { checkWritability } from './fs-utils';\nimport { ASSET_DIR_NAME, serializeReview } from './xml-serializer';\nimport type { PlannedAsset } from './xml-serializer';\nimport {\n SafeFsError,\n atomicReplace,\n defaultRandomName,\n guarded,\n inspectReplaceTarget,\n lstatOrNull,\n nodeFsLayer,\n toSafeFsError,\n unlinkQuietly,\n writeExclusiveNoFollow,\n} from './safe-fs';\nimport type { FsLayer, SafeFsErrorCode } from './safe-fs';\nimport { AttachmentRelocationError, relocateAttachments } from './attachment-origins';\nimport type { AttachmentOrigins } from './attachment-origins';\nimport type { ReviewState } from './types';\n\nexport type ReviewPublishErrorCode =\n /** `details` lists each XSD violation. */\n | 'validation-failed'\n | 'xml-illegal-character'\n | 'output-is-directory'\n | 'permission-denied'\n | 'no-space'\n /** A link where the publisher would write, or an inherited path resolving outside its base. */\n | 'unsafe-link'\n /** A hard-linked output, or a non-directory or foreign-owned asset directory. */\n | 'unsupported-target'\n /** A resumed attachment that must move cannot be read where its document put it. */\n | 'attachment-unavailable'\n | 'io-error';\n\nexport class ReviewPublishError extends Error {\n readonly code: ReviewPublishErrorCode;\n readonly path: string;\n /** One rendered line per problem; empty when the message is all there is. */\n readonly details: readonly string[];\n readonly cause?: unknown;\n\n constructor(\n code: ReviewPublishErrorCode,\n path: string,\n message: string,\n options: { details?: readonly string[]; cause?: unknown } = {}\n ) {\n super(message);\n this.name = 'ReviewPublishError';\n this.code = code;\n this.path = path;\n this.details = options.details ?? [];\n if (options.cause !== undefined) this.cause = options.cause;\n }\n}\n\n/** `inherited` paths come from something a repository can commit, so they must stay inside `baseDir`. */\nexport type ReviewOutputOrigin = 'explicit' | 'inherited';\n\n/** Resolved by `resolveOutputTarget` in `startup.ts`. */\nexport type ReviewOutputTarget =\n | { path: string; origin: 'explicit' }\n | { path: string; origin: 'inherited'; baseDir: string };\n\ninterface PublishReviewCommonOptions {\n fs?: FsLayer;\n randomName?: () => string;\n /** Imported attachments whose origin is elsewhere are copied beside the output (`relocateAttachments`). */\n attachmentOrigins?: AttachmentOrigins;\n}\n\nexport type PublishReviewOptions = PublishReviewCommonOptions &\n (\n | { outputOrigin: 'explicit' }\n | {\n outputOrigin: 'inherited';\n baseDir: string;\n }\n );\n\nexport interface PublishReviewResult {\n outputPath: string;\n /** The attachment files this publication created. */\n assetPaths: string[];\n}\n\n/** @throws ReviewPublishError for every failure, document or filesystem. */\nexport async function publishReview(\n state: ReviewState,\n outputPath: string,\n options: PublishReviewOptions\n): Promise<PublishReviewResult> {\n const fs = options.fs ?? nodeFsLayer;\n const randomName = options.randomName ?? defaultRandomName;\n const target = path.resolve(outputPath);\n const outputDir = path.dirname(target);\n const assetDir = path.join(outputDir, ASSET_DIR_NAME);\n\n // 1. The document and the output policy, from reads alone.\n let xml: string;\n let assets: PlannedAsset[];\n try {\n const publishable = options.attachmentOrigins\n ? await relocateAttachments(state, options.attachmentOrigins, target)\n : state;\n const namer = uniqueAssetNamer(assetDir, fs, randomName);\n ({ xml, assets } = await serializeReview(publishable, target, { assetName: namer }));\n checkOutputPolicy(target, options, fs);\n } catch (error) {\n throw toPublishError(error, target);\n }\n\n // 2. Stage the new blobs; every file created here is removed on failure.\n const staged: string[] = [];\n try {\n if (assets.length > 0) {\n ensureAssetDirectory(outputDir, fs);\n for (const asset of assets) {\n writeExclusiveNoFollow(asset.absolutePath, new Uint8Array(asset.data), { fs });\n staged.push(asset.absolutePath);\n }\n }\n\n // 3. The commit point.\n atomicReplace(target, Buffer.from(xml + '\\n', 'utf-8'), {\n fs,\n preserveMode: true,\n randomName,\n });\n } catch (error) {\n for (const file of staged) unlinkQuietly(file, fs);\n throw toPublishError(error, target);\n }\n\n if (staged.length > 0) {\n console.error(`[main] Wrote ${staged.length} attachment file(s) to ${assetDir}`);\n }\n return { outputPath: target, assetPaths: staged };\n}\n\n/** The error `publishReview` would throw for the path as it stands; advisory, since the disk can change. */\nexport function inspectOutputPath(\n outputPath: string,\n options: PublishReviewOptions\n): ReviewPublishError | null {\n const fs = options.fs ?? nodeFsLayer;\n const target = path.resolve(outputPath);\n try {\n checkOutputPolicy(target, options, fs);\n } catch (error) {\n return toPublishError(error, target);\n }\n if (!checkWritability(target)) {\n const dir = path.dirname(target);\n return new ReviewPublishError(\n 'permission-denied',\n target,\n `Cannot write ${target}: ${dir} does not exist or is not writable`\n );\n }\n return null;\n}\n\n/** A file at a drawn name means another draw; a link there is a trap and is refused. */\nfunction uniqueAssetNamer(assetDir: string, fs: FsLayer, randomName: () => string) {\n const chosen = new Set<string>();\n return (idPrefix: string, _index: number, ext: string): string => {\n for (let attempt = 0; attempt < 16; attempt++) {\n const name = `${idPrefix}-${randomName()}.${ext}`;\n if (chosen.has(name)) continue;\n const candidate = path.join(assetDir, name);\n const stats = lstatOrNull(candidate, fs);\n if (stats?.isSymbolicLink()) {\n throw new SafeFsError(\n 'unsafe-link',\n candidate,\n `Refusing to write attachment ${candidate}: a symbolic link already sits at that name`\n );\n }\n if (stats === null) {\n chosen.add(name);\n return name;\n }\n }\n throw new SafeFsError(\n 'io-error',\n assetDir,\n `Could not find a free attachment name under ${assetDir} after 16 attempts`\n );\n };\n}\n\n/** The leaf and, for an inherited path, the containment checks. Reads only. */\nfunction checkOutputPolicy(target: string, options: PublishReviewOptions, fs: FsLayer): void {\n if (options.outputOrigin === 'inherited') {\n const base = path.resolve(options.baseDir);\n const outputDir = path.dirname(target);\n const physicalBase = guarded(base, 'resolve', () => fs.realpathSync(base));\n const physicalDir = guarded(outputDir, 'resolve', () => fs.realpathSync(outputDir));\n const rel = path.relative(physicalBase, physicalDir);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new SafeFsError(\n 'unsafe-link',\n target,\n `Refusing to write ${target}: the configured output directory resolves to ${physicalDir}, outside ${physicalBase}. ` +\n 'Choose the output path explicitly to save there.'\n );\n }\n }\n // Checked now as well as at write time, so no asset is staged for a document that cannot be published.\n inspectReplaceTarget(target, fs);\n}\n\n/** A real directory this user owns. `mkdir` is not recursive: a missing output directory fails the save anyway. */\nfunction ensureAssetDirectory(outputDir: string, fs: FsLayer): void {\n const assetDir = path.join(outputDir, ASSET_DIR_NAME);\n let stats = lstatOrNull(assetDir, fs);\n if (stats === null) {\n guarded(assetDir, 'create attachment directory', () => fs.mkdirSync(assetDir, 0o755));\n stats = guarded(assetDir, 'inspect', () => fs.lstatSync(assetDir));\n }\n\n if (stats.isSymbolicLink()) {\n throw new SafeFsError(\n 'unsafe-link',\n assetDir,\n `Refusing to write attachments through ${assetDir}: it is a symbolic link`\n );\n }\n if (!stats.isDirectory()) {\n throw new SafeFsError(\n 'unsupported-target',\n assetDir,\n `Cannot write attachments: ${assetDir} exists but is not a directory`\n );\n }\n const uid = typeof process.getuid === 'function' ? process.getuid() : undefined;\n if (uid !== undefined && stats.uid !== uid) {\n throw new SafeFsError(\n 'unsupported-target',\n assetDir,\n `Refusing to write attachments into ${assetDir}: it is owned by another user`\n );\n }\n}\n\nconst SAFE_FS_TO_PUBLISH: Partial<Record<SafeFsErrorCode, ReviewPublishErrorCode>> = {\n 'output-is-directory': 'output-is-directory',\n 'permission-denied': 'permission-denied',\n 'no-space': 'no-space',\n 'unsafe-link': 'unsafe-link',\n 'unsupported-target': 'unsupported-target',\n};\n\nfunction toPublishError(error: unknown, target: string): ReviewPublishError {\n if (error instanceof ReviewPublishError) return error;\n if (error instanceof AttachmentRelocationError) {\n return new ReviewPublishError('attachment-unavailable', error.origin, error.message, {\n details: [error.message],\n cause: error,\n });\n }\n if (error instanceof XmlIllegalCharacterError) {\n return new ReviewPublishError('xml-illegal-character', target, error.message, {\n details: [error.message],\n cause: error,\n });\n }\n if (error instanceof ReviewXmlError) {\n return new ReviewPublishError('validation-failed', target, error.message, {\n details: error.details,\n cause: error,\n });\n }\n const fsError = toSafeFsError(error, target, 'write');\n const code = SAFE_FS_TO_PUBLISH[fsError.code] ?? 'io-error';\n return new ReviewPublishError(code, fsError.path, fsError.message, {\n cause: fsError.cause ?? fsError,\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","// packages/core/src/safe-fs.ts\n// No-follow filesystem primitives every core reader and writer goes through. Linux and macOS only:\n// Node does not define `O_NOFOLLOW` on Windows.\n\nimport * as nodeFs from 'node:fs';\nimport { randomBytes } from 'node:crypto';\nimport * as path from 'node:path';\nimport { READ_FLAGS, readDescriptorWithinBudget } from './bounded-read';\nimport { formatBytes } from './input-budgets';\n\nexport type SafeFsErrorCode =\n | 'output-is-directory'\n /** EACCES, EPERM or EROFS. */\n | 'permission-denied'\n /** ENOSPC or EDQUOT. */\n | 'no-space'\n /** A symlink sits where this module would read, create or replace a file, or on the way to it. */\n | 'unsafe-link'\n /** Exists, but replacing it would change semantics: hard-linked, not a regular file, or foreign-owned. */\n | 'unsupported-target'\n /** The file at the target is not the one the caller checked. */\n | 'identity-changed'\n /** ENOENT or ENOTDIR. */\n | 'not-found'\n /** A FIFO, socket or device. */\n | 'not-regular'\n | 'too-large'\n | 'io-error';\n\nexport class SafeFsError extends Error {\n readonly code: SafeFsErrorCode;\n readonly path: string;\n readonly cause?: unknown;\n\n constructor(code: SafeFsErrorCode, path: string, message: string, cause?: unknown) {\n super(message);\n this.name = 'SafeFsError';\n this.code = code;\n this.path = path;\n if (cause !== undefined) this.cause = cause;\n }\n}\n\n/** The subset of `fs` used here, synchronous so a test can inject a failure at an exact step. */\nexport interface FsLayer {\n openSync(path: string, flags: number, mode?: number): number;\n /** May write fewer bytes than given, as the real one may. */\n writeSync(fd: number, buffer: Uint8Array): number;\n fsyncSync(fd: number): void;\n fchmodSync(fd: number, mode: number): void;\n fchownSync(fd: number, uid: number, gid: number): void;\n closeSync(fd: number): void;\n renameSync(from: string, to: string): void;\n unlinkSync(path: string): void;\n lstatSync(path: string): nodeFs.Stats;\n fstatSync(fd: number): nodeFs.Stats;\n readFileSync(fd: number): Buffer;\n mkdirSync(path: string, mode: number): void;\n realpathSync(path: string): string;\n}\n\nexport const nodeFsLayer: FsLayer = {\n openSync: (p, flags, mode) => nodeFs.openSync(p, flags, mode),\n writeSync: (fd, buffer) => nodeFs.writeSync(fd, buffer),\n fsyncSync: fd => nodeFs.fsyncSync(fd),\n fchmodSync: (fd, mode) => nodeFs.fchmodSync(fd, mode),\n fchownSync: (fd, uid, gid) => nodeFs.fchownSync(fd, uid, gid),\n closeSync: fd => nodeFs.closeSync(fd),\n renameSync: (from, to) => nodeFs.renameSync(from, to),\n unlinkSync: p => nodeFs.unlinkSync(p),\n lstatSync: p => nodeFs.lstatSync(p),\n fstatSync: fd => nodeFs.fstatSync(fd),\n readFileSync: fd => nodeFs.readFileSync(fd),\n mkdirSync: (p, mode) => {\n nodeFs.mkdirSync(p, { mode });\n },\n realpathSync: p => nodeFs.realpathSync(p),\n};\n\nconst { O_WRONLY, O_CREAT, O_EXCL, O_NOFOLLOW, O_RDONLY } = nodeFs.constants;\n\nexport interface FileIdentity {\n dev: number;\n ino: number;\n /** Permission bits only (`mode & 0o7777`). */\n mode: number;\n nlink: number;\n size: number;\n mtimeMs: number;\n uid: number;\n gid: number;\n}\n\nexport function snapshotIdentity(stats: nodeFs.Stats): FileIdentity {\n return {\n dev: stats.dev,\n ino: stats.ino,\n mode: stats.mode & 0o7777,\n nlink: stats.nlink,\n size: stats.size,\n mtimeMs: stats.mtimeMs,\n uid: stats.uid,\n gid: stats.gid,\n };\n}\n\nexport function sameFile(a: FileIdentity, b: FileIdentity): boolean {\n return a.dev === b.dev && a.ino === b.ino;\n}\n\n/** A rewrite within the filesystem's timestamp granularity passes; callers compare content too. */\nexport function sameStamp(a: FileIdentity, b: FileIdentity): boolean {\n return a.size === b.size && a.mtimeMs === b.mtimeMs;\n}\n\nconst ERRNO_CODES = new Map<string, SafeFsErrorCode>([\n ['ENOENT', 'not-found'],\n ['ENOTDIR', 'not-found'],\n ['EISDIR', 'output-is-directory'],\n ['EACCES', 'permission-denied'],\n ['EPERM', 'permission-denied'],\n ['EROFS', 'permission-denied'],\n ['ENOSPC', 'no-space'],\n ['EDQUOT', 'no-space'],\n ['ELOOP', 'unsafe-link'],\n]);\n\n/** The code a caller maps to its own reason; anything unknown is `io-error`. */\nexport function classifyFsError(error: unknown): SafeFsErrorCode {\n return ERRNO_CODES.get(errnoOf(error) ?? '') ?? 'io-error';\n}\n\nexport function errnoOf(error: unknown): string | undefined {\n if (error && typeof error === 'object' && 'code' in error) {\n const code = (error as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n }\n return undefined;\n}\n\n/** Wrap a raw fs failure, passing a `SafeFsError` through untouched. */\nexport function toSafeFsError(error: unknown, filePath: string, action: string): SafeFsError {\n if (error instanceof SafeFsError) return error;\n const reason = error instanceof Error ? error.message : String(error);\n return new SafeFsError(\n classifyFsError(error),\n filePath,\n `Cannot ${action} ${filePath}: ${reason}`,\n error\n );\n}\n\nexport function guarded<T>(filePath: string, action: string, fn: () => T): T {\n try {\n return fn();\n } catch (error) {\n throw toSafeFsError(error, filePath, action);\n }\n}\n\n/** Best effort: a failure here is not worth reporting over the one in flight. */\nfunction quietly(fn: () => void): void {\n try {\n fn();\n } catch {\n // Ignored.\n }\n}\n\nexport function lstatOrNull(filePath: string, fs: FsLayer = nodeFsLayer): nodeFs.Stats | null {\n try {\n return fs.lstatSync(filePath);\n } catch (error) {\n if (errnoOf(error) === 'ENOENT') return null;\n throw toSafeFsError(error, filePath, 'inspect');\n }\n}\n\n/**\n * Refuse a `rel` whose directories under `root` include a symlink. The leaf is the caller's\n * policy, and a missing component ends the walk: nothing can be linked where nothing is.\n */\nexport function assertNoSymlinkAncestors(root: string, rel: string, fs: FsLayer = nodeFsLayer) {\n const normalized = path.normalize(rel);\n if (\n path.isAbsolute(normalized) ||\n normalized === '..' ||\n normalized.startsWith(`..${path.sep}`)\n ) {\n throw new SafeFsError(\n 'unsupported-target',\n path.join(root, rel),\n `Refusing ${rel}: it does not stay under ${root}`\n );\n }\n let current = root;\n for (const segment of path.dirname(normalized).split(path.sep)) {\n if (!segment || segment === '.') continue;\n current = path.join(current, segment);\n const stats = lstatOrNull(current, fs);\n if (stats === null) return;\n if (stats.isSymbolicLink()) {\n throw new SafeFsError(\n 'unsafe-link',\n current,\n `Refusing to go through ${current}: it is a symbolic link`\n );\n }\n }\n}\n\n/**\n * No link on the way or at the leaf, no FIFO blocking, regular files only. The walk and the open are\n * separate syscalls, so afterwards the name must still resolve under `root` to the opened inode.\n */\nexport function openContainedFile(\n root: string,\n rel: string,\n fs: FsLayer = nodeFsLayer\n): { fd: number; stats: nodeFs.Stats } {\n assertNoSymlinkAncestors(root, rel, fs);\n const target = path.join(root, rel);\n const fd = guarded(target, 'open', () => fs.openSync(target, READ_FLAGS | O_NOFOLLOW));\n try {\n const stats = fs.fstatSync(fd);\n if (stats.isDirectory()) {\n throw new SafeFsError('output-is-directory', target, `${target} is a directory`);\n }\n if (!stats.isFile()) {\n throw new SafeFsError('not-regular', target, `${target} is not a regular file`);\n }\n if (\n !sameFile(fs.lstatSync(target), stats) ||\n fs.realpathSync(target) !== path.join(fs.realpathSync(root), rel)\n ) {\n throw new SafeFsError('unsafe-link', target, `${target} changed while it was being opened`);\n }\n return { fd, stats };\n } catch (error) {\n quietly(() => fs.closeSync(fd));\n throw toSafeFsError(error, target, 'open');\n }\n}\n\n/** Read the whole of a file {@link openContainedFile} accepts, if it fits `maxBytes`. */\nexport async function readContainedFile(\n root: string,\n rel: string,\n maxBytes: number\n): Promise<Buffer> {\n const { fd, stats } = openContainedFile(root, rel);\n const target = path.join(root, rel);\n try {\n const read = await readDescriptorWithinBudget(fd, stats, maxBytes);\n if (read.kind === 'ok') return read.content;\n throw new SafeFsError(\n 'too-large',\n target,\n `The file is ${formatBytes(read.size)}, over the ${formatBytes(maxBytes)} limit`\n );\n } catch (error) {\n throw toSafeFsError(error, target, 'read');\n } finally {\n nodeFs.closeSync(fd);\n }\n}\n\nexport interface WriteExclusiveOptions {\n /** Masked by the umask. Default 0o666. */\n mode?: number;\n /** Applied after creation, bypassing the umask. */\n exactMode?: number;\n /** Applied after creation; failing to is `unsupported-target` and removes the file. */\n exactOwner?: { uid: number; gid: number };\n fs?: FsLayer;\n}\n\n/**\n * Create `filePath`, which must not exist, write every byte and sync. A symlink at the path,\n * dangling or not, is `unsafe-link`. Any failure after creation removes the file again.\n */\nexport function writeExclusiveNoFollow(\n filePath: string,\n bytes: Uint8Array,\n options: WriteExclusiveOptions = {}\n): FileIdentity {\n const fs = options.fs ?? nodeFsLayer;\n let fd: number;\n try {\n fd = fs.openSync(filePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, options.mode ?? 0o666);\n } catch (error) {\n if (errnoOf(error) === 'EEXIST' && isSymlink(filePath, fs)) {\n throw new SafeFsError(\n 'unsafe-link',\n filePath,\n `Refusing to write ${filePath}: a symbolic link already sits at that name`\n );\n }\n throw toSafeFsError(error, filePath, 'create');\n }\n\n try {\n let offset = 0;\n while (offset < bytes.length) {\n const written = fs.writeSync(fd, bytes.subarray(offset));\n if (written <= 0) {\n throw new SafeFsError(\n 'io-error',\n filePath,\n `Cannot write ${filePath}: write made no progress`\n );\n }\n offset += written;\n }\n if (options.exactMode !== undefined) fs.fchmodSync(fd, options.exactMode);\n if (options.exactOwner !== undefined) {\n const { uid, gid } = options.exactOwner;\n try {\n fs.fchownSync(fd, uid, gid);\n } catch (error) {\n throw new SafeFsError(\n 'unsupported-target',\n filePath,\n `Cannot give ${filePath} its owner (uid ${uid}, gid ${gid})`,\n error\n );\n }\n }\n fs.fsyncSync(fd);\n const identity = snapshotIdentity(fs.fstatSync(fd));\n fs.closeSync(fd);\n return identity;\n } catch (error) {\n quietly(() => fs.closeSync(fd));\n unlinkQuietly(filePath, fs);\n throw toSafeFsError(error, filePath, 'write');\n }\n}\n\nexport interface AtomicReplaceOptions {\n /** Give the replacement the replaced file's permission bits. */\n preserveMode?: boolean;\n /**\n * Give the replacement the replaced file's owner (`rename` swaps the inode). An owner this\n * process may not restore with `fchown` is refused as `unsupported-target` before any write.\n */\n preserveOwner?: boolean;\n /** Refused as `identity-changed` when the target is no longer this file (dev/ino). */\n expectedIdentity?: FileIdentity;\n /** With `expectedIdentity`: also refuse a same-inode rewrite (size or mtime moved). */\n expectUnmodified?: boolean;\n fs?: FsLayer;\n randomName?: () => string;\n}\n\nexport interface AtomicReplaceResult {\n identity: FileIdentity;\n /** Whether a file existed at `target` before. */\n replaced: boolean;\n}\n\n/**\n * Replace or create `target` in one `rename` from a same-directory temp file. The `lstat`→`rename`\n * window is accepted: `rename` never follows a link and nothing before it creates through one.\n */\nexport function atomicReplace(\n target: string,\n bytes: Uint8Array,\n options: AtomicReplaceOptions = {}\n): AtomicReplaceResult {\n const fs = options.fs ?? nodeFsLayer;\n const existing = inspectReplaceTarget(target, fs);\n const expected = options.expectedIdentity;\n if (expected && (!existing || !sameFile(existing, expected))) {\n throw new SafeFsError(\n 'identity-changed',\n target,\n `Refusing to replace ${target}: it is no longer the file that was checked`\n );\n }\n if (expected && options.expectUnmodified && existing && !sameStamp(existing, expected)) {\n throw new SafeFsError(\n 'identity-changed',\n target,\n `Refusing to replace ${target}: it was modified after it was checked`\n );\n }\n const exactOwner =\n options.preserveOwner && existing ? ownerToRestore(target, existing) : undefined;\n\n const random = options.randomName ?? defaultRandomName;\n const temp = path.join(path.dirname(target), `.${path.basename(target)}.${random()}.tmp`);\n try {\n writeExclusiveNoFollow(temp, bytes, {\n fs,\n exactMode: options.preserveMode && existing ? existing.mode : undefined,\n exactOwner,\n });\n } catch (error) {\n // Report the target, not the temp name, unless a link was planted at the temp name.\n if (error instanceof SafeFsError && error.code === 'unsupported-target') {\n throw new SafeFsError(\n 'unsupported-target',\n target,\n `Refusing to replace ${target}: its owner could not be preserved on the replacement`,\n error.cause\n );\n }\n if (error instanceof SafeFsError && error.code !== 'unsafe-link' && error.cause !== undefined) {\n throw toSafeFsError(error.cause, target, 'write');\n }\n throw error;\n }\n return { identity: finishReplace(temp, target, fs), replaced: existing !== null };\n}\n\n/** Undefined when the new file already gets the right owner; only root may give one away. */\nfunction ownerToRestore(\n target: string,\n existing: FileIdentity\n): { uid: number; gid: number } | undefined {\n if (typeof process.geteuid !== 'function' || typeof process.getegid !== 'function')\n return undefined;\n const me = { uid: process.geteuid(), gid: process.getegid() };\n if (existing.uid === me.uid && existing.gid === me.gid) return undefined;\n if (existing.uid !== me.uid && me.uid !== 0) {\n throw new SafeFsError(\n 'unsupported-target',\n target,\n `Refusing to replace ${target}: it is owned by another user (uid ${existing.uid}), and replacing it would change its owner`\n );\n }\n return { uid: existing.uid, gid: existing.gid };\n}\n\nfunction finishReplace(temp: string, target: string, fs: FsLayer): FileIdentity {\n try {\n fs.renameSync(temp, target);\n } catch (error) {\n unlinkQuietly(temp, fs);\n throw toSafeFsError(error, target, 'replace');\n }\n syncDirectoryQuietly(path.dirname(target), fs);\n return guarded(target, 'inspect', () => snapshotIdentity(fs.lstatSync(target)));\n}\n\n/** `lstat` a replace target under the policy of {@link atomicReplace}; null when absent. */\nexport function inspectReplaceTarget(\n target: string,\n fs: FsLayer = nodeFsLayer\n): FileIdentity | null {\n const stats = lstatOrNull(target, fs);\n if (stats === null) return null;\n if (stats.isSymbolicLink()) {\n throw new SafeFsError(\n 'unsafe-link',\n target,\n `Refusing to write ${target}: it is a symbolic link, and this program does not follow links when saving`\n );\n }\n if (stats.isDirectory()) {\n throw new SafeFsError(\n 'output-is-directory',\n target,\n `Cannot write ${target}: it is a directory`\n );\n }\n if (!stats.isFile()) {\n throw new SafeFsError(\n 'unsupported-target',\n target,\n `Cannot write ${target}: it exists but is not a regular file`\n );\n }\n // A rename would detach this name from the other links.\n if (stats.nlink > 1) {\n throw new SafeFsError(\n 'unsupported-target',\n target,\n `Refusing to replace ${target}: it has ${stats.nlink} hard links, and replacing it would silently detach the others`\n );\n }\n return snapshotIdentity(stats);\n}\n\nexport function defaultRandomName(): string {\n return randomBytes(6).toString('hex');\n}\n\nfunction isSymlink(filePath: string, fs: FsLayer): boolean {\n try {\n return fs.lstatSync(filePath).isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport function unlinkQuietly(filePath: string, fs: FsLayer = nodeFsLayer): void {\n quietly(() => fs.unlinkSync(filePath));\n}\n\n/** Linux needs a directory fsync for a rename to survive a crash; macOS may refuse it (EINVAL). */\nfunction syncDirectoryQuietly(dir: string, fs: FsLayer): void {\n quietly(() => {\n const fd = fs.openSync(dir, O_RDONLY);\n try {\n fs.fsyncSync(fd);\n } finally {\n quietly(() => fs.closeSync(fd));\n }\n });\n}\n","// packages/core/src/attachment-origins.ts\n// Where resumed attachment bytes live, which references may be read, and how they follow a relocated output.\n\nimport * as path from 'path';\nimport { MAX_IMAGE_BYTES } from './input-budgets';\nimport { readContainedFile, toSafeFsError } from './safe-fs';\nimport { canonicalSourcePath } from './source-identity';\nimport type { SafeFsErrorCode } from './safe-fs';\nimport { ASSET_DIR_NAME } from './xml-serializer';\nimport type { Attachment, ReviewComment, ReviewState } from './types';\n\n/** Reference as the resumed document wrote it → absolute path beside that document. Session state only. */\nexport type AttachmentOrigins = ReadonlyMap<string, string>;\n\nexport type AttachmentReadFailureReason =\n | 'not-authorized'\n | 'not-found'\n | 'not-regular'\n | 'unsafe-link'\n | 'too-large'\n | 'io-error';\n\nexport type AttachmentReadResult =\n | { ok: true; data: ArrayBuffer }\n | { ok: false; reason: AttachmentReadFailureReason; message: string };\n\n/** The bare name in `.self-review-assets/<name>`; null for any other shape. */\nexport function parseAttachmentReference(reference: unknown): string | null {\n if (typeof reference !== 'string') return null;\n const prefix = `${ASSET_DIR_NAME}/`;\n if (!reference.startsWith(prefix)) return null;\n const name = reference.slice(prefix.length);\n if (name === '' || name === '.' || name === '..') return null;\n if (/[/\\\\\\0]/.test(name)) return null;\n return name;\n}\n\nfunction* attachmentLists(comments: readonly ReviewComment[]) {\n for (const comment of comments) {\n if (comment.attachments) yield { comment, attachments: comment.attachments };\n for (const reply of comment.replies ?? []) {\n if (reply.attachments) yield { comment, attachments: reply.attachments };\n }\n }\n}\n\n/** Origins resolve against the resumed document's directory; an unrecorded reference is never read. */\nexport function resolveAttachmentOrigins(\n comments: readonly ReviewComment[],\n resumeDocumentPath: string\n): { origins: Map<string, string>; diagnostics: string[] } {\n const assetDir = path.join(\n canonicalSourcePath(path.dirname(path.resolve(resumeDocumentPath))),\n ASSET_DIR_NAME\n );\n const origins = new Map<string, string>();\n const diagnostics: string[] = [];\n for (const { comment, attachments } of attachmentLists(comments)) {\n for (const attachment of attachments) {\n const name = parseAttachmentReference(attachment.fileName);\n if (name === null) {\n diagnostics.push(\n `${comment.filePath || '(review)'}: attachment \"${attachment.fileName}\" is not in the ` +\n `document's ${ASSET_DIR_NAME} directory; it will not be loaded`\n );\n continue;\n }\n origins.set(attachment.fileName, path.join(assetDir, name));\n }\n }\n return { origins, diagnostics };\n}\n\nconst READ_FAILURES: Partial<Record<SafeFsErrorCode, AttachmentReadFailureReason>> = {\n 'not-found': 'not-found',\n 'unsafe-link': 'unsafe-link',\n 'output-is-directory': 'not-regular',\n 'not-regular': 'not-regular',\n 'too-large': 'too-large',\n};\n\n/** Read one asset the caller authorized: the asset directory must not be a link, nor the leaf. */\nexport async function readAssetFile(assetPath: string): Promise<AttachmentReadResult> {\n const assetDir = path.dirname(assetPath);\n const rel = path.join(path.basename(assetDir), path.basename(assetPath));\n try {\n const content = await readContainedFile(path.dirname(assetDir), rel, MAX_IMAGE_BYTES);\n const data = content.buffer.slice(content.byteOffset, content.byteOffset + content.byteLength);\n return { ok: true, data: data as ArrayBuffer };\n } catch (error) {\n const fsError = toSafeFsError(error, assetPath, 'read');\n return {\n ok: false,\n reason: READ_FAILURES[fsError.code] ?? 'io-error',\n message: fsError.message,\n };\n }\n}\n\n/** The recorded origin of an imported reference, else the same name in `currentAssetDir`. */\nexport function authorizeAttachmentReference(\n reference: unknown,\n origins: AttachmentOrigins,\n currentAssetDir: string | null\n): string | null {\n const name = parseAttachmentReference(reference);\n if (name === null) return null;\n const origin = origins.get(reference as string);\n if (origin !== undefined) return origin;\n return currentAssetDir ? path.join(currentAssetDir, name) : null;\n}\n\nexport class AttachmentRelocationError extends Error {\n readonly reference: string;\n readonly origin: string;\n readonly reason: AttachmentReadFailureReason;\n\n constructor(\n reference: string,\n origin: string,\n reason: AttachmentReadFailureReason,\n detail: string\n ) {\n super(\n `Attachment ${reference} from the resumed review could not be copied beside the new output: ${detail}. ` +\n `Save next to the resumed review, or remove that attachment, and save again.`\n );\n this.name = 'AttachmentRelocationError';\n this.reference = reference;\n this.origin = origin;\n this.reason = reason;\n }\n}\n\n/**\n * Give every imported attachment whose origin is not beside `outputPath` its bytes, so the\n * publisher stages a copy. Unreadable ones throw: the old reference would resolve to the wrong file.\n */\nexport async function relocateAttachments(\n state: ReviewState,\n origins: AttachmentOrigins,\n outputPath: string\n): Promise<ReviewState> {\n if (origins.size === 0) return state;\n const targetAssetDir = path.join(\n canonicalSourcePath(path.dirname(path.resolve(outputPath))),\n ASSET_DIR_NAME\n );\n const read = new Map<string, ArrayBuffer>();\n\n const relocate = async (attachments: Attachment[]): Promise<Attachment[]> => {\n const result: Attachment[] = [];\n for (const attachment of attachments) {\n const origin = attachment.data ? undefined : origins.get(attachment.fileName);\n if (origin === undefined || path.dirname(origin) === targetAssetDir) {\n result.push(attachment);\n continue;\n }\n let data = read.get(origin);\n if (data === undefined) {\n const outcome = await readAssetFile(origin);\n if (!outcome.ok) {\n throw new AttachmentRelocationError(\n attachment.fileName,\n origin,\n outcome.reason,\n outcome.message\n );\n }\n data = outcome.data;\n read.set(origin, data);\n }\n result.push({ ...attachment, data });\n }\n return result;\n };\n\n const files = [];\n for (const file of state.files) {\n const comments = [];\n for (const comment of file.comments) {\n const next: ReviewComment = { ...comment };\n if (comment.attachments) next.attachments = await relocate(comment.attachments);\n if (comment.replies) {\n next.replies = [];\n for (const reply of comment.replies) {\n next.replies.push(\n reply.attachments ? { ...reply, attachments: await relocate(reply.attachments) } : reply\n );\n }\n }\n comments.push(next);\n }\n files.push({ ...file, comments });\n }\n return { ...state, files };\n}\n","// Resolves the two snapshots a `git diff` compares, once at load, so later reads (an image\n// preview of a staged review) use those bytes and not the working tree. A shape this\n// module cannot vouch for is `unknown`, and a read from it fails visibly.\n\nimport { execFile } from 'child_process';\nimport { realpathSync } from 'fs';\nimport * as path from 'path';\nimport { promisify } from 'util';\nimport type { ReviewSourceIdentity, ReviewSourceSide } from './types';\nimport {\n classifyGitDiffArgs,\n consumesNextArgument,\n describeDiffPathRelativity,\n} from './git-diff-args';\n\nconst execFileAsync = promisify(execFile);\n\n/** One side as the arguments describe it, before resolution; `implicit` is the HEAD git assumes. */\nexport type GitDiffSideSpec =\n | { kind: 'working-tree' }\n | { kind: 'index' }\n | { kind: 'revision'; rev: string; implicit: boolean }\n | { kind: 'merge-base'; left: string; right: string }\n | { kind: 'unknown'; reason: string };\n\nexport interface GitDiffSides {\n oldSide: GitDiffSideSpec;\n newSide: GitDiffSideSpec;\n}\n\nconst WORKING_TREE: GitDiffSideSpec = { kind: 'working-tree' };\nconst INDEX: GitDiffSideSpec = { kind: 'index' };\nconst HEAD: GitDiffSideSpec = { kind: 'revision', rev: 'HEAD', implicit: true };\n\nfunction revision(rev: string): GitDiffSideSpec {\n return rev === '' ? HEAD : { kind: 'revision', rev, implicit: false };\n}\n\nfunction mergeBase(left: string, right: string): GitDiffSideSpec {\n return { kind: 'merge-base', left: left || 'HEAD', right: right || 'HEAD' };\n}\n\nfunction unknownSides(reason: string): GitDiffSides {\n return { oldSide: { kind: 'unknown', reason }, newSide: { kind: 'unknown', reason } };\n}\n\n/**\n * The two snapshots a `git diff` argv compares. Pure: runs no git and checks no revision.\n * Uses the classifier's arity rules, so `-S --cached` is not a flag. `--no-index`, three\n * or more revisions and `--cached` with a range are `unknown`.\n */\nexport function describeGitDiffSides(argv: readonly string[]): GitDiffSides {\n const separator = argv.indexOf('--');\n const end = separator === -1 ? argv.length : separator;\n const positional = new Set(\n classifyGitDiffArgs([...argv]).positionalIndices.filter(index => index < end)\n );\n\n let cached = false;\n let reverse = false;\n let useMergeBase = false;\n const revs: string[] = [];\n for (let i = 0; i < end; i++) {\n const arg = argv[i];\n if (positional.has(i)) {\n revs.push(arg);\n continue;\n }\n if (consumesNextArgument(arg)) {\n i++;\n continue;\n }\n if (arg === '--cached' || arg === '--staged') cached = true;\n else if (arg === '-R') reverse = true;\n else if (arg === '--merge-base') useMergeBase = true;\n else if (arg === '--no-index') return unknownSides('--no-index compares paths, not snapshots');\n }\n\n const sides = describeRevisionSides(revs, cached, useMergeBase);\n return reverse ? { oldSide: sides.newSide, newSide: sides.oldSide } : sides;\n}\n\nfunction describeRevisionSides(\n revs: readonly string[],\n cached: boolean,\n useMergeBase: boolean\n): GitDiffSides {\n if (revs.length === 0) {\n return cached ? { oldSide: HEAD, newSide: INDEX } : { oldSide: INDEX, newSide: WORKING_TREE };\n }\n\n if (revs.length === 1) {\n const rev = revs[0];\n const symmetric = rev.indexOf('...');\n if (symmetric !== -1) {\n if (cached) return unknownSides('--cached does not accept a revision range');\n const left = rev.slice(0, symmetric);\n const right = rev.slice(symmetric + 3);\n return { oldSide: mergeBase(left, right), newSide: revision(right) };\n }\n const range = rev.indexOf('..');\n if (range !== -1) {\n if (cached) return unknownSides('--cached does not accept a revision range');\n return { oldSide: revision(rev.slice(0, range)), newSide: revision(rev.slice(range + 2)) };\n }\n const oldSide = useMergeBase ? mergeBase(rev, 'HEAD') : revision(rev);\n return { oldSide, newSide: cached ? INDEX : WORKING_TREE };\n }\n\n if (revs.length === 2) {\n if (cached) return unknownSides('--cached does not accept two revisions');\n const [left, right] = revs;\n return {\n oldSide: useMergeBase ? mergeBase(left, right) : revision(left),\n newSide: revision(right),\n };\n }\n\n return unknownSides(`a combined diff of ${revs.length} revisions has no single old side`);\n}\n\nasync function gitOutput(repository: string, args: string[]): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync('git', args, {\n cwd: repository,\n timeout: 10_000,\n maxBuffer: 1024 * 1024,\n });\n return stdout.replace(/\\r?\\n$/, '');\n } catch {\n return null;\n }\n}\n\nconst SHA_PATTERN = /^[0-9a-f]{40,64}$/;\n\nasync function resolveCommit(repository: string, rev: string): Promise<string | null> {\n // `--end-of-options` keeps a leading `-` from being an option; `^{commit}` refuses a blob or\n // tree.\n const sha = await gitOutput(repository, [\n 'rev-parse',\n '--verify',\n '--quiet',\n '--end-of-options',\n `${rev}^{commit}`,\n ]);\n return sha !== null && SHA_PATTERN.test(sha) ? sha : null;\n}\n\nasync function resolveSide(repository: string, spec: GitDiffSideSpec): Promise<ReviewSourceSide> {\n switch (spec.kind) {\n case 'working-tree':\n case 'index':\n case 'unknown':\n return spec;\n case 'revision': {\n const sha = await resolveCommit(repository, spec.rev);\n if (sha !== null) return { kind: 'commit', sha };\n // An implicit HEAD resolving to nothing is an unborn branch: the empty tree.\n if (spec.implicit) return { kind: 'none' };\n return { kind: 'unknown', reason: `${spec.rev} does not name a commit` };\n }\n case 'merge-base': {\n const sha = await gitOutput(repository, ['merge-base', spec.left, spec.right]);\n if (sha !== null && SHA_PATTERN.test(sha)) return { kind: 'commit', sha };\n return {\n kind: 'unknown',\n reason: `no merge base between ${spec.left} and ${spec.right}`,\n };\n }\n }\n}\n\nexport function canonicalSourcePath(target: string): string {\n try {\n return realpathSync(target);\n } catch {\n return path.resolve(target);\n }\n}\n\n/**\n * `ReviewSourceIdentity.pathPrefix`: empty for root-relative output, the\n * `--relative=<dir>` directory without trailing slashes, or for bare `--relative`\n * the launch directory under the root (empty when outside the work tree, as in git).\n */\nexport function resolveReviewedPathPrefix(\n gitDiffArgv: readonly string[],\n sourceRoot: string,\n invocationCwd: string\n): string {\n const relative = describeDiffPathRelativity(gitDiffArgv);\n switch (relative.kind) {\n case 'root':\n return '';\n case 'directory':\n return relative.directory.replace(/\\/+$/, '');\n case 'cwd': {\n const fromRoot = path.relative(\n canonicalSourcePath(sourceRoot),\n canonicalSourcePath(invocationCwd)\n );\n if (fromRoot === '' || fromRoot.startsWith('..') || path.isAbsolute(fromRoot)) return '';\n return fromRoot.split(path.sep).join('/');\n }\n }\n}\n\n/** The one mapping every reader, Apply and re-diff uses, so they all name the same file. */\nexport function rootRelativeReviewedPath(\n identity: Pick<ReviewSourceIdentity, 'pathPrefix'>,\n filePath: string\n): string {\n return identity.pathPrefix === '' ? filePath : `${identity.pathPrefix}/${filePath}`;\n}\n\nexport interface GitSourceIdentityOptions {\n repository: string;\n gitDiffArgv: readonly string[];\n /** Defaults to the process's working directory. */\n invocationCwd?: string;\n /** `'remote'` for a materialized PR/MR; the git-mode machinery is the same. */\n mode?: 'git' | 'remote';\n}\n\n/** Resolves the compared sides to commit SHAs. Never throws; an unresolvable side is `unknown`. */\nexport async function resolveGitSourceIdentity(\n options: GitSourceIdentityOptions\n): Promise<ReviewSourceIdentity> {\n const sides = describeGitDiffSides(options.gitDiffArgv);\n const repository = options.repository;\n const [oldSide, newSide] = await Promise.all([\n resolveSide(repository, sides.oldSide),\n resolveSide(repository, sides.newSide),\n ]);\n const sourceRoot = canonicalSourcePath(repository);\n const invocationCwd = options.invocationCwd ?? process.cwd();\n return {\n mode: options.mode ?? 'git',\n sourceRoot,\n invocationCwd,\n gitDiffArgv: [...options.gitDiffArgv],\n pathPrefix: resolveReviewedPathPrefix(options.gitDiffArgv, sourceRoot, invocationCwd),\n oldSide,\n newSide,\n };\n}\n\nexport interface LocalSourceIdentityOptions {\n type: 'directory' | 'file';\n sourcePath: string;\n /** Defaults to the process's working directory. */\n invocationCwd?: string;\n}\n\n/**\n * Everything is an addition, so the old side is `none`. A single-file review follows a\n * symlink the user named, recording its target once; its root is the parent of the path as given.\n */\nexport function resolveLocalSourceIdentity(\n options: LocalSourceIdentityOptions\n): ReviewSourceIdentity {\n const invocationCwd = options.invocationCwd ?? process.cwd();\n if (options.type === 'directory') {\n return {\n mode: 'directory',\n sourceRoot: canonicalSourcePath(options.sourcePath),\n invocationCwd,\n gitDiffArgv: [],\n pathPrefix: '',\n oldSide: { kind: 'none' },\n newSide: { kind: 'directory' },\n };\n }\n return {\n mode: 'file',\n sourceRoot: canonicalSourcePath(path.dirname(options.sourcePath)),\n invocationCwd,\n gitDiffArgv: [],\n pathPrefix: '',\n oldSide: { kind: 'none' },\n newSide: { kind: 'file', path: canonicalSourcePath(options.sourcePath) },\n };\n}\n","// packages/core/src/git-diff-args.ts\n// Normalization of pass-through git diff arguments.\n\nimport { existsSync } from 'fs';\nimport { resolve } from 'path';\n\n// Only options whose bare spelling consumes the next argument belong here.\n// Optional values (for example --color, --relative and -U) must be attached.\nconst OPTIONS_WITH_SEPARATE_VALUES = new Set([\n '--output',\n '--src-prefix',\n '--dst-prefix',\n '--line-prefix',\n '--output-indicator-new',\n '--output-indicator-old',\n '--output-indicator-context',\n '--inter-hunk-context',\n '--stat-width',\n '--stat-name-width',\n '--stat-graph-width',\n '--stat-count',\n '--diff-algorithm',\n '--word-diff-regex',\n '--ignore-matching-lines',\n '--anchored',\n '--diff-filter',\n '--find-object',\n '--rotate-to',\n '--skip-to',\n '--ws-error-highlight',\n '--color-moved-ws',\n]);\n\n// Required values may be attached or the next argument; optional ones are attached only (`-U 5` is\n// `-U`, then `5`).\nconst SHORT_OPTIONS_WITH_REQUIRED_VALUES = 'SGOIl';\nconst SHORT_OPTIONS_WITH_OPTIONAL_VALUES = 'UBMC';\n\n/** True when `arg`'s value is the next argument, which is then neither a flag nor a positional. */\nexport function consumesNextArgument(arg: string): boolean {\n if (arg.startsWith('--')) return OPTIONS_WITH_SEPARATE_VALUES.has(arg);\n if (!arg.startsWith('-')) return false;\n // Git accepts short-option groups, such as -pS pattern. Once an option\n // takes a value, the rest of that token is its attached value, if present.\n for (let i = 1; i < arg.length; i++) {\n if (SHORT_OPTIONS_WITH_REQUIRED_VALUES.includes(arg[i])) return i === arg.length - 1;\n if (SHORT_OPTIONS_WITH_OPTIONAL_VALUES.includes(arg[i])) return false;\n }\n return false;\n}\n\n/** What the paths in `git diff` output are relative to. */\nexport type DiffPathRelativity =\n | { kind: 'root' }\n | { kind: 'cwd' }\n // `directory` is read by git from the repository root.\n | { kind: 'directory'; directory: string };\n\nexport interface SingleFileRediff {\n args: string[];\n /** Resolved from the original arguments; its option is not in `args`. */\n relative: DiffPathRelativity;\n}\n\n// Long options that decide only how much context surrounds a change.\nconst CONTEXT_OPTIONS = new Set(['--unified', '--function-context', '--no-function-context']);\n// `--rotate-to` and `--skip-to` make git fail when their file is not in the diff.\nconst FILE_ORDER_OPTIONS = new Set(['--rotate-to', '--skip-to']);\n\nfunction isDroppedLongOption(arg: string): boolean {\n const name = arg.includes('=') ? arg.slice(0, arg.indexOf('=')) : arg;\n return CONTEXT_OPTIONS.has(name) || FILE_ORDER_OPTIONS.has(name);\n}\n\n/**\n * A short-option group minus `-U`, `-W` and `-O` (which end the group: the rest is their value), or\n * null if empty.\n */\nfunction withoutDroppedShortOptions(arg: string): string | null {\n let kept = '';\n for (let i = 1; i < arg.length; i++) {\n const option = arg[i];\n if (option === 'U' || option === 'O') break;\n if (option === 'W') continue;\n if (\n SHORT_OPTIONS_WITH_REQUIRED_VALUES.includes(option) ||\n SHORT_OPTIONS_WITH_OPTIONAL_VALUES.includes(option)\n ) {\n kept += arg.slice(i);\n break;\n }\n kept += option;\n }\n return kept === '' ? null : `-${kept}`;\n}\n\n/**\n * The last of `--relative`, `--relative=<dir>` and `--no-relative` before `--` decides.\n * Only arguments count: every git diff forces `diff.relative=false`\n * (`PARSER_COMPATIBLE_GIT_CONFIG`).\n */\nexport function describeDiffPathRelativity(args: readonly string[]): DiffPathRelativity {\n let relative: DiffPathRelativity = { kind: 'root' };\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--') break;\n if (arg === '--relative') relative = { kind: 'cwd' };\n else if (arg.startsWith('--relative='))\n relative = { kind: 'directory', directory: arg.slice('--relative='.length) };\n else if (arg === '--no-relative') relative = { kind: 'root' };\n else if (consumesNextArgument(arg)) i++;\n }\n return relative;\n}\n\n/**\n * Arguments for re-running a review's `git diff` over one file with other context.\n * Removed: context options (a bare `-U` never takes the next argument, so `-U HEAD`\n * keeps `HEAD`), file-order options, `--relative` forms (resolved into `relative`),\n * and `--` with its pathspecs. Everything else is kept in order.\n */\nexport function singleFileRediffArgs(args: readonly string[]): SingleFileRediff {\n const kept: string[] = [];\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--') break;\n if (arg === '--relative' || arg.startsWith('--relative=') || arg === '--no-relative') {\n continue;\n }\n // The value goes wherever its option goes.\n const takesNext = consumesNextArgument(arg) && i + 1 < args.length;\n let option: string | null = arg;\n let keepValue = true;\n if (arg.startsWith('--')) {\n if (isDroppedLongOption(arg)) option = null;\n keepValue = option !== null;\n } else if (arg.startsWith('-') && arg.length > 1) {\n option = withoutDroppedShortOptions(arg);\n keepValue = !arg.endsWith('O');\n }\n if (option !== null) kept.push(option);\n if (takesNext) {\n i++;\n if (keepValue) kept.push(args[i]);\n }\n }\n return { args: kept, relative: describeDiffPathRelativity(args) };\n}\n\n// Options a committed config must not hand to git: `--output` truncates and fills a file\n// (following symlinks, even for an empty diff); the others run external drivers.\n// Git accepts no abbreviations, and negations (`--no-ext-diff`) are allowed.\nconst WRITE_CAPABLE_OPTIONS = new Set(['--output', '--ext-diff', '--textconv']);\n\n/**\n * Options that make git write a file or run a program, as written. Used to refuse project\n * `default-diff-args`; the reviewer's own arguments are unrestricted.\n */\nexport function findWriteCapableGitDiffOptions(args: readonly string[]): string[] {\n const offending: string[] = [];\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--') break;\n const name = arg.includes('=') ? arg.slice(0, arg.indexOf('=')) : arg;\n if (WRITE_CAPABLE_OPTIONS.has(name)) offending.push(arg);\n if (consumesNextArgument(arg)) i++;\n }\n return offending;\n}\n\n// Output formats `parseDiff` cannot consume: exact spellings plus attached-value prefixes\n// (`--stat=120`).\nconst UNSUPPORTED_OUTPUT_OPTIONS = new Set([\n '--stat',\n '--numstat',\n '--shortstat',\n '--dirstat',\n '--dirstat-by-file',\n '--cumulative',\n '--summary',\n '--name-only',\n '--name-status',\n '--raw',\n '--patch-with-stat',\n '--patch-with-raw',\n '--compact-summary',\n '--word-diff',\n '--word-diff-regex',\n '--color-words',\n '--color-moved',\n '--color-moved-ws',\n '--no-patch',\n '-s',\n '--exit-code',\n '--quiet',\n '--output',\n '--line-prefix',\n '--output-indicator-new',\n '--output-indicator-old',\n '--output-indicator-context',\n '--check',\n]);\n\nconst UNSUPPORTED_OUTPUT_OPTION_PREFIXES = [\n '--stat=',\n '--stat-width=',\n '--stat-name-width=',\n '--stat-graph-width=',\n '--stat-count=',\n '--dirstat=',\n '--dirstat-by-file=',\n '--word-diff=',\n '--word-diff-regex=',\n '--color-words=',\n '--color-moved=',\n '--color-moved-ws=',\n '--output=',\n '--line-prefix=',\n '--output-indicator-new=',\n '--output-indicator-old=',\n '--output-indicator-context=',\n];\n\nfunction isUnsupportedOutputOption(arg: string): boolean {\n return (\n UNSUPPORTED_OUTPUT_OPTIONS.has(arg) ||\n UNSUPPORTED_OUTPUT_OPTION_PREFIXES.some(prefix => arg.startsWith(prefix))\n );\n}\n\n/** Options selecting an output format the parser cannot consume, as the user wrote them. */\nexport function findUnsupportedGitDiffOptions(args: readonly string[]): string[] {\n const offending: string[] = [];\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--') break;\n if (isUnsupportedOutputOption(arg)) {\n offending.push(arg);\n }\n if (consumesNextArgument(arg)) i++;\n }\n return offending;\n}\n\n/** Identify positional arguments without mistaking option values for paths. */\nexport function classifyGitDiffArgs(args: string[]): {\n positionalIndices: number[];\n hasSeparator: boolean;\n} {\n const positionalIndices: number[] = [];\n let hasSeparator = false;\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (!hasSeparator) {\n if (arg === '--') {\n hasSeparator = true;\n continue;\n }\n if (consumesNextArgument(arg)) {\n i++;\n continue;\n }\n if (arg.startsWith('-')) continue;\n }\n positionalIndices.push(i);\n }\n return { positionalIndices, hasSeparator };\n}\n\n/**\n * Insert `--` before the first non-flag positional arg that exists as a\n * filesystem path. This makes the args unambiguous so downstream code\n * (expand-context) never confuses a path for a revision.\n *\n * Idempotent: an explicit `--` separator leaves the args unchanged.\n */\nexport function normalizeGitDiffArgs(args: string[], cwd: string = process.cwd()): string[] {\n const { positionalIndices, hasSeparator } = classifyGitDiffArgs(args);\n if (hasSeparator) return args;\n for (const i of positionalIndices) {\n const arg = args[i];\n // Only positional args can be filesystem paths.\n if (existsSync(resolve(cwd, arg))) {\n return [...args.slice(0, i), '--', ...args.slice(i)];\n }\n }\n return args;\n}\n\n/**\n * Split a configured argument string into argv the way a shell would, so a\n * quoted path or search string survives as one argument.\n *\n * Two callers rely on this: `default-diff-args` from YAML, which people write\n * with shell quoting, and the `git-diff-args` string carried on a git diff\n * source, which `formatGitDiffArgs` writes in the same syntax. Unquoted input\n * splits on whitespace exactly as a plain split did, so older config and older\n * review documents keep parsing identically.\n *\n * Malformed input never throws. An unterminated quote closes at end of input:\n * a broken config line degrades to a best-effort argument list instead of\n * taking startup down with it.\n */\nexport function tokenizeGitDiffArgs(value: string): string[] {\n const args: string[] = [];\n let current = '';\n let started = false;\n let quote: \"'\" | '\"' | null = null;\n\n for (let i = 0; i < value.length; i++) {\n const char = value[i];\n\n if (quote === \"'\") {\n if (char === \"'\") quote = null;\n else current += char;\n continue;\n }\n\n if (quote === '\"') {\n // Inside double quotes only the quote and the backslash are escapable;\n // every other backslash is a literal character, as in POSIX shells.\n if (char === '\\\\' && (value[i + 1] === '\"' || value[i + 1] === '\\\\')) {\n current += value[++i];\n } else if (char === '\"') {\n quote = null;\n } else {\n current += char;\n }\n continue;\n }\n\n if (char === \"'\" || char === '\"') {\n quote = char;\n started = true;\n continue;\n }\n if (char === '\\\\' && i + 1 < value.length) {\n current += value[++i];\n started = true;\n continue;\n }\n if (/\\s/.test(char)) {\n if (started) {\n args.push(current);\n current = '';\n started = false;\n }\n continue;\n }\n current += char;\n started = true;\n }\n\n if (started) args.push(current);\n return args;\n}\n\n/** True when rendering this argument bare would lose its boundary. */\nfunction needsQuoting(arg: string): boolean {\n return arg.length === 0 || /[\\s'\"\\\\]/.test(arg);\n}\n\n/**\n * Render argv as the single string a git diff source carries, such that\n * `tokenizeGitDiffArgs` recovers the exact argument list.\n *\n * Arguments that survive a bare round trip are written bare, so ordinary\n * invocations produce byte-identical output to a plain join and the\n * `git-diff-args` XML attribute does not change shape for them.\n */\nexport function formatGitDiffArgs(args: string[]): string {\n return args.map(arg => (needsQuoting(arg) ? `'${arg.replace(/'/g, \"'\\\\''\")}'` : arg)).join(' ');\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 = { ok: true; guide: ReviewGuide } | { 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: [{ fileName: 'self-review-guide-v1.xsd', contents: GUIDE_XSD_SCHEMA }],\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(guide: ReviewGuide, diffFilePaths: string[]): 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","// 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 *\n * Revision provenance (the mapper compares it with the reviewed head; providers\n * report only what the forge told them):\n * - `headSha`: head commit the line numbers were computed against, when the\n * forge reports one per note (GitLab). A suggestion activates only on a match.\n * - `outdated`: the forge's own per-note verdict (GitHub `line: null`). `true`\n * degrades to file-level; `false` vouches for the anchor when no `headSha` exists.\n *\n * An anchor carrying neither is unverifiable: it never activates a suggestion.\n */\nexport interface ForgeThreadAnchor {\n filePath: string;\n side: ForgeAnchorSide;\n startLine: number | null;\n endLine: number | null;\n headSha?: string;\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 * Optional lifetime bounds; either one kills the child and rejects with {@link\n * CommandCancelledError}.\n */\nexport interface ForgeCommandOptions {\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\n/**\n * Injectable command runner for providers and the materializer. Resolves with\n * the exit code on any completed run; rejects when the binary cannot be spawned\n * and, with a {@link CommandCancelledError}, when cut short by `options`.\n */\nexport type ForgeCommandRunner = (\n command: string,\n args: string[],\n options?: ForgeCommandOptions\n) => Promise<ForgeCommandResult>;\n\n/** Why a command run was cut short. */\nexport type CommandCancelReason = 'aborted' | 'timeout';\n\n/**\n * A run ended by its caller's bounds (abort or timeout) after the child was\n * killed. Providers must not fold it into {@link ForgeCliUnavailableError}: a\n * session being torn down must not degrade into a review without threads.\n */\nexport class CommandCancelledError extends Error {\n readonly reason: CommandCancelReason;\n readonly command: string;\n readonly args: readonly string[];\n\n constructor(reason: CommandCancelReason, command: string, args: readonly string[]) {\n super(\n reason === 'timeout'\n ? `${command} ${args.join(' ')} timed out and was killed`\n : `${command} ${args.join(' ')} was cancelled`\n );\n this.name = 'CommandCancelledError';\n this.reason = reason;\n this.command = command;\n this.args = args;\n }\n}\n\n/** Matches by name too, so it works across module instances. */\nexport function isCommandCancelled(error: unknown): error is CommandCancelledError {\n return (\n error instanceof CommandCancelledError ||\n (error instanceof Error && error.name === 'CommandCancelledError')\n );\n}\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(url: ForgeUrl, options?: FetchThreadsOptions): 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","// Scans a directory (or one file) into DiffFile[], every file a new addition.\n// The walk is bounded (input-budgets.ts): ignored directories are never opened, and\n// hitting `maxEntries` yields no files rather than a shorter review that looks complete.\n// Only regular files are reviewed; links are never followed out of the tree.\n\nimport { opendir, stat } from 'fs/promises';\nimport { basename, dirname, join } from 'path';\nimport { DiffFile } from './types';\nimport { loadSyntheticFiles } from './synthetic-diff';\nimport { createIgnoreFilter } from './ignore-filter';\nimport { resolveSourceBudgets, type SourceBudgets } from './input-budgets';\n\nexport interface SourceScanOptions {\n budgets?: Partial<SourceBudgets>;\n}\n\nexport interface SourceScanResult {\n files: DiffFile[];\n /** For `DiffLoadPayload.diagnostics`; empty for a clean scan. */\n diagnostics: string[];\n /** `files` is empty when this is true. */\n entryLimitExceeded: boolean;\n}\n\n/**\n * Recursively scans `directoryPath`; a directory matching `ignorePatterns` is pruned without being\n * opened.\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = [],\n options: SourceScanOptions = {}\n): Promise<SourceScanResult> {\n const budgets = resolveSourceBudgets(options.budgets);\n\n try {\n const dirStat = await stat(directoryPath);\n if (!dirStat.isDirectory()) {\n return failed(`Cannot review \"${directoryPath}\": it is not a directory.`);\n }\n } catch (error) {\n return failed(`Cannot read directory \"${directoryPath}\": ${messageOf(error)}`);\n }\n\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n let walk: WalkResult;\n try {\n walk = await walkDirectory(directoryPath, shouldKeep, budgets.maxEntries);\n } catch (error) {\n return failed(`Cannot read directory \"${directoryPath}\": ${messageOf(error)}`);\n }\n\n if (walk.limitExceeded) {\n console.error(`[scan] Stopped scanning ${directoryPath} after ${budgets.maxEntries} entries`);\n return {\n files: [],\n diagnostics: [\n `\"${directoryPath}\" has more than ${budgets.maxEntries.toLocaleString('en-US')} ` +\n 'entries outside ignored directories, so it was not loaded. Review a ' +\n 'subdirectory, or add ignore patterns (the `ignore` config key) for build ' +\n 'output and dependency folders.',\n ],\n entryLimitExceeded: true,\n };\n }\n\n // Sort for deterministic output\n walk.files.sort();\n if (walk.files.length === 0) {\n return { files: [], diagnostics: [], entryLimitExceeded: false };\n }\n\n const { files, diagnostics } = loadSyntheticFiles(walk.files, directoryPath, {\n budgets: options.budgets,\n });\n return { files, diagnostics, entryLimitExceeded: false };\n}\n\n/**\n * The reviewer named this path explicitly, so a symlink is read through; the per-file budget still\n * applies.\n */\nexport async function scanFile(\n filePath: string,\n options: SourceScanOptions = {}\n): Promise<SourceScanResult> {\n try {\n const fileStat = await stat(filePath);\n if (!fileStat.isFile()) {\n return failed(`Cannot review \"${filePath}\": it is not a regular file.`);\n }\n } catch (error) {\n return failed(`Cannot read file \"${filePath}\": ${messageOf(error)}`);\n }\n\n const { files, diagnostics } = loadSyntheticFiles([basename(filePath)], dirname(filePath), {\n followSymlinks: true,\n budgets: options.budgets,\n });\n return { files, diagnostics, entryLimitExceeded: false };\n}\n\ninterface WalkResult {\n files: string[];\n limitExceeded: boolean;\n}\n\nasync function walkDirectory(\n root: string,\n shouldKeep: (path: string) => boolean,\n maxEntries: number\n): Promise<WalkResult> {\n const files: string[] = [];\n // Relative directory paths still to open; '' is the root itself.\n const pending: string[] = [''];\n let examined = 0;\n\n while (pending.length > 0) {\n const relativeDir = pending.pop()!;\n const dir = await opendir(relativeDir === '' ? root : join(root, relativeDir));\n try {\n for await (const entry of dir) {\n examined++;\n if (examined > maxEntries) return { files, limitExceeded: true };\n\n const relativePath = relativeDir === '' ? entry.name : `${relativeDir}/${entry.name}`;\n if (entry.isDirectory()) {\n // The trailing slash lets `node_modules/`-style patterns match.\n if (shouldKeep(`${relativePath}/`)) pending.push(relativePath);\n } else if (entry.isFile()) {\n if (shouldKeep(relativePath)) files.push(relativePath);\n }\n }\n } finally {\n // Breaking out of the iterator already closes the handle; a second close throws\n // ERR_DIR_CLOSED.\n await dir.close().catch(() => {});\n }\n }\n\n return { files, limitExceeded: false };\n}\n\nfunction failed(message: string): SourceScanResult {\n console.error(`[scan] ${message}`);\n return { files: [], diagnostics: [message], entryLimitExceeded: false };\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\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(patterns: string[]): (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","// packages/core/src/snapshot-reader.ts\n// The one place a reviewed path turns into bytes, read from the side the review compared (audit R13, A6).\n\nimport { execFile } from 'child_process';\nimport * as path from 'path';\nimport type { ReviewSourceIdentity, ReviewSourceSide } from './types';\nimport { MAX_SOURCE_FILE_BYTES } from './input-budgets';\nimport { errnoOf, readContainedFile, toSafeFsError } from './safe-fs';\nimport type { SafeFsErrorCode } from './safe-fs';\nimport { rootRelativeReviewedPath } from './source-identity';\n\nexport interface ReviewedSnapshot {\n sourceIdentity: ReviewSourceIdentity | null;\n reviewedPaths: ReadonlySet<string>;\n}\n\nexport type ReviewedPathRefusal =\n | 'no-source'\n | 'not-reviewed'\n /** Absolute, empty, or leaving the source root. */\n | 'invalid-path';\n\nexport type ReviewedPathAuthorization =\n | {\n ok: true;\n /** Restated from `sourceRoot` through the identity's prefix, normalized. */\n relativePath: string;\n sourceRoot: string;\n }\n | { ok: false; reason: ReviewedPathRefusal; message: string };\n\n/** The one path check every front end delegates to; what passes is exactly what the readers open. */\nexport function authorizeReviewedPath(\n source: ReviewedSnapshot,\n filePath: string\n): ReviewedPathAuthorization {\n const identity = source.sourceIdentity;\n if (identity === null) {\n return { ok: false, reason: 'no-source', message: 'No review has been loaded.' };\n }\n const invalid: ReviewedPathAuthorization = {\n ok: false,\n reason: 'invalid-path',\n message: 'This path does not stay inside the reviewed source.',\n };\n // The path as sent must be sound before a prefix is put in front of it:\n // `<prefix>//etc/passwd` would normalize into a relative path.\n if (normalizeReviewedPath(filePath) === null) return invalid;\n if (!source.reviewedPaths.has(filePath)) {\n return {\n ok: false,\n reason: 'not-reviewed',\n message: 'This file is not part of the reviewed diff.',\n };\n }\n const relativePath = normalizeReviewedPath(rootRelativeReviewedPath(identity, filePath));\n if (relativePath === null) return invalid;\n return { ok: true, relativePath, sourceRoot: identity.sourceRoot };\n}\n\n/** Diff paths are `/`-separated on every platform; a backslash is an ordinary character. */\nfunction normalizeReviewedPath(filePath: string): string | null {\n if (filePath === '' || filePath.includes('\\0') || path.posix.isAbsolute(filePath)) return null;\n const normalized = path.posix.normalize(filePath);\n if (normalized === '.' || normalized === '..' || normalized.startsWith('../')) return null;\n if (normalized.split('/').includes('..')) return null;\n return normalized;\n}\n\nexport type SnapshotReadFailure =\n | ReviewedPathRefusal\n /** The side has no content (`none`) or could not be identified (`unknown`). */\n | 'side-unavailable'\n | 'not-found'\n /** A directory, FIFO, socket or device. */\n | 'not-regular'\n | 'unsafe-link'\n | 'too-large'\n | 'read-failed';\n\nexport type SnapshotReadResult =\n | { ok: true; content: Buffer }\n | { ok: false; reason: SnapshotReadFailure; message: string };\n\nexport interface SnapshotReadOptions {\n /** Defaults to `MAX_SOURCE_FILE_BYTES`. */\n maxBytes?: number;\n}\n\nfunction failure(reason: SnapshotReadFailure, message: string): SnapshotReadResult {\n return { ok: false, reason, message };\n}\n\n/** A blob from the object store, or the file under the physical source root; authorized first. */\nexport async function readReviewedContent(\n source: ReviewedSnapshot,\n filePath: string,\n side: 'old' | 'new',\n options: SnapshotReadOptions = {}\n): Promise<SnapshotReadResult> {\n const authorized = authorizeReviewedPath(source, filePath);\n if (!authorized.ok) return failure(authorized.reason, authorized.message);\n const identity = source.sourceIdentity!;\n const descriptor = side === 'old' ? identity.oldSide : identity.newSide;\n const maxBytes = options.maxBytes ?? MAX_SOURCE_FILE_BYTES;\n return readSide(descriptor, authorized.sourceRoot, authorized.relativePath, maxBytes);\n}\n\nasync function readSide(\n descriptor: ReviewSourceSide,\n sourceRoot: string,\n relativePath: string,\n maxBytes: number\n): Promise<SnapshotReadResult> {\n switch (descriptor.kind) {\n case 'working-tree':\n case 'directory':\n return readPhysicalFile(sourceRoot, relativePath, maxBytes);\n case 'file': {\n // Walked from the filesystem root: the path was physical at load, so any link now is new.\n const fsRoot = path.parse(descriptor.path).root;\n return readPhysicalFile(fsRoot, path.relative(fsRoot, descriptor.path), maxBytes);\n }\n case 'index':\n // `:path` alone would read a leading `<n>:` in the path as a stage number.\n return readGitBlob(sourceRoot, `:0:${relativePath}`, maxBytes);\n case 'commit':\n return readGitBlob(sourceRoot, `${descriptor.sha}:${relativePath}`, maxBytes);\n case 'none':\n return failure('side-unavailable', 'This side of the review has no content.');\n case 'unknown':\n return failure(\n 'side-unavailable',\n `This side of the review could not be identified: ${descriptor.reason}.`\n );\n }\n}\n\nasync function readPhysicalFile(\n root: string,\n relativePath: string,\n maxBytes: number\n): Promise<SnapshotReadResult> {\n try {\n return { ok: true, content: await readContainedFile(root, relativePath, maxBytes) };\n } catch (error) {\n const fsError = toSafeFsError(error, relativePath, 'read');\n const [reason, message = fsError.message] = FS_FAILURES[fsError.code] ?? ['read-failed'];\n return failure(reason, message);\n }\n}\n\nconst FS_FAILURES: Partial<Record<SafeFsErrorCode, [SnapshotReadFailure, string?]>> = {\n 'not-found': ['not-found', 'The file does not exist on this side of the review.'],\n 'unsafe-link': ['unsafe-link', 'The path goes through a symbolic link.'],\n 'output-is-directory': ['not-regular', 'The path is a directory.'],\n 'not-regular': ['not-regular', 'The path is not a regular file.'],\n 'unsupported-target': ['invalid-path', 'This path does not stay inside the reviewed source.'],\n 'too-large': ['too-large'],\n};\n\n/** `cat-file blob`, not `show`: it refuses a tree and never smudges, so the bytes are the ones git compared. */\nfunction readGitBlob(root: string, spec: string, maxBytes: number): Promise<SnapshotReadResult> {\n return new Promise(resolve => {\n execFile(\n 'git',\n ['cat-file', 'blob', spec],\n { cwd: root, encoding: 'buffer', maxBuffer: maxBytes + 1, timeout: 30_000 },\n (error, stdout, stderr) => {\n if (error) {\n if (errnoOf(error) === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {\n resolve(failure('too-large', `The blob is over the ${maxBytes}-byte limit.`));\n return;\n }\n const detail = stderr.toString('utf-8').trim();\n if (\n /does not exist|not a valid object name|invalid object name|not a blob/i.test(detail)\n ) {\n resolve(failure('not-found', 'The file does not exist on this side of the review.'));\n return;\n }\n resolve(failure('read-failed', `git cat-file failed: ${detail || error.message}`));\n return;\n }\n if (stdout.length > maxBytes) {\n resolve(failure('too-large', `The blob is over the ${maxBytes}-byte limit.`));\n return;\n }\n resolve({ ok: true, content: stdout });\n }\n );\n });\n}\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';\nimport { DEFAULT_CONFIG } from '../../react/src/config-defaults';\n\n// Shared with the renderer's ConfigProvider; see packages/react/src/config-defaults.ts.\nconst defaults: AppConfig = DEFAULT_CONFIG;\n\n/**\n * `project` config is repository data and is trusted less than the reviewer's own `user` config.\n */\nexport type ConfigValueOrigin = 'default' | 'user' | 'project';\n\nexport type ConfigProvenance = Readonly<Record<keyof AppConfig, ConfigValueOrigin>>;\n\nexport interface ConfigSource {\n origin: 'user' | 'project';\n path: string;\n}\n\nexport interface LoadedConfig {\n config: AppConfig;\n provenance: ConfigProvenance;\n sources: ConfigSource[];\n}\n\nexport interface LoadConfigOptions {\n cwd?: string;\n homeDir?: string;\n}\n\nconst CONFIG_KEYS = Object.keys(defaults) as (keyof AppConfig)[];\n\n/** Project overrides user overrides defaults; an invalid value is not attributed to its file. */\nexport function loadConfigWithProvenance(options: LoadConfigOptions = {}): LoadedConfig {\n let config = { ...defaults };\n const provenance = Object.fromEntries(CONFIG_KEYS.map(key => [key, 'default'])) as Record<\n keyof AppConfig,\n ConfigValueOrigin\n >;\n // `guideFile` has no default, so it is missing from CONFIG_KEYS.\n provenance.guideFile = 'default';\n const sources: ConfigSource[] = [];\n\n const files: ConfigSource[] = [\n {\n origin: 'user',\n path: join(options.homeDir ?? homedir(), '.config', 'self-review', 'config.yaml'),\n },\n { origin: 'project', path: join(options.cwd ?? process.cwd(), '.self-review.yaml') },\n ];\n for (const source of files) {\n if (!existsSync(source.path)) continue;\n try {\n const override = loadYamlConfig(source.path);\n config = mergeConfig(config, override);\n for (const key of Object.keys(override) as (keyof AppConfig)[]) {\n provenance[key] = source.origin;\n }\n sources.push(source);\n } catch (error) {\n console.error(\n `Warning: Failed to load ${source.origin} config from ${source.path}: ${error}`\n );\n }\n }\n\n return { config, provenance, sources };\n}\n\nexport function loadConfig(options: LoadConfigOptions = {}): AppConfig {\n return loadConfigWithProvenance(options).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(`Warning: Invalid theme value \"${raw.theme}\", using default`);\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(`Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`);\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((item: unknown) => typeof item === 'string');\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n const usableCategories = 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 (cat as Record<string, unknown>).name !== '' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n\n // A `categories` list that leaves no usable entry (empty list, every entry\n // shaped wrong, or every entry named '') would silently disable commenting,\n // so it's treated the same as any other invalid value: warn and keep the default.\n if (usableCategories.length > 0) {\n config.categories = usableCategories;\n } else {\n console.error(\n 'Warning: Category configuration has no usable categories, using default categories'\n );\n }\n }\n\n if ('default-diff-args' in raw && typeof raw['default-diff-args'] === 'string') {\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 =\n 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: override.categories !== undefined ? override.categories : base.categories,\n };\n}\n","/**\n * Default `AppConfig`, shared by core's YAML loader and `ConfigProvider`. It lives in react\n * because react may not import core; core imports it by relative path. Type-only imports only,\n * since it ships to browsers and Node alike.\n */\nimport type { AppConfig, CategoryDef } from '@self-review/types';\n\nexport const DEFAULT_CATEGORIES: readonly CategoryDef[] = [\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\n/** Only core's directory scanner reads these; the renderer carries them so the defaults stay one. */\nexport const DEFAULT_IGNORE_PATTERNS: readonly string[] = [\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\nexport const DEFAULT_FONT_SIZE = 14;\n\nexport const DEFAULT_MAX_FILES = 500;\nexport const DEFAULT_MAX_TOTAL_LINES = 100000;\n\n/** `guideFile` is absent on purpose: the loader derives it from the output path. */\nexport const DEFAULT_CONFIG: Readonly<AppConfig> = {\n theme: 'system',\n diffView: 'split',\n fontSize: DEFAULT_FONT_SIZE,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: [...DEFAULT_IGNORE_PATTERNS],\n categories: [...DEFAULT_CATEGORIES],\n defaultDiffArgs: '',\n showUntracked: true,\n showUntrackedExplicit: false,\n wordWrap: true,\n maxFiles: DEFAULT_MAX_FILES,\n maxTotalLines: DEFAULT_MAX_TOTAL_LINES,\n};\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execFileAsync = promisify(execFile);\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 execFileAsync('git', ['diff', '--numstat', ...args], {\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","// apply-suggestion.ts\n// Writes one anchored suggestion into one working file, or refuses and\n// writes nothing. Node-only, Electron-free, and free of process-global\n// state: the caller names the destination root, so nothing here ever\n// consults `process.cwd()`.\n//\n// The engine is deliberately narrow. It performs a byte-for-byte context\n// check and a literal line replacement — no fuzzy matching, no force flag,\n// no staging, no git. Every outcome is reported: a refusal names its reason\n// and leaves the file untouched (PRD Section 5.4.8). Containment and the\n// transactional write live here, not in a transport (audit A3/A4, R04).\n\nimport * as path from 'path';\nimport type { LineRange, Suggestion } from './types';\nimport { validateLineRange } from './anchor-validation';\nimport {\n atomicReplace,\n errnoOf,\n nodeFsLayer,\n openContainedFile,\n snapshotIdentity,\n toSafeFsError,\n} from './safe-fs';\nimport type { FileIdentity, FsLayer, SafeFsErrorCode } from './safe-fs';\n\n/**\n * Why an apply was refused. Every value is a structural fact about the\n * request or the file — never a fragment of the file's contents, so a\n * refusal is safe to surface in the UI and in logs.\n */\nexport type ApplyRefusalReason =\n /** The suggestion is file-level: there is nothing to replace. */\n | 'no-anchor'\n /**\n * The anchor names deleted lines (`side: 'old'`). Those lines are not in\n * the working file, and the app holds no old→new line mapping, so the\n * target is undefined rather than merely missing.\n */\n | 'old-side-anchor'\n /** Unknown side, non-positive or non-integer bounds, or reversed; checked before any I/O. */\n | 'invalid-anchor'\n /** `destinationRoot` is relative; resolving it would consult the cwd. */\n | 'destination-not-absolute'\n | 'destination-missing'\n /** `filePath` resolves outside `destinationRoot`. */\n | 'path-escapes-destination'\n | 'control-file'\n /** A link on the way or at the leaf, a hard-linked or special file, or a swap during the open. */\n | 'unsafe-target'\n /** Replacing the file would change its owner, which this process cannot restore. */\n | 'unsupported-target'\n /** No file at the resolved path. */\n | 'file-missing'\n /** The path exists but could not be read (permissions, a directory, …). */\n | 'file-unreadable'\n /**\n * The file is not valid UTF-8. Rewriting it would round-trip its bytes\n * through a lossy decode and corrupt regions outside the anchor.\n */\n | 'file-not-utf8'\n /** The anchor falls outside the file's line count. */\n | 'anchor-out-of-range'\n /** The anchored lines no longer match `suggestion.originalCode`. */\n | 'context-mismatch'\n /** The file was replaced or rewritten between the read and the commit. */\n | 'file-changed'\n /** The context matched but the write itself failed. */\n | 'write-failed';\n\nexport interface ApplySuggestionRequest {\n /**\n * Absolute path of the directory the reviewed files live in. Always\n * supplied by the caller: a git-mode working tree, a directory-mode root,\n * a reused clone, or the destination the user picked for a temporary-clone\n * review. Never derived here.\n */\n destinationRoot: string;\n /** Path of the file to modify, relative to `destinationRoot`. */\n filePath: string;\n /** The comment's anchor. `null` (file-level) is refused. */\n lineRange: LineRange | null;\n suggestion: Suggestion;\n}\n\nexport interface ApplySuggestionOptions {\n fs?: FsLayer;\n randomName?: () => string;\n}\n\nexport interface ApplySuggestionApplied {\n status: 'applied';\n /** Echoed from the request, so a batch caller can attribute the result. */\n filePath: string;\n absolutePath: string;\n /** How many on-disk lines the proposal replaced. */\n replacedLines: number;\n}\n\nexport interface ApplySuggestionRefused {\n status: 'refused';\n filePath: string;\n reason: ApplyRefusalReason;\n /** One sentence naming the refusal, safe to show to the reviewer. */\n detail: string;\n}\n\nexport type ApplySuggestionResult = ApplySuggestionApplied | ApplySuggestionRefused;\n\n/**\n * A `.git` segment at any depth, directory or worktree file: git executes what is in there. `.gitmodules`\n * and the like are reviewed content, gated by diff membership in the session handler instead.\n */\nexport function isRepositoryControlPath(filePath: string): boolean {\n return filePath.split(/[\\\\/]+/).some(segment => segment.toLowerCase() === '.git');\n}\n\nfunction refuse(\n filePath: string,\n reason: ApplyRefusalReason,\n detail: string\n): ApplySuggestionRefused {\n return { status: 'refused', filePath, reason, detail };\n}\n\nconst FS_REFUSALS: Partial<Record<SafeFsErrorCode, [ApplyRefusalReason, string]>> = {\n 'not-found': ['file-missing', 'The file is not in the destination directory.'],\n 'unsafe-link': [\n 'unsafe-target',\n 'The path goes through a symbolic link, and this program does not write through links.',\n ],\n 'not-regular': ['unsafe-target', 'The path is not a regular file.'],\n 'output-is-directory': ['file-unreadable', 'The path is a directory, not a file.'],\n 'unsupported-target': [\n 'unsupported-target',\n 'The file is owned by another user, and replacing it would change its owner.',\n ],\n 'identity-changed': [\n 'file-changed',\n 'The file changed on disk after it was read, so nothing was written.',\n ],\n};\n\nfunction refuseFsError(\n filePath: string,\n error: unknown,\n fallback: 'file-unreadable' | 'write-failed'\n): ApplySuggestionRefused {\n const fsError = toSafeFsError(error, filePath, 'access');\n const [reason, detail] = FS_REFUSALS[fsError.code] ?? [\n fallback,\n `The file could not be ${fallback === 'write-failed' ? 'written' : 'read'} (${errnoOf(fsError.cause) ?? 'unknown'}).`,\n ];\n return refuse(filePath, reason, detail);\n}\n\n/** Purely lexical, so an escape is refused before the filesystem is consulted. */\nfunction relativeWithinRoot(filePath: string): string | null {\n if (filePath === '' || path.posix.isAbsolute(filePath) || path.win32.isAbsolute(filePath)) {\n return null;\n }\n if (filePath.split('/').some(segment => segment === '..')) return null;\n const normalized = path.posix.normalize(filePath);\n if (normalized === '.' || normalized === '..' || normalized.startsWith('../')) return null;\n return normalized;\n}\n\n/**\n * Split file text into lines, keeping each line's own bytes intact.\n *\n * The split is on `\\n` only, so a CRLF file's `\\r` stays at the end of the\n * line it terminates. That makes the comparison against `originalCode`\n * byte-exact (the diff parser hands the same `\\r` through in `DiffLine`),\n * and it means rejoining preserves mixed line endings exactly as found.\n */\nfunction splitLines(content: string): string[] {\n if (content === '') return [];\n const lines = content.split('\\n');\n // A trailing terminator produces an empty final element that is not a line.\n if (lines[lines.length - 1] === '') lines.pop();\n return lines;\n}\n\n/** One trailing `\\n` or `\\r\\n` terminates rather than adds a line; `''` is zero lines (a deletion). */\nfunction proposalLines(proposedCode: string): string[] {\n if (proposedCode === '') return [];\n const body = proposedCode.endsWith('\\r\\n')\n ? proposedCode.slice(0, -2)\n : proposedCode.endsWith('\\n')\n ? proposedCode.slice(0, -1)\n : proposedCode;\n return body.split('\\n');\n}\n\n/**\n * True when every line being replaced carries a CRLF terminator. Only then\n * is it unambiguous that a hand-typed LF proposal should be written back as\n * CRLF; a mixed or LF region takes the proposal verbatim.\n */\nfunction isCrlfRegion(anchored: string[]): boolean {\n return anchored.length > 0 && anchored.every(line => line.endsWith('\\r'));\n}\n\ninterface OpenedTarget {\n identity: FileIdentity;\n buffer: Buffer;\n}\n\n/** Read through the descriptor that was checked, so the bytes compared are the recorded inode's. */\nfunction openAndRead(\n realRoot: string,\n rel: string,\n filePath: string,\n fs: FsLayer\n): OpenedTarget | ApplySuggestionRefused {\n let opened: ReturnType<typeof openContainedFile>;\n try {\n opened = openContainedFile(realRoot, rel, fs);\n } catch (error) {\n return refuseFsError(filePath, error, 'file-unreadable');\n }\n const { fd, stats } = opened;\n try {\n if (stats.nlink > 1) {\n return refuse(\n filePath,\n 'unsafe-target',\n `The file has ${stats.nlink} hard links, and replacing it would silently detach the others.`\n );\n }\n return { identity: snapshotIdentity(stats), buffer: fs.readFileSync(fd) };\n } catch (error) {\n return refuseFsError(filePath, error, 'file-unreadable');\n } finally {\n try {\n fs.closeSync(fd);\n } catch {\n // Read-only descriptor; nothing depends on the close.\n }\n }\n}\n\n/**\n * Apply one anchored suggestion to one file under `destinationRoot`.\n *\n * On a byte-for-byte match between the anchored lines and\n * `suggestion.originalCode`, the anchored lines are replaced with\n * `suggestion.proposedCode` and the file is rewritten. Lines outside the\n * anchor keep their exact bytes, including their line terminators, and the\n * file's trailing-newline state is preserved either way. Any other outcome\n * refuses with a reason and writes nothing.\n */\nexport function applySuggestion(\n request: ApplySuggestionRequest,\n options: ApplySuggestionOptions = {}\n): ApplySuggestionResult {\n const { destinationRoot, filePath, lineRange, suggestion } = request;\n const fs = options.fs ?? nodeFsLayer;\n\n if (!lineRange) {\n return refuse(\n filePath,\n 'no-anchor',\n 'This suggestion is file-level, so there are no lines to replace.'\n );\n }\n if (lineRange.side === 'old') {\n return refuse(\n filePath,\n 'old-side-anchor',\n 'This suggestion is anchored to deleted lines, which are not in the working file.'\n );\n }\n if (lineRange.side !== 'new') {\n return refuse(filePath, 'invalid-anchor', 'The anchor does not name a side of the diff.');\n }\n const anchor = validateLineRange(lineRange);\n if (!anchor.ok) {\n return refuse(\n filePath,\n 'invalid-anchor',\n `The anchor is not a usable range: ${anchor.reason}.`\n );\n }\n const { start, end } = anchor.anchor;\n\n if (!path.isAbsolute(destinationRoot)) {\n return refuse(\n filePath,\n 'destination-not-absolute',\n 'The destination directory must be an absolute path.'\n );\n }\n const rel = relativeWithinRoot(filePath);\n if (rel === null) {\n return refuse(\n filePath,\n 'path-escapes-destination',\n 'The file path resolves outside the destination directory.'\n );\n }\n if (isRepositoryControlPath(rel)) {\n return refuse(\n filePath,\n 'control-file',\n 'The path is repository metadata (.git), which is never part of a review.'\n );\n }\n\n let realRoot: string;\n try {\n realRoot = fs.realpathSync(path.resolve(destinationRoot));\n } catch (error) {\n return refuse(\n filePath,\n 'destination-missing',\n `The destination directory could not be resolved (${errnoOf(error) ?? 'unknown'}).`\n );\n }\n const absolutePath = path.join(realRoot, rel);\n\n const opened = openAndRead(realRoot, rel, filePath, fs);\n if ('status' in opened) return opened;\n const { identity, buffer } = opened;\n\n const content = buffer.toString('utf8');\n if (!Buffer.from(content, 'utf8').equals(buffer)) {\n return refuse(filePath, 'file-not-utf8', 'The file is not valid UTF-8 text.');\n }\n\n const lines = splitLines(content);\n if (end > lines.length) {\n return refuse(\n filePath,\n 'anchor-out-of-range',\n `Lines ${start}-${end} are outside this file, which has ${lines.length} line(s).`\n );\n }\n\n const anchored = lines.slice(start - 1, end);\n if (anchored.join('\\n') !== suggestion.originalCode) {\n return refuse(\n filePath,\n 'context-mismatch',\n `Lines ${start}-${end} no longer match the code this suggestion was written against.`\n );\n }\n\n const proposed = proposalLines(suggestion.proposedCode);\n const replacement = isCrlfRegion(anchored)\n ? proposed.map(line => (line.endsWith('\\r') ? line : `${line}\\r`))\n : proposed;\n const updated = [...lines.slice(0, start - 1), ...replacement, ...lines.slice(end)];\n const output =\n updated.length === 0 ? '' : updated.join('\\n') + (content.endsWith('\\n') ? '\\n' : '');\n\n try {\n atomicReplace(absolutePath, Buffer.from(output, 'utf8'), {\n fs,\n preserveMode: true,\n preserveOwner: true,\n expectedIdentity: identity,\n expectUnmodified: true,\n randomName: options.randomName,\n });\n } catch (error) {\n return refuseFsError(filePath, error, 'write-failed');\n }\n\n return { status: 'applied', filePath, absolutePath, replacedLines: anchored.length };\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 isCommandCancelled,\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(runCommand: ForgeCommandRunner, args: string[]): Promise<string> {\n let result: ForgeCommandResult;\n try {\n result = await runCommand(GH_CLI, args);\n } catch (error) {\n // A run cut short by the session's own bounds is not a missing CLI.\n if (isCommandCancelled(error)) throw error;\n const detail = error instanceof Error ? error.message : String(error);\n throw new ForgeCliUnavailableError('github', GH_CLI, `Failed to run the gh CLI: ${detail}`);\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 *\n * GitHub re-anchors comments on each push, so `line: null` is the forge's own\n * outdated verdict. No `headSha` is carried: `commit_id` cannot be verified to\n * follow re-anchoring, and a lagging SHA would disable every suggestion.\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(runCommand: ForgeCommandRunner): 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('github', GH_CLI, 'gh pr view returned no baseRefName');\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(url: ForgeUrl, _options?: FetchThreadsOptions): 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 { DiffFile, LineRange, Reply, ReviewComment, Suggestion } 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 * How an anchor's line numbers relate to the reviewed head (R05).\n * - `outdated`: forge says so, or `headSha` differs from the reviewed head. Degrades to\n * file-level, since lines of another revision would yield the wrong `originalCode`.\n * - `verified`: names the reviewed head, or the forge vouches for it. The only\n * status that activates a suggestion.\n * - `unverified`: nothing ties it to a revision. Line placement kept, no suggestion.\n */\ntype AnchorStatus = 'verified' | 'unverified' | 'outdated';\n\nfunction classifyAnchor(\n anchor: ForgeThreadAnchor,\n reviewedHeadSha: string | undefined\n): AnchorStatus {\n if (anchor.outdated === true) {\n return 'outdated';\n }\n if (anchor.headSha !== undefined) {\n if (reviewedHeadSha === undefined) return 'unverified';\n return anchor.headSha === reviewedHeadSha ? 'verified' : 'outdated';\n }\n return anchor.outdated === false ? 'verified' : 'unverified';\n}\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, status: AnchorStatus): LineRange | null {\n if (status === '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\n/**\n * Opening line of a fenced code block: up to three spaces of indent, then\n * three or more backticks or tildes, then the info string. A fence indented\n * four spaces or more is an indented code block, not a fence.\n */\nconst FENCE_OPEN = /^( {0,3})(`{3,}|~{3,})(.*)$/;\n\n/** Drop a single trailing CR so a CRLF body yields LF-terminated lines. */\nfunction stripCr(line: string): string {\n return line.endsWith('\\r') ? line.slice(0, -1) : line;\n}\n\n/** Remove up to `width` leading spaces, the way CommonMark unindents a fence. */\nfunction stripIndent(line: string, width: number): string {\n let i = 0;\n while (i < width && line[i] === ' ') i++;\n return line.slice(i);\n}\n\n/** A closing fence: the same character, at least as long, nothing after it. */\nfunction isClosingFence(line: string, marker: string): boolean {\n const match = FENCE_OPEN.exec(line);\n return (\n match !== null &&\n match[2][0] === marker[0] &&\n match[2].length >= marker.length &&\n match[3].trim() === ''\n );\n}\n\n/**\n * Collect the bodies of every top-level ` ```suggestion ` block in a\n * markdown body, in document order.\n *\n * Fences are walked in order so a `suggestion` fence nested inside another\n * code block is never mistaken for a real one. The info string must be the\n * bare word `suggestion`: GitLab's range form (`suggestion:-1+2`) widens the\n * anchor by an amount this mapper cannot verify against the diff, so it is\n * deliberately not recognized and leaves the thread without a suggestion.\n */\nfunction findSuggestionBlocks(body: string): string[] {\n const lines = body.split('\\n').map(stripCr);\n const blocks: string[] = [];\n let i = 0;\n while (i < lines.length) {\n const open = FENCE_OPEN.exec(lines[i]);\n if (!open) {\n i++;\n continue;\n }\n const [, indent, marker, info] = open;\n // A backtick fence's info string may not contain a backtick.\n if (marker[0] === '`' && info.includes('`')) {\n i++;\n continue;\n }\n const content: string[] = [];\n let j = i + 1;\n for (; j < lines.length && !isClosingFence(lines[j], marker); j++) {\n content.push(stripIndent(lines[j], indent.length));\n }\n if (info.trim().toLowerCase() === 'suggestion') {\n blocks.push(content.join('\\n'));\n }\n // An unclosed fence runs to the end of the body, as GitHub renders it.\n i = j + 1;\n }\n return blocks;\n}\n\n/**\n * Read the reviewed lines the anchor points at, straight out of the diff.\n *\n * Returns `null` unless the diff covers the whole range: a partially covered\n * anchor would produce an `originalCode` that matches nothing, and the apply\n * engine's byte-for-byte check would refuse it anyway. Taking the text from\n * the diff rather than from the thread body is what makes the extracted\n * suggestion anchored rather than merely quoted.\n */\nfunction readAnchoredLines(\n diffFiles: DiffFile[],\n filePath: string,\n range: LineRange\n): string | null {\n const sidePath = (file: DiffFile) => (range.side === 'old' ? file.oldPath : file.newPath);\n const file =\n diffFiles.find(f => sidePath(f) === filePath) ??\n diffFiles.find(f => f.oldPath === filePath || f.newPath === filePath);\n if (!file) return null;\n\n const found: string[] = [];\n for (const hunk of file.hunks) {\n for (const line of hunk.lines) {\n const number = range.side === 'old' ? line.oldLineNumber : line.newLineNumber;\n if (number !== null && number >= range.start && number <= range.end) {\n found.push(line.content);\n }\n }\n }\n return found.length === range.end - range.start + 1 ? found.join('\\n') : null;\n}\n\n/**\n * Turn a `suggestion` fence in a thread's root body into an anchored\n * {@link Suggestion}, or `null` when there is nothing safe to anchor.\n *\n * `null` covers every uncertain case: no fence, more than one fence (keeping\n * the first would drop the rest), a file-level, outdated or unverified anchor\n * (see {@link AnchorStatus}), and an anchor the reviewed diff does not cover.\n */\nfunction extractSuggestion(\n body: string,\n filePath: string,\n range: LineRange | null,\n status: AnchorStatus,\n diffFiles: DiffFile[]\n): Suggestion | null {\n if (!range || status !== 'verified') return null;\n const blocks = findSuggestionBlocks(body);\n if (blocks.length !== 1) return null;\n const originalCode = readAnchoredLines(diffFiles, filePath, range);\n if (originalCode === null) return null;\n return { originalCode, proposedCode: blocks[0] };\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 * - A root body carrying a single ` ```suggestion ` fence becomes a\n * `Suggestion` anchored to the thread's line range, with `originalCode`\n * read out of `diffFiles` at that anchor, only when the anchor is verified\n * (see {@link AnchorStatus}). Without the diff, every `suggestion` is `null`.\n * - An anchor naming a head other than `reviewedHeadSha` is outdated and\n * degrades to file-level; its body is intact.\n *\n * `reviewedHeadSha` is the head `diffFiles` was taken against; omitted, every\n * revision-naming anchor is unverified.\n *\n * Output order is input order. The input is never mutated.\n */\nexport function mapThreadsToReviewComments(\n threads: ForgeThread[],\n diffFiles: DiffFile[] = [],\n reviewedHeadSha?: string\n): ReviewComment[] {\n return threads.map(thread => {\n const filePath = thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH;\n const status = thread.anchor ? classifyAnchor(thread.anchor, reviewedHeadSha) : 'unverified';\n const lineRange = thread.anchor ? mapAnchorToLineRange(thread.anchor, status) : null;\n const comment: ReviewComment = {\n id: internalId(thread.root),\n filePath,\n lineRange,\n body: thread.root.body,\n category: '',\n suggestion: extractSuggestion(thread.root.body, filePath, lineRange, status, diffFiles),\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 isCommandCancelled,\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 head_sha?: string | null;\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 // A run cut short by the session's own bounds is not a missing CLI.\n if (isCommandCancelled(error)) throw 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 exposes outdatedness only as `position.head_sha`, so the anchor carries\n * `headSha` verbatim and no `outdated` verdict; the mapper compares it with the\n * reviewed head, and a position naming no head stays unverifiable.\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' ? 'old' : '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 const anchor: ForgeThreadAnchor = { filePath, side, startLine, endLine };\n if (typeof position.head_sha === 'string' && position.head_sha.length > 0) {\n anchor.headSha = position.head_sha;\n }\n return anchor;\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// Every run owns its snapshot: base and head are fetched into\n// `refs/self-review/<session>/base|head` and the SHAs read from exactly those refs,\n// so concurrent sessions never see each other's SHAs (R16). Every git command runs\n// under the session's `AbortSignal` and a per-command timeout.\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 { spawn } from 'child_process';\nimport { randomUUID } from 'crypto';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { stripTrailingNewline } from './git';\nimport { CommandCancelledError } from './forge-provider';\nimport type {\n CommandCancelReason,\n ForgeCommandOptions,\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 * Refs this session created in a reused clone and deletes on cleanup; empty for a temp clone.\n */\n ownedRefs: readonly string[];\n /**\n * Removes the temp clone (synchronously, before the first await, so an `exit`\n * handler that cannot wait still gets that far) and deletes the session's refs\n * from a reused clone. Idempotent, never rejects; a failed deletion goes to stderr.\n */\n cleanup: () => Promise<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\nexport interface MaterializeOptions {\n /**\n * Aborting kills the command in flight and rejects with {@link CommandCancelledError}; the temp\n * clone is removed first.\n */\n signal?: AbortSignal;\n /** Defaults to {@link DEFAULT_GIT_COMMAND_TIMEOUT_MS}. */\n commandTimeoutMs?: number;\n}\n\n/**\n * Generous because a blobless clone over a slow link is legitimately slow; tighter hosts abort via\n * the signal.\n */\nexport const DEFAULT_GIT_COMMAND_TIMEOUT_MS = 10 * 60 * 1000;\n\nconst CLEANUP_COMMAND_TIMEOUT_MS = 15_000;\n\nconst KILL_GRACE_MS = 2_000;\n\nconst MAX_OUTPUT_BYTES = 50 * 1024 * 1024;\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 the real binary. Rejects on spawn failure, on output over\n * the buffer cap, and with {@link CommandCancelledError} on abort or timeout (SIGTERM,\n * then SIGKILL after {@link KILL_GRACE_MS}; settles once the child exited).\n *\n * Deliberately not in its own process group: that would detach the controlling\n * terminal and silently disable git's and ssh's credential prompts.\n */\nexport const defaultGitRunner: ForgeCommandRunner = (command, args, options = {}) =>\n new Promise<ForgeCommandResult>((resolve, reject) => {\n const { signal, timeoutMs } = options;\n if (signal?.aborted) {\n reject(new CommandCancelledError('aborted', command, args));\n return;\n }\n\n const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n let outputBytes = 0;\n let settled = false;\n let cancelled: CommandCancelReason | null = null;\n let overflowed = false;\n let killTimer: NodeJS.Timeout | undefined;\n let timeoutTimer: NodeJS.Timeout | undefined;\n\n const killChild = () => {\n child.kill('SIGTERM');\n killTimer = setTimeout(() => {\n if (!settled) child.kill('SIGKILL');\n }, KILL_GRACE_MS);\n };\n const cancel = (reason: CommandCancelReason) => {\n if (settled || cancelled !== null) return;\n cancelled = reason;\n killChild();\n };\n const onAbort = () => cancel('aborted');\n signal?.addEventListener('abort', onAbort, { once: true });\n if (timeoutMs !== undefined && timeoutMs > 0) {\n timeoutTimer = setTimeout(() => cancel('timeout'), timeoutMs);\n }\n\n const settle = (outcome: () => void) => {\n if (settled) return;\n settled = true;\n if (killTimer) clearTimeout(killTimer);\n if (timeoutTimer) clearTimeout(timeoutTimer);\n signal?.removeEventListener('abort', onAbort);\n outcome();\n };\n\n const collect = (sink: Buffer[]) => (chunk: Buffer) => {\n outputBytes += chunk.length;\n if (outputBytes > MAX_OUTPUT_BYTES) {\n if (!overflowed) {\n overflowed = true;\n killChild();\n }\n return;\n }\n sink.push(chunk);\n };\n child.stdout?.on('data', collect(stdout));\n child.stderr?.on('data', collect(stderr));\n\n child.on('error', error => settle(() => reject(error)));\n\n // A helper (ssh waiting on the terminal) may hold our pipes; closing them lets `close` follow\n // `exit`.\n child.on('exit', () => {\n if (cancelled !== null || overflowed) {\n child.stdout?.destroy();\n child.stderr?.destroy();\n }\n });\n\n child.on('close', (code, exitSignal) =>\n settle(() => {\n if (cancelled !== null) {\n reject(new CommandCancelledError(cancelled, command, args));\n return;\n }\n if (overflowed) {\n reject(\n new Error(`${command} ${args.join(' ')} produced more than ${MAX_OUTPUT_BYTES} bytes`)\n );\n return;\n }\n let stderrText = Buffer.concat(stderr).toString('utf-8');\n if (code === null && exitSignal) {\n stderrText += `${stderrText.endsWith('\\n') || stderrText === '' ? '' : '\\n'}(killed by ${exitSignal})\\n`;\n }\n resolve({\n stdout: Buffer.concat(stdout).toString('utf-8'),\n stderr: stderrText,\n exitCode: code ?? 1,\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\n/** The refs one session fetches into. Unique per call. */\nfunction sessionRefs(): { base: string; head: string } {\n const session = randomUUID();\n return {\n base: `refs/self-review/${session}/base`,\n head: `refs/self-review/${session}/head`,\n };\n}\n\n/** A git runner bound to one session's bounds: `git <args>` under its signal and timeout. */\ntype SessionGit = (args: string[]) => Promise<ForgeCommandResult>;\n\nfunction bindGit(runner: ForgeCommandRunner, options: MaterializeOptions): SessionGit {\n const commandOptions: ForgeCommandOptions = {\n signal: options.signal,\n timeoutMs: options.commandTimeoutMs ?? DEFAULT_GIT_COMMAND_TIMEOUT_MS,\n };\n return args => {\n // A scripted runner may ignore the signal; the answer must not depend on the runner.\n if (options.signal?.aborted) {\n return Promise.reject(new CommandCancelledError('aborted', 'git', args));\n }\n return runner('git', args, commandOptions);\n };\n}\n\nfunction gitFailure(what: string, result: ForgeCommandResult, withAuthHint: boolean): 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(raw: string): { 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(git: SessionGit, repoPath: string, ref: string): Promise<string> {\n const result = await 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/** One fetch into this session's refs, SHAs read back from exactly those refs. */\nasync function fetchSnapshot(\n git: SessionGit,\n repoPath: string,\n remote: string,\n url: ForgeUrl,\n baseBranch: string,\n refs: { base: string; head: string },\n failureLabel: string\n): Promise<{ baseSha: string; headSha: string }> {\n // Forced refspecs are fine: these refs are ours alone.\n const fetch = await git([\n '-C',\n repoPath,\n 'fetch',\n remote,\n `+refs/heads/${baseBranch}:${refs.base}`,\n `+${headRefFor(url)}:${refs.head}`,\n ]);\n if (fetch.exitCode !== 0) {\n throw gitFailure(failureLabel, fetch, true);\n }\n return {\n baseSha: await revParse(git, repoPath, refs.base),\n headSha: await revParse(git, repoPath, refs.head),\n };\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 options: MaterializeOptions = {}\n): Promise<ExistingClone | null> {\n const git = bindGit(runner, options);\n const toplevel = await git(['-C', cwd, 'rev-parse', '--show-toplevel']);\n if (toplevel.exitCode !== 0) {\n return null;\n }\n // A blanket .trim() would eat whitespace that is part of the actual path\n // (SR-0047, same defect class as SR-0036's git.ts fix), reporting a root\n // short of what's on disk and breaking the `remote -v` call right after.\n const repoPath = stripTrailingNewline(toplevel.stdout);\n const remotes = await 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 options: MaterializeOptions,\n url: ForgeUrl,\n baseBranch: string,\n repoPath: string,\n remoteName: string\n): Promise<MaterializeResult> {\n console.error(`self-review: reusing existing clone at ${repoPath} (remote \"${remoteName}\")`);\n const git = bindGit(runner, options);\n const refs = sessionRefs();\n const ownedRefs = [refs.base, refs.head];\n\n // Not under the session signal: an aborted session must still release its refs.\n let released = false;\n const cleanup = async (): Promise<void> => {\n if (released) return;\n released = true;\n for (const ref of ownedRefs) {\n try {\n const result = await runner('git', ['-C', repoPath, 'update-ref', '-d', ref], {\n timeoutMs: CLEANUP_COMMAND_TIMEOUT_MS,\n });\n if (result.exitCode !== 0) {\n console.error(\n `self-review: could not delete ${ref} in ${repoPath}: ${result.stderr.trim()}`\n );\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`self-review: could not delete ${ref} in ${repoPath}: ${message}`);\n }\n }\n };\n\n // Namespaced refs only: no checkout, branch or working-tree change. A part-way\n // failure may have created one ref, so release them before rethrowing.\n try {\n const { baseSha, headSha } = await fetchSnapshot(\n git,\n repoPath,\n remoteName,\n url,\n baseBranch,\n refs,\n `fetch from remote \"${remoteName}\"`\n );\n return { repoPath, baseSha, headSha, mode: 'existing-clone', ownedRefs, cleanup };\n } catch (error) {\n await cleanup();\n throw error;\n }\n}\n\nasync function materializeIntoTempClone(\n runner: ForgeCommandRunner,\n options: MaterializeOptions,\n url: ForgeUrl,\n baseBranch: string\n): Promise<MaterializeResult> {\n const git = bindGit(runner, options);\n // This run creates the directory, so cleanup may only ever remove it; it is owned\n // from here on, before any git runs.\n const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'self-review-'));\n let removed = false;\n const cleanup = async (): Promise<void> => {\n if (removed) return;\n removed = true;\n fs.rmSync(tempDir, { recursive: true, force: true });\n };\n\n try {\n console.error(`self-review: created temporary blobless clone at ${tempDir}`);\n const cloneUrl = cloneUrlFor(url);\n // Blobless, never shallow: --depth would break merge-base computation.\n const clone = await git(['clone', '--filter=blob:none', cloneUrl, tempDir]);\n if (clone.exitCode !== 0) {\n throw gitFailure(`clone of ${cloneUrl}`, clone, true);\n }\n const { baseSha, headSha } = await fetchSnapshot(\n git,\n tempDir,\n 'origin',\n url,\n baseBranch,\n sessionRefs(),\n `fetch of ${headRefFor(url)}`\n );\n return { repoPath: tempDir, baseSha, headSha, mode: 'temp-clone', ownedRefs: [], cleanup };\n } catch (error) {\n await 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/<session>/` (read-only for the working tree; `cleanup()`\n * deletes exactly those two refs). Otherwise a blobless clone is created in a\n * unique directory under the OS temp root and `cleanup()` removes it. Callers\n * that already detected a clone may pass it to skip 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 options: MaterializeOptions = {}\n): Promise<MaterializeResult> {\n if (options.signal?.aborted) {\n throw new CommandCancelledError('aborted', 'git', ['materialize', cloneUrlFor(url)]);\n }\n const existing =\n existingClone === undefined\n ? await detectExistingClone(url, cwd, runner, options)\n : existingClone;\n if (existing) {\n return materializeIntoExistingClone(\n runner,\n options,\n url,\n baseBranch,\n existing.repoPath,\n existing.remoteName\n );\n }\n return materializeIntoTempClone(runner, options, 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 options: MaterializeOptions = {}\n): Promise<string> {\n const git = bindGit(runner, options);\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 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","// packages/core/src/review-handlers.ts\n// Transport-agnostic review handler bodies.\n//\n// Every function here takes the session it operates on as a parameter and\n// returns a value. Nothing in this module reaches state that is not reachable\n// through that parameter, and nothing in it touches Electron: the registration\n// layer (src/main/ipc-handlers.ts) owns the transport and does the sending.\n\nimport * as fs from 'fs';\nimport path from 'path';\nimport {\n DiffLoadPayload,\n DiffFile,\n DiffHunk,\n ResumeLoadPayload,\n GuideLoadPayload,\n AppConfig,\n OutputPathInfo,\n PayloadStats,\n ReviewState,\n ReviewComment,\n ReviewSourceIdentity,\n ExpandContextRequest,\n ImageLoadResult,\n RemoteDriftInfo,\n SuggestionApplyRequest,\n SuggestionApplyOutcome,\n ApplyDestinationOutcome,\n} from './types';\nimport { scanDirectory, scanFile } from './directory-scanner';\nimport { singleFileRediffArgs } from './git-diff-args';\nimport { computePayloadStats, countTotalLines } from './payload-sizing';\nimport { applySuggestion } from './apply-suggestion';\nimport { MAX_GIT_DIFF_OUTPUT_BYTES, MAX_IMAGE_BYTES } from './input-budgets';\nimport { isPreviewableImage } from './file-type-utils';\nimport { readReviewedContent } from './snapshot-reader';\nimport { resolveLocalSourceIdentity, rootRelativeReviewedPath } from './source-identity';\nimport {\n authorizeAttachmentReference,\n readAssetFile,\n resolveAttachmentOrigins,\n} from './attachment-origins';\nimport type { AttachmentOrigins, AttachmentReadResult } from './attachment-origins';\nimport { ASSET_DIR_NAME } from './xml-serializer';\n\n/**\n * The state a single review session owns. One desktop application window is\n * one session; two sessions are independent and cannot observe each other.\n */\nexport interface ReviewSession {\n reviewState: ReviewState | null;\n diffData: DiffLoadPayload | null;\n guideData: GuideLoadPayload | null;\n config: AppConfig | null;\n outputPathInfo: OutputPathInfo | null;\n resumeComments: ReviewComment[];\n resumeViewedFiles: string[];\n resumeRemoteDrift: RemoteDriftInfo | null;\n resumeImportDiagnostics: string[];\n /**\n * Destination directory the user named for this session's applies, or\n * null when none has been named. Only a temporary-clone remote review\n * needs one; see {@link resolveApplyDestination}.\n */\n applyDestinationRoot: string | null;\n /**\n * Old and new path of every file in the committed diff, frozen by {@link commitDiffData}.\n * The authorization set for writes; resumed comments, submitted state and placeholder\n * entries can name other paths and never reach it.\n */\n reviewedPaths: ReadonlySet<string>;\n /**\n * Recorded by {@link commitDiffData}; null until then (and for welcome), when every read of\n * reviewed content refuses.\n */\n sourceIdentity: ReviewSourceIdentity | null;\n /**\n * Resumed reference to absolute path beside *the resumed document*; authorizes reads and tells\n * the publisher which bytes to carry. Never sent to the front end.\n */\n attachmentOrigins: AttachmentOrigins;\n}\n\n/** Create an empty session. */\nexport function createReviewSession(): ReviewSession {\n return {\n reviewState: null,\n diffData: null,\n guideData: null,\n config: null,\n outputPathInfo: null,\n resumeComments: [],\n resumeViewedFiles: [],\n resumeRemoteDrift: null,\n resumeImportDiagnostics: [],\n applyDestinationRoot: null,\n reviewedPaths: emptyReviewedPaths(),\n sourceIdentity: null,\n attachmentOrigins: new Map(),\n };\n}\n\nfunction emptyReviewedPaths(): ReadonlySet<string> {\n return freezeSet(new Set<string>());\n}\n\nfunction freezeSet(set: Set<string>): ReadonlySet<string> {\n const frozen = () => {\n throw new TypeError('reviewedPaths is captured when the diff is committed and cannot change');\n };\n Object.defineProperties(set, {\n add: { value: frozen },\n delete: { value: frozen },\n clear: { value: frozen },\n });\n return Object.freeze(set);\n}\n\nfunction reviewedPathsOf(files: readonly DiffFile[]): ReadonlySet<string> {\n const paths = new Set<string>();\n for (const file of files) {\n if (file.newPath) paths.add(file.newPath);\n if (file.oldPath) paths.add(file.oldPath);\n }\n return freezeSet(paths);\n}\n\n/**\n * The one place a diff is committed to a session: captures `reviewedPaths` and\n * records `sourceIdentity`; later `diffData` edits (expanded hunks) leave both alone.\n * The identity comes from the loader, and is `null` only for a payload that\n * reviews nothing (welcome), so reads refuse rather than guess a root.\n */\nexport function commitDiffData(\n session: ReviewSession,\n payload: DiffLoadPayload,\n identity: ReviewSourceIdentity | null\n): void {\n session.diffData = payload;\n session.reviewedPaths = reviewedPathsOf(payload.files);\n session.sourceIdentity = identity;\n}\n\n/**\n * The old side is where a deletion or a rename's old name lives. Null when the diff has no such\n * file.\n */\nexport function locateReviewedFile(\n session: ReviewSession,\n filePath: string\n): { file: DiffFile; side: 'old' | 'new' } | null {\n const files = session.diffData?.files ?? [];\n const byNewPath = files.find(f => f.newPath !== '' && f.newPath === filePath);\n if (byNewPath) return { file: byNewPath, side: 'new' };\n const byOldPath = files.find(f => f.oldPath !== '' && f.oldPath === filePath);\n if (byOldPath) return { file: byOldPath, side: 'old' };\n return null;\n}\n\n/**\n * Prepare a DiffLoadPayload for IPC transmission.\n * In large-payload mode, strips hunks from files to reduce initial transfer size.\n * The full data stays in the session for on-demand loading via DIFF_LOAD_FILE.\n */\nexport function preparePayload(payload: DiffLoadPayload): DiffLoadPayload {\n if (payload.isLargePayload) {\n return {\n ...payload,\n files: payload.files.map(f => ({ ...f, hunks: [] as DiffHunk[], contentLoaded: false })),\n };\n }\n return {\n ...payload,\n files: payload.files.map(f => ({ ...f, contentLoaded: true })),\n };\n}\n\n/**\n * Resolve what a diff request should deliver: the prepared diff payload and,\n * when one is loaded, the guide that rides with it. Returns null when the\n * session has no diff, so the caller sends nothing at all.\n */\nexport function getDiffLoad(\n session: ReviewSession\n): { diff: DiffLoadPayload; guide: GuideLoadPayload | null } | null {\n if (!session.diffData) {\n return null;\n }\n // The guide rides after the diff payload in both normal and\n // large-payload modes — it is metadata-only (paths, names,\n // descriptions) and never triggers eager hunk loading.\n return {\n diff: preparePayload(session.diffData),\n guide: session.guideData,\n };\n}\n\n/** The read-only source root; {@link resolveApplyDestination} decides where applies write. */\nexport function resolveSourceBaseDir(session: ReviewSession): string | null {\n return session.sourceIdentity?.sourceRoot ?? null;\n}\n\nconst IMAGE_MIME_TYPES: Record<string, string> = {\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.bmp': 'image/bmp',\n};\n\n/**\n * Reads from the snapshot the review compared, never the current working tree; only reviewed,\n * previewable paths are read.\n */\nexport async function loadImage(\n session: ReviewSession,\n filePath: string\n): Promise<ImageLoadResult> {\n if (!session.reviewedPaths.has(filePath)) {\n return { error: 'Image preview unavailable — this file is not part of the reviewed diff.' };\n }\n if (!isPreviewableImage(filePath)) {\n return { error: 'Image preview unavailable — this file is not a previewable image.' };\n }\n const located = locateReviewedFile(session, filePath);\n const side = located?.side ?? 'new';\n\n const result = await readReviewedContent(session, filePath, side, { maxBytes: MAX_IMAGE_BYTES });\n if (!result.ok) {\n if (result.reason === 'too-large') {\n return { error: 'File too large to preview (>10 MB)' };\n }\n console.error(`[review] Image preview unavailable for ${filePath}: ${result.message}`);\n return { error: `Image preview unavailable — ${result.message}` };\n }\n const mimeType = IMAGE_MIME_TYPES[path.posix.extname(filePath).toLowerCase()];\n return { dataUri: `data:${mimeType};base64,${result.content.toString('base64')}` };\n}\n\n/** Zero when unreadable; the caller treats that as unknown. */\nasync function countReviewedLines(session: ReviewSession, file: DiffFile): Promise<number> {\n const side = file.newPath ? 'new' : 'old';\n const filePath = side === 'new' ? file.newPath : file.oldPath;\n const result = await readReviewedContent(session, filePath, side, {\n maxBytes: MAX_GIT_DIFF_OUTPUT_BYTES,\n });\n if (!result.ok) {\n console.error(`[review] Line count unavailable for ${filePath}: ${result.message}`);\n return 0;\n }\n return countLines(result.content);\n}\n\nfunction countLines(content: Buffer): number {\n let newlines = 0;\n for (const byte of content) {\n if (byte === 0x0a) newlines++;\n }\n return content.length > 0 && content[content.length - 1] === 0x0a ? newlines : newlines + 1;\n}\n\n/**\n * Return a single file's hunks for lazy (large-payload) mode, or null when the\n * session has no diff or the diff has no such file.\n */\nexport function getFileHunks(session: ReviewSession, filePath: string): DiffHunk[] | null {\n if (!session.diffData) return null;\n const file = session.diffData.files.find(f => (f.newPath || f.oldPath) === filePath);\n if (!file) return null;\n return file.hunks;\n}\n\n/**\n * Resolve the config and the output path info that travel with it. Returns null\n * when the session has no config, so the caller sends nothing at all: the\n * renderer distinguishes an absent message from an empty one.\n */\nexport function getConfigLoad(\n session: ReviewSession\n): { config: AppConfig; outputPathInfo: OutputPathInfo | null } | null {\n if (!session.config) {\n return null;\n }\n return { config: session.config, outputPathInfo: session.outputPathInfo };\n}\n\n/**\n * Store a review state submitted by the front end on the session.\n */\nexport function submitReviewState(session: ReviewSession, state: ReviewState): void {\n console.error(\n '[review] Review state submitted:',\n JSON.stringify({\n timestamp: state.timestamp,\n source: state.source,\n fileCount: state.files.length,\n })\n );\n session.reviewState = state;\n}\n\n/**\n * Take the submitted review state off the session, clearing it so it is\n * consumed exactly once. Returns null when nothing has been submitted.\n */\nexport function takeReviewState(session: ReviewSession): ReviewState | null {\n const state = session.reviewState;\n session.reviewState = null;\n return state;\n}\n\n/**\n * True when this session reviews a remote PR/MR that was materialized into\n * a temporary clone. That clone is removed when the app exits, so a write\n * into it is lost the moment the review ends (PRD Section 5.4.8).\n */\nexport function isTemporaryCloneSession(session: ReviewSession): boolean {\n return session.diffData?.remote?.temporaryClone === true;\n}\n\n/** Canonical form of a path, following symlinks when the path exists. */\nfunction canonicalize(target: string): string {\n try {\n return fs.realpathSync(target);\n } catch {\n return path.resolve(target);\n }\n}\n\n/** True when `candidate` is `root` itself or sits anywhere beneath it. */\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(canonicalize(root), canonicalize(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/**\n * The directory an apply may write into for this session, or null when the\n * session has none.\n *\n * For every review whose files sit in a place the user controls — a git\n * working tree, a scanned directory, a reused remote clone — that is the\n * root the reviewed paths are relative to, and no one is asked anything.\n *\n * A temporary-clone review is the one exception. Its files live in a\n * directory the app deletes on exit, so the clone is never a destination:\n * the answer is the directory the user named, and null until they name one.\n */\nexport function resolveApplyDestination(session: ReviewSession): string | null {\n if (isTemporaryCloneSession(session)) {\n return session.applyDestinationRoot;\n }\n return resolveSourceBaseDir(session);\n}\n\n/**\n * Record the directory the user named as this session's apply destination.\n *\n * The caller supplies a path the user picked; this decides whether it can\n * be written into and stores it only if so. The temporary clone, and\n * anything inside it, is refused however it was reached — that directory\n * is gone when the review ends, which is the whole reason a destination is\n * asked for.\n */\nexport function setApplyDestination(\n session: ReviewSession,\n directoryPath: string\n): ApplyDestinationOutcome {\n if (!path.isAbsolute(directoryPath)) {\n return {\n status: 'rejected',\n reason: 'destination-not-absolute',\n detail: 'Pick a destination by its full path.',\n };\n }\n\n let isDirectory = false;\n try {\n isDirectory = fs.statSync(directoryPath).isDirectory();\n } catch {\n isDirectory = false;\n }\n if (!isDirectory) {\n return {\n status: 'rejected',\n reason: 'destination-not-a-directory',\n detail: 'That destination is not a directory that exists.',\n };\n }\n\n const clonePath = isTemporaryCloneSession(session) ? resolveSourceBaseDir(session) : null;\n if (clonePath && isWithin(clonePath, directoryPath)) {\n return {\n status: 'rejected',\n reason: 'destination-inside-temporary-clone',\n detail:\n 'That directory is inside the temporary clone, which is deleted when the review ends.',\n };\n }\n\n session.applyDestinationRoot = canonicalize(directoryPath);\n console.error(`[suggestion:apply] destination set for this session`);\n return { status: 'chosen', destinationRoot: session.applyDestinationRoot };\n}\n\n/**\n * Apply one suggestion to the reviewed working file, or refuse and write\n * nothing. The engine does the work; this handler names the destination, which\n * the engine never derives, and authorizes the target.\n *\n * Authorization is membership in {@link ReviewSession.reviewedPaths}\n * (`not-reviewed` otherwise), so a resumed document or a client reaching this\n * handler cannot name an unreviewed file. The request is not bound to a\n * comment (the session keeps no registry of live suggestions); the binding is\n * the anchor plus the engine's byte-exact `originalCode` match.\n *\n * The engine gets the path through the identity's prefix, so a `--relative`\n * review of `sub/` writes `sub/<path>`, never the root's same-named file.\n *\n * A refusal travels as a value, never a thrown error.\n */\nexport function applySuggestionForSession(\n session: ReviewSession,\n request: SuggestionApplyRequest\n): SuggestionApplyOutcome {\n const destinationRoot = resolveApplyDestination(session);\n const identity = session.sourceIdentity;\n if (!destinationRoot || identity === null) {\n const temporary = isTemporaryCloneSession(session);\n return {\n status: 'refused',\n filePath: request.filePath,\n reason: temporary ? 'destination-required' : 'no-destination',\n detail: temporary\n ? 'This pull request was cloned into a temporary directory that is deleted when the review ends. Choose a destination directory to apply into.'\n : 'This review has no working directory to write into.',\n };\n }\n\n if (!session.reviewedPaths.has(request.filePath)) {\n console.error(`[suggestion:apply] ${request.filePath}: refused (not-reviewed)`);\n return {\n status: 'refused',\n filePath: request.filePath,\n reason: 'not-reviewed',\n detail: 'This file is not part of the reviewed diff, so nothing was written.',\n };\n }\n\n const result = applySuggestion({\n destinationRoot,\n filePath: rootRelativeReviewedPath(identity, request.filePath),\n lineRange: request.lineRange,\n suggestion: request.suggestion,\n });\n console.error(\n `[suggestion:apply] ${request.filePath}: ${\n result.status === 'applied' ? 'applied' : `refused (${result.reason})`\n }`\n );\n\n // Projected field by field rather than passed through. The engine also\n // reports the resolved absolute path, which the front end has no use for\n // and should not be handed; naming the fields here keeps the wire shape\n // exactly what SuggestionApplyOutcome declares, today and after the engine\n // grows a field. The path is the request's, not the engine's root-relative one.\n if (result.status === 'applied') {\n return {\n status: 'applied',\n filePath: request.filePath,\n replacedLines: result.replacedLines,\n };\n }\n return {\n status: 'refused',\n filePath: request.filePath,\n reason: result.reason,\n detail: result.detail,\n };\n}\n\n/**\n * Records that resumed attachments live beside the resumed document, whatever the\n * launch directory or save location. Returns one diagnostic per reference that is\n * not `.self-review-assets/<name>` and so will never be read.\n */\nexport function recordResumedAttachments(\n session: ReviewSession,\n comments: readonly ReviewComment[],\n resumeDocumentPath: string\n): string[] {\n const { origins, diagnostics } = resolveAttachmentOrigins(comments, resumeDocumentPath);\n session.attachmentOrigins = origins;\n return diagnostics;\n}\n\n/**\n * Read one attachment by its `.self-review-assets/<name>` reference, never a path:\n * an imported one from its recorded origin, any other from the current output's asset\n * directory. Anything else is `not-authorized` and touches nothing.\n */\nexport async function readAttachment(\n session: ReviewSession,\n reference: unknown\n): Promise<AttachmentReadResult> {\n const outputPath = session.outputPathInfo?.resolvedOutputPath;\n const currentAssetDir = outputPath ? path.join(path.dirname(outputPath), ASSET_DIR_NAME) : null;\n const assetPath = authorizeAttachmentReference(\n reference,\n session.attachmentOrigins,\n currentAssetDir\n );\n if (assetPath === null) {\n console.error(`[attachment:read] Refused: ${JSON.stringify(reference)}`);\n return {\n ok: false,\n reason: 'not-authorized',\n message: `Attachments are read only from the review's ${ASSET_DIR_NAME} directory`,\n };\n }\n const result = await readAssetFile(assetPath);\n if (!result.ok) {\n console.error(`[attachment:read] ${result.reason}: ${result.message}`);\n }\n return result;\n}\n\n/**\n * Resolve the resumed comments, viewed files and remote drift for a session.\n * Returns null when there is nothing to resume, so the caller sends nothing\n * at all.\n */\nexport function getResumeLoad(session: ReviewSession): ResumeLoadPayload | null {\n if (\n session.resumeComments.length > 0 ||\n session.resumeViewedFiles.length > 0 ||\n session.resumeRemoteDrift !== null ||\n session.resumeImportDiagnostics.length > 0\n ) {\n const payload: ResumeLoadPayload = {\n comments: session.resumeComments,\n viewedFiles: session.resumeViewedFiles,\n };\n if (session.resumeRemoteDrift !== null) {\n payload.remoteDrift = session.resumeRemoteDrift;\n }\n if (session.resumeImportDiagnostics.length > 0) {\n payload.importDiagnostics = session.resumeImportDiagnostics;\n }\n return payload;\n }\n return null;\n}\n\n/**\n * Re-run the review's own git diff over one file with more context, via\n * {@link singleFileRediffArgs}. Git runs at the source root; a `--relative` review is\n * restated with the prefix resolved at load time, and the file's paths (both, for a\n * rename or copy, so git pairs them) are root-relative literal pathspecs. The entry\n * returned is the one matching the file's old and new paths, not git's first.\n *\n * Expanded hunks are written back to the session's diff data. Returns null when\n * there is no git diff or tracked file, git's output lacks the file, or git fails.\n */\nexport async function expandContext(\n session: ReviewSession,\n request: ExpandContextRequest\n): Promise<{ hunks: DiffHunk[]; totalLines: number } | null> {\n const diffData = session.diffData;\n const identity = session.sourceIdentity;\n if (!diffData || diffData.source.type !== 'git' || identity === null) {\n return null;\n }\n if (identity.mode !== 'git' && identity.mode !== 'remote') {\n return null;\n }\n if (!Number.isSafeInteger(request.contextLines) || request.contextLines < 0) {\n return null;\n }\n // Untracked files are synthetic additions git never compared.\n const target = diffData.files.find(\n f => !f.isUntracked && (f.newPath || f.oldPath) === request.filePath\n );\n if (!target) {\n return null;\n }\n\n try {\n const { runGitDiffAsync } = await import('./git');\n const { parseDiff } = await import('./diff-parser');\n\n const rediff = singleFileRediffArgs(identity.gitDiffArgv);\n const prefix = identity.pathPrefix;\n const paths = [...new Set([target.oldPath, target.newPath].filter(p => p !== ''))];\n const expandArgs = [\n ...rediff.args,\n ...(prefix === '' ? [] : [`--relative=${prefix}`]),\n `-U${request.contextLines}`,\n '--',\n ...paths.map(p => `:(top,literal)${rootRelativeReviewedPath(identity, p)}`),\n ];\n\n // Never the process cwd.\n const rawDiff = await runGitDiffAsync(expandArgs, identity.sourceRoot);\n const expandedFile = parseDiff(rawDiff).find(\n f => f.oldPath === target.oldPath && f.newPath === target.newPath\n );\n if (!expandedFile) {\n console.error(`[review] Expanded diff for ${request.filePath} did not contain the file`);\n return null;\n }\n\n // The reviewed side's length, for gap detection; zero keeps the bars visible.\n const totalLines = await countReviewedLines(session, target);\n\n session.diffData = {\n ...diffData,\n files: diffData.files.map(f => (f === target ? { ...f, hunks: expandedFile.hunks } : f)),\n };\n\n return { hunks: expandedFile.hunks, totalLines };\n } catch (error) {\n console.error(`[review] Failed to expand context for ${request.filePath}:`, error);\n return null;\n }\n}\n\n/**\n * What a review start produced: the payload built from the scanned path, the\n * stats it was measured against (null when the session has no config, in which\n * case no thresholds apply), and whether those stats exceeded a threshold.\n *\n * The payload is deliberately *not* stored on the session: the caller may still\n * need to abandon it (a user declining a large review keeps the review they\n * were already looking at), so committing it is the caller's decision.\n */\nexport interface ReviewStartResult {\n payload: DiffLoadPayload;\n identity: ReviewSourceIdentity;\n stats: PayloadStats | null;\n exceedsThresholds: boolean;\n}\n\n/**\n * Scan a picked path and build the diff payload for a directory (or single\n * file) review, measured against the session's large-payload thresholds.\n * Nothing is stored on the session — see `ReviewStartResult`.\n */\nexport async function prepareDirectoryReview(\n session: ReviewSession,\n directoryPath: string\n): Promise<ReviewStartResult> {\n console.error('[review] Starting directory review for:', directoryPath);\n\n // Check if the path is a file (not a directory)\n let isFile = false;\n try {\n isFile = fs.statSync(directoryPath).isFile();\n } catch {\n // Failed to stat — proceed as directory\n }\n\n // Scan diagnostics ride on the payload so a failed load never looks empty.\n const scan = isFile\n ? await scanFile(directoryPath)\n : await scanDirectory(directoryPath, session.config?.ignore ?? []);\n const type = isFile ? 'file' : 'directory';\n const payload: DiffLoadPayload = {\n files: scan.files,\n source: { type, sourcePath: directoryPath },\n ...(scan.diagnostics.length > 0 ? { diagnostics: scan.diagnostics } : {}),\n };\n const identity = resolveLocalSourceIdentity({ type, sourcePath: directoryPath });\n\n // Large payload guard — skipped entirely when there is no config.\n if (!session.config) {\n return { payload, identity, stats: null, exceedsThresholds: false };\n }\n const stats = computePayloadStats(\n payload.files.length,\n countTotalLines(payload.files),\n session.config\n );\n return { payload, identity, stats, exceedsThresholds: stats.exceedsAny };\n}\n\n/**\n * Commit a prepared review payload to the session, once the caller has decided\n * it should proceed. Returns the payload to hand to the transport.\n */\nexport function commitReviewStart(\n session: ReviewSession,\n payload: DiffLoadPayload,\n identity: ReviewSourceIdentity | null\n): DiffLoadPayload {\n commitDiffData(session, payload, identity);\n return preparePayload(payload);\n}\n","// packages/core/src/startup-mode.ts\n// Startup mode detection: what the app should review, from the CLI args and the CWD.\n\nimport { existsSync, statSync } from 'fs';\nimport { execFileSync, execSync } from 'child_process';\nimport { resolve } from 'path';\nimport { classifyGitDiffArgs } from './git-diff-args';\n\n/**\n * Check if `cwd` is inside a git repository.\n */\nfunction isInGitRepo(cwd: string): boolean {\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore', cwd });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file is tracked by git (known to the index).\n */\nfunction isGitTracked(filePath: string, cwd: string): boolean {\n try {\n execFileSync('git', ['ls-files', '--error-unmatch', '--', filePath], {\n stdio: 'ignore',\n cwd,\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * What a review starts from; `welcome` means nothing to review (desktop shows its picker, serve\n * refuses).\n */\nexport type StartupSource =\n | { mode: 'git' }\n | { mode: 'directory'; sourcePath: string }\n | { mode: 'file'; sourcePath: string }\n | { mode: 'welcome' };\n\n/**\n * The candidate is the first *positional* by the shared classifier, so `-S src/x.ts` never selects\n * a file.\n */\nexport function resolveStartupSource(\n gitDiffArgs: readonly string[],\n cwd: string = process.cwd()\n): StartupSource {\n const { positionalIndices } = classifyGitDiffArgs([...gitDiffArgs]);\n const firstPositional =\n positionalIndices.length > 0 ? gitDiffArgs[positionalIndices[0]] : undefined;\n const candidate = firstPositional ? resolve(cwd, firstPositional) : null;\n\n // Tracked files go through git diff, others are scanned.\n if (candidate && firstPositional && isExisting(candidate, 'file')) {\n if (isInGitRepo(cwd)) {\n return isGitTracked(firstPositional, cwd)\n ? { mode: 'git' }\n : { mode: 'file', sourcePath: candidate };\n }\n return { mode: 'file', sourcePath: candidate };\n }\n\n if (isInGitRepo(cwd)) {\n return { mode: 'git' };\n }\n\n if (candidate && isExisting(candidate, 'directory')) {\n return { mode: 'directory', sourcePath: candidate };\n }\n\n return { mode: 'welcome' };\n}\n\nfunction isExisting(candidate: string, kind: 'file' | 'directory'): boolean {\n try {\n if (!existsSync(candidate)) return false;\n const stats = statSync(candidate);\n return kind === 'file' ? stats.isFile() : stats.isDirectory();\n } catch {\n return false;\n }\n}\n\n/** The mode alone; see {@link resolveStartupSource} for the source path. */\nexport function determineMode(gitDiffArgs: string[]): 'git' | 'directory' | 'file' | 'welcome' {\n return resolveStartupSource(gitDiffArgs).mode;\n}\n","// Startup decisions that must come out the same in desktop and serve (audit R15); each host\n// keeps its own transport and dialogs.\n//\n// The command lines differ on purpose. Both take `--resume-from <file>` (or `=<file>`), stop\n// reading their own flags at `--`, and pass everything else to `git diff`. Beyond that:\n//\n// | Flag or input | Desktop (`self-review`) | Serve\n// (`self-review-serve`) |\n// | ------------------------------------- | ------------------------------------ |\n// ---------------------------------- |\n// | `--output <file>`, `-o`, `--output=` | no (save dialog changes the path) | yes (fixed for\n// the process) |\n// | `--help`/`-h`, `--version`/`-v` | yes | yes\n// |\n// | forge PR/MR URL as first positional | yes (remote GUI mode) | no (passed to\n// git) |\n// | `fetch-comments <url> [--all-threads]`| yes (headless subcommand, args[0]) | no\n// |\n// | leading Chromium switches | dropped (the launcher's, not git's) | n/a\n// |\n// | nothing to review (`welcome`) | directory picker | startup error\n// |\n\nimport { resolve } from 'path';\nimport type { AppConfig, DiffLoadPayload, ReviewSourceIdentity } from './types';\nimport type { ConfigValueOrigin, LoadedConfig } from './config';\nimport type { PublishReviewOptions, ReviewOutputTarget } from './review-publisher';\nimport type { AttachmentOrigins } from './attachment-origins';\nimport {\n findWriteCapableGitDiffOptions,\n formatGitDiffArgs,\n normalizeGitDiffArgs,\n tokenizeGitDiffArgs,\n} from './git-diff-args';\nimport { applyStagedUntrackedDefault } from './staged-untracked';\nimport { loadGitDiffWithUntracked } from './git-diff-loader';\nimport { createIgnoreFilter } from './ignore-filter';\nimport { scanDirectory, scanFile } from './directory-scanner';\nimport { resolveLocalSourceIdentity } from './source-identity';\nimport type { StartupSource } from './startup-mode';\nimport { parseReviewXml } from './xml-parser';\nimport type { ParsedReview } from './xml-parser';\nimport { recordResumedAttachments } from './review-handlers';\nimport type { ReviewSession } from './review-handlers';\n\n/**\n * A CLI path or the reviewer's user-level `output-file` is explicit and may point anywhere.\n * Project `output-file` or the default is inherited and contained under `cwd`, since a\n * repository could otherwise redirect the save (audit A5).\n */\nexport function resolveOutputTarget(\n explicitPath: string | null,\n loaded: LoadedConfig,\n cwd: string\n): ReviewOutputTarget {\n if (explicitPath !== null) {\n return { path: resolve(cwd, explicitPath), origin: 'explicit' };\n }\n const path = resolve(cwd, loaded.config.outputFile);\n if (loaded.provenance.outputFile === 'user') {\n return { path, origin: 'explicit' };\n }\n return { path, origin: 'inherited', baseDir: cwd };\n}\n\nexport function publishOptionsFor(\n target: ReviewOutputTarget,\n attachmentOrigins?: AttachmentOrigins\n): PublishReviewOptions {\n return target.origin === 'explicit'\n ? { outputOrigin: 'explicit', attachmentOrigins }\n : { outputOrigin: 'inherited', baseDir: target.baseDir, attachmentOrigins };\n}\n\n/**\n * Project `default-diff-args` would make git write a file or run a program; thrown before any git\n * command.\n */\nexport class ConfiguredDiffArgsError extends Error {\n readonly options: readonly string[];\n readonly configPath: string;\n\n constructor(options: readonly string[], configPath: string) {\n super(\n `Refusing default-diff-args from ${configPath}: ${options.join(' ')} ` +\n 'would make git write a file or run an external program. A committed project ' +\n 'configuration may not supply such options; pass them on the command line instead.'\n );\n this.name = 'ConfiguredDiffArgsError';\n this.options = [...options];\n this.configPath = configPath;\n }\n}\n\nexport interface ResolvedDiffArgs {\n gitDiffArgs: string[];\n origin: 'cli' | ConfigValueOrigin;\n config: AppConfig;\n}\n\n/**\n * The CLI's arguments, else `default-diff-args` split with shell quoting. Project-supplied\n * ones are refused with {@link ConfiguredDiffArgsError} if write-capable; the\n * reviewer's own are not.\n */\nexport function resolveStartupDiffArgs(\n cliGitDiffArgs: readonly string[],\n loaded: LoadedConfig,\n cwd: string\n): ResolvedDiffArgs {\n let gitDiffArgs = [...cliGitDiffArgs];\n let origin: ResolvedDiffArgs['origin'] = 'cli';\n if (gitDiffArgs.length === 0 && loaded.config.defaultDiffArgs) {\n gitDiffArgs = tokenizeGitDiffArgs(loaded.config.defaultDiffArgs);\n origin = loaded.provenance.defaultDiffArgs;\n if (origin === 'project') {\n const offending = findWriteCapableGitDiffOptions(gitDiffArgs);\n if (offending.length > 0) {\n const source = loaded.sources.find(s => s.origin === 'project');\n throw new ConfiguredDiffArgsError(offending, source?.path ?? '.self-review.yaml');\n }\n }\n }\n gitDiffArgs = normalizeGitDiffArgs(gitDiffArgs, cwd);\n return {\n gitDiffArgs,\n origin,\n config: applyStagedUntrackedDefault(loaded.config, gitDiffArgs),\n };\n}\n\nexport interface LoadedLocalReview {\n payload: DiffLoadPayload;\n identity: ReviewSourceIdentity | null;\n}\n\n/**\n * Diagnostics ride on the payload and go to `log`, so a failed load never reads as empty. A welcome\n * source yields no identity.\n */\nexport async function loadLocalReview(\n source: StartupSource,\n gitDiffArgs: readonly string[],\n config: AppConfig,\n cwd: string,\n log: (message: string) => void\n): Promise<LoadedLocalReview> {\n if (source.mode === 'git') {\n const { files, repository, diagnostics, identity } = await loadGitDiffWithUntracked(\n [...gitDiffArgs],\n cwd\n );\n for (const diagnostic of diagnostics) log(`Diff diagnostic: ${diagnostic}`);\n const shouldKeep = createIgnoreFilter(config.ignore);\n return {\n payload: {\n files: files.filter(f => shouldKeep(f.newPath || f.oldPath)),\n source: {\n type: 'git',\n // Quoted so the argv is recoverable exactly from the document's git-diff-args.\n gitDiffArgs: formatGitDiffArgs([...gitDiffArgs]),\n repository,\n },\n ...(diagnostics.length > 0 ? { diagnostics } : {}),\n },\n identity,\n };\n }\n\n if (source.mode === 'file' || source.mode === 'directory') {\n const scan =\n source.mode === 'file'\n ? await scanFile(source.sourcePath)\n : await scanDirectory(source.sourcePath, config.ignore);\n for (const diagnostic of scan.diagnostics) log(`Diff diagnostic: ${diagnostic}`);\n return {\n payload: {\n files: scan.files,\n source: { type: source.mode, sourcePath: source.sourcePath },\n ...(scan.diagnostics.length > 0 ? { diagnostics: scan.diagnostics } : {}),\n },\n identity: resolveLocalSourceIdentity({ type: source.mode, sourcePath: source.sourcePath }),\n };\n }\n\n return { payload: { files: [], source: { type: 'welcome' } }, identity: null };\n}\n\n/**\n * Throws `ReviewXmlError` for an unreadable document. Returns it for what the host still needs (the\n * remote head, for drift).\n */\nexport function loadResumeDocument(session: ReviewSession, resumePath: string): ParsedReview {\n const parsed = parseReviewXml(resumePath);\n session.resumeComments = parsed.comments;\n session.resumeViewedFiles = parsed.viewedFiles;\n session.resumeImportDiagnostics = [\n ...parsed.importDiagnostics,\n ...recordResumedAttachments(session, parsed.comments, resumePath),\n ];\n return parsed;\n}\n","// packages/core/src/staged-untracked.ts\n// Initial-config adjustment for staged-mode reviews.\n\nimport type { AppConfig } from './types';\n\n/**\n * In staged-mode reviews (--staged / --cached), untracked files are not\n * part of the index and should be hidden by default. If the user has\n * explicitly opted in via `show-untracked: true` in their YAML config,\n * respect that choice.\n *\n * Untracked files are still preloaded by the backend so that the toolbar\n * toggle can reveal them instantly without re-running git.\n */\nexport function applyStagedUntrackedDefault(config: AppConfig, gitDiffArgs: string[]): AppConfig {\n const stagedMode = gitDiffArgs.includes('--staged') || gitDiffArgs.includes('--cached');\n if (!stagedMode) return config;\n\n const userExplicitOptIn = config.showUntrackedExplicit && config.showUntracked;\n if (userExplicitOptIn) return config;\n\n return { ...config, showUntracked: false };\n}\n","import type { DiffFile, ReviewSourceIdentity } from './types';\nimport {\n runGitDiffAsync,\n getRepoRootAsync,\n getUntrackedFilesAsync,\n isOutputLimitError,\n} from './git';\nimport { parseDiffWithDiagnostics } from './diff-parser';\nimport { findUnsupportedGitDiffOptions } from './git-diff-args';\nimport { loadSyntheticFiles } from './synthetic-diff';\nimport { formatBytes, resolveSourceBudgets, type SourceBudgets } from './input-budgets';\nimport { resolveGitSourceIdentity } from './source-identity';\n\nexport interface LoadGitDiffOptions {\n /**\n * Include untracked working-tree files as synthetic additions. Defaults\n * to true (local git mode). Remote mode passes false: a base...head diff\n * of a PR/MR must never pick up unrelated local untracked files.\n */\n includeUntracked?: boolean;\n budgets?: Partial<SourceBudgets>;\n}\n\nexport interface LoadGitDiffResult {\n files: DiffFile[];\n repository: string;\n /** What the diff compared; previews and line counts read this snapshot, not the working tree. */\n identity: ReviewSourceIdentity;\n /** What could not be shown faithfully; front ends show these instead of \"no changes\". */\n diagnostics: string[];\n}\n\n/** The path a diff entry is keyed by throughout the review. */\nfunction entryPath(file: DiffFile): string {\n return file.newPath || file.oldPath;\n}\n\n/**\n * Tracked wins on a path collision (after `git rm --cached f`, `f` is both a\n * deletion and untracked); two entries would share React keys and comment state.\n */\nexport function dedupeUntrackedByPath(tracked: DiffFile[], untracked: DiffFile[]): DiffFile[] {\n const seen = new Set(tracked.map(entryPath));\n return untracked.filter(file => !seen.has(entryPath(file)));\n}\n\nexport async function loadGitDiffWithUntracked(\n gitDiffArgs: string[],\n cwd?: string,\n options: LoadGitDiffOptions = {}\n): Promise<LoadGitDiffResult> {\n const { includeUntracked = true } = options;\n const budgets = resolveSourceBudgets(options.budgets);\n const repository = await getRepoRootAsync(cwd);\n // Before the diff runs, so the SHAs hold even if a ref moves meanwhile.\n const identity = await resolveGitSourceIdentity({\n repository,\n gitDiffArgv: gitDiffArgs,\n invocationCwd: cwd ?? process.cwd(),\n });\n\n // Such output would parse as an empty review; name the flag and skip git.\n const unsupported = findUnsupportedGitDiffOptions(gitDiffArgs);\n if (unsupported.length > 0) {\n return {\n files: [],\n repository,\n identity,\n diagnostics: unsupported.map(\n flag =>\n `Unsupported git diff option ${flag}: self-review reads patch output only; ` +\n 'remove it to review the changes.'\n ),\n };\n }\n\n let rawDiff: string;\n try {\n rawDiff = await runGitDiffAsync(gitDiffArgs, cwd, budgets.maxGitDiffOutputBytes);\n } catch (error) {\n if (!isOutputLimitError(error)) throw error;\n // A truncated diff must never be parsed as the review.\n return {\n files: [],\n repository,\n identity,\n diagnostics: [\n `git diff produced more than ${formatBytes(budgets.maxGitDiffOutputBytes)} of output, ` +\n 'the most self-review reads from one diff, so nothing was loaded. Narrow the ' +\n 'diff with a pathspec (for example `-- src/`) or a smaller revision range.',\n ],\n };\n }\n const { files, diagnostics } = parseDiffWithDiagnostics(rawDiff);\n\n if (!includeUntracked) {\n return { files, repository, identity, diagnostics };\n }\n\n // Enumerate at the repository root. `git diff` reports root-relative paths\n // for the whole repository, while `git ls-files` reports cwd-relative paths\n // for the cwd subtree only. Read those cwd-relative names against the root\n // and a nested file resolves to its same-named root neighbour, or to\n // nothing at all.\n const untrackedPaths = await getUntrackedFilesAsync(repository);\n if (untrackedPaths.length > budgets.maxEntries) {\n diagnostics.push(\n `${untrackedPaths.length.toLocaleString('en-US')} untracked files exceed the ` +\n `${budgets.maxEntries.toLocaleString('en-US')}-file limit, so none of them were ` +\n 'loaded; only tracked changes are shown. Ignore build output and dependency ' +\n 'folders in .gitignore, or stage the files you mean to review.'\n );\n return { files, repository, identity, diagnostics };\n }\n\n let allFiles = files;\n if (untrackedPaths.length > 0) {\n const untracked = loadSyntheticFiles(untrackedPaths, repository, {\n followSymlinks: false,\n budgets: options.budgets,\n });\n diagnostics.push(...untracked.diagnostics);\n const untrackedFiles = dedupeUntrackedByPath(files, untracked.files);\n for (const file of untrackedFiles) {\n file.isUntracked = true;\n }\n allFiles = [...files, ...untrackedFiles];\n }\n\n return { files: allFiles, repository, identity, diagnostics };\n}\n","// Shared by the desktop and serve command lines (audit R15). `--` ends application\n// options; a git option's separate value stays git's (`-S --output` searches for\n// \"--output\"); an empty value is refused because `--output=` resolves to a directory.\n\nimport { consumesNextArgument } from './git-diff-args';\n\nexport interface ApplicationOptionsSpec<V extends string, B extends string> {\n /** Spelling to field. Long flags take `--flag value` or `--flag=value`; short ones `-o value`. */\n valueFlags: Record<string, V>;\n booleanFlags?: Record<string, B>;\n}\n\nexport interface ExtractedApplicationOptions<V extends string, B extends string> {\n values: Record<V, string | null>;\n flags: Record<B, boolean>;\n /** The `git diff` arguments in order, `--` and all that follows included. */\n rest: string[];\n}\n\n/** A value flag given without a value, or with an empty one. */\nexport class ApplicationOptionError extends Error {\n readonly flag: string;\n\n constructor(flag: string) {\n super(`${flag} requires a file path argument`);\n this.name = 'ApplicationOptionError';\n this.flag = flag;\n }\n}\n\n/**\n * Takes the application's own flags out of `argv`; throws {@link ApplicationOptionError} for a\n * missing or empty value.\n */\nexport function extractApplicationOptions<V extends string, B extends string = never>(\n argv: readonly string[],\n spec: ApplicationOptionsSpec<V, B>\n): ExtractedApplicationOptions<V, B> {\n const values = Object.fromEntries(\n Object.values(spec.valueFlags).map(field => [field, null])\n ) as Record<V, string | null>;\n const flags = Object.fromEntries(\n Object.values(spec.booleanFlags ?? {}).map(field => [field, false])\n ) as Record<B, boolean>;\n const rest: string[] = [];\n\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === '--') {\n rest.push(...argv.slice(i));\n break;\n }\n\n const booleanField = spec.booleanFlags?.[arg];\n if (booleanField !== undefined) {\n flags[booleanField] = true;\n continue;\n }\n\n const valueField = spec.valueFlags[arg];\n if (valueField !== undefined) {\n if (i + 1 >= argv.length) throw new ApplicationOptionError(arg);\n values[valueField] = requireValue(arg, argv[i + 1]);\n i++;\n continue;\n }\n\n const equals = arg.indexOf('=');\n if (arg.startsWith('--') && equals > 0) {\n const equalsField = spec.valueFlags[arg.slice(0, equals)];\n if (equalsField !== undefined) {\n values[equalsField] = requireValue(arg.slice(0, equals), arg.slice(equals + 1));\n continue;\n }\n }\n\n rest.push(arg);\n // A git option's separate value is that option's, whatever it is spelled like.\n if (consumesNextArgument(arg) && i + 1 < argv.length) {\n rest.push(argv[++i]);\n }\n }\n\n return { values, flags, rest };\n}\n\nfunction requireValue(flag: string, value: string): string {\n if (value === '') throw new ApplicationOptionError(flag);\n return value;\n}\n","// packages/core/src/guide-loader.ts\n// Discovery + tolerant loading of the walkthrough guide sidecar.\n//\n// The guide is orientation garnish on a deterministic tool (see\n// docs/intent/llm-review-guide.md): a missing file is a silent no-op, and\n// an unreadable or invalid one produces exactly one stderr warning and no\n// guide. Nothing in this module may throw out of it — every failure mode\n// resolves to null.\n//\n// Note on startup cost: loadGuide IS awaited before window creation\n// (main.ts Phase 5b), deliberately — `guide:load` piggybacks on the\n// DIFF_REQUEST handler, so the payload must be cached via setGuideData\n// before the renderer's first request arrives. When a guide exists, the\n// xmllint-wasm init and validation delay window paint by a few hundred ms;\n// when none exists the cost is a single failed open.\n//\n// Discovery is one-shot: the guide is resolved from the startup output\n// path. Changing the output path at runtime does not re-discover.\n\nimport { extname, resolve } from 'path';\nimport { readFileWithinBudget } from './bounded-read';\nimport { parseGuideXml, reconcileGuide } from './guide-parser';\nimport { formatBytes, MAX_GUIDE_BYTES } from './input-budgets';\nimport { AppConfig, GuideLoadPayload } from './types';\n\n/**\n * Derive the guide sidecar path from the resolved output path: strip the\n * last extension and append `.guide.xml` (`review.xml` →\n * `review.guide.xml`). An output filename with no extension gets\n * `.guide.xml` appended verbatim.\n */\nexport function deriveGuidePath(outputPath: string): string {\n const ext = extname(outputPath);\n const base = ext ? outputPath.slice(0, -ext.length) : outputPath;\n return `${base}.guide.xml`;\n}\n\n/**\n * Resolve where to look for the guide: the `guide-file` config override\n * (resolved against cwd, like `output-file`) when set, otherwise the path\n * derived from the resolved output path.\n */\nexport function resolveGuidePath(outputPath: string, config: Pick<AppConfig, 'guideFile'>): string {\n if (config.guideFile) {\n return resolve(process.cwd(), config.guideFile);\n }\n return deriveGuidePath(outputPath);\n}\n\n/**\n * Discover, read, parse, validate, and reconcile the guide sidecar.\n *\n * Returns the display-ready payload, or null when there is no usable\n * guide. Missing file: silent. Unreadable or invalid file: exactly one\n * `console.error()` line (guide path + reason class). Never throws.\n */\nexport async function loadGuide(\n outputPath: string,\n config: Pick<AppConfig, 'guideFile'>,\n diffFilePaths: string[]\n): Promise<GuideLoadPayload | null> {\n let guidePath: string;\n try {\n guidePath = resolveGuidePath(outputPath, config);\n } catch {\n return null;\n }\n\n try {\n // Refused on fstat size / non-regular file before any read, so a FIFO cannot block.\n let content: string;\n try {\n const read = await readFileWithinBudget(guidePath, MAX_GUIDE_BYTES);\n if (read.kind === 'too-large') {\n console.error(\n `[guide] Ignoring guide at ${guidePath}: too large (${formatBytes(read.size)}, ` +\n `over the ${formatBytes(MAX_GUIDE_BYTES)} guide budget)`\n );\n return null;\n }\n if (read.kind === 'not-regular') {\n console.error(`[guide] Ignoring guide at ${guidePath}: unreadable (not a regular file)`);\n return null;\n }\n content = read.content.toString('utf-8');\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n // No sidecar next to the output path — the normal case.\n return null;\n }\n console.error(\n `[guide] Ignoring guide at ${guidePath}: unreadable (${code ?? 'unknown error'})`\n );\n return null;\n }\n\n const result = await parseGuideXml(content);\n // Explicit comparison: with strictNullChecks off (see tsconfig),\n // truthiness alone does not narrow the discriminated union.\n if (result.ok === false) {\n console.error(`[guide] Ignoring guide at ${guidePath}: invalid (${result.reason})`);\n return null;\n }\n\n const payload: GuideLoadPayload = {\n groups: reconcileGuide(result.guide, diffFilePaths),\n };\n if (result.guide.overview !== undefined) {\n payload.overview = result.guide.overview;\n }\n return payload;\n } catch (error) {\n // Belt and braces: no failure mode of the guide loader may escape.\n const message = error instanceof Error ? error.message : String(error);\n console.error(`[guide] Ignoring guide at ${guidePath}: invalid (${message})`);\n return null;\n }\n}\n","// packages/core/src/remote-mode.ts\n// Remote PR/MR session bootstrap, shared by every front end.\n//\n// Binding rule: after materialization, remote mode *is* git mode. This\n// module turns a forge URL into the inputs the existing git-mode pipeline\n// already understands — a repo path and a `baseSha...headSha` range — plus\n// the fetched discussion threads and the remote provenance the serializer\n// records. `loadRemoteReview` then loads the diff and maps the threads against it,\n// so the app and `fetch-comments` produce the same comments. Every external effect\n// is injectable so unit tests never spawn git/gh/glab.\n//\n// Lifetime: one session, one `AbortSignal`. Aborting kills the command in flight\n// and rejects with `CommandCancelledError`; whatever the session acquired is\n// released first. A returned session hands its `cleanup` to the caller.\n\nimport {\n CommandCancelledError,\n ForgeCliUnavailableError,\n isCommandCancelled,\n parseForgeUrl,\n} from './forge-provider';\nimport type {\n ForgeCommandRunner,\n ForgeName,\n ForgeProvider,\n ForgeThread,\n ForgeUrl,\n} from './forge-provider';\nimport { createGitHubProvider } from './github-provider';\nimport { createGitLabProvider } from './gitlab-provider';\nimport {\n DEFAULT_GIT_COMMAND_TIMEOUT_MS,\n defaultGitRunner,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n} from './materializer';\nimport type {\n ExistingClone,\n MaterializeMode,\n MaterializeOptions,\n MaterializeResult,\n} from './materializer';\nimport { mapThreadsToReviewComments } from './thread-mapper';\nimport { createIgnoreFilter } from './ignore-filter';\nimport type {\n DiffFile,\n DiffLoadPayload,\n RemoteDriftInfo,\n RemoteSessionInfo,\n ReviewComment,\n ReviewSourceIdentity,\n ReviewState,\n} from './types';\nimport { loadGitDiffWithUntracked } from './git-diff-loader';\nimport { formatGitDiffArgs } from './git-diff-args';\nimport { canonicalSourcePath } from './source-identity';\n\n/**\n * The git-mode inputs plus the forge threads, before any diff is loaded (so nothing to anchor\n * suggestions to yet).\n */\nexport interface MaterializedRemoteSession {\n forgeUrl: ForgeUrl;\n /** Root of the materialized clone; the pipeline's repo path. */\n repoPath: string;\n /** Arguments for the existing git-diff machinery: `[base...head]`. */\n gitDiffArgs: string[];\n mode: MaterializeMode;\n /** Idempotent, never rejects; the receiver of the session must call it. */\n cleanup: () => Promise<void>;\n /** Provenance + thread-sync status for payloads and the saved review. */\n remote: RemoteSessionInfo;\n /** Verbatim; empty when thread sync is unavailable. */\n fetchedThreads: ForgeThread[];\n}\n\n/** A session whose diff is loaded and whose threads are mapped against it. */\nexport interface RemoteSession extends MaterializedRemoteSession {\n /** Review-level threads keep the sentinel `filePath: ''` (REVIEW_LEVEL_FILE_PATH). */\n fetchedComments: ReviewComment[];\n}\n\n/** Injectable seams; defaults are the real core APIs. */\nexport interface RemoteSessionDeps {\n createProvider: (forge: ForgeName, runner: ForgeCommandRunner) => ForgeProvider;\n materialize: (\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner,\n existingClone?: ExistingClone | null,\n options?: MaterializeOptions\n ) => Promise<MaterializeResult>;\n detectExistingClone: (\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner,\n options?: MaterializeOptions\n ) => Promise<ExistingClone | null>;\n resolveRemoteDefaultBranch: (\n url: ForgeUrl,\n runner: ForgeCommandRunner,\n existing?: ExistingClone | null,\n options?: MaterializeOptions\n ) => Promise<string>;\n runner: ForgeCommandRunner;\n /** Untracked files are never included. A stand-in may omit `diagnostics` and `identity`. */\n loadDiff: (\n gitDiffArgs: string[],\n cwd: string\n ) => Promise<{\n files: DiffFile[];\n repository: string;\n diagnostics?: string[];\n identity?: ReviewSourceIdentity;\n }>;\n}\n\nfunction defaultCreateProvider(forge: ForgeName, runner: ForgeCommandRunner): ForgeProvider {\n return forge === 'github' ? createGitHubProvider(runner) : createGitLabProvider(runner);\n}\n\n/** Puts `gh`/`glab` under the session's bounds too, so a startup deadline can reach them. */\nfunction bindSessionRunner(runner: ForgeCommandRunner, signal?: AbortSignal): ForgeCommandRunner {\n return (command, args, options) => {\n if (signal?.aborted) {\n return Promise.reject(new CommandCancelledError('aborted', command, args));\n }\n return runner(command, args, {\n signal,\n timeoutMs: DEFAULT_GIT_COMMAND_TIMEOUT_MS,\n ...options,\n });\n };\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined, stage: string): void {\n if (signal?.aborted) {\n throw new CommandCancelledError('aborted', 'self-review', [stage]);\n }\n}\n\nexport const defaultRemoteSessionDeps: RemoteSessionDeps = {\n createProvider: defaultCreateProvider,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n runner: defaultGitRunner,\n loadDiff: (gitDiffArgs, cwd) =>\n // A base...head diff of a remote PR/MR must never pick up local\n // untracked files (an existing clone may have unrelated ones).\n loadGitDiffWithUntracked(gitDiffArgs, cwd, { includeUntracked: false }),\n};\n\nexport interface RemoteLifetimeOptions {\n /** Without one, the session is bounded only by the per-command timeout. */\n signal?: AbortSignal;\n}\n\nexport interface StartRemoteSessionOptions extends RemoteLifetimeOptions {\n includeResolved?: boolean;\n /**\n * `'optional'` (default, the app): a failed fetch degrades to no threads.\n * `'required'` (`fetch-comments`): always attempted, and a failure is fatal.\n */\n threads?: 'optional' | 'required';\n}\n\n/**\n * Materialize a forge PR/MR URL into a local git context and fetch its\n * discussion threads.\n *\n * Fatal failures (unrecognizable URL, materialization errors, base-branch\n * lookup failures other than a missing CLI) throw — callers surface them\n * like any other startup git error. Forge-CLI unavailability is never\n * fatal for the base branch (git-only fallback); for threads see\n * {@link StartRemoteSessionOptions.threads}.\n */\nexport async function startRemoteSession(\n url: string,\n cwd: string,\n deps: Partial<RemoteSessionDeps> = {},\n options: StartRemoteSessionOptions = {}\n): Promise<MaterializedRemoteSession> {\n const d: RemoteSessionDeps = { ...defaultRemoteSessionDeps, ...deps };\n const threadsRequired = options.threads === 'required';\n const { signal } = options;\n const lifetime: MaterializeOptions = { signal };\n throwIfAborted(signal, 'start');\n\n const forgeUrl = parseForgeUrl(url);\n if (!forgeUrl) {\n throw new Error(\n `Not a recognized pull-request or merge-request URL: ${url}\\n` +\n 'Expected a GitHub PR URL (…/pull/N) or a GitLab MR URL (…/-/merge_requests/N).'\n );\n }\n\n const provider = d.createProvider(forgeUrl.forge, bindSessionRunner(d.runner, signal));\n\n let cliAvailable = true;\n let baseBranch: string;\n let existingClone: ExistingClone | null | undefined;\n try {\n baseBranch = await provider.fetchBaseBranch(forgeUrl);\n } catch (error) {\n if (!(error instanceof ForgeCliUnavailableError)) {\n throw error;\n }\n cliAvailable = false;\n console.error(\n `[remote] Forge CLI unavailable (${error.cli}): ${error.message} — ` +\n 'falling back to the remote default branch via git.'\n );\n existingClone = await d.detectExistingClone(forgeUrl, cwd, d.runner, lifetime);\n baseBranch = await d.resolveRemoteDefaultBranch(forgeUrl, d.runner, existingClone, lifetime);\n }\n console.error(`[remote] Base branch: ${baseBranch}`);\n\n const materialized = await d.materialize(\n forgeUrl,\n baseBranch,\n cwd,\n d.runner,\n existingClone,\n lifetime\n );\n\n // The caller gets the cleanup handle only with a session, so anything ending the call before that\n // releases here.\n let fetchedThreads: ForgeThread[] = [];\n let threadSyncAvailable = false;\n if (cliAvailable || threadsRequired) {\n try {\n fetchedThreads = await provider.fetchThreads(forgeUrl, {\n includeResolved: options.includeResolved ?? false,\n });\n threadSyncAvailable = true;\n } catch (error) {\n // A cancelled fetch ends the session under either policy.\n if (threadsRequired || isCommandCancelled(error)) {\n await materialized.cleanup();\n if (error instanceof ForgeCliUnavailableError) {\n throw new Error(\n `Cannot fetch discussion threads: ${error.message}\\n` +\n `This requires the ${error.cli} CLI to be installed and authenticated.`\n );\n }\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n console.error(\n `[remote] thread sync unavailable — continuing without forge threads: ${message}`\n );\n }\n } else {\n console.error(\n '[remote] thread sync unavailable — forge CLI missing, continuing without forge threads.'\n );\n }\n if (signal?.aborted) {\n await materialized.cleanup();\n throwIfAborted(signal, 'threads');\n }\n\n return {\n forgeUrl,\n repoPath: materialized.repoPath,\n gitDiffArgs: [`${materialized.baseSha}...${materialized.headSha}`],\n mode: materialized.mode,\n cleanup: materialized.cleanup,\n remote: {\n remoteUrl: url,\n remoteBaseSha: materialized.baseSha,\n remoteHeadSha: materialized.headSha,\n remoteForge: forgeUrl.forge,\n threadSyncAvailable,\n // A temporary clone is deleted on exit, so nothing may be written\n // into it; the front end needs the fact, not the path.\n temporaryClone: materialized.mode === 'temp-clone',\n },\n fetchedThreads,\n };\n}\n\nexport interface RemoteReviewLoad {\n /** After the ignore configuration. */\n files: DiffFile[];\n repository: string;\n diagnostics: string[];\n /** `session.fetchedThreads` mapped against `files` and the materialized head. */\n comments: ReviewComment[];\n identity?: ReviewSourceIdentity;\n}\n\n/**\n * Load the diff, apply the ignore configuration and map the threads: the one place\n * this happens, so the app and `fetch-comments` cannot drift. Mapping against the\n * filtered files and the materialized head keeps a suggestion on an ignored path\n * or another head plain text (R05). Does not release the session on failure. An\n * abort during the load discards the result and throws.\n */\nexport async function loadRemoteReview(\n session: MaterializedRemoteSession,\n ignorePatterns: string[],\n loadDiff: RemoteSessionDeps['loadDiff'] = defaultRemoteSessionDeps.loadDiff,\n options: RemoteLifetimeOptions = {}\n): Promise<RemoteReviewLoad> {\n throwIfAborted(options.signal, 'load');\n const { files, repository, diagnostics, identity } = await loadDiff(\n session.gitDiffArgs,\n session.repoPath\n );\n throwIfAborted(options.signal, 'load');\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredFiles = files.filter(f => shouldKeep(f.newPath || f.oldPath));\n return {\n files: filteredFiles,\n repository,\n diagnostics: diagnostics ?? [],\n comments: mapThreadsToReviewComments(\n session.fetchedThreads,\n filteredFiles,\n session.remote.remoteHeadSha\n ),\n ...(identity ? { identity } : {}),\n };\n}\n\n/** A remote session plus the ready-to-send git-mode diff payload. */\nexport interface RemoteBootstrapResult {\n session: RemoteSession;\n payload: DiffLoadPayload;\n identity: ReviewSourceIdentity;\n}\n\n/**\n * The loader's identity relabelled as remote, with the user's launch directory rather than the\n * clone's; a stand-in loader still yields the head, with the merge base unknown.\n */\nfunction remoteSourceIdentity(\n started: MaterializedRemoteSession,\n loaded: RemoteReviewLoad,\n cwd: string\n): ReviewSourceIdentity {\n const resolved = loaded.identity ?? {\n sourceRoot: canonicalSourcePath(loaded.repository),\n gitDiffArgv: [...started.gitDiffArgs],\n pathPrefix: '',\n oldSide: { kind: 'unknown' as const, reason: 'the merge base was not resolved' },\n newSide: { kind: 'commit' as const, sha: started.remote.remoteHeadSha },\n };\n return { ...resolved, mode: 'remote', invocationCwd: cwd };\n}\n\n/**\n * Full remote bootstrap for the app: materialize, {@link loadRemoteReview}, and shape\n * the git-mode `DiffLoadPayload`. Thread sync degrades rather than failing.\n */\nexport async function bootstrapRemoteDiff(\n url: string,\n cwd: string,\n ignorePatterns: string[],\n deps: Partial<RemoteSessionDeps> = {},\n options: RemoteLifetimeOptions = {}\n): Promise<RemoteBootstrapResult> {\n const d: RemoteSessionDeps = { ...defaultRemoteSessionDeps, ...deps };\n const started = await startRemoteSession(url, cwd, d, { signal: options.signal });\n\n // The caller gets the cleanup handle only with the result, so any failure before that releases\n // here.\n try {\n const loaded = await loadRemoteReview(started, ignorePatterns, d.loadDiff, options);\n for (const diagnostic of loaded.diagnostics) {\n console.error(`[remote] Diff diagnostic: ${diagnostic}`);\n }\n\n const session: RemoteSession = { ...started, fetchedComments: loaded.comments };\n return {\n session,\n identity: remoteSourceIdentity(started, loaded, cwd),\n payload: {\n files: loaded.files,\n source: {\n type: 'git',\n // Same renderer the git-mode path uses, so expand-context can\n // tokenize this string back into the exact argv.\n gitDiffArgs: formatGitDiffArgs(session.gitDiffArgs),\n repository: loaded.repository,\n },\n remote: session.remote,\n // So the renderer never mistakes a failed load for \"no changes\".\n ...(loaded.diagnostics.length > 0 ? { diagnostics: loaded.diagnostics } : {}),\n },\n };\n } catch (error) {\n await started.cleanup();\n throw error;\n }\n}\n\n/**\n * Merge fetched forge threads into a resumed document's comments. The\n * resumed document wins: a fetched thread whose root `remoteId` already\n * appears in the resumed comments is skipped (the resumed copy may carry\n * the user's added replies). Order: resumed comments first, then the\n * non-duplicate fetched threads in fetch order. Inputs are not mutated.\n */\nexport function mergeRemoteThreads(\n resumed: ReviewComment[],\n fetched: ReviewComment[]\n): ReviewComment[] {\n const resumedRemoteIds = new Set(\n resumed.map(c => c.remoteId).filter((id): id is string => id !== undefined)\n );\n return [\n ...resumed,\n ...fetched.filter(c => c.remoteId === undefined || !resumedRemoteIds.has(c.remoteId)),\n ];\n}\n\n/**\n * Return a copy of the state carrying this session's remote provenance, so\n * \"Finish Review\" writes the `remote-*` root attributes. Always records the\n * live session values: the saved document describes the diff that was\n * actually reviewed.\n */\nexport function applyRemoteProvenance(state: ReviewState, remote: RemoteSessionInfo): ReviewState {\n return {\n ...state,\n // The three source shapes are mutually exclusive in the document: the\n // remote-* attributes ARE the source, so the in-session git source\n // (the materialized clone) must not leak into the saved review. The\n // welcome source emits no source attributes, mirroring fetch-comments.\n source: { type: 'welcome' },\n remoteUrl: remote.remoteUrl,\n remoteBaseSha: remote.remoteBaseSha,\n remoteHeadSha: remote.remoteHeadSha,\n remoteForge: remote.remoteForge,\n };\n}\n\n/**\n * Compare a resumed document's recorded `remote-head-sha` with the live\n * head from materialization. Returns `null` when the document recorded no\n * head SHA (nothing to compare).\n */\nexport function computeRemoteDrift(\n recordedHeadSha: string | undefined,\n liveHeadSha: string\n): RemoteDriftInfo | null {\n if (recordedHeadSha === undefined) {\n return null;\n }\n return {\n recordedHeadSha,\n liveHeadSha,\n drifted: recordedHeadSha !== liveHeadSha,\n };\n}\n","// packages/core/src/fetch-comments.ts\n// Headless orchestrator for `self-review fetch-comments <URL>`: materialize\n// the PR/MR, fetch and map its discussion threads, and write a v3 review.xml\n// with remote provenance — no window, nothing on stdout, all logging on\n// stderr. Shares its load/filter/map steps with the app (remote-mode.ts); only the\n// thread-fetch policy differs (the app degrades, this fails).\n//\n// No overall deadline: bounded by the per-command timeout and the caller's `signal`.\n// Either way the in-flight command is killed, the clone removed and nothing written.\n\nimport { REVIEW_LEVEL_FILE_PATH } from './thread-mapper';\nimport { publishReview } from './review-publisher';\nimport type { PublishReviewOptions, PublishReviewResult } from './review-publisher';\nimport { loadConfigWithProvenance } from './config';\nimport type { LoadedConfig } from './config';\nimport { publishOptionsFor, resolveOutputTarget } from './startup';\nimport { defaultRemoteSessionDeps, loadRemoteReview, startRemoteSession } from './remote-mode';\nimport type { RemoteLifetimeOptions, RemoteSessionDeps } from './remote-mode';\nimport type { DiffFile, FileReviewState, RemoteForge, ReviewComment, ReviewState } from './types';\n\n/** Injectable seams: the app's remote-session seams plus this subcommand's output. */\nexport interface FetchCommentsDeps extends RemoteSessionDeps {\n publish: (\n state: ReviewState,\n outputPath: string,\n options: PublishReviewOptions\n ) => Promise<PublishReviewResult>;\n loadConfig: () => LoadedConfig;\n now: () => Date;\n}\n\nfunction defaultDeps(): FetchCommentsDeps {\n return {\n ...defaultRemoteSessionDeps,\n publish: publishReview,\n loadConfig: loadConfigWithProvenance,\n now: () => new Date(),\n };\n}\n\nexport interface BuildRemoteReviewStateArgs {\n remoteUrl: string;\n forge: RemoteForge;\n baseSha: string;\n headSha: string;\n diffFiles: DiffFile[];\n comments: ReviewComment[];\n timestamp: string;\n}\n\n/**\n * Assemble the ReviewState for a fetched remote review. Pure and\n * deterministic: same inputs, same state.\n *\n * Placement rules:\n * - Every diff file gets a file entry in diff order; fetched threads land on\n * their files, in thread order.\n * - Comments whose path is not in the diff (e.g. outdated anchors on files\n * no longer touched) get a synthetic entry with change-type \"modified\" —\n * the schema requires the attribute and \"modified\" is the least-claiming\n * value for a file we cannot classify.\n * - Review-level threads (sentinel {@link REVIEW_LEVEL_FILE_PATH}) are\n * folded into a single trailing file entry with the sentinel path: the v3\n * schema requires every <comment> inside a <file path>, and the empty\n * path can never collide with a real diff path, so consumers detect these\n * by comparing against the constant. Omitted when there are none.\n * - Every file is viewed=\"false\": fetch-comments reviews nothing, and a\n * viewed mark claims a human looked at the file. A subsequent\n * --resume-from session therefore starts with the full file list pending.\n * - `source` is `{ type: 'welcome' }`: the remote-* root attributes are the\n * review's source shape, and the three shapes (git, directory, remote)\n * are mutually exclusive by contract, so no local source attributes are\n * serialized.\n */\nexport function buildRemoteReviewState(args: BuildRemoteReviewStateArgs): ReviewState {\n const commentsByPath = new Map<string, ReviewComment[]>();\n for (const comment of args.comments) {\n const list = commentsByPath.get(comment.filePath);\n if (list) {\n list.push(comment);\n } else {\n commentsByPath.set(comment.filePath, [comment]);\n }\n }\n\n const files: FileReviewState[] = [];\n const diffPaths = new Set<string>();\n for (const diffFile of args.diffFiles) {\n const path = diffFile.changeType === 'deleted' ? diffFile.oldPath : diffFile.newPath;\n diffPaths.add(path);\n files.push({\n path,\n changeType: diffFile.changeType,\n viewed: false,\n comments: commentsByPath.get(path) ?? [],\n });\n }\n\n // Synthetic entries for anchored comments whose file is not in the diff,\n // in first-appearance order.\n for (const [path, comments] of commentsByPath) {\n if (path === REVIEW_LEVEL_FILE_PATH || diffPaths.has(path)) continue;\n files.push({ path, changeType: 'modified', viewed: false, comments });\n }\n\n const reviewLevel = commentsByPath.get(REVIEW_LEVEL_FILE_PATH);\n if (reviewLevel && reviewLevel.length > 0) {\n files.push({\n path: REVIEW_LEVEL_FILE_PATH,\n changeType: 'modified',\n viewed: false,\n comments: reviewLevel,\n });\n }\n\n return {\n timestamp: args.timestamp,\n source: { type: 'welcome' },\n files,\n remoteUrl: args.remoteUrl,\n remoteBaseSha: args.baseSha,\n remoteHeadSha: args.headSha,\n remoteForge: args.forge,\n };\n}\n\nexport interface FetchCommentsOptions extends RemoteLifetimeOptions {\n /** Include threads the forge marks resolved (GitLab). Default false. */\n includeResolved?: boolean;\n /** Working directory for clone detection and output resolution. */\n cwd?: string;\n /** Test seams; every omitted member falls back to the real default. */\n deps?: Partial<FetchCommentsDeps>;\n}\n\n/**\n * Run the headless fetch-comments flow end to end. Throws on any failure\n * (the caller prints the message to stderr and exits 1); the temporary\n * clone, when one was created, is removed on both success and failure, and\n * the removal has completed by the time the promise settles.\n *\n * Fetching comments is the whole point, so threads run under the `'required'`\n * policy: an unavailable forge CLI is an error, not a degraded review.\n */\nexport async function runFetchComments(\n url: string,\n options: FetchCommentsOptions = {}\n): Promise<void> {\n const deps: FetchCommentsDeps = { ...defaultDeps(), ...options.deps };\n const cwd = options.cwd ?? process.cwd();\n const lifetime: RemoteLifetimeOptions = { signal: options.signal };\n\n // startRemoteSession cleans up after its own failure; once it returns, this try/finally owns the\n // session.\n const session = await startRemoteSession(url, cwd, deps, {\n ...lifetime,\n includeResolved: options.includeResolved ?? false,\n threads: 'required',\n });\n try {\n console.error(`[fetch-comments] Fetched ${session.fetchedThreads.length} threads`);\n\n const loadedConfig = deps.loadConfig();\n const config = loadedConfig.config;\n const loaded = await loadRemoteReview(session, config.ignore ?? [], deps.loadDiff, lifetime);\n for (const diagnostic of loaded.diagnostics) {\n console.error(`[fetch-comments] Diff diagnostic: ${diagnostic}`);\n }\n\n const state = buildRemoteReviewState({\n remoteUrl: url,\n forge: session.forgeUrl.forge,\n baseSha: session.remote.remoteBaseSha,\n headSha: session.remote.remoteHeadSha,\n diffFiles: loaded.files,\n comments: loaded.comments,\n timestamp: deps.now().toISOString(),\n });\n\n // No flag names the output, so config provenance decides its trust (as in the app and serve).\n const target = resolveOutputTarget(null, loadedConfig, cwd);\n await deps.publish(state, target.path, publishOptionsFor(target));\n console.error(`[fetch-comments] ${loaded.comments.length} threads written to ${target.path}`);\n } finally {\n await session.cleanup();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,YAAY,UAAU;AAEtB,SAAS,mBAAmB;;;ACSrB,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAMxC,YACE,MACA,SACA,SACA;AAEA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU,SAAS,WAAW,CAAC;AACpC,QAAI,SAAS,UAAU,OAAW,MAAK,QAAQ,QAAQ;AAAA,EACzD;AACF;AAcO,IAAM,2BAAN,cAAuC,eAAe;AAAA,EAO3D,YAAY,WAAmB,UAAuC;AACpE,UAAM,yBAAyB,yBAAyB,WAAW,QAAQ,CAAC;AAC5E,SAAK,OAAO;AACZ,SAAK,YAAY;AACjB,SAAK,QAAQ,SAAS;AACtB,SAAK,WAAW,SAAS;AACzB,SAAK,YAAY,SAAS;AAC1B,SAAK,UAAU,SAAS;AAAA,EAC1B;AACF;AAEA,SAAS,yBACP,WACA,UACQ;AACR,QAAM,MAAM,UAAU,SAAS,EAAE,EAAE,YAAY,EAAE,SAAS,GAAG,GAAG;AAChE,QAAM,QAAQ;AAAA,IACZ,SAAS,aAAa,SAA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AC,GAAG,KAAK,UAAU,QAAQ;AAC3F,eAAW,cAAc,OAAO,aAAa;AAC3C,cAAQ,MAAM,qCAAqC,UAAU,EAAE;AAAA,IACjE;AAEA,UAAM,QAAQ,uBAAuB;AAAA,MACnC,WAAW;AAAA,MACX,OAAO,QAAQ,SAAS;AAAA,MACxB,SAAS,QAAQ,OAAO;AAAA,MACxB,SAAS,QAAQ,OAAO;AAAA,MACxB,WAAW,OAAO;AAAA,MAClB,UAAU,OAAO;AAAA,MACjB,WAAW,KAAK,IAAI,EAAE,YAAY;AAAA,IACpC,CAAC;AAGD,UAAM,SAAS,oBAAoB,MAAM,cAAc,GAAG;AAC1D,UAAM,KAAK,QAAQ,OAAO,OAAO,MAAM,kBAAkB,MAAM,CAAC;AAChE,YAAQ,MAAM,oBAAoB,OAAO,SAAS,MAAM,uBAAuB,OAAO,IAAI,EAAE;AAAA,EAC9F,UAAE;AACA,UAAM,QAAQ,QAAQ;AAAA,EACxB;AACF;","names":["text","text","path","dirname","path","path","fs","path","realpathSync","path","resolve","relative","realpathSync","relative","path","fs","XMLParser","validateXML","validateXML","XMLParser","path","basename","dirname","join","messageOf","basename","dirname","join","execFile","path","resolve","execFile","readFileSync","existsSync","join","join","existsSync","path","readFileSync","execFile","promisify","execFileAsync","path","fs","file","text","toTurn","toAnchor","path","resolve","fs","path","path","path","runGitDiffAsync","parseDiff","existsSync","statSync","resolve","resolve","existsSync","statSync","resolve","resolve","path","resolve","resolve","path"]}
|