@self-review/core 1.39.1 → 1.39.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -844,10 +844,14 @@ function parseReviewXmlString(xmlContent) {
844
844
  const gitDiffArgs = review["@_git-diff-args"] || "";
845
845
  const source = parseSource(review);
846
846
  const comments = [];
847
+ const viewedFiles = [];
847
848
  const files = Array.isArray(review.file) ? review.file : review.file ? [review.file] : [];
848
849
  for (const file of files) {
849
850
  const filePath = file["@_path"];
850
851
  if (!filePath) continue;
852
+ if (parseViewed(file["@_viewed"])) {
853
+ viewedFiles.push(String(filePath));
854
+ }
851
855
  const fileComments = Array.isArray(file.comment) ? file.comment : file.comment ? [file.comment] : [];
852
856
  for (const comment of fileComments) {
853
857
  const reviewComment = {
@@ -874,7 +878,7 @@ function parseReviewXmlString(xmlContent) {
874
878
  comments.push(reviewComment);
875
879
  }
876
880
  }
877
- return { comments, gitDiffArgs, source };
881
+ return { comments, viewedFiles, gitDiffArgs, source };
878
882
  } catch (error) {
879
883
  if (error instanceof Error) {
880
884
  console.error(`Error parsing XML: ${error.message}`);
@@ -889,6 +893,9 @@ function parseEnumAttribute(raw, allowed) {
889
893
  const value = String(raw);
890
894
  return allowed.includes(value) ? value : void 0;
891
895
  }
896
+ function parseViewed(raw) {
897
+ return raw === true || String(raw) === "true";
898
+ }
892
899
  function parseSource(review) {
893
900
  const sourcePath = review["@_source-path"];
894
901
  if (sourcePath) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/diff-parser.ts","../src/xml-serializer.ts","../src/xml-parser.ts","../src/git.ts","../src/synthetic-diff.ts","../src/directory-scanner.ts","../src/ignore-filter.ts","../src/config.ts","../src/payload-sizing.ts","../src/fs-utils.ts","../src/file-type-utils.ts"],"sourcesContent":["// @self-review/core — Node.js API for diff parsing, git operations, XML serialization, and configuration\n\n// Types\nexport type {\n ChangeType,\n DiffLineType,\n DiffLine,\n DiffHunk,\n DiffFile,\n DiffSource,\n Suggestion,\n Attachment,\n LineRange,\n ReviewComment,\n CommentSeverity,\n CommentConfidence,\n FileReviewState,\n ReviewState,\n CategoryDef,\n AppConfig,\n DiffLoadPayload,\n ResumeLoadPayload,\n OutputPathInfo,\n ExpandContextRequest,\n ExpandContextResponse,\n FindInPageRequest,\n FindInPageResult,\n VersionUpdateInfo,\n PayloadStats,\n ImageLoadResult,\n} from './types';\n\n// Diff parsing\nexport { parseDiff } from './diff-parser';\n\n// XML I/O\nexport { serializeReview } from './xml-serializer';\nexport { parseReviewXml, parseReviewXmlString } from './xml-parser';\n\n// Git operations\nexport {\n runGitDiff,\n runGitDiffAsync,\n getRepoRoot,\n getRepoRootAsync,\n getUntrackedFilesAsync,\n validateGitAvailable,\n generateUntrackedDiffs,\n} from './git';\n\n// Synthetic diffs (for non-git files/directories)\nexport { generateSyntheticDiffs } from './synthetic-diff';\n\n// Directory/file scanning\nexport { scanDirectory, scanFile } from './directory-scanner';\n\n// Configuration\nexport { loadConfig } from './config';\n\n// Payload sizing\nexport { computePayloadStats, countTotalLines, getGitDiffStats } from './payload-sizing';\n\n// Ignore filter\nexport { createIgnoreFilter } from './ignore-filter';\n\n// File system utilities\nexport { checkWritability } from './fs-utils';\n\n// File type detection utilities\nexport {\n getLanguageFromPath,\n getRenderedTextMode,\n isHtmlFile,\n isMarkdownFile,\n isPreviewableImage,\n isPreviewableRenderedText,\n isPreviewableSvg,\n} from './file-type-utils';\nexport type { RenderedTextMode } from './file-type-utils';\n","// src/main/diff-parser.ts\n// Parse unified diff output into DiffFile[]\n\nimport { DiffFile, DiffHunk, ChangeType } from './types';\n\nexport function parseDiff(rawDiff: string): DiffFile[] {\n if (!rawDiff.trim()) {\n return [];\n }\n\n const lines = rawDiff.split('\\n');\n const files: DiffFile[] = [];\n let currentFile: Partial<DiffFile> | null = null;\n let currentHunk: Partial<DiffHunk> | null = null;\n let oldLineNumber = 0;\n let newLineNumber = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Start of a new file\n if (line.startsWith('diff --git ')) {\n // Flush the pending hunk into the current file before saving\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n currentHunk = null;\n }\n\n // Save previous file if exists and has actual changes\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n // Extract paths from \"diff --git a/<old> b/<new>\" as fallback\n // for binary files that lack --- / +++ lines\n const gitPaths = parseGitDiffHeader(line);\n\n // Initialize new file\n currentFile = {\n oldPath: gitPaths.oldPath,\n newPath: gitPaths.newPath,\n changeType: 'modified' as ChangeType,\n isBinary: false,\n hunks: [],\n };\n currentHunk = null;\n continue;\n }\n\n if (!currentFile) continue;\n\n // Detect file mode changes\n if (line.startsWith('new file mode')) {\n currentFile.changeType = 'added';\n continue;\n }\n\n if (line.startsWith('deleted file mode')) {\n currentFile.changeType = 'deleted';\n continue;\n }\n\n if (line.startsWith('rename from ')) {\n currentFile.changeType = 'renamed';\n continue;\n }\n\n // Parse old file path\n if (line.startsWith('--- ')) {\n const path = line.substring(4);\n currentFile.oldPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Parse new file path\n if (line.startsWith('+++ ')) {\n const path = line.substring(4);\n currentFile.newPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Detect binary files\n if (line.startsWith('Binary files ')) {\n currentFile.isBinary = true;\n continue;\n }\n\n // Parse hunk header\n if (line.startsWith('@@')) {\n // Save previous hunk if exists\n if (currentHunk && currentHunk.header) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n\n // Parse hunk header: @@ -oldStart,oldLines +newStart,newLines @@ context\n const match = line.match(\n /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(.*)$/\n );\n if (match) {\n const oldStart = parseInt(match[1], 10);\n const oldLines = match[2] ? parseInt(match[2], 10) : 1;\n const newStart = parseInt(match[3], 10);\n const newLines = match[4] ? parseInt(match[4], 10) : 1;\n const _context = match[5];\n\n currentHunk = {\n header: line,\n oldStart,\n oldLines,\n newStart,\n newLines,\n lines: [],\n };\n\n oldLineNumber = oldStart;\n newLineNumber = newStart;\n }\n continue;\n }\n\n // Parse diff lines (must have a current hunk)\n if (currentHunk && currentHunk.lines) {\n if (line.startsWith('+')) {\n // Addition\n currentHunk.lines.push({\n type: 'addition',\n oldLineNumber: null,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n newLineNumber++;\n } else if (line.startsWith('-')) {\n // Deletion\n currentHunk.lines.push({\n type: 'deletion',\n oldLineNumber: oldLineNumber,\n newLineNumber: null,\n content: line.substring(1),\n });\n oldLineNumber++;\n } else if (line.startsWith(' ')) {\n // Context line\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n oldLineNumber++;\n newLineNumber++;\n } else if (line.startsWith('\\\\')) {\n // \"\\" - ignore\n continue;\n } else {\n // Some other line (could be empty or malformed), treat as context\n if (currentHunk.lines.length > 0) {\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line,\n });\n oldLineNumber++;\n newLineNumber++;\n }\n }\n }\n }\n\n // Save the last hunk and file\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n return files;\n}\n\nfunction stripPrefix(path: string): string {\n // Remove single-character prefix (a/, b/, c/, i/, w/, etc.)\n // Git uses a/b by default, but mnemonicPrefix uses c/i/w/o\n if (path.length > 2 && path[1] === '/') {\n return path.substring(2);\n }\n return path;\n}\n\nfunction parseGitDiffHeader(line: string): {\n oldPath: string;\n newPath: string;\n} {\n // Format: \"diff --git a/<old> b/<new>\"\n // With diff.mnemonicPrefix, git uses i/ w/ c/ o/ instead of a/ b/.\n // Paths may contain spaces, so we find the \" X/\" separator where X is a\n // single-letter prefix.\n const withoutPrefix = line.substring('diff --git '.length);\n\n // Find \" X/\" — the boundary between old and new paths.\n // Try common prefixes: b/ (default), w/ i/ c/ o/ (mnemonic)\n let bIdx = -1;\n for (const prefix of [' b/', ' w/', ' i/', ' c/', ' o/']) {\n bIdx = withoutPrefix.indexOf(prefix);\n if (bIdx !== -1) break;\n }\n\n if (bIdx === -1) {\n return { oldPath: '', newPath: '' };\n }\n\n const oldPath = stripPrefix(withoutPrefix.substring(0, bIdx));\n const newPath = stripPrefix(withoutPrefix.substring(bIdx + 1));\n return { oldPath, newPath };\n}\n","// src/main/xml-serializer.ts\n// Serialize ReviewState to XML and validate against XSD\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { ReviewState, FileReviewState, ReviewComment } 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 copies listed in AGENTS.md;\n// the sync test in xml-serializer.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:v2\"\n targetNamespace=\"urn:self-review:v2\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review XML Schema v2\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\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\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: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: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: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:schema>`;\n\nfunction extFromMediaType(mediaType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\nfunction writeAttachments(state: ReviewState, outputFilePath: string): ReviewState {\n const assetDir = path.join(path.dirname(outputFilePath), '.self-review-assets');\n let hasAttachments = false;\n\n const updatedFiles = state.files.map(file => ({\n ...file,\n comments: file.comments.map(comment => {\n if (!comment.attachments?.length) return comment;\n\n const updatedAttachments = comment.attachments.map((att, index) => {\n if (!att.data) return att;\n hasAttachments = true;\n\n const ext = extFromMediaType(att.mediaType);\n const fileName = `${comment.id}-${index}.${ext}`;\n const relativePath = `.self-review-assets/${fileName}`;\n\n if (!fs.existsSync(assetDir)) {\n fs.mkdirSync(assetDir, { recursive: true });\n }\n fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));\n\n return { ...att, fileName: relativePath, data: undefined };\n });\n\n return { ...comment, attachments: updatedAttachments };\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-v2.xsd', contents: XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const errors = validationResult.errors || [];\n console.error('XML validation failed:');\n errors.forEach((err: unknown) => console.error(` ${err}`));\n throw new Error('Generated XML does not conform to schema');\n }\n } catch (error) {\n // Re-throw if it's a schema validation failure (our own throw above)\n if (error instanceof Error && error.message === 'Generated XML does not conform to schema') {\n throw error;\n }\n // Infrastructure failure (e.g. WASM load): log warning and return XML anyway\n if (error instanceof Error) {\n console.error(`[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`);\n } else {\n console.error('[main] XML validation infrastructure failed - emitting XML without validation');\n }\n return xml;\n }\n\n return xml;\n}\n\nfunction buildSourceAttributes(state: ReviewState): string {\n const source = state.source;\n if (source.type === 'git') {\n return ` git-diff-args=\"${escapeXml(source.gitDiffArgs)}\" repository=\"${escapeXml(source.repository)}\"`;\n }\n if (source.type === 'directory' || source.type === 'file') {\n return ` source-path=\"${escapeXml(source.sourcePath)}\"`;\n }\n // welcome mode: no source attributes\n return '';\n}\n\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 lines.push(\n `<review xmlns=\"urn:self-review:v2\" timestamp=\"${escapeXml(state.timestamp)}\"${sourceAttrs}>`\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 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 if (comment.attachments?.length) {\n for (const att of comment.attachments) {\n lines.push(` <attachment path=\"${escapeXml(att.fileName)}\" media-type=\"${escapeXml(att.mediaType)}\" />`);\n }\n }\n\n // Closing tag\n lines.push(' </comment>');\n\n return lines;\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\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} from './types';\n\nconst SEVERITY_VALUES: readonly CommentSeverity[] = ['critical', 'major', 'minor', 'info'];\nconst CONFIDENCE_VALUES: readonly CommentConfidence[] = ['high', 'medium', 'low'];\n\nexport interface ParsedReview {\n comments: ReviewComment[];\n gitDiffArgs: string;\n source: DiffSource;\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 });\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\n // Handle files array\n const files = Array.isArray(review.file)\n ? review.file\n : review.file\n ? [review.file]\n : [];\n\n for (const file of files) {\n const filePath = file['@_path'];\n if (!filePath) continue;\n\n // Handle comments array\n const fileComments = Array.isArray(file.comment)\n ? file.comment\n : file.comment\n ? [file.comment]\n : [];\n\n for (const comment of fileComments) {\n const reviewComment: ReviewComment = {\n id: generateId(),\n filePath,\n lineRange: parseLineRange(comment),\n body: comment.body || '',\n category: 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 };\n\n // Parse attachments\n const commentAttachments = Array.isArray(comment.attachment)\n ? comment.attachment\n : comment.attachment\n ? [comment.attachment]\n : [];\n\n if (commentAttachments.length > 0) {\n reviewComment.attachments = commentAttachments.map(\n (att: Record<string, unknown>, i: number) => ({\n id: `${reviewComment.id}-att-${i}`,\n fileName: String(att['@_path'] || ''),\n mediaType: String(att['@_media-type'] || 'image/png'),\n })\n );\n }\n\n comments.push(reviewComment);\n }\n }\n\n return { comments, gitDiffArgs, source };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error parsing XML: ${error.message}`);\n } else {\n console.error('Error parsing XML: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Read an enumerated attribute, dropping values the schema does not define.\n *\n * An unrecognised value becomes undefined rather than being passed through:\n * undefined is the fail-safe reading (below every threshold floor), and it\n * keeps a resumed review serializable, since the serializer validates its\n * output against the XSD before writing.\n */\nfunction parseEnumAttribute<T extends string>(\n raw: unknown,\n allowed: readonly T[]\n): T | undefined {\n if (raw === undefined || raw === null) return undefined;\n const value = String(raw);\n return allowed.includes(value as T) ? (value as T) : undefined;\n}\n\nfunction parseSource(review: Record<string, unknown>): DiffSource {\n const sourcePath = review['@_source-path'];\n if (sourcePath) {\n return { type: 'directory', sourcePath: String(sourcePath) };\n }\n\n const gitDiffArgs = review['@_git-diff-args'];\n const repository = review['@_repository'];\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: String(gitDiffArgs || ''),\n repository: String(repository || ''),\n };\n }\n\n return { type: 'welcome' };\n}\n\nfunction parseLineRange(comment: Record<string, unknown>): LineRange | null {\n const hasOld =\n comment['@_old-line-start'] !== undefined &&\n comment['@_old-line-end'] !== undefined;\n const hasNew =\n comment['@_new-line-start'] !== undefined &&\n comment['@_new-line-end'] !== undefined;\n\n if (hasOld) {\n return {\n side: 'old',\n start: parseInt(String(comment['@_old-line-start']), 10),\n end: parseInt(String(comment['@_old-line-end']), 10),\n };\n }\n\n if (hasNew) {\n return {\n side: 'new',\n start: parseInt(String(comment['@_new-line-start']), 10),\n end: parseInt(String(comment['@_new-line-end']), 10),\n };\n }\n\n return null; // File-level comment\n}\n\nfunction parseSuggestion(comment: Record<string, unknown>): Suggestion | null {\n if (!comment.suggestion) {\n return null;\n }\n\n const suggestion = comment.suggestion as Record<string, unknown>;\n return {\n originalCode: String(suggestion['original-code'] || ''),\n proposedCode: String(suggestion['proposed-code'] || ''),\n };\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// src/main/git.ts\n// Git command execution\n\nimport { execSync, exec } from 'child_process';\nimport { promisify } from 'util';\nimport { generateSyntheticDiffs } from './synthetic-diff';\n\nconst execAsync = promisify(exec);\n\nexport function runGitDiff(args: string[]): string {\n try {\n // Check if git is available\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n // Check if we're in a git repository\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n\n // Run git diff with the provided arguments\n const result = execSync(`git diff ${args.join(' ')}`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large diffs\n });\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function getRepoRoot(): string {\n try {\n const result = execSync('git rev-parse --show-toplevel', {\n encoding: 'utf-8',\n });\n return result.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Lightweight sync validation - checks if git is available and we're in a repo.\n * Called BEFORE Electron initialization for early exit path.\n */\nexport function validateGitAvailable(): void {\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n}\n\n/**\n * Async version of getRepoRoot - called AFTER app.whenReady().\n */\nexport async function getRepoRootAsync(cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync('git rev-parse --show-toplevel', {\n timeout: 10000, // 10 second timeout\n cwd,\n });\n return stdout.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Async version of runGitDiff - called AFTER app.whenReady().\n * Uses timeout to prevent hanging in CI environments.\n */\nexport async function runGitDiffAsync(args: string[], cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`git diff ${args.join(' ')}`, {\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer\n timeout: 30000, // 30 second timeout\n cwd,\n });\n return stdout;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Get list of untracked files (respects .gitignore).\n */\nexport async function getUntrackedFilesAsync(cwd?: string): Promise<string[]> {\n try {\n const { stdout } = await execAsync(\n 'git ls-files --others --exclude-standard',\n {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 10000,\n cwd,\n }\n );\n return stdout\n .trim()\n .split('\\n')\n .filter(line => line.length > 0);\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Warning: Failed to list untracked files: ${error.message}`\n );\n } else {\n console.error('Warning: Failed to list untracked files: unknown error');\n }\n return [];\n }\n}\n\n/**\n * Generate synthetic unified diffs for untracked files so they can be\n * parsed by the existing diff parser.\n *\n * Delegates to the reusable generateSyntheticDiffs module.\n */\nexport function generateUntrackedDiffs(\n paths: string[],\n repoRoot: string\n): string {\n return generateSyntheticDiffs(paths, repoRoot);\n}\n","// src/main/synthetic-diff.ts\n// Generates synthetic unified diffs for files that aren't tracked by git.\n// Reusable by both git untracked file handling and directory-based scanning.\n\nimport { readFileSync } from 'fs';\n\n/**\n * Generate synthetic unified diffs for a list of file paths so they can be\n * parsed by the existing diff parser. Each file is treated as a new addition.\n *\n * @param paths - Relative file paths (e.g. \"src/foo.ts\")\n * @param rootDir - Absolute path to the root directory containing the files\n * @returns A unified diff string covering all provided files\n */\nexport function generateSyntheticDiffs(\n paths: string[],\n rootDir: string\n): string {\n const diffs: string[] = [];\n\n for (const filePath of paths) {\n const fullPath = `${rootDir}/${filePath}`;\n let content: Buffer;\n try {\n content = readFileSync(fullPath);\n } catch {\n // File may have been deleted between listing and reading\n continue;\n }\n\n // Detect binary files by checking for null bytes in the first 8KB\n const sample = content.subarray(0, 8192);\n const isBinary = sample.includes(0);\n\n if (isBinary) {\n diffs.push(\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `Binary files /dev/null and b/${filePath} differ`\n );\n continue;\n }\n\n const text = content.toString('utf-8');\n const lines = text.split('\\n');\n\n // Remove trailing empty string from split if file ends with newline\n if (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n\n const lineCount = lines.length;\n const addedLines = lines.map(line => `+${line}`).join('\\n');\n\n let diff =\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `--- /dev/null\\n` +\n `+++ b/${filePath}\\n` +\n `@@ -0,0 +1,${lineCount} @@\\n` +\n addedLines;\n\n // Indicate missing newline at end of file\n if (text.length > 0 && !text.endsWith('\\n')) {\n diff += '\\n\\\';\n }\n\n diffs.push(diff);\n }\n\n return diffs.join('\\n');\n}\n","// src/main/directory-scanner.ts\n// Recursively scans a directory and produces DiffFile[] treating all files as new additions.\n\nimport { readdir, stat } from 'fs/promises';\nimport { join, relative, basename, dirname } from 'path';\nimport { DiffFile } from './types';\nimport { generateSyntheticDiffs } from './synthetic-diff';\nimport { parseDiff } from './diff-parser';\nimport { createIgnoreFilter } from './ignore-filter';\n\n/**\n * Recursively scan a directory and return DiffFile[] with every file\n * treated as a new addition (changeType: 'added').\n *\n * @param directoryPath - Absolute path to the directory to scan\n * @param ignorePatterns - Optional gitignore-compatible patterns to exclude files\n * @returns Parsed DiffFile array for all files in the directory\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = []\n): Promise<DiffFile[]> {\n // Verify the path is a directory\n try {\n const dirStat = await stat(directoryPath);\n if (!dirStat.isDirectory()) {\n console.error(\n `Error: \"${directoryPath}\" is not a directory`\n );\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error accessing directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error accessing directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n const filePaths: string[] = [];\n\n try {\n const entries = await readdir(directoryPath, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n\n // Build the full path from the entry's parentPath (or path) and name\n const parentDir = entry.parentPath ?? entry.path;\n const fullPath = join(parentDir, entry.name);\n const relativePath = relative(directoryPath, fullPath);\n filePaths.push(relativePath);\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error reading directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error reading directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n // Sort for deterministic output\n filePaths.sort();\n\n // Apply ignore patterns\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredPaths = filePaths.filter(p => shouldKeep(p));\n\n if (filteredPaths.length === 0) {\n return [];\n }\n\n const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);\n return parseDiff(diffText);\n}\n\n/**\n * Scan a single file and return DiffFile[] with the file treated as a new addition.\n *\n * @param filePath - Absolute path to the file to scan\n * @returns Parsed DiffFile array (single element)\n */\nexport async function scanFile(filePath: string): Promise<DiffFile[]> {\n try {\n const fileStat = await stat(filePath);\n if (!fileStat.isFile()) {\n console.error(`Error: \"${filePath}\" is not a file`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing file \"${filePath}\": ${error.message}`);\n } else {\n console.error(`Error accessing file \"${filePath}\": unknown error`);\n }\n return [];\n }\n\n const fileName = basename(filePath);\n const rootDir = dirname(filePath);\n const diffText = generateSyntheticDiffs([fileName], rootDir);\n return parseDiff(diffText);\n}\n","// src/main/ignore-filter.ts\n// Gitignore-compatible file path filtering using the `ignore` package.\n\nimport ignore from 'ignore';\n\n/**\n * Create a filter function from gitignore-compatible patterns.\n *\n * @param patterns - Array of gitignore-compatible glob patterns\n * @returns A predicate that returns `true` if the path should be kept (not ignored)\n */\nexport function createIgnoreFilter(\n patterns: string[]\n): (path: string) => boolean {\n if (patterns.length === 0) return () => true;\n const ig = ignore().add(patterns);\n return (filePath: string) => !ig.ignores(filePath);\n}\n","// src/main/config.ts\n// YAML configuration loading and merging\n\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { parse as parseYaml } from 'yaml';\nimport { AppConfig } from './types';\n\nconst defaults: AppConfig = {\n theme: 'system',\n diffView: 'split',\n fontSize: 14,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: [\n '.git',\n 'node_modules',\n 'vendor',\n '.vendor',\n '__pycache__',\n '.venv',\n 'venv',\n '.env',\n 'dist',\n 'build',\n '.next',\n '.nuxt',\n '.svelte-kit',\n 'target',\n '*.min.js',\n '*.min.css',\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Gemfile.lock',\n 'Cargo.lock',\n 'poetry.lock',\n 'go.sum',\n ],\n categories: [\n {\n name: 'question',\n description: 'Clarification needed — not necessarily a problem',\n color: '#805ad5',\n },\n {\n name: 'bug',\n description: 'Likely defect or incorrect behavior',\n color: '#e53e3e',\n },\n {\n name: 'security',\n description: 'Security vulnerability or concern',\n color: '#dd6b20',\n },\n {\n name: 'style',\n description: 'Code style, naming, or formatting issue',\n color: '#3182ce',\n },\n {\n name: 'task',\n description: 'Action item or follow-up task',\n color: '#38a169',\n },\n {\n name: 'nit',\n description: 'Minor nitpick, low priority',\n color: '#718096',\n },\n ],\n defaultDiffArgs: '',\n showUntracked: true,\n showUntrackedExplicit: false,\n wordWrap: true,\n maxFiles: 500,\n maxTotalLines: 100000,\n};\n\nexport function loadConfig(): AppConfig {\n let config = { ...defaults };\n\n // Load user-level config\n const userConfigPath = join(\n homedir(),\n '.config',\n 'self-review',\n 'config.yaml'\n );\n if (existsSync(userConfigPath)) {\n try {\n const userConfig = loadYamlConfig(userConfigPath);\n config = mergeConfig(config, userConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load user config from ${userConfigPath}: ${error}`\n );\n }\n }\n\n // Load project-level config\n const projectConfigPath = join(process.cwd(), '.self-review.yaml');\n if (existsSync(projectConfigPath)) {\n try {\n const projectConfig = loadYamlConfig(projectConfigPath);\n config = mergeConfig(config, projectConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load project config from ${projectConfigPath}: ${error}`\n );\n }\n }\n\n return config;\n}\n\nfunction loadYamlConfig(path: string): Partial<AppConfig> {\n const content = readFileSync(path, 'utf-8');\n const raw = parseYaml(content);\n\n // An empty file (or one containing only `null`) is a valid \"use defaults\" state.\n if (raw === null || raw === undefined) {\n return {};\n }\n\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error('Invalid YAML format');\n }\n\n // Map kebab-case keys to camelCase\n const config: Partial<AppConfig> = {};\n\n if ('theme' in raw) {\n if (['light', 'dark', 'system'].includes(raw.theme)) {\n config.theme = raw.theme;\n } else {\n console.error(\n `Warning: Invalid theme value \"${raw.theme}\", using default`\n );\n }\n }\n\n if ('diff-view' in raw) {\n if (['split', 'unified'].includes(raw['diff-view'])) {\n config.diffView = raw['diff-view'];\n } else {\n console.error(\n `Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`\n );\n }\n }\n\n if ('font-size' in raw && typeof raw['font-size'] === 'number') {\n config.fontSize = raw['font-size'];\n }\n\n if ('output-format' in raw && typeof raw['output-format'] === 'string') {\n config.outputFormat = raw['output-format'];\n }\n\n if ('ignore' in raw && Array.isArray(raw.ignore)) {\n config.ignore = raw.ignore.filter(\n (item: unknown) => typeof item === 'string'\n );\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n config.categories = raw.categories.filter(\n (cat: unknown): cat is { name: string; description: string; color: string } =>\n cat !== null &&\n typeof cat === 'object' &&\n typeof (cat as Record<string, unknown>).name === 'string' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n }\n\n if (\n 'default-diff-args' in raw &&\n typeof raw['default-diff-args'] === 'string'\n ) {\n config.defaultDiffArgs = raw['default-diff-args'];\n }\n\n if ('show-untracked' in raw && typeof raw['show-untracked'] === 'boolean') {\n config.showUntracked = raw['show-untracked'];\n config.showUntrackedExplicit = true;\n }\n\n if ('word-wrap' in raw && typeof raw['word-wrap'] === 'boolean') {\n config.wordWrap = raw['word-wrap'];\n }\n\n if ('max-files' in raw && typeof raw['max-files'] === 'number') {\n config.maxFiles = raw['max-files'] >= 0 ? raw['max-files'] : defaults.maxFiles;\n }\n\n if ('max-total-lines' in raw && typeof raw['max-total-lines'] === 'number') {\n config.maxTotalLines = raw['max-total-lines'] >= 0 ? raw['max-total-lines'] : defaults.maxTotalLines;\n }\n\n if (\n 'output-file' in raw &&\n typeof raw['output-file'] === 'string' &&\n raw['output-file'].length > 0\n ) {\n config.outputFile = raw['output-file'];\n }\n\n return config;\n}\n\nfunction mergeConfig(base: AppConfig, override: Partial<AppConfig>): AppConfig {\n return {\n ...base,\n ...override,\n // Arrays are replaced, not merged\n ignore: override.ignore !== undefined ? override.ignore : base.ignore,\n categories:\n override.categories !== undefined ? override.categories : base.categories,\n };\n}\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execAsync = promisify(exec);\n\n/**\n * Compute payload statistics and check against configured thresholds.\n * A maxFiles or maxTotalLines value of 0 disables that guard.\n */\nexport function computePayloadStats(\n fileCount: number,\n totalLines: number,\n config: AppConfig\n): PayloadStats {\n const maxFiles = config.maxFiles;\n const maxTotalLines = config.maxTotalLines;\n const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;\n const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;\n return {\n fileCount,\n totalLines,\n exceedsFiles,\n exceedsLines,\n exceedsAny: exceedsFiles || exceedsLines,\n };\n}\n\n/**\n * Count total diff lines across all files and hunks.\n */\nexport function countTotalLines(files: DiffFile[]): number {\n let total = 0;\n for (const file of files) {\n for (const hunk of file.hunks) {\n total += hunk.lines.length;\n }\n }\n return total;\n}\n\n/**\n * Get git diff stats cheaply using --numstat (avoids full diff parsing).\n * Each output line is \"added\\tremoved\\tfilename\".\n * Returns file count and total changed lines (added + removed).\n */\nexport async function getGitDiffStats(\n args: string[],\n repoRoot: string\n): Promise<{ fileCount: number; totalLines: number }> {\n try {\n const { stdout } = await execAsync(`git diff --numstat ${args.join(' ')}`, {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 15000,\n cwd: repoRoot,\n });\n\n let fileCount = 0;\n let totalLines = 0;\n\n for (const line of stdout.trim().split('\\n')) {\n if (!line) continue;\n const parts = line.split('\\t');\n if (parts.length < 3) continue;\n\n fileCount++;\n // Binary files show '-' for added/removed\n const added = parts[0] === '-' ? 0 : parseInt(parts[0], 10);\n const removed = parts[1] === '-' ? 0 : parseInt(parts[1], 10);\n totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);\n }\n\n return { fileCount, totalLines };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);\n } else {\n console.error('[payload-sizing] Failed to get git diff stats: unknown error');\n }\n // Return zeros so the guard does not block on failure\n return { fileCount: 0, totalLines: 0 };\n }\n}\n","// src/main/fs-utils.ts\n// Filesystem utility functions for the main process.\n\nimport { accessSync, constants as fsConstants } from 'fs';\nimport { dirname } from 'path';\n\n/**\n * Check if a file's parent directory is writable.\n * Returns true if the directory exists and the process has write permission,\n * false otherwise (including non-existent directories).\n */\nexport function checkWritability(filePath: string): boolean {\n try {\n const dir = dirname(filePath);\n accessSync(dir, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * File-type detection utilities.\n *\n * NOTE: This file is intentionally duplicated in packages/react/src/utils/file-type-utils.ts.\n * @self-review/core has Node-only dependencies, so @self-review/react cannot safely import\n * from this package. Both copies must be kept in sync.\n */\n\nconst RASTER_IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.ico', '.bmp']);\nconst MARKDOWN_EXTENSIONS = new Set(['.md', '.markdown']);\nconst HTML_EXTENSIONS = new Set(['.html', '.htm']);\n\nexport type RenderedTextMode = 'markdown' | 'html';\n\nfunction getExtension(filePath: string): string {\n const lastDot = filePath.lastIndexOf('.');\n if (lastDot === -1 || lastDot === filePath.length - 1) return '';\n return filePath.slice(lastDot).toLowerCase();\n}\n\nexport function isPreviewableImage(filePath: string): boolean {\n return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isPreviewableSvg(filePath: string): boolean {\n return getExtension(filePath) === '.svg';\n}\n\nexport function isMarkdownFile(filePath: string): boolean {\n return MARKDOWN_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isHtmlFile(filePath: string): boolean {\n return HTML_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function getRenderedTextMode(filePath: string): RenderedTextMode | null {\n if (isMarkdownFile(filePath)) return 'markdown';\n if (isHtmlFile(filePath)) return 'html';\n return null;\n}\n\nexport function isPreviewableRenderedText(filePath: string): boolean {\n return getRenderedTextMode(filePath) !== null;\n}\n\nexport function getLanguageFromPath(filePath: string): string {\n const ext = filePath.split('.').pop()?.toLowerCase() || '';\n const langMap: Record<string, string> = {\n ts: 'typescript',\n tsx: 'tsx',\n js: 'javascript',\n jsx: 'jsx',\n py: 'python',\n css: 'css',\n json: 'json',\n md: 'markdown',\n markdown: 'markdown',\n sh: 'bash',\n bash: 'bash',\n yml: 'yaml',\n yaml: 'yaml',\n java: 'java',\n go: 'go',\n rs: 'rust',\n sql: 'sql',\n html: 'markup',\n htm: 'markup',\n xml: 'markup',\n rb: 'ruby',\n php: 'php',\n twig: 'twig',\n c: 'c',\n cpp: 'cpp',\n h: 'c',\n hpp: 'cpp',\n // Config and data formats\n ini: 'ini',\n toml: 'toml',\n csv: 'csv',\n diff: 'diff',\n patch: 'diff',\n // Web and infrastructure\n scss: 'scss',\n sass: 'sass',\n graphql: 'graphql',\n gql: 'graphql',\n conf: 'nginx',\n // Database\n mongodb: 'mongodb',\n // Tooling\n makefile: 'makefile',\n mk: 'makefile',\n mak: 'makefile',\n vim: 'vim',\n vimrc: 'vim',\n };\n\n // Check for special filenames without extensions\n const filename = filePath.split('/').pop()?.toLowerCase() || '';\n if (filename === 'dockerfile' || filename.startsWith('dockerfile.')) {\n return 'docker';\n }\n if (filename === 'makefile' || filename.startsWith('makefile.')) {\n return 'makefile';\n }\n if (filename.startsWith('.git')) {\n return 'git';\n }\n if (filename === '.vimrc' || filename.startsWith('.vim')) {\n return 'vim';\n }\n\n return langMap[ext] || 'plaintext';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;ACKO,SAAS,UAAU,SAA6B;AACrD,MAAI,CAAC,QAAQ,KAAK,GAAG;AACnB,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,QAAQ,QAAQ,MAAM,IAAI;AAChC,QAAM,QAAoB,CAAC;AAC3B,MAAI,cAAwC;AAC5C,MA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AAAA;AAAA,IAEP,MAAM;AAAA,IACN,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA;AAAA,IAEN,SAAS;AAAA;AAAA,IAET,UAAU;AAAA,IACV,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,OAAO;AAAA,EACT;AAGA,QAAM,WAAW,SAAS,MAAM,GAAG,EAAE,IAAI,GAAG,YAAY,KAAK;AAC7D,MAAI,aAAa,gBAAgB,SAAS,WAAW,aAAa,GAAG;AACnE,WAAO;AAAA,EACT;AACA,MAAI,aAAa,cAAc,SAAS,WAAW,WAAW,GAAG;AAC/D,WAAO;AAAA,EACT;AACA,MAAI,SAAS,WAAW,MAAM,GAAG;AAC/B,WAAO;AAAA,EACT;AACA,MAAI,aAAa,YAAY,SAAS,WAAW,MAAM,GAAG;AACxD,WAAO;AAAA,EACT;AAEA,SAAO,QAAQ,GAAG,KAAK;AACzB;","names":["path","import_fs","ignore","import_fs","import_path","path","parseYaml","import_child_process","import_util","execAsync","import_fs","import_path","fsConstants"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/diff-parser.ts","../src/xml-serializer.ts","../src/xml-parser.ts","../src/git.ts","../src/synthetic-diff.ts","../src/directory-scanner.ts","../src/ignore-filter.ts","../src/config.ts","../src/payload-sizing.ts","../src/fs-utils.ts","../src/file-type-utils.ts"],"sourcesContent":["// @self-review/core — Node.js API for diff parsing, git operations, XML serialization, and configuration\n\n// Types\nexport type {\n ChangeType,\n DiffLineType,\n DiffLine,\n DiffHunk,\n DiffFile,\n DiffSource,\n Suggestion,\n Attachment,\n LineRange,\n ReviewComment,\n CommentSeverity,\n CommentConfidence,\n FileReviewState,\n ReviewState,\n CategoryDef,\n AppConfig,\n DiffLoadPayload,\n ResumeLoadPayload,\n OutputPathInfo,\n ExpandContextRequest,\n ExpandContextResponse,\n FindInPageRequest,\n FindInPageResult,\n VersionUpdateInfo,\n PayloadStats,\n ImageLoadResult,\n} from './types';\n\n// Diff parsing\nexport { parseDiff } from './diff-parser';\n\n// XML I/O\nexport { serializeReview } from './xml-serializer';\nexport { parseReviewXml, parseReviewXmlString } from './xml-parser';\n\n// Git operations\nexport {\n runGitDiff,\n runGitDiffAsync,\n getRepoRoot,\n getRepoRootAsync,\n getUntrackedFilesAsync,\n validateGitAvailable,\n generateUntrackedDiffs,\n} from './git';\n\n// Synthetic diffs (for non-git files/directories)\nexport { generateSyntheticDiffs } from './synthetic-diff';\n\n// Directory/file scanning\nexport { scanDirectory, scanFile } from './directory-scanner';\n\n// Configuration\nexport { loadConfig } from './config';\n\n// Payload sizing\nexport { computePayloadStats, countTotalLines, getGitDiffStats } from './payload-sizing';\n\n// Ignore filter\nexport { createIgnoreFilter } from './ignore-filter';\n\n// File system utilities\nexport { checkWritability } from './fs-utils';\n\n// File type detection utilities\nexport {\n getLanguageFromPath,\n getRenderedTextMode,\n isHtmlFile,\n isMarkdownFile,\n isPreviewableImage,\n isPreviewableRenderedText,\n isPreviewableSvg,\n} from './file-type-utils';\nexport type { RenderedTextMode } from './file-type-utils';\n","// src/main/diff-parser.ts\n// Parse unified diff output into DiffFile[]\n\nimport { DiffFile, DiffHunk, ChangeType } from './types';\n\nexport function parseDiff(rawDiff: string): DiffFile[] {\n if (!rawDiff.trim()) {\n return [];\n }\n\n const lines = rawDiff.split('\\n');\n const files: DiffFile[] = [];\n let currentFile: Partial<DiffFile> | null = null;\n let currentHunk: Partial<DiffHunk> | null = null;\n let oldLineNumber = 0;\n let newLineNumber = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Start of a new file\n if (line.startsWith('diff --git ')) {\n // Flush the pending hunk into the current file before saving\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n currentHunk = null;\n }\n\n // Save previous file if exists and has actual changes\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n // Extract paths from \"diff --git a/<old> b/<new>\" as fallback\n // for binary files that lack --- / +++ lines\n const gitPaths = parseGitDiffHeader(line);\n\n // Initialize new file\n currentFile = {\n oldPath: gitPaths.oldPath,\n newPath: gitPaths.newPath,\n changeType: 'modified' as ChangeType,\n isBinary: false,\n hunks: [],\n };\n currentHunk = null;\n continue;\n }\n\n if (!currentFile) continue;\n\n // Detect file mode changes\n if (line.startsWith('new file mode')) {\n currentFile.changeType = 'added';\n continue;\n }\n\n if (line.startsWith('deleted file mode')) {\n currentFile.changeType = 'deleted';\n continue;\n }\n\n if (line.startsWith('rename from ')) {\n currentFile.changeType = 'renamed';\n continue;\n }\n\n // Parse old file path\n if (line.startsWith('--- ')) {\n const path = line.substring(4);\n currentFile.oldPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Parse new file path\n if (line.startsWith('+++ ')) {\n const path = line.substring(4);\n currentFile.newPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Detect binary files\n if (line.startsWith('Binary files ')) {\n currentFile.isBinary = true;\n continue;\n }\n\n // Parse hunk header\n if (line.startsWith('@@')) {\n // Save previous hunk if exists\n if (currentHunk && currentHunk.header) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n\n // Parse hunk header: @@ -oldStart,oldLines +newStart,newLines @@ context\n const match = line.match(\n /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(.*)$/\n );\n if (match) {\n const oldStart = parseInt(match[1], 10);\n const oldLines = match[2] ? parseInt(match[2], 10) : 1;\n const newStart = parseInt(match[3], 10);\n const newLines = match[4] ? parseInt(match[4], 10) : 1;\n const _context = match[5];\n\n currentHunk = {\n header: line,\n oldStart,\n oldLines,\n newStart,\n newLines,\n lines: [],\n };\n\n oldLineNumber = oldStart;\n newLineNumber = newStart;\n }\n continue;\n }\n\n // Parse diff lines (must have a current hunk)\n if (currentHunk && currentHunk.lines) {\n if (line.startsWith('+')) {\n // Addition\n currentHunk.lines.push({\n type: 'addition',\n oldLineNumber: null,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n newLineNumber++;\n } else if (line.startsWith('-')) {\n // Deletion\n currentHunk.lines.push({\n type: 'deletion',\n oldLineNumber: oldLineNumber,\n newLineNumber: null,\n content: line.substring(1),\n });\n oldLineNumber++;\n } else if (line.startsWith(' ')) {\n // Context line\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n oldLineNumber++;\n newLineNumber++;\n } else if (line.startsWith('\\\\')) {\n // \"\\" - ignore\n continue;\n } else {\n // Some other line (could be empty or malformed), treat as context\n if (currentHunk.lines.length > 0) {\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line,\n });\n oldLineNumber++;\n newLineNumber++;\n }\n }\n }\n }\n\n // Save the last hunk and file\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n return files;\n}\n\nfunction stripPrefix(path: string): string {\n // Remove single-character prefix (a/, b/, c/, i/, w/, etc.)\n // Git uses a/b by default, but mnemonicPrefix uses c/i/w/o\n if (path.length > 2 && path[1] === '/') {\n return path.substring(2);\n }\n return path;\n}\n\nfunction parseGitDiffHeader(line: string): {\n oldPath: string;\n newPath: string;\n} {\n // Format: \"diff --git a/<old> b/<new>\"\n // With diff.mnemonicPrefix, git uses i/ w/ c/ o/ instead of a/ b/.\n // Paths may contain spaces, so we find the \" X/\" separator where X is a\n // single-letter prefix.\n const withoutPrefix = line.substring('diff --git '.length);\n\n // Find \" X/\" — the boundary between old and new paths.\n // Try common prefixes: b/ (default), w/ i/ c/ o/ (mnemonic)\n let bIdx = -1;\n for (const prefix of [' b/', ' w/', ' i/', ' c/', ' o/']) {\n bIdx = withoutPrefix.indexOf(prefix);\n if (bIdx !== -1) break;\n }\n\n if (bIdx === -1) {\n return { oldPath: '', newPath: '' };\n }\n\n const oldPath = stripPrefix(withoutPrefix.substring(0, bIdx));\n const newPath = stripPrefix(withoutPrefix.substring(bIdx + 1));\n return { oldPath, newPath };\n}\n","// src/main/xml-serializer.ts\n// Serialize ReviewState to XML and validate against XSD\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { ReviewState, FileReviewState, ReviewComment } 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 copies listed in AGENTS.md;\n// the sync test in xml-serializer.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:v2\"\n targetNamespace=\"urn:self-review:v2\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review XML Schema v2\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\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\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: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: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: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:schema>`;\n\nfunction extFromMediaType(mediaType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\nfunction writeAttachments(state: ReviewState, outputFilePath: string): ReviewState {\n const assetDir = path.join(path.dirname(outputFilePath), '.self-review-assets');\n let hasAttachments = false;\n\n const updatedFiles = state.files.map(file => ({\n ...file,\n comments: file.comments.map(comment => {\n if (!comment.attachments?.length) return comment;\n\n const updatedAttachments = comment.attachments.map((att, index) => {\n if (!att.data) return att;\n hasAttachments = true;\n\n const ext = extFromMediaType(att.mediaType);\n const fileName = `${comment.id}-${index}.${ext}`;\n const relativePath = `.self-review-assets/${fileName}`;\n\n if (!fs.existsSync(assetDir)) {\n fs.mkdirSync(assetDir, { recursive: true });\n }\n fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));\n\n return { ...att, fileName: relativePath, data: undefined };\n });\n\n return { ...comment, attachments: updatedAttachments };\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-v2.xsd', contents: XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const errors = validationResult.errors || [];\n console.error('XML validation failed:');\n errors.forEach((err: unknown) => console.error(` ${err}`));\n throw new Error('Generated XML does not conform to schema');\n }\n } catch (error) {\n // Re-throw if it's a schema validation failure (our own throw above)\n if (error instanceof Error && error.message === 'Generated XML does not conform to schema') {\n throw error;\n }\n // Infrastructure failure (e.g. WASM load): log warning and return XML anyway\n if (error instanceof Error) {\n console.error(`[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`);\n } else {\n console.error('[main] XML validation infrastructure failed - emitting XML without validation');\n }\n return xml;\n }\n\n return xml;\n}\n\nfunction buildSourceAttributes(state: ReviewState): string {\n const source = state.source;\n if (source.type === 'git') {\n return ` git-diff-args=\"${escapeXml(source.gitDiffArgs)}\" repository=\"${escapeXml(source.repository)}\"`;\n }\n if (source.type === 'directory' || source.type === 'file') {\n return ` source-path=\"${escapeXml(source.sourcePath)}\"`;\n }\n // welcome mode: no source attributes\n return '';\n}\n\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 lines.push(\n `<review xmlns=\"urn:self-review:v2\" timestamp=\"${escapeXml(state.timestamp)}\"${sourceAttrs}>`\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 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 if (comment.attachments?.length) {\n for (const att of comment.attachments) {\n lines.push(` <attachment path=\"${escapeXml(att.fileName)}\" media-type=\"${escapeXml(att.mediaType)}\" />`);\n }\n }\n\n // Closing tag\n lines.push(' </comment>');\n\n return lines;\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\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} from './types';\n\nconst SEVERITY_VALUES: readonly CommentSeverity[] = ['critical', 'major', 'minor', 'info'];\nconst CONFIDENCE_VALUES: readonly CommentConfidence[] = ['high', 'medium', 'low'];\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\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 });\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 = Array.isArray(review.file)\n ? review.file\n : review.file\n ? [review.file]\n : [];\n\n for (const file of files) {\n const filePath = file['@_path'];\n if (!filePath) continue;\n\n if (parseViewed(file['@_viewed'])) {\n viewedFiles.push(String(filePath));\n }\n\n // Handle comments array\n const fileComments = Array.isArray(file.comment)\n ? file.comment\n : file.comment\n ? [file.comment]\n : [];\n\n for (const comment of fileComments) {\n const reviewComment: ReviewComment = {\n id: generateId(),\n filePath,\n lineRange: parseLineRange(comment),\n body: comment.body || '',\n category: 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 };\n\n // Parse attachments\n const commentAttachments = Array.isArray(comment.attachment)\n ? comment.attachment\n : comment.attachment\n ? [comment.attachment]\n : [];\n\n if (commentAttachments.length > 0) {\n reviewComment.attachments = commentAttachments.map(\n (att: Record<string, unknown>, i: number) => ({\n id: `${reviewComment.id}-att-${i}`,\n fileName: String(att['@_path'] || ''),\n mediaType: String(att['@_media-type'] || 'image/png'),\n })\n );\n }\n\n comments.push(reviewComment);\n }\n }\n\n return { comments, viewedFiles, gitDiffArgs, source };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error parsing XML: ${error.message}`);\n } else {\n console.error('Error parsing XML: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Read an enumerated attribute, dropping values the schema does not define.\n *\n * An unrecognised value becomes undefined rather than being passed through:\n * undefined is the fail-safe reading (below every threshold floor), and it\n * keeps a resumed review serializable, since the serializer validates its\n * output against the XSD before writing.\n */\nfunction parseEnumAttribute<T extends string>(\n raw: unknown,\n allowed: readonly T[]\n): T | undefined {\n if (raw === undefined || raw === null) return undefined;\n const value = String(raw);\n return allowed.includes(value as T) ? (value as T) : undefined;\n}\n\n/**\n * Read the `viewed` attribute of a <file> element.\n *\n * Anything other than an explicit true reads as not viewed: the attribute is\n * optional, and treating an unknown value as \"already reviewed\" would silently\n * hide files from the resumed review.\n */\nfunction parseViewed(raw: unknown): boolean {\n return raw === true || String(raw) === 'true';\n}\n\nfunction parseSource(review: Record<string, unknown>): DiffSource {\n const sourcePath = review['@_source-path'];\n if (sourcePath) {\n return { type: 'directory', sourcePath: String(sourcePath) };\n }\n\n const gitDiffArgs = review['@_git-diff-args'];\n const repository = review['@_repository'];\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: String(gitDiffArgs || ''),\n repository: String(repository || ''),\n };\n }\n\n return { type: 'welcome' };\n}\n\nfunction parseLineRange(comment: Record<string, unknown>): LineRange | null {\n const hasOld =\n comment['@_old-line-start'] !== undefined &&\n comment['@_old-line-end'] !== undefined;\n const hasNew =\n comment['@_new-line-start'] !== undefined &&\n comment['@_new-line-end'] !== undefined;\n\n if (hasOld) {\n return {\n side: 'old',\n start: parseInt(String(comment['@_old-line-start']), 10),\n end: parseInt(String(comment['@_old-line-end']), 10),\n };\n }\n\n if (hasNew) {\n return {\n side: 'new',\n start: parseInt(String(comment['@_new-line-start']), 10),\n end: parseInt(String(comment['@_new-line-end']), 10),\n };\n }\n\n return null; // File-level comment\n}\n\nfunction parseSuggestion(comment: Record<string, unknown>): Suggestion | null {\n if (!comment.suggestion) {\n return null;\n }\n\n const suggestion = comment.suggestion as Record<string, unknown>;\n return {\n originalCode: String(suggestion['original-code'] || ''),\n proposedCode: String(suggestion['proposed-code'] || ''),\n };\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// src/main/git.ts\n// Git command execution\n\nimport { execSync, exec } from 'child_process';\nimport { promisify } from 'util';\nimport { generateSyntheticDiffs } from './synthetic-diff';\n\nconst execAsync = promisify(exec);\n\nexport function runGitDiff(args: string[]): string {\n try {\n // Check if git is available\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n // Check if we're in a git repository\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n\n // Run git diff with the provided arguments\n const result = execSync(`git diff ${args.join(' ')}`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large diffs\n });\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function getRepoRoot(): string {\n try {\n const result = execSync('git rev-parse --show-toplevel', {\n encoding: 'utf-8',\n });\n return result.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Lightweight sync validation - checks if git is available and we're in a repo.\n * Called BEFORE Electron initialization for early exit path.\n */\nexport function validateGitAvailable(): void {\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n}\n\n/**\n * Async version of getRepoRoot - called AFTER app.whenReady().\n */\nexport async function getRepoRootAsync(cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync('git rev-parse --show-toplevel', {\n timeout: 10000, // 10 second timeout\n cwd,\n });\n return stdout.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Async version of runGitDiff - called AFTER app.whenReady().\n * Uses timeout to prevent hanging in CI environments.\n */\nexport async function runGitDiffAsync(args: string[], cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`git diff ${args.join(' ')}`, {\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer\n timeout: 30000, // 30 second timeout\n cwd,\n });\n return stdout;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Get list of untracked files (respects .gitignore).\n */\nexport async function getUntrackedFilesAsync(cwd?: string): Promise<string[]> {\n try {\n const { stdout } = await execAsync(\n 'git ls-files --others --exclude-standard',\n {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 10000,\n cwd,\n }\n );\n return stdout\n .trim()\n .split('\\n')\n .filter(line => line.length > 0);\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Warning: Failed to list untracked files: ${error.message}`\n );\n } else {\n console.error('Warning: Failed to list untracked files: unknown error');\n }\n return [];\n }\n}\n\n/**\n * Generate synthetic unified diffs for untracked files so they can be\n * parsed by the existing diff parser.\n *\n * Delegates to the reusable generateSyntheticDiffs module.\n */\nexport function generateUntrackedDiffs(\n paths: string[],\n repoRoot: string\n): string {\n return generateSyntheticDiffs(paths, repoRoot);\n}\n","// src/main/synthetic-diff.ts\n// Generates synthetic unified diffs for files that aren't tracked by git.\n// Reusable by both git untracked file handling and directory-based scanning.\n\nimport { readFileSync } from 'fs';\n\n/**\n * Generate synthetic unified diffs for a list of file paths so they can be\n * parsed by the existing diff parser. Each file is treated as a new addition.\n *\n * @param paths - Relative file paths (e.g. \"src/foo.ts\")\n * @param rootDir - Absolute path to the root directory containing the files\n * @returns A unified diff string covering all provided files\n */\nexport function generateSyntheticDiffs(\n paths: string[],\n rootDir: string\n): string {\n const diffs: string[] = [];\n\n for (const filePath of paths) {\n const fullPath = `${rootDir}/${filePath}`;\n let content: Buffer;\n try {\n content = readFileSync(fullPath);\n } catch {\n // File may have been deleted between listing and reading\n continue;\n }\n\n // Detect binary files by checking for null bytes in the first 8KB\n const sample = content.subarray(0, 8192);\n const isBinary = sample.includes(0);\n\n if (isBinary) {\n diffs.push(\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `Binary files /dev/null and b/${filePath} differ`\n );\n continue;\n }\n\n const text = content.toString('utf-8');\n const lines = text.split('\\n');\n\n // Remove trailing empty string from split if file ends with newline\n if (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n\n const lineCount = lines.length;\n const addedLines = lines.map(line => `+${line}`).join('\\n');\n\n let diff =\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `--- /dev/null\\n` +\n `+++ b/${filePath}\\n` +\n `@@ -0,0 +1,${lineCount} @@\\n` +\n addedLines;\n\n // Indicate missing newline at end of file\n if (text.length > 0 && !text.endsWith('\\n')) {\n diff += '\\n\\\';\n }\n\n diffs.push(diff);\n }\n\n return diffs.join('\\n');\n}\n","// src/main/directory-scanner.ts\n// Recursively scans a directory and produces DiffFile[] treating all files as new additions.\n\nimport { readdir, stat } from 'fs/promises';\nimport { join, relative, basename, dirname } from 'path';\nimport { DiffFile } from './types';\nimport { generateSyntheticDiffs } from './synthetic-diff';\nimport { parseDiff } from './diff-parser';\nimport { createIgnoreFilter } from './ignore-filter';\n\n/**\n * Recursively scan a directory and return DiffFile[] with every file\n * treated as a new addition (changeType: 'added').\n *\n * @param directoryPath - Absolute path to the directory to scan\n * @param ignorePatterns - Optional gitignore-compatible patterns to exclude files\n * @returns Parsed DiffFile array for all files in the directory\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = []\n): Promise<DiffFile[]> {\n // Verify the path is a directory\n try {\n const dirStat = await stat(directoryPath);\n if (!dirStat.isDirectory()) {\n console.error(\n `Error: \"${directoryPath}\" is not a directory`\n );\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error accessing directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error accessing directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n const filePaths: string[] = [];\n\n try {\n const entries = await readdir(directoryPath, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n\n // Build the full path from the entry's parentPath (or path) and name\n const parentDir = entry.parentPath ?? entry.path;\n const fullPath = join(parentDir, entry.name);\n const relativePath = relative(directoryPath, fullPath);\n filePaths.push(relativePath);\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error reading directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error reading directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n // Sort for deterministic output\n filePaths.sort();\n\n // Apply ignore patterns\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredPaths = filePaths.filter(p => shouldKeep(p));\n\n if (filteredPaths.length === 0) {\n return [];\n }\n\n const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);\n return parseDiff(diffText);\n}\n\n/**\n * Scan a single file and return DiffFile[] with the file treated as a new addition.\n *\n * @param filePath - Absolute path to the file to scan\n * @returns Parsed DiffFile array (single element)\n */\nexport async function scanFile(filePath: string): Promise<DiffFile[]> {\n try {\n const fileStat = await stat(filePath);\n if (!fileStat.isFile()) {\n console.error(`Error: \"${filePath}\" is not a file`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing file \"${filePath}\": ${error.message}`);\n } else {\n console.error(`Error accessing file \"${filePath}\": unknown error`);\n }\n return [];\n }\n\n const fileName = basename(filePath);\n const rootDir = dirname(filePath);\n const diffText = generateSyntheticDiffs([fileName], rootDir);\n return parseDiff(diffText);\n}\n","// src/main/ignore-filter.ts\n// Gitignore-compatible file path filtering using the `ignore` package.\n\nimport ignore from 'ignore';\n\n/**\n * Create a filter function from gitignore-compatible patterns.\n *\n * @param patterns - Array of gitignore-compatible glob patterns\n * @returns A predicate that returns `true` if the path should be kept (not ignored)\n */\nexport function createIgnoreFilter(\n patterns: string[]\n): (path: string) => boolean {\n if (patterns.length === 0) return () => true;\n const ig = ignore().add(patterns);\n return (filePath: string) => !ig.ignores(filePath);\n}\n","// src/main/config.ts\n// YAML configuration loading and merging\n\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { parse as parseYaml } from 'yaml';\nimport { AppConfig } from './types';\n\nconst defaults: AppConfig = {\n theme: 'system',\n diffView: 'split',\n fontSize: 14,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: [\n '.git',\n 'node_modules',\n 'vendor',\n '.vendor',\n '__pycache__',\n '.venv',\n 'venv',\n '.env',\n 'dist',\n 'build',\n '.next',\n '.nuxt',\n '.svelte-kit',\n 'target',\n '*.min.js',\n '*.min.css',\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Gemfile.lock',\n 'Cargo.lock',\n 'poetry.lock',\n 'go.sum',\n ],\n categories: [\n {\n name: 'question',\n description: 'Clarification needed — not necessarily a problem',\n color: '#805ad5',\n },\n {\n name: 'bug',\n description: 'Likely defect or incorrect behavior',\n color: '#e53e3e',\n },\n {\n name: 'security',\n description: 'Security vulnerability or concern',\n color: '#dd6b20',\n },\n {\n name: 'style',\n description: 'Code style, naming, or formatting issue',\n color: '#3182ce',\n },\n {\n name: 'task',\n description: 'Action item or follow-up task',\n color: '#38a169',\n },\n {\n name: 'nit',\n description: 'Minor nitpick, low priority',\n color: '#718096',\n },\n ],\n defaultDiffArgs: '',\n showUntracked: true,\n showUntrackedExplicit: false,\n wordWrap: true,\n maxFiles: 500,\n maxTotalLines: 100000,\n};\n\nexport function loadConfig(): AppConfig {\n let config = { ...defaults };\n\n // Load user-level config\n const userConfigPath = join(\n homedir(),\n '.config',\n 'self-review',\n 'config.yaml'\n );\n if (existsSync(userConfigPath)) {\n try {\n const userConfig = loadYamlConfig(userConfigPath);\n config = mergeConfig(config, userConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load user config from ${userConfigPath}: ${error}`\n );\n }\n }\n\n // Load project-level config\n const projectConfigPath = join(process.cwd(), '.self-review.yaml');\n if (existsSync(projectConfigPath)) {\n try {\n const projectConfig = loadYamlConfig(projectConfigPath);\n config = mergeConfig(config, projectConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load project config from ${projectConfigPath}: ${error}`\n );\n }\n }\n\n return config;\n}\n\nfunction loadYamlConfig(path: string): Partial<AppConfig> {\n const content = readFileSync(path, 'utf-8');\n const raw = parseYaml(content);\n\n // An empty file (or one containing only `null`) is a valid \"use defaults\" state.\n if (raw === null || raw === undefined) {\n return {};\n }\n\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error('Invalid YAML format');\n }\n\n // Map kebab-case keys to camelCase\n const config: Partial<AppConfig> = {};\n\n if ('theme' in raw) {\n if (['light', 'dark', 'system'].includes(raw.theme)) {\n config.theme = raw.theme;\n } else {\n console.error(\n `Warning: Invalid theme value \"${raw.theme}\", using default`\n );\n }\n }\n\n if ('diff-view' in raw) {\n if (['split', 'unified'].includes(raw['diff-view'])) {\n config.diffView = raw['diff-view'];\n } else {\n console.error(\n `Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`\n );\n }\n }\n\n if ('font-size' in raw && typeof raw['font-size'] === 'number') {\n config.fontSize = raw['font-size'];\n }\n\n if ('output-format' in raw && typeof raw['output-format'] === 'string') {\n config.outputFormat = raw['output-format'];\n }\n\n if ('ignore' in raw && Array.isArray(raw.ignore)) {\n config.ignore = raw.ignore.filter(\n (item: unknown) => typeof item === 'string'\n );\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n config.categories = raw.categories.filter(\n (cat: unknown): cat is { name: string; description: string; color: string } =>\n cat !== null &&\n typeof cat === 'object' &&\n typeof (cat as Record<string, unknown>).name === 'string' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n }\n\n if (\n 'default-diff-args' in raw &&\n typeof raw['default-diff-args'] === 'string'\n ) {\n config.defaultDiffArgs = raw['default-diff-args'];\n }\n\n if ('show-untracked' in raw && typeof raw['show-untracked'] === 'boolean') {\n config.showUntracked = raw['show-untracked'];\n config.showUntrackedExplicit = true;\n }\n\n if ('word-wrap' in raw && typeof raw['word-wrap'] === 'boolean') {\n config.wordWrap = raw['word-wrap'];\n }\n\n if ('max-files' in raw && typeof raw['max-files'] === 'number') {\n config.maxFiles = raw['max-files'] >= 0 ? raw['max-files'] : defaults.maxFiles;\n }\n\n if ('max-total-lines' in raw && typeof raw['max-total-lines'] === 'number') {\n config.maxTotalLines = raw['max-total-lines'] >= 0 ? raw['max-total-lines'] : defaults.maxTotalLines;\n }\n\n if (\n 'output-file' in raw &&\n typeof raw['output-file'] === 'string' &&\n raw['output-file'].length > 0\n ) {\n config.outputFile = raw['output-file'];\n }\n\n return config;\n}\n\nfunction mergeConfig(base: AppConfig, override: Partial<AppConfig>): AppConfig {\n return {\n ...base,\n ...override,\n // Arrays are replaced, not merged\n ignore: override.ignore !== undefined ? override.ignore : base.ignore,\n categories:\n override.categories !== undefined ? override.categories : base.categories,\n };\n}\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execAsync = promisify(exec);\n\n/**\n * Compute payload statistics and check against configured thresholds.\n * A maxFiles or maxTotalLines value of 0 disables that guard.\n */\nexport function computePayloadStats(\n fileCount: number,\n totalLines: number,\n config: AppConfig\n): PayloadStats {\n const maxFiles = config.maxFiles;\n const maxTotalLines = config.maxTotalLines;\n const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;\n const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;\n return {\n fileCount,\n totalLines,\n exceedsFiles,\n exceedsLines,\n exceedsAny: exceedsFiles || exceedsLines,\n };\n}\n\n/**\n * Count total diff lines across all files and hunks.\n */\nexport function countTotalLines(files: DiffFile[]): number {\n let total = 0;\n for (const file of files) {\n for (const hunk of file.hunks) {\n total += hunk.lines.length;\n }\n }\n return total;\n}\n\n/**\n * Get git diff stats cheaply using --numstat (avoids full diff parsing).\n * Each output line is \"added\\tremoved\\tfilename\".\n * Returns file count and total changed lines (added + removed).\n */\nexport async function getGitDiffStats(\n args: string[],\n repoRoot: string\n): Promise<{ fileCount: number; totalLines: number }> {\n try {\n const { stdout } = await execAsync(`git diff --numstat ${args.join(' ')}`, {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 15000,\n cwd: repoRoot,\n });\n\n let fileCount = 0;\n let totalLines = 0;\n\n for (const line of stdout.trim().split('\\n')) {\n if (!line) continue;\n const parts = line.split('\\t');\n if (parts.length < 3) continue;\n\n fileCount++;\n // Binary files show '-' for added/removed\n const added = parts[0] === '-' ? 0 : parseInt(parts[0], 10);\n const removed = parts[1] === '-' ? 0 : parseInt(parts[1], 10);\n totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);\n }\n\n return { fileCount, totalLines };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);\n } else {\n console.error('[payload-sizing] Failed to get git diff stats: unknown error');\n }\n // Return zeros so the guard does not block on failure\n return { fileCount: 0, totalLines: 0 };\n }\n}\n","// src/main/fs-utils.ts\n// Filesystem utility functions for the main process.\n\nimport { accessSync, constants as fsConstants } from 'fs';\nimport { dirname } from 'path';\n\n/**\n * Check if a file's parent directory is writable.\n * Returns true if the directory exists and the process has write permission,\n * false otherwise (including non-existent directories).\n */\nexport function checkWritability(filePath: string): boolean {\n try {\n const dir = dirname(filePath);\n accessSync(dir, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * File-type detection utilities.\n *\n * NOTE: This file is intentionally duplicated in packages/react/src/utils/file-type-utils.ts.\n * @self-review/core has Node-only dependencies, so @self-review/react cannot safely import\n * from this package. Both copies must be kept in sync.\n */\n\nconst RASTER_IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.ico', '.bmp']);\nconst MARKDOWN_EXTENSIONS = new Set(['.md', '.markdown']);\nconst HTML_EXTENSIONS = new Set(['.html', '.htm']);\n\nexport type RenderedTextMode = 'markdown' | 'html';\n\nfunction getExtension(filePath: string): string {\n const lastDot = filePath.lastIndexOf('.');\n if (lastDot === -1 || lastDot === filePath.length - 1) return '';\n return filePath.slice(lastDot).toLowerCase();\n}\n\nexport function isPreviewableImage(filePath: string): boolean {\n return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isPreviewableSvg(filePath: string): boolean {\n return getExtension(filePath) === '.svg';\n}\n\nexport function isMarkdownFile(filePath: string): boolean {\n return MARKDOWN_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isHtmlFile(filePath: string): boolean {\n return HTML_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function getRenderedTextMode(filePath: string): RenderedTextMode | null {\n if (isMarkdownFile(filePath)) return 'markdown';\n if (isHtmlFile(filePath)) return 'html';\n return null;\n}\n\nexport function isPreviewableRenderedText(filePath: string): boolean {\n return getRenderedTextMode(filePath) !== null;\n}\n\nexport function getLanguageFromPath(filePath: string): string {\n const ext = filePath.split('.').pop()?.toLowerCase() || '';\n const langMap: Record<string, string> = {\n ts: 'typescript',\n tsx: 'tsx',\n js: 'javascript',\n jsx: 'jsx',\n py: 'python',\n css: 'css',\n json: 'json',\n md: 'markdown',\n markdown: 'markdown',\n sh: 'bash',\n bash: 'bash',\n yml: 'yaml',\n yaml: 'yaml',\n java: 'java',\n go: 'go',\n rs: 'rust',\n sql: 'sql',\n html: 'markup',\n htm: 'markup',\n xml: 'markup',\n rb: 'ruby',\n php: 'php',\n twig: 'twig',\n c: 'c',\n cpp: 'cpp',\n h: 'c',\n hpp: 'cpp',\n // Config and data formats\n ini: 'ini',\n toml: 'toml',\n csv: 'csv',\n diff: 'diff',\n patch: 'diff',\n // Web and infrastructure\n scss: 'scss',\n sass: 'sass',\n graphql: 'graphql',\n gql: 'graphql',\n conf: 'nginx',\n // Database\n mongodb: 'mongodb',\n // Tooling\n makefile: 'makefile',\n mk: 'makefile',\n mak: 'makefile',\n vim: 'vim',\n vimrc: 'vim',\n };\n\n // Check for special filenames without extensions\n const filename = filePath.split('/').pop()?.toLowerCase() || '';\n if (filename === 'dockerfile' || filename.startsWith('dockerfile.')) {\n return 'docker';\n }\n if (filename === 'makefile' || filename.startsWith('makefile.')) {\n return 'makefile';\n }\n if (filename.startsWith('.git')) {\n return 'git';\n }\n if (filename === '.vimrc' || filename.startsWith('.vim')) {\n return 'vim';\n }\n\n return langMap[ext] || 'plaintext';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;ACKO,SAAS,UAAU,SAA6B;AACrD,MAAI,CAAC,QAAQ,KAAK,GAAG;AACnB,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,QAAQ,QAAQ,MAAM,IAAI;AAChC,QAAM,QAAoB,CAAC;A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;AAAA,IACL,KAAK;AAAA,IACL,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,MAAM;AAAA,IACN,GAAG;AAAA,IACH,KAAK;AAAA,IACL,GAAG;AAAA,IACH,KAAK;AAAA;AAAA,IAEL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA;AAAA,IAEP,MAAM;AAAA,IACN,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA;AAAA,IAEN,SAAS;AAAA;AAAA,IAET,UAAU;AAAA,IACV,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,OAAO;AAAA,EACT;AAGA,QAAM,WAAW,SAAS,MAAM,GAAG,EAAE,IAAI,GAAG,YAAY,KAAK;AAC7D,MAAI,aAAa,gBAAgB,SAAS,WAAW,aAAa,GAAG;AACnE,WAAO;AAAA,EACT;AACA,MAAI,aAAa,cAAc,SAAS,WAAW,WAAW,GAAG;AAC/D,WAAO;AAAA,EACT;AACA,MAAI,SAAS,WAAW,MAAM,GAAG;AAC/B,WAAO;AAAA,EACT;AACA,MAAI,aAAa,YAAY,SAAS,WAAW,MAAM,GAAG;AACxD,WAAO;AAAA,EACT;AAEA,SAAO,QAAQ,GAAG,KAAK;AACzB;","names":["path","import_fs","ignore","import_fs","import_path","path","parseYaml","import_child_process","import_util","execAsync","import_fs","import_path","fsConstants"]}
package/dist/index.d.cts CHANGED
@@ -7,6 +7,8 @@ declare function serializeReview(state: ReviewState, outputFilePath: string): Pr
7
7
 
8
8
  interface ParsedReview {
9
9
  comments: ReviewComment[];
10
+ /** Paths of files the previous review marked as done (`viewed="true"`). */
11
+ viewedFiles: string[];
10
12
  gitDiffArgs: string;
11
13
  source: DiffSource;
12
14
  }
package/dist/index.d.ts CHANGED
@@ -7,6 +7,8 @@ declare function serializeReview(state: ReviewState, outputFilePath: string): Pr
7
7
 
8
8
  interface ParsedReview {
9
9
  comments: ReviewComment[];
10
+ /** Paths of files the previous review marked as done (`viewed="true"`). */
11
+ viewedFiles: string[];
10
12
  gitDiffArgs: string;
11
13
  source: DiffSource;
12
14
  }
package/dist/index.js CHANGED
@@ -782,10 +782,14 @@ function parseReviewXmlString(xmlContent) {
782
782
  const gitDiffArgs = review["@_git-diff-args"] || "";
783
783
  const source = parseSource(review);
784
784
  const comments = [];
785
+ const viewedFiles = [];
785
786
  const files = Array.isArray(review.file) ? review.file : review.file ? [review.file] : [];
786
787
  for (const file of files) {
787
788
  const filePath = file["@_path"];
788
789
  if (!filePath) continue;
790
+ if (parseViewed(file["@_viewed"])) {
791
+ viewedFiles.push(String(filePath));
792
+ }
789
793
  const fileComments = Array.isArray(file.comment) ? file.comment : file.comment ? [file.comment] : [];
790
794
  for (const comment of fileComments) {
791
795
  const reviewComment = {
@@ -812,7 +816,7 @@ function parseReviewXmlString(xmlContent) {
812
816
  comments.push(reviewComment);
813
817
  }
814
818
  }
815
- return { comments, gitDiffArgs, source };
819
+ return { comments, viewedFiles, gitDiffArgs, source };
816
820
  } catch (error) {
817
821
  if (error instanceof Error) {
818
822
  console.error(`Error parsing XML: ${error.message}`);
@@ -827,6 +831,9 @@ function parseEnumAttribute(raw, allowed) {
827
831
  const value = String(raw);
828
832
  return allowed.includes(value) ? value : void 0;
829
833
  }
834
+ function parseViewed(raw) {
835
+ return raw === true || String(raw) === "true";
836
+ }
830
837
  function parseSource(review) {
831
838
  const sourcePath = review["@_source-path"];
832
839
  if (sourcePath) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/diff-parser.ts","../src/xml-serializer.ts","../src/xml-parser.ts","../src/git.ts","../src/synthetic-diff.ts","../src/directory-scanner.ts","../src/ignore-filter.ts","../src/config.ts","../src/payload-sizing.ts","../src/fs-utils.ts","../src/file-type-utils.ts"],"sourcesContent":["// src/main/diff-parser.ts\n// Parse unified diff output into DiffFile[]\n\nimport { DiffFile, DiffHunk, ChangeType } from './types';\n\nexport function parseDiff(rawDiff: string): DiffFile[] {\n if (!rawDiff.trim()) {\n return [];\n }\n\n const lines = rawDiff.split('\\n');\n const files: DiffFile[] = [];\n let currentFile: Partial<DiffFile> | null = null;\n let currentHunk: Partial<DiffHunk> | null = null;\n let oldLineNumber = 0;\n let newLineNumber = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Start of a new file\n if (line.startsWith('diff --git ')) {\n // Flush the pending hunk into the current file before saving\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n currentHunk = null;\n }\n\n // Save previous file if exists and has actual changes\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n // Extract paths from \"diff --git a/<old> b/<new>\" as fallback\n // for binary files that lack --- / +++ lines\n const gitPaths = parseGitDiffHeader(line);\n\n // Initialize new file\n currentFile = {\n oldPath: gitPaths.oldPath,\n newPath: gitPaths.newPath,\n changeType: 'modified' as ChangeType,\n isBinary: false,\n hunks: [],\n };\n currentHunk = null;\n continue;\n }\n\n if (!currentFile) continue;\n\n // Detect file mode changes\n if (line.startsWith('new file mode')) {\n currentFile.changeType = 'added';\n continue;\n }\n\n if (line.startsWith('deleted file mode')) {\n currentFile.changeType = 'deleted';\n continue;\n }\n\n if (line.startsWith('rename from ')) {\n currentFile.changeType = 'renamed';\n continue;\n }\n\n // Parse old file path\n if (line.startsWith('--- ')) {\n const path = line.substring(4);\n currentFile.oldPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Parse new file path\n if (line.startsWith('+++ ')) {\n const path = line.substring(4);\n currentFile.newPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Detect binary files\n if (line.startsWith('Binary files ')) {\n currentFile.isBinary = true;\n continue;\n }\n\n // Parse hunk header\n if (line.startsWith('@@')) {\n // Save previous hunk if exists\n if (currentHunk && currentHunk.header) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n\n // Parse hunk header: @@ -oldStart,oldLines +newStart,newLines @@ context\n const match = line.match(\n /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(.*)$/\n );\n if (match) {\n const oldStart = parseInt(match[1], 10);\n const oldLines = match[2] ? parseInt(match[2], 10) : 1;\n const newStart = parseInt(match[3], 10);\n const newLines = match[4] ? parseInt(match[4], 10) : 1;\n const _context = match[5];\n\n currentHunk = {\n header: line,\n oldStart,\n oldLines,\n newStart,\n newLines,\n lines: [],\n };\n\n oldLineNumber = oldStart;\n newLineNumber = newStart;\n }\n continue;\n }\n\n // Parse diff lines (must have a current hunk)\n if (currentHunk && currentHunk.lines) {\n if (line.startsWith('+')) {\n // Addition\n currentHunk.lines.push({\n type: 'addition',\n oldLineNumber: null,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n newLineNumber++;\n } else if (line.startsWith('-')) {\n // Deletion\n currentHunk.lines.push({\n type: 'deletion',\n oldLineNumber: oldLineNumber,\n newLineNumber: null,\n content: line.substring(1),\n });\n oldLineNumber++;\n } else if (line.startsWith(' ')) {\n // Context line\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n oldLineNumber++;\n newLineNumber++;\n } else if (line.startsWith('\\\\')) {\n // \"\\" - ignore\n continue;\n } else {\n // Some other line (could be empty or malformed), treat as context\n if (currentHunk.lines.length > 0) {\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line,\n });\n oldLineNumber++;\n newLineNumber++;\n }\n }\n }\n }\n\n // Save the last hunk and file\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n return files;\n}\n\nfunction stripPrefix(path: string): string {\n // Remove single-character prefix (a/, b/, c/, i/, w/, etc.)\n // Git uses a/b by default, but mnemonicPrefix uses c/i/w/o\n if (path.length > 2 && path[1] === '/') {\n return path.substring(2);\n }\n return path;\n}\n\nfunction parseGitDiffHeader(line: string): {\n oldPath: string;\n newPath: string;\n} {\n // Format: \"diff --git a/<old> b/<new>\"\n // With diff.mnemonicPrefix, git uses i/ w/ c/ o/ instead of a/ b/.\n // Paths may contain spaces, so we find the \" X/\" separator where X is a\n // single-letter prefix.\n const withoutPrefix = line.substring('diff --git '.length);\n\n // Find \" X/\" — the boundary between old and new paths.\n // Try common prefixes: b/ (default), w/ i/ c/ o/ (mnemonic)\n let bIdx = -1;\n for (const prefix of [' b/', ' w/', ' i/', ' c/', ' o/']) {\n bIdx = withoutPrefix.indexOf(prefix);\n if (bIdx !== -1) break;\n }\n\n if (bIdx === -1) {\n return { oldPath: '', newPath: '' };\n }\n\n const oldPath = stripPrefix(withoutPrefix.substring(0, bIdx));\n const newPath = stripPrefix(withoutPrefix.substring(bIdx + 1));\n return { oldPath, newPath };\n}\n","// src/main/xml-serializer.ts\n// Serialize ReviewState to XML and validate against XSD\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { ReviewState, FileReviewState, ReviewComment } 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 copies listed in AGENTS.md;\n// the sync test in xml-serializer.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:v2\"\n targetNamespace=\"urn:self-review:v2\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review XML Schema v2\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\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\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: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: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: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:schema>`;\n\nfunction extFromMediaType(mediaType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\nfunction writeAttachments(state: ReviewState, outputFilePath: string): ReviewState {\n const assetDir = path.join(path.dirname(outputFilePath), '.self-review-assets');\n let hasAttachments = false;\n\n const updatedFiles = state.files.map(file => ({\n ...file,\n comments: file.comments.map(comment => {\n if (!comment.attachments?.length) return comment;\n\n const updatedAttachments = comment.attachments.map((att, index) => {\n if (!att.data) return att;\n hasAttachments = true;\n\n const ext = extFromMediaType(att.mediaType);\n const fileName = `${comment.id}-${index}.${ext}`;\n const relativePath = `.self-review-assets/${fileName}`;\n\n if (!fs.existsSync(assetDir)) {\n fs.mkdirSync(assetDir, { recursive: true });\n }\n fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));\n\n return { ...att, fileName: relativePath, data: undefined };\n });\n\n return { ...comment, attachments: updatedAttachments };\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-v2.xsd', contents: XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const errors = validationResult.errors || [];\n console.error('XML validation failed:');\n errors.forEach((err: unknown) => console.error(` ${err}`));\n throw new Error('Generated XML does not conform to schema');\n }\n } catch (error) {\n // Re-throw if it's a schema validation failure (our own throw above)\n if (error instanceof Error && error.message === 'Generated XML does not conform to schema') {\n throw error;\n }\n // Infrastructure failure (e.g. WASM load): log warning and return XML anyway\n if (error instanceof Error) {\n console.error(`[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`);\n } else {\n console.error('[main] XML validation infrastructure failed - emitting XML without validation');\n }\n return xml;\n }\n\n return xml;\n}\n\nfunction buildSourceAttributes(state: ReviewState): string {\n const source = state.source;\n if (source.type === 'git') {\n return ` git-diff-args=\"${escapeXml(source.gitDiffArgs)}\" repository=\"${escapeXml(source.repository)}\"`;\n }\n if (source.type === 'directory' || source.type === 'file') {\n return ` source-path=\"${escapeXml(source.sourcePath)}\"`;\n }\n // welcome mode: no source attributes\n return '';\n}\n\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 lines.push(\n `<review xmlns=\"urn:self-review:v2\" timestamp=\"${escapeXml(state.timestamp)}\"${sourceAttrs}>`\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 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 if (comment.attachments?.length) {\n for (const att of comment.attachments) {\n lines.push(` <attachment path=\"${escapeXml(att.fileName)}\" media-type=\"${escapeXml(att.mediaType)}\" />`);\n }\n }\n\n // Closing tag\n lines.push(' </comment>');\n\n return lines;\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\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} from './types';\n\nconst SEVERITY_VALUES: readonly CommentSeverity[] = ['critical', 'major', 'minor', 'info'];\nconst CONFIDENCE_VALUES: readonly CommentConfidence[] = ['high', 'medium', 'low'];\n\nexport interface ParsedReview {\n comments: ReviewComment[];\n gitDiffArgs: string;\n source: DiffSource;\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 });\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\n // Handle files array\n const files = Array.isArray(review.file)\n ? review.file\n : review.file\n ? [review.file]\n : [];\n\n for (const file of files) {\n const filePath = file['@_path'];\n if (!filePath) continue;\n\n // Handle comments array\n const fileComments = Array.isArray(file.comment)\n ? file.comment\n : file.comment\n ? [file.comment]\n : [];\n\n for (const comment of fileComments) {\n const reviewComment: ReviewComment = {\n id: generateId(),\n filePath,\n lineRange: parseLineRange(comment),\n body: comment.body || '',\n category: 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 };\n\n // Parse attachments\n const commentAttachments = Array.isArray(comment.attachment)\n ? comment.attachment\n : comment.attachment\n ? [comment.attachment]\n : [];\n\n if (commentAttachments.length > 0) {\n reviewComment.attachments = commentAttachments.map(\n (att: Record<string, unknown>, i: number) => ({\n id: `${reviewComment.id}-att-${i}`,\n fileName: String(att['@_path'] || ''),\n mediaType: String(att['@_media-type'] || 'image/png'),\n })\n );\n }\n\n comments.push(reviewComment);\n }\n }\n\n return { comments, gitDiffArgs, source };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error parsing XML: ${error.message}`);\n } else {\n console.error('Error parsing XML: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Read an enumerated attribute, dropping values the schema does not define.\n *\n * An unrecognised value becomes undefined rather than being passed through:\n * undefined is the fail-safe reading (below every threshold floor), and it\n * keeps a resumed review serializable, since the serializer validates its\n * output against the XSD before writing.\n */\nfunction parseEnumAttribute<T extends string>(\n raw: unknown,\n allowed: readonly T[]\n): T | undefined {\n if (raw === undefined || raw === null) return undefined;\n const value = String(raw);\n return allowed.includes(value as T) ? (value as T) : undefined;\n}\n\nfunction parseSource(review: Record<string, unknown>): DiffSource {\n const sourcePath = review['@_source-path'];\n if (sourcePath) {\n return { type: 'directory', sourcePath: String(sourcePath) };\n }\n\n const gitDiffArgs = review['@_git-diff-args'];\n const repository = review['@_repository'];\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: String(gitDiffArgs || ''),\n repository: String(repository || ''),\n };\n }\n\n return { type: 'welcome' };\n}\n\nfunction parseLineRange(comment: Record<string, unknown>): LineRange | null {\n const hasOld =\n comment['@_old-line-start'] !== undefined &&\n comment['@_old-line-end'] !== undefined;\n const hasNew =\n comment['@_new-line-start'] !== undefined &&\n comment['@_new-line-end'] !== undefined;\n\n if (hasOld) {\n return {\n side: 'old',\n start: parseInt(String(comment['@_old-line-start']), 10),\n end: parseInt(String(comment['@_old-line-end']), 10),\n };\n }\n\n if (hasNew) {\n return {\n side: 'new',\n start: parseInt(String(comment['@_new-line-start']), 10),\n end: parseInt(String(comment['@_new-line-end']), 10),\n };\n }\n\n return null; // File-level comment\n}\n\nfunction parseSuggestion(comment: Record<string, unknown>): Suggestion | null {\n if (!comment.suggestion) {\n return null;\n }\n\n const suggestion = comment.suggestion as Record<string, unknown>;\n return {\n originalCode: String(suggestion['original-code'] || ''),\n proposedCode: String(suggestion['proposed-code'] || ''),\n };\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// src/main/git.ts\n// Git command execution\n\nimport { execSync, exec } from 'child_process';\nimport { promisify } from 'util';\nimport { generateSyntheticDiffs } from './synthetic-diff';\n\nconst execAsync = promisify(exec);\n\nexport function runGitDiff(args: string[]): string {\n try {\n // Check if git is available\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n // Check if we're in a git repository\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n\n // Run git diff with the provided arguments\n const result = execSync(`git diff ${args.join(' ')}`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large diffs\n });\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function getRepoRoot(): string {\n try {\n const result = execSync('git rev-parse --show-toplevel', {\n encoding: 'utf-8',\n });\n return result.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Lightweight sync validation - checks if git is available and we're in a repo.\n * Called BEFORE Electron initialization for early exit path.\n */\nexport function validateGitAvailable(): void {\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n}\n\n/**\n * Async version of getRepoRoot - called AFTER app.whenReady().\n */\nexport async function getRepoRootAsync(cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync('git rev-parse --show-toplevel', {\n timeout: 10000, // 10 second timeout\n cwd,\n });\n return stdout.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Async version of runGitDiff - called AFTER app.whenReady().\n * Uses timeout to prevent hanging in CI environments.\n */\nexport async function runGitDiffAsync(args: string[], cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`git diff ${args.join(' ')}`, {\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer\n timeout: 30000, // 30 second timeout\n cwd,\n });\n return stdout;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Get list of untracked files (respects .gitignore).\n */\nexport async function getUntrackedFilesAsync(cwd?: string): Promise<string[]> {\n try {\n const { stdout } = await execAsync(\n 'git ls-files --others --exclude-standard',\n {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 10000,\n cwd,\n }\n );\n return stdout\n .trim()\n .split('\\n')\n .filter(line => line.length > 0);\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Warning: Failed to list untracked files: ${error.message}`\n );\n } else {\n console.error('Warning: Failed to list untracked files: unknown error');\n }\n return [];\n }\n}\n\n/**\n * Generate synthetic unified diffs for untracked files so they can be\n * parsed by the existing diff parser.\n *\n * Delegates to the reusable generateSyntheticDiffs module.\n */\nexport function generateUntrackedDiffs(\n paths: string[],\n repoRoot: string\n): string {\n return generateSyntheticDiffs(paths, repoRoot);\n}\n","// src/main/synthetic-diff.ts\n// Generates synthetic unified diffs for files that aren't tracked by git.\n// Reusable by both git untracked file handling and directory-based scanning.\n\nimport { readFileSync } from 'fs';\n\n/**\n * Generate synthetic unified diffs for a list of file paths so they can be\n * parsed by the existing diff parser. Each file is treated as a new addition.\n *\n * @param paths - Relative file paths (e.g. \"src/foo.ts\")\n * @param rootDir - Absolute path to the root directory containing the files\n * @returns A unified diff string covering all provided files\n */\nexport function generateSyntheticDiffs(\n paths: string[],\n rootDir: string\n): string {\n const diffs: string[] = [];\n\n for (const filePath of paths) {\n const fullPath = `${rootDir}/${filePath}`;\n let content: Buffer;\n try {\n content = readFileSync(fullPath);\n } catch {\n // File may have been deleted between listing and reading\n continue;\n }\n\n // Detect binary files by checking for null bytes in the first 8KB\n const sample = content.subarray(0, 8192);\n const isBinary = sample.includes(0);\n\n if (isBinary) {\n diffs.push(\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `Binary files /dev/null and b/${filePath} differ`\n );\n continue;\n }\n\n const text = content.toString('utf-8');\n const lines = text.split('\\n');\n\n // Remove trailing empty string from split if file ends with newline\n if (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n\n const lineCount = lines.length;\n const addedLines = lines.map(line => `+${line}`).join('\\n');\n\n let diff =\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `--- /dev/null\\n` +\n `+++ b/${filePath}\\n` +\n `@@ -0,0 +1,${lineCount} @@\\n` +\n addedLines;\n\n // Indicate missing newline at end of file\n if (text.length > 0 && !text.endsWith('\\n')) {\n diff += '\\n\\\';\n }\n\n diffs.push(diff);\n }\n\n return diffs.join('\\n');\n}\n","// src/main/directory-scanner.ts\n// Recursively scans a directory and produces DiffFile[] treating all files as new additions.\n\nimport { readdir, stat } from 'fs/promises';\nimport { join, relative, basename, dirname } from 'path';\nimport { DiffFile } from './types';\nimport { generateSyntheticDiffs } from './synthetic-diff';\nimport { parseDiff } from './diff-parser';\nimport { createIgnoreFilter } from './ignore-filter';\n\n/**\n * Recursively scan a directory and return DiffFile[] with every file\n * treated as a new addition (changeType: 'added').\n *\n * @param directoryPath - Absolute path to the directory to scan\n * @param ignorePatterns - Optional gitignore-compatible patterns to exclude files\n * @returns Parsed DiffFile array for all files in the directory\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = []\n): Promise<DiffFile[]> {\n // Verify the path is a directory\n try {\n const dirStat = await stat(directoryPath);\n if (!dirStat.isDirectory()) {\n console.error(\n `Error: \"${directoryPath}\" is not a directory`\n );\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error accessing directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error accessing directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n const filePaths: string[] = [];\n\n try {\n const entries = await readdir(directoryPath, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n\n // Build the full path from the entry's parentPath (or path) and name\n const parentDir = entry.parentPath ?? entry.path;\n const fullPath = join(parentDir, entry.name);\n const relativePath = relative(directoryPath, fullPath);\n filePaths.push(relativePath);\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error reading directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error reading directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n // Sort for deterministic output\n filePaths.sort();\n\n // Apply ignore patterns\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredPaths = filePaths.filter(p => shouldKeep(p));\n\n if (filteredPaths.length === 0) {\n return [];\n }\n\n const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);\n return parseDiff(diffText);\n}\n\n/**\n * Scan a single file and return DiffFile[] with the file treated as a new addition.\n *\n * @param filePath - Absolute path to the file to scan\n * @returns Parsed DiffFile array (single element)\n */\nexport async function scanFile(filePath: string): Promise<DiffFile[]> {\n try {\n const fileStat = await stat(filePath);\n if (!fileStat.isFile()) {\n console.error(`Error: \"${filePath}\" is not a file`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing file \"${filePath}\": ${error.message}`);\n } else {\n console.error(`Error accessing file \"${filePath}\": unknown error`);\n }\n return [];\n }\n\n const fileName = basename(filePath);\n const rootDir = dirname(filePath);\n const diffText = generateSyntheticDiffs([fileName], rootDir);\n return parseDiff(diffText);\n}\n","// src/main/ignore-filter.ts\n// Gitignore-compatible file path filtering using the `ignore` package.\n\nimport ignore from 'ignore';\n\n/**\n * Create a filter function from gitignore-compatible patterns.\n *\n * @param patterns - Array of gitignore-compatible glob patterns\n * @returns A predicate that returns `true` if the path should be kept (not ignored)\n */\nexport function createIgnoreFilter(\n patterns: string[]\n): (path: string) => boolean {\n if (patterns.length === 0) return () => true;\n const ig = ignore().add(patterns);\n return (filePath: string) => !ig.ignores(filePath);\n}\n","// src/main/config.ts\n// YAML configuration loading and merging\n\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { parse as parseYaml } from 'yaml';\nimport { AppConfig } from './types';\n\nconst defaults: AppConfig = {\n theme: 'system',\n diffView: 'split',\n fontSize: 14,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: [\n '.git',\n 'node_modules',\n 'vendor',\n '.vendor',\n '__pycache__',\n '.venv',\n 'venv',\n '.env',\n 'dist',\n 'build',\n '.next',\n '.nuxt',\n '.svelte-kit',\n 'target',\n '*.min.js',\n '*.min.css',\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Gemfile.lock',\n 'Cargo.lock',\n 'poetry.lock',\n 'go.sum',\n ],\n categories: [\n {\n name: 'question',\n description: 'Clarification needed — not necessarily a problem',\n color: '#805ad5',\n },\n {\n name: 'bug',\n description: 'Likely defect or incorrect behavior',\n color: '#e53e3e',\n },\n {\n name: 'security',\n description: 'Security vulnerability or concern',\n color: '#dd6b20',\n },\n {\n name: 'style',\n description: 'Code style, naming, or formatting issue',\n color: '#3182ce',\n },\n {\n name: 'task',\n description: 'Action item or follow-up task',\n color: '#38a169',\n },\n {\n name: 'nit',\n description: 'Minor nitpick, low priority',\n color: '#718096',\n },\n ],\n defaultDiffArgs: '',\n showUntracked: true,\n showUntrackedExplicit: false,\n wordWrap: true,\n maxFiles: 500,\n maxTotalLines: 100000,\n};\n\nexport function loadConfig(): AppConfig {\n let config = { ...defaults };\n\n // Load user-level config\n const userConfigPath = join(\n homedir(),\n '.config',\n 'self-review',\n 'config.yaml'\n );\n if (existsSync(userConfigPath)) {\n try {\n const userConfig = loadYamlConfig(userConfigPath);\n config = mergeConfig(config, userConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load user config from ${userConfigPath}: ${error}`\n );\n }\n }\n\n // Load project-level config\n const projectConfigPath = join(process.cwd(), '.self-review.yaml');\n if (existsSync(projectConfigPath)) {\n try {\n const projectConfig = loadYamlConfig(projectConfigPath);\n config = mergeConfig(config, projectConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load project config from ${projectConfigPath}: ${error}`\n );\n }\n }\n\n return config;\n}\n\nfunction loadYamlConfig(path: string): Partial<AppConfig> {\n const content = readFileSync(path, 'utf-8');\n const raw = parseYaml(content);\n\n // An empty file (or one containing only `null`) is a valid \"use defaults\" state.\n if (raw === null || raw === undefined) {\n return {};\n }\n\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error('Invalid YAML format');\n }\n\n // Map kebab-case keys to camelCase\n const config: Partial<AppConfig> = {};\n\n if ('theme' in raw) {\n if (['light', 'dark', 'system'].includes(raw.theme)) {\n config.theme = raw.theme;\n } else {\n console.error(\n `Warning: Invalid theme value \"${raw.theme}\", using default`\n );\n }\n }\n\n if ('diff-view' in raw) {\n if (['split', 'unified'].includes(raw['diff-view'])) {\n config.diffView = raw['diff-view'];\n } else {\n console.error(\n `Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`\n );\n }\n }\n\n if ('font-size' in raw && typeof raw['font-size'] === 'number') {\n config.fontSize = raw['font-size'];\n }\n\n if ('output-format' in raw && typeof raw['output-format'] === 'string') {\n config.outputFormat = raw['output-format'];\n }\n\n if ('ignore' in raw && Array.isArray(raw.ignore)) {\n config.ignore = raw.ignore.filter(\n (item: unknown) => typeof item === 'string'\n );\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n config.categories = raw.categories.filter(\n (cat: unknown): cat is { name: string; description: string; color: string } =>\n cat !== null &&\n typeof cat === 'object' &&\n typeof (cat as Record<string, unknown>).name === 'string' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n }\n\n if (\n 'default-diff-args' in raw &&\n typeof raw['default-diff-args'] === 'string'\n ) {\n config.defaultDiffArgs = raw['default-diff-args'];\n }\n\n if ('show-untracked' in raw && typeof raw['show-untracked'] === 'boolean') {\n config.showUntracked = raw['show-untracked'];\n config.showUntrackedExplicit = true;\n }\n\n if ('word-wrap' in raw && typeof raw['word-wrap'] === 'boolean') {\n config.wordWrap = raw['word-wrap'];\n }\n\n if ('max-files' in raw && typeof raw['max-files'] === 'number') {\n config.maxFiles = raw['max-files'] >= 0 ? raw['max-files'] : defaults.maxFiles;\n }\n\n if ('max-total-lines' in raw && typeof raw['max-total-lines'] === 'number') {\n config.maxTotalLines = raw['max-total-lines'] >= 0 ? raw['max-total-lines'] : defaults.maxTotalLines;\n }\n\n if (\n 'output-file' in raw &&\n typeof raw['output-file'] === 'string' &&\n raw['output-file'].length > 0\n ) {\n config.outputFile = raw['output-file'];\n }\n\n return config;\n}\n\nfunction mergeConfig(base: AppConfig, override: Partial<AppConfig>): AppConfig {\n return {\n ...base,\n ...override,\n // Arrays are replaced, not merged\n ignore: override.ignore !== undefined ? override.ignore : base.ignore,\n categories:\n override.categories !== undefined ? override.categories : base.categories,\n };\n}\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execAsync = promisify(exec);\n\n/**\n * Compute payload statistics and check against configured thresholds.\n * A maxFiles or maxTotalLines value of 0 disables that guard.\n */\nexport function computePayloadStats(\n fileCount: number,\n totalLines: number,\n config: AppConfig\n): PayloadStats {\n const maxFiles = config.maxFiles;\n const maxTotalLines = config.maxTotalLines;\n const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;\n const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;\n return {\n fileCount,\n totalLines,\n exceedsFiles,\n exceedsLines,\n exceedsAny: exceedsFiles || exceedsLines,\n };\n}\n\n/**\n * Count total diff lines across all files and hunks.\n */\nexport function countTotalLines(files: DiffFile[]): number {\n let total = 0;\n for (const file of files) {\n for (const hunk of file.hunks) {\n total += hunk.lines.length;\n }\n }\n return total;\n}\n\n/**\n * Get git diff stats cheaply using --numstat (avoids full diff parsing).\n * Each output line is \"added\\tremoved\\tfilename\".\n * Returns file count and total changed lines (added + removed).\n */\nexport async function getGitDiffStats(\n args: string[],\n repoRoot: string\n): Promise<{ fileCount: number; totalLines: number }> {\n try {\n const { stdout } = await execAsync(`git diff --numstat ${args.join(' ')}`, {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 15000,\n cwd: repoRoot,\n });\n\n let fileCount = 0;\n let totalLines = 0;\n\n for (const line of stdout.trim().split('\\n')) {\n if (!line) continue;\n const parts = line.split('\\t');\n if (parts.length < 3) continue;\n\n fileCount++;\n // Binary files show '-' for added/removed\n const added = parts[0] === '-' ? 0 : parseInt(parts[0], 10);\n const removed = parts[1] === '-' ? 0 : parseInt(parts[1], 10);\n totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);\n }\n\n return { fileCount, totalLines };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);\n } else {\n console.error('[payload-sizing] Failed to get git diff stats: unknown error');\n }\n // Return zeros so the guard does not block on failure\n return { fileCount: 0, totalLines: 0 };\n }\n}\n","// src/main/fs-utils.ts\n// Filesystem utility functions for the main process.\n\nimport { accessSync, constants as fsConstants } from 'fs';\nimport { dirname } from 'path';\n\n/**\n * Check if a file's parent directory is writable.\n * Returns true if the directory exists and the process has write permission,\n * false otherwise (including non-existent directories).\n */\nexport function checkWritability(filePath: string): boolean {\n try {\n const dir = dirname(filePath);\n accessSync(dir, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * File-type detection utilities.\n *\n * NOTE: This file is intentionally duplicated in packages/react/src/utils/file-type-utils.ts.\n * @self-review/core has Node-only dependencies, so @self-review/react cannot safely import\n * from this package. Both copies must be kept in sync.\n */\n\nconst RASTER_IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.ico', '.bmp']);\nconst MARKDOWN_EXTENSIONS = new Set(['.md', '.markdown']);\nconst HTML_EXTENSIONS = new Set(['.html', '.htm']);\n\nexport type RenderedTextMode = 'markdown' | 'html';\n\nfunction getExtension(filePath: string): string {\n const lastDot = filePath.lastIndexOf('.');\n if (lastDot === -1 || lastDot === filePath.length - 1) return '';\n return filePath.slice(lastDot).toLowerCase();\n}\n\nexport function isPreviewableImage(filePath: string): boolean {\n return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isPreviewableSvg(filePath: string): boolean {\n return getExtension(filePath) === '.svg';\n}\n\nexport function isMarkdownFile(filePath: string): boolean {\n return MARKDOWN_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isHtmlFile(filePath: string): boolean {\n return HTML_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function getRenderedTextMode(filePath: string): RenderedTextMode | null {\n if (isMarkdownFile(filePath)) return 'markdown';\n if (isHtmlFile(filePath)) return 'html';\n return null;\n}\n\nexport function isPreviewableRenderedText(filePath: string): boolean {\n return getRenderedTextMode(filePath) !== null;\n}\n\nexport function getLanguageFromPath(filePath: string): string {\n const ext = filePath.split('.').pop()?.toLowerCase() || '';\n const langMap: Record<string, string> = {\n ts: 'typescript',\n tsx: 'tsx',\n js: 'javascript',\n jsx: 'jsx',\n py: 'python',\n css: 'css',\n json: 'json',\n md: 'markdown',\n markdown: 'markdown',\n sh: 'bash',\n bash: 'bash',\n yml: 'yaml',\n yaml: 'yaml',\n java: 'java',\n go: 'go',\n rs: 'rust',\n sql: 'sql',\n html: 'markup',\n htm: 'markup',\n xml: 'markup',\n rb: 'ruby',\n php: 'php',\n twig: 'twig',\n c: 'c',\n cpp: 'cpp',\n h: 'c',\n hpp: 'cpp',\n // Config and data formats\n ini: 'ini',\n toml: 'toml',\n csv: 'csv',\n diff: 'diff',\n patch: 'diff',\n // Web and infrastructure\n scss: 'scss',\n sass: 'sass',\n graphql: 'graphql',\n gql: 'graphql',\n conf: 'nginx',\n // Database\n mongodb: 'mongodb',\n // Tooling\n makefile: 'makefile',\n mk: 'makefile',\n mak: 'makefile',\n vim: 'vim',\n vimrc: 'vim',\n };\n\n // Check for special filenames without extensions\n const filename = filePath.split('/').pop()?.toLowerCase() || '';\n if (filename === 'dockerfile' || filename.startsWith('dockerfile.')) {\n return 'docker';\n }\n if (filename === 'makefile' || filename.startsWith('makefile.')) {\n return 'makefile';\n }\n if (filename.startsWith('.git')) {\n return 'git';\n }\n if (filename === '.vimrc' || filename.startsWith('.vim')) {\n return 'vim';\n }\n\n return langMap[ext] || 'plaintext';\n}\n"],"mappings":";AAKO,SAAS,UAAU,SAA6B;AACrD,MAAI,CAAC,QAAQ,KAAK,GAAG;AACnB,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,QAAQ,QAAQ,MAAM,IAAI;AAChC,QAAM,QAAoB,CAAC;AAC3B,MAAI,cAAwC;AAC5C,MAAI,cAAwC;AAC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;AAAA,IACH,KAAK;AAAA;AAAA,IAEL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA;AAAA,IAEP,MAAM;AAAA,IACN,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA;AAAA,IAEN,SAAS;AAAA;AAAA,IAET,UAAU;AAAA,IACV,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,OAAO;AAAA,EACT;AAGA,QAAM,WAAW,SAAS,MAAM,GAAG,EAAE,IAAI,GAAG,YAAY,KAAK;AAC7D,MAAI,aAAa,gBAAgB,SAAS,WAAW,aAAa,GAAG;AACnE,WAAO;AAAA,EACT;AACA,MAAI,aAAa,cAAc,SAAS,WAAW,WAAW,GAAG;AAC/D,WAAO;AAAA,EACT;AACA,MAAI,SAAS,WAAW,MAAM,GAAG;AAC/B,WAAO;AAAA,EACT;AACA,MAAI,aAAa,YAAY,SAAS,WAAW,MAAM,GAAG;AACxD,WAAO;AAAA,EACT;AAEA,SAAO,QAAQ,GAAG,KAAK;AACzB;","names":["path","readFileSync","join","dirname","join","dirname","readFileSync","existsSync","join","path","exec","promisify","execAsync","dirname"]}
1
+ {"version":3,"sources":["../src/diff-parser.ts","../src/xml-serializer.ts","../src/xml-parser.ts","../src/git.ts","../src/synthetic-diff.ts","../src/directory-scanner.ts","../src/ignore-filter.ts","../src/config.ts","../src/payload-sizing.ts","../src/fs-utils.ts","../src/file-type-utils.ts"],"sourcesContent":["// src/main/diff-parser.ts\n// Parse unified diff output into DiffFile[]\n\nimport { DiffFile, DiffHunk, ChangeType } from './types';\n\nexport function parseDiff(rawDiff: string): DiffFile[] {\n if (!rawDiff.trim()) {\n return [];\n }\n\n const lines = rawDiff.split('\\n');\n const files: DiffFile[] = [];\n let currentFile: Partial<DiffFile> | null = null;\n let currentHunk: Partial<DiffHunk> | null = null;\n let oldLineNumber = 0;\n let newLineNumber = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Start of a new file\n if (line.startsWith('diff --git ')) {\n // Flush the pending hunk into the current file before saving\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n currentHunk = null;\n }\n\n // Save previous file if exists and has actual changes\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n // Extract paths from \"diff --git a/<old> b/<new>\" as fallback\n // for binary files that lack --- / +++ lines\n const gitPaths = parseGitDiffHeader(line);\n\n // Initialize new file\n currentFile = {\n oldPath: gitPaths.oldPath,\n newPath: gitPaths.newPath,\n changeType: 'modified' as ChangeType,\n isBinary: false,\n hunks: [],\n };\n currentHunk = null;\n continue;\n }\n\n if (!currentFile) continue;\n\n // Detect file mode changes\n if (line.startsWith('new file mode')) {\n currentFile.changeType = 'added';\n continue;\n }\n\n if (line.startsWith('deleted file mode')) {\n currentFile.changeType = 'deleted';\n continue;\n }\n\n if (line.startsWith('rename from ')) {\n currentFile.changeType = 'renamed';\n continue;\n }\n\n // Parse old file path\n if (line.startsWith('--- ')) {\n const path = line.substring(4);\n currentFile.oldPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Parse new file path\n if (line.startsWith('+++ ')) {\n const path = line.substring(4);\n currentFile.newPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Detect binary files\n if (line.startsWith('Binary files ')) {\n currentFile.isBinary = true;\n continue;\n }\n\n // Parse hunk header\n if (line.startsWith('@@')) {\n // Save previous hunk if exists\n if (currentHunk && currentHunk.header) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n\n // Parse hunk header: @@ -oldStart,oldLines +newStart,newLines @@ context\n const match = line.match(\n /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(.*)$/\n );\n if (match) {\n const oldStart = parseInt(match[1], 10);\n const oldLines = match[2] ? parseInt(match[2], 10) : 1;\n const newStart = parseInt(match[3], 10);\n const newLines = match[4] ? parseInt(match[4], 10) : 1;\n const _context = match[5];\n\n currentHunk = {\n header: line,\n oldStart,\n oldLines,\n newStart,\n newLines,\n lines: [],\n };\n\n oldLineNumber = oldStart;\n newLineNumber = newStart;\n }\n continue;\n }\n\n // Parse diff lines (must have a current hunk)\n if (currentHunk && currentHunk.lines) {\n if (line.startsWith('+')) {\n // Addition\n currentHunk.lines.push({\n type: 'addition',\n oldLineNumber: null,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n newLineNumber++;\n } else if (line.startsWith('-')) {\n // Deletion\n currentHunk.lines.push({\n type: 'deletion',\n oldLineNumber: oldLineNumber,\n newLineNumber: null,\n content: line.substring(1),\n });\n oldLineNumber++;\n } else if (line.startsWith(' ')) {\n // Context line\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n oldLineNumber++;\n newLineNumber++;\n } else if (line.startsWith('\\\\')) {\n // \"\\" - ignore\n continue;\n } else {\n // Some other line (could be empty or malformed), treat as context\n if (currentHunk.lines.length > 0) {\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line,\n });\n oldLineNumber++;\n newLineNumber++;\n }\n }\n }\n }\n\n // Save the last hunk and file\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n return files;\n}\n\nfunction stripPrefix(path: string): string {\n // Remove single-character prefix (a/, b/, c/, i/, w/, etc.)\n // Git uses a/b by default, but mnemonicPrefix uses c/i/w/o\n if (path.length > 2 && path[1] === '/') {\n return path.substring(2);\n }\n return path;\n}\n\nfunction parseGitDiffHeader(line: string): {\n oldPath: string;\n newPath: string;\n} {\n // Format: \"diff --git a/<old> b/<new>\"\n // With diff.mnemonicPrefix, git uses i/ w/ c/ o/ instead of a/ b/.\n // Paths may contain spaces, so we find the \" X/\" separator where X is a\n // single-letter prefix.\n const withoutPrefix = line.substring('diff --git '.length);\n\n // Find \" X/\" — the boundary between old and new paths.\n // Try common prefixes: b/ (default), w/ i/ c/ o/ (mnemonic)\n let bIdx = -1;\n for (const prefix of [' b/', ' w/', ' i/', ' c/', ' o/']) {\n bIdx = withoutPrefix.indexOf(prefix);\n if (bIdx !== -1) break;\n }\n\n if (bIdx === -1) {\n return { oldPath: '', newPath: '' };\n }\n\n const oldPath = stripPrefix(withoutPrefix.substring(0, bIdx));\n const newPath = stripPrefix(withoutPrefix.substring(bIdx + 1));\n return { oldPath, newPath };\n}\n","// src/main/xml-serializer.ts\n// Serialize ReviewState to XML and validate against XSD\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { ReviewState, FileReviewState, ReviewComment } 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 copies listed in AGENTS.md;\n// the sync test in xml-serializer.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:v2\"\n targetNamespace=\"urn:self-review:v2\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review XML Schema v2\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\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\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: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: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: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:schema>`;\n\nfunction extFromMediaType(mediaType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\nfunction writeAttachments(state: ReviewState, outputFilePath: string): ReviewState {\n const assetDir = path.join(path.dirname(outputFilePath), '.self-review-assets');\n let hasAttachments = false;\n\n const updatedFiles = state.files.map(file => ({\n ...file,\n comments: file.comments.map(comment => {\n if (!comment.attachments?.length) return comment;\n\n const updatedAttachments = comment.attachments.map((att, index) => {\n if (!att.data) return att;\n hasAttachments = true;\n\n const ext = extFromMediaType(att.mediaType);\n const fileName = `${comment.id}-${index}.${ext}`;\n const relativePath = `.self-review-assets/${fileName}`;\n\n if (!fs.existsSync(assetDir)) {\n fs.mkdirSync(assetDir, { recursive: true });\n }\n fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));\n\n return { ...att, fileName: relativePath, data: undefined };\n });\n\n return { ...comment, attachments: updatedAttachments };\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-v2.xsd', contents: XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const errors = validationResult.errors || [];\n console.error('XML validation failed:');\n errors.forEach((err: unknown) => console.error(` ${err}`));\n throw new Error('Generated XML does not conform to schema');\n }\n } catch (error) {\n // Re-throw if it's a schema validation failure (our own throw above)\n if (error instanceof Error && error.message === 'Generated XML does not conform to schema') {\n throw error;\n }\n // Infrastructure failure (e.g. WASM load): log warning and return XML anyway\n if (error instanceof Error) {\n console.error(`[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`);\n } else {\n console.error('[main] XML validation infrastructure failed - emitting XML without validation');\n }\n return xml;\n }\n\n return xml;\n}\n\nfunction buildSourceAttributes(state: ReviewState): string {\n const source = state.source;\n if (source.type === 'git') {\n return ` git-diff-args=\"${escapeXml(source.gitDiffArgs)}\" repository=\"${escapeXml(source.repository)}\"`;\n }\n if (source.type === 'directory' || source.type === 'file') {\n return ` source-path=\"${escapeXml(source.sourcePath)}\"`;\n }\n // welcome mode: no source attributes\n return '';\n}\n\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 lines.push(\n `<review xmlns=\"urn:self-review:v2\" timestamp=\"${escapeXml(state.timestamp)}\"${sourceAttrs}>`\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 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 if (comment.attachments?.length) {\n for (const att of comment.attachments) {\n lines.push(` <attachment path=\"${escapeXml(att.fileName)}\" media-type=\"${escapeXml(att.mediaType)}\" />`);\n }\n }\n\n // Closing tag\n lines.push(' </comment>');\n\n return lines;\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\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} from './types';\n\nconst SEVERITY_VALUES: readonly CommentSeverity[] = ['critical', 'major', 'minor', 'info'];\nconst CONFIDENCE_VALUES: readonly CommentConfidence[] = ['high', 'medium', 'low'];\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\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 });\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 = Array.isArray(review.file)\n ? review.file\n : review.file\n ? [review.file]\n : [];\n\n for (const file of files) {\n const filePath = file['@_path'];\n if (!filePath) continue;\n\n if (parseViewed(file['@_viewed'])) {\n viewedFiles.push(String(filePath));\n }\n\n // Handle comments array\n const fileComments = Array.isArray(file.comment)\n ? file.comment\n : file.comment\n ? [file.comment]\n : [];\n\n for (const comment of fileComments) {\n const reviewComment: ReviewComment = {\n id: generateId(),\n filePath,\n lineRange: parseLineRange(comment),\n body: comment.body || '',\n category: 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 };\n\n // Parse attachments\n const commentAttachments = Array.isArray(comment.attachment)\n ? comment.attachment\n : comment.attachment\n ? [comment.attachment]\n : [];\n\n if (commentAttachments.length > 0) {\n reviewComment.attachments = commentAttachments.map(\n (att: Record<string, unknown>, i: number) => ({\n id: `${reviewComment.id}-att-${i}`,\n fileName: String(att['@_path'] || ''),\n mediaType: String(att['@_media-type'] || 'image/png'),\n })\n );\n }\n\n comments.push(reviewComment);\n }\n }\n\n return { comments, viewedFiles, gitDiffArgs, source };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error parsing XML: ${error.message}`);\n } else {\n console.error('Error parsing XML: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Read an enumerated attribute, dropping values the schema does not define.\n *\n * An unrecognised value becomes undefined rather than being passed through:\n * undefined is the fail-safe reading (below every threshold floor), and it\n * keeps a resumed review serializable, since the serializer validates its\n * output against the XSD before writing.\n */\nfunction parseEnumAttribute<T extends string>(\n raw: unknown,\n allowed: readonly T[]\n): T | undefined {\n if (raw === undefined || raw === null) return undefined;\n const value = String(raw);\n return allowed.includes(value as T) ? (value as T) : undefined;\n}\n\n/**\n * Read the `viewed` attribute of a <file> element.\n *\n * Anything other than an explicit true reads as not viewed: the attribute is\n * optional, and treating an unknown value as \"already reviewed\" would silently\n * hide files from the resumed review.\n */\nfunction parseViewed(raw: unknown): boolean {\n return raw === true || String(raw) === 'true';\n}\n\nfunction parseSource(review: Record<string, unknown>): DiffSource {\n const sourcePath = review['@_source-path'];\n if (sourcePath) {\n return { type: 'directory', sourcePath: String(sourcePath) };\n }\n\n const gitDiffArgs = review['@_git-diff-args'];\n const repository = review['@_repository'];\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: String(gitDiffArgs || ''),\n repository: String(repository || ''),\n };\n }\n\n return { type: 'welcome' };\n}\n\nfunction parseLineRange(comment: Record<string, unknown>): LineRange | null {\n const hasOld =\n comment['@_old-line-start'] !== undefined &&\n comment['@_old-line-end'] !== undefined;\n const hasNew =\n comment['@_new-line-start'] !== undefined &&\n comment['@_new-line-end'] !== undefined;\n\n if (hasOld) {\n return {\n side: 'old',\n start: parseInt(String(comment['@_old-line-start']), 10),\n end: parseInt(String(comment['@_old-line-end']), 10),\n };\n }\n\n if (hasNew) {\n return {\n side: 'new',\n start: parseInt(String(comment['@_new-line-start']), 10),\n end: parseInt(String(comment['@_new-line-end']), 10),\n };\n }\n\n return null; // File-level comment\n}\n\nfunction parseSuggestion(comment: Record<string, unknown>): Suggestion | null {\n if (!comment.suggestion) {\n return null;\n }\n\n const suggestion = comment.suggestion as Record<string, unknown>;\n return {\n originalCode: String(suggestion['original-code'] || ''),\n proposedCode: String(suggestion['proposed-code'] || ''),\n };\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// src/main/git.ts\n// Git command execution\n\nimport { execSync, exec } from 'child_process';\nimport { promisify } from 'util';\nimport { generateSyntheticDiffs } from './synthetic-diff';\n\nconst execAsync = promisify(exec);\n\nexport function runGitDiff(args: string[]): string {\n try {\n // Check if git is available\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n // Check if we're in a git repository\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n\n // Run git diff with the provided arguments\n const result = execSync(`git diff ${args.join(' ')}`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large diffs\n });\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function getRepoRoot(): string {\n try {\n const result = execSync('git rev-parse --show-toplevel', {\n encoding: 'utf-8',\n });\n return result.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Lightweight sync validation - checks if git is available and we're in a repo.\n * Called BEFORE Electron initialization for early exit path.\n */\nexport function validateGitAvailable(): void {\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n}\n\n/**\n * Async version of getRepoRoot - called AFTER app.whenReady().\n */\nexport async function getRepoRootAsync(cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync('git rev-parse --show-toplevel', {\n timeout: 10000, // 10 second timeout\n cwd,\n });\n return stdout.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Async version of runGitDiff - called AFTER app.whenReady().\n * Uses timeout to prevent hanging in CI environments.\n */\nexport async function runGitDiffAsync(args: string[], cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`git diff ${args.join(' ')}`, {\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer\n timeout: 30000, // 30 second timeout\n cwd,\n });\n return stdout;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Get list of untracked files (respects .gitignore).\n */\nexport async function getUntrackedFilesAsync(cwd?: string): Promise<string[]> {\n try {\n const { stdout } = await execAsync(\n 'git ls-files --others --exclude-standard',\n {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 10000,\n cwd,\n }\n );\n return stdout\n .trim()\n .split('\\n')\n .filter(line => line.length > 0);\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Warning: Failed to list untracked files: ${error.message}`\n );\n } else {\n console.error('Warning: Failed to list untracked files: unknown error');\n }\n return [];\n }\n}\n\n/**\n * Generate synthetic unified diffs for untracked files so they can be\n * parsed by the existing diff parser.\n *\n * Delegates to the reusable generateSyntheticDiffs module.\n */\nexport function generateUntrackedDiffs(\n paths: string[],\n repoRoot: string\n): string {\n return generateSyntheticDiffs(paths, repoRoot);\n}\n","// src/main/synthetic-diff.ts\n// Generates synthetic unified diffs for files that aren't tracked by git.\n// Reusable by both git untracked file handling and directory-based scanning.\n\nimport { readFileSync } from 'fs';\n\n/**\n * Generate synthetic unified diffs for a list of file paths so they can be\n * parsed by the existing diff parser. Each file is treated as a new addition.\n *\n * @param paths - Relative file paths (e.g. \"src/foo.ts\")\n * @param rootDir - Absolute path to the root directory containing the files\n * @returns A unified diff string covering all provided files\n */\nexport function generateSyntheticDiffs(\n paths: string[],\n rootDir: string\n): string {\n const diffs: string[] = [];\n\n for (const filePath of paths) {\n const fullPath = `${rootDir}/${filePath}`;\n let content: Buffer;\n try {\n content = readFileSync(fullPath);\n } catch {\n // File may have been deleted between listing and reading\n continue;\n }\n\n // Detect binary files by checking for null bytes in the first 8KB\n const sample = content.subarray(0, 8192);\n const isBinary = sample.includes(0);\n\n if (isBinary) {\n diffs.push(\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `Binary files /dev/null and b/${filePath} differ`\n );\n continue;\n }\n\n const text = content.toString('utf-8');\n const lines = text.split('\\n');\n\n // Remove trailing empty string from split if file ends with newline\n if (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n\n const lineCount = lines.length;\n const addedLines = lines.map(line => `+${line}`).join('\\n');\n\n let diff =\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `--- /dev/null\\n` +\n `+++ b/${filePath}\\n` +\n `@@ -0,0 +1,${lineCount} @@\\n` +\n addedLines;\n\n // Indicate missing newline at end of file\n if (text.length > 0 && !text.endsWith('\\n')) {\n diff += '\\n\\\';\n }\n\n diffs.push(diff);\n }\n\n return diffs.join('\\n');\n}\n","// src/main/directory-scanner.ts\n// Recursively scans a directory and produces DiffFile[] treating all files as new additions.\n\nimport { readdir, stat } from 'fs/promises';\nimport { join, relative, basename, dirname } from 'path';\nimport { DiffFile } from './types';\nimport { generateSyntheticDiffs } from './synthetic-diff';\nimport { parseDiff } from './diff-parser';\nimport { createIgnoreFilter } from './ignore-filter';\n\n/**\n * Recursively scan a directory and return DiffFile[] with every file\n * treated as a new addition (changeType: 'added').\n *\n * @param directoryPath - Absolute path to the directory to scan\n * @param ignorePatterns - Optional gitignore-compatible patterns to exclude files\n * @returns Parsed DiffFile array for all files in the directory\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = []\n): Promise<DiffFile[]> {\n // Verify the path is a directory\n try {\n const dirStat = await stat(directoryPath);\n if (!dirStat.isDirectory()) {\n console.error(\n `Error: \"${directoryPath}\" is not a directory`\n );\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error accessing directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error accessing directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n const filePaths: string[] = [];\n\n try {\n const entries = await readdir(directoryPath, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n\n // Build the full path from the entry's parentPath (or path) and name\n const parentDir = entry.parentPath ?? entry.path;\n const fullPath = join(parentDir, entry.name);\n const relativePath = relative(directoryPath, fullPath);\n filePaths.push(relativePath);\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error reading directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error reading directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n // Sort for deterministic output\n filePaths.sort();\n\n // Apply ignore patterns\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredPaths = filePaths.filter(p => shouldKeep(p));\n\n if (filteredPaths.length === 0) {\n return [];\n }\n\n const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);\n return parseDiff(diffText);\n}\n\n/**\n * Scan a single file and return DiffFile[] with the file treated as a new addition.\n *\n * @param filePath - Absolute path to the file to scan\n * @returns Parsed DiffFile array (single element)\n */\nexport async function scanFile(filePath: string): Promise<DiffFile[]> {\n try {\n const fileStat = await stat(filePath);\n if (!fileStat.isFile()) {\n console.error(`Error: \"${filePath}\" is not a file`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing file \"${filePath}\": ${error.message}`);\n } else {\n console.error(`Error accessing file \"${filePath}\": unknown error`);\n }\n return [];\n }\n\n const fileName = basename(filePath);\n const rootDir = dirname(filePath);\n const diffText = generateSyntheticDiffs([fileName], rootDir);\n return parseDiff(diffText);\n}\n","// src/main/ignore-filter.ts\n// Gitignore-compatible file path filtering using the `ignore` package.\n\nimport ignore from 'ignore';\n\n/**\n * Create a filter function from gitignore-compatible patterns.\n *\n * @param patterns - Array of gitignore-compatible glob patterns\n * @returns A predicate that returns `true` if the path should be kept (not ignored)\n */\nexport function createIgnoreFilter(\n patterns: string[]\n): (path: string) => boolean {\n if (patterns.length === 0) return () => true;\n const ig = ignore().add(patterns);\n return (filePath: string) => !ig.ignores(filePath);\n}\n","// src/main/config.ts\n// YAML configuration loading and merging\n\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { parse as parseYaml } from 'yaml';\nimport { AppConfig } from './types';\n\nconst defaults: AppConfig = {\n theme: 'system',\n diffView: 'split',\n fontSize: 14,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: [\n '.git',\n 'node_modules',\n 'vendor',\n '.vendor',\n '__pycache__',\n '.venv',\n 'venv',\n '.env',\n 'dist',\n 'build',\n '.next',\n '.nuxt',\n '.svelte-kit',\n 'target',\n '*.min.js',\n '*.min.css',\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Gemfile.lock',\n 'Cargo.lock',\n 'poetry.lock',\n 'go.sum',\n ],\n categories: [\n {\n name: 'question',\n description: 'Clarification needed — not necessarily a problem',\n color: '#805ad5',\n },\n {\n name: 'bug',\n description: 'Likely defect or incorrect behavior',\n color: '#e53e3e',\n },\n {\n name: 'security',\n description: 'Security vulnerability or concern',\n color: '#dd6b20',\n },\n {\n name: 'style',\n description: 'Code style, naming, or formatting issue',\n color: '#3182ce',\n },\n {\n name: 'task',\n description: 'Action item or follow-up task',\n color: '#38a169',\n },\n {\n name: 'nit',\n description: 'Minor nitpick, low priority',\n color: '#718096',\n },\n ],\n defaultDiffArgs: '',\n showUntracked: true,\n showUntrackedExplicit: false,\n wordWrap: true,\n maxFiles: 500,\n maxTotalLines: 100000,\n};\n\nexport function loadConfig(): AppConfig {\n let config = { ...defaults };\n\n // Load user-level config\n const userConfigPath = join(\n homedir(),\n '.config',\n 'self-review',\n 'config.yaml'\n );\n if (existsSync(userConfigPath)) {\n try {\n const userConfig = loadYamlConfig(userConfigPath);\n config = mergeConfig(config, userConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load user config from ${userConfigPath}: ${error}`\n );\n }\n }\n\n // Load project-level config\n const projectConfigPath = join(process.cwd(), '.self-review.yaml');\n if (existsSync(projectConfigPath)) {\n try {\n const projectConfig = loadYamlConfig(projectConfigPath);\n config = mergeConfig(config, projectConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load project config from ${projectConfigPath}: ${error}`\n );\n }\n }\n\n return config;\n}\n\nfunction loadYamlConfig(path: string): Partial<AppConfig> {\n const content = readFileSync(path, 'utf-8');\n const raw = parseYaml(content);\n\n // An empty file (or one containing only `null`) is a valid \"use defaults\" state.\n if (raw === null || raw === undefined) {\n return {};\n }\n\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error('Invalid YAML format');\n }\n\n // Map kebab-case keys to camelCase\n const config: Partial<AppConfig> = {};\n\n if ('theme' in raw) {\n if (['light', 'dark', 'system'].includes(raw.theme)) {\n config.theme = raw.theme;\n } else {\n console.error(\n `Warning: Invalid theme value \"${raw.theme}\", using default`\n );\n }\n }\n\n if ('diff-view' in raw) {\n if (['split', 'unified'].includes(raw['diff-view'])) {\n config.diffView = raw['diff-view'];\n } else {\n console.error(\n `Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`\n );\n }\n }\n\n if ('font-size' in raw && typeof raw['font-size'] === 'number') {\n config.fontSize = raw['font-size'];\n }\n\n if ('output-format' in raw && typeof raw['output-format'] === 'string') {\n config.outputFormat = raw['output-format'];\n }\n\n if ('ignore' in raw && Array.isArray(raw.ignore)) {\n config.ignore = raw.ignore.filter(\n (item: unknown) => typeof item === 'string'\n );\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n config.categories = raw.categories.filter(\n (cat: unknown): cat is { name: string; description: string; color: string } =>\n cat !== null &&\n typeof cat === 'object' &&\n typeof (cat as Record<string, unknown>).name === 'string' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n }\n\n if (\n 'default-diff-args' in raw &&\n typeof raw['default-diff-args'] === 'string'\n ) {\n config.defaultDiffArgs = raw['default-diff-args'];\n }\n\n if ('show-untracked' in raw && typeof raw['show-untracked'] === 'boolean') {\n config.showUntracked = raw['show-untracked'];\n config.showUntrackedExplicit = true;\n }\n\n if ('word-wrap' in raw && typeof raw['word-wrap'] === 'boolean') {\n config.wordWrap = raw['word-wrap'];\n }\n\n if ('max-files' in raw && typeof raw['max-files'] === 'number') {\n config.maxFiles = raw['max-files'] >= 0 ? raw['max-files'] : defaults.maxFiles;\n }\n\n if ('max-total-lines' in raw && typeof raw['max-total-lines'] === 'number') {\n config.maxTotalLines = raw['max-total-lines'] >= 0 ? raw['max-total-lines'] : defaults.maxTotalLines;\n }\n\n if (\n 'output-file' in raw &&\n typeof raw['output-file'] === 'string' &&\n raw['output-file'].length > 0\n ) {\n config.outputFile = raw['output-file'];\n }\n\n return config;\n}\n\nfunction mergeConfig(base: AppConfig, override: Partial<AppConfig>): AppConfig {\n return {\n ...base,\n ...override,\n // Arrays are replaced, not merged\n ignore: override.ignore !== undefined ? override.ignore : base.ignore,\n categories:\n override.categories !== undefined ? override.categories : base.categories,\n };\n}\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execAsync = promisify(exec);\n\n/**\n * Compute payload statistics and check against configured thresholds.\n * A maxFiles or maxTotalLines value of 0 disables that guard.\n */\nexport function computePayloadStats(\n fileCount: number,\n totalLines: number,\n config: AppConfig\n): PayloadStats {\n const maxFiles = config.maxFiles;\n const maxTotalLines = config.maxTotalLines;\n const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;\n const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;\n return {\n fileCount,\n totalLines,\n exceedsFiles,\n exceedsLines,\n exceedsAny: exceedsFiles || exceedsLines,\n };\n}\n\n/**\n * Count total diff lines across all files and hunks.\n */\nexport function countTotalLines(files: DiffFile[]): number {\n let total = 0;\n for (const file of files) {\n for (const hunk of file.hunks) {\n total += hunk.lines.length;\n }\n }\n return total;\n}\n\n/**\n * Get git diff stats cheaply using --numstat (avoids full diff parsing).\n * Each output line is \"added\\tremoved\\tfilename\".\n * Returns file count and total changed lines (added + removed).\n */\nexport async function getGitDiffStats(\n args: string[],\n repoRoot: string\n): Promise<{ fileCount: number; totalLines: number }> {\n try {\n const { stdout } = await execAsync(`git diff --numstat ${args.join(' ')}`, {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 15000,\n cwd: repoRoot,\n });\n\n let fileCount = 0;\n let totalLines = 0;\n\n for (const line of stdout.trim().split('\\n')) {\n if (!line) continue;\n const parts = line.split('\\t');\n if (parts.length < 3) continue;\n\n fileCount++;\n // Binary files show '-' for added/removed\n const added = parts[0] === '-' ? 0 : parseInt(parts[0], 10);\n const removed = parts[1] === '-' ? 0 : parseInt(parts[1], 10);\n totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);\n }\n\n return { fileCount, totalLines };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);\n } else {\n console.error('[payload-sizing] Failed to get git diff stats: unknown error');\n }\n // Return zeros so the guard does not block on failure\n return { fileCount: 0, totalLines: 0 };\n }\n}\n","// src/main/fs-utils.ts\n// Filesystem utility functions for the main process.\n\nimport { accessSync, constants as fsConstants } from 'fs';\nimport { dirname } from 'path';\n\n/**\n * Check if a file's parent directory is writable.\n * Returns true if the directory exists and the process has write permission,\n * false otherwise (including non-existent directories).\n */\nexport function checkWritability(filePath: string): boolean {\n try {\n const dir = dirname(filePath);\n accessSync(dir, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * File-type detection utilities.\n *\n * NOTE: This file is intentionally duplicated in packages/react/src/utils/file-type-utils.ts.\n * @self-review/core has Node-only dependencies, so @self-review/react cannot safely import\n * from this package. Both copies must be kept in sync.\n */\n\nconst RASTER_IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.ico', '.bmp']);\nconst MARKDOWN_EXTENSIONS = new Set(['.md', '.markdown']);\nconst HTML_EXTENSIONS = new Set(['.html', '.htm']);\n\nexport type RenderedTextMode = 'markdown' | 'html';\n\nfunction getExtension(filePath: string): string {\n const lastDot = filePath.lastIndexOf('.');\n if (lastDot === -1 || lastDot === filePath.length - 1) return '';\n return filePath.slice(lastDot).toLowerCase();\n}\n\nexport function isPreviewableImage(filePath: string): boolean {\n return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isPreviewableSvg(filePath: string): boolean {\n return getExtension(filePath) === '.svg';\n}\n\nexport function isMarkdownFile(filePath: string): boolean {\n return MARKDOWN_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isHtmlFile(filePath: string): boolean {\n return HTML_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function getRenderedTextMode(filePath: string): RenderedTextMode | null {\n if (isMarkdownFile(filePath)) return 'markdown';\n if (isHtmlFile(filePath)) return 'html';\n return null;\n}\n\nexport function isPreviewableRenderedText(filePath: string): boolean {\n return getRenderedTextMode(filePath) !== null;\n}\n\nexport function getLanguageFromPath(filePath: string): string {\n const ext = filePath.split('.').pop()?.toLowerCase() || '';\n const langMap: Record<string, string> = {\n ts: 'typescript',\n tsx: 'tsx',\n js: 'javascript',\n jsx: 'jsx',\n py: 'python',\n css: 'css',\n json: 'json',\n md: 'markdown',\n markdown: 'markdown',\n sh: 'bash',\n bash: 'bash',\n yml: 'yaml',\n yaml: 'yaml',\n java: 'java',\n go: 'go',\n rs: 'rust',\n sql: 'sql',\n html: 'markup',\n htm: 'markup',\n xml: 'markup',\n rb: 'ruby',\n php: 'php',\n twig: 'twig',\n c: 'c',\n cpp: 'cpp',\n h: 'c',\n hpp: 'cpp',\n // Config and data formats\n ini: 'ini',\n toml: 'toml',\n csv: 'csv',\n diff: 'diff',\n patch: 'diff',\n // Web and infrastructure\n scss: 'scss',\n sass: 'sass',\n graphql: 'graphql',\n gql: 'graphql',\n conf: 'nginx',\n // Database\n mongodb: 'mongodb',\n // Tooling\n makefile: 'makefile',\n mk: 'makefile',\n mak: 'makefile',\n vim: 'vim',\n vimrc: 'vim',\n };\n\n // Check for special filenames without extensions\n const filename = filePath.split('/').pop()?.toLowerCase() || '';\n if (filename === 'dockerfile' || filename.startsWith('dockerfile.')) {\n return 'docker';\n }\n if (filename === 'makefile' || filename.startsWith('makefile.')) {\n return 'makefile';\n }\n if (filename.startsWith('.git')) {\n return 'git';\n }\n if (filename === '.vimrc' || filename.startsWith('.vim')) {\n return 'vim';\n }\n\n return langMap[ext] || 'plaintext';\n}\n"],"mappings":";AAKO,SAAS,UAAU,SAA6B;AACrD,MAAI,CAAC,QAAQ,KAAK,GAAG;AACnB,WAAO,CAAC;AAAA,EACV;AA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AA,IACJ,UAAU;AAAA,IACV,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,KAAK;AAAA,IACL,MAAM;AAAA,IACN,MAAM;AAAA,IACN,IAAI;AAAA,IACJ,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,KAAK;AAAA,IACL,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,MAAM;AAAA,IACN,GAAG;AAAA,IACH,KAAK;AAAA,IACL,GAAG;AAAA,IACH,KAAK;AAAA;AAAA,IAEL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA;AAAA,IAEP,MAAM;AAAA,IACN,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA;AAAA,IAEN,SAAS;AAAA;AAAA,IAET,UAAU;AAAA,IACV,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,OAAO;AAAA,EACT;AAGA,QAAM,WAAW,SAAS,MAAM,GAAG,EAAE,IAAI,GAAG,YAAY,KAAK;AAC7D,MAAI,aAAa,gBAAgB,SAAS,WAAW,aAAa,GAAG;AACnE,WAAO;AAAA,EACT;AACA,MAAI,aAAa,cAAc,SAAS,WAAW,WAAW,GAAG;AAC/D,WAAO;AAAA,EACT;AACA,MAAI,SAAS,WAAW,MAAM,GAAG;AAC/B,WAAO;AAAA,EACT;AACA,MAAI,aAAa,YAAY,SAAS,WAAW,MAAM,GAAG;AACxD,WAAO;AAAA,EACT;AAEA,SAAO,QAAQ,GAAG,KAAK;AACzB;","names":["path","readFileSync","join","dirname","join","dirname","readFileSync","existsSync","join","path","exec","promisify","execAsync","dirname"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@self-review/core",
3
- "version": "1.39.1",
3
+ "version": "1.39.2",
4
4
  "description": "Core library for self-review: diff parsing, git operations, XML serialization, and configuration",
5
5
  "repository": {
6
6
  "type": "git",