@self-review/core 1.44.0 → 1.45.0
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 +13 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +23 -16
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/diff-parser.ts","../src/synthetic-diff.ts","../src/git.ts","../src/index.ts","../src/xml-serializer.ts","../src/xml-parser.ts","../src/guide-schema.ts","../src/guide-parser.ts","../src/forge-provider.ts","../src/directory-scanner.ts","../src/ignore-filter.ts","../src/config.ts","../src/payload-sizing.ts","../src/fs-utils.ts","../src/apply-suggestion.ts","../src/file-type-utils.ts","../src/github-provider.ts","../src/thread-mapper.ts","../src/gitlab-provider.ts","../src/materializer.ts","../src/review-handlers.ts","../src/git-diff-args.ts","../src/startup-mode.ts","../src/guide-loader.ts","../src/git-diff-loader.ts","../src/staged-untracked.ts","../src/remote-mode.ts","../src/fetch-comments.ts"],"sourcesContent":["// src/main/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 let hasModeChange = false;\n\n function flushFile(): void {\n if (\n currentFile &&\n (currentFile.oldPath || currentFile.newPath) &&\n (currentFile.isBinary ||\n currentFile.hunks!.length > 0 ||\n currentFile.changeType !== 'modified' ||\n hasModeChange)\n ) {\n files.push(currentFile as DiffFile);\n }\n }\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 flushFile();\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 hasModeChange = false;\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 currentFile.oldPath = '';\n continue;\n }\n\n if (line.startsWith('deleted file mode')) {\n currentFile.changeType = 'deleted';\n currentFile.newPath = '';\n continue;\n }\n\n if (line.startsWith('new mode ')) {\n hasModeChange = true;\n continue;\n }\n\n if (line.startsWith('rename from ')) {\n currentFile.changeType = 'renamed';\n currentFile.oldPath = decodeGitPath(line.substring('rename from '.length));\n continue;\n }\n\n if (line.startsWith('rename to ')) {\n currentFile.newPath = decodeGitPath(line.substring('rename to '.length));\n continue;\n }\n\n // Parse old file path\n if (!currentHunk && line.startsWith('--- ')) {\n const path = decodeGitPath(line.substring(4).split('\\t')[0]);\n currentFile.oldPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Parse new file path\n if (!currentHunk && line.startsWith('+++ ')) {\n const path = decodeGitPath(line.substring(4).split('\\t')[0]);\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(/@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(.*)$/);\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 flushFile();\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 decodeGitPath(path: string): string {\n if (!path.startsWith('\"') || !path.endsWith('\"')) return path;\n\n const escapes: Record<string, string> = {\n a: '\\x07',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t',\n v: '\\v',\n '\"': '\"',\n '\\\\': '\\\\',\n };\n return path.slice(1, -1).replace(/(?:\\\\[0-7]{1,3})+|\\\\[abfnrtv\"\\\\]/g, escape => {\n if (/^\\\\[0-7]/.test(escape)) {\n // Git quotes UTF-8 bytes as octal, so decode each run together.\n const bytes = escape\n .slice(1)\n .split('\\\\')\n .map(byte => parseInt(byte, 8));\n return Buffer.from(bytes).toString('utf8');\n }\n return escapes[escape[1]];\n });\n}\n\nfunction parseGitDiffHeader(line: string): {\n oldPath: string;\n newPath: string;\n} {\n const paths = line.substring('diff --git '.length);\n // Quoted paths are single C-style tokens, even when they contain spaces.\n const quotedOld = paths.match(/^(\"(?:\\\\.|[^\"\\\\])*\") (.+)$/);\n const quotedNew = paths.match(/^(.+) (\"(?:\\\\.|[^\"\\\\])*\")$/);\n const quoted = quotedOld || quotedNew;\n if (quoted) {\n return {\n oldPath: stripPrefix(decodeGitPath(quoted[1])),\n newPath: stripPrefix(decodeGitPath(quoted[2])),\n };\n }\n\n // Unquoted names can contain spaces. Prefer a boundary whose two paths\n // agree; rename headers supply the exact paths when they differ.\n const separators = [...paths.matchAll(/ [bwico]\\//g)];\n const boundary =\n separators.find(\n match =>\n stripPrefix(paths.substring(0, match.index)) ===\n stripPrefix(paths.substring(match.index! + 1))\n ) || separators[0];\n if (!boundary) return { oldPath: '', newPath: '' };\n\n return {\n oldPath: stripPrefix(paths.substring(0, boundary.index)),\n newPath: stripPrefix(paths.substring(boundary.index! + 1)),\n };\n}\n","// packages/core/src/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';\nimport { join } from 'path';\n\n// C-style escapes git emits for the characters that have one.\nconst C_STYLE_ESCAPES: Record<number, string> = {\n 0x07: '\\\\a',\n 0x08: '\\\\b',\n 0x09: '\\\\t',\n 0x0a: '\\\\n',\n 0x0b: '\\\\v',\n 0x0c: '\\\\f',\n 0x0d: '\\\\r',\n 0x22: '\\\\\"',\n 0x5c: '\\\\\\\\',\n};\n\nfunction needsQuoting(byte: number): boolean {\n return byte < 0x20 || byte >= 0x7f || byte === 0x22 || byte === 0x5c;\n}\n\n/**\n * Encode a path the way git writes it in diff headers. A plain path goes out\n * verbatim. Anything else becomes a double-quoted C-style token with control\n * characters, quotes, backslashes and non-ASCII UTF-8 bytes escaped.\n *\n * This inverts `decodeGitPath` in diff-parser.ts. Without it, a filename\n * containing a newline ends the header line mid-name and the parser recovers\n * a name no file on disk answers to.\n */\nexport function quoteGitPath(path: string): string {\n const bytes = Buffer.from(path, 'utf-8');\n if (!bytes.some(needsQuoting)) return path;\n\n let quoted = '\"';\n for (const byte of bytes) {\n const escape = C_STYLE_ESCAPES[byte];\n if (escape) {\n quoted += escape;\n } else if (byte < 0x20 || byte >= 0x7f) {\n quoted += `\\\\${byte.toString(8).padStart(3, '0')}`;\n } else {\n quoted += String.fromCharCode(byte);\n }\n }\n return `${quoted}\"`;\n}\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 - Literal relative file paths (e.g. \"src/foo.ts\"), resolved\n * against rootDir and never git-quoted on the way in\n * @param rootDir - Absolute path to the root directory the paths are relative to\n * @returns A unified diff string covering all provided files\n */\nexport function generateSyntheticDiffs(paths: string[], rootDir: string): string {\n const diffs: string[] = [];\n\n for (const filePath of paths) {\n const fullPath = join(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 // Git quotes the prefixed path as a whole (\"a/name\"), not the name alone.\n const oldHeaderPath = quoteGitPath(`a/${filePath}`);\n const newHeaderPath = quoteGitPath(`b/${filePath}`);\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 ${oldHeaderPath} ${newHeaderPath}\\n` +\n `new file mode 100644\\n` +\n `Binary files /dev/null and ${newHeaderPath} 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 ${oldHeaderPath} ${newHeaderPath}\\n` +\n `new file mode 100644\\n` +\n `--- /dev/null\\n` +\n `+++ ${newHeaderPath}\\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/git.ts\n// Git command execution\n\nimport { execSync, execFile, execFileSync } from 'child_process';\nimport { promisify } from 'util';\nimport { generateSyntheticDiffs } from './synthetic-diff';\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Strip only the single trailing newline git appends to command output.\n * A plain `.trim()` also eats leading/trailing whitespace that is part of\n * the actual path (e.g. a repository root with a trailing space), reporting\n * a path that does not exist on disk.\n */\nexport function stripTrailingNewline(text: string): string {\n return text.replace(/\\r?\\n$/, '');\n}\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('Error: not a git repository (or any parent up to mount point)');\n process.exit(1);\n }\n\n // Run git diff with the provided arguments\n const result = execFileSync('git', ['diff', ...args], {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large diffs\n });\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function getRepoRoot(): string {\n try {\n const result = execSync('git rev-parse --show-toplevel', {\n encoding: 'utf-8',\n });\n return stripTrailingNewline(result);\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('Error: not a git repository (or any parent up to mount point)');\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 execFileAsync('git', ['rev-parse', '--show-toplevel'], {\n timeout: 10000, // 10 second timeout\n cwd,\n });\n return stripTrailingNewline(stdout);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Async version of runGitDiff - called AFTER app.whenReady().\n * Uses timeout to prevent hanging in CI environments.\n */\nexport async function runGitDiffAsync(args: string[], cwd?: string): Promise<string> {\n try {\n const { stdout } = await execFileAsync('git', ['diff', ...args], {\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer\n timeout: 30000, // 30 second timeout\n cwd,\n });\n return stdout;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Read a blob from a git object spec (`<sha>:<path>`) as raw bytes.\n * Remote mode reads reviewed content at the fetched head SHA — a temporary\n * clone's working tree stays on the default branch and never reflects the\n * PR/MR head.\n */\nexport async function readGitBlobAsync(repoPath: string, spec: string): Promise<Buffer> {\n return await new Promise<Buffer>((resolve, reject) => {\n execFile(\n 'git',\n ['-C', repoPath, 'show', spec],\n { encoding: 'buffer', maxBuffer: 50 * 1024 * 1024, timeout: 30000 },\n (error, stdout) => {\n if (error) {\n reject(error);\n } else {\n resolve(stdout);\n }\n }\n );\n });\n}\n\n/**\n * Get list of untracked files (respects .gitignore).\n *\n * Pass the repository root. `git ls-files` reports paths relative to the\n * directory it runs in and lists that subtree only, while `git diff` reports\n * root-relative paths for the whole repository from anywhere inside it. Run\n * anywhere else and the names match neither the diff nor the root the files\n * are read from.\n *\n * `-z` keeps the names literal. NUL termination survives newlines in\n * filenames, and it turns off the C-style quoting git otherwise applies to\n * control characters and non-ASCII bytes.\n */\nexport async function getUntrackedFilesAsync(repoRoot?: string): Promise<string[]> {\n try {\n const { stdout } = await execFileAsync(\n 'git',\n ['ls-files', '--others', '--exclude-standard', '-z'],\n {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 10000,\n cwd: repoRoot,\n }\n );\n return stdout.split('\\0').filter(name => name.length > 0);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Warning: Failed to list untracked files: ${error.message}`);\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(paths: string[], repoRoot: string): string {\n return generateSyntheticDiffs(paths, repoRoot);\n}\n","// @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 ReviewGuide,\n GuideGroup,\n GuideFileEntry,\n ResolvedGuideGroup,\n ResolvedGuideFile,\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// Walkthrough guide schema\nexport { GUIDE_XSD_SCHEMA } from './guide-schema';\n\n// Walkthrough guide parsing and reconciliation\nexport { parseGuideXml, reconcileGuide, IMPLICIT_GUIDE_GROUP_NAME } from './guide-parser';\nexport type { GuideParseResult } from './guide-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// Forge providers (remote PR/MR conversation plane)\nexport { parseForgeUrl, ForgeCliUnavailableError } from './forge-provider';\nexport type {\n ForgeName,\n ForgeUrl,\n ForgeAnchorSide,\n ForgeThreadAnchor,\n ForgeThreadTurn,\n ForgeThread,\n FetchThreadsOptions,\n ForgeCommandResult,\n ForgeCommandRunner,\n ForgeProvider,\n} from './forge-provider';\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// Anchored suggestion application (writes a reviewed working file)\nexport { applySuggestion } from './apply-suggestion';\nexport type {\n ApplyRefusalReason,\n ApplySuggestionRequest,\n ApplySuggestionApplied,\n ApplySuggestionRefused,\n ApplySuggestionResult,\n} from './apply-suggestion';\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\n// GitHub forge provider (gh CLI backed)\nexport { createGitHubProvider } from './github-provider';\n\n// Forge thread → ReviewComment mapper (remote PR/MR fetch direction)\nexport { mapThreadsToReviewComments, REVIEW_LEVEL_FILE_PATH } from './thread-mapper';\n\n// GitLab forge provider (glab CLI backed)\nexport { createGitLabProvider } from './gitlab-provider';\n\n// Clone-aware diff materializer (remote PR/MR git plane)\nexport {\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n defaultGitRunner,\n} from './materializer';\nexport type { ExistingClone, MaterializeMode, MaterializeResult } from './materializer';\n\n// Review session orchestration (transport agnostic; each handler takes the\n// session it acts on and reads no module-scope state)\nexport {\n createReviewSession,\n preparePayload,\n getDiffLoad,\n loadImage,\n getFileHunks,\n getConfigLoad,\n submitReviewState,\n takeReviewState,\n readAttachment,\n getResumeLoad,\n expandContext,\n prepareDirectoryReview,\n commitReviewStart,\n resolveSourceBaseDir,\n resolveApplyDestination,\n applySuggestionForSession,\n} from './review-handlers';\nexport type { ReviewSession, ReviewStartResult } from './review-handlers';\n\n// Startup mode detection (git, directory, file, welcome)\nexport { determineMode } from './startup-mode';\n\n// Walkthrough guide sidecar discovery and tolerant loading\nexport { deriveGuidePath, resolveGuidePath, loadGuide } from './guide-loader';\n\n// Git diff loading, staged/untracked defaulting, and argument normalisation\nexport { loadGitDiffWithUntracked } from './git-diff-loader';\nexport type { LoadGitDiffOptions } from './git-diff-loader';\nexport { applyStagedUntrackedDefault } from './staged-untracked';\nexport { normalizeGitDiffArgs } from './git-diff-args';\n\n// Remote PR/MR session bootstrap (URL -> materialized git-mode inputs)\nexport {\n startRemoteSession,\n bootstrapRemoteDiff,\n mergeRemoteThreads,\n applyRemoteProvenance,\n computeRemoteDrift,\n} from './remote-mode';\nexport type { RemoteSession, RemoteSessionDeps, RemoteBootstrapResult } from './remote-mode';\n\n// Headless fetch-comments orchestrator\nexport { buildRemoteReviewState, runFetchComments } from './fetch-comments';\nexport type {\n FetchCommentsDeps,\n BuildRemoteReviewStateArgs,\n FetchCommentsOptions,\n} from './fetch-comments';\n","// src/main/xml-serializer.ts\n// Serialize ReviewState to XML and validate against XSD\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { ReviewState, FileReviewState, ReviewComment, Reply, Attachment } from './types';\nimport { validateXML } from 'xmllint-wasm';\n\n// Embed the XSD schema for validation.\n// This MUST stay byte-identical to the on-disk canonical copy\n// (.agents/skills/self-review-apply/assets/self-review-v3.xsd);\n// the sync test in xsd-schema.test.ts enforces it.\nexport const XSD_SCHEMA = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sr=\"urn:self-review:v3\"\n targetNamespace=\"urn:self-review:v3\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review XML Schema v3\n =========================\n Defines the output format for the self-review application.\n This schema is designed to be both machine-validated and\n fed to an LLM so it can understand the structure of review feedback.\n\n Key concepts:\n - A <review> contains one <file> per file in the diff.\n - A <file> contains zero or more <comment> elements.\n - A <comment> with no line attributes is a file-level comment.\n - A <comment> with old-line-start/old-line-end refers to lines\n in the pre-change version of the file (typically deleted lines).\n - A <comment> with new-line-start/new-line-end refers to lines\n in the post-change version of the file (added or context lines).\n - Exactly one pair (old-line-* or new-line-*) should be present\n for line-level comments. This constraint cannot be expressed in\n XSD 1.0 and is enforced by the application.\n - A <comment> may carry an ordered list of <reply> children, which\n are turns in a conversation about that comment.\n\n Changes from v1:\n - <comment> gained two optional attributes, severity and confidence,\n so an automated consumer can threshold on findings instead of\n applying all of them or none of them. See CommentType.\n\n Changes from v2:\n - <comment> gained an optional, unbounded <reply> child, so a finding\n and the responses to it form a single legible thread instead of a\n set of disconnected assertions. See ReplyType.\n\n Amended in place (still v3):\n - The review root gained optional remote-url, remote-base-sha,\n remote-head-sha and remote-forge attributes, and <comment> and\n <reply> gained an optional remote-id attribute, so a review taken\n against a remote pull/merge request records its provenance. Purely\n additive: a document carrying none of them is unchanged. See\n ReviewType.\n -->\n\n <!-- ===== Root element ===== -->\n\n <xs:element name=\"review\" type=\"sr:ReviewType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review output file. Contains one file element\n per file in the git diff, including files with no comments.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <!-- ===== Complex types ===== -->\n\n <xs:complexType name=\"ReviewType\">\n <xs:sequence>\n <xs:element name=\"file\" type=\"sr:FileType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the review was completed (window closed).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments that were passed to self-review on the CLI.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root where self-review was invoked.\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"source-path\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the directory being reviewed.\n Present only when reviewing a directory (non-git mode).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-url\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n URL of the remote pull/merge request this review was taken\n against. Example: \"https://github.com/owner/repo/pull/42\".\n Present only when reviewing a remote PR/MR.\n\n The remote-* attributes form a third source shape alongside\n git-diff-args/repository (local git diff) and source-path\n (directory review). The three shapes are mutually exclusive;\n XSD 1.0 cannot express that constraint, so it is enforced by\n the application.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-base-sha\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Commit SHA the remote diff was computed from (the base of the\n PR/MR at fetch time). Together with remote-head-sha it pins the\n review to the exact diff it was written against, so a consumer\n can detect drift when the remote branch moves.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-head-sha\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Commit SHA of the head of the remote PR/MR branch at fetch time.\n See remote-base-sha for how the pair supports drift detection.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-forge\" type=\"sr:RemoteForgeEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Which forge hosts the remote PR/MR. Names the id space of the\n remote-id attributes on comments and replies, and selects the\n API machinery a future posting feature would use.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileType\">\n <xs:annotation>\n <xs:documentation>\n Represents a single file in the diff. Files with no comments\n appear as empty elements. The path is relative to the repository root.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"comment\" type=\"sr:CommentType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root. For renamed files,\n this is the new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"change-type\" type=\"sr:ChangeTypeEnum\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n The type of change: added, modified, deleted, or renamed.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"viewed\" type=\"xs:boolean\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Whether the reviewer marked this file as reviewed.\n true = the reviewer looked at this file.\n false = the reviewer did not mark this file as viewed.\n This helps an AI agent distinguish \"reviewed with no comments\"\n from \"not yet reviewed.\"\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"CommentType\">\n <xs:annotation>\n <xs:documentation>\n A review comment. Three forms:\n\n 1. File-level comment: no line attributes present.\n Applies to the file as a whole.\n\n 2. Comment on new/added/context lines: new-line-start and\n new-line-end are present. These reference line numbers in the\n post-change version of the file.\n\n 3. Comment on old/deleted lines: old-line-start and old-line-end\n are present. These reference line numbers in the pre-change\n version of the file.\n\n For single-line comments, start and end are equal.\n Exactly one pair (old or new) should be present for line-level\n comments. Both pairs absent = file-level comment.\n\n The category child says what kind of finding this is. The severity\n and confidence attributes say how much weight to put on it: severity\n is how consequential the finding is if it is real, confidence is how\n sure the author is that it is real. They are independent, and an\n automated consumer is expected to threshold on both.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The comment text. May contain markdown formatting.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"category\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n Required category tag for this comment (e.g., \"bug\", \"style\",\n \"nit\", \"question\", \"security\"). Categories are defined in the\n project-level .self-review.yaml configuration. Every comment\n must have a category to help AI agents prioritize and triage\n feedback.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"suggestion\" type=\"sr:SuggestionType\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Optional code replacement proposal. When present, the AI agent\n should replace the original-code with the proposed-code at the\n referenced line range.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment. The path attribute references an image file\n stored in the .self-review-assets/ directory alongside the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"reply\" type=\"sr:ReplyType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional ordered list of replies to this comment. The comment\n itself is the root of the thread; each reply is a later turn in\n the conversation about it.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"old-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the pre-change (old) version of the file.\n Use for comments on deleted lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"old-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the pre-change (old) version.\n Must be >= old-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the post-change (new) version of the file.\n Use for comments on added or context (unchanged) lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the post-change (new) version.\n Must be >= new-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"author\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The author of this comment. When present, indicates the comment\n was generated by a bot or LLM (e.g., \"Claude Sonnet 4.6\").\n When absent, the comment is assumed to be authored by the human\n reviewer.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"severity\" type=\"sr:SeverityEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n How consequential this finding is if it turns out to be real.\n Judge the impact of the problem, not how confident you are that\n the problem exists, and not how much work the fix is.\n\n This attribute has no schema default on purpose. When it is\n absent, a consumer must treat the comment as falling below any\n severity floor it applies, i.e. absent never satisfies a\n threshold. Comments written by a human in the self-review UI\n normally carry no severity.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"confidence\" type=\"sr:ConfidenceEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n How sure the author is that this finding is real, i.e. that it\n describes an actual defect in the code as written rather than a\n hypothetical one.\n\n Confidence is about the evidence, not about how strongly the\n comment is worded. A finding whose argument depends on a\n constraint that is not visible in the diff, on a caller that was\n not read, or on a failure scenario that was imagined rather than\n traced, is low confidence however plausible its prose sounds.\n LLM reviewers systematically overstate certainty here; a\n consumer thresholding on this attribute is relying on it being\n lowered honestly.\n\n This attribute has no schema default on purpose. When it is\n absent, a consumer must treat the comment as falling below any\n confidence floor it applies, i.e. absent never satisfies a\n threshold.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-id\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Identifier of the remote discussion thread or comment this\n comment was fetched from, in the id space of the forge named by\n remote-forge on the review root. Provenance and forward\n machinery: it lets a consumer trace the finding back to its\n origin, and a future posting feature reply to the existing\n thread instead of opening a new one. Absent on comments\n authored locally.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"ReplyType\">\n <xs:annotation>\n <xs:documentation>\n A reply to a review comment. Replies turn a finding into a\n conversation: the comment asserts something, a reply answers it, a\n later reply answers that.\n\n Four rules govern replies. Only the first is beyond what XSD 1.0\n can express, and it is enforced by the application and by the\n skills that author these documents. Rules 2 to 4 are enforced by\n the content model below; they are spelled out anyway, because the\n reason for a constraint is what an author needs in order to write\n a good reply, and a validator only ever reports the constraint:\n\n 1. Replies are ordered. Document order is conversation order, and\n it is the only ordering signal. There are no timestamps and no\n identifiers: the earlier reply is the earlier turn.\n\n 2. Replies are flat. A reply is never nested inside another reply.\n A reply that addresses an earlier reply says so in its body.\n\n 3. A reply carries no thresholding metadata. There is no category,\n no severity and no confidence on a reply. Those are properties\n of the finding, and the finding is the root comment, whose\n severity and confidence govern the whole thread.\n\n 4. A reply carries no suggestion. A concrete counter-proposal goes\n in the reply body as a fenced code block. Allowing a suggestion\n on both the root and a reply would force every consumer to\n invent its own precedence rule.\n\n When a machine consumes a thread, the last human turn is the\n tie-breaker over any earlier machine assertion.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The reply text. May contain markdown formatting, including\n fenced code blocks, which is where a counter-proposal goes\n since replies carry no suggestion element.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment, identical in form and semantics to\n a comment attachment. The path attribute references an image\n file stored in the .self-review-assets/ directory alongside\n the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"author\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The author of this reply, with the same semantics as\n CommentType/@author. When present, the reply was generated by a\n bot or LLM (e.g., \"Claude Opus 5\"). When absent, the reply is\n the human reviewer's.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-id\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Identifier of the remote comment this reply was fetched from,\n with the same semantics as CommentType/@remote-id: an id in the\n forge's own id space, kept for provenance and for a future\n posting feature. Absent on replies authored locally.\n\n A remote-id is not an ordering signal. Document order remains\n conversation order, exactly as rule 1 above states.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"SuggestionType\">\n <xs:annotation>\n <xs:documentation>\n A code replacement proposal. The original-code is the literal text\n currently at the referenced lines. The proposed-code is what the\n reviewer suggests it should be replaced with. The AI agent can apply\n this by performing a text substitution.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"original-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The existing code at the referenced line range, copied verbatim\n from the diff. Used by the AI agent to locate the replacement\n target via text matching.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"proposed-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The replacement code proposed by the reviewer. The AI agent\n should substitute original-code with this text.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n\n <xs:complexType name=\"AttachmentType\">\n <xs:annotation>\n <xs:documentation>\n Reference to an image file attached to a review comment. The file is stored\n alongside the XML output in the .self-review-assets/ directory.\n </xs:documentation>\n </xs:annotation>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>Relative path from the XML file to the image file.</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"media-type\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>MIME type of the image (e.g., image/png, image/jpeg).</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <!-- ===== Simple types ===== -->\n\n <xs:simpleType name=\"ChangeTypeEnum\">\n <xs:annotation>\n <xs:documentation>\n The type of change a file underwent in the diff.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"added\">\n <xs:annotation>\n <xs:documentation>New file that did not exist before.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"modified\">\n <xs:annotation>\n <xs:documentation>Existing file with content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"deleted\">\n <xs:annotation>\n <xs:documentation>File was removed.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"renamed\">\n <xs:annotation>\n <xs:documentation>File was moved or renamed, with or without content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"SeverityEnum\">\n <xs:annotation>\n <xs:documentation>\n How consequential a finding is if it is real. Ordered from most to\n least consequential: critical, major, minor, info.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"critical\">\n <xs:annotation>\n <xs:documentation>\n Causes data loss, a security hole, or a crash or corruption on a\n path that real usage reaches. Shipping this is not acceptable.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"major\">\n <xs:annotation>\n <xs:documentation>\n Produces wrong behaviour, or breaks a documented contract, on a\n path that real usage reaches. The code does not do what it is\n supposed to do, but nothing is destroyed and there is no security\n impact.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"minor\">\n <xs:annotation>\n <xs:documentation>\n Real but bounded: a mishandled edge case that is unlikely to be\n hit, a missing test, a leak of something cheap, or a maintenance\n hazard that will cost time later. Behaviour is correct today.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"info\">\n <xs:annotation>\n <xs:documentation>\n No defect. Style, naming, phrasing, a question for the author, or\n a note recorded for context. Nothing is wrong if this is never\n acted on.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"ConfidenceEnum\">\n <xs:annotation>\n <xs:documentation>\n How sure the author is that a finding is real. Ordered from most to\n least sure: high, medium, low.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"high\">\n <xs:annotation>\n <xs:documentation>\n The evidence is in the code that was read. The failure can be\n traced from the diff itself, and no assumption about unseen code,\n unseen callers, or unstated requirements is needed to reach it.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"medium\">\n <xs:annotation>\n <xs:documentation>\n Likely real, but it rests on one assumption that was not verified,\n such as how a caller behaves, what a dependency guarantees, or\n what the intended requirement was. Stating that assumption in the\n body is expected at this level.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"low\">\n <xs:annotation>\n <xs:documentation>\n Speculative. The failure scenario was imagined rather than traced,\n or the finding depends on a constraint the author invented, or the\n author could not tell intent from the code. Worth a human's eyes,\n not worth acting on unattended.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"RemoteForgeEnum\">\n <xs:annotation>\n <xs:documentation>\n The forge hosting a remote pull/merge request.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"github\">\n <xs:annotation>\n <xs:documentation>A GitHub pull request.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"gitlab\">\n <xs:annotation>\n <xs:documentation>A GitLab merge request.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n</xs:schema>`;\n\nfunction extFromMediaType(mediaType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\n/**\n * Copies one attachment list's in-memory blobs into the asset directory and\n * returns the list with each fileName rewritten to its on-disk location and the\n * data buffer stripped.\n *\n * Shared by the comment walk and the reply walk. Serialization emits the\n * fileName it is given without checking that anything was written, so an\n * attachment list that misses this function produces a document that validates\n * against the schema while pointing at a file that does not exist. That failure\n * has no error surface, which is why both walks go through here.\n *\n * The idPrefix names the resulting files. Comments pass their own id, so\n * existing asset names are unchanged; replies pass a prefix that cannot collide\n * with a comment's.\n */\nfunction persistAttachments(\n attachments: Attachment[] | undefined,\n idPrefix: string,\n assetDir: string,\n onWrite: () => void\n): Attachment[] | undefined {\n if (!attachments?.length) return attachments;\n\n return attachments.map((att, index) => {\n if (!att.data) return att;\n onWrite();\n\n const ext = extFromMediaType(att.mediaType);\n const fileName = `${idPrefix}-${index}.${ext}`;\n const relativePath = `.self-review-assets/${fileName}`;\n\n if (!fs.existsSync(assetDir)) {\n fs.mkdirSync(assetDir, { recursive: true });\n }\n fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));\n\n return { ...att, fileName: relativePath, data: undefined };\n });\n}\n\nfunction writeAttachments(state: ReviewState, outputFilePath: string): ReviewState {\n const assetDir = path.join(path.dirname(outputFilePath), '.self-review-assets');\n let hasAttachments = false;\n const markWritten = () => {\n hasAttachments = true;\n };\n\n const updatedFiles = state.files.map(file => ({\n ...file,\n // Every comment is walked, including one with no attachments of its own:\n // its replies may carry attachments, and short-circuiting on the comment's\n // own list would drop those blobs without a word.\n comments: file.comments.map(comment => ({\n ...comment,\n attachments: persistAttachments(comment.attachments, comment.id, assetDir, markWritten),\n ...(comment.replies\n ? {\n replies: comment.replies.map(reply => ({\n ...reply,\n attachments: persistAttachments(\n reply.attachments,\n `${comment.id}-r-${reply.id}`,\n assetDir,\n markWritten\n ),\n })),\n }\n : {}),\n })),\n }));\n\n if (hasAttachments) {\n console.error(`[main] Wrote attachment files to ${assetDir}`);\n }\n\n return { ...state, files: updatedFiles };\n}\n\nexport async function serializeReview(state: ReviewState, outputFilePath: string): Promise<string> {\n const processedState = writeAttachments(state, outputFilePath);\n const xml = buildXml(processedState);\n\n // Validate the XML against the XSD\n try {\n const validationResult = await validateXML({\n xml: [{ fileName: 'review.xml', contents: xml }],\n schema: [{ fileName: 'self-review-v3.xsd', contents: XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const errors = validationResult.errors || [];\n console.error('XML validation failed:');\n errors.forEach((err: unknown) => console.error(` ${err}`));\n throw new Error('Generated XML does not conform to schema');\n }\n } catch (error) {\n // Re-throw if it's a schema validation failure (our own throw above)\n if (error instanceof Error && error.message === 'Generated XML does not conform to schema') {\n throw error;\n }\n // Infrastructure failure (e.g. WASM load): log warning and return XML anyway\n if (error instanceof Error) {\n console.error(\n `[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`\n );\n } else {\n console.error(\n '[main] XML validation infrastructure failed - emitting XML without validation'\n );\n }\n return xml;\n }\n\n return xml;\n}\n\nfunction buildSourceAttributes(state: ReviewState): string {\n const source = state.source;\n if (source.type === 'git') {\n return ` git-diff-args=\"${escapeXml(source.gitDiffArgs)}\" repository=\"${escapeXml(source.repository)}\"`;\n }\n if (source.type === 'directory' || source.type === 'file') {\n return ` source-path=\"${escapeXml(source.sourcePath)}\"`;\n }\n // welcome mode: no source attributes\n return '';\n}\n\n/**\n * Remote provenance attributes on the review root. Like severity and\n * confidence on a comment, absent means \"not a remote review\", so each\n * attribute is emitted only when its field is set: a purely local review\n * serializes byte-identically to a document written before these existed.\n */\nfunction buildRemoteAttributes(state: ReviewState): string {\n const attrs: string[] = [];\n\n if (state.remoteUrl) {\n attrs.push(`remote-url=\"${escapeXml(state.remoteUrl)}\"`);\n }\n if (state.remoteBaseSha) {\n attrs.push(`remote-base-sha=\"${escapeXml(state.remoteBaseSha)}\"`);\n }\n if (state.remoteHeadSha) {\n attrs.push(`remote-head-sha=\"${escapeXml(state.remoteHeadSha)}\"`);\n }\n if (state.remoteForge) {\n attrs.push(`remote-forge=\"${state.remoteForge}\"`);\n }\n\n return attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n}\n\nfunction buildXml(state: ReviewState): string {\n const lines: string[] = [];\n\n // XML declaration\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n\n // Root element with namespace\n const sourceAttrs = buildSourceAttributes(state);\n const remoteAttrs = buildRemoteAttributes(state);\n lines.push(\n `<review xmlns=\"urn:self-review:v3\" timestamp=\"${escapeXml(state.timestamp)}\"${sourceAttrs}${remoteAttrs}>`\n );\n\n // Files\n for (const file of state.files) {\n lines.push(...buildFileXml(file));\n }\n\n // Close root element\n lines.push('</review>');\n\n return lines.join('\\n');\n}\n\nfunction buildFileXml(file: FileReviewState): string[] {\n const lines: string[] = [];\n\n if (file.comments.length === 0) {\n // Self-closing tag for files with no comments\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\" />`\n );\n } else {\n // Opening tag\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\">`\n );\n\n // Comments\n for (const comment of file.comments) {\n lines.push(...buildCommentXml(comment));\n }\n\n // Closing tag\n lines.push(' </file>');\n }\n\n return lines;\n}\n\nfunction buildCommentXml(comment: ReviewComment): string[] {\n const lines: string[] = [];\n const attrs: string[] = [];\n\n // Add line attributes\n if (comment.lineRange) {\n if (comment.lineRange.side === 'old') {\n attrs.push(`old-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`old-line-end=\"${comment.lineRange.end}\"`);\n } else {\n attrs.push(`new-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`new-line-end=\"${comment.lineRange.end}\"`);\n }\n }\n\n if (comment.author) {\n attrs.push(`author=\"${escapeXml(comment.author)}\"`);\n }\n\n // Thresholding signals. Absent means \"below any floor\", so they are omitted\n // rather than defaulted when the author did not take a position.\n if (comment.severity) {\n attrs.push(`severity=\"${comment.severity}\"`);\n }\n\n if (comment.confidence) {\n attrs.push(`confidence=\"${comment.confidence}\"`);\n }\n\n // Remote provenance. Absent means locally authored, so it is omitted\n // rather than defaulted, exactly like the signals above.\n if (comment.remoteId) {\n attrs.push(`remote-id=\"${escapeXml(comment.remoteId)}\"`);\n }\n\n const attrStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n\n // Opening tag\n lines.push(` <comment${attrStr}>`);\n\n // Body (preserve whitespace and newlines)\n lines.push(` <body>${escapeXml(comment.body)}</body>`);\n\n // Category (required)\n lines.push(` <category>${escapeXml(comment.category)}</category>`);\n\n // Suggestion\n if (comment.suggestion) {\n lines.push(' <suggestion>');\n lines.push(\n ` <original-code>${escapeXml(comment.suggestion.originalCode)}</original-code>`\n );\n lines.push(\n ` <proposed-code>${escapeXml(comment.suggestion.proposedCode)}</proposed-code>`\n );\n lines.push(' </suggestion>');\n }\n\n // Attachments\n lines.push(...buildAttachmentXml(comment.attachments, ' '));\n\n // Replies, in array order: document order is conversation order, and it is\n // the only ordering signal a reply has.\n for (const reply of comment.replies ?? []) {\n lines.push(...buildReplyXml(reply));\n }\n\n // Closing tag\n lines.push(' </comment>');\n\n return lines;\n}\n\n/**\n * Attachment elements are identical in form and meaning under a comment and\n * under a reply, so both call sites emit them from here.\n */\nfunction buildAttachmentXml(attachments: Attachment[] | undefined, indent: string): string[] {\n if (!attachments?.length) return [];\n\n return attachments.map(\n att =>\n `${indent}<attachment path=\"${escapeXml(att.fileName)}\" media-type=\"${escapeXml(att.mediaType)}\" />`\n );\n}\n\n/**\n * A reply is a flat turn in the thread: a body, optional attachments and an\n * optional author. It carries no category, severity, confidence, suggestion or\n * nested replies — those belong to the root comment, which owns the finding.\n * See ReplyType in the XSD for the reasoning.\n */\nfunction buildReplyXml(reply: Reply): string[] {\n const attrs: string[] = [];\n\n if (reply.author) {\n attrs.push(`author=\"${escapeXml(reply.author)}\"`);\n }\n if (reply.remoteId) {\n attrs.push(`remote-id=\"${escapeXml(reply.remoteId)}\"`);\n }\n\n const attrStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n\n return [\n ` <reply${attrStr}>`,\n ` <body>${escapeXml(reply.body)}</body>`,\n ...buildAttachmentXml(reply.attachments, ' '),\n ' </reply>',\n ];\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n","// src/main/xml-parser.ts\n// Parse XML review file back into ReviewComment[]\n\nimport { readFileSync } from 'fs';\nimport { XMLParser } from 'fast-xml-parser';\nimport {\n ReviewComment,\n Suggestion,\n LineRange,\n DiffSource,\n CommentSeverity,\n CommentConfidence,\n RemoteForge,\n Attachment,\n Reply,\n} from './types';\n\nconst SEVERITY_VALUES: readonly CommentSeverity[] = ['critical', 'major', 'minor', 'info'];\nconst CONFIDENCE_VALUES: readonly CommentConfidence[] = ['high', 'medium', 'low'];\nconst REMOTE_FORGE_VALUES: readonly RemoteForge[] = ['github', 'gitlab'];\n\nexport interface ParsedReview {\n comments: ReviewComment[];\n /** Paths of files the previous review marked as done (`viewed=\"true\"`). */\n viewedFiles: string[];\n gitDiffArgs: string;\n source: DiffSource;\n // Remote provenance, read tolerantly off the review root. Undefined when\n // the document carries no remote attributes, i.e. every pre-remote and\n // purely local review.\n remoteUrl?: string;\n remoteBaseSha?: string;\n remoteHeadSha?: string;\n remoteForge?: RemoteForge;\n}\n\nexport function parseReviewXml(xmlPath: string): ParsedReview {\n try {\n const xmlContent = readFileSync(xmlPath, 'utf-8');\n return parseReviewXmlString(xmlContent);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error reading XML file: ${error.message}`);\n } else {\n console.error('Error reading XML file: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function parseReviewXmlString(xmlContent: string): ParsedReview {\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n allowBooleanAttributes: true,\n trimValues: false,\n });\n\n try {\n const result = parser.parse(xmlContent);\n\n if (!result.review) {\n throw new Error('Invalid XML: missing <review> root element');\n }\n\n const review = result.review;\n const gitDiffArgs = review['@_git-diff-args'] || '';\n const source = parseSource(review);\n const comments: ReviewComment[] = [];\n const viewedFiles: string[] = [];\n\n // Handle files array\n const files = toChildArray(review.file);\n\n for (const file of files) {\n // Skip only when the attribute is genuinely absent: the empty string\n // is the review-level sentinel path (REVIEW_LEVEL_FILE_PATH) used by\n // fetch-comments for threads with no file anchor, and must round-trip.\n const rawPath = file['@_path'];\n if (rawPath === undefined || rawPath === null) continue;\n const filePath = String(rawPath);\n\n if (parseViewed(file['@_viewed'])) {\n viewedFiles.push(filePath);\n }\n\n // Handle comments array\n const fileComments = toChildArray(file.comment);\n\n for (const comment of fileComments) {\n const reviewComment: ReviewComment = {\n id: generateId(),\n filePath,\n lineRange: parseLineRange(comment),\n body: comment.body !== undefined ? String(comment.body) : '',\n category: comment.category !== undefined ? String(comment.category) : '',\n suggestion: parseSuggestion(comment),\n author: comment['@_author'] ? String(comment['@_author']) : undefined,\n severity: parseEnumAttribute(comment['@_severity'], SEVERITY_VALUES),\n confidence: parseEnumAttribute(comment['@_confidence'], CONFIDENCE_VALUES),\n remoteId: parseStringAttribute(comment['@_remote-id']),\n };\n\n const attachments = parseAttachments(comment, reviewComment.id);\n if (attachments) reviewComment.attachments = attachments;\n\n const replies = parseReplies(comment);\n if (replies) reviewComment.replies = replies;\n\n comments.push(reviewComment);\n }\n }\n\n return {\n comments,\n viewedFiles,\n gitDiffArgs,\n source,\n remoteUrl: parseStringAttribute(review['@_remote-url']),\n remoteBaseSha: parseStringAttribute(review['@_remote-base-sha']),\n remoteHeadSha: parseStringAttribute(review['@_remote-head-sha']),\n remoteForge: parseEnumAttribute(review['@_remote-forge'], REMOTE_FORGE_VALUES),\n };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error parsing XML: ${error.message}`);\n } else {\n console.error('Error parsing XML: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Read an enumerated attribute, dropping values the schema does not define.\n *\n * An unrecognised value becomes undefined rather than being passed through:\n * undefined is the fail-safe reading (below every threshold floor), and it\n * keeps a resumed review serializable, since the serializer validates its\n * output against the XSD before writing.\n */\nfunction parseEnumAttribute<T extends string>(raw: unknown, allowed: readonly T[]): T | undefined {\n if (raw === undefined || raw === null) return undefined;\n const value = String(raw);\n return allowed.includes(value as T) ? (value as T) : undefined;\n}\n\n/**\n * Read an optional free-form string attribute, leaving absent as undefined.\n * Values are taken as-is: the remote attributes are provenance the app never\n * interprets, so there is nothing to validate on read.\n */\nfunction parseStringAttribute(raw: unknown): string | undefined {\n return raw === undefined || raw === null ? undefined : String(raw);\n}\n\n/**\n * Read the `viewed` attribute of a <file> element.\n *\n * Anything other than an explicit true reads as not viewed: the attribute is\n * optional, and treating an unknown value as \"already reviewed\" would silently\n * hide files from the resumed review.\n */\nfunction parseViewed(raw: unknown): boolean {\n return raw === true || String(raw) === 'true';\n}\n\nfunction parseSource(review: Record<string, unknown>): DiffSource {\n const sourcePath = review['@_source-path'];\n if (sourcePath) {\n return { type: 'directory', sourcePath: String(sourcePath) };\n }\n\n const gitDiffArgs = review['@_git-diff-args'];\n const repository = review['@_repository'];\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: String(gitDiffArgs || ''),\n repository: String(repository || ''),\n };\n }\n\n return { type: 'welcome' };\n}\n\nfunction parseLineRange(comment: Record<string, unknown>): LineRange | null {\n const hasOld =\n comment['@_old-line-start'] !== undefined && comment['@_old-line-end'] !== undefined;\n const hasNew =\n comment['@_new-line-start'] !== undefined && comment['@_new-line-end'] !== undefined;\n\n if (hasOld) {\n return {\n side: 'old',\n start: parseInt(String(comment['@_old-line-start']), 10),\n end: parseInt(String(comment['@_old-line-end']), 10),\n };\n }\n\n if (hasNew) {\n return {\n side: 'new',\n start: parseInt(String(comment['@_new-line-start']), 10),\n end: parseInt(String(comment['@_new-line-end']), 10),\n };\n }\n\n return null; // File-level comment\n}\n\nfunction parseSuggestion(comment: Record<string, unknown>): Suggestion | null {\n if (!comment.suggestion) {\n return null;\n }\n\n const suggestion = comment.suggestion as Record<string, unknown>;\n return {\n originalCode: String(suggestion['original-code'] || ''),\n proposedCode: String(suggestion['proposed-code'] || ''),\n };\n}\n\n/**\n * Normalize a repeatable child element into an array.\n *\n * fast-xml-parser collapses a single occurrence into a bare object and only\n * produces an array from two or more, so every repeatable child in this file\n * has to be widened before it can be iterated. An absent child yields an empty\n * array.\n */\nfunction toChildArray(raw: unknown): Record<string, unknown>[] {\n if (Array.isArray(raw)) return raw as Record<string, unknown>[];\n if (raw === undefined || raw === null) return [];\n return [raw as Record<string, unknown>];\n}\n\n/**\n * Read `<attachment>` children of a comment or a reply.\n *\n * Attachment ids are synthetic: nothing in the document names them, so they are\n * derived from the id of their owner, which is why the prefix is a parameter\n * rather than read off the node. Returns undefined rather than [] when there\n * are none, matching the optional field on the type.\n */\nfunction parseAttachments(\n node: Record<string, unknown>,\n idPrefix: string\n): Attachment[] | undefined {\n const raw = toChildArray(node.attachment);\n if (raw.length === 0) return undefined;\n\n return raw.map((att, i) => ({\n id: `${idPrefix}-att-${i}`,\n fileName: String(att['@_path'] || ''),\n mediaType: String(att['@_media-type'] || 'image/png'),\n }));\n}\n\n/**\n * Read `<reply>` children in document order.\n *\n * Document order is conversation order: a reply carries no timestamp and no\n * identifier, so the order of this array is the only ordering signal a thread\n * ever has. Returns undefined rather than [] when there are none, so a\n * reply-free comment keeps exactly the shape it had before threads existed.\n */\nfunction parseReplies(comment: Record<string, unknown>): Reply[] | undefined {\n const raw = toChildArray(comment.reply);\n if (raw.length === 0) return undefined;\n\n return raw.map(node => {\n const id = generateId();\n const reply: Reply = {\n id,\n body: node.body !== undefined ? String(node.body) : '',\n author: node['@_author'] ? String(node['@_author']) : undefined,\n remoteId: parseStringAttribute(node['@_remote-id']),\n };\n\n const attachments = parseAttachments(node, id);\n if (attachments) reply.attachments = attachments;\n\n return reply;\n });\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// packages/core/src/guide-schema.ts\n// Embedded copy of the walkthrough guide XSD for validation.\n\n// This MUST stay byte-identical to the on-disk copy at\n// .agents/skills/self-review-guide/assets/self-review-guide-v1.xsd;\n// the sync test in xsd-schema.test.ts enforces it.\nexport const GUIDE_XSD_SCHEMA = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sg=\"urn:self-review-guide:v1\"\n targetNamespace=\"urn:self-review-guide:v1\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review guide XML Schema v1\n ===============================\n Defines the walkthrough guide sidecar for the self-review application.\n This schema is designed to be both machine-validated and fed to an LLM\n so it can author valid guide documents from the schema alone.\n\n Key concepts:\n - A <guide> is a read-only orientation aid generated BEFORE a review\n starts. It lives next to the review output file and is discovered by\n convention; it is never written by the review UI.\n - The optional <overview> is short Markdown prose shown before the\n first file, orienting the reviewer to the change as a whole.\n - Each <group> names a set of files that belong together (for example\n \"Core change\", \"Tests\", \"Generated/mechanical\") and explains, in one\n line, why they are grouped and where they sit in the reading order.\n - Each <file> inside a group points at one diff file by its\n repository-relative path and carries a one-line description of the\n role that file plays in the change.\n\n Ordering:\n - Document order IS the reading order. Groups are presented in the\n order they appear, and files within a group are presented in the\n order they appear. There are no explicit ordering attributes; to\n reorder, reorder the elements.\n\n Presentation only, never suppression:\n - This vocabulary labels and orders content; it cannot hide it. There\n is deliberately no element or attribute that hides, collapses, or\n marks a file as skippable, and none may be added to v1. Files in the\n diff that no group mentions remain fully visible in an implicit\n \"Everything else\" group; files mentioned here but absent from the\n diff are silently ignored.\n\n Tolerance:\n - A missing, stale, or invalid guide degrades the consumer to its\n normal ungrouped view. A guide can therefore never block or fail a\n review, but an invalid guide is silently useless, so authors should\n validate against this schema before writing the file.\n -->\n\n <!-- ===== Root element ===== -->\n\n <xs:element name=\"guide\" type=\"sg:GuideType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review walkthrough guide sidecar. Contains\n an optional overview followed by zero or more ordered groups.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <!-- ===== Complex types ===== -->\n\n <xs:complexType name=\"GuideType\">\n <xs:annotation>\n <xs:documentation>\n The whole walkthrough guide. The optional metadata attributes\n mirror the review schema's provenance attributes so a consumer can\n sanity-check that the guide was generated for the diff it is being\n shown next to; none of them are required and none affect\n presentation.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"overview\" type=\"xs:string\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Review-level orientation prose shown before the first file.\n Markdown formatting is allowed, including fenced code blocks;\n a fenced code block labelled \"mermaid\" may be used for a\n diagram of the change.\n Keep it short: a few sentences saying what the change does and\n where to start reading, not a restatement of every file.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"group\" type=\"sg:GroupType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Ordered reading groups. The first group should hold the files\n the reviewer must understand first (the core of the change);\n later groups hold consequences, tests, and mechanical fallout.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the guide was generated.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments the guide was generated against.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when the guide describes a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root the guide was generated in.\n Present only when the guide describes a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"GroupType\">\n <xs:annotation>\n <xs:documentation>\n A named set of related files with a one-line rationale. Groups are\n labels for orientation, never suppressions: a consumer shows every\n group and every file in it. Position in the document is position\n in the reading order.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"rationale\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n One line explaining why these files form a group and what the\n reviewer should look for in them (e.g., \"The retry wrapper\n everything else calls; read this first\"). Plain text, a single\n sentence; no Markdown, no line breaks.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"file\" type=\"sg:FileEntryType\" minOccurs=\"1\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n The files in this group, in reading order. A group must list\n at least one file; do not author empty placeholder groups.\n Every file in the diff may appear in at most one group, and\n files omitted from every group are not hidden — the consumer\n shows them in an implicit trailing \"Everything else\" group.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Short display name for the group, e.g. \"Core change\", \"Tests\",\n \"Generated/mechanical\". Shown as the group heading in the file\n tree; keep it to a few words.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileEntryType\">\n <xs:annotation>\n <xs:documentation>\n One file in a group. The path must match a file in the diff being\n reviewed; entries whose path matches nothing in the diff are\n silently dropped by the consumer, so a stale guide degrades\n instead of erroring.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"description\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n One line describing the role this file plays in the change\n (e.g., \"Adds the retry wrapper that everything else calls\").\n Plain text, a single sentence; no Markdown, no line breaks.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root, using the same\n convention as review.xml file paths. For renamed files, use the\n new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n</xs:schema>`;\n","// packages/core/src/guide-parser.ts\n// Parse a walkthrough guide XML string into a typed ReviewGuide, and\n// reconcile a guide with the diff's file list into resolved display groups.\n//\n// Tolerance contract (binding, from docs/intent/llm-review-guide.md): the\n// guide is orientation garnish on a deterministic tool. A missing, stale, or\n// invalid guide degrades the consumer to its flat view — parsing problems\n// are failure VALUES the caller can log and ignore, never exceptions.\n\nimport { XMLParser } from 'fast-xml-parser';\nimport { validateXML } from 'xmllint-wasm';\nimport type {\n GuideFileEntry,\n GuideGroup,\n ResolvedGuideGroup,\n ResolvedGuideFile,\n ReviewGuide,\n} from './types';\nimport { GUIDE_XSD_SCHEMA } from './guide-schema';\n\n/** Display name given to the derived trailing group of unmentioned files. */\nexport const IMPLICIT_GUIDE_GROUP_NAME = 'Everything else';\n\nexport type GuideParseResult = { ok: true; guide: ReviewGuide } | { ok: false; reason: string };\n\n/**\n * Parse and validate a guide XML string.\n *\n * The document is validated against the embedded self-review-guide-v1 XSD\n * (same xmllint-wasm tooling the review serializer uses) before being read,\n * so a successful result is structurally guaranteed by the schema. Any\n * defect — non-XML input, schema violations, validator failure — comes back\n * as `{ ok: false, reason }`; this function never throws on bad input.\n */\nexport async function parseGuideXml(xmlContent: string): Promise<GuideParseResult> {\n try {\n const validationResult = await validateXML({\n xml: [{ fileName: 'guide.xml', contents: xmlContent }],\n schema: [{ fileName: 'self-review-guide-v1.xsd', contents: GUIDE_XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const details = (validationResult.errors || [])\n .map(err => (typeof err === 'string' ? err : err.message))\n .join('; ');\n return {\n ok: false,\n reason: `Guide XML does not conform to self-review-guide-v1 schema${details ? `: ${details}` : ''}`,\n };\n }\n\n return { ok: true, guide: readGuide(xmlContent) };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, reason: `Failed to parse guide XML: ${message}` };\n }\n}\n\n/**\n * Extract the typed guide from a document that already passed XSD\n * validation. Values are still string-coerced defensively, but structural\n * guarantees (required attributes/elements, at least one file per group)\n * come from the schema.\n */\nfunction readGuide(xmlContent: string): ReviewGuide {\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n // Keep values verbatim: a description like \"007\" or an overview of\n // \"true\" must stay a string, not become a number or boolean.\n parseTagValue: false,\n parseAttributeValue: false,\n // A prefixed form (<sg:guide xmlns:sg=\"urn:self-review-guide:v1\">) is\n // schema-valid, so reading must accept it too; without this the lookup\n // of `.guide` below finds nothing.\n removeNSPrefix: true,\n });\n\n const root = parser.parse(xmlContent).guide as Record<string, unknown>;\n\n const guide: ReviewGuide = { groups: asArray(root.group).map(readGroup) };\n\n const overview = root.overview;\n if (typeof overview === 'string' && overview !== '') {\n guide.overview = overview;\n }\n\n return guide;\n}\n\nfunction readGroup(raw: unknown): GuideGroup {\n const group = raw as Record<string, unknown>;\n return {\n name: String(group['@_name']),\n rationale: String(group.rationale ?? ''),\n files: asArray(group.file).map(readFileEntry),\n };\n}\n\nfunction readFileEntry(raw: unknown): GuideFileEntry {\n const file = raw as Record<string, unknown>;\n return {\n path: String(file['@_path']),\n description: String(file.description ?? ''),\n };\n}\n\n/** fast-xml-parser yields a bare object for singular elements; normalize. */\nfunction asArray(value: unknown): unknown[] {\n if (value === undefined || value === null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Merge a parsed guide with the diff's file list into resolved display\n * groups, tolerantly:\n *\n * - Guide entries whose path is not in the diff are dropped (stale guide);\n * a group left with no surviving files is dropped entirely.\n * - A file referenced by more than one group appears only in the first.\n * - Diff files no group mentions land in a terminal implicit\n * \"Everything else\" group, preserving the diff's file order, marked\n * `implicit: true` so the UI can label it.\n * - Guide group order and in-group file order are preserved.\n */\nexport function reconcileGuide(guide: ReviewGuide, diffFilePaths: string[]): ResolvedGuideGroup[] {\n const diffPaths = new Set(diffFilePaths);\n const claimed = new Set<string>();\n const resolved: ResolvedGuideGroup[] = [];\n\n for (const group of guide.groups) {\n const files: ResolvedGuideFile[] = [];\n for (const file of group.files) {\n if (!diffPaths.has(file.path) || claimed.has(file.path)) continue;\n claimed.add(file.path);\n files.push({ path: file.path, description: file.description });\n }\n if (files.length > 0) {\n resolved.push({\n name: group.name,\n rationale: group.rationale,\n implicit: false,\n files,\n });\n }\n }\n\n const leftover = diffFilePaths.filter(path => !claimed.has(path));\n if (leftover.length > 0) {\n resolved.push({\n name: IMPLICIT_GUIDE_GROUP_NAME,\n implicit: true,\n files: leftover.map(path => ({ path })),\n });\n }\n\n return resolved;\n}\n","// forge-provider.ts\n// Conversation-plane forge abstraction: URL parsing with forge detection by\n// path shape, the ForgeProvider interface (base-branch lookup + thread fetch),\n// and the forge-neutral normalized thread types produced by every provider.\n//\n// This module is pure code: no I/O, no child processes. Provider\n// implementations (github-provider.ts, gitlab-provider.ts) do the CLI work\n// through an injectable command runner so they stay unit-testable.\n\n/** Forges the app knows how to talk to. */\nexport type ForgeName = 'github' | 'gitlab';\n\n/**\n * A parsed pull-request / merge-request web URL.\n *\n * Detection is by URL path shape only (`/pull/N` → GitHub,\n * `/-/merge_requests/N` → GitLab) on any host, so self-hosted instances such\n * as git.drupalcode.org work with zero configuration.\n */\nexport interface ForgeUrl {\n forge: ForgeName;\n /** Host as it appears in the URL, including a port when present. */\n host: string;\n /**\n * Repository owner. For GitLab this is the full namespace path and may\n * contain slashes (subgroups, e.g. `group/subgroup`); for GitHub it is a\n * single segment.\n */\n owner: string;\n /** Repository name (final path segment before the PR/MR marker). */\n repo: string;\n /** Pull-request number / merge-request IID. */\n number: number;\n}\n\n/** Which side of the diff a thread anchor points at. */\nexport type ForgeAnchorSide = 'old' | 'new';\n\n/**\n * Forge-neutral anchor of a discussion thread onto the diff.\n *\n * The mapper consumes this shape without forge-conditional logic:\n * - `startLine`/`endLine` are equal for single-line anchors.\n * - `startLine`/`endLine` are `null` when the forge supplies a file path but\n * no usable line information (the mapper degrades to a file-level comment;\n * `side` is meaningless in that case and providers should set `'new'`).\n * - `outdated: true` means the forge reports the anchor no longer applies to\n * the current head (e.g. GitHub outdated review comments); the line fields\n * then hold the historic anchor and the mapper degrades to file-level.\n */\nexport interface ForgeThreadAnchor {\n filePath: string;\n side: ForgeAnchorSide;\n startLine: number | null;\n endLine: number | null;\n outdated: boolean;\n}\n\n/** One turn (root comment or reply) in a forge discussion thread. */\nexport interface ForgeThreadTurn {\n /** Forge-assigned comment/note ID, kept as a string verbatim. */\n remoteId: string;\n /** Forge username of the turn's author. */\n author: string;\n /** Markdown body, passed through verbatim. */\n body: string;\n}\n\n/**\n * A normalized discussion thread: an ordered root + flat replies.\n *\n * The root turn owns the anchor. `anchor` is `null` for threads with no file\n * association at all (e.g. GitLab non-diff discussions); the mapper turns\n * those into its review-level representation. `replies` preserve the forge's\n * document order — nothing else sorts them.\n */\nexport interface ForgeThread {\n root: ForgeThreadTurn;\n replies: ForgeThreadTurn[];\n anchor: ForgeThreadAnchor | null;\n}\n\n/** Options for {@link ForgeProvider.fetchThreads}. */\nexport interface FetchThreadsOptions {\n /**\n * Include threads the forge marks resolved. Defaults to false where the\n * forge tracks resolution (GitLab); providers without a comparable concept\n * on the fetch path (GitHub REST review comments) may ignore it.\n */\n includeResolved?: boolean;\n}\n\n/**\n * Result of running a forge CLI command through {@link ForgeCommandRunner}.\n */\nexport interface ForgeCommandResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n}\n\n/**\n * Injectable command runner used by provider implementations, mirroring how\n * `git.ts` keeps child-process execution testable. Resolves with the exit\n * code on any completed run (including non-zero); rejects only when the\n * binary cannot be spawned at all (e.g. ENOENT when the CLI is absent).\n */\nexport type ForgeCommandRunner = (command: string, args: string[]) => Promise<ForgeCommandResult>;\n\n/**\n * The conversation plane of a forge. Exactly two capabilities: base-branch\n * lookup and discussion-thread fetching. No diff fetching, no blob fetching,\n * no posting — those concerns live elsewhere.\n *\n * Implementations throw {@link ForgeCliUnavailableError} when their CLI is\n * absent or unauthenticated so callers can degrade cleanly.\n */\nexport interface ForgeProvider {\n readonly forge: ForgeName;\n /** Resolve the PR/MR base (target) branch name. */\n fetchBaseBranch(url: ForgeUrl): Promise<string>;\n /** Fetch the PR/MR discussion threads in normalized form. */\n fetchThreads(url: ForgeUrl, options?: FetchThreadsOptions): Promise<ForgeThread[]>;\n}\n\n/**\n * Thrown by providers when their CLI is missing (spawn ENOENT) or exits\n * non-zero due to authentication/API failure. Callers catch this to degrade\n * (print to stderr, continue without threads) instead of crashing.\n */\nexport class ForgeCliUnavailableError extends Error {\n readonly forge: ForgeName;\n readonly cli: string;\n\n constructor(forge: ForgeName, cli: string, message: string) {\n super(message);\n this.name = 'ForgeCliUnavailableError';\n this.forge = forge;\n this.cli = cli;\n }\n}\n\n// Path-shape matchers. The number must terminate its path segment so\n// `/pull/12x` does not parse as PR 12; anything after the number segment\n// (trailing slash, sub-pages like /files) still identifies the same PR/MR.\n// Numbered groups (owner, repo, number in order): the app tsconfig targets\n// ES6, which predates named capture groups.\nconst GITHUB_PR_PATH = /^\\/([^/]+)\\/([^/]+)\\/pull\\/(\\d+)(?=\\/|$)/;\nconst GITLAB_MR_PATH = /^\\/(.+)\\/([^/]+)\\/-\\/merge_requests\\/(\\d+)(?=\\/|$)/;\n\n/**\n * Parse a forge web URL into a {@link ForgeUrl}, or return `null` for\n * anything that is not a PR/MR URL. Detection is by path shape only, on any\n * http(s) host. Query strings and fragments are ignored.\n */\nexport function parseForgeUrl(url: string): ForgeUrl | null {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return null;\n }\n\n // GitLab first: `/-/merge_requests/` is the more specific marker.\n const gitlab = GITLAB_MR_PATH.exec(parsed.pathname);\n if (gitlab) {\n return {\n forge: 'gitlab',\n host: parsed.host,\n owner: gitlab[1],\n repo: gitlab[2],\n number: Number.parseInt(gitlab[3], 10),\n };\n }\n\n const github = GITHUB_PR_PATH.exec(parsed.pathname);\n if (github) {\n return {\n forge: 'github',\n host: parsed.host,\n owner: github[1],\n repo: github[2],\n number: Number.parseInt(github[3], 10),\n };\n }\n\n return null;\n}\n","// src/main/directory-scanner.ts\n// Recursively scans a directory and produces DiffFile[] treating all files as new additions.\n\nimport { readdir, stat } from 'fs/promises';\nimport { join, relative, basename, dirname } from 'path';\nimport { DiffFile } from './types';\nimport { generateSyntheticDiffs } from './synthetic-diff';\nimport { parseDiff } from './diff-parser';\nimport { createIgnoreFilter } from './ignore-filter';\n\n/**\n * Recursively scan a directory and return DiffFile[] with every file\n * treated as a new addition (changeType: 'added').\n *\n * @param directoryPath - Absolute path to the directory to scan\n * @param ignorePatterns - Optional gitignore-compatible patterns to exclude files\n * @returns Parsed DiffFile array for all files in the directory\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = []\n): Promise<DiffFile[]> {\n // Verify the path is a directory\n try {\n const dirStat = await stat(directoryPath);\n if (!dirStat.isDirectory()) {\n console.error(`Error: \"${directoryPath}\" is not a directory`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing directory \"${directoryPath}\": ${error.message}`);\n } else {\n console.error(`Error accessing directory \"${directoryPath}\": unknown error`);\n }\n return [];\n }\n\n const filePaths: string[] = [];\n\n try {\n const entries = await readdir(directoryPath, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n\n // Build the full path from the entry's parentPath (or path) and name\n const parentDir = entry.parentPath ?? entry.path;\n const fullPath = join(parentDir, entry.name);\n const relativePath = relative(directoryPath, fullPath);\n filePaths.push(relativePath);\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error reading directory \"${directoryPath}\": ${error.message}`);\n } else {\n console.error(`Error reading directory \"${directoryPath}\": unknown error`);\n }\n return [];\n }\n\n // Sort for deterministic output\n filePaths.sort();\n\n // Apply ignore patterns\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredPaths = filePaths.filter(p => shouldKeep(p));\n\n if (filteredPaths.length === 0) {\n return [];\n }\n\n const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);\n return parseDiff(diffText);\n}\n\n/**\n * Scan a single file and return DiffFile[] with the file treated as a new addition.\n *\n * @param filePath - Absolute path to the file to scan\n * @returns Parsed DiffFile array (single element)\n */\nexport async function scanFile(filePath: string): Promise<DiffFile[]> {\n try {\n const fileStat = await stat(filePath);\n if (!fileStat.isFile()) {\n console.error(`Error: \"${filePath}\" is not a file`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing file \"${filePath}\": ${error.message}`);\n } else {\n console.error(`Error accessing file \"${filePath}\": unknown error`);\n }\n return [];\n }\n\n const fileName = basename(filePath);\n const rootDir = dirname(filePath);\n const diffText = generateSyntheticDiffs([fileName], rootDir);\n return parseDiff(diffText);\n}\n","// src/main/ignore-filter.ts\n// Gitignore-compatible file path filtering using the `ignore` package.\n\nimport ignore from 'ignore';\n\n/**\n * Create a filter function from gitignore-compatible patterns.\n *\n * @param patterns - Array of gitignore-compatible glob patterns\n * @returns A predicate that returns `true` if the path should be kept (not ignored)\n */\nexport function createIgnoreFilter(patterns: string[]): (path: string) => boolean {\n if (patterns.length === 0) return () => true;\n const ig = ignore().add(patterns);\n return (filePath: string) => !ig.ignores(filePath);\n}\n","// src/main/config.ts\n// YAML configuration loading and merging\n\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { parse as parseYaml } from 'yaml';\nimport { AppConfig } from './types';\n\nconst defaults: AppConfig = {\n theme: 'system',\n diffView: 'split',\n fontSize: 14,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: [\n '.git',\n 'node_modules',\n 'vendor',\n '.vendor',\n '__pycache__',\n '.venv',\n 'venv',\n '.env',\n 'dist',\n 'build',\n '.next',\n '.nuxt',\n '.svelte-kit',\n 'target',\n '*.min.js',\n '*.min.css',\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Gemfile.lock',\n 'Cargo.lock',\n 'poetry.lock',\n 'go.sum',\n ],\n categories: [\n {\n name: 'question',\n description: 'Clarification needed — not necessarily a problem',\n color: '#805ad5',\n },\n {\n name: 'bug',\n description: 'Likely defect or incorrect behavior',\n color: '#e53e3e',\n },\n {\n name: 'security',\n description: 'Security vulnerability or concern',\n color: '#dd6b20',\n },\n {\n name: 'style',\n description: 'Code style, naming, or formatting issue',\n color: '#3182ce',\n },\n {\n name: 'task',\n description: 'Action item or follow-up task',\n color: '#38a169',\n },\n {\n name: 'nit',\n description: 'Minor nitpick, low priority',\n color: '#718096',\n },\n ],\n defaultDiffArgs: '',\n showUntracked: true,\n showUntrackedExplicit: false,\n wordWrap: true,\n maxFiles: 500,\n maxTotalLines: 100000,\n};\n\nexport function loadConfig(): AppConfig {\n let config = { ...defaults };\n\n // Load user-level config\n const userConfigPath = join(homedir(), '.config', 'self-review', 'config.yaml');\n if (existsSync(userConfigPath)) {\n try {\n const userConfig = loadYamlConfig(userConfigPath);\n config = mergeConfig(config, userConfig);\n } catch (error) {\n console.error(`Warning: Failed to load user config from ${userConfigPath}: ${error}`);\n }\n }\n\n // Load project-level config\n const projectConfigPath = join(process.cwd(), '.self-review.yaml');\n if (existsSync(projectConfigPath)) {\n try {\n const projectConfig = loadYamlConfig(projectConfigPath);\n config = mergeConfig(config, projectConfig);\n } catch (error) {\n console.error(`Warning: Failed to load project config from ${projectConfigPath}: ${error}`);\n }\n }\n\n return config;\n}\n\nfunction loadYamlConfig(path: string): Partial<AppConfig> {\n const content = readFileSync(path, 'utf-8');\n const raw = parseYaml(content);\n\n // An empty file (or one containing only `null`) is a valid \"use defaults\" state.\n if (raw === null || raw === undefined) {\n return {};\n }\n\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error('Invalid YAML format');\n }\n\n // Map kebab-case keys to camelCase\n const config: Partial<AppConfig> = {};\n\n if ('theme' in raw) {\n if (['light', 'dark', 'system'].includes(raw.theme)) {\n config.theme = raw.theme;\n } else {\n console.error(`Warning: Invalid theme value \"${raw.theme}\", using default`);\n }\n }\n\n if ('diff-view' in raw) {\n if (['split', 'unified'].includes(raw['diff-view'])) {\n config.diffView = raw['diff-view'];\n } else {\n console.error(`Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`);\n }\n }\n\n if ('font-size' in raw && typeof raw['font-size'] === 'number') {\n config.fontSize = raw['font-size'];\n }\n\n if ('output-format' in raw && typeof raw['output-format'] === 'string') {\n config.outputFormat = raw['output-format'];\n }\n\n if ('ignore' in raw && Array.isArray(raw.ignore)) {\n config.ignore = raw.ignore.filter((item: unknown) => typeof item === 'string');\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n const usableCategories = raw.categories.filter(\n (cat: unknown): cat is { name: string; description: string; color: string } =>\n cat !== null &&\n typeof cat === 'object' &&\n typeof (cat as Record<string, unknown>).name === 'string' &&\n (cat as Record<string, unknown>).name !== '' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n\n // A `categories` list that leaves no usable entry (empty list, every entry\n // shaped wrong, or every entry named '') would silently disable commenting,\n // so it's treated the same as any other invalid value: warn and keep the default.\n if (usableCategories.length > 0) {\n config.categories = usableCategories;\n } else {\n console.error(\n 'Warning: Category configuration has no usable categories, using default categories'\n );\n }\n }\n\n if ('default-diff-args' in raw && typeof raw['default-diff-args'] === 'string') {\n config.defaultDiffArgs = raw['default-diff-args'];\n }\n\n if ('show-untracked' in raw && typeof raw['show-untracked'] === 'boolean') {\n config.showUntracked = raw['show-untracked'];\n config.showUntrackedExplicit = true;\n }\n\n if ('word-wrap' in raw && typeof raw['word-wrap'] === 'boolean') {\n config.wordWrap = raw['word-wrap'];\n }\n\n if ('max-files' in raw && typeof raw['max-files'] === 'number') {\n config.maxFiles = raw['max-files'] >= 0 ? raw['max-files'] : defaults.maxFiles;\n }\n\n if ('max-total-lines' in raw && typeof raw['max-total-lines'] === 'number') {\n config.maxTotalLines =\n raw['max-total-lines'] >= 0 ? raw['max-total-lines'] : defaults.maxTotalLines;\n }\n\n if (\n 'output-file' in raw &&\n typeof raw['output-file'] === 'string' &&\n raw['output-file'].length > 0\n ) {\n config.outputFile = raw['output-file'];\n }\n\n if (\n 'guide-file' in raw &&\n typeof raw['guide-file'] === 'string' &&\n raw['guide-file'].length > 0\n ) {\n config.guideFile = raw['guide-file'];\n }\n\n return config;\n}\n\nfunction mergeConfig(base: AppConfig, override: Partial<AppConfig>): AppConfig {\n return {\n ...base,\n ...override,\n // Arrays are replaced, not merged\n ignore: override.ignore !== undefined ? override.ignore : base.ignore,\n categories: override.categories !== undefined ? override.categories : base.categories,\n };\n}\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Compute payload statistics and check against configured thresholds.\n * A maxFiles or maxTotalLines value of 0 disables that guard.\n */\nexport function computePayloadStats(\n fileCount: number,\n totalLines: number,\n config: AppConfig\n): PayloadStats {\n const maxFiles = config.maxFiles;\n const maxTotalLines = config.maxTotalLines;\n const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;\n const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;\n return {\n fileCount,\n totalLines,\n exceedsFiles,\n exceedsLines,\n exceedsAny: exceedsFiles || exceedsLines,\n };\n}\n\n/**\n * Count total diff lines across all files and hunks.\n */\nexport function countTotalLines(files: DiffFile[]): number {\n let total = 0;\n for (const file of files) {\n for (const hunk of file.hunks) {\n total += hunk.lines.length;\n }\n }\n return total;\n}\n\n/**\n * Get git diff stats cheaply using --numstat (avoids full diff parsing).\n * Each output line is \"added\\tremoved\\tfilename\".\n * Returns file count and total changed lines (added + removed).\n */\nexport async function getGitDiffStats(\n args: string[],\n repoRoot: string\n): Promise<{ fileCount: number; totalLines: number }> {\n try {\n const { stdout } = await execFileAsync('git', ['diff', '--numstat', ...args], {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 15000,\n cwd: repoRoot,\n });\n\n let fileCount = 0;\n let totalLines = 0;\n\n for (const line of stdout.trim().split('\\n')) {\n if (!line) continue;\n const parts = line.split('\\t');\n if (parts.length < 3) continue;\n\n fileCount++;\n // Binary files show '-' for added/removed\n const added = parts[0] === '-' ? 0 : parseInt(parts[0], 10);\n const removed = parts[1] === '-' ? 0 : parseInt(parts[1], 10);\n totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);\n }\n\n return { fileCount, totalLines };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);\n } else {\n console.error('[payload-sizing] Failed to get git diff stats: unknown error');\n }\n // Return zeros so the guard does not block on failure\n return { fileCount: 0, totalLines: 0 };\n }\n}\n","// src/main/fs-utils.ts\n// Filesystem utility functions for the main process.\n\nimport { accessSync, constants as fsConstants } from 'fs';\nimport { dirname } from 'path';\n\n/**\n * Check if a file's parent directory is writable.\n * Returns true if the directory exists and the process has write permission,\n * false otherwise (including non-existent directories).\n */\nexport function checkWritability(filePath: string): boolean {\n try {\n const dir = dirname(filePath);\n accessSync(dir, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","// apply-suggestion.ts\n// Writes one anchored suggestion into one working file, or refuses and\n// writes nothing. Node-only, Electron-free, and free of process-global\n// state: the caller names the destination root, so nothing here ever\n// consults `process.cwd()`.\n//\n// The engine is deliberately narrow. It performs a byte-for-byte context\n// check and a literal line replacement — no fuzzy matching, no force flag,\n// no staging, no git. Every outcome is reported: a refusal names its reason\n// and leaves the file untouched (PRD Section 5.4.8).\n\nimport { readFileSync, writeFileSync } from 'fs';\nimport { isAbsolute, relative, resolve, sep } from 'path';\nimport type { LineRange, Suggestion } from './types';\n\n/**\n * Why an apply was refused. Every value is a structural fact about the\n * request or the file — never a fragment of the file's contents, so a\n * refusal is safe to surface in the UI and in logs.\n */\nexport type ApplyRefusalReason =\n /** The suggestion is file-level: there is nothing to replace. */\n | 'no-anchor'\n /**\n * The anchor names deleted lines (`side: 'old'`). Those lines are not in\n * the working file, and the app holds no old→new line mapping, so the\n * target is undefined rather than merely missing.\n */\n | 'old-side-anchor'\n /** `destinationRoot` is relative; resolving it would consult the cwd. */\n | 'destination-not-absolute'\n /** `filePath` resolves outside `destinationRoot`. */\n | 'path-escapes-destination'\n /** No file at the resolved path. */\n | 'file-missing'\n /** The path exists but could not be read (permissions, a directory, …). */\n | 'file-unreadable'\n /**\n * The file is not valid UTF-8. Rewriting it would round-trip its bytes\n * through a lossy decode and corrupt regions outside the anchor.\n */\n | 'file-not-utf8'\n /** The anchor falls outside the file's line count. */\n | 'anchor-out-of-range'\n /** The anchored lines no longer match `suggestion.originalCode`. */\n | 'context-mismatch'\n /** The context matched but the write itself failed. */\n | 'write-failed';\n\nexport interface ApplySuggestionRequest {\n /**\n * Absolute path of the directory the reviewed files live in. Always\n * supplied by the caller: a git-mode working tree, a directory-mode root,\n * a reused clone, or the destination the user picked for a temporary-clone\n * review. Never derived here.\n */\n destinationRoot: string;\n /** Path of the file to modify, relative to `destinationRoot`. */\n filePath: string;\n /** The comment's anchor. `null` (file-level) is refused. */\n lineRange: LineRange | null;\n suggestion: Suggestion;\n}\n\nexport interface ApplySuggestionApplied {\n status: 'applied';\n /** Echoed from the request, so a batch caller can attribute the result. */\n filePath: string;\n absolutePath: string;\n /** How many on-disk lines the proposal replaced. */\n replacedLines: number;\n}\n\nexport interface ApplySuggestionRefused {\n status: 'refused';\n filePath: string;\n reason: ApplyRefusalReason;\n /** One sentence naming the refusal, safe to show to the reviewer. */\n detail: string;\n}\n\nexport type ApplySuggestionResult = ApplySuggestionApplied | ApplySuggestionRefused;\n\nfunction refuse(\n filePath: string,\n reason: ApplyRefusalReason,\n detail: string\n): ApplySuggestionRefused {\n return { status: 'refused', filePath, reason, detail };\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return (error as NodeJS.ErrnoException | undefined)?.code;\n}\n\n/**\n * Split file text into lines, keeping each line's own bytes intact.\n *\n * The split is on `\\n` only, so a CRLF file's `\\r` stays at the end of the\n * line it terminates. That makes the comparison against `originalCode`\n * byte-exact (the diff parser hands the same `\\r` through in `DiffLine`),\n * and it means rejoining preserves mixed line endings exactly as found.\n */\nfunction splitLines(content: string): string[] {\n if (content === '') return [];\n const lines = content.split('\\n');\n // A trailing terminator produces an empty final element that is not a line.\n if (lines[lines.length - 1] === '') lines.pop();\n return lines;\n}\n\n/**\n * True when every line being replaced carries a CRLF terminator. Only then\n * is it unambiguous that a hand-typed LF proposal should be written back as\n * CRLF; a mixed or LF region takes the proposal verbatim.\n */\nfunction isCrlfRegion(anchored: string[]): boolean {\n return anchored.length > 0 && anchored.every(line => line.endsWith('\\r'));\n}\n\n/**\n * Apply one anchored suggestion to one file under `destinationRoot`.\n *\n * On a byte-for-byte match between the anchored lines and\n * `suggestion.originalCode`, the anchored lines are replaced with\n * `suggestion.proposedCode` and the file is rewritten. Lines outside the\n * anchor keep their exact bytes, including their line terminators, and the\n * file's trailing-newline state is preserved either way. Any other outcome\n * refuses with a reason and writes nothing.\n */\nexport function applySuggestion(request: ApplySuggestionRequest): ApplySuggestionResult {\n const { destinationRoot, filePath, lineRange, suggestion } = request;\n\n if (!lineRange) {\n return refuse(\n filePath,\n 'no-anchor',\n 'This suggestion is file-level, so there are no lines to replace.'\n );\n }\n if (lineRange.side === 'old') {\n return refuse(\n filePath,\n 'old-side-anchor',\n 'This suggestion is anchored to deleted lines, which are not in the working file.'\n );\n }\n if (!isAbsolute(destinationRoot)) {\n return refuse(\n filePath,\n 'destination-not-absolute',\n 'The destination directory must be an absolute path.'\n );\n }\n\n const root = resolve(destinationRoot);\n const absolutePath = resolve(root, filePath);\n const rel = relative(root, absolutePath);\n if (isAbsolute(filePath) || rel === '' || rel === '..' || rel.startsWith(`..${sep}`)) {\n return refuse(\n filePath,\n 'path-escapes-destination',\n 'The file path resolves outside the destination directory.'\n );\n }\n\n let buffer: Buffer;\n try {\n buffer = readFileSync(absolutePath);\n } catch (error) {\n const code = errorCode(error);\n if (code === 'ENOENT' || code === 'ENOTDIR') {\n return refuse(filePath, 'file-missing', 'The file is not in the destination directory.');\n }\n return refuse(\n filePath,\n 'file-unreadable',\n `The file could not be read (${code ?? 'unknown'}).`\n );\n }\n\n const content = buffer.toString('utf8');\n if (!Buffer.from(content, 'utf8').equals(buffer)) {\n return refuse(filePath, 'file-not-utf8', 'The file is not valid UTF-8 text.');\n }\n\n const lines = splitLines(content);\n const { start, end } = lineRange;\n if (start < 1 || end < start || end > lines.length) {\n return refuse(\n filePath,\n 'anchor-out-of-range',\n `Lines ${start}-${end} are outside this file, which has ${lines.length} line(s).`\n );\n }\n\n const anchored = lines.slice(start - 1, end);\n if (anchored.join('\\n') !== suggestion.originalCode) {\n return refuse(\n filePath,\n 'context-mismatch',\n `Lines ${start}-${end} no longer match the code this suggestion was written against.`\n );\n }\n\n const proposed = suggestion.proposedCode.split('\\n');\n const replacement = isCrlfRegion(anchored)\n ? proposed.map(line => (line.endsWith('\\r') ? line : `${line}\\r`))\n : proposed;\n const updated = [...lines.slice(0, start - 1), ...replacement, ...lines.slice(end)];\n const output = updated.join('\\n') + (content.endsWith('\\n') ? '\\n' : '');\n\n try {\n writeFileSync(absolutePath, output, 'utf8');\n } catch (error) {\n return refuse(\n filePath,\n 'write-failed',\n `The file could not be written (${errorCode(error) ?? 'unknown'}).`\n );\n }\n\n return { status: 'applied', filePath, absolutePath, replacedLines: anchored.length };\n}\n","/**\n * File-type detection utilities.\n *\n * NOTE: This file is intentionally duplicated in packages/react/src/utils/file-type-utils.ts.\n * @self-review/core has Node-only dependencies, so @self-review/react cannot safely import\n * from this package. Both copies must be kept in sync.\n */\n\nconst RASTER_IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.ico', '.bmp']);\nconst MARKDOWN_EXTENSIONS = new Set(['.md', '.markdown']);\nconst HTML_EXTENSIONS = new Set(['.html', '.htm']);\n\nexport type RenderedTextMode = 'markdown' | 'html';\n\nfunction getExtension(filePath: string): string {\n const lastDot = filePath.lastIndexOf('.');\n if (lastDot === -1 || lastDot === filePath.length - 1) return '';\n return filePath.slice(lastDot).toLowerCase();\n}\n\nexport function isPreviewableImage(filePath: string): boolean {\n return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isPreviewableSvg(filePath: string): boolean {\n return getExtension(filePath) === '.svg';\n}\n\nexport function isMarkdownFile(filePath: string): boolean {\n return MARKDOWN_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isHtmlFile(filePath: string): boolean {\n return HTML_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function getRenderedTextMode(filePath: string): RenderedTextMode | null {\n if (isMarkdownFile(filePath)) return 'markdown';\n if (isHtmlFile(filePath)) return 'html';\n return null;\n}\n\nexport function isPreviewableRenderedText(filePath: string): boolean {\n return getRenderedTextMode(filePath) !== null;\n}\n\nexport function getLanguageFromPath(filePath: string): string {\n const ext = filePath.split('.').pop()?.toLowerCase() || '';\n const langMap: Record<string, string> = {\n ts: 'typescript',\n tsx: 'tsx',\n js: 'javascript',\n jsx: 'jsx',\n py: 'python',\n css: 'css',\n json: 'json',\n md: 'markdown',\n markdown: 'markdown',\n sh: 'bash',\n bash: 'bash',\n yml: 'yaml',\n yaml: 'yaml',\n java: 'java',\n go: 'go',\n rs: 'rust',\n sql: 'sql',\n html: 'markup',\n htm: 'markup',\n xml: 'markup',\n rb: 'ruby',\n php: 'php',\n twig: 'twig',\n c: 'c',\n cpp: 'cpp',\n h: 'c',\n hpp: 'cpp',\n // Config and data formats\n ini: 'ini',\n toml: 'toml',\n csv: 'csv',\n diff: 'diff',\n patch: 'diff',\n // Web and infrastructure\n scss: 'scss',\n sass: 'sass',\n graphql: 'graphql',\n gql: 'graphql',\n conf: 'nginx',\n // Database\n mongodb: 'mongodb',\n // Tooling\n makefile: 'makefile',\n mk: 'makefile',\n mak: 'makefile',\n vim: 'vim',\n vimrc: 'vim',\n };\n\n // Check for special filenames without extensions\n const filename = filePath.split('/').pop()?.toLowerCase() || '';\n if (filename === 'dockerfile' || filename.startsWith('dockerfile.')) {\n return 'docker';\n }\n if (filename === 'makefile' || filename.startsWith('makefile.')) {\n return 'makefile';\n }\n if (filename.startsWith('.git')) {\n return 'git';\n }\n if (filename === '.vimrc' || filename.startsWith('.vim')) {\n return 'vim';\n }\n\n return langMap[ext] || 'plaintext';\n}\n","// github-provider.ts\n// GitHub implementation of the ForgeProvider interface, backed entirely by\n// the `gh` CLI through an injectable command runner (never the network\n// directly). Read-only: only `gh pr view` and `gh api` GET calls.\n//\n// GitHub Enterprise-style hosts are honored by passing the URL's host (which\n// may include a port) verbatim to gh: as the HOST/OWNER/REPO form for\n// `pr view --repo` and as `--hostname` for `gh api`. gh's own host handling\n// takes it from there (auth per host, API base URL).\n\nimport {\n ForgeCliUnavailableError,\n type FetchThreadsOptions,\n type ForgeCommandResult,\n type ForgeCommandRunner,\n type ForgeProvider,\n type ForgeThread,\n type ForgeThreadAnchor,\n type ForgeUrl,\n} from './forge-provider';\n\n/** Relevant subset of a GitHub REST pull-request review comment. */\ninterface GitHubReviewComment {\n id: number;\n in_reply_to_id?: number | null;\n /** `null` for deleted user accounts. */\n user: { login: string } | null;\n body: string;\n path: string;\n side?: 'LEFT' | 'RIGHT' | null;\n line: number | null;\n start_line?: number | null;\n original_line?: number | null;\n original_start_line?: number | null;\n}\n\nconst GH_CLI = 'gh';\n\n/**\n * Run a gh command, translating both failure modes into the typed\n * unavailable error: a runner rejection means the CLI could not be spawned\n * (e.g. ENOENT when gh is absent), a non-zero exit means gh ran but failed\n * (unauthenticated, API error). Callers degrade on this error, never crash.\n */\nasync function runGh(runCommand: ForgeCommandRunner, args: string[]): Promise<string> {\n let result: ForgeCommandResult;\n try {\n result = await runCommand(GH_CLI, args);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new ForgeCliUnavailableError('github', GH_CLI, `Failed to run the gh CLI: ${detail}`);\n }\n if (result.exitCode !== 0) {\n const detail = result.stderr.trim() || `exit code ${result.exitCode}`;\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `gh exited with code ${result.exitCode}: ${detail}`\n );\n }\n return result.stdout;\n}\n\n/**\n * Parse gh JSON output, surfacing malformed output as the typed unavailable\n * error so callers keep a single degradation path.\n */\nfunction parseGhJson(stdout: string, context: string): unknown {\n try {\n return JSON.parse(stdout);\n } catch {\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `gh returned unparseable JSON for ${context}`\n );\n }\n}\n\n/**\n * Normalize one review comment's anchor. GitHub reports `line: null` when\n * the comment no longer applies to the head diff (outdated); the\n * `original_*` fields then retain the historic anchor.\n */\nfunction toAnchor(comment: GitHubReviewComment): ForgeThreadAnchor {\n const outdated = comment.line === null || comment.line === undefined;\n const endLine = outdated ? (comment.original_line ?? null) : comment.line;\n const startLine = outdated\n ? (comment.original_start_line ?? comment.original_line ?? null)\n : (comment.start_line ?? comment.line);\n const hasLines = startLine !== null && endLine !== null;\n return {\n filePath: comment.path,\n // Side is meaningless without usable lines; the contract says 'new'.\n side: hasLines && comment.side === 'LEFT' ? 'old' : 'new',\n startLine: hasLines ? startLine : null,\n endLine: hasLines ? endLine : null,\n outdated,\n };\n}\n\n/** GitHub shows deleted user accounts as \"ghost\"; mirror that. */\nfunction toTurn(comment: GitHubReviewComment) {\n return {\n remoteId: String(comment.id),\n author: comment.user?.login ?? 'ghost',\n body: comment.body,\n };\n}\n\n/**\n * Group flat review comments into threads. A comment without\n * `in_reply_to_id` roots a thread; a reply attaches to the thread containing\n * the comment it replies to (root or any member). An orphan reply whose\n * parent is unknown degrades to a thread root of its own. Document order is\n * preserved throughout — nothing sorts.\n */\nfunction groupIntoThreads(comments: GitHubReviewComment[]): ForgeThread[] {\n const threads: ForgeThread[] = [];\n const threadByCommentId = new Map<number, ForgeThread>();\n for (const comment of comments) {\n const parentThread =\n comment.in_reply_to_id === null || comment.in_reply_to_id === undefined\n ? undefined\n : threadByCommentId.get(comment.in_reply_to_id);\n if (parentThread) {\n parentThread.replies.push(toTurn(comment));\n threadByCommentId.set(comment.id, parentThread);\n } else {\n const thread: ForgeThread = {\n root: toTurn(comment),\n replies: [],\n anchor: toAnchor(comment),\n };\n threads.push(thread);\n threadByCommentId.set(comment.id, thread);\n }\n }\n return threads;\n}\n\n/**\n * Create the GitHub {@link ForgeProvider} backed by an injected command\n * runner, mirroring how `git.ts` keeps child-process execution testable.\n */\nexport function createGitHubProvider(runCommand: ForgeCommandRunner): ForgeProvider {\n return {\n forge: 'github',\n\n async fetchBaseBranch(url: ForgeUrl): Promise<string> {\n const stdout = await runGh(runCommand, [\n 'pr',\n 'view',\n String(url.number),\n '--repo',\n `${url.host}/${url.owner}/${url.repo}`,\n '--json',\n 'baseRefName',\n ]);\n const parsed = parseGhJson(stdout, 'pr view') as {\n baseRefName?: unknown;\n };\n if (typeof parsed?.baseRefName !== 'string' || parsed.baseRefName === '') {\n throw new ForgeCliUnavailableError('github', GH_CLI, 'gh pr view returned no baseRefName');\n }\n return parsed.baseRefName;\n },\n\n // The REST review-comment list carries no resolution state, so\n // `options.includeResolved` is deliberately ignored: GitHub fetch\n // returns all review threads (resolved-state filtering is a GitLab\n // concern).\n async fetchThreads(url: ForgeUrl, _options?: FetchThreadsOptions): Promise<ForgeThread[]> {\n const stdout = await runGh(runCommand, [\n 'api',\n `repos/${url.owner}/${url.repo}/pulls/${url.number}/comments`,\n '--hostname',\n url.host,\n '--paginate',\n '--slurp',\n ]);\n // `--paginate --slurp` wraps each response page in an outer array:\n // [[...page1], [...page2]]. Flatten one level to the comment list.\n const pages = parseGhJson(stdout, 'pull request comments');\n if (!Array.isArray(pages)) {\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n 'gh api returned an unexpected payload shape for pull request comments'\n );\n }\n const comments = pages.flat(1) as GitHubReviewComment[];\n return groupIntoThreads(comments);\n },\n };\n}\n","// thread-mapper.ts\n// Deterministic mapper from forge-neutral discussion threads to the v3\n// ReviewComment model. Pure code: no I/O, no randomness, no timestamps —\n// the same input always yields byte-identical output, and it contains no\n// forge-conditional logic (anything forge-specific belongs in the\n// providers). Fetch direction only.\n\nimport type { ForgeThread, ForgeThreadAnchor, ForgeThreadTurn } from './forge-provider';\nimport type { DiffFile, LineRange, Reply, ReviewComment, Suggestion } from './types';\n\n/**\n * Sentinel `filePath` for review-level threads (threads with no file\n * association at all, e.g. GitLab non-diff discussions).\n *\n * The v3 schema has no review-level comment element — every `<comment>`\n * lives inside a `<file path>` — so the mapper degrades these threads to\n * file-level comments on this sentinel path, the closest legal shape.\n * The empty string can never collide with a repository-relative diff path,\n * so consumers (the fetch-comments orchestrator, the app's remote mode)\n * detect review-level comments by comparing against this constant and\n * decide their placement (e.g. a synthetic review-level file entry).\n */\nexport const REVIEW_LEVEL_FILE_PATH = '';\n\n/**\n * Map an anchor to the model's line range, honoring the exactly-one-pair\n * rule: the single `LineRange.side` selects which pair the serializer\n * emits (`'new'` → `new-line-*`, `'old'` → `old-line-*`), so a comment can\n * never carry both.\n *\n * Returns `null` (file-level) when the anchor is outdated, has no usable\n * line information, or carries non-positive lines (the XSD requires\n * `xs:positiveInteger`, and the serializer must never receive an\n * unserializable range). Reversed bounds are normalized rather than\n * rejected so a defective provider payload still maps deterministically.\n */\nfunction mapAnchorToLineRange(anchor: ForgeThreadAnchor): LineRange | null {\n if (anchor.outdated) {\n return null;\n }\n const { startLine, endLine } = anchor;\n if (startLine === null || endLine === null) {\n return null;\n }\n if (startLine < 1 || endLine < 1) {\n return null;\n }\n return {\n side: anchor.side,\n start: Math.min(startLine, endLine),\n end: Math.max(startLine, endLine),\n };\n}\n\n/**\n * Internal ids are in-memory render keys the app normally generates\n * randomly on parse. The mapper must be deterministic, so it derives them\n * from the forge-assigned ids instead.\n */\nfunction internalId(turn: ForgeThreadTurn): string {\n return `remote-${turn.remoteId}`;\n}\n\n/**\n * Opening line of a fenced code block: up to three spaces of indent, then\n * three or more backticks or tildes, then the info string. A fence indented\n * four spaces or more is an indented code block, not a fence.\n */\nconst FENCE_OPEN = /^( {0,3})(`{3,}|~{3,})(.*)$/;\n\n/** Drop a single trailing CR so a CRLF body yields LF-terminated lines. */\nfunction stripCr(line: string): string {\n return line.endsWith('\\r') ? line.slice(0, -1) : line;\n}\n\n/** Remove up to `width` leading spaces, the way CommonMark unindents a fence. */\nfunction stripIndent(line: string, width: number): string {\n let i = 0;\n while (i < width && line[i] === ' ') i++;\n return line.slice(i);\n}\n\n/** A closing fence: the same character, at least as long, nothing after it. */\nfunction isClosingFence(line: string, marker: string): boolean {\n const match = FENCE_OPEN.exec(line);\n return (\n match !== null &&\n match[2][0] === marker[0] &&\n match[2].length >= marker.length &&\n match[3].trim() === ''\n );\n}\n\n/**\n * Collect the bodies of every top-level ` ```suggestion ` block in a\n * markdown body, in document order.\n *\n * Fences are walked in order so a `suggestion` fence nested inside another\n * code block is never mistaken for a real one. The info string must be the\n * bare word `suggestion`: GitLab's range form (`suggestion:-1+2`) widens the\n * anchor by an amount this mapper cannot verify against the diff, so it is\n * deliberately not recognized and leaves the thread without a suggestion.\n */\nfunction findSuggestionBlocks(body: string): string[] {\n const lines = body.split('\\n').map(stripCr);\n const blocks: string[] = [];\n let i = 0;\n while (i < lines.length) {\n const open = FENCE_OPEN.exec(lines[i]);\n if (!open) {\n i++;\n continue;\n }\n const [, indent, marker, info] = open;\n // A backtick fence's info string may not contain a backtick.\n if (marker[0] === '`' && info.includes('`')) {\n i++;\n continue;\n }\n const content: string[] = [];\n let j = i + 1;\n for (; j < lines.length && !isClosingFence(lines[j], marker); j++) {\n content.push(stripIndent(lines[j], indent.length));\n }\n if (info.trim().toLowerCase() === 'suggestion') {\n blocks.push(content.join('\\n'));\n }\n // An unclosed fence runs to the end of the body, as GitHub renders it.\n i = j + 1;\n }\n return blocks;\n}\n\n/**\n * Read the reviewed lines the anchor points at, straight out of the diff.\n *\n * Returns `null` unless the diff covers the whole range: a partially covered\n * anchor would produce an `originalCode` that matches nothing, and the apply\n * engine's byte-for-byte check would refuse it anyway. Taking the text from\n * the diff rather than from the thread body is what makes the extracted\n * suggestion anchored rather than merely quoted.\n */\nfunction readAnchoredLines(\n diffFiles: DiffFile[],\n filePath: string,\n range: LineRange\n): string | null {\n const sidePath = (file: DiffFile) => (range.side === 'old' ? file.oldPath : file.newPath);\n const file =\n diffFiles.find(f => sidePath(f) === filePath) ??\n diffFiles.find(f => f.oldPath === filePath || f.newPath === filePath);\n if (!file) return null;\n\n const found: string[] = [];\n for (const hunk of file.hunks) {\n for (const line of hunk.lines) {\n const number = range.side === 'old' ? line.oldLineNumber : line.newLineNumber;\n if (number !== null && number >= range.start && number <= range.end) {\n found.push(line.content);\n }\n }\n }\n return found.length === range.end - range.start + 1 ? found.join('\\n') : null;\n}\n\n/**\n * Turn a `suggestion` fence in a thread's root body into an anchored\n * {@link Suggestion}, or `null` when there is nothing safe to anchor.\n *\n * `null` covers every uncertain case: no fence, more than one fence (the\n * model holds a single suggestion, and silently keeping the first would drop\n * the rest), a file-level or outdated anchor, and an anchor the reviewed\n * diff does not cover.\n */\nfunction extractSuggestion(\n body: string,\n filePath: string,\n range: LineRange | null,\n diffFiles: DiffFile[]\n): Suggestion | null {\n if (!range) return null;\n const blocks = findSuggestionBlocks(body);\n if (blocks.length !== 1) return null;\n const originalCode = readAnchoredLines(diffFiles, filePath, range);\n if (originalCode === null) return null;\n return { originalCode, proposedCode: blocks[0] };\n}\n\nfunction mapReply(turn: ForgeThreadTurn): Reply {\n return {\n id: internalId(turn),\n body: turn.body,\n author: turn.author,\n remoteId: turn.remoteId,\n };\n}\n\n/**\n * Convert normalized forge threads into v3 `ReviewComment` threads.\n *\n * - The root turn becomes the root comment and owns the anchor; subsequent\n * turns become flat replies in document order (nothing sorts them).\n * - Forge usernames land in `author`, forge thread/comment ids in\n * `remoteId`, markdown bodies pass through verbatim.\n * - Outdated or line-less anchors degrade to file-level comments\n * (`lineRange: null`); anchor-less threads degrade to file-level\n * comments on {@link REVIEW_LEVEL_FILE_PATH}. The degradation is\n * structural, never textual.\n * - Mapped comments carry no category, severity or confidence: forge\n * threads have none, and absent means below every threshold. The empty\n * `category` matches how the XML parser represents a missing category.\n * - A root body carrying a single ` ```suggestion ` fence becomes a\n * `Suggestion` anchored to the thread's line range, with `originalCode`\n * read out of `diffFiles` at that anchor. Without the reviewed diff there\n * is nothing to anchor against, so the default leaves every\n * `suggestion: null` exactly as before.\n *\n * Output order is input order. The input is never mutated.\n */\nexport function mapThreadsToReviewComments(\n threads: ForgeThread[],\n diffFiles: DiffFile[] = []\n): ReviewComment[] {\n return threads.map(thread => {\n const filePath = thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH;\n const lineRange = thread.anchor ? mapAnchorToLineRange(thread.anchor) : null;\n const comment: ReviewComment = {\n id: internalId(thread.root),\n filePath,\n lineRange,\n body: thread.root.body,\n category: '',\n suggestion: extractSuggestion(thread.root.body, filePath, lineRange, diffFiles),\n author: thread.root.author,\n remoteId: thread.root.remoteId,\n };\n if (thread.replies.length > 0) {\n comment.replies = thread.replies.map(mapReply);\n }\n return comment;\n });\n}\n","// gitlab-provider.ts\n// ForgeProvider implementation for GitLab (gitlab.com and self-hosted) backed\n// by the read-only `glab` CLI. All child-process execution goes through an\n// injected ForgeCommandRunner so the provider stays unit-testable and no real\n// `glab` calls happen in tests. Only GET-style commands are issued (`glab\n// api`); nothing is ever posted.\n\nimport {\n ForgeCliUnavailableError,\n type FetchThreadsOptions,\n type ForgeAnchorSide,\n type ForgeCommandRunner,\n type ForgeProvider,\n type ForgeThread,\n type ForgeThreadAnchor,\n type ForgeThreadTurn,\n type ForgeUrl,\n} from './forge-provider';\n\nconst GLAB_CLI = 'glab';\n\n// --- Minimal shapes of the GitLab API payloads we consume ---------------\n\ninterface GitLabLineRangeEdge {\n old_line?: number | null;\n new_line?: number | null;\n}\n\ninterface GitLabPosition {\n old_path?: string | null;\n new_path?: string | null;\n old_line?: number | null;\n new_line?: number | null;\n line_range?: {\n start?: GitLabLineRangeEdge | null;\n end?: GitLabLineRangeEdge | null;\n } | null;\n}\n\ninterface GitLabNote {\n id: number | string;\n body?: string;\n author?: { username?: string } | null;\n system?: boolean;\n resolvable?: boolean;\n resolved?: boolean;\n position?: GitLabPosition | null;\n}\n\ninterface GitLabDiscussion {\n id: string;\n notes?: GitLabNote[];\n}\n\n// --- CLI plumbing -------------------------------------------------------\n\n/** URL-encode the full project path; subgroup slashes become %2F. */\nfunction encodeProjectPath(url: ForgeUrl): string {\n return encodeURIComponent(`${url.owner}/${url.repo}`);\n}\n\nfunction unavailable(message: string): ForgeCliUnavailableError {\n return new ForgeCliUnavailableError('gitlab', GLAB_CLI, message);\n}\n\n/**\n * Run `glab api <endpoint>` against the URL's host and return raw stdout.\n * Spawn failures (ENOENT) and non-zero exits (unauthenticated, API errors)\n * both surface as {@link ForgeCliUnavailableError}.\n */\nasync function runGlabApi(\n runCommand: ForgeCommandRunner,\n url: ForgeUrl,\n endpoint: string,\n extraArgs: string[] = []\n): Promise<string> {\n const args = ['api', endpoint, '--hostname', url.host, ...extraArgs];\n let result;\n try {\n result = await runCommand(GLAB_CLI, args);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw unavailable(`glab CLI could not be spawned: ${detail}`);\n }\n if (result.exitCode !== 0) {\n const detail = result.stderr.trim() || `exit code ${result.exitCode}`;\n throw unavailable(`glab api ${endpoint} failed: ${detail}`);\n }\n return result.stdout;\n}\n\n/**\n * Parse stdout that may contain several concatenated top-level JSON\n * documents, as `glab api --paginate` emits one array per page. A simple\n * bracket/string scanner keeps `][` sequences inside note bodies from\n * breaking the split.\n */\nfunction parseJsonDocuments(text: string): unknown[] {\n const documents: unknown[] = [];\n let depth = 0;\n let inString = false;\n let escaped = false;\n let start = -1;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === '\\\\') {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (ch === '\"') {\n inString = true;\n } else if (ch === '[' || ch === '{') {\n if (depth === 0) start = i;\n depth += 1;\n } else if (ch === ']' || ch === '}') {\n depth -= 1;\n if (depth === 0 && start >= 0) {\n documents.push(JSON.parse(text.slice(start, i + 1)));\n start = -1;\n }\n }\n }\n if (depth !== 0 || inString) {\n throw new Error('truncated JSON document');\n }\n return documents;\n}\n\n// --- Normalization ------------------------------------------------------\n\nfunction toTurn(note: GitLabNote): ForgeThreadTurn {\n return {\n remoteId: String(note.id),\n author: note.author?.username ?? 'unknown',\n body: note.body ?? '',\n };\n}\n\n/**\n * A discussion counts as resolved when it has at least one resolvable note\n * and every resolvable note is resolved. Discussions with no resolvable\n * notes (non-diff discussions) are never \"resolved\".\n */\nfunction isDiscussionResolved(notes: GitLabNote[]): boolean {\n const resolvable = notes.filter(note => note.resolvable === true);\n return resolvable.length > 0 && resolvable.every(note => note.resolved === true);\n}\n\n/**\n * Build the neutral anchor from a GitLab position object, or `null` when the\n * note has no position (non-diff discussion) or the position carries no\n * usable file path.\n *\n * Side selection: `new_line` present → `'new'` (using `new_path`), otherwise\n * `old_line` present → `'old'` (using `old_path`). A position with a path\n * but neither line (e.g. `position_type: \"file\"`) becomes a file-level\n * anchor with null lines and side `'new'`, per the neutral shape's contract.\n * Multi-line `line_range` edges are read on the side chosen above, falling\n * back to the single-line position when an edge lacks that side's line.\n *\n * GitLab has no per-note outdated flag (positions on older heads stay valid\n * positions), so `outdated` is always `false`; drift detection downstream\n * informs the reviewer instead.\n */\nfunction toAnchor(position: GitLabPosition | null | undefined): ForgeThreadAnchor | null {\n if (!position) return null;\n\n const side: ForgeAnchorSide =\n typeof position.old_line === 'number' && typeof position.new_line !== 'number' ? 'old' : 'new';\n const pathForSide = side === 'old' ? position.old_path : position.new_path;\n const filePath = pathForSide ?? position.new_path ?? position.old_path;\n if (!filePath) return null;\n\n const lineOf = (edge: GitLabLineRangeEdge | null | undefined): number | null => {\n const value = side === 'old' ? edge?.old_line : edge?.new_line;\n return typeof value === 'number' ? value : null;\n };\n\n const positionLine = lineOf(position);\n const startLine = lineOf(position.line_range?.start) ?? positionLine;\n const endLine = lineOf(position.line_range?.end) ?? positionLine;\n\n return { filePath, side, startLine, endLine, outdated: false };\n}\n\n/**\n * Normalize one GitLab discussion into the forge-neutral thread shape, or\n * `null` when nothing user-authored remains after dropping system notes.\n * The first surviving note roots the thread and owns the anchor; the rest\n * are ordered replies (GitLab document order is preserved verbatim).\n */\nfunction toThread(discussion: GitLabDiscussion): ForgeThread | null {\n const notes = (discussion.notes ?? []).filter(note => note.system !== true);\n if (notes.length === 0) return null;\n const [rootNote, ...replyNotes] = notes;\n return {\n root: toTurn(rootNote),\n replies: replyNotes.map(toTurn),\n anchor: toAnchor(rootNote.position),\n };\n}\n\n// --- Provider -----------------------------------------------------------\n\n/**\n * Create the GitLab {@link ForgeProvider} backed by the `glab` CLI.\n *\n * The URL's host is forwarded via `--hostname`, so self-hosted instances\n * (e.g. git.drupalcode.org) work with zero configuration beyond `glab auth`.\n * Resolved discussions are excluded unless `includeResolved` is set.\n */\nexport function createGitLabProvider(runCommand: ForgeCommandRunner): ForgeProvider {\n return {\n forge: 'gitlab',\n\n async fetchBaseBranch(url: ForgeUrl): Promise<string> {\n const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}`;\n const stdout = await runGlabApi(runCommand, url, endpoint);\n let mr: unknown;\n try {\n mr = JSON.parse(stdout);\n } catch {\n throw unavailable(`glab api ${endpoint} returned unparseable JSON`);\n }\n const targetBranch = (mr as { target_branch?: unknown })?.target_branch;\n if (typeof targetBranch !== 'string' || targetBranch.length === 0) {\n throw unavailable(`glab api ${endpoint} returned no target_branch`);\n }\n return targetBranch;\n },\n\n async fetchThreads(url: ForgeUrl, options?: FetchThreadsOptions): Promise<ForgeThread[]> {\n const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}/discussions`;\n const stdout = await runGlabApi(runCommand, url, endpoint, ['--paginate']);\n\n let discussions: GitLabDiscussion[];\n try {\n const pages = parseJsonDocuments(stdout);\n if (pages.length === 0 && stdout.trim() !== '') {\n throw new Error('no JSON documents in output');\n }\n discussions = pages.flatMap(page =>\n Array.isArray(page) ? (page as GitLabDiscussion[]) : []\n );\n } catch {\n throw unavailable(`glab api ${endpoint} returned unparseable JSON`);\n }\n\n const includeResolved = options?.includeResolved === true;\n const threads: ForgeThread[] = [];\n for (const discussion of discussions) {\n const notes = discussion.notes ?? [];\n if (!includeResolved && isDiscussionResolved(notes)) continue;\n const thread = toThread(discussion);\n if (thread) threads.push(thread);\n }\n return threads;\n },\n };\n}\n","// materializer.ts\n// Clone-aware diff materializer: turns a parsed forge URL into a local git\n// context. Reuses an existing matching clone (fetch only, no working-tree\n// changes) or creates a disposable blobless clone under the OS temp root,\n// then reports the resolved base/head SHAs so downstream code can run the\n// existing local git-mode pipeline over `baseSha...headSha`.\n//\n// All git interaction goes through an injectable command runner (the same\n// shape providers use) so unit tests never spawn real git. This module never\n// talks to a forge API: head refs come from the forges' well-known git refs\n// (`refs/pull/N/head`, `refs/merge-requests/N/head`) over plain git.\n\nimport { execFile } from 'child_process';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { stripTrailingNewline } from './git';\nimport type { ForgeCommandResult, ForgeCommandRunner, ForgeUrl } from './forge-provider';\n\n/** How the local git context was obtained. */\nexport type MaterializeMode = 'existing-clone' | 'temp-clone';\n\n/** Result of materializing a forge URL into a local git context. */\nexport interface MaterializeResult {\n /** Root of the git repository to run the diff pipeline in. */\n repoPath: string;\n /** Resolved SHA of the PR/MR base branch tip. */\n baseSha: string;\n /** Resolved SHA of the PR/MR head (the live remote head). */\n headSha: string;\n mode: MaterializeMode;\n /**\n * Removes the temp clone directory when one was created this run; a no-op\n * for the existing-clone mode. Safe to call more than once. Only ever\n * deletes a directory this materializer created.\n */\n cleanup: () => void;\n}\n\n/** A local clone whose fetch remote matches the requested forge repository. */\nexport interface ExistingClone {\n repoPath: string;\n remoteName: string;\n}\n\n/** Local namespaced refs the materializer fetches into (never branches). */\nconst LOCAL_BASE_REF = 'refs/self-review/base';\nconst LOCAL_HEAD_REF = 'refs/self-review/head';\n\nconst AUTH_HINT =\n 'Hint: if this repository is private or requires authentication, run ' +\n '`gh auth setup-git` (GitHub) or `glab auth git-credential` (GitLab) to ' +\n 'wire your CLI credentials into git.';\n\n/**\n * Default runner: spawns real git. Resolves with the exit code on any\n * completed run (including non-zero); rejects only when git cannot be\n * spawned at all (e.g. ENOENT).\n */\nexport const defaultGitRunner: ForgeCommandRunner = (command, args) =>\n new Promise<ForgeCommandResult>((resolve, reject) => {\n execFile(command, args, { maxBuffer: 50 * 1024 * 1024 }, (error, stdout, stderr) => {\n const spawnCode = (error as NodeJS.ErrnoException | null)?.code;\n if (error && typeof spawnCode === 'string') {\n reject(error);\n return;\n }\n resolve({\n stdout: stdout ?? '',\n stderr: stderr ?? '',\n exitCode: error ? (typeof spawnCode === 'number' ? spawnCode : 1) : 0,\n });\n });\n });\n\n/** Well-known git ref for the PR/MR head on each forge. */\nfunction headRefFor(url: ForgeUrl): string {\n return url.forge === 'github'\n ? `refs/pull/${url.number}/head`\n : `refs/merge-requests/${url.number}/head`;\n}\n\n/**\n * HTTPS clone URL for the forge repository. Git's credential machinery\n * (helpers, `gh auth setup-git`) handles auth; no transport selection here.\n */\nfunction cloneUrlFor(url: ForgeUrl): string {\n return `https://${url.host}/${url.owner}/${url.repo}.git`;\n}\n\nfunction gitFailure(what: string, result: ForgeCommandResult, withAuthHint: boolean): Error {\n const stderr = result.stderr.trim();\n const lines = [\n `git ${what} failed (exit code ${result.exitCode})${stderr ? `:\\n${stderr}` : ''}`,\n ];\n if (withAuthHint) {\n lines.push('', AUTH_HINT);\n }\n return new Error(lines.join('\\n'));\n}\n\n/** Strip a trailing `.git` and trailing slashes from a repo path. */\nfunction stripRepoPath(repoPath: string): string {\n return repoPath.replace(/\\/+$/, '').replace(/\\.git$/i, '');\n}\n\n/**\n * Normalize a git remote URL (SSH scp-style, ssh://, http(s)://) into a\n * comparable `{ host, path }` pair, or `null` when unrecognized.\n */\nfunction normalizeRemoteUrl(raw: string): { host: string; path: string } | null {\n const trimmed = raw.trim();\n if (trimmed.includes('://')) {\n try {\n const parsed = new URL(trimmed);\n return {\n host: parsed.host.toLowerCase(),\n path: stripRepoPath(parsed.pathname.replace(/^\\/+/, '')).toLowerCase(),\n };\n } catch {\n return null;\n }\n }\n // scp-style: [user@]host:path\n const scp = /^(?:[^@\\s]+@)?([^:/\\s]+):(.+)$/.exec(trimmed);\n if (scp) {\n return {\n host: scp[1].toLowerCase(),\n path: stripRepoPath(scp[2].replace(/^\\/+/, '')).toLowerCase(),\n };\n }\n return null;\n}\n\n/**\n * Parse `git remote -v` output and return the name of the first remote whose\n * fetch URL matches the forge URL's host and owner/repo, or `null`.\n */\nfunction findMatchingRemote(remoteVOutput: string, url: ForgeUrl): string | null {\n const wantedHost = url.host.toLowerCase();\n const wantedPath = `${url.owner}/${url.repo}`.toLowerCase();\n for (const line of remoteVOutput.split('\\n')) {\n const match = /^(\\S+)\\t(.+?)\\s+\\(fetch\\)$/.exec(line.trim());\n if (!match) continue;\n const normalized = normalizeRemoteUrl(match[2]);\n if (normalized && normalized.host === wantedHost && normalized.path === wantedPath) {\n return match[1];\n }\n }\n return null;\n}\n\nasync function revParse(\n runner: ForgeCommandRunner,\n repoPath: string,\n ref: string\n): Promise<string> {\n const result = await runner('git', ['-C', repoPath, 'rev-parse', ref]);\n if (result.exitCode !== 0) {\n throw gitFailure(`rev-parse ${ref}`, result, false);\n }\n return result.stdout.trim();\n}\n\n/**\n * Detect an existing clone: when `cwd` is inside a git repository with a\n * remote matching the forge URL, return `{ repoPath, remoteName }`.\n */\nexport async function detectExistingClone(\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner = defaultGitRunner\n): Promise<ExistingClone | null> {\n const toplevel = await runner('git', ['-C', cwd, 'rev-parse', '--show-toplevel']);\n if (toplevel.exitCode !== 0) {\n return null;\n }\n // A blanket .trim() would eat whitespace that is part of the actual path\n // (SR-0047, same defect class as SR-0036's git.ts fix), reporting a root\n // short of what's on disk and breaking the `remote -v` call right after.\n const repoPath = stripTrailingNewline(toplevel.stdout);\n const remotes = await runner('git', ['-C', repoPath, 'remote', '-v']);\n if (remotes.exitCode !== 0) {\n return null;\n }\n const remoteName = findMatchingRemote(remotes.stdout, url);\n return remoteName === null ? null : { repoPath, remoteName };\n}\n\nasync function materializeIntoExistingClone(\n runner: ForgeCommandRunner,\n url: ForgeUrl,\n baseBranch: string,\n repoPath: string,\n remoteName: string\n): Promise<MaterializeResult> {\n console.error(`self-review: reusing existing clone at ${repoPath} (remote \"${remoteName}\")`);\n // Fetch into namespaced local refs only: no checkout, no branch creation,\n // no working-tree change. Forced refspecs are fine — these refs are ours.\n const fetch = await runner('git', [\n '-C',\n repoPath,\n 'fetch',\n remoteName,\n `+refs/heads/${baseBranch}:${LOCAL_BASE_REF}`,\n `+${headRefFor(url)}:${LOCAL_HEAD_REF}`,\n ]);\n if (fetch.exitCode !== 0) {\n throw gitFailure(`fetch from remote \"${remoteName}\"`, fetch, true);\n }\n return {\n repoPath,\n baseSha: await revParse(runner, repoPath, LOCAL_BASE_REF),\n headSha: await revParse(runner, repoPath, LOCAL_HEAD_REF),\n mode: 'existing-clone',\n cleanup: () => {},\n };\n}\n\nasync function materializeIntoTempClone(\n runner: ForgeCommandRunner,\n url: ForgeUrl,\n baseBranch: string\n): Promise<MaterializeResult> {\n // This run creates the directory, so cleanup may only ever remove it.\n const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'self-review-'));\n let removed = false;\n const cleanup = () => {\n if (removed) return;\n removed = true;\n fs.rmSync(tempDir, { recursive: true, force: true });\n };\n\n try {\n console.error(`self-review: created temporary blobless clone at ${tempDir}`);\n const cloneUrl = cloneUrlFor(url);\n // Blobless, never shallow: --depth would break merge-base computation.\n const clone = await runner('git', ['clone', '--filter=blob:none', cloneUrl, tempDir]);\n if (clone.exitCode !== 0) {\n throw gitFailure(`clone of ${cloneUrl}`, clone, true);\n }\n const fetch = await runner('git', [\n '-C',\n tempDir,\n 'fetch',\n 'origin',\n `+${headRefFor(url)}:${LOCAL_HEAD_REF}`,\n ]);\n if (fetch.exitCode !== 0) {\n throw gitFailure(`fetch of ${headRefFor(url)}`, fetch, true);\n }\n return {\n repoPath: tempDir,\n baseSha: await revParse(runner, tempDir, `origin/${baseBranch}`),\n headSha: await revParse(runner, tempDir, LOCAL_HEAD_REF),\n mode: 'temp-clone',\n cleanup,\n };\n } catch (error) {\n cleanup();\n throw error;\n }\n}\n\n/**\n * Materialize a forge PR/MR into a local git context.\n *\n * When `cwd` is inside a git repository with a remote matching the forge\n * URL (SSH and HTTPS forms recognized, `.git` suffix tolerated), the base\n * branch and PR/MR head refs are fetched into that clone under\n * `refs/self-review/*` — read-only for the working tree. Otherwise a\n * blobless clone is created in a unique directory under the OS temp root\n * and `cleanup()` removes exactly that directory. Callers that already\n * detected a clone may pass it to avoid repeating the git probes.\n *\n * The returned `headSha` is the live remote head, so callers can compare it\n * against a recorded `remote-head-sha` for drift detection.\n */\nexport async function materialize(\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner = defaultGitRunner,\n existingClone?: ExistingClone | null\n): Promise<MaterializeResult> {\n const existing =\n existingClone === undefined ? await detectExistingClone(url, cwd, runner) : existingClone;\n if (existing) {\n return materializeIntoExistingClone(\n runner,\n url,\n baseBranch,\n existing.repoPath,\n existing.remoteName\n );\n }\n return materializeIntoTempClone(runner, url, baseBranch);\n}\n\n/**\n * Git-only fallback for the base branch when no forge CLI is available:\n * resolves the remote's default branch from its HEAD symref via\n * `git ls-remote --symref <remote> HEAD`. When an existing matching clone\n * is supplied, the configured remote is used so its SSH/HTTPS transport\n * and credentials are preserved. Otherwise the forge HTTPS URL is used.\n * No forge API involved.\n */\nexport async function resolveRemoteDefaultBranch(\n url: ForgeUrl,\n runner: ForgeCommandRunner = defaultGitRunner,\n existing: ExistingClone | null = null\n): Promise<string> {\n const cloneUrl = cloneUrlFor(url);\n const remote = existing?.remoteName ?? cloneUrl;\n // Errors must identify the repository; a bare alias such as \"origin\"\n // does not say which repository the lookup was made against.\n const label = existing ? `${remote} (${cloneUrl})` : cloneUrl;\n const args = existing\n ? ['-C', existing.repoPath, 'ls-remote', '--symref', remote, 'HEAD']\n : ['ls-remote', '--symref', remote, 'HEAD'];\n const result = await runner('git', args);\n if (result.exitCode !== 0) {\n throw gitFailure(`ls-remote of ${label}`, result, true);\n }\n const match = /^ref:\\s+refs\\/heads\\/(\\S+)\\s+HEAD$/m.exec(result.stdout);\n if (!match) {\n throw new Error(\n `Failed to resolve the default branch of ${label}: ` +\n 'git ls-remote returned no HEAD symref.'\n );\n }\n return match[1];\n}\n","// packages/core/src/review-handlers.ts\n// Transport-agnostic review handler bodies.\n//\n// Every function here takes the session it operates on as a parameter and\n// returns a value. Nothing in this module reaches state that is not reachable\n// through that parameter, and nothing in it touches Electron: the registration\n// layer (src/main/ipc-handlers.ts) owns the transport and does the sending.\n\nimport * as fs from 'fs';\nimport path from 'path';\nimport {\n DiffLoadPayload,\n DiffHunk,\n ResumeLoadPayload,\n GuideLoadPayload,\n AppConfig,\n OutputPathInfo,\n PayloadStats,\n ReviewState,\n ReviewComment,\n ExpandContextRequest,\n ImageLoadResult,\n RemoteDriftInfo,\n SuggestionApplyRequest,\n SuggestionApplyOutcome,\n ApplyDestinationOutcome,\n} from './types';\nimport { scanDirectory, scanFile } from './directory-scanner';\nimport { tokenizeGitDiffArgs } from './git-diff-args';\nimport { computePayloadStats, countTotalLines } from './payload-sizing';\nimport { applySuggestion } from './apply-suggestion';\n\n/**\n * The state a single review session owns. One desktop application window is\n * one session; two sessions are independent and cannot observe each other.\n */\nexport interface ReviewSession {\n reviewState: ReviewState | null;\n diffData: DiffLoadPayload | null;\n guideData: GuideLoadPayload | null;\n config: AppConfig | null;\n outputPathInfo: OutputPathInfo | null;\n resumeComments: ReviewComment[];\n resumeViewedFiles: string[];\n resumeRemoteDrift: RemoteDriftInfo | null;\n /**\n * Destination directory the user named for this session's applies, or\n * null when none has been named. Only a temporary-clone remote review\n * needs one; see {@link resolveApplyDestination}.\n */\n applyDestinationRoot: string | null;\n}\n\n/** Create an empty session. */\nexport function createReviewSession(): ReviewSession {\n return {\n reviewState: null,\n diffData: null,\n guideData: null,\n config: null,\n outputPathInfo: null,\n resumeComments: [],\n resumeViewedFiles: [],\n resumeRemoteDrift: null,\n applyDestinationRoot: null,\n };\n}\n\n/**\n * Prepare a DiffLoadPayload for IPC transmission.\n * In large-payload mode, strips hunks from files to reduce initial transfer size.\n * The full data stays in the session for on-demand loading via DIFF_LOAD_FILE.\n */\nexport function preparePayload(payload: DiffLoadPayload): DiffLoadPayload {\n if (payload.isLargePayload) {\n return {\n ...payload,\n files: payload.files.map(f => ({ ...f, hunks: [] as DiffHunk[], contentLoaded: false })),\n };\n }\n return {\n ...payload,\n files: payload.files.map(f => ({ ...f, contentLoaded: true })),\n };\n}\n\n/**\n * Resolve what a diff request should deliver: the prepared diff payload and,\n * when one is loaded, the guide that rides with it. Returns null when the\n * session has no diff, so the caller sends nothing at all.\n */\nexport function getDiffLoad(\n session: ReviewSession\n): { diff: DiffLoadPayload; guide: GuideLoadPayload | null } | null {\n if (!session.diffData) {\n return null;\n }\n // The guide rides after the diff payload in both normal and\n // large-payload modes — it is metadata-only (paths, names,\n // descriptions) and never triggers eager hunk loading.\n return {\n diff: preparePayload(session.diffData),\n guide: session.guideData,\n };\n}\n\n/**\n * The directory the session's reviewed paths are relative to, or null when the\n * session has no diff yet.\n *\n * Scanner paths are relative to the reviewed directory, or to the reviewed\n * file's parent. Git paths are relative to the repository, which in remote\n * mode is the materialized clone.\n */\nexport function resolveSourceBaseDir(session: ReviewSession): string | null {\n const source = session.diffData?.source;\n if (!source) return null;\n if (source.type === 'git') return source.repository;\n if (source.type === 'directory') return source.sourcePath;\n if (source.type === 'file') return path.dirname(source.sourcePath);\n return null;\n}\n\n/**\n * Load a binary image as a base64 data URI for the rendered preview.\n */\nexport async function loadImage(\n session: ReviewSession,\n filePath: string\n): Promise<ImageLoadResult> {\n const MIME_MAP: Record<string, string> = {\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.bmp': 'image/bmp',\n '.svg': 'image/svg+xml',\n };\n const MAX_SIZE = 10 * 1024 * 1024; // 10 MB\n const baseDir = resolveSourceBaseDir(session) ?? process.cwd();\n const resolved = path.isAbsolute(filePath) ? filePath : path.resolve(baseDir, filePath);\n const ext = path.extname(filePath).toLowerCase();\n const mimeType = MIME_MAP[ext] ?? 'application/octet-stream';\n\n // In a remote session the reviewed content lives at the fetched head\n // SHA, not in the clone's working tree (a temporary clone stays on the\n // default branch), so read the blob through git instead of the fs.\n const remote = session.diffData?.remote;\n if (remote && session.diffData?.source.type === 'git') {\n try {\n const { readGitBlobAsync } = await import('./git');\n const data = await readGitBlobAsync(\n session.diffData.source.repository,\n `${remote.remoteHeadSha}:${filePath}`\n );\n if (data.length > MAX_SIZE) {\n return { error: 'File too large to preview (>10 MB)' };\n }\n return { dataUri: `data:${mimeType};base64,${data.toString('base64')}` };\n } catch {\n return {\n error: 'Image preview unavailable — blob not found at the reviewed commit.',\n };\n }\n }\n\n try {\n const stat = await fs.promises.stat(resolved);\n if (stat.size > MAX_SIZE) {\n return { error: 'File too large to preview (>10 MB)' };\n }\n const data = await fs.promises.readFile(resolved);\n return { dataUri: `data:${mimeType};base64,${data.toString('base64')}` };\n } catch {\n return { error: 'Image preview unavailable — file not found on disk.' };\n }\n}\n\n/**\n * Return a single file's hunks for lazy (large-payload) mode, or null when the\n * session has no diff or the diff has no such file.\n */\nexport function getFileHunks(session: ReviewSession, filePath: string): DiffHunk[] | null {\n if (!session.diffData) return null;\n const file = session.diffData.files.find(f => (f.newPath || f.oldPath) === filePath);\n if (!file) return null;\n return file.hunks;\n}\n\n/**\n * Resolve the config and the output path info that travel with it. Returns null\n * when the session has no config, so the caller sends nothing at all: the\n * renderer distinguishes an absent message from an empty one.\n */\nexport function getConfigLoad(\n session: ReviewSession\n): { config: AppConfig; outputPathInfo: OutputPathInfo | null } | null {\n if (!session.config) {\n return null;\n }\n return { config: session.config, outputPathInfo: session.outputPathInfo };\n}\n\n/**\n * Store a review state submitted by the front end on the session.\n */\nexport function submitReviewState(session: ReviewSession, state: ReviewState): void {\n console.error(\n '[review] Review state submitted:',\n JSON.stringify({\n timestamp: state.timestamp,\n source: state.source,\n fileCount: state.files.length,\n })\n );\n session.reviewState = state;\n}\n\n/**\n * Take the submitted review state off the session, clearing it so it is\n * consumed exactly once. Returns null when nothing has been submitted.\n */\nexport function takeReviewState(session: ReviewSession): ReviewState | null {\n const state = session.reviewState;\n session.reviewState = null;\n return state;\n}\n\n/**\n * True when this session reviews a remote PR/MR that was materialized into\n * a temporary clone. That clone is removed when the app exits, so a write\n * into it is lost the moment the review ends (PRD Section 5.4.8).\n */\nexport function isTemporaryCloneSession(session: ReviewSession): boolean {\n return session.diffData?.remote?.temporaryClone === true;\n}\n\n/** Canonical form of a path, following symlinks when the path exists. */\nfunction canonicalize(target: string): string {\n try {\n return fs.realpathSync(target);\n } catch {\n return path.resolve(target);\n }\n}\n\n/** True when `candidate` is `root` itself or sits anywhere beneath it. */\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(canonicalize(root), canonicalize(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/**\n * The directory an apply may write into for this session, or null when the\n * session has none.\n *\n * For every review whose files sit in a place the user controls — a git\n * working tree, a scanned directory, a reused remote clone — that is the\n * root the reviewed paths are relative to, and no one is asked anything.\n *\n * A temporary-clone review is the one exception. Its files live in a\n * directory the app deletes on exit, so the clone is never a destination:\n * the answer is the directory the user named, and null until they name one.\n */\nexport function resolveApplyDestination(session: ReviewSession): string | null {\n if (isTemporaryCloneSession(session)) {\n return session.applyDestinationRoot;\n }\n return resolveSourceBaseDir(session);\n}\n\n/**\n * Record the directory the user named as this session's apply destination.\n *\n * The caller supplies a path the user picked; this decides whether it can\n * be written into and stores it only if so. The temporary clone, and\n * anything inside it, is refused however it was reached — that directory\n * is gone when the review ends, which is the whole reason a destination is\n * asked for.\n */\nexport function setApplyDestination(\n session: ReviewSession,\n directoryPath: string\n): ApplyDestinationOutcome {\n if (!path.isAbsolute(directoryPath)) {\n return {\n status: 'rejected',\n reason: 'destination-not-absolute',\n detail: 'Pick a destination by its full path.',\n };\n }\n\n let isDirectory = false;\n try {\n isDirectory = fs.statSync(directoryPath).isDirectory();\n } catch {\n isDirectory = false;\n }\n if (!isDirectory) {\n return {\n status: 'rejected',\n reason: 'destination-not-a-directory',\n detail: 'That destination is not a directory that exists.',\n };\n }\n\n const clonePath = isTemporaryCloneSession(session) ? resolveSourceBaseDir(session) : null;\n if (clonePath && isWithin(clonePath, directoryPath)) {\n return {\n status: 'rejected',\n reason: 'destination-inside-temporary-clone',\n detail:\n 'That directory is inside the temporary clone, which is deleted when the review ends.',\n };\n }\n\n session.applyDestinationRoot = canonicalize(directoryPath);\n console.error(`[suggestion:apply] destination set for this session`);\n return { status: 'chosen', destinationRoot: session.applyDestinationRoot };\n}\n\n/**\n * Apply one suggestion to the reviewed working file, or refuse and write\n * nothing. The engine in `apply-suggestion.ts` does the work; this handler\n * only names the destination the session reviews, which the engine never\n * derives for itself.\n *\n * A refusal travels as a value, never as a thrown error. The front end\n * renders its `detail` next to the suggestion the attempt came from.\n */\nexport function applySuggestionForSession(\n session: ReviewSession,\n request: SuggestionApplyRequest\n): SuggestionApplyOutcome {\n const destinationRoot = resolveApplyDestination(session);\n if (!destinationRoot) {\n const temporary = isTemporaryCloneSession(session);\n return {\n status: 'refused',\n filePath: request.filePath,\n reason: temporary ? 'destination-required' : 'no-destination',\n detail: temporary\n ? 'This pull request was cloned into a temporary directory that is deleted when the review ends. Choose a destination directory to apply into.'\n : 'This review has no working directory to write into.',\n };\n }\n\n const result = applySuggestion({\n destinationRoot,\n filePath: request.filePath,\n lineRange: request.lineRange,\n suggestion: request.suggestion,\n });\n console.error(\n `[suggestion:apply] ${request.filePath}: ${\n result.status === 'applied' ? 'applied' : `refused (${result.reason})`\n }`\n );\n\n // Projected field by field rather than passed through. The engine also\n // reports the resolved absolute path, which the front end has no use for\n // and should not be handed; naming the fields here keeps the wire shape\n // exactly what SuggestionApplyOutcome declares, today and after the engine\n // grows a field.\n if (result.status === 'applied') {\n return {\n status: 'applied',\n filePath: result.filePath,\n replacedLines: result.replacedLines,\n };\n }\n return {\n status: 'refused',\n filePath: result.filePath,\n reason: result.reason,\n detail: result.detail,\n };\n}\n\n/**\n * Read an attachment file from disk, as an ArrayBuffer the front end can use.\n * Returns null when the file cannot be read.\n */\nexport async function readAttachment(filePath: string) {\n try {\n const buffer = await fs.promises.readFile(filePath);\n return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n } catch {\n console.error(`[attachment:read] Failed to read file: ${filePath}`);\n return null;\n }\n}\n\n/**\n * Resolve the resumed comments, viewed files and remote drift for a session.\n * Returns null when there is nothing to resume, so the caller sends nothing\n * at all.\n */\nexport function getResumeLoad(session: ReviewSession): ResumeLoadPayload | null {\n if (\n session.resumeComments.length > 0 ||\n session.resumeViewedFiles.length > 0 ||\n session.resumeRemoteDrift !== null\n ) {\n const payload: ResumeLoadPayload = {\n comments: session.resumeComments,\n viewedFiles: session.resumeViewedFiles,\n };\n if (session.resumeRemoteDrift !== null) {\n payload.remoteDrift = session.resumeRemoteDrift;\n }\n return payload;\n }\n return null;\n}\n\n/**\n * Expand the context of a single file by re-running git diff with more context\n * lines. The expanded hunks are written back to the session's diff data so a\n * later file load on the same session sees them. Returns null when the session\n * has no git diff, when nothing parses, or when git fails.\n */\nexport async function expandContext(\n session: ReviewSession,\n request: ExpandContextRequest\n): Promise<{ hunks: DiffHunk[]; totalLines: number } | null> {\n const diffData = session.diffData;\n if (!diffData || diffData.source.type !== 'git') {\n return null;\n }\n\n try {\n const { runGitDiffAsync } = await import('./git');\n const { parseDiff } = await import('./diff-parser');\n\n const source = diffData.source;\n // Shell-style tokenizing, the inverse of how the source string was\n // written: a search string or path with a space comes back as one\n // argument instead of several.\n const originalArgs = tokenizeGitDiffArgs(source.gitDiffArgs);\n\n // Strip -U/--unified flags. Stop at `--` — paths after it were the\n // original path restriction; the specific file is supplied below.\n const filteredArgs: string[] = [];\n for (let i = 0; i < originalArgs.length; i++) {\n const arg = originalArgs[i];\n if (arg.match(/^-U\\d+$/) || arg.match(/^--unified=\\d+$/)) {\n continue;\n }\n if (arg === '-U' || arg === '--unified') {\n i++; // skip next arg (the number)\n continue;\n }\n if (arg === '--') {\n break;\n }\n filteredArgs.push(arg);\n }\n\n const expandArgs = [...filteredArgs, `-U${request.contextLines}`, '--', request.filePath];\n\n // Run in the diff's repository root — in remote mode this is the\n // materialized clone, not the process cwd.\n const rawDiff = await runGitDiffAsync(expandArgs, source.repository);\n const parsedFiles = parseDiff(rawDiff);\n\n if (parsedFiles.length === 0) {\n return null;\n }\n\n const expandedFile = parsedFiles[0];\n\n // Count total lines in the working tree file for gap detection.\n // Diff paths are repository-relative — resolve accordingly.\n let totalLines = 0;\n try {\n const content = await fs.promises.readFile(\n path.resolve(source.repository, request.filePath),\n 'utf-8'\n );\n totalLines = content.split('\\n').length;\n // If file ends with newline, last split element is empty — don't count it\n if (content.endsWith('\\n')) totalLines--;\n } catch {\n // Can't determine line count — leave as 0 (bars will stay visible)\n }\n\n // Update the session's diff data\n session.diffData = {\n ...diffData,\n files: diffData.files.map(f => {\n const fPath = f.newPath || f.oldPath;\n if (fPath === request.filePath) {\n return { ...f, hunks: expandedFile.hunks };\n }\n return f;\n }),\n };\n\n return { hunks: expandedFile.hunks, totalLines };\n } catch (error) {\n console.error(`[review] Failed to expand context for ${request.filePath}:`, error);\n return null;\n }\n}\n\n/**\n * What a review start produced: the payload built from the scanned path, the\n * stats it was measured against (null when the session has no config, in which\n * case no thresholds apply), and whether those stats exceeded a threshold.\n *\n * The payload is deliberately *not* stored on the session: the caller may still\n * need to abandon it (a user declining a large review keeps the review they\n * were already looking at), so committing it is the caller's decision.\n */\nexport interface ReviewStartResult {\n payload: DiffLoadPayload;\n stats: PayloadStats | null;\n exceedsThresholds: boolean;\n}\n\n/**\n * Scan a picked path and build the diff payload for a directory (or single\n * file) review, measured against the session's large-payload thresholds.\n * Nothing is stored on the session — see `ReviewStartResult`.\n */\nexport async function prepareDirectoryReview(\n session: ReviewSession,\n directoryPath: string\n): Promise<ReviewStartResult> {\n console.error('[review] Starting directory review for:', directoryPath);\n\n // Check if the path is a file (not a directory)\n let isFile = false;\n try {\n isFile = fs.statSync(directoryPath).isFile();\n } catch {\n // Failed to stat — proceed as directory\n }\n\n let payload: DiffLoadPayload;\n if (isFile) {\n const files = await scanFile(directoryPath);\n payload = {\n files,\n source: { type: 'file', sourcePath: directoryPath },\n };\n } else {\n // Directory mode: scan all files as new additions\n const ignorePatterns = session.config?.ignore ?? [];\n const files = await scanDirectory(directoryPath, ignorePatterns);\n payload = {\n files,\n source: { type: 'directory', sourcePath: directoryPath },\n };\n }\n\n // Large payload guard — skipped entirely when there is no config.\n if (!session.config) {\n return { payload, stats: null, exceedsThresholds: false };\n }\n const stats = computePayloadStats(\n payload.files.length,\n countTotalLines(payload.files),\n session.config\n );\n return { payload, stats, exceedsThresholds: stats.exceedsAny };\n}\n\n/**\n * Commit a prepared review payload to the session, once the caller has decided\n * it should proceed. Returns the payload to hand to the transport.\n */\nexport function commitReviewStart(\n session: ReviewSession,\n payload: DiffLoadPayload\n): DiffLoadPayload {\n session.diffData = payload;\n return preparePayload(payload);\n}\n","// packages/core/src/git-diff-args.ts\n// Normalization of pass-through git diff arguments.\n\nimport { existsSync } from 'fs';\nimport { resolve } from 'path';\n\n// Only options whose bare spelling consumes the next argument belong here.\n// Optional values (for example --color, --relative and -U) must be attached.\nconst OPTIONS_WITH_SEPARATE_VALUES = new Set([\n '--output',\n '--src-prefix',\n '--dst-prefix',\n '--line-prefix',\n '--output-indicator-new',\n '--output-indicator-old',\n '--output-indicator-context',\n '--inter-hunk-context',\n '--stat-width',\n '--stat-name-width',\n '--stat-graph-width',\n '--stat-count',\n '--diff-algorithm',\n '--word-diff-regex',\n '--ignore-matching-lines',\n '--anchored',\n '--diff-filter',\n '--find-object',\n '--rotate-to',\n '--skip-to',\n '--ws-error-highlight',\n '--color-moved-ws',\n]);\n\nfunction consumesNextArgument(arg: string): boolean {\n if (arg.startsWith('--')) return OPTIONS_WITH_SEPARATE_VALUES.has(arg);\n if (!arg.startsWith('-')) return false;\n // Git accepts short-option groups, such as -pS pattern. Once an option\n // takes a value, the rest of that token is its attached value, if present.\n for (let i = 1; i < arg.length; i++) {\n if ('SGOIl'.includes(arg[i])) return i === arg.length - 1;\n if ('UBMC'.includes(arg[i])) return false; // optional, attached values\n }\n return false;\n}\n\n/** Identify positional arguments without mistaking option values for paths. */\nexport function classifyGitDiffArgs(args: string[]): {\n positionalIndices: number[];\n hasSeparator: boolean;\n} {\n const positionalIndices: number[] = [];\n let hasSeparator = false;\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (!hasSeparator) {\n if (arg === '--') {\n hasSeparator = true;\n continue;\n }\n if (consumesNextArgument(arg)) {\n i++;\n continue;\n }\n if (arg.startsWith('-')) continue;\n }\n positionalIndices.push(i);\n }\n return { positionalIndices, hasSeparator };\n}\n\n/**\n * Insert `--` before the first non-flag positional arg that exists as a\n * filesystem path. This makes the args unambiguous so downstream code\n * (expand-context) never confuses a path for a revision.\n *\n * Idempotent: an explicit `--` separator leaves the args unchanged.\n */\nexport function normalizeGitDiffArgs(args: string[], cwd: string = process.cwd()): string[] {\n const { positionalIndices, hasSeparator } = classifyGitDiffArgs(args);\n if (hasSeparator) return args;\n for (const i of positionalIndices) {\n const arg = args[i];\n // Only positional args can be filesystem paths.\n if (existsSync(resolve(cwd, arg))) {\n return [...args.slice(0, i), '--', ...args.slice(i)];\n }\n }\n return args;\n}\n\n/**\n * Split a configured argument string into argv the way a shell would, so a\n * quoted path or search string survives as one argument.\n *\n * Two callers rely on this: `default-diff-args` from YAML, which people write\n * with shell quoting, and the `git-diff-args` string carried on a git diff\n * source, which `formatGitDiffArgs` writes in the same syntax. Unquoted input\n * splits on whitespace exactly as a plain split did, so older config and older\n * review documents keep parsing identically.\n *\n * Malformed input never throws. An unterminated quote closes at end of input:\n * a broken config line degrades to a best-effort argument list instead of\n * taking startup down with it.\n */\nexport function tokenizeGitDiffArgs(value: string): string[] {\n const args: string[] = [];\n let current = '';\n let started = false;\n let quote: \"'\" | '\"' | null = null;\n\n for (let i = 0; i < value.length; i++) {\n const char = value[i];\n\n if (quote === \"'\") {\n if (char === \"'\") quote = null;\n else current += char;\n continue;\n }\n\n if (quote === '\"') {\n // Inside double quotes only the quote and the backslash are escapable;\n // every other backslash is a literal character, as in POSIX shells.\n if (char === '\\\\' && (value[i + 1] === '\"' || value[i + 1] === '\\\\')) {\n current += value[++i];\n } else if (char === '\"') {\n quote = null;\n } else {\n current += char;\n }\n continue;\n }\n\n if (char === \"'\" || char === '\"') {\n quote = char;\n started = true;\n continue;\n }\n if (char === '\\\\' && i + 1 < value.length) {\n current += value[++i];\n started = true;\n continue;\n }\n if (/\\s/.test(char)) {\n if (started) {\n args.push(current);\n current = '';\n started = false;\n }\n continue;\n }\n current += char;\n started = true;\n }\n\n if (started) args.push(current);\n return args;\n}\n\n/** True when rendering this argument bare would lose its boundary. */\nfunction needsQuoting(arg: string): boolean {\n return arg.length === 0 || /[\\s'\"\\\\]/.test(arg);\n}\n\n/**\n * Render argv as the single string a git diff source carries, such that\n * `tokenizeGitDiffArgs` recovers the exact argument list.\n *\n * Arguments that survive a bare round trip are written bare, so ordinary\n * invocations produce byte-identical output to a plain join and the\n * `git-diff-args` XML attribute does not change shape for them.\n */\nexport function formatGitDiffArgs(args: string[]): string {\n return args.map(arg => (needsQuoting(arg) ? `'${arg.replace(/'/g, \"'\\\\''\")}'` : arg)).join(' ');\n}\n","// packages/core/src/startup-mode.ts\n// Startup mode detection: what the app should review, from the CLI args and the CWD.\n\nimport { existsSync, statSync } from 'fs';\nimport { execFileSync, execSync } from 'child_process';\nimport { resolve } from 'path';\nimport { classifyGitDiffArgs } from './git-diff-args';\n\n/**\n * Check if the current working directory is inside a git repository.\n */\nfunction isInGitRepo(): boolean {\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file is tracked by git (known to the index).\n */\nfunction isGitTracked(filePath: string): boolean {\n try {\n execFileSync('git', ['ls-files', '--error-unmatch', '--', filePath], {\n stdio: 'ignore',\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Determine the startup mode based on git availability and CLI arguments.\n * Returns the DiffSource type to use.\n */\nexport function determineMode(gitDiffArgs: string[]): 'git' | 'directory' | 'file' | 'welcome' {\n const { positionalIndices } = classifyGitDiffArgs(gitDiffArgs);\n const firstPositional = gitDiffArgs[positionalIndices[0]];\n\n // Check if first positional arg is an existing file\n if (firstPositional) {\n const candidate = resolve(process.cwd(), firstPositional);\n try {\n if (existsSync(candidate) && statSync(candidate).isFile()) {\n if (isInGitRepo()) {\n // In git repo: tracked files go through git diff, untracked use file mode\n return isGitTracked(firstPositional) ? 'git' : 'file';\n }\n return 'file';\n }\n } catch {\n // Failed to stat — fall through\n }\n }\n\n if (isInGitRepo()) {\n return 'git';\n }\n\n // Not in a git repo — check if first positional arg is an existing directory\n if (firstPositional) {\n const candidate = resolve(process.cwd(), firstPositional);\n try {\n if (existsSync(candidate) && statSync(candidate).isDirectory()) {\n return 'directory';\n }\n } catch {\n // Failed to stat — fall through to welcome\n }\n }\n\n return 'welcome';\n}\n","// packages/core/src/guide-loader.ts\n// Discovery + tolerant loading of the walkthrough guide sidecar.\n//\n// The guide is orientation garnish on a deterministic tool (see\n// docs/intent/llm-review-guide.md): a missing file is a silent no-op, and\n// an unreadable or invalid one produces exactly one stderr warning and no\n// guide. Nothing in this module may throw out of it — every failure mode\n// resolves to null.\n//\n// Note on startup cost: loadGuide IS awaited before window creation\n// (main.ts Phase 5b), deliberately — `guide:load` piggybacks on the\n// DIFF_REQUEST handler, so the payload must be cached via setGuideData\n// before the renderer's first request arrives. When a guide exists, the\n// xmllint-wasm init and validation delay window paint by a few hundred ms;\n// when none exists the cost is a single failed stat.\n//\n// Discovery is one-shot: the guide is resolved from the startup output\n// path. Changing the output path at runtime does not re-discover.\n\nimport { readFile } from 'fs/promises';\nimport { extname, resolve } from 'path';\nimport { parseGuideXml, reconcileGuide } from './guide-parser';\nimport { AppConfig, GuideLoadPayload } from './types';\n\n/**\n * Derive the guide sidecar path from the resolved output path: strip the\n * last extension and append `.guide.xml` (`review.xml` →\n * `review.guide.xml`). An output filename with no extension gets\n * `.guide.xml` appended verbatim.\n */\nexport function deriveGuidePath(outputPath: string): string {\n const ext = extname(outputPath);\n const base = ext ? outputPath.slice(0, -ext.length) : outputPath;\n return `${base}.guide.xml`;\n}\n\n/**\n * Resolve where to look for the guide: the `guide-file` config override\n * (resolved against cwd, like `output-file`) when set, otherwise the path\n * derived from the resolved output path.\n */\nexport function resolveGuidePath(outputPath: string, config: Pick<AppConfig, 'guideFile'>): string {\n if (config.guideFile) {\n return resolve(process.cwd(), config.guideFile);\n }\n return deriveGuidePath(outputPath);\n}\n\n/**\n * Discover, read, parse, validate, and reconcile the guide sidecar.\n *\n * Returns the display-ready payload, or null when there is no usable\n * guide. Missing file: silent. Unreadable or invalid file: exactly one\n * `console.error()` line (guide path + reason class). Never throws.\n */\nexport async function loadGuide(\n outputPath: string,\n config: Pick<AppConfig, 'guideFile'>,\n diffFilePaths: string[]\n): Promise<GuideLoadPayload | null> {\n let guidePath: string;\n try {\n guidePath = resolveGuidePath(outputPath, config);\n } catch {\n return null;\n }\n\n try {\n let content: string;\n try {\n content = await readFile(guidePath, 'utf-8');\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n // No sidecar next to the output path — the normal case.\n return null;\n }\n console.error(\n `[guide] Ignoring guide at ${guidePath}: unreadable (${code ?? 'unknown error'})`\n );\n return null;\n }\n\n const result = await parseGuideXml(content);\n // Explicit comparison: with strictNullChecks off (see tsconfig),\n // truthiness alone does not narrow the discriminated union.\n if (result.ok === false) {\n console.error(`[guide] Ignoring guide at ${guidePath}: invalid (${result.reason})`);\n return null;\n }\n\n const payload: GuideLoadPayload = {\n groups: reconcileGuide(result.guide, diffFilePaths),\n };\n if (result.guide.overview !== undefined) {\n payload.overview = result.guide.overview;\n }\n return payload;\n } catch (error) {\n // Belt and braces: no failure mode of the guide loader may escape.\n const message = error instanceof Error ? error.message : String(error);\n console.error(`[guide] Ignoring guide at ${guidePath}: invalid (${message})`);\n return null;\n }\n}\n","import type { DiffFile } from './types';\nimport {\n runGitDiffAsync,\n getRepoRootAsync,\n getUntrackedFilesAsync,\n generateUntrackedDiffs,\n} from './git';\nimport { parseDiff } from './diff-parser';\n\nexport interface LoadGitDiffOptions {\n /**\n * Include untracked working-tree files as synthetic additions. Defaults\n * to true (local git mode). Remote mode passes false: a base...head diff\n * of a PR/MR must never pick up unrelated local untracked files.\n */\n includeUntracked?: boolean;\n}\n\nexport async function loadGitDiffWithUntracked(\n gitDiffArgs: string[],\n cwd?: string,\n options: LoadGitDiffOptions = {}\n): Promise<{ files: DiffFile[]; repository: string }> {\n const { includeUntracked = true } = options;\n const repository = await getRepoRootAsync(cwd);\n const rawDiff = await runGitDiffAsync(gitDiffArgs, cwd);\n const files = parseDiff(rawDiff);\n\n if (!includeUntracked) {\n return { files, repository };\n }\n\n // Enumerate at the repository root. `git diff` reports root-relative paths\n // for the whole repository, while `git ls-files` reports cwd-relative paths\n // for the cwd subtree only. Read those cwd-relative names against the root\n // and a nested file resolves to its same-named root neighbour, or to\n // nothing at all.\n const untrackedPaths = await getUntrackedFilesAsync(repository);\n let allFiles = files;\n if (untrackedPaths.length > 0) {\n const untrackedDiffStr = generateUntrackedDiffs(untrackedPaths, repository);\n if (untrackedDiffStr.length > 0) {\n const untrackedFiles = parseDiff(untrackedDiffStr);\n for (const file of untrackedFiles) {\n file.isUntracked = true;\n }\n allFiles = [...files, ...untrackedFiles];\n }\n }\n\n return { files: allFiles, repository };\n}\n","// packages/core/src/staged-untracked.ts\n// Initial-config adjustment for staged-mode reviews.\n\nimport type { AppConfig } from './types';\n\n/**\n * In staged-mode reviews (--staged / --cached), untracked files are not\n * part of the index and should be hidden by default. If the user has\n * explicitly opted in via `show-untracked: true` in their YAML config,\n * respect that choice.\n *\n * Untracked files are still preloaded by the backend so that the toolbar\n * toggle can reveal them instantly without re-running git.\n */\nexport function applyStagedUntrackedDefault(config: AppConfig, gitDiffArgs: string[]): AppConfig {\n const stagedMode = gitDiffArgs.includes('--staged') || gitDiffArgs.includes('--cached');\n if (!stagedMode) return config;\n\n const userExplicitOptIn = config.showUntrackedExplicit && config.showUntracked;\n if (userExplicitOptIn) return config;\n\n return { ...config, showUntracked: false };\n}\n","// packages/core/src/remote-mode.ts\n// Remote PR/MR session bootstrap for the main process.\n//\n// Binding rule: after materialization, remote mode *is* git mode. This\n// module turns a forge URL into the inputs the existing git-mode pipeline\n// already understands — a repo path and a `baseSha...headSha` range — plus\n// the fetched discussion threads (mapped to ReviewComments for the\n// resume:load path) and the remote provenance the serializer records.\n//\n// Reused by both the CLI URL path (main.ts startup) and the splash-screen\n// URL entry (the remote:open-url IPC handler). Every external effect goes\n// through an injectable dependency so unit tests never spawn git/gh/glab.\n\nimport {\n parseForgeUrl,\n ForgeCliUnavailableError,\n createGitHubProvider,\n createGitLabProvider,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n defaultGitRunner,\n mapThreadsToReviewComments,\n createIgnoreFilter,\n} from './index';\nimport type {\n ForgeCommandRunner,\n ForgeName,\n ForgeProvider,\n ForgeThread,\n ForgeUrl,\n ExistingClone,\n MaterializeMode,\n MaterializeResult,\n} from './index';\nimport type {\n DiffFile,\n DiffLoadPayload,\n RemoteDriftInfo,\n RemoteSessionInfo,\n ReviewComment,\n ReviewState,\n} from './types';\nimport { loadGitDiffWithUntracked } from './git-diff-loader';\nimport { formatGitDiffArgs } from './git-diff-args';\n\n/** A materialized remote PR/MR session, ready for the git-mode pipeline. */\nexport interface RemoteSession {\n forgeUrl: ForgeUrl;\n /** Root of the materialized clone; the pipeline's repo path. */\n repoPath: string;\n /** Arguments for the existing git-diff machinery: `[base...head]`. */\n gitDiffArgs: string[];\n mode: MaterializeMode;\n /** Removes the temp clone when one was created; idempotent no-op otherwise. */\n cleanup: () => void;\n /** Provenance + thread-sync status for payloads and the saved review. */\n remote: RemoteSessionInfo;\n /**\n * Forge discussion threads mapped to ReviewComments. Empty when the forge\n * CLI is unavailable. Review-level threads keep the mapper's sentinel\n * `filePath: ''` (REVIEW_LEVEL_FILE_PATH).\n *\n * Mapped here without the reviewed diff, which is not loaded yet, so a\n * `suggestion` fence stays plain body text. {@link bootstrapRemoteDiff}\n * replaces these with the same threads mapped against the loaded files.\n */\n fetchedComments: ReviewComment[];\n /**\n * The threads behind `fetchedComments`, verbatim. Carried so the caller\n * that loads the diff can map them again with it (SR-0063).\n */\n fetchedThreads: ForgeThread[];\n}\n\n/** Injectable seams; defaults are the real core APIs. */\nexport interface RemoteSessionDeps {\n createProvider: (forge: ForgeName, runner: ForgeCommandRunner) => ForgeProvider;\n materialize: (\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner,\n existingClone?: ExistingClone | null\n ) => Promise<MaterializeResult>;\n detectExistingClone: (\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner\n ) => Promise<ExistingClone | null>;\n resolveRemoteDefaultBranch: (\n url: ForgeUrl,\n runner: ForgeCommandRunner,\n existing?: ExistingClone | null\n ) => Promise<string>;\n runner: ForgeCommandRunner;\n /** Loads the diff from the clone. Untracked files are never included. */\n loadDiff: (\n gitDiffArgs: string[],\n cwd: string\n ) => Promise<{ files: DiffFile[]; repository: string }>;\n}\n\nfunction defaultCreateProvider(forge: ForgeName, runner: ForgeCommandRunner): ForgeProvider {\n return forge === 'github' ? createGitHubProvider(runner) : createGitLabProvider(runner);\n}\n\nconst defaultDeps: RemoteSessionDeps = {\n createProvider: defaultCreateProvider,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n runner: defaultGitRunner,\n loadDiff: (gitDiffArgs, cwd) =>\n // A base...head diff of a remote PR/MR must never pick up local\n // untracked files (an existing clone may have unrelated ones).\n loadGitDiffWithUntracked(gitDiffArgs, cwd, { includeUntracked: false }),\n};\n\n/**\n * Materialize a forge PR/MR URL into a local git context and fetch its\n * discussion threads.\n *\n * Fatal failures (unrecognizable URL, materialization errors, base-branch\n * lookup failures other than a missing CLI) throw — callers surface them\n * like any other startup git error. Forge-CLI unavailability is never\n * fatal: the base branch falls back to the git-only default-branch lookup\n * and thread sync degrades to an empty list with a single stderr note.\n */\nexport async function startRemoteSession(\n url: string,\n cwd: string,\n deps: Partial<RemoteSessionDeps> = {}\n): Promise<RemoteSession> {\n const d: RemoteSessionDeps = { ...defaultDeps, ...deps };\n\n const forgeUrl = parseForgeUrl(url);\n if (!forgeUrl) {\n throw new Error(`Not a recognized pull-request or merge-request URL: ${url}`);\n }\n\n const provider = d.createProvider(forgeUrl.forge, d.runner);\n\n let cliAvailable = true;\n let baseBranch: string;\n let existingClone: ExistingClone | null | undefined;\n try {\n baseBranch = await provider.fetchBaseBranch(forgeUrl);\n } catch (error) {\n if (!(error instanceof ForgeCliUnavailableError)) {\n throw error;\n }\n cliAvailable = false;\n console.error(\n `[remote] Forge CLI unavailable (${error.cli}): ${error.message} — ` +\n 'falling back to the remote default branch via git.'\n );\n existingClone = await d.detectExistingClone(forgeUrl, cwd, d.runner);\n baseBranch = await d.resolveRemoteDefaultBranch(forgeUrl, d.runner, existingClone);\n }\n\n const materialized = await d.materialize(forgeUrl, baseBranch, cwd, d.runner, existingClone);\n\n let fetchedThreads: ForgeThread[] = [];\n let threadSyncAvailable = false;\n if (cliAvailable) {\n try {\n fetchedThreads = await provider.fetchThreads(forgeUrl);\n threadSyncAvailable = true;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(\n `[remote] thread sync unavailable — continuing without forge threads: ${message}`\n );\n }\n } else {\n console.error(\n '[remote] thread sync unavailable — forge CLI missing, continuing without forge threads.'\n );\n }\n\n return {\n forgeUrl,\n repoPath: materialized.repoPath,\n gitDiffArgs: [`${materialized.baseSha}...${materialized.headSha}`],\n mode: materialized.mode,\n cleanup: materialized.cleanup,\n remote: {\n remoteUrl: url,\n remoteBaseSha: materialized.baseSha,\n remoteHeadSha: materialized.headSha,\n remoteForge: forgeUrl.forge,\n threadSyncAvailable,\n // A temporary clone is deleted on exit, so nothing may be written\n // into it; the front end needs the fact, not the path.\n temporaryClone: materialized.mode === 'temp-clone',\n },\n fetchedComments: mapThreadsToReviewComments(fetchedThreads),\n fetchedThreads,\n };\n}\n\n/** A remote session plus the ready-to-send git-mode diff payload. */\nexport interface RemoteBootstrapResult {\n session: RemoteSession;\n payload: DiffLoadPayload;\n}\n\n/**\n * Full remote bootstrap: materialize the session, load the diff from the\n * clone through the existing git-diff machinery, apply the ignore filter,\n * map the fetched threads against those files, and shape the git-mode\n * `DiffLoadPayload` (with `remote` provenance attached). Shared by the CLI\n * URL startup path and the splash-screen `remote:open-url` handler.\n */\nexport async function bootstrapRemoteDiff(\n url: string,\n cwd: string,\n ignorePatterns: string[],\n deps: Partial<RemoteSessionDeps> = {}\n): Promise<RemoteBootstrapResult> {\n const d: RemoteSessionDeps = { ...defaultDeps, ...deps };\n const started = await startRemoteSession(url, cwd, d);\n\n // From here on the session may own a temporary clone; if anything below\n // fails the caller never receives the cleanup handle, so release it here.\n let files: DiffFile[];\n let repository: string;\n try {\n ({ files, repository } = await d.loadDiff(started.gitDiffArgs, started.repoPath));\n } catch (error) {\n started.cleanup();\n throw error;\n }\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredFiles = files.filter(f => shouldKeep(f.newPath || f.oldPath));\n\n // The reviewed diff exists only now, and the mapper needs it to anchor a\n // `suggestion` fence. Mapping against the filtered files keeps the\n // comments consistent with the payload the renderer receives.\n const session: RemoteSession = {\n ...started,\n fetchedComments: mapThreadsToReviewComments(started.fetchedThreads, filteredFiles),\n };\n\n return {\n session,\n payload: {\n files: filteredFiles,\n source: {\n type: 'git',\n // Same renderer the git-mode path uses, so expand-context can\n // tokenize this string back into the exact argv.\n gitDiffArgs: formatGitDiffArgs(session.gitDiffArgs),\n repository,\n },\n remote: session.remote,\n },\n };\n}\n\n/**\n * Merge fetched forge threads into a resumed document's comments. The\n * resumed document wins: a fetched thread whose root `remoteId` already\n * appears in the resumed comments is skipped (the resumed copy may carry\n * the user's added replies). Order: resumed comments first, then the\n * non-duplicate fetched threads in fetch order. Inputs are not mutated.\n */\nexport function mergeRemoteThreads(\n resumed: ReviewComment[],\n fetched: ReviewComment[]\n): ReviewComment[] {\n const resumedRemoteIds = new Set(\n resumed.map(c => c.remoteId).filter((id): id is string => id !== undefined)\n );\n return [\n ...resumed,\n ...fetched.filter(c => c.remoteId === undefined || !resumedRemoteIds.has(c.remoteId)),\n ];\n}\n\n/**\n * Return a copy of the state carrying this session's remote provenance, so\n * \"Finish Review\" writes the `remote-*` root attributes. Always records the\n * live session values: the saved document describes the diff that was\n * actually reviewed.\n */\nexport function applyRemoteProvenance(state: ReviewState, remote: RemoteSessionInfo): ReviewState {\n return {\n ...state,\n // The three source shapes are mutually exclusive in the document: the\n // remote-* attributes ARE the source, so the in-session git source\n // (the materialized clone) must not leak into the saved review. The\n // welcome source emits no source attributes, mirroring fetch-comments.\n source: { type: 'welcome' },\n remoteUrl: remote.remoteUrl,\n remoteBaseSha: remote.remoteBaseSha,\n remoteHeadSha: remote.remoteHeadSha,\n remoteForge: remote.remoteForge,\n };\n}\n\n/**\n * Compare a resumed document's recorded `remote-head-sha` with the live\n * head from materialization. Returns `null` when the document recorded no\n * head SHA (nothing to compare).\n */\nexport function computeRemoteDrift(\n recordedHeadSha: string | undefined,\n liveHeadSha: string\n): RemoteDriftInfo | null {\n if (recordedHeadSha === undefined) {\n return null;\n }\n return {\n recordedHeadSha,\n liveHeadSha,\n drifted: recordedHeadSha !== liveHeadSha,\n };\n}\n","// packages/core/src/fetch-comments.ts\n// Headless orchestrator for `self-review fetch-comments <URL>`: materialize\n// the PR/MR, fetch and map its discussion threads, and write a v3 review.xml\n// with remote provenance — no window, nothing on stdout, all logging on\n// stderr. Every collaborator is injectable so the flow is unit-testable; the\n// CLI entry in main.ts stays thin.\n\nimport { writeFileSync } from 'fs';\nimport { resolve } from 'path';\nimport { ForgeCliUnavailableError, parseForgeUrl } from './forge-provider';\nimport type { ForgeCommandRunner, ForgeName, ForgeProvider, ForgeUrl } from './forge-provider';\nimport { createGitHubProvider } from './github-provider';\nimport { createGitLabProvider } from './gitlab-provider';\nimport {\n defaultGitRunner,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n} from './materializer';\nimport type { ExistingClone, MaterializeResult } from './materializer';\nimport { mapThreadsToReviewComments, REVIEW_LEVEL_FILE_PATH } from './thread-mapper';\nimport { parseDiff } from './diff-parser';\nimport { runGitDiffAsync } from './git';\nimport { serializeReview } from './xml-serializer';\nimport { loadConfig } from './config';\nimport type {\n AppConfig,\n DiffFile,\n FileReviewState,\n RemoteForge,\n ReviewComment,\n ReviewState,\n} from './types';\n\n/**\n * Injectable seams for the orchestration. Defaults spawn real processes and\n * touch the real filesystem; tests replace them wholesale.\n */\nexport interface FetchCommentsDeps {\n /** Command runner shared by git, gh and glab invocations. */\n runner: ForgeCommandRunner;\n createProvider: (forge: ForgeName, runner: ForgeCommandRunner) => ForgeProvider;\n materialize: (\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner,\n existingClone?: ExistingClone | null\n ) => Promise<MaterializeResult>;\n detectExistingClone: (\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner\n ) => Promise<ExistingClone | null>;\n resolveRemoteDefaultBranch: (\n url: ForgeUrl,\n runner: ForgeCommandRunner,\n existing?: ExistingClone | null\n ) => Promise<string>;\n loadDiffFiles: (repoPath: string, baseSha: string, headSha: string) => Promise<DiffFile[]>;\n serialize: (state: ReviewState, outputPath: string) => Promise<string>;\n writeFile: (path: string, content: string) => void;\n loadConfig: () => AppConfig;\n now: () => Date;\n}\n\nfunction defaultDeps(): FetchCommentsDeps {\n return {\n runner: defaultGitRunner,\n createProvider: (forge, runner) =>\n forge === 'github' ? createGitHubProvider(runner) : createGitLabProvider(runner),\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n loadDiffFiles: async (repoPath, baseSha, headSha) =>\n // Triple-dot: diff from the merge base, matching how forges present a\n // PR/MR diff. Runs inside the materialized clone.\n parseDiff(await runGitDiffAsync([`${baseSha}...${headSha}`], repoPath)),\n serialize: serializeReview,\n writeFile: (path, content) => writeFileSync(path, content, 'utf-8'),\n loadConfig,\n now: () => new Date(),\n };\n}\n\nexport interface BuildRemoteReviewStateArgs {\n remoteUrl: string;\n forge: RemoteForge;\n baseSha: string;\n headSha: string;\n diffFiles: DiffFile[];\n comments: ReviewComment[];\n timestamp: string;\n}\n\n/**\n * Assemble the ReviewState for a fetched remote review. Pure and\n * deterministic: same inputs, same state.\n *\n * Placement rules:\n * - Every diff file gets a file entry in diff order; fetched threads land on\n * their files, in thread order.\n * - Comments whose path is not in the diff (e.g. outdated anchors on files\n * no longer touched) get a synthetic entry with change-type \"modified\" —\n * the schema requires the attribute and \"modified\" is the least-claiming\n * value for a file we cannot classify.\n * - Review-level threads (sentinel {@link REVIEW_LEVEL_FILE_PATH}) are\n * folded into a single trailing file entry with the sentinel path: the v3\n * schema requires every <comment> inside a <file path>, and the empty\n * path can never collide with a real diff path, so consumers detect these\n * by comparing against the constant. Omitted when there are none.\n * - Every file is viewed=\"false\": fetch-comments reviews nothing, and a\n * viewed mark claims a human looked at the file. A subsequent\n * --resume-from session therefore starts with the full file list pending.\n * - `source` is `{ type: 'welcome' }`: the remote-* root attributes are the\n * review's source shape, and the three shapes (git, directory, remote)\n * are mutually exclusive by contract, so no local source attributes are\n * serialized.\n */\nexport function buildRemoteReviewState(args: BuildRemoteReviewStateArgs): ReviewState {\n const commentsByPath = new Map<string, ReviewComment[]>();\n for (const comment of args.comments) {\n const list = commentsByPath.get(comment.filePath);\n if (list) {\n list.push(comment);\n } else {\n commentsByPath.set(comment.filePath, [comment]);\n }\n }\n\n const files: FileReviewState[] = [];\n const diffPaths = new Set<string>();\n for (const diffFile of args.diffFiles) {\n const path = diffFile.changeType === 'deleted' ? diffFile.oldPath : diffFile.newPath;\n diffPaths.add(path);\n files.push({\n path,\n changeType: diffFile.changeType,\n viewed: false,\n comments: commentsByPath.get(path) ?? [],\n });\n }\n\n // Synthetic entries for anchored comments whose file is not in the diff,\n // in first-appearance order.\n for (const [path, comments] of commentsByPath) {\n if (path === REVIEW_LEVEL_FILE_PATH || diffPaths.has(path)) continue;\n files.push({ path, changeType: 'modified', viewed: false, comments });\n }\n\n const reviewLevel = commentsByPath.get(REVIEW_LEVEL_FILE_PATH);\n if (reviewLevel && reviewLevel.length > 0) {\n files.push({\n path: REVIEW_LEVEL_FILE_PATH,\n changeType: 'modified',\n viewed: false,\n comments: reviewLevel,\n });\n }\n\n return {\n timestamp: args.timestamp,\n source: { type: 'welcome' },\n files,\n remoteUrl: args.remoteUrl,\n remoteBaseSha: args.baseSha,\n remoteHeadSha: args.headSha,\n remoteForge: args.forge,\n };\n}\n\nexport interface FetchCommentsOptions {\n /** Include threads the forge marks resolved (GitLab). Default false. */\n includeResolved?: boolean;\n /** Working directory for clone detection and output resolution. */\n cwd?: string;\n /** Test seams; every omitted member falls back to the real default. */\n deps?: Partial<FetchCommentsDeps>;\n}\n\n/**\n * Run the headless fetch-comments flow end to end. Throws on any failure\n * (the caller prints the message to stderr and exits 1); the temporary\n * clone, when one was created, is removed on both success and failure.\n */\nexport async function runFetchComments(\n url: string,\n options: FetchCommentsOptions = {}\n): Promise<void> {\n const deps: FetchCommentsDeps = { ...defaultDeps(), ...options.deps };\n const cwd = options.cwd ?? process.cwd();\n\n const forgeUrl = parseForgeUrl(url);\n if (forgeUrl === null) {\n throw new Error(\n `Not a recognized pull/merge request URL: ${url}\\n` +\n 'Expected a GitHub PR URL (…/pull/N) or a GitLab MR URL ' +\n '(…/-/merge_requests/N).'\n );\n }\n\n const provider = deps.createProvider(forgeUrl.forge, deps.runner);\n\n let baseBranch: string;\n let existingClone: ExistingClone | null | undefined;\n try {\n baseBranch = await provider.fetchBaseBranch(forgeUrl);\n } catch (error) {\n if (!(error instanceof ForgeCliUnavailableError)) throw error;\n console.error(`[fetch-comments] ${error.message}`);\n console.error(\n `[fetch-comments] ${error.cli} unavailable for the base-branch lookup — ` +\n 'falling back to the remote default branch via git ls-remote.'\n );\n existingClone = await deps.detectExistingClone(forgeUrl, cwd, deps.runner);\n baseBranch = await deps.resolveRemoteDefaultBranch(forgeUrl, deps.runner, existingClone);\n }\n console.error(`[fetch-comments] Base branch: ${baseBranch}`);\n\n const materialized = await deps.materialize(\n forgeUrl,\n baseBranch,\n cwd,\n deps.runner,\n existingClone\n );\n try {\n let threads;\n try {\n threads = await provider.fetchThreads(forgeUrl, {\n includeResolved: options.includeResolved ?? false,\n });\n } catch (error) {\n if (error instanceof ForgeCliUnavailableError) {\n // Fetching comments is this subcommand's entire purpose: no\n // degradation, fail with a clear error.\n throw new Error(\n `Cannot fetch discussion threads: ${error.message}\\n` +\n `fetch-comments requires the ${error.cli} CLI to be installed ` +\n 'and authenticated.'\n );\n }\n throw error;\n }\n console.error(`[fetch-comments] Fetched ${threads.length} threads`);\n\n const diffFiles = await deps.loadDiffFiles(\n materialized.repoPath,\n materialized.baseSha,\n materialized.headSha\n );\n // The diff is what anchors a `suggestion` fence: without it the mapper\n // cannot read the original code a fence proposes to replace.\n const comments = mapThreadsToReviewComments(threads, diffFiles);\n\n const state = buildRemoteReviewState({\n remoteUrl: url,\n forge: forgeUrl.forge,\n baseSha: materialized.baseSha,\n headSha: materialized.headSha,\n diffFiles,\n comments,\n timestamp: deps.now().toISOString(),\n });\n\n const config = deps.loadConfig();\n const outputPath = resolve(cwd, config.outputFile);\n const xml = await deps.serialize(state, outputPath);\n deps.writeFile(outputPath, xml + '\\n');\n console.error(`[fetch-comments] ${comments.length} threads written to ${outputPath}`);\n } finally {\n materialized.cleanup();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAKO,SAAS,UAAU,SAA6B;AACrD,MAAI,CAAC,QAAQ,KAAK,GAAG;AACnB,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,QAAQ,QAAQ,MAAM,IAAI;AAChC,QAAM,QAAoB,CAAC;AAC3B,MAAI,cAAwC;AAC5C,MAAI,cAAwC;AAC5C,MAAI,gBAAgB;AACpB,MAAI,gBAAgB;AACpB,MAAI,gBAAgB;AAEpB,WAAS,YAAkB;AACzB,QACE,gBACC,YAAY,WAAW,YAAY,aACnC,YAAY,YACX,YAAY,MAAO,SAAS,KAC5B,YAAY,eAAe,cAC3B,gBACF;AACA,YAAM,KAAK,WAAuB;AAAA,IACpC;AAAA,EACF;AAEA,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,UAAM,OAAO,MAAM,CAAC;AAGpB,QAAI,KAAK,WAAW,aAAa,GAAG;AAElC,UAAI,eAAe,YAAY,UAAU,aAAa;AACpD,oBAAY,MAAO,KAAK,WAAuB;AAC/C,sBAAc;AAAA,MAChB;AAEA,gBAAU;AAIV,YAAM,WAAW,mBAAmB,IAAI;AAGxC,oBAAc;AAAA,QACZ,SAAS,SAAS;AAAA,QAClB,SAAS,SAAS;AAAA,QAClB,YAAY;AAAA,QACZ,UAAU;AAAA,QACV,OAAO,CAAC;AAAA,MACV;AACA,oBAAc;AACd,sBAAgB;AAChB;AAAA,IACF;AAEA,QAAI,CAAC,YAAa;AAGlB,QAAI,KAAK,WAAW,eAAe,GAAG;AACpC,kBAAY,aAAa;AACzB,kBAAY,UAAU;AACtB;AAAA,IACF;AAEA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I;AACF,QAAI;AACJ,QAAI;AACF,gBAAU,MAAM,SAAS,aAAa,UAAU;AAAA,QAC9C,iBAAiB,QAAQ,mBAAmB;AAAA,MAC9C,CAAC;AAAA,IACH,SAAS,OAAO;AACd,UAAI,iBAAiB,0BAA0B;AAG7C,cAAM,IAAI;AAAA,UACR,oCAAoC,MAAM,OAAO;AAAA,8BAChB,MAAM,GAAG;AAAA,QAE5C;AAAA,MACF;AACA,YAAM;AAAA,IACR;AACA,YAAQ,MAAM,4BAA4B,QAAQ,MAAM,UAAU;AAElE,UAAM,YAAY,MAAM,KAAK;AAAA,MAC3B,aAAa;AAAA,MACb,aAAa;AAAA,MACb,aAAa;AAAA,IACf;AAGA,UAAM,WAAW,2BAA2B,SAAS,SAAS;AAE9D,UAAM,QAAQ,uBAAuB;AAAA,MACnC,WAAW;AAAA,MACX,OAAO,SAAS;AAAA,MAChB,SAAS,aAAa;AAAA,MACtB,SAAS,aAAa;AAAA,MACtB;AAAA,MACA;AAAA,MACA,WAAW,KAAK,IAAI,EAAE,YAAY;AAAA,IACpC,CAAC;AAED,UAAM,SAAS,KAAK,WAAW;AAC/B,UAAM,iBAAa,uBAAQ,KAAK,OAAO,UAAU;AACjD,UAAM,MAAM,MAAM,KAAK,UAAU,OAAO,UAAU;AAClD,SAAK,UAAU,YAAY,MAAM,IAAI;AACrC,YAAQ,MAAM,oBAAoB,SAAS,MAAM,uBAAuB,UAAU,EAAE;AAAA,EACtF,UAAE;AACA,iBAAa,QAAQ;AAAA,EACvB;AACF;","names":["path","path","import_fs","resolve","import_fast_xml_parser","import_xmllint_wasm","path","import_path","ignore","import_fs","import_path","path","parseYaml","import_child_process","import_util","execFileAsync","import_fs","import_path","fsConstants","import_fs","import_path","file","toTurn","toAnchor","import_child_process","fs","path","resolve","fs","import_path","import_fs","import_path","needsQuoting","path","readGitBlobAsync","stat","runGitDiffAsync","parseDiff","path","import_fs","import_child_process","import_path","import_promises","import_path","import_fs","import_path","defaultDeps","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/diff-parser.ts","../src/synthetic-diff.ts","../src/git.ts","../src/index.ts","../src/xml-serializer.ts","../src/xml-parser.ts","../src/guide-schema.ts","../src/guide-parser.ts","../src/forge-provider.ts","../src/directory-scanner.ts","../src/ignore-filter.ts","../src/config.ts","../src/payload-sizing.ts","../src/fs-utils.ts","../src/apply-suggestion.ts","../src/file-type-utils.ts","../src/github-provider.ts","../src/thread-mapper.ts","../src/gitlab-provider.ts","../src/materializer.ts","../src/review-handlers.ts","../src/git-diff-args.ts","../src/startup-mode.ts","../src/guide-loader.ts","../src/git-diff-loader.ts","../src/staged-untracked.ts","../src/remote-mode.ts","../src/fetch-comments.ts"],"sourcesContent":["// src/main/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 let hasModeChange = false;\n\n function flushFile(): void {\n if (\n currentFile &&\n (currentFile.oldPath || currentFile.newPath) &&\n (currentFile.isBinary ||\n currentFile.hunks!.length > 0 ||\n currentFile.changeType !== 'modified' ||\n hasModeChange)\n ) {\n files.push(currentFile as DiffFile);\n }\n }\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 flushFile();\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 hasModeChange = false;\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 currentFile.oldPath = '';\n continue;\n }\n\n if (line.startsWith('deleted file mode')) {\n currentFile.changeType = 'deleted';\n currentFile.newPath = '';\n continue;\n }\n\n if (line.startsWith('new mode ')) {\n hasModeChange = true;\n continue;\n }\n\n if (line.startsWith('rename from ')) {\n currentFile.changeType = 'renamed';\n currentFile.oldPath = decodeGitPath(line.substring('rename from '.length));\n continue;\n }\n\n if (line.startsWith('rename to ')) {\n currentFile.newPath = decodeGitPath(line.substring('rename to '.length));\n continue;\n }\n\n // Parse old file path\n if (!currentHunk && line.startsWith('--- ')) {\n const path = decodeGitPath(line.substring(4).split('\\t')[0]);\n currentFile.oldPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Parse new file path\n if (!currentHunk && line.startsWith('+++ ')) {\n const path = decodeGitPath(line.substring(4).split('\\t')[0]);\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(/@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(.*)$/);\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 flushFile();\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 decodeGitPath(path: string): string {\n if (!path.startsWith('\"') || !path.endsWith('\"')) return path;\n\n const escapes: Record<string, string> = {\n a: '\\x07',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t',\n v: '\\v',\n '\"': '\"',\n '\\\\': '\\\\',\n };\n return path.slice(1, -1).replace(/(?:\\\\[0-7]{1,3})+|\\\\[abfnrtv\"\\\\]/g, escape => {\n if (/^\\\\[0-7]/.test(escape)) {\n // Git quotes UTF-8 bytes as octal, so decode each run together.\n const bytes = escape\n .slice(1)\n .split('\\\\')\n .map(byte => parseInt(byte, 8));\n return Buffer.from(bytes).toString('utf8');\n }\n return escapes[escape[1]];\n });\n}\n\nfunction parseGitDiffHeader(line: string): {\n oldPath: string;\n newPath: string;\n} {\n const paths = line.substring('diff --git '.length);\n // Quoted paths are single C-style tokens, even when they contain spaces.\n const quotedOld = paths.match(/^(\"(?:\\\\.|[^\"\\\\])*\") (.+)$/);\n const quotedNew = paths.match(/^(.+) (\"(?:\\\\.|[^\"\\\\])*\")$/);\n const quoted = quotedOld || quotedNew;\n if (quoted) {\n return {\n oldPath: stripPrefix(decodeGitPath(quoted[1])),\n newPath: stripPrefix(decodeGitPath(quoted[2])),\n };\n }\n\n // Unquoted names can contain spaces. Prefer a boundary whose two paths\n // agree; rename headers supply the exact paths when they differ.\n const separators = [...paths.matchAll(/ [bwico]\\//g)];\n const boundary =\n separators.find(\n match =>\n stripPrefix(paths.substring(0, match.index)) ===\n stripPrefix(paths.substring(match.index! + 1))\n ) || separators[0];\n if (!boundary) return { oldPath: '', newPath: '' };\n\n return {\n oldPath: stripPrefix(paths.substring(0, boundary.index)),\n newPath: stripPrefix(paths.substring(boundary.index! + 1)),\n };\n}\n","// packages/core/src/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';\nimport { join } from 'path';\n\n// C-style escapes git emits for the characters that have one.\nconst C_STYLE_ESCAPES: Record<number, string> = {\n 0x07: '\\\\a',\n 0x08: '\\\\b',\n 0x09: '\\\\t',\n 0x0a: '\\\\n',\n 0x0b: '\\\\v',\n 0x0c: '\\\\f',\n 0x0d: '\\\\r',\n 0x22: '\\\\\"',\n 0x5c: '\\\\\\\\',\n};\n\nfunction needsQuoting(byte: number): boolean {\n return byte < 0x20 || byte >= 0x7f || byte === 0x22 || byte === 0x5c;\n}\n\n/**\n * Encode a path the way git writes it in diff headers. A plain path goes out\n * verbatim. Anything else becomes a double-quoted C-style token with control\n * characters, quotes, backslashes and non-ASCII UTF-8 bytes escaped.\n *\n * This inverts `decodeGitPath` in diff-parser.ts. Without it, a filename\n * containing a newline ends the header line mid-name and the parser recovers\n * a name no file on disk answers to.\n */\nexport function quoteGitPath(path: string): string {\n const bytes = Buffer.from(path, 'utf-8');\n if (!bytes.some(needsQuoting)) return path;\n\n let quoted = '\"';\n for (const byte of bytes) {\n const escape = C_STYLE_ESCAPES[byte];\n if (escape) {\n quoted += escape;\n } else if (byte < 0x20 || byte >= 0x7f) {\n quoted += `\\\\${byte.toString(8).padStart(3, '0')}`;\n } else {\n quoted += String.fromCharCode(byte);\n }\n }\n return `${quoted}\"`;\n}\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 - Literal relative file paths (e.g. \"src/foo.ts\"), resolved\n * against rootDir and never git-quoted on the way in\n * @param rootDir - Absolute path to the root directory the paths are relative to\n * @returns A unified diff string covering all provided files\n */\nexport function generateSyntheticDiffs(paths: string[], rootDir: string): string {\n const diffs: string[] = [];\n\n for (const filePath of paths) {\n const fullPath = join(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 // Git quotes the prefixed path as a whole (\"a/name\"), not the name alone.\n const oldHeaderPath = quoteGitPath(`a/${filePath}`);\n const newHeaderPath = quoteGitPath(`b/${filePath}`);\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 ${oldHeaderPath} ${newHeaderPath}\\n` +\n `new file mode 100644\\n` +\n `Binary files /dev/null and ${newHeaderPath} 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 ${oldHeaderPath} ${newHeaderPath}\\n` +\n `new file mode 100644\\n` +\n `--- /dev/null\\n` +\n `+++ ${newHeaderPath}\\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/git.ts\n// Git command execution\n\nimport { execSync, execFile, execFileSync } from 'child_process';\nimport { promisify } from 'util';\nimport { generateSyntheticDiffs } from './synthetic-diff';\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Strip only the single trailing newline git appends to command output.\n * A plain `.trim()` also eats leading/trailing whitespace that is part of\n * the actual path (e.g. a repository root with a trailing space), reporting\n * a path that does not exist on disk.\n */\nexport function stripTrailingNewline(text: string): string {\n return text.replace(/\\r?\\n$/, '');\n}\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('Error: not a git repository (or any parent up to mount point)');\n process.exit(1);\n }\n\n // Run git diff with the provided arguments\n const result = execFileSync('git', ['diff', ...args], {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large diffs\n });\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function getRepoRoot(): string {\n try {\n const result = execSync('git rev-parse --show-toplevel', {\n encoding: 'utf-8',\n });\n return stripTrailingNewline(result);\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('Error: not a git repository (or any parent up to mount point)');\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 execFileAsync('git', ['rev-parse', '--show-toplevel'], {\n timeout: 10000, // 10 second timeout\n cwd,\n });\n return stripTrailingNewline(stdout);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Async version of runGitDiff - called AFTER app.whenReady().\n * Uses timeout to prevent hanging in CI environments.\n */\nexport async function runGitDiffAsync(args: string[], cwd?: string): Promise<string> {\n try {\n const { stdout } = await execFileAsync('git', ['diff', ...args], {\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer\n timeout: 30000, // 30 second timeout\n cwd,\n });\n return stdout;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Read a blob from a git object spec (`<sha>:<path>`) as raw bytes.\n * Remote mode reads reviewed content at the fetched head SHA — a temporary\n * clone's working tree stays on the default branch and never reflects the\n * PR/MR head.\n */\nexport async function readGitBlobAsync(repoPath: string, spec: string): Promise<Buffer> {\n return await new Promise<Buffer>((resolve, reject) => {\n execFile(\n 'git',\n ['-C', repoPath, 'show', spec],\n { encoding: 'buffer', maxBuffer: 50 * 1024 * 1024, timeout: 30000 },\n (error, stdout) => {\n if (error) {\n reject(error);\n } else {\n resolve(stdout);\n }\n }\n );\n });\n}\n\n/**\n * Get list of untracked files (respects .gitignore).\n *\n * Pass the repository root. `git ls-files` reports paths relative to the\n * directory it runs in and lists that subtree only, while `git diff` reports\n * root-relative paths for the whole repository from anywhere inside it. Run\n * anywhere else and the names match neither the diff nor the root the files\n * are read from.\n *\n * `-z` keeps the names literal. NUL termination survives newlines in\n * filenames, and it turns off the C-style quoting git otherwise applies to\n * control characters and non-ASCII bytes.\n */\nexport async function getUntrackedFilesAsync(repoRoot?: string): Promise<string[]> {\n try {\n const { stdout } = await execFileAsync(\n 'git',\n ['ls-files', '--others', '--exclude-standard', '-z'],\n {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 10000,\n cwd: repoRoot,\n }\n );\n return stdout.split('\\0').filter(name => name.length > 0);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Warning: Failed to list untracked files: ${error.message}`);\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(paths: string[], repoRoot: string): string {\n return generateSyntheticDiffs(paths, repoRoot);\n}\n","// @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 SuggestionApplyRequest,\n SuggestionApplyOutcome,\n ApplyDestinationOutcome,\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 ReviewGuide,\n GuideGroup,\n GuideFileEntry,\n ResolvedGuideGroup,\n ResolvedGuideFile,\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// Walkthrough guide schema\nexport { GUIDE_XSD_SCHEMA } from './guide-schema';\n\n// Walkthrough guide parsing and reconciliation\nexport { parseGuideXml, reconcileGuide, IMPLICIT_GUIDE_GROUP_NAME } from './guide-parser';\nexport type { GuideParseResult } from './guide-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// Forge providers (remote PR/MR conversation plane)\nexport { parseForgeUrl, ForgeCliUnavailableError } from './forge-provider';\nexport type {\n ForgeName,\n ForgeUrl,\n ForgeAnchorSide,\n ForgeThreadAnchor,\n ForgeThreadTurn,\n ForgeThread,\n FetchThreadsOptions,\n ForgeCommandResult,\n ForgeCommandRunner,\n ForgeProvider,\n} from './forge-provider';\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// Anchored suggestion application (writes a reviewed working file)\nexport { applySuggestion } from './apply-suggestion';\nexport type {\n ApplyRefusalReason,\n ApplySuggestionRequest,\n ApplySuggestionApplied,\n ApplySuggestionRefused,\n ApplySuggestionResult,\n} from './apply-suggestion';\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\n// GitHub forge provider (gh CLI backed)\nexport { createGitHubProvider } from './github-provider';\n\n// Forge thread → ReviewComment mapper (remote PR/MR fetch direction)\nexport { mapThreadsToReviewComments, REVIEW_LEVEL_FILE_PATH } from './thread-mapper';\n\n// GitLab forge provider (glab CLI backed)\nexport { createGitLabProvider } from './gitlab-provider';\n\n// Clone-aware diff materializer (remote PR/MR git plane)\nexport {\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n defaultGitRunner,\n} from './materializer';\nexport type { ExistingClone, MaterializeMode, MaterializeResult } from './materializer';\n\n// Review session orchestration (transport agnostic; each handler takes the\n// session it acts on and reads no module-scope state)\nexport {\n createReviewSession,\n preparePayload,\n getDiffLoad,\n loadImage,\n getFileHunks,\n getConfigLoad,\n submitReviewState,\n takeReviewState,\n readAttachment,\n getResumeLoad,\n expandContext,\n prepareDirectoryReview,\n commitReviewStart,\n resolveSourceBaseDir,\n resolveApplyDestination,\n applySuggestionForSession,\n} from './review-handlers';\nexport type { ReviewSession, ReviewStartResult } from './review-handlers';\n\n// Startup mode detection (git, directory, file, welcome)\nexport { determineMode } from './startup-mode';\n\n// Walkthrough guide sidecar discovery and tolerant loading\nexport { deriveGuidePath, resolveGuidePath, loadGuide } from './guide-loader';\n\n// Git diff loading, staged/untracked defaulting, and argument normalisation\nexport { loadGitDiffWithUntracked } from './git-diff-loader';\nexport type { LoadGitDiffOptions } from './git-diff-loader';\nexport { applyStagedUntrackedDefault } from './staged-untracked';\nexport { normalizeGitDiffArgs } from './git-diff-args';\n\n// Remote PR/MR session bootstrap (URL -> materialized git-mode inputs)\nexport {\n startRemoteSession,\n bootstrapRemoteDiff,\n mergeRemoteThreads,\n applyRemoteProvenance,\n computeRemoteDrift,\n} from './remote-mode';\nexport type { RemoteSession, RemoteSessionDeps, RemoteBootstrapResult } from './remote-mode';\n\n// Headless fetch-comments orchestrator\nexport { buildRemoteReviewState, runFetchComments } from './fetch-comments';\nexport type {\n FetchCommentsDeps,\n BuildRemoteReviewStateArgs,\n FetchCommentsOptions,\n} from './fetch-comments';\n","// src/main/xml-serializer.ts\n// Serialize ReviewState to XML and validate against XSD\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { ReviewState, FileReviewState, ReviewComment, Reply, Attachment } from './types';\nimport { validateXML } from 'xmllint-wasm';\n\n// Embed the XSD schema for validation.\n// This MUST stay byte-identical to the on-disk canonical copy\n// (.agents/skills/self-review-apply/assets/self-review-v3.xsd);\n// the sync test in xsd-schema.test.ts enforces it.\nexport const XSD_SCHEMA = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sr=\"urn:self-review:v3\"\n targetNamespace=\"urn:self-review:v3\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review XML Schema v3\n =========================\n Defines the output format for the self-review application.\n This schema is designed to be both machine-validated and\n fed to an LLM so it can understand the structure of review feedback.\n\n Key concepts:\n - A <review> contains one <file> per file in the diff.\n - A <file> contains zero or more <comment> elements.\n - A <comment> with no line attributes is a file-level comment.\n - A <comment> with old-line-start/old-line-end refers to lines\n in the pre-change version of the file (typically deleted lines).\n - A <comment> with new-line-start/new-line-end refers to lines\n in the post-change version of the file (added or context lines).\n - Exactly one pair (old-line-* or new-line-*) should be present\n for line-level comments. This constraint cannot be expressed in\n XSD 1.0 and is enforced by the application.\n - A <comment> may carry an ordered list of <reply> children, which\n are turns in a conversation about that comment.\n\n Changes from v1:\n - <comment> gained two optional attributes, severity and confidence,\n so an automated consumer can threshold on findings instead of\n applying all of them or none of them. See CommentType.\n\n Changes from v2:\n - <comment> gained an optional, unbounded <reply> child, so a finding\n and the responses to it form a single legible thread instead of a\n set of disconnected assertions. See ReplyType.\n\n Amended in place (still v3):\n - The review root gained optional remote-url, remote-base-sha,\n remote-head-sha and remote-forge attributes, and <comment> and\n <reply> gained an optional remote-id attribute, so a review taken\n against a remote pull/merge request records its provenance. Purely\n additive: a document carrying none of them is unchanged. See\n ReviewType.\n -->\n\n <!-- ===== Root element ===== -->\n\n <xs:element name=\"review\" type=\"sr:ReviewType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review output file. Contains one file element\n per file in the git diff, including files with no comments.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <!-- ===== Complex types ===== -->\n\n <xs:complexType name=\"ReviewType\">\n <xs:sequence>\n <xs:element name=\"file\" type=\"sr:FileType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the review was completed (window closed).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments that were passed to self-review on the CLI.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root where self-review was invoked.\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"source-path\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the directory being reviewed.\n Present only when reviewing a directory (non-git mode).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-url\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n URL of the remote pull/merge request this review was taken\n against. Example: \"https://github.com/owner/repo/pull/42\".\n Present only when reviewing a remote PR/MR.\n\n The remote-* attributes form a third source shape alongside\n git-diff-args/repository (local git diff) and source-path\n (directory review). The three shapes are mutually exclusive;\n XSD 1.0 cannot express that constraint, so it is enforced by\n the application.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-base-sha\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Commit SHA the remote diff was computed from (the base of the\n PR/MR at fetch time). Together with remote-head-sha it pins the\n review to the exact diff it was written against, so a consumer\n can detect drift when the remote branch moves.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-head-sha\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Commit SHA of the head of the remote PR/MR branch at fetch time.\n See remote-base-sha for how the pair supports drift detection.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-forge\" type=\"sr:RemoteForgeEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Which forge hosts the remote PR/MR. Names the id space of the\n remote-id attributes on comments and replies, and selects the\n API machinery a future posting feature would use.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileType\">\n <xs:annotation>\n <xs:documentation>\n Represents a single file in the diff. Files with no comments\n appear as empty elements. The path is relative to the repository root.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"comment\" type=\"sr:CommentType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root. For renamed files,\n this is the new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"change-type\" type=\"sr:ChangeTypeEnum\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n The type of change: added, modified, deleted, or renamed.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"viewed\" type=\"xs:boolean\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Whether the reviewer marked this file as reviewed.\n true = the reviewer looked at this file.\n false = the reviewer did not mark this file as viewed.\n This helps an AI agent distinguish \"reviewed with no comments\"\n from \"not yet reviewed.\"\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"CommentType\">\n <xs:annotation>\n <xs:documentation>\n A review comment. Three forms:\n\n 1. File-level comment: no line attributes present.\n Applies to the file as a whole.\n\n 2. Comment on new/added/context lines: new-line-start and\n new-line-end are present. These reference line numbers in the\n post-change version of the file.\n\n 3. Comment on old/deleted lines: old-line-start and old-line-end\n are present. These reference line numbers in the pre-change\n version of the file.\n\n For single-line comments, start and end are equal.\n Exactly one pair (old or new) should be present for line-level\n comments. Both pairs absent = file-level comment.\n\n The category child says what kind of finding this is. The severity\n and confidence attributes say how much weight to put on it: severity\n is how consequential the finding is if it is real, confidence is how\n sure the author is that it is real. They are independent, and an\n automated consumer is expected to threshold on both.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The comment text. May contain markdown formatting.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"category\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n Required category tag for this comment (e.g., \"bug\", \"style\",\n \"nit\", \"question\", \"security\"). Categories are defined in the\n project-level .self-review.yaml configuration. Every comment\n must have a category to help AI agents prioritize and triage\n feedback.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"suggestion\" type=\"sr:SuggestionType\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Optional code replacement proposal. When present, the AI agent\n should replace the original-code with the proposed-code at the\n referenced line range.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment. The path attribute references an image file\n stored in the .self-review-assets/ directory alongside the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"reply\" type=\"sr:ReplyType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional ordered list of replies to this comment. The comment\n itself is the root of the thread; each reply is a later turn in\n the conversation about it.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"old-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the pre-change (old) version of the file.\n Use for comments on deleted lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"old-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the pre-change (old) version.\n Must be >= old-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the post-change (new) version of the file.\n Use for comments on added or context (unchanged) lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the post-change (new) version.\n Must be >= new-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"author\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The author of this comment. When present, indicates the comment\n was generated by a bot or LLM (e.g., \"Claude Sonnet 4.6\").\n When absent, the comment is assumed to be authored by the human\n reviewer.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"severity\" type=\"sr:SeverityEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n How consequential this finding is if it turns out to be real.\n Judge the impact of the problem, not how confident you are that\n the problem exists, and not how much work the fix is.\n\n This attribute has no schema default on purpose. When it is\n absent, a consumer must treat the comment as falling below any\n severity floor it applies, i.e. absent never satisfies a\n threshold. Comments written by a human in the self-review UI\n normally carry no severity.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"confidence\" type=\"sr:ConfidenceEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n How sure the author is that this finding is real, i.e. that it\n describes an actual defect in the code as written rather than a\n hypothetical one.\n\n Confidence is about the evidence, not about how strongly the\n comment is worded. A finding whose argument depends on a\n constraint that is not visible in the diff, on a caller that was\n not read, or on a failure scenario that was imagined rather than\n traced, is low confidence however plausible its prose sounds.\n LLM reviewers systematically overstate certainty here; a\n consumer thresholding on this attribute is relying on it being\n lowered honestly.\n\n This attribute has no schema default on purpose. When it is\n absent, a consumer must treat the comment as falling below any\n confidence floor it applies, i.e. absent never satisfies a\n threshold.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-id\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Identifier of the remote discussion thread or comment this\n comment was fetched from, in the id space of the forge named by\n remote-forge on the review root. Provenance and forward\n machinery: it lets a consumer trace the finding back to its\n origin, and a future posting feature reply to the existing\n thread instead of opening a new one. Absent on comments\n authored locally.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"ReplyType\">\n <xs:annotation>\n <xs:documentation>\n A reply to a review comment. Replies turn a finding into a\n conversation: the comment asserts something, a reply answers it, a\n later reply answers that.\n\n Four rules govern replies. Only the first is beyond what XSD 1.0\n can express, and it is enforced by the application and by the\n skills that author these documents. Rules 2 to 4 are enforced by\n the content model below; they are spelled out anyway, because the\n reason for a constraint is what an author needs in order to write\n a good reply, and a validator only ever reports the constraint:\n\n 1. Replies are ordered. Document order is conversation order, and\n it is the only ordering signal. There are no timestamps and no\n identifiers: the earlier reply is the earlier turn.\n\n 2. Replies are flat. A reply is never nested inside another reply.\n A reply that addresses an earlier reply says so in its body.\n\n 3. A reply carries no thresholding metadata. There is no category,\n no severity and no confidence on a reply. Those are properties\n of the finding, and the finding is the root comment, whose\n severity and confidence govern the whole thread.\n\n 4. A reply carries no suggestion. A concrete counter-proposal goes\n in the reply body as a fenced code block. Allowing a suggestion\n on both the root and a reply would force every consumer to\n invent its own precedence rule.\n\n When a machine consumes a thread, the last human turn is the\n tie-breaker over any earlier machine assertion.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The reply text. May contain markdown formatting, including\n fenced code blocks, which is where a counter-proposal goes\n since replies carry no suggestion element.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment, identical in form and semantics to\n a comment attachment. The path attribute references an image\n file stored in the .self-review-assets/ directory alongside\n the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"author\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The author of this reply, with the same semantics as\n CommentType/@author. When present, the reply was generated by a\n bot or LLM (e.g., \"Claude Opus 5\"). When absent, the reply is\n the human reviewer's.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-id\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Identifier of the remote comment this reply was fetched from,\n with the same semantics as CommentType/@remote-id: an id in the\n forge's own id space, kept for provenance and for a future\n posting feature. Absent on replies authored locally.\n\n A remote-id is not an ordering signal. Document order remains\n conversation order, exactly as rule 1 above states.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"SuggestionType\">\n <xs:annotation>\n <xs:documentation>\n A code replacement proposal. The original-code is the literal text\n currently at the referenced lines. The proposed-code is what the\n reviewer suggests it should be replaced with. The AI agent can apply\n this by performing a text substitution.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"original-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The existing code at the referenced line range, copied verbatim\n from the diff. Used by the AI agent to locate the replacement\n target via text matching.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"proposed-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The replacement code proposed by the reviewer. The AI agent\n should substitute original-code with this text.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n\n <xs:complexType name=\"AttachmentType\">\n <xs:annotation>\n <xs:documentation>\n Reference to an image file attached to a review comment. The file is stored\n alongside the XML output in the .self-review-assets/ directory.\n </xs:documentation>\n </xs:annotation>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>Relative path from the XML file to the image file.</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"media-type\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>MIME type of the image (e.g., image/png, image/jpeg).</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <!-- ===== Simple types ===== -->\n\n <xs:simpleType name=\"ChangeTypeEnum\">\n <xs:annotation>\n <xs:documentation>\n The type of change a file underwent in the diff.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"added\">\n <xs:annotation>\n <xs:documentation>New file that did not exist before.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"modified\">\n <xs:annotation>\n <xs:documentation>Existing file with content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"deleted\">\n <xs:annotation>\n <xs:documentation>File was removed.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"renamed\">\n <xs:annotation>\n <xs:documentation>File was moved or renamed, with or without content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"SeverityEnum\">\n <xs:annotation>\n <xs:documentation>\n How consequential a finding is if it is real. Ordered from most to\n least consequential: critical, major, minor, info.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"critical\">\n <xs:annotation>\n <xs:documentation>\n Causes data loss, a security hole, or a crash or corruption on a\n path that real usage reaches. Shipping this is not acceptable.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"major\">\n <xs:annotation>\n <xs:documentation>\n Produces wrong behaviour, or breaks a documented contract, on a\n path that real usage reaches. The code does not do what it is\n supposed to do, but nothing is destroyed and there is no security\n impact.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"minor\">\n <xs:annotation>\n <xs:documentation>\n Real but bounded: a mishandled edge case that is unlikely to be\n hit, a missing test, a leak of something cheap, or a maintenance\n hazard that will cost time later. Behaviour is correct today.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"info\">\n <xs:annotation>\n <xs:documentation>\n No defect. Style, naming, phrasing, a question for the author, or\n a note recorded for context. Nothing is wrong if this is never\n acted on.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"ConfidenceEnum\">\n <xs:annotation>\n <xs:documentation>\n How sure the author is that a finding is real. Ordered from most to\n least sure: high, medium, low.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"high\">\n <xs:annotation>\n <xs:documentation>\n The evidence is in the code that was read. The failure can be\n traced from the diff itself, and no assumption about unseen code,\n unseen callers, or unstated requirements is needed to reach it.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"medium\">\n <xs:annotation>\n <xs:documentation>\n Likely real, but it rests on one assumption that was not verified,\n such as how a caller behaves, what a dependency guarantees, or\n what the intended requirement was. Stating that assumption in the\n body is expected at this level.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"low\">\n <xs:annotation>\n <xs:documentation>\n Speculative. The failure scenario was imagined rather than traced,\n or the finding depends on a constraint the author invented, or the\n author could not tell intent from the code. Worth a human's eyes,\n not worth acting on unattended.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"RemoteForgeEnum\">\n <xs:annotation>\n <xs:documentation>\n The forge hosting a remote pull/merge request.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"github\">\n <xs:annotation>\n <xs:documentation>A GitHub pull request.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"gitlab\">\n <xs:annotation>\n <xs:documentation>A GitLab merge request.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n</xs:schema>`;\n\nfunction extFromMediaType(mediaType: string): string {\n // Same reasoning as `assetNameComponent`: anything not in the map falls\n // back to png, including a value that is not a string at all.\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\n/**\n * Copies one attachment list's in-memory blobs into the asset directory and\n * returns the list with each fileName rewritten to its on-disk location and the\n * data buffer stripped.\n *\n * Shared by the comment walk and the reply walk. Serialization emits the\n * fileName it is given without checking that anything was written, so an\n * attachment list that misses this function produces a document that validates\n * against the schema while pointing at a file that does not exist. That failure\n * has no error surface, which is why both walks go through here.\n *\n * The idPrefix names the resulting files. Comments pass their own id, so\n * existing asset names are unchanged; replies pass a prefix that cannot collide\n * with a comment's.\n */\n/**\n * Reduce an id to something that can only ever name a file *inside* the asset\n * directory.\n *\n * A comment id is not trusted input. The desktop gets its ReviewState from its\n * own renderer, but the serve front end accepts a whole document over HTTP, so\n * `../../x` in an id would walk this function's write out of the asset\n * directory and onto an arbitrary path. Every id this app generates is a UUID,\n * so restricting the prefix to the URL-safe alphabet renames nothing in\n * practice and leaves existing asset names byte-identical.\n */\nfunction assetNameComponent(idPrefix: string): string {\n // Coerced rather than assumed: this runs before the document is validated\n // against anything, so a caller that omits an id reaches here with\n // `undefined`, and a bare `.replace` would turn that into a crash *after*\n // the review has already been taken off the session — losing it. The\n // serializer's job here is to name a file, not to police the document.\n return String(idPrefix ?? '').replace(/[^A-Za-z0-9_-]/g, '_');\n}\n\nfunction persistAttachments(\n attachments: Attachment[] | undefined,\n idPrefix: string,\n assetDir: string,\n onWrite: () => void\n): Attachment[] | undefined {\n if (!attachments?.length) return attachments;\n\n return attachments.map((att, index) => {\n if (!att.data) return att;\n onWrite();\n\n const ext = extFromMediaType(att.mediaType);\n const fileName = `${assetNameComponent(idPrefix)}-${index}.${ext}`;\n const relativePath = `.self-review-assets/${fileName}`;\n const target = path.join(assetDir, fileName);\n\n // `assetNameComponent` already makes this unreachable. It stays because\n // this write happens *before* the document is validated against the XSD\n // (see `serializeReview`), so a file lands on disk even when serialization\n // goes on to fail — which makes an escape here permanent, and worth a\n // second, independent check rather than one clever regex.\n if (path.dirname(path.resolve(target)) !== path.resolve(assetDir)) {\n throw new Error(`Refusing to write an attachment outside ${assetDir}: ${fileName}`);\n }\n\n if (!fs.existsSync(assetDir)) {\n fs.mkdirSync(assetDir, { recursive: true });\n }\n fs.writeFileSync(target, Buffer.from(att.data));\n\n return { ...att, fileName: relativePath, data: undefined };\n });\n}\n\nfunction writeAttachments(state: ReviewState, outputFilePath: string): ReviewState {\n const assetDir = path.join(path.dirname(outputFilePath), '.self-review-assets');\n let hasAttachments = false;\n const markWritten = () => {\n hasAttachments = true;\n };\n\n const updatedFiles = state.files.map(file => ({\n ...file,\n // Every comment is walked, including one with no attachments of its own:\n // its replies may carry attachments, and short-circuiting on the comment's\n // own list would drop those blobs without a word.\n comments: file.comments.map(comment => ({\n ...comment,\n attachments: persistAttachments(comment.attachments, comment.id, assetDir, markWritten),\n ...(comment.replies\n ? {\n replies: comment.replies.map(reply => ({\n ...reply,\n attachments: persistAttachments(\n reply.attachments,\n `${comment.id}-r-${reply.id}`,\n assetDir,\n markWritten\n ),\n })),\n }\n : {}),\n })),\n }));\n\n if (hasAttachments) {\n console.error(`[main] Wrote attachment files to ${assetDir}`);\n }\n\n return { ...state, files: updatedFiles };\n}\n\nexport async function serializeReview(state: ReviewState, outputFilePath: string): Promise<string> {\n const processedState = writeAttachments(state, outputFilePath);\n const xml = buildXml(processedState);\n\n // Validate the XML against the XSD\n try {\n const validationResult = await validateXML({\n xml: [{ fileName: 'review.xml', contents: xml }],\n schema: [{ fileName: 'self-review-v3.xsd', contents: XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const errors = validationResult.errors || [];\n console.error('XML validation failed:');\n errors.forEach((err: unknown) => console.error(` ${err}`));\n throw new Error('Generated XML does not conform to schema');\n }\n } catch (error) {\n // Re-throw if it's a schema validation failure (our own throw above)\n if (error instanceof Error && error.message === 'Generated XML does not conform to schema') {\n throw error;\n }\n // Infrastructure failure (e.g. WASM load): log warning and return XML anyway\n if (error instanceof Error) {\n console.error(\n `[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`\n );\n } else {\n console.error(\n '[main] XML validation infrastructure failed - emitting XML without validation'\n );\n }\n return xml;\n }\n\n return xml;\n}\n\nfunction buildSourceAttributes(state: ReviewState): string {\n const source = state.source;\n if (source.type === 'git') {\n return ` git-diff-args=\"${escapeXml(source.gitDiffArgs)}\" repository=\"${escapeXml(source.repository)}\"`;\n }\n if (source.type === 'directory' || source.type === 'file') {\n return ` source-path=\"${escapeXml(source.sourcePath)}\"`;\n }\n // welcome mode: no source attributes\n return '';\n}\n\n/**\n * Remote provenance attributes on the review root. Like severity and\n * confidence on a comment, absent means \"not a remote review\", so each\n * attribute is emitted only when its field is set: a purely local review\n * serializes byte-identically to a document written before these existed.\n */\nfunction buildRemoteAttributes(state: ReviewState): string {\n const attrs: string[] = [];\n\n if (state.remoteUrl) {\n attrs.push(`remote-url=\"${escapeXml(state.remoteUrl)}\"`);\n }\n if (state.remoteBaseSha) {\n attrs.push(`remote-base-sha=\"${escapeXml(state.remoteBaseSha)}\"`);\n }\n if (state.remoteHeadSha) {\n attrs.push(`remote-head-sha=\"${escapeXml(state.remoteHeadSha)}\"`);\n }\n if (state.remoteForge) {\n attrs.push(`remote-forge=\"${state.remoteForge}\"`);\n }\n\n return attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n}\n\nfunction buildXml(state: ReviewState): string {\n const lines: string[] = [];\n\n // XML declaration\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n\n // Root element with namespace\n const sourceAttrs = buildSourceAttributes(state);\n const remoteAttrs = buildRemoteAttributes(state);\n lines.push(\n `<review xmlns=\"urn:self-review:v3\" timestamp=\"${escapeXml(state.timestamp)}\"${sourceAttrs}${remoteAttrs}>`\n );\n\n // Files\n for (const file of state.files) {\n lines.push(...buildFileXml(file));\n }\n\n // Close root element\n lines.push('</review>');\n\n return lines.join('\\n');\n}\n\nfunction buildFileXml(file: FileReviewState): string[] {\n const lines: string[] = [];\n\n if (file.comments.length === 0) {\n // Self-closing tag for files with no comments\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\" />`\n );\n } else {\n // Opening tag\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\">`\n );\n\n // Comments\n for (const comment of file.comments) {\n lines.push(...buildCommentXml(comment));\n }\n\n // Closing tag\n lines.push(' </file>');\n }\n\n return lines;\n}\n\nfunction buildCommentXml(comment: ReviewComment): string[] {\n const lines: string[] = [];\n const attrs: string[] = [];\n\n // Add line attributes\n if (comment.lineRange) {\n if (comment.lineRange.side === 'old') {\n attrs.push(`old-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`old-line-end=\"${comment.lineRange.end}\"`);\n } else {\n attrs.push(`new-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`new-line-end=\"${comment.lineRange.end}\"`);\n }\n }\n\n if (comment.author) {\n attrs.push(`author=\"${escapeXml(comment.author)}\"`);\n }\n\n // Thresholding signals. Absent means \"below any floor\", so they are omitted\n // rather than defaulted when the author did not take a position.\n if (comment.severity) {\n attrs.push(`severity=\"${comment.severity}\"`);\n }\n\n if (comment.confidence) {\n attrs.push(`confidence=\"${comment.confidence}\"`);\n }\n\n // Remote provenance. Absent means locally authored, so it is omitted\n // rather than defaulted, exactly like the signals above.\n if (comment.remoteId) {\n attrs.push(`remote-id=\"${escapeXml(comment.remoteId)}\"`);\n }\n\n const attrStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n\n // Opening tag\n lines.push(` <comment${attrStr}>`);\n\n // Body (preserve whitespace and newlines)\n lines.push(` <body>${escapeXml(comment.body)}</body>`);\n\n // Category (required)\n lines.push(` <category>${escapeXml(comment.category)}</category>`);\n\n // Suggestion\n if (comment.suggestion) {\n lines.push(' <suggestion>');\n lines.push(\n ` <original-code>${escapeXml(comment.suggestion.originalCode)}</original-code>`\n );\n lines.push(\n ` <proposed-code>${escapeXml(comment.suggestion.proposedCode)}</proposed-code>`\n );\n lines.push(' </suggestion>');\n }\n\n // Attachments\n lines.push(...buildAttachmentXml(comment.attachments, ' '));\n\n // Replies, in array order: document order is conversation order, and it is\n // the only ordering signal a reply has.\n for (const reply of comment.replies ?? []) {\n lines.push(...buildReplyXml(reply));\n }\n\n // Closing tag\n lines.push(' </comment>');\n\n return lines;\n}\n\n/**\n * Attachment elements are identical in form and meaning under a comment and\n * under a reply, so both call sites emit them from here.\n */\nfunction buildAttachmentXml(attachments: Attachment[] | undefined, indent: string): string[] {\n if (!attachments?.length) return [];\n\n return attachments.map(\n att =>\n `${indent}<attachment path=\"${escapeXml(att.fileName)}\" media-type=\"${escapeXml(att.mediaType)}\" />`\n );\n}\n\n/**\n * A reply is a flat turn in the thread: a body, optional attachments and an\n * optional author. It carries no category, severity, confidence, suggestion or\n * nested replies — those belong to the root comment, which owns the finding.\n * See ReplyType in the XSD for the reasoning.\n */\nfunction buildReplyXml(reply: Reply): string[] {\n const attrs: string[] = [];\n\n if (reply.author) {\n attrs.push(`author=\"${escapeXml(reply.author)}\"`);\n }\n if (reply.remoteId) {\n attrs.push(`remote-id=\"${escapeXml(reply.remoteId)}\"`);\n }\n\n const attrStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n\n return [\n ` <reply${attrStr}>`,\n ` <body>${escapeXml(reply.body)}</body>`,\n ...buildAttachmentXml(reply.attachments, ' '),\n ' </reply>',\n ];\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n","// src/main/xml-parser.ts\n// Parse XML review file back into ReviewComment[]\n\nimport { readFileSync } from 'fs';\nimport { XMLParser } from 'fast-xml-parser';\nimport {\n ReviewComment,\n Suggestion,\n LineRange,\n DiffSource,\n CommentSeverity,\n CommentConfidence,\n RemoteForge,\n Attachment,\n Reply,\n} from './types';\n\nconst SEVERITY_VALUES: readonly CommentSeverity[] = ['critical', 'major', 'minor', 'info'];\nconst CONFIDENCE_VALUES: readonly CommentConfidence[] = ['high', 'medium', 'low'];\nconst REMOTE_FORGE_VALUES: readonly RemoteForge[] = ['github', 'gitlab'];\n\nexport interface ParsedReview {\n comments: ReviewComment[];\n /** Paths of files the previous review marked as done (`viewed=\"true\"`). */\n viewedFiles: string[];\n gitDiffArgs: string;\n source: DiffSource;\n // Remote provenance, read tolerantly off the review root. Undefined when\n // the document carries no remote attributes, i.e. every pre-remote and\n // purely local review.\n remoteUrl?: string;\n remoteBaseSha?: string;\n remoteHeadSha?: string;\n remoteForge?: RemoteForge;\n}\n\nexport function parseReviewXml(xmlPath: string): ParsedReview {\n try {\n const xmlContent = readFileSync(xmlPath, 'utf-8');\n return parseReviewXmlString(xmlContent);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error reading XML file: ${error.message}`);\n } else {\n console.error('Error reading XML file: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function parseReviewXmlString(xmlContent: string): ParsedReview {\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n allowBooleanAttributes: true,\n trimValues: false,\n });\n\n try {\n const result = parser.parse(xmlContent);\n\n if (!result.review) {\n throw new Error('Invalid XML: missing <review> root element');\n }\n\n const review = result.review;\n const gitDiffArgs = review['@_git-diff-args'] || '';\n const source = parseSource(review);\n const comments: ReviewComment[] = [];\n const viewedFiles: string[] = [];\n\n // Handle files array\n const files = toChildArray(review.file);\n\n for (const file of files) {\n // Skip only when the attribute is genuinely absent: the empty string\n // is the review-level sentinel path (REVIEW_LEVEL_FILE_PATH) used by\n // fetch-comments for threads with no file anchor, and must round-trip.\n const rawPath = file['@_path'];\n if (rawPath === undefined || rawPath === null) continue;\n const filePath = String(rawPath);\n\n if (parseViewed(file['@_viewed'])) {\n viewedFiles.push(filePath);\n }\n\n // Handle comments array\n const fileComments = toChildArray(file.comment);\n\n for (const comment of fileComments) {\n const reviewComment: ReviewComment = {\n id: generateId(),\n filePath,\n lineRange: parseLineRange(comment),\n body: comment.body !== undefined ? String(comment.body) : '',\n category: comment.category !== undefined ? String(comment.category) : '',\n suggestion: parseSuggestion(comment),\n author: comment['@_author'] ? String(comment['@_author']) : undefined,\n severity: parseEnumAttribute(comment['@_severity'], SEVERITY_VALUES),\n confidence: parseEnumAttribute(comment['@_confidence'], CONFIDENCE_VALUES),\n remoteId: parseStringAttribute(comment['@_remote-id']),\n };\n\n const attachments = parseAttachments(comment, reviewComment.id);\n if (attachments) reviewComment.attachments = attachments;\n\n const replies = parseReplies(comment);\n if (replies) reviewComment.replies = replies;\n\n comments.push(reviewComment);\n }\n }\n\n return {\n comments,\n viewedFiles,\n gitDiffArgs,\n source,\n remoteUrl: parseStringAttribute(review['@_remote-url']),\n remoteBaseSha: parseStringAttribute(review['@_remote-base-sha']),\n remoteHeadSha: parseStringAttribute(review['@_remote-head-sha']),\n remoteForge: parseEnumAttribute(review['@_remote-forge'], REMOTE_FORGE_VALUES),\n };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error parsing XML: ${error.message}`);\n } else {\n console.error('Error parsing XML: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Read an enumerated attribute, dropping values the schema does not define.\n *\n * An unrecognised value becomes undefined rather than being passed through:\n * undefined is the fail-safe reading (below every threshold floor), and it\n * keeps a resumed review serializable, since the serializer validates its\n * output against the XSD before writing.\n */\nfunction parseEnumAttribute<T extends string>(raw: unknown, allowed: readonly T[]): T | undefined {\n if (raw === undefined || raw === null) return undefined;\n const value = String(raw);\n return allowed.includes(value as T) ? (value as T) : undefined;\n}\n\n/**\n * Read an optional free-form string attribute, leaving absent as undefined.\n * Values are taken as-is: the remote attributes are provenance the app never\n * interprets, so there is nothing to validate on read.\n */\nfunction parseStringAttribute(raw: unknown): string | undefined {\n return raw === undefined || raw === null ? undefined : String(raw);\n}\n\n/**\n * Read the `viewed` attribute of a <file> element.\n *\n * Anything other than an explicit true reads as not viewed: the attribute is\n * optional, and treating an unknown value as \"already reviewed\" would silently\n * hide files from the resumed review.\n */\nfunction parseViewed(raw: unknown): boolean {\n return raw === true || String(raw) === 'true';\n}\n\nfunction parseSource(review: Record<string, unknown>): DiffSource {\n const sourcePath = review['@_source-path'];\n if (sourcePath) {\n return { type: 'directory', sourcePath: String(sourcePath) };\n }\n\n const gitDiffArgs = review['@_git-diff-args'];\n const repository = review['@_repository'];\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: String(gitDiffArgs || ''),\n repository: String(repository || ''),\n };\n }\n\n return { type: 'welcome' };\n}\n\nfunction parseLineRange(comment: Record<string, unknown>): LineRange | null {\n const hasOld =\n comment['@_old-line-start'] !== undefined && comment['@_old-line-end'] !== undefined;\n const hasNew =\n comment['@_new-line-start'] !== undefined && comment['@_new-line-end'] !== undefined;\n\n if (hasOld) {\n return {\n side: 'old',\n start: parseInt(String(comment['@_old-line-start']), 10),\n end: parseInt(String(comment['@_old-line-end']), 10),\n };\n }\n\n if (hasNew) {\n return {\n side: 'new',\n start: parseInt(String(comment['@_new-line-start']), 10),\n end: parseInt(String(comment['@_new-line-end']), 10),\n };\n }\n\n return null; // File-level comment\n}\n\nfunction parseSuggestion(comment: Record<string, unknown>): Suggestion | null {\n if (!comment.suggestion) {\n return null;\n }\n\n const suggestion = comment.suggestion as Record<string, unknown>;\n return {\n originalCode: String(suggestion['original-code'] || ''),\n proposedCode: String(suggestion['proposed-code'] || ''),\n };\n}\n\n/**\n * Normalize a repeatable child element into an array.\n *\n * fast-xml-parser collapses a single occurrence into a bare object and only\n * produces an array from two or more, so every repeatable child in this file\n * has to be widened before it can be iterated. An absent child yields an empty\n * array.\n */\nfunction toChildArray(raw: unknown): Record<string, unknown>[] {\n if (Array.isArray(raw)) return raw as Record<string, unknown>[];\n if (raw === undefined || raw === null) return [];\n return [raw as Record<string, unknown>];\n}\n\n/**\n * Read `<attachment>` children of a comment or a reply.\n *\n * Attachment ids are synthetic: nothing in the document names them, so they are\n * derived from the id of their owner, which is why the prefix is a parameter\n * rather than read off the node. Returns undefined rather than [] when there\n * are none, matching the optional field on the type.\n */\nfunction parseAttachments(\n node: Record<string, unknown>,\n idPrefix: string\n): Attachment[] | undefined {\n const raw = toChildArray(node.attachment);\n if (raw.length === 0) return undefined;\n\n return raw.map((att, i) => ({\n id: `${idPrefix}-att-${i}`,\n fileName: String(att['@_path'] || ''),\n mediaType: String(att['@_media-type'] || 'image/png'),\n }));\n}\n\n/**\n * Read `<reply>` children in document order.\n *\n * Document order is conversation order: a reply carries no timestamp and no\n * identifier, so the order of this array is the only ordering signal a thread\n * ever has. Returns undefined rather than [] when there are none, so a\n * reply-free comment keeps exactly the shape it had before threads existed.\n */\nfunction parseReplies(comment: Record<string, unknown>): Reply[] | undefined {\n const raw = toChildArray(comment.reply);\n if (raw.length === 0) return undefined;\n\n return raw.map(node => {\n const id = generateId();\n const reply: Reply = {\n id,\n body: node.body !== undefined ? String(node.body) : '',\n author: node['@_author'] ? String(node['@_author']) : undefined,\n remoteId: parseStringAttribute(node['@_remote-id']),\n };\n\n const attachments = parseAttachments(node, id);\n if (attachments) reply.attachments = attachments;\n\n return reply;\n });\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// packages/core/src/guide-schema.ts\n// Embedded copy of the walkthrough guide XSD for validation.\n\n// This MUST stay byte-identical to the on-disk copy at\n// .agents/skills/self-review-guide/assets/self-review-guide-v1.xsd;\n// the sync test in xsd-schema.test.ts enforces it.\nexport const GUIDE_XSD_SCHEMA = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sg=\"urn:self-review-guide:v1\"\n targetNamespace=\"urn:self-review-guide:v1\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review guide XML Schema v1\n ===============================\n Defines the walkthrough guide sidecar for the self-review application.\n This schema is designed to be both machine-validated and fed to an LLM\n so it can author valid guide documents from the schema alone.\n\n Key concepts:\n - A <guide> is a read-only orientation aid generated BEFORE a review\n starts. It lives next to the review output file and is discovered by\n convention; it is never written by the review UI.\n - The optional <overview> is short Markdown prose shown before the\n first file, orienting the reviewer to the change as a whole.\n - Each <group> names a set of files that belong together (for example\n \"Core change\", \"Tests\", \"Generated/mechanical\") and explains, in one\n line, why they are grouped and where they sit in the reading order.\n - Each <file> inside a group points at one diff file by its\n repository-relative path and carries a one-line description of the\n role that file plays in the change.\n\n Ordering:\n - Document order IS the reading order. Groups are presented in the\n order they appear, and files within a group are presented in the\n order they appear. There are no explicit ordering attributes; to\n reorder, reorder the elements.\n\n Presentation only, never suppression:\n - This vocabulary labels and orders content; it cannot hide it. There\n is deliberately no element or attribute that hides, collapses, or\n marks a file as skippable, and none may be added to v1. Files in the\n diff that no group mentions remain fully visible in an implicit\n \"Everything else\" group; files mentioned here but absent from the\n diff are silently ignored.\n\n Tolerance:\n - A missing, stale, or invalid guide degrades the consumer to its\n normal ungrouped view. A guide can therefore never block or fail a\n review, but an invalid guide is silently useless, so authors should\n validate against this schema before writing the file.\n -->\n\n <!-- ===== Root element ===== -->\n\n <xs:element name=\"guide\" type=\"sg:GuideType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review walkthrough guide sidecar. Contains\n an optional overview followed by zero or more ordered groups.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <!-- ===== Complex types ===== -->\n\n <xs:complexType name=\"GuideType\">\n <xs:annotation>\n <xs:documentation>\n The whole walkthrough guide. The optional metadata attributes\n mirror the review schema's provenance attributes so a consumer can\n sanity-check that the guide was generated for the diff it is being\n shown next to; none of them are required and none affect\n presentation.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"overview\" type=\"xs:string\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Review-level orientation prose shown before the first file.\n Markdown formatting is allowed, including fenced code blocks;\n a fenced code block labelled \"mermaid\" may be used for a\n diagram of the change.\n Keep it short: a few sentences saying what the change does and\n where to start reading, not a restatement of every file.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"group\" type=\"sg:GroupType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Ordered reading groups. The first group should hold the files\n the reviewer must understand first (the core of the change);\n later groups hold consequences, tests, and mechanical fallout.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the guide was generated.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments the guide was generated against.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when the guide describes a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root the guide was generated in.\n Present only when the guide describes a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"GroupType\">\n <xs:annotation>\n <xs:documentation>\n A named set of related files with a one-line rationale. Groups are\n labels for orientation, never suppressions: a consumer shows every\n group and every file in it. Position in the document is position\n in the reading order.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"rationale\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n One line explaining why these files form a group and what the\n reviewer should look for in them (e.g., \"The retry wrapper\n everything else calls; read this first\"). Plain text, a single\n sentence; no Markdown, no line breaks.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"file\" type=\"sg:FileEntryType\" minOccurs=\"1\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n The files in this group, in reading order. A group must list\n at least one file; do not author empty placeholder groups.\n Every file in the diff may appear in at most one group, and\n files omitted from every group are not hidden — the consumer\n shows them in an implicit trailing \"Everything else\" group.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Short display name for the group, e.g. \"Core change\", \"Tests\",\n \"Generated/mechanical\". Shown as the group heading in the file\n tree; keep it to a few words.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileEntryType\">\n <xs:annotation>\n <xs:documentation>\n One file in a group. The path must match a file in the diff being\n reviewed; entries whose path matches nothing in the diff are\n silently dropped by the consumer, so a stale guide degrades\n instead of erroring.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"description\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n One line describing the role this file plays in the change\n (e.g., \"Adds the retry wrapper that everything else calls\").\n Plain text, a single sentence; no Markdown, no line breaks.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root, using the same\n convention as review.xml file paths. For renamed files, use the\n new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n</xs:schema>`;\n","// packages/core/src/guide-parser.ts\n// Parse a walkthrough guide XML string into a typed ReviewGuide, and\n// reconcile a guide with the diff's file list into resolved display groups.\n//\n// Tolerance contract (binding, from docs/intent/llm-review-guide.md): the\n// guide is orientation garnish on a deterministic tool. A missing, stale, or\n// invalid guide degrades the consumer to its flat view — parsing problems\n// are failure VALUES the caller can log and ignore, never exceptions.\n\nimport { XMLParser } from 'fast-xml-parser';\nimport { validateXML } from 'xmllint-wasm';\nimport type {\n GuideFileEntry,\n GuideGroup,\n ResolvedGuideGroup,\n ResolvedGuideFile,\n ReviewGuide,\n} from './types';\nimport { GUIDE_XSD_SCHEMA } from './guide-schema';\n\n/** Display name given to the derived trailing group of unmentioned files. */\nexport const IMPLICIT_GUIDE_GROUP_NAME = 'Everything else';\n\nexport type GuideParseResult = { ok: true; guide: ReviewGuide } | { ok: false; reason: string };\n\n/**\n * Parse and validate a guide XML string.\n *\n * The document is validated against the embedded self-review-guide-v1 XSD\n * (same xmllint-wasm tooling the review serializer uses) before being read,\n * so a successful result is structurally guaranteed by the schema. Any\n * defect — non-XML input, schema violations, validator failure — comes back\n * as `{ ok: false, reason }`; this function never throws on bad input.\n */\nexport async function parseGuideXml(xmlContent: string): Promise<GuideParseResult> {\n try {\n const validationResult = await validateXML({\n xml: [{ fileName: 'guide.xml', contents: xmlContent }],\n schema: [{ fileName: 'self-review-guide-v1.xsd', contents: GUIDE_XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const details = (validationResult.errors || [])\n .map(err => (typeof err === 'string' ? err : err.message))\n .join('; ');\n return {\n ok: false,\n reason: `Guide XML does not conform to self-review-guide-v1 schema${details ? `: ${details}` : ''}`,\n };\n }\n\n return { ok: true, guide: readGuide(xmlContent) };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, reason: `Failed to parse guide XML: ${message}` };\n }\n}\n\n/**\n * Extract the typed guide from a document that already passed XSD\n * validation. Values are still string-coerced defensively, but structural\n * guarantees (required attributes/elements, at least one file per group)\n * come from the schema.\n */\nfunction readGuide(xmlContent: string): ReviewGuide {\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n // Keep values verbatim: a description like \"007\" or an overview of\n // \"true\" must stay a string, not become a number or boolean.\n parseTagValue: false,\n parseAttributeValue: false,\n // A prefixed form (<sg:guide xmlns:sg=\"urn:self-review-guide:v1\">) is\n // schema-valid, so reading must accept it too; without this the lookup\n // of `.guide` below finds nothing.\n removeNSPrefix: true,\n });\n\n const root = parser.parse(xmlContent).guide as Record<string, unknown>;\n\n const guide: ReviewGuide = { groups: asArray(root.group).map(readGroup) };\n\n const overview = root.overview;\n if (typeof overview === 'string' && overview !== '') {\n guide.overview = overview;\n }\n\n return guide;\n}\n\nfunction readGroup(raw: unknown): GuideGroup {\n const group = raw as Record<string, unknown>;\n return {\n name: String(group['@_name']),\n rationale: String(group.rationale ?? ''),\n files: asArray(group.file).map(readFileEntry),\n };\n}\n\nfunction readFileEntry(raw: unknown): GuideFileEntry {\n const file = raw as Record<string, unknown>;\n return {\n path: String(file['@_path']),\n description: String(file.description ?? ''),\n };\n}\n\n/** fast-xml-parser yields a bare object for singular elements; normalize. */\nfunction asArray(value: unknown): unknown[] {\n if (value === undefined || value === null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Merge a parsed guide with the diff's file list into resolved display\n * groups, tolerantly:\n *\n * - Guide entries whose path is not in the diff are dropped (stale guide);\n * a group left with no surviving files is dropped entirely.\n * - A file referenced by more than one group appears only in the first.\n * - Diff files no group mentions land in a terminal implicit\n * \"Everything else\" group, preserving the diff's file order, marked\n * `implicit: true` so the UI can label it.\n * - Guide group order and in-group file order are preserved.\n */\nexport function reconcileGuide(guide: ReviewGuide, diffFilePaths: string[]): ResolvedGuideGroup[] {\n const diffPaths = new Set(diffFilePaths);\n const claimed = new Set<string>();\n const resolved: ResolvedGuideGroup[] = [];\n\n for (const group of guide.groups) {\n const files: ResolvedGuideFile[] = [];\n for (const file of group.files) {\n if (!diffPaths.has(file.path) || claimed.has(file.path)) continue;\n claimed.add(file.path);\n files.push({ path: file.path, description: file.description });\n }\n if (files.length > 0) {\n resolved.push({\n name: group.name,\n rationale: group.rationale,\n implicit: false,\n files,\n });\n }\n }\n\n const leftover = diffFilePaths.filter(path => !claimed.has(path));\n if (leftover.length > 0) {\n resolved.push({\n name: IMPLICIT_GUIDE_GROUP_NAME,\n implicit: true,\n files: leftover.map(path => ({ path })),\n });\n }\n\n return resolved;\n}\n","// forge-provider.ts\n// Conversation-plane forge abstraction: URL parsing with forge detection by\n// path shape, the ForgeProvider interface (base-branch lookup + thread fetch),\n// and the forge-neutral normalized thread types produced by every provider.\n//\n// This module is pure code: no I/O, no child processes. Provider\n// implementations (github-provider.ts, gitlab-provider.ts) do the CLI work\n// through an injectable command runner so they stay unit-testable.\n\n/** Forges the app knows how to talk to. */\nexport type ForgeName = 'github' | 'gitlab';\n\n/**\n * A parsed pull-request / merge-request web URL.\n *\n * Detection is by URL path shape only (`/pull/N` → GitHub,\n * `/-/merge_requests/N` → GitLab) on any host, so self-hosted instances such\n * as git.drupalcode.org work with zero configuration.\n */\nexport interface ForgeUrl {\n forge: ForgeName;\n /** Host as it appears in the URL, including a port when present. */\n host: string;\n /**\n * Repository owner. For GitLab this is the full namespace path and may\n * contain slashes (subgroups, e.g. `group/subgroup`); for GitHub it is a\n * single segment.\n */\n owner: string;\n /** Repository name (final path segment before the PR/MR marker). */\n repo: string;\n /** Pull-request number / merge-request IID. */\n number: number;\n}\n\n/** Which side of the diff a thread anchor points at. */\nexport type ForgeAnchorSide = 'old' | 'new';\n\n/**\n * Forge-neutral anchor of a discussion thread onto the diff.\n *\n * The mapper consumes this shape without forge-conditional logic:\n * - `startLine`/`endLine` are equal for single-line anchors.\n * - `startLine`/`endLine` are `null` when the forge supplies a file path but\n * no usable line information (the mapper degrades to a file-level comment;\n * `side` is meaningless in that case and providers should set `'new'`).\n * - `outdated: true` means the forge reports the anchor no longer applies to\n * the current head (e.g. GitHub outdated review comments); the line fields\n * then hold the historic anchor and the mapper degrades to file-level.\n */\nexport interface ForgeThreadAnchor {\n filePath: string;\n side: ForgeAnchorSide;\n startLine: number | null;\n endLine: number | null;\n outdated: boolean;\n}\n\n/** One turn (root comment or reply) in a forge discussion thread. */\nexport interface ForgeThreadTurn {\n /** Forge-assigned comment/note ID, kept as a string verbatim. */\n remoteId: string;\n /** Forge username of the turn's author. */\n author: string;\n /** Markdown body, passed through verbatim. */\n body: string;\n}\n\n/**\n * A normalized discussion thread: an ordered root + flat replies.\n *\n * The root turn owns the anchor. `anchor` is `null` for threads with no file\n * association at all (e.g. GitLab non-diff discussions); the mapper turns\n * those into its review-level representation. `replies` preserve the forge's\n * document order — nothing else sorts them.\n */\nexport interface ForgeThread {\n root: ForgeThreadTurn;\n replies: ForgeThreadTurn[];\n anchor: ForgeThreadAnchor | null;\n}\n\n/** Options for {@link ForgeProvider.fetchThreads}. */\nexport interface FetchThreadsOptions {\n /**\n * Include threads the forge marks resolved. Defaults to false where the\n * forge tracks resolution (GitLab); providers without a comparable concept\n * on the fetch path (GitHub REST review comments) may ignore it.\n */\n includeResolved?: boolean;\n}\n\n/**\n * Result of running a forge CLI command through {@link ForgeCommandRunner}.\n */\nexport interface ForgeCommandResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n}\n\n/**\n * Injectable command runner used by provider implementations, mirroring how\n * `git.ts` keeps child-process execution testable. Resolves with the exit\n * code on any completed run (including non-zero); rejects only when the\n * binary cannot be spawned at all (e.g. ENOENT when the CLI is absent).\n */\nexport type ForgeCommandRunner = (command: string, args: string[]) => Promise<ForgeCommandResult>;\n\n/**\n * The conversation plane of a forge. Exactly two capabilities: base-branch\n * lookup and discussion-thread fetching. No diff fetching, no blob fetching,\n * no posting — those concerns live elsewhere.\n *\n * Implementations throw {@link ForgeCliUnavailableError} when their CLI is\n * absent or unauthenticated so callers can degrade cleanly.\n */\nexport interface ForgeProvider {\n readonly forge: ForgeName;\n /** Resolve the PR/MR base (target) branch name. */\n fetchBaseBranch(url: ForgeUrl): Promise<string>;\n /** Fetch the PR/MR discussion threads in normalized form. */\n fetchThreads(url: ForgeUrl, options?: FetchThreadsOptions): Promise<ForgeThread[]>;\n}\n\n/**\n * Thrown by providers when their CLI is missing (spawn ENOENT) or exits\n * non-zero due to authentication/API failure. Callers catch this to degrade\n * (print to stderr, continue without threads) instead of crashing.\n */\nexport class ForgeCliUnavailableError extends Error {\n readonly forge: ForgeName;\n readonly cli: string;\n\n constructor(forge: ForgeName, cli: string, message: string) {\n super(message);\n this.name = 'ForgeCliUnavailableError';\n this.forge = forge;\n this.cli = cli;\n }\n}\n\n// Path-shape matchers. The number must terminate its path segment so\n// `/pull/12x` does not parse as PR 12; anything after the number segment\n// (trailing slash, sub-pages like /files) still identifies the same PR/MR.\n// Numbered groups (owner, repo, number in order): the app tsconfig targets\n// ES6, which predates named capture groups.\nconst GITHUB_PR_PATH = /^\\/([^/]+)\\/([^/]+)\\/pull\\/(\\d+)(?=\\/|$)/;\nconst GITLAB_MR_PATH = /^\\/(.+)\\/([^/]+)\\/-\\/merge_requests\\/(\\d+)(?=\\/|$)/;\n\n/**\n * Parse a forge web URL into a {@link ForgeUrl}, or return `null` for\n * anything that is not a PR/MR URL. Detection is by path shape only, on any\n * http(s) host. Query strings and fragments are ignored.\n */\nexport function parseForgeUrl(url: string): ForgeUrl | null {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return null;\n }\n\n // GitLab first: `/-/merge_requests/` is the more specific marker.\n const gitlab = GITLAB_MR_PATH.exec(parsed.pathname);\n if (gitlab) {\n return {\n forge: 'gitlab',\n host: parsed.host,\n owner: gitlab[1],\n repo: gitlab[2],\n number: Number.parseInt(gitlab[3], 10),\n };\n }\n\n const github = GITHUB_PR_PATH.exec(parsed.pathname);\n if (github) {\n return {\n forge: 'github',\n host: parsed.host,\n owner: github[1],\n repo: github[2],\n number: Number.parseInt(github[3], 10),\n };\n }\n\n return null;\n}\n","// src/main/directory-scanner.ts\n// Recursively scans a directory and produces DiffFile[] treating all files as new additions.\n\nimport { readdir, stat } from 'fs/promises';\nimport { join, relative, basename, dirname } from 'path';\nimport { DiffFile } from './types';\nimport { generateSyntheticDiffs } from './synthetic-diff';\nimport { parseDiff } from './diff-parser';\nimport { createIgnoreFilter } from './ignore-filter';\n\n/**\n * Recursively scan a directory and return DiffFile[] with every file\n * treated as a new addition (changeType: 'added').\n *\n * @param directoryPath - Absolute path to the directory to scan\n * @param ignorePatterns - Optional gitignore-compatible patterns to exclude files\n * @returns Parsed DiffFile array for all files in the directory\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = []\n): Promise<DiffFile[]> {\n // Verify the path is a directory\n try {\n const dirStat = await stat(directoryPath);\n if (!dirStat.isDirectory()) {\n console.error(`Error: \"${directoryPath}\" is not a directory`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing directory \"${directoryPath}\": ${error.message}`);\n } else {\n console.error(`Error accessing directory \"${directoryPath}\": unknown error`);\n }\n return [];\n }\n\n const filePaths: string[] = [];\n\n try {\n const entries = await readdir(directoryPath, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n\n // Build the full path from the entry's parentPath (or path) and name\n const parentDir = entry.parentPath ?? entry.path;\n const fullPath = join(parentDir, entry.name);\n const relativePath = relative(directoryPath, fullPath);\n filePaths.push(relativePath);\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error reading directory \"${directoryPath}\": ${error.message}`);\n } else {\n console.error(`Error reading directory \"${directoryPath}\": unknown error`);\n }\n return [];\n }\n\n // Sort for deterministic output\n filePaths.sort();\n\n // Apply ignore patterns\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredPaths = filePaths.filter(p => shouldKeep(p));\n\n if (filteredPaths.length === 0) {\n return [];\n }\n\n const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);\n return parseDiff(diffText);\n}\n\n/**\n * Scan a single file and return DiffFile[] with the file treated as a new addition.\n *\n * @param filePath - Absolute path to the file to scan\n * @returns Parsed DiffFile array (single element)\n */\nexport async function scanFile(filePath: string): Promise<DiffFile[]> {\n try {\n const fileStat = await stat(filePath);\n if (!fileStat.isFile()) {\n console.error(`Error: \"${filePath}\" is not a file`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing file \"${filePath}\": ${error.message}`);\n } else {\n console.error(`Error accessing file \"${filePath}\": unknown error`);\n }\n return [];\n }\n\n const fileName = basename(filePath);\n const rootDir = dirname(filePath);\n const diffText = generateSyntheticDiffs([fileName], rootDir);\n return parseDiff(diffText);\n}\n","// src/main/ignore-filter.ts\n// Gitignore-compatible file path filtering using the `ignore` package.\n\nimport ignore from 'ignore';\n\n/**\n * Create a filter function from gitignore-compatible patterns.\n *\n * @param patterns - Array of gitignore-compatible glob patterns\n * @returns A predicate that returns `true` if the path should be kept (not ignored)\n */\nexport function createIgnoreFilter(patterns: string[]): (path: string) => boolean {\n if (patterns.length === 0) return () => true;\n const ig = ignore().add(patterns);\n return (filePath: string) => !ig.ignores(filePath);\n}\n","// src/main/config.ts\n// YAML configuration loading and merging\n\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { parse as parseYaml } from 'yaml';\nimport { AppConfig } from './types';\n\nconst defaults: AppConfig = {\n theme: 'system',\n diffView: 'split',\n fontSize: 14,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: [\n '.git',\n 'node_modules',\n 'vendor',\n '.vendor',\n '__pycache__',\n '.venv',\n 'venv',\n '.env',\n 'dist',\n 'build',\n '.next',\n '.nuxt',\n '.svelte-kit',\n 'target',\n '*.min.js',\n '*.min.css',\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Gemfile.lock',\n 'Cargo.lock',\n 'poetry.lock',\n 'go.sum',\n ],\n categories: [\n {\n name: 'question',\n description: 'Clarification needed — not necessarily a problem',\n color: '#805ad5',\n },\n {\n name: 'bug',\n description: 'Likely defect or incorrect behavior',\n color: '#e53e3e',\n },\n {\n name: 'security',\n description: 'Security vulnerability or concern',\n color: '#dd6b20',\n },\n {\n name: 'style',\n description: 'Code style, naming, or formatting issue',\n color: '#3182ce',\n },\n {\n name: 'task',\n description: 'Action item or follow-up task',\n color: '#38a169',\n },\n {\n name: 'nit',\n description: 'Minor nitpick, low priority',\n color: '#718096',\n },\n ],\n defaultDiffArgs: '',\n showUntracked: true,\n showUntrackedExplicit: false,\n wordWrap: true,\n maxFiles: 500,\n maxTotalLines: 100000,\n};\n\nexport function loadConfig(): AppConfig {\n let config = { ...defaults };\n\n // Load user-level config\n const userConfigPath = join(homedir(), '.config', 'self-review', 'config.yaml');\n if (existsSync(userConfigPath)) {\n try {\n const userConfig = loadYamlConfig(userConfigPath);\n config = mergeConfig(config, userConfig);\n } catch (error) {\n console.error(`Warning: Failed to load user config from ${userConfigPath}: ${error}`);\n }\n }\n\n // Load project-level config\n const projectConfigPath = join(process.cwd(), '.self-review.yaml');\n if (existsSync(projectConfigPath)) {\n try {\n const projectConfig = loadYamlConfig(projectConfigPath);\n config = mergeConfig(config, projectConfig);\n } catch (error) {\n console.error(`Warning: Failed to load project config from ${projectConfigPath}: ${error}`);\n }\n }\n\n return config;\n}\n\nfunction loadYamlConfig(path: string): Partial<AppConfig> {\n const content = readFileSync(path, 'utf-8');\n const raw = parseYaml(content);\n\n // An empty file (or one containing only `null`) is a valid \"use defaults\" state.\n if (raw === null || raw === undefined) {\n return {};\n }\n\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error('Invalid YAML format');\n }\n\n // Map kebab-case keys to camelCase\n const config: Partial<AppConfig> = {};\n\n if ('theme' in raw) {\n if (['light', 'dark', 'system'].includes(raw.theme)) {\n config.theme = raw.theme;\n } else {\n console.error(`Warning: Invalid theme value \"${raw.theme}\", using default`);\n }\n }\n\n if ('diff-view' in raw) {\n if (['split', 'unified'].includes(raw['diff-view'])) {\n config.diffView = raw['diff-view'];\n } else {\n console.error(`Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`);\n }\n }\n\n if ('font-size' in raw && typeof raw['font-size'] === 'number') {\n config.fontSize = raw['font-size'];\n }\n\n if ('output-format' in raw && typeof raw['output-format'] === 'string') {\n config.outputFormat = raw['output-format'];\n }\n\n if ('ignore' in raw && Array.isArray(raw.ignore)) {\n config.ignore = raw.ignore.filter((item: unknown) => typeof item === 'string');\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n const usableCategories = raw.categories.filter(\n (cat: unknown): cat is { name: string; description: string; color: string } =>\n cat !== null &&\n typeof cat === 'object' &&\n typeof (cat as Record<string, unknown>).name === 'string' &&\n (cat as Record<string, unknown>).name !== '' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n\n // A `categories` list that leaves no usable entry (empty list, every entry\n // shaped wrong, or every entry named '') would silently disable commenting,\n // so it's treated the same as any other invalid value: warn and keep the default.\n if (usableCategories.length > 0) {\n config.categories = usableCategories;\n } else {\n console.error(\n 'Warning: Category configuration has no usable categories, using default categories'\n );\n }\n }\n\n if ('default-diff-args' in raw && typeof raw['default-diff-args'] === 'string') {\n config.defaultDiffArgs = raw['default-diff-args'];\n }\n\n if ('show-untracked' in raw && typeof raw['show-untracked'] === 'boolean') {\n config.showUntracked = raw['show-untracked'];\n config.showUntrackedExplicit = true;\n }\n\n if ('word-wrap' in raw && typeof raw['word-wrap'] === 'boolean') {\n config.wordWrap = raw['word-wrap'];\n }\n\n if ('max-files' in raw && typeof raw['max-files'] === 'number') {\n config.maxFiles = raw['max-files'] >= 0 ? raw['max-files'] : defaults.maxFiles;\n }\n\n if ('max-total-lines' in raw && typeof raw['max-total-lines'] === 'number') {\n config.maxTotalLines =\n raw['max-total-lines'] >= 0 ? raw['max-total-lines'] : defaults.maxTotalLines;\n }\n\n if (\n 'output-file' in raw &&\n typeof raw['output-file'] === 'string' &&\n raw['output-file'].length > 0\n ) {\n config.outputFile = raw['output-file'];\n }\n\n if (\n 'guide-file' in raw &&\n typeof raw['guide-file'] === 'string' &&\n raw['guide-file'].length > 0\n ) {\n config.guideFile = raw['guide-file'];\n }\n\n return config;\n}\n\nfunction mergeConfig(base: AppConfig, override: Partial<AppConfig>): AppConfig {\n return {\n ...base,\n ...override,\n // Arrays are replaced, not merged\n ignore: override.ignore !== undefined ? override.ignore : base.ignore,\n categories: override.categories !== undefined ? override.categories : base.categories,\n };\n}\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Compute payload statistics and check against configured thresholds.\n * A maxFiles or maxTotalLines value of 0 disables that guard.\n */\nexport function computePayloadStats(\n fileCount: number,\n totalLines: number,\n config: AppConfig\n): PayloadStats {\n const maxFiles = config.maxFiles;\n const maxTotalLines = config.maxTotalLines;\n const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;\n const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;\n return {\n fileCount,\n totalLines,\n exceedsFiles,\n exceedsLines,\n exceedsAny: exceedsFiles || exceedsLines,\n };\n}\n\n/**\n * Count total diff lines across all files and hunks.\n */\nexport function countTotalLines(files: DiffFile[]): number {\n let total = 0;\n for (const file of files) {\n for (const hunk of file.hunks) {\n total += hunk.lines.length;\n }\n }\n return total;\n}\n\n/**\n * Get git diff stats cheaply using --numstat (avoids full diff parsing).\n * Each output line is \"added\\tremoved\\tfilename\".\n * Returns file count and total changed lines (added + removed).\n */\nexport async function getGitDiffStats(\n args: string[],\n repoRoot: string\n): Promise<{ fileCount: number; totalLines: number }> {\n try {\n const { stdout } = await execFileAsync('git', ['diff', '--numstat', ...args], {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 15000,\n cwd: repoRoot,\n });\n\n let fileCount = 0;\n let totalLines = 0;\n\n for (const line of stdout.trim().split('\\n')) {\n if (!line) continue;\n const parts = line.split('\\t');\n if (parts.length < 3) continue;\n\n fileCount++;\n // Binary files show '-' for added/removed\n const added = parts[0] === '-' ? 0 : parseInt(parts[0], 10);\n const removed = parts[1] === '-' ? 0 : parseInt(parts[1], 10);\n totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);\n }\n\n return { fileCount, totalLines };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);\n } else {\n console.error('[payload-sizing] Failed to get git diff stats: unknown error');\n }\n // Return zeros so the guard does not block on failure\n return { fileCount: 0, totalLines: 0 };\n }\n}\n","// src/main/fs-utils.ts\n// Filesystem utility functions for the main process.\n\nimport { accessSync, constants as fsConstants } from 'fs';\nimport { dirname } from 'path';\n\n/**\n * Check if a file's parent directory is writable.\n * Returns true if the directory exists and the process has write permission,\n * false otherwise (including non-existent directories).\n */\nexport function checkWritability(filePath: string): boolean {\n try {\n const dir = dirname(filePath);\n accessSync(dir, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","// apply-suggestion.ts\n// Writes one anchored suggestion into one working file, or refuses and\n// writes nothing. Node-only, Electron-free, and free of process-global\n// state: the caller names the destination root, so nothing here ever\n// consults `process.cwd()`.\n//\n// The engine is deliberately narrow. It performs a byte-for-byte context\n// check and a literal line replacement — no fuzzy matching, no force flag,\n// no staging, no git. Every outcome is reported: a refusal names its reason\n// and leaves the file untouched (PRD Section 5.4.8).\n\nimport { readFileSync, writeFileSync } from 'fs';\nimport { isAbsolute, relative, resolve, sep } from 'path';\nimport type { LineRange, Suggestion } from './types';\n\n/**\n * Why an apply was refused. Every value is a structural fact about the\n * request or the file — never a fragment of the file's contents, so a\n * refusal is safe to surface in the UI and in logs.\n */\nexport type ApplyRefusalReason =\n /** The suggestion is file-level: there is nothing to replace. */\n | 'no-anchor'\n /**\n * The anchor names deleted lines (`side: 'old'`). Those lines are not in\n * the working file, and the app holds no old→new line mapping, so the\n * target is undefined rather than merely missing.\n */\n | 'old-side-anchor'\n /** `destinationRoot` is relative; resolving it would consult the cwd. */\n | 'destination-not-absolute'\n /** `filePath` resolves outside `destinationRoot`. */\n | 'path-escapes-destination'\n /** No file at the resolved path. */\n | 'file-missing'\n /** The path exists but could not be read (permissions, a directory, …). */\n | 'file-unreadable'\n /**\n * The file is not valid UTF-8. Rewriting it would round-trip its bytes\n * through a lossy decode and corrupt regions outside the anchor.\n */\n | 'file-not-utf8'\n /** The anchor falls outside the file's line count. */\n | 'anchor-out-of-range'\n /** The anchored lines no longer match `suggestion.originalCode`. */\n | 'context-mismatch'\n /** The context matched but the write itself failed. */\n | 'write-failed';\n\nexport interface ApplySuggestionRequest {\n /**\n * Absolute path of the directory the reviewed files live in. Always\n * supplied by the caller: a git-mode working tree, a directory-mode root,\n * a reused clone, or the destination the user picked for a temporary-clone\n * review. Never derived here.\n */\n destinationRoot: string;\n /** Path of the file to modify, relative to `destinationRoot`. */\n filePath: string;\n /** The comment's anchor. `null` (file-level) is refused. */\n lineRange: LineRange | null;\n suggestion: Suggestion;\n}\n\nexport interface ApplySuggestionApplied {\n status: 'applied';\n /** Echoed from the request, so a batch caller can attribute the result. */\n filePath: string;\n absolutePath: string;\n /** How many on-disk lines the proposal replaced. */\n replacedLines: number;\n}\n\nexport interface ApplySuggestionRefused {\n status: 'refused';\n filePath: string;\n reason: ApplyRefusalReason;\n /** One sentence naming the refusal, safe to show to the reviewer. */\n detail: string;\n}\n\nexport type ApplySuggestionResult = ApplySuggestionApplied | ApplySuggestionRefused;\n\nfunction refuse(\n filePath: string,\n reason: ApplyRefusalReason,\n detail: string\n): ApplySuggestionRefused {\n return { status: 'refused', filePath, reason, detail };\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return (error as NodeJS.ErrnoException | undefined)?.code;\n}\n\n/**\n * Split file text into lines, keeping each line's own bytes intact.\n *\n * The split is on `\\n` only, so a CRLF file's `\\r` stays at the end of the\n * line it terminates. That makes the comparison against `originalCode`\n * byte-exact (the diff parser hands the same `\\r` through in `DiffLine`),\n * and it means rejoining preserves mixed line endings exactly as found.\n */\nfunction splitLines(content: string): string[] {\n if (content === '') return [];\n const lines = content.split('\\n');\n // A trailing terminator produces an empty final element that is not a line.\n if (lines[lines.length - 1] === '') lines.pop();\n return lines;\n}\n\n/**\n * True when every line being replaced carries a CRLF terminator. Only then\n * is it unambiguous that a hand-typed LF proposal should be written back as\n * CRLF; a mixed or LF region takes the proposal verbatim.\n */\nfunction isCrlfRegion(anchored: string[]): boolean {\n return anchored.length > 0 && anchored.every(line => line.endsWith('\\r'));\n}\n\n/**\n * Apply one anchored suggestion to one file under `destinationRoot`.\n *\n * On a byte-for-byte match between the anchored lines and\n * `suggestion.originalCode`, the anchored lines are replaced with\n * `suggestion.proposedCode` and the file is rewritten. Lines outside the\n * anchor keep their exact bytes, including their line terminators, and the\n * file's trailing-newline state is preserved either way. Any other outcome\n * refuses with a reason and writes nothing.\n */\nexport function applySuggestion(request: ApplySuggestionRequest): ApplySuggestionResult {\n const { destinationRoot, filePath, lineRange, suggestion } = request;\n\n if (!lineRange) {\n return refuse(\n filePath,\n 'no-anchor',\n 'This suggestion is file-level, so there are no lines to replace.'\n );\n }\n if (lineRange.side === 'old') {\n return refuse(\n filePath,\n 'old-side-anchor',\n 'This suggestion is anchored to deleted lines, which are not in the working file.'\n );\n }\n if (!isAbsolute(destinationRoot)) {\n return refuse(\n filePath,\n 'destination-not-absolute',\n 'The destination directory must be an absolute path.'\n );\n }\n\n const root = resolve(destinationRoot);\n const absolutePath = resolve(root, filePath);\n const rel = relative(root, absolutePath);\n if (isAbsolute(filePath) || rel === '' || rel === '..' || rel.startsWith(`..${sep}`)) {\n return refuse(\n filePath,\n 'path-escapes-destination',\n 'The file path resolves outside the destination directory.'\n );\n }\n\n let buffer: Buffer;\n try {\n buffer = readFileSync(absolutePath);\n } catch (error) {\n const code = errorCode(error);\n if (code === 'ENOENT' || code === 'ENOTDIR') {\n return refuse(filePath, 'file-missing', 'The file is not in the destination directory.');\n }\n return refuse(\n filePath,\n 'file-unreadable',\n `The file could not be read (${code ?? 'unknown'}).`\n );\n }\n\n const content = buffer.toString('utf8');\n if (!Buffer.from(content, 'utf8').equals(buffer)) {\n return refuse(filePath, 'file-not-utf8', 'The file is not valid UTF-8 text.');\n }\n\n const lines = splitLines(content);\n const { start, end } = lineRange;\n if (start < 1 || end < start || end > lines.length) {\n return refuse(\n filePath,\n 'anchor-out-of-range',\n `Lines ${start}-${end} are outside this file, which has ${lines.length} line(s).`\n );\n }\n\n const anchored = lines.slice(start - 1, end);\n if (anchored.join('\\n') !== suggestion.originalCode) {\n return refuse(\n filePath,\n 'context-mismatch',\n `Lines ${start}-${end} no longer match the code this suggestion was written against.`\n );\n }\n\n const proposed = suggestion.proposedCode.split('\\n');\n const replacement = isCrlfRegion(anchored)\n ? proposed.map(line => (line.endsWith('\\r') ? line : `${line}\\r`))\n : proposed;\n const updated = [...lines.slice(0, start - 1), ...replacement, ...lines.slice(end)];\n const output = updated.join('\\n') + (content.endsWith('\\n') ? '\\n' : '');\n\n try {\n writeFileSync(absolutePath, output, 'utf8');\n } catch (error) {\n return refuse(\n filePath,\n 'write-failed',\n `The file could not be written (${errorCode(error) ?? 'unknown'}).`\n );\n }\n\n return { status: 'applied', filePath, absolutePath, replacedLines: anchored.length };\n}\n","/**\n * File-type detection utilities.\n *\n * NOTE: This file is intentionally duplicated in packages/react/src/utils/file-type-utils.ts.\n * @self-review/core has Node-only dependencies, so @self-review/react cannot safely import\n * from this package. Both copies must be kept in sync.\n */\n\nconst RASTER_IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.ico', '.bmp']);\nconst MARKDOWN_EXTENSIONS = new Set(['.md', '.markdown']);\nconst HTML_EXTENSIONS = new Set(['.html', '.htm']);\n\nexport type RenderedTextMode = 'markdown' | 'html';\n\nfunction getExtension(filePath: string): string {\n const lastDot = filePath.lastIndexOf('.');\n if (lastDot === -1 || lastDot === filePath.length - 1) return '';\n return filePath.slice(lastDot).toLowerCase();\n}\n\nexport function isPreviewableImage(filePath: string): boolean {\n return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isPreviewableSvg(filePath: string): boolean {\n return getExtension(filePath) === '.svg';\n}\n\nexport function isMarkdownFile(filePath: string): boolean {\n return MARKDOWN_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isHtmlFile(filePath: string): boolean {\n return HTML_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function getRenderedTextMode(filePath: string): RenderedTextMode | null {\n if (isMarkdownFile(filePath)) return 'markdown';\n if (isHtmlFile(filePath)) return 'html';\n return null;\n}\n\nexport function isPreviewableRenderedText(filePath: string): boolean {\n return getRenderedTextMode(filePath) !== null;\n}\n\nexport function getLanguageFromPath(filePath: string): string {\n const ext = filePath.split('.').pop()?.toLowerCase() || '';\n const langMap: Record<string, string> = {\n ts: 'typescript',\n tsx: 'tsx',\n js: 'javascript',\n jsx: 'jsx',\n py: 'python',\n css: 'css',\n json: 'json',\n md: 'markdown',\n markdown: 'markdown',\n sh: 'bash',\n bash: 'bash',\n yml: 'yaml',\n yaml: 'yaml',\n java: 'java',\n go: 'go',\n rs: 'rust',\n sql: 'sql',\n html: 'markup',\n htm: 'markup',\n xml: 'markup',\n rb: 'ruby',\n php: 'php',\n twig: 'twig',\n c: 'c',\n cpp: 'cpp',\n h: 'c',\n hpp: 'cpp',\n // Config and data formats\n ini: 'ini',\n toml: 'toml',\n csv: 'csv',\n diff: 'diff',\n patch: 'diff',\n // Web and infrastructure\n scss: 'scss',\n sass: 'sass',\n graphql: 'graphql',\n gql: 'graphql',\n conf: 'nginx',\n // Database\n mongodb: 'mongodb',\n // Tooling\n makefile: 'makefile',\n mk: 'makefile',\n mak: 'makefile',\n vim: 'vim',\n vimrc: 'vim',\n };\n\n // Check for special filenames without extensions\n const filename = filePath.split('/').pop()?.toLowerCase() || '';\n if (filename === 'dockerfile' || filename.startsWith('dockerfile.')) {\n return 'docker';\n }\n if (filename === 'makefile' || filename.startsWith('makefile.')) {\n return 'makefile';\n }\n if (filename.startsWith('.git')) {\n return 'git';\n }\n if (filename === '.vimrc' || filename.startsWith('.vim')) {\n return 'vim';\n }\n\n return langMap[ext] || 'plaintext';\n}\n","// github-provider.ts\n// GitHub implementation of the ForgeProvider interface, backed entirely by\n// the `gh` CLI through an injectable command runner (never the network\n// directly). Read-only: only `gh pr view` and `gh api` GET calls.\n//\n// GitHub Enterprise-style hosts are honored by passing the URL's host (which\n// may include a port) verbatim to gh: as the HOST/OWNER/REPO form for\n// `pr view --repo` and as `--hostname` for `gh api`. gh's own host handling\n// takes it from there (auth per host, API base URL).\n\nimport {\n ForgeCliUnavailableError,\n type FetchThreadsOptions,\n type ForgeCommandResult,\n type ForgeCommandRunner,\n type ForgeProvider,\n type ForgeThread,\n type ForgeThreadAnchor,\n type ForgeUrl,\n} from './forge-provider';\n\n/** Relevant subset of a GitHub REST pull-request review comment. */\ninterface GitHubReviewComment {\n id: number;\n in_reply_to_id?: number | null;\n /** `null` for deleted user accounts. */\n user: { login: string } | null;\n body: string;\n path: string;\n side?: 'LEFT' | 'RIGHT' | null;\n line: number | null;\n start_line?: number | null;\n original_line?: number | null;\n original_start_line?: number | null;\n}\n\nconst GH_CLI = 'gh';\n\n/**\n * Run a gh command, translating both failure modes into the typed\n * unavailable error: a runner rejection means the CLI could not be spawned\n * (e.g. ENOENT when gh is absent), a non-zero exit means gh ran but failed\n * (unauthenticated, API error). Callers degrade on this error, never crash.\n */\nasync function runGh(runCommand: ForgeCommandRunner, args: string[]): Promise<string> {\n let result: ForgeCommandResult;\n try {\n result = await runCommand(GH_CLI, args);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new ForgeCliUnavailableError('github', GH_CLI, `Failed to run the gh CLI: ${detail}`);\n }\n if (result.exitCode !== 0) {\n const detail = result.stderr.trim() || `exit code ${result.exitCode}`;\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `gh exited with code ${result.exitCode}: ${detail}`\n );\n }\n return result.stdout;\n}\n\n/**\n * Parse gh JSON output, surfacing malformed output as the typed unavailable\n * error so callers keep a single degradation path.\n */\nfunction parseGhJson(stdout: string, context: string): unknown {\n try {\n return JSON.parse(stdout);\n } catch {\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `gh returned unparseable JSON for ${context}`\n );\n }\n}\n\n/**\n * Normalize one review comment's anchor. GitHub reports `line: null` when\n * the comment no longer applies to the head diff (outdated); the\n * `original_*` fields then retain the historic anchor.\n */\nfunction toAnchor(comment: GitHubReviewComment): ForgeThreadAnchor {\n const outdated = comment.line === null || comment.line === undefined;\n const endLine = outdated ? (comment.original_line ?? null) : comment.line;\n const startLine = outdated\n ? (comment.original_start_line ?? comment.original_line ?? null)\n : (comment.start_line ?? comment.line);\n const hasLines = startLine !== null && endLine !== null;\n return {\n filePath: comment.path,\n // Side is meaningless without usable lines; the contract says 'new'.\n side: hasLines && comment.side === 'LEFT' ? 'old' : 'new',\n startLine: hasLines ? startLine : null,\n endLine: hasLines ? endLine : null,\n outdated,\n };\n}\n\n/** GitHub shows deleted user accounts as \"ghost\"; mirror that. */\nfunction toTurn(comment: GitHubReviewComment) {\n return {\n remoteId: String(comment.id),\n author: comment.user?.login ?? 'ghost',\n body: comment.body,\n };\n}\n\n/**\n * Group flat review comments into threads. A comment without\n * `in_reply_to_id` roots a thread; a reply attaches to the thread containing\n * the comment it replies to (root or any member). An orphan reply whose\n * parent is unknown degrades to a thread root of its own. Document order is\n * preserved throughout — nothing sorts.\n */\nfunction groupIntoThreads(comments: GitHubReviewComment[]): ForgeThread[] {\n const threads: ForgeThread[] = [];\n const threadByCommentId = new Map<number, ForgeThread>();\n for (const comment of comments) {\n const parentThread =\n comment.in_reply_to_id === null || comment.in_reply_to_id === undefined\n ? undefined\n : threadByCommentId.get(comment.in_reply_to_id);\n if (parentThread) {\n parentThread.replies.push(toTurn(comment));\n threadByCommentId.set(comment.id, parentThread);\n } else {\n const thread: ForgeThread = {\n root: toTurn(comment),\n replies: [],\n anchor: toAnchor(comment),\n };\n threads.push(thread);\n threadByCommentId.set(comment.id, thread);\n }\n }\n return threads;\n}\n\n/**\n * Create the GitHub {@link ForgeProvider} backed by an injected command\n * runner, mirroring how `git.ts` keeps child-process execution testable.\n */\nexport function createGitHubProvider(runCommand: ForgeCommandRunner): ForgeProvider {\n return {\n forge: 'github',\n\n async fetchBaseBranch(url: ForgeUrl): Promise<string> {\n const stdout = await runGh(runCommand, [\n 'pr',\n 'view',\n String(url.number),\n '--repo',\n `${url.host}/${url.owner}/${url.repo}`,\n '--json',\n 'baseRefName',\n ]);\n const parsed = parseGhJson(stdout, 'pr view') as {\n baseRefName?: unknown;\n };\n if (typeof parsed?.baseRefName !== 'string' || parsed.baseRefName === '') {\n throw new ForgeCliUnavailableError('github', GH_CLI, 'gh pr view returned no baseRefName');\n }\n return parsed.baseRefName;\n },\n\n // The REST review-comment list carries no resolution state, so\n // `options.includeResolved` is deliberately ignored: GitHub fetch\n // returns all review threads (resolved-state filtering is a GitLab\n // concern).\n async fetchThreads(url: ForgeUrl, _options?: FetchThreadsOptions): Promise<ForgeThread[]> {\n const stdout = await runGh(runCommand, [\n 'api',\n `repos/${url.owner}/${url.repo}/pulls/${url.number}/comments`,\n '--hostname',\n url.host,\n '--paginate',\n '--slurp',\n ]);\n // `--paginate --slurp` wraps each response page in an outer array:\n // [[...page1], [...page2]]. Flatten one level to the comment list.\n const pages = parseGhJson(stdout, 'pull request comments');\n if (!Array.isArray(pages)) {\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n 'gh api returned an unexpected payload shape for pull request comments'\n );\n }\n const comments = pages.flat(1) as GitHubReviewComment[];\n return groupIntoThreads(comments);\n },\n };\n}\n","// thread-mapper.ts\n// Deterministic mapper from forge-neutral discussion threads to the v3\n// ReviewComment model. Pure code: no I/O, no randomness, no timestamps —\n// the same input always yields byte-identical output, and it contains no\n// forge-conditional logic (anything forge-specific belongs in the\n// providers). Fetch direction only.\n\nimport type { ForgeThread, ForgeThreadAnchor, ForgeThreadTurn } from './forge-provider';\nimport type { DiffFile, LineRange, Reply, ReviewComment, Suggestion } from './types';\n\n/**\n * Sentinel `filePath` for review-level threads (threads with no file\n * association at all, e.g. GitLab non-diff discussions).\n *\n * The v3 schema has no review-level comment element — every `<comment>`\n * lives inside a `<file path>` — so the mapper degrades these threads to\n * file-level comments on this sentinel path, the closest legal shape.\n * The empty string can never collide with a repository-relative diff path,\n * so consumers (the fetch-comments orchestrator, the app's remote mode)\n * detect review-level comments by comparing against this constant and\n * decide their placement (e.g. a synthetic review-level file entry).\n */\nexport const REVIEW_LEVEL_FILE_PATH = '';\n\n/**\n * Map an anchor to the model's line range, honoring the exactly-one-pair\n * rule: the single `LineRange.side` selects which pair the serializer\n * emits (`'new'` → `new-line-*`, `'old'` → `old-line-*`), so a comment can\n * never carry both.\n *\n * Returns `null` (file-level) when the anchor is outdated, has no usable\n * line information, or carries non-positive lines (the XSD requires\n * `xs:positiveInteger`, and the serializer must never receive an\n * unserializable range). Reversed bounds are normalized rather than\n * rejected so a defective provider payload still maps deterministically.\n */\nfunction mapAnchorToLineRange(anchor: ForgeThreadAnchor): LineRange | null {\n if (anchor.outdated) {\n return null;\n }\n const { startLine, endLine } = anchor;\n if (startLine === null || endLine === null) {\n return null;\n }\n if (startLine < 1 || endLine < 1) {\n return null;\n }\n return {\n side: anchor.side,\n start: Math.min(startLine, endLine),\n end: Math.max(startLine, endLine),\n };\n}\n\n/**\n * Internal ids are in-memory render keys the app normally generates\n * randomly on parse. The mapper must be deterministic, so it derives them\n * from the forge-assigned ids instead.\n */\nfunction internalId(turn: ForgeThreadTurn): string {\n return `remote-${turn.remoteId}`;\n}\n\n/**\n * Opening line of a fenced code block: up to three spaces of indent, then\n * three or more backticks or tildes, then the info string. A fence indented\n * four spaces or more is an indented code block, not a fence.\n */\nconst FENCE_OPEN = /^( {0,3})(`{3,}|~{3,})(.*)$/;\n\n/** Drop a single trailing CR so a CRLF body yields LF-terminated lines. */\nfunction stripCr(line: string): string {\n return line.endsWith('\\r') ? line.slice(0, -1) : line;\n}\n\n/** Remove up to `width` leading spaces, the way CommonMark unindents a fence. */\nfunction stripIndent(line: string, width: number): string {\n let i = 0;\n while (i < width && line[i] === ' ') i++;\n return line.slice(i);\n}\n\n/** A closing fence: the same character, at least as long, nothing after it. */\nfunction isClosingFence(line: string, marker: string): boolean {\n const match = FENCE_OPEN.exec(line);\n return (\n match !== null &&\n match[2][0] === marker[0] &&\n match[2].length >= marker.length &&\n match[3].trim() === ''\n );\n}\n\n/**\n * Collect the bodies of every top-level ` ```suggestion ` block in a\n * markdown body, in document order.\n *\n * Fences are walked in order so a `suggestion` fence nested inside another\n * code block is never mistaken for a real one. The info string must be the\n * bare word `suggestion`: GitLab's range form (`suggestion:-1+2`) widens the\n * anchor by an amount this mapper cannot verify against the diff, so it is\n * deliberately not recognized and leaves the thread without a suggestion.\n */\nfunction findSuggestionBlocks(body: string): string[] {\n const lines = body.split('\\n').map(stripCr);\n const blocks: string[] = [];\n let i = 0;\n while (i < lines.length) {\n const open = FENCE_OPEN.exec(lines[i]);\n if (!open) {\n i++;\n continue;\n }\n const [, indent, marker, info] = open;\n // A backtick fence's info string may not contain a backtick.\n if (marker[0] === '`' && info.includes('`')) {\n i++;\n continue;\n }\n const content: string[] = [];\n let j = i + 1;\n for (; j < lines.length && !isClosingFence(lines[j], marker); j++) {\n content.push(stripIndent(lines[j], indent.length));\n }\n if (info.trim().toLowerCase() === 'suggestion') {\n blocks.push(content.join('\\n'));\n }\n // An unclosed fence runs to the end of the body, as GitHub renders it.\n i = j + 1;\n }\n return blocks;\n}\n\n/**\n * Read the reviewed lines the anchor points at, straight out of the diff.\n *\n * Returns `null` unless the diff covers the whole range: a partially covered\n * anchor would produce an `originalCode` that matches nothing, and the apply\n * engine's byte-for-byte check would refuse it anyway. Taking the text from\n * the diff rather than from the thread body is what makes the extracted\n * suggestion anchored rather than merely quoted.\n */\nfunction readAnchoredLines(\n diffFiles: DiffFile[],\n filePath: string,\n range: LineRange\n): string | null {\n const sidePath = (file: DiffFile) => (range.side === 'old' ? file.oldPath : file.newPath);\n const file =\n diffFiles.find(f => sidePath(f) === filePath) ??\n diffFiles.find(f => f.oldPath === filePath || f.newPath === filePath);\n if (!file) return null;\n\n const found: string[] = [];\n for (const hunk of file.hunks) {\n for (const line of hunk.lines) {\n const number = range.side === 'old' ? line.oldLineNumber : line.newLineNumber;\n if (number !== null && number >= range.start && number <= range.end) {\n found.push(line.content);\n }\n }\n }\n return found.length === range.end - range.start + 1 ? found.join('\\n') : null;\n}\n\n/**\n * Turn a `suggestion` fence in a thread's root body into an anchored\n * {@link Suggestion}, or `null` when there is nothing safe to anchor.\n *\n * `null` covers every uncertain case: no fence, more than one fence (the\n * model holds a single suggestion, and silently keeping the first would drop\n * the rest), a file-level or outdated anchor, and an anchor the reviewed\n * diff does not cover.\n */\nfunction extractSuggestion(\n body: string,\n filePath: string,\n range: LineRange | null,\n diffFiles: DiffFile[]\n): Suggestion | null {\n if (!range) return null;\n const blocks = findSuggestionBlocks(body);\n if (blocks.length !== 1) return null;\n const originalCode = readAnchoredLines(diffFiles, filePath, range);\n if (originalCode === null) return null;\n return { originalCode, proposedCode: blocks[0] };\n}\n\nfunction mapReply(turn: ForgeThreadTurn): Reply {\n return {\n id: internalId(turn),\n body: turn.body,\n author: turn.author,\n remoteId: turn.remoteId,\n };\n}\n\n/**\n * Convert normalized forge threads into v3 `ReviewComment` threads.\n *\n * - The root turn becomes the root comment and owns the anchor; subsequent\n * turns become flat replies in document order (nothing sorts them).\n * - Forge usernames land in `author`, forge thread/comment ids in\n * `remoteId`, markdown bodies pass through verbatim.\n * - Outdated or line-less anchors degrade to file-level comments\n * (`lineRange: null`); anchor-less threads degrade to file-level\n * comments on {@link REVIEW_LEVEL_FILE_PATH}. The degradation is\n * structural, never textual.\n * - Mapped comments carry no category, severity or confidence: forge\n * threads have none, and absent means below every threshold. The empty\n * `category` matches how the XML parser represents a missing category.\n * - A root body carrying a single ` ```suggestion ` fence becomes a\n * `Suggestion` anchored to the thread's line range, with `originalCode`\n * read out of `diffFiles` at that anchor. Without the reviewed diff there\n * is nothing to anchor against, so the default leaves every\n * `suggestion: null` exactly as before.\n *\n * Output order is input order. The input is never mutated.\n */\nexport function mapThreadsToReviewComments(\n threads: ForgeThread[],\n diffFiles: DiffFile[] = []\n): ReviewComment[] {\n return threads.map(thread => {\n const filePath = thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH;\n const lineRange = thread.anchor ? mapAnchorToLineRange(thread.anchor) : null;\n const comment: ReviewComment = {\n id: internalId(thread.root),\n filePath,\n lineRange,\n body: thread.root.body,\n category: '',\n suggestion: extractSuggestion(thread.root.body, filePath, lineRange, diffFiles),\n author: thread.root.author,\n remoteId: thread.root.remoteId,\n };\n if (thread.replies.length > 0) {\n comment.replies = thread.replies.map(mapReply);\n }\n return comment;\n });\n}\n","// gitlab-provider.ts\n// ForgeProvider implementation for GitLab (gitlab.com and self-hosted) backed\n// by the read-only `glab` CLI. All child-process execution goes through an\n// injected ForgeCommandRunner so the provider stays unit-testable and no real\n// `glab` calls happen in tests. Only GET-style commands are issued (`glab\n// api`); nothing is ever posted.\n\nimport {\n ForgeCliUnavailableError,\n type FetchThreadsOptions,\n type ForgeAnchorSide,\n type ForgeCommandRunner,\n type ForgeProvider,\n type ForgeThread,\n type ForgeThreadAnchor,\n type ForgeThreadTurn,\n type ForgeUrl,\n} from './forge-provider';\n\nconst GLAB_CLI = 'glab';\n\n// --- Minimal shapes of the GitLab API payloads we consume ---------------\n\ninterface GitLabLineRangeEdge {\n old_line?: number | null;\n new_line?: number | null;\n}\n\ninterface GitLabPosition {\n old_path?: string | null;\n new_path?: string | null;\n old_line?: number | null;\n new_line?: number | null;\n line_range?: {\n start?: GitLabLineRangeEdge | null;\n end?: GitLabLineRangeEdge | null;\n } | null;\n}\n\ninterface GitLabNote {\n id: number | string;\n body?: string;\n author?: { username?: string } | null;\n system?: boolean;\n resolvable?: boolean;\n resolved?: boolean;\n position?: GitLabPosition | null;\n}\n\ninterface GitLabDiscussion {\n id: string;\n notes?: GitLabNote[];\n}\n\n// --- CLI plumbing -------------------------------------------------------\n\n/** URL-encode the full project path; subgroup slashes become %2F. */\nfunction encodeProjectPath(url: ForgeUrl): string {\n return encodeURIComponent(`${url.owner}/${url.repo}`);\n}\n\nfunction unavailable(message: string): ForgeCliUnavailableError {\n return new ForgeCliUnavailableError('gitlab', GLAB_CLI, message);\n}\n\n/**\n * Run `glab api <endpoint>` against the URL's host and return raw stdout.\n * Spawn failures (ENOENT) and non-zero exits (unauthenticated, API errors)\n * both surface as {@link ForgeCliUnavailableError}.\n */\nasync function runGlabApi(\n runCommand: ForgeCommandRunner,\n url: ForgeUrl,\n endpoint: string,\n extraArgs: string[] = []\n): Promise<string> {\n const args = ['api', endpoint, '--hostname', url.host, ...extraArgs];\n let result;\n try {\n result = await runCommand(GLAB_CLI, args);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw unavailable(`glab CLI could not be spawned: ${detail}`);\n }\n if (result.exitCode !== 0) {\n const detail = result.stderr.trim() || `exit code ${result.exitCode}`;\n throw unavailable(`glab api ${endpoint} failed: ${detail}`);\n }\n return result.stdout;\n}\n\n/**\n * Parse stdout that may contain several concatenated top-level JSON\n * documents, as `glab api --paginate` emits one array per page. A simple\n * bracket/string scanner keeps `][` sequences inside note bodies from\n * breaking the split.\n */\nfunction parseJsonDocuments(text: string): unknown[] {\n const documents: unknown[] = [];\n let depth = 0;\n let inString = false;\n let escaped = false;\n let start = -1;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === '\\\\') {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (ch === '\"') {\n inString = true;\n } else if (ch === '[' || ch === '{') {\n if (depth === 0) start = i;\n depth += 1;\n } else if (ch === ']' || ch === '}') {\n depth -= 1;\n if (depth === 0 && start >= 0) {\n documents.push(JSON.parse(text.slice(start, i + 1)));\n start = -1;\n }\n }\n }\n if (depth !== 0 || inString) {\n throw new Error('truncated JSON document');\n }\n return documents;\n}\n\n// --- Normalization ------------------------------------------------------\n\nfunction toTurn(note: GitLabNote): ForgeThreadTurn {\n return {\n remoteId: String(note.id),\n author: note.author?.username ?? 'unknown',\n body: note.body ?? '',\n };\n}\n\n/**\n * A discussion counts as resolved when it has at least one resolvable note\n * and every resolvable note is resolved. Discussions with no resolvable\n * notes (non-diff discussions) are never \"resolved\".\n */\nfunction isDiscussionResolved(notes: GitLabNote[]): boolean {\n const resolvable = notes.filter(note => note.resolvable === true);\n return resolvable.length > 0 && resolvable.every(note => note.resolved === true);\n}\n\n/**\n * Build the neutral anchor from a GitLab position object, or `null` when the\n * note has no position (non-diff discussion) or the position carries no\n * usable file path.\n *\n * Side selection: `new_line` present → `'new'` (using `new_path`), otherwise\n * `old_line` present → `'old'` (using `old_path`). A position with a path\n * but neither line (e.g. `position_type: \"file\"`) becomes a file-level\n * anchor with null lines and side `'new'`, per the neutral shape's contract.\n * Multi-line `line_range` edges are read on the side chosen above, falling\n * back to the single-line position when an edge lacks that side's line.\n *\n * GitLab has no per-note outdated flag (positions on older heads stay valid\n * positions), so `outdated` is always `false`; drift detection downstream\n * informs the reviewer instead.\n */\nfunction toAnchor(position: GitLabPosition | null | undefined): ForgeThreadAnchor | null {\n if (!position) return null;\n\n const side: ForgeAnchorSide =\n typeof position.old_line === 'number' && typeof position.new_line !== 'number' ? 'old' : 'new';\n const pathForSide = side === 'old' ? position.old_path : position.new_path;\n const filePath = pathForSide ?? position.new_path ?? position.old_path;\n if (!filePath) return null;\n\n const lineOf = (edge: GitLabLineRangeEdge | null | undefined): number | null => {\n const value = side === 'old' ? edge?.old_line : edge?.new_line;\n return typeof value === 'number' ? value : null;\n };\n\n const positionLine = lineOf(position);\n const startLine = lineOf(position.line_range?.start) ?? positionLine;\n const endLine = lineOf(position.line_range?.end) ?? positionLine;\n\n return { filePath, side, startLine, endLine, outdated: false };\n}\n\n/**\n * Normalize one GitLab discussion into the forge-neutral thread shape, or\n * `null` when nothing user-authored remains after dropping system notes.\n * The first surviving note roots the thread and owns the anchor; the rest\n * are ordered replies (GitLab document order is preserved verbatim).\n */\nfunction toThread(discussion: GitLabDiscussion): ForgeThread | null {\n const notes = (discussion.notes ?? []).filter(note => note.system !== true);\n if (notes.length === 0) return null;\n const [rootNote, ...replyNotes] = notes;\n return {\n root: toTurn(rootNote),\n replies: replyNotes.map(toTurn),\n anchor: toAnchor(rootNote.position),\n };\n}\n\n// --- Provider -----------------------------------------------------------\n\n/**\n * Create the GitLab {@link ForgeProvider} backed by the `glab` CLI.\n *\n * The URL's host is forwarded via `--hostname`, so self-hosted instances\n * (e.g. git.drupalcode.org) work with zero configuration beyond `glab auth`.\n * Resolved discussions are excluded unless `includeResolved` is set.\n */\nexport function createGitLabProvider(runCommand: ForgeCommandRunner): ForgeProvider {\n return {\n forge: 'gitlab',\n\n async fetchBaseBranch(url: ForgeUrl): Promise<string> {\n const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}`;\n const stdout = await runGlabApi(runCommand, url, endpoint);\n let mr: unknown;\n try {\n mr = JSON.parse(stdout);\n } catch {\n throw unavailable(`glab api ${endpoint} returned unparseable JSON`);\n }\n const targetBranch = (mr as { target_branch?: unknown })?.target_branch;\n if (typeof targetBranch !== 'string' || targetBranch.length === 0) {\n throw unavailable(`glab api ${endpoint} returned no target_branch`);\n }\n return targetBranch;\n },\n\n async fetchThreads(url: ForgeUrl, options?: FetchThreadsOptions): Promise<ForgeThread[]> {\n const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}/discussions`;\n const stdout = await runGlabApi(runCommand, url, endpoint, ['--paginate']);\n\n let discussions: GitLabDiscussion[];\n try {\n const pages = parseJsonDocuments(stdout);\n if (pages.length === 0 && stdout.trim() !== '') {\n throw new Error('no JSON documents in output');\n }\n discussions = pages.flatMap(page =>\n Array.isArray(page) ? (page as GitLabDiscussion[]) : []\n );\n } catch {\n throw unavailable(`glab api ${endpoint} returned unparseable JSON`);\n }\n\n const includeResolved = options?.includeResolved === true;\n const threads: ForgeThread[] = [];\n for (const discussion of discussions) {\n const notes = discussion.notes ?? [];\n if (!includeResolved && isDiscussionResolved(notes)) continue;\n const thread = toThread(discussion);\n if (thread) threads.push(thread);\n }\n return threads;\n },\n };\n}\n","// materializer.ts\n// Clone-aware diff materializer: turns a parsed forge URL into a local git\n// context. Reuses an existing matching clone (fetch only, no working-tree\n// changes) or creates a disposable blobless clone under the OS temp root,\n// then reports the resolved base/head SHAs so downstream code can run the\n// existing local git-mode pipeline over `baseSha...headSha`.\n//\n// All git interaction goes through an injectable command runner (the same\n// shape providers use) so unit tests never spawn real git. This module never\n// talks to a forge API: head refs come from the forges' well-known git refs\n// (`refs/pull/N/head`, `refs/merge-requests/N/head`) over plain git.\n\nimport { execFile } from 'child_process';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { stripTrailingNewline } from './git';\nimport type { ForgeCommandResult, ForgeCommandRunner, ForgeUrl } from './forge-provider';\n\n/** How the local git context was obtained. */\nexport type MaterializeMode = 'existing-clone' | 'temp-clone';\n\n/** Result of materializing a forge URL into a local git context. */\nexport interface MaterializeResult {\n /** Root of the git repository to run the diff pipeline in. */\n repoPath: string;\n /** Resolved SHA of the PR/MR base branch tip. */\n baseSha: string;\n /** Resolved SHA of the PR/MR head (the live remote head). */\n headSha: string;\n mode: MaterializeMode;\n /**\n * Removes the temp clone directory when one was created this run; a no-op\n * for the existing-clone mode. Safe to call more than once. Only ever\n * deletes a directory this materializer created.\n */\n cleanup: () => void;\n}\n\n/** A local clone whose fetch remote matches the requested forge repository. */\nexport interface ExistingClone {\n repoPath: string;\n remoteName: string;\n}\n\n/** Local namespaced refs the materializer fetches into (never branches). */\nconst LOCAL_BASE_REF = 'refs/self-review/base';\nconst LOCAL_HEAD_REF = 'refs/self-review/head';\n\nconst AUTH_HINT =\n 'Hint: if this repository is private or requires authentication, run ' +\n '`gh auth setup-git` (GitHub) or `glab auth git-credential` (GitLab) to ' +\n 'wire your CLI credentials into git.';\n\n/**\n * Default runner: spawns real git. Resolves with the exit code on any\n * completed run (including non-zero); rejects only when git cannot be\n * spawned at all (e.g. ENOENT).\n */\nexport const defaultGitRunner: ForgeCommandRunner = (command, args) =>\n new Promise<ForgeCommandResult>((resolve, reject) => {\n execFile(command, args, { maxBuffer: 50 * 1024 * 1024 }, (error, stdout, stderr) => {\n const spawnCode = (error as NodeJS.ErrnoException | null)?.code;\n if (error && typeof spawnCode === 'string') {\n reject(error);\n return;\n }\n resolve({\n stdout: stdout ?? '',\n stderr: stderr ?? '',\n exitCode: error ? (typeof spawnCode === 'number' ? spawnCode : 1) : 0,\n });\n });\n });\n\n/** Well-known git ref for the PR/MR head on each forge. */\nfunction headRefFor(url: ForgeUrl): string {\n return url.forge === 'github'\n ? `refs/pull/${url.number}/head`\n : `refs/merge-requests/${url.number}/head`;\n}\n\n/**\n * HTTPS clone URL for the forge repository. Git's credential machinery\n * (helpers, `gh auth setup-git`) handles auth; no transport selection here.\n */\nfunction cloneUrlFor(url: ForgeUrl): string {\n return `https://${url.host}/${url.owner}/${url.repo}.git`;\n}\n\nfunction gitFailure(what: string, result: ForgeCommandResult, withAuthHint: boolean): Error {\n const stderr = result.stderr.trim();\n const lines = [\n `git ${what} failed (exit code ${result.exitCode})${stderr ? `:\\n${stderr}` : ''}`,\n ];\n if (withAuthHint) {\n lines.push('', AUTH_HINT);\n }\n return new Error(lines.join('\\n'));\n}\n\n/** Strip a trailing `.git` and trailing slashes from a repo path. */\nfunction stripRepoPath(repoPath: string): string {\n return repoPath.replace(/\\/+$/, '').replace(/\\.git$/i, '');\n}\n\n/**\n * Normalize a git remote URL (SSH scp-style, ssh://, http(s)://) into a\n * comparable `{ host, path }` pair, or `null` when unrecognized.\n */\nfunction normalizeRemoteUrl(raw: string): { host: string; path: string } | null {\n const trimmed = raw.trim();\n if (trimmed.includes('://')) {\n try {\n const parsed = new URL(trimmed);\n return {\n host: parsed.host.toLowerCase(),\n path: stripRepoPath(parsed.pathname.replace(/^\\/+/, '')).toLowerCase(),\n };\n } catch {\n return null;\n }\n }\n // scp-style: [user@]host:path\n const scp = /^(?:[^@\\s]+@)?([^:/\\s]+):(.+)$/.exec(trimmed);\n if (scp) {\n return {\n host: scp[1].toLowerCase(),\n path: stripRepoPath(scp[2].replace(/^\\/+/, '')).toLowerCase(),\n };\n }\n return null;\n}\n\n/**\n * Parse `git remote -v` output and return the name of the first remote whose\n * fetch URL matches the forge URL's host and owner/repo, or `null`.\n */\nfunction findMatchingRemote(remoteVOutput: string, url: ForgeUrl): string | null {\n const wantedHost = url.host.toLowerCase();\n const wantedPath = `${url.owner}/${url.repo}`.toLowerCase();\n for (const line of remoteVOutput.split('\\n')) {\n const match = /^(\\S+)\\t(.+?)\\s+\\(fetch\\)$/.exec(line.trim());\n if (!match) continue;\n const normalized = normalizeRemoteUrl(match[2]);\n if (normalized && normalized.host === wantedHost && normalized.path === wantedPath) {\n return match[1];\n }\n }\n return null;\n}\n\nasync function revParse(\n runner: ForgeCommandRunner,\n repoPath: string,\n ref: string\n): Promise<string> {\n const result = await runner('git', ['-C', repoPath, 'rev-parse', ref]);\n if (result.exitCode !== 0) {\n throw gitFailure(`rev-parse ${ref}`, result, false);\n }\n return result.stdout.trim();\n}\n\n/**\n * Detect an existing clone: when `cwd` is inside a git repository with a\n * remote matching the forge URL, return `{ repoPath, remoteName }`.\n */\nexport async function detectExistingClone(\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner = defaultGitRunner\n): Promise<ExistingClone | null> {\n const toplevel = await runner('git', ['-C', cwd, 'rev-parse', '--show-toplevel']);\n if (toplevel.exitCode !== 0) {\n return null;\n }\n // A blanket .trim() would eat whitespace that is part of the actual path\n // (SR-0047, same defect class as SR-0036's git.ts fix), reporting a root\n // short of what's on disk and breaking the `remote -v` call right after.\n const repoPath = stripTrailingNewline(toplevel.stdout);\n const remotes = await runner('git', ['-C', repoPath, 'remote', '-v']);\n if (remotes.exitCode !== 0) {\n return null;\n }\n const remoteName = findMatchingRemote(remotes.stdout, url);\n return remoteName === null ? null : { repoPath, remoteName };\n}\n\nasync function materializeIntoExistingClone(\n runner: ForgeCommandRunner,\n url: ForgeUrl,\n baseBranch: string,\n repoPath: string,\n remoteName: string\n): Promise<MaterializeResult> {\n console.error(`self-review: reusing existing clone at ${repoPath} (remote \"${remoteName}\")`);\n // Fetch into namespaced local refs only: no checkout, no branch creation,\n // no working-tree change. Forced refspecs are fine — these refs are ours.\n const fetch = await runner('git', [\n '-C',\n repoPath,\n 'fetch',\n remoteName,\n `+refs/heads/${baseBranch}:${LOCAL_BASE_REF}`,\n `+${headRefFor(url)}:${LOCAL_HEAD_REF}`,\n ]);\n if (fetch.exitCode !== 0) {\n throw gitFailure(`fetch from remote \"${remoteName}\"`, fetch, true);\n }\n return {\n repoPath,\n baseSha: await revParse(runner, repoPath, LOCAL_BASE_REF),\n headSha: await revParse(runner, repoPath, LOCAL_HEAD_REF),\n mode: 'existing-clone',\n cleanup: () => {},\n };\n}\n\nasync function materializeIntoTempClone(\n runner: ForgeCommandRunner,\n url: ForgeUrl,\n baseBranch: string\n): Promise<MaterializeResult> {\n // This run creates the directory, so cleanup may only ever remove it.\n const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'self-review-'));\n let removed = false;\n const cleanup = () => {\n if (removed) return;\n removed = true;\n fs.rmSync(tempDir, { recursive: true, force: true });\n };\n\n try {\n console.error(`self-review: created temporary blobless clone at ${tempDir}`);\n const cloneUrl = cloneUrlFor(url);\n // Blobless, never shallow: --depth would break merge-base computation.\n const clone = await runner('git', ['clone', '--filter=blob:none', cloneUrl, tempDir]);\n if (clone.exitCode !== 0) {\n throw gitFailure(`clone of ${cloneUrl}`, clone, true);\n }\n const fetch = await runner('git', [\n '-C',\n tempDir,\n 'fetch',\n 'origin',\n `+${headRefFor(url)}:${LOCAL_HEAD_REF}`,\n ]);\n if (fetch.exitCode !== 0) {\n throw gitFailure(`fetch of ${headRefFor(url)}`, fetch, true);\n }\n return {\n repoPath: tempDir,\n baseSha: await revParse(runner, tempDir, `origin/${baseBranch}`),\n headSha: await revParse(runner, tempDir, LOCAL_HEAD_REF),\n mode: 'temp-clone',\n cleanup,\n };\n } catch (error) {\n cleanup();\n throw error;\n }\n}\n\n/**\n * Materialize a forge PR/MR into a local git context.\n *\n * When `cwd` is inside a git repository with a remote matching the forge\n * URL (SSH and HTTPS forms recognized, `.git` suffix tolerated), the base\n * branch and PR/MR head refs are fetched into that clone under\n * `refs/self-review/*` — read-only for the working tree. Otherwise a\n * blobless clone is created in a unique directory under the OS temp root\n * and `cleanup()` removes exactly that directory. Callers that already\n * detected a clone may pass it to avoid repeating the git probes.\n *\n * The returned `headSha` is the live remote head, so callers can compare it\n * against a recorded `remote-head-sha` for drift detection.\n */\nexport async function materialize(\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner = defaultGitRunner,\n existingClone?: ExistingClone | null\n): Promise<MaterializeResult> {\n const existing =\n existingClone === undefined ? await detectExistingClone(url, cwd, runner) : existingClone;\n if (existing) {\n return materializeIntoExistingClone(\n runner,\n url,\n baseBranch,\n existing.repoPath,\n existing.remoteName\n );\n }\n return materializeIntoTempClone(runner, url, baseBranch);\n}\n\n/**\n * Git-only fallback for the base branch when no forge CLI is available:\n * resolves the remote's default branch from its HEAD symref via\n * `git ls-remote --symref <remote> HEAD`. When an existing matching clone\n * is supplied, the configured remote is used so its SSH/HTTPS transport\n * and credentials are preserved. Otherwise the forge HTTPS URL is used.\n * No forge API involved.\n */\nexport async function resolveRemoteDefaultBranch(\n url: ForgeUrl,\n runner: ForgeCommandRunner = defaultGitRunner,\n existing: ExistingClone | null = null\n): Promise<string> {\n const cloneUrl = cloneUrlFor(url);\n const remote = existing?.remoteName ?? cloneUrl;\n // Errors must identify the repository; a bare alias such as \"origin\"\n // does not say which repository the lookup was made against.\n const label = existing ? `${remote} (${cloneUrl})` : cloneUrl;\n const args = existing\n ? ['-C', existing.repoPath, 'ls-remote', '--symref', remote, 'HEAD']\n : ['ls-remote', '--symref', remote, 'HEAD'];\n const result = await runner('git', args);\n if (result.exitCode !== 0) {\n throw gitFailure(`ls-remote of ${label}`, result, true);\n }\n const match = /^ref:\\s+refs\\/heads\\/(\\S+)\\s+HEAD$/m.exec(result.stdout);\n if (!match) {\n throw new Error(\n `Failed to resolve the default branch of ${label}: ` +\n 'git ls-remote returned no HEAD symref.'\n );\n }\n return match[1];\n}\n","// packages/core/src/review-handlers.ts\n// Transport-agnostic review handler bodies.\n//\n// Every function here takes the session it operates on as a parameter and\n// returns a value. Nothing in this module reaches state that is not reachable\n// through that parameter, and nothing in it touches Electron: the registration\n// layer (src/main/ipc-handlers.ts) owns the transport and does the sending.\n\nimport * as fs from 'fs';\nimport path from 'path';\nimport {\n DiffLoadPayload,\n DiffHunk,\n ResumeLoadPayload,\n GuideLoadPayload,\n AppConfig,\n OutputPathInfo,\n PayloadStats,\n ReviewState,\n ReviewComment,\n ExpandContextRequest,\n ImageLoadResult,\n RemoteDriftInfo,\n SuggestionApplyRequest,\n SuggestionApplyOutcome,\n ApplyDestinationOutcome,\n} from './types';\nimport { scanDirectory, scanFile } from './directory-scanner';\nimport { tokenizeGitDiffArgs } from './git-diff-args';\nimport { computePayloadStats, countTotalLines } from './payload-sizing';\nimport { applySuggestion } from './apply-suggestion';\n\n/**\n * The state a single review session owns. One desktop application window is\n * one session; two sessions are independent and cannot observe each other.\n */\nexport interface ReviewSession {\n reviewState: ReviewState | null;\n diffData: DiffLoadPayload | null;\n guideData: GuideLoadPayload | null;\n config: AppConfig | null;\n outputPathInfo: OutputPathInfo | null;\n resumeComments: ReviewComment[];\n resumeViewedFiles: string[];\n resumeRemoteDrift: RemoteDriftInfo | null;\n /**\n * Destination directory the user named for this session's applies, or\n * null when none has been named. Only a temporary-clone remote review\n * needs one; see {@link resolveApplyDestination}.\n */\n applyDestinationRoot: string | null;\n}\n\n/** Create an empty session. */\nexport function createReviewSession(): ReviewSession {\n return {\n reviewState: null,\n diffData: null,\n guideData: null,\n config: null,\n outputPathInfo: null,\n resumeComments: [],\n resumeViewedFiles: [],\n resumeRemoteDrift: null,\n applyDestinationRoot: null,\n };\n}\n\n/**\n * Prepare a DiffLoadPayload for IPC transmission.\n * In large-payload mode, strips hunks from files to reduce initial transfer size.\n * The full data stays in the session for on-demand loading via DIFF_LOAD_FILE.\n */\nexport function preparePayload(payload: DiffLoadPayload): DiffLoadPayload {\n if (payload.isLargePayload) {\n return {\n ...payload,\n files: payload.files.map(f => ({ ...f, hunks: [] as DiffHunk[], contentLoaded: false })),\n };\n }\n return {\n ...payload,\n files: payload.files.map(f => ({ ...f, contentLoaded: true })),\n };\n}\n\n/**\n * Resolve what a diff request should deliver: the prepared diff payload and,\n * when one is loaded, the guide that rides with it. Returns null when the\n * session has no diff, so the caller sends nothing at all.\n */\nexport function getDiffLoad(\n session: ReviewSession\n): { diff: DiffLoadPayload; guide: GuideLoadPayload | null } | null {\n if (!session.diffData) {\n return null;\n }\n // The guide rides after the diff payload in both normal and\n // large-payload modes — it is metadata-only (paths, names,\n // descriptions) and never triggers eager hunk loading.\n return {\n diff: preparePayload(session.diffData),\n guide: session.guideData,\n };\n}\n\n/**\n * The directory the session's reviewed paths are relative to, or null when the\n * session has no diff yet.\n *\n * Scanner paths are relative to the reviewed directory, or to the reviewed\n * file's parent. Git paths are relative to the repository, which in remote\n * mode is the materialized clone.\n */\nexport function resolveSourceBaseDir(session: ReviewSession): string | null {\n const source = session.diffData?.source;\n if (!source) return null;\n if (source.type === 'git') return source.repository;\n if (source.type === 'directory') return source.sourcePath;\n if (source.type === 'file') return path.dirname(source.sourcePath);\n return null;\n}\n\n/**\n * Load a binary image as a base64 data URI for the rendered preview.\n */\nexport async function loadImage(\n session: ReviewSession,\n filePath: string\n): Promise<ImageLoadResult> {\n const MIME_MAP: Record<string, string> = {\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.bmp': 'image/bmp',\n '.svg': 'image/svg+xml',\n };\n const MAX_SIZE = 10 * 1024 * 1024; // 10 MB\n const baseDir = resolveSourceBaseDir(session) ?? process.cwd();\n const resolved = path.isAbsolute(filePath) ? filePath : path.resolve(baseDir, filePath);\n const ext = path.extname(filePath).toLowerCase();\n const mimeType = MIME_MAP[ext] ?? 'application/octet-stream';\n\n // In a remote session the reviewed content lives at the fetched head\n // SHA, not in the clone's working tree (a temporary clone stays on the\n // default branch), so read the blob through git instead of the fs.\n const remote = session.diffData?.remote;\n if (remote && session.diffData?.source.type === 'git') {\n try {\n const { readGitBlobAsync } = await import('./git');\n const data = await readGitBlobAsync(\n session.diffData.source.repository,\n `${remote.remoteHeadSha}:${filePath}`\n );\n if (data.length > MAX_SIZE) {\n return { error: 'File too large to preview (>10 MB)' };\n }\n return { dataUri: `data:${mimeType};base64,${data.toString('base64')}` };\n } catch {\n return {\n error: 'Image preview unavailable — blob not found at the reviewed commit.',\n };\n }\n }\n\n try {\n const stat = await fs.promises.stat(resolved);\n if (stat.size > MAX_SIZE) {\n return { error: 'File too large to preview (>10 MB)' };\n }\n const data = await fs.promises.readFile(resolved);\n return { dataUri: `data:${mimeType};base64,${data.toString('base64')}` };\n } catch {\n return { error: 'Image preview unavailable — file not found on disk.' };\n }\n}\n\n/**\n * Return a single file's hunks for lazy (large-payload) mode, or null when the\n * session has no diff or the diff has no such file.\n */\nexport function getFileHunks(session: ReviewSession, filePath: string): DiffHunk[] | null {\n if (!session.diffData) return null;\n const file = session.diffData.files.find(f => (f.newPath || f.oldPath) === filePath);\n if (!file) return null;\n return file.hunks;\n}\n\n/**\n * Resolve the config and the output path info that travel with it. Returns null\n * when the session has no config, so the caller sends nothing at all: the\n * renderer distinguishes an absent message from an empty one.\n */\nexport function getConfigLoad(\n session: ReviewSession\n): { config: AppConfig; outputPathInfo: OutputPathInfo | null } | null {\n if (!session.config) {\n return null;\n }\n return { config: session.config, outputPathInfo: session.outputPathInfo };\n}\n\n/**\n * Store a review state submitted by the front end on the session.\n */\nexport function submitReviewState(session: ReviewSession, state: ReviewState): void {\n console.error(\n '[review] Review state submitted:',\n JSON.stringify({\n timestamp: state.timestamp,\n source: state.source,\n fileCount: state.files.length,\n })\n );\n session.reviewState = state;\n}\n\n/**\n * Take the submitted review state off the session, clearing it so it is\n * consumed exactly once. Returns null when nothing has been submitted.\n */\nexport function takeReviewState(session: ReviewSession): ReviewState | null {\n const state = session.reviewState;\n session.reviewState = null;\n return state;\n}\n\n/**\n * True when this session reviews a remote PR/MR that was materialized into\n * a temporary clone. That clone is removed when the app exits, so a write\n * into it is lost the moment the review ends (PRD Section 5.4.8).\n */\nexport function isTemporaryCloneSession(session: ReviewSession): boolean {\n return session.diffData?.remote?.temporaryClone === true;\n}\n\n/** Canonical form of a path, following symlinks when the path exists. */\nfunction canonicalize(target: string): string {\n try {\n return fs.realpathSync(target);\n } catch {\n return path.resolve(target);\n }\n}\n\n/** True when `candidate` is `root` itself or sits anywhere beneath it. */\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(canonicalize(root), canonicalize(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/**\n * The directory an apply may write into for this session, or null when the\n * session has none.\n *\n * For every review whose files sit in a place the user controls — a git\n * working tree, a scanned directory, a reused remote clone — that is the\n * root the reviewed paths are relative to, and no one is asked anything.\n *\n * A temporary-clone review is the one exception. Its files live in a\n * directory the app deletes on exit, so the clone is never a destination:\n * the answer is the directory the user named, and null until they name one.\n */\nexport function resolveApplyDestination(session: ReviewSession): string | null {\n if (isTemporaryCloneSession(session)) {\n return session.applyDestinationRoot;\n }\n return resolveSourceBaseDir(session);\n}\n\n/**\n * Record the directory the user named as this session's apply destination.\n *\n * The caller supplies a path the user picked; this decides whether it can\n * be written into and stores it only if so. The temporary clone, and\n * anything inside it, is refused however it was reached — that directory\n * is gone when the review ends, which is the whole reason a destination is\n * asked for.\n */\nexport function setApplyDestination(\n session: ReviewSession,\n directoryPath: string\n): ApplyDestinationOutcome {\n if (!path.isAbsolute(directoryPath)) {\n return {\n status: 'rejected',\n reason: 'destination-not-absolute',\n detail: 'Pick a destination by its full path.',\n };\n }\n\n let isDirectory = false;\n try {\n isDirectory = fs.statSync(directoryPath).isDirectory();\n } catch {\n isDirectory = false;\n }\n if (!isDirectory) {\n return {\n status: 'rejected',\n reason: 'destination-not-a-directory',\n detail: 'That destination is not a directory that exists.',\n };\n }\n\n const clonePath = isTemporaryCloneSession(session) ? resolveSourceBaseDir(session) : null;\n if (clonePath && isWithin(clonePath, directoryPath)) {\n return {\n status: 'rejected',\n reason: 'destination-inside-temporary-clone',\n detail:\n 'That directory is inside the temporary clone, which is deleted when the review ends.',\n };\n }\n\n session.applyDestinationRoot = canonicalize(directoryPath);\n console.error(`[suggestion:apply] destination set for this session`);\n return { status: 'chosen', destinationRoot: session.applyDestinationRoot };\n}\n\n/**\n * Apply one suggestion to the reviewed working file, or refuse and write\n * nothing. The engine in `apply-suggestion.ts` does the work; this handler\n * only names the destination the session reviews, which the engine never\n * derives for itself.\n *\n * A refusal travels as a value, never as a thrown error. The front end\n * renders its `detail` next to the suggestion the attempt came from.\n */\nexport function applySuggestionForSession(\n session: ReviewSession,\n request: SuggestionApplyRequest\n): SuggestionApplyOutcome {\n const destinationRoot = resolveApplyDestination(session);\n if (!destinationRoot) {\n const temporary = isTemporaryCloneSession(session);\n return {\n status: 'refused',\n filePath: request.filePath,\n reason: temporary ? 'destination-required' : 'no-destination',\n detail: temporary\n ? 'This pull request was cloned into a temporary directory that is deleted when the review ends. Choose a destination directory to apply into.'\n : 'This review has no working directory to write into.',\n };\n }\n\n const result = applySuggestion({\n destinationRoot,\n filePath: request.filePath,\n lineRange: request.lineRange,\n suggestion: request.suggestion,\n });\n console.error(\n `[suggestion:apply] ${request.filePath}: ${\n result.status === 'applied' ? 'applied' : `refused (${result.reason})`\n }`\n );\n\n // Projected field by field rather than passed through. The engine also\n // reports the resolved absolute path, which the front end has no use for\n // and should not be handed; naming the fields here keeps the wire shape\n // exactly what SuggestionApplyOutcome declares, today and after the engine\n // grows a field.\n if (result.status === 'applied') {\n return {\n status: 'applied',\n filePath: result.filePath,\n replacedLines: result.replacedLines,\n };\n }\n return {\n status: 'refused',\n filePath: result.filePath,\n reason: result.reason,\n detail: result.detail,\n };\n}\n\n/**\n * Read an attachment file from disk, as an ArrayBuffer the front end can use.\n * Returns null when the file cannot be read.\n */\nexport async function readAttachment(filePath: string) {\n try {\n const buffer = await fs.promises.readFile(filePath);\n return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n } catch {\n console.error(`[attachment:read] Failed to read file: ${filePath}`);\n return null;\n }\n}\n\n/**\n * Resolve the resumed comments, viewed files and remote drift for a session.\n * Returns null when there is nothing to resume, so the caller sends nothing\n * at all.\n */\nexport function getResumeLoad(session: ReviewSession): ResumeLoadPayload | null {\n if (\n session.resumeComments.length > 0 ||\n session.resumeViewedFiles.length > 0 ||\n session.resumeRemoteDrift !== null\n ) {\n const payload: ResumeLoadPayload = {\n comments: session.resumeComments,\n viewedFiles: session.resumeViewedFiles,\n };\n if (session.resumeRemoteDrift !== null) {\n payload.remoteDrift = session.resumeRemoteDrift;\n }\n return payload;\n }\n return null;\n}\n\n/**\n * Expand the context of a single file by re-running git diff with more context\n * lines. The expanded hunks are written back to the session's diff data so a\n * later file load on the same session sees them. Returns null when the session\n * has no git diff, when nothing parses, or when git fails.\n */\nexport async function expandContext(\n session: ReviewSession,\n request: ExpandContextRequest\n): Promise<{ hunks: DiffHunk[]; totalLines: number } | null> {\n const diffData = session.diffData;\n if (!diffData || diffData.source.type !== 'git') {\n return null;\n }\n\n try {\n const { runGitDiffAsync } = await import('./git');\n const { parseDiff } = await import('./diff-parser');\n\n const source = diffData.source;\n // Shell-style tokenizing, the inverse of how the source string was\n // written: a search string or path with a space comes back as one\n // argument instead of several.\n const originalArgs = tokenizeGitDiffArgs(source.gitDiffArgs);\n\n // Strip -U/--unified flags. Stop at `--` — paths after it were the\n // original path restriction; the specific file is supplied below.\n const filteredArgs: string[] = [];\n for (let i = 0; i < originalArgs.length; i++) {\n const arg = originalArgs[i];\n if (arg.match(/^-U\\d+$/) || arg.match(/^--unified=\\d+$/)) {\n continue;\n }\n if (arg === '-U' || arg === '--unified') {\n i++; // skip next arg (the number)\n continue;\n }\n if (arg === '--') {\n break;\n }\n filteredArgs.push(arg);\n }\n\n const expandArgs = [...filteredArgs, `-U${request.contextLines}`, '--', request.filePath];\n\n // Run in the diff's repository root — in remote mode this is the\n // materialized clone, not the process cwd.\n const rawDiff = await runGitDiffAsync(expandArgs, source.repository);\n const parsedFiles = parseDiff(rawDiff);\n\n if (parsedFiles.length === 0) {\n return null;\n }\n\n const expandedFile = parsedFiles[0];\n\n // Count total lines in the working tree file for gap detection.\n // Diff paths are repository-relative — resolve accordingly.\n let totalLines = 0;\n try {\n const content = await fs.promises.readFile(\n path.resolve(source.repository, request.filePath),\n 'utf-8'\n );\n totalLines = content.split('\\n').length;\n // If file ends with newline, last split element is empty — don't count it\n if (content.endsWith('\\n')) totalLines--;\n } catch {\n // Can't determine line count — leave as 0 (bars will stay visible)\n }\n\n // Update the session's diff data\n session.diffData = {\n ...diffData,\n files: diffData.files.map(f => {\n const fPath = f.newPath || f.oldPath;\n if (fPath === request.filePath) {\n return { ...f, hunks: expandedFile.hunks };\n }\n return f;\n }),\n };\n\n return { hunks: expandedFile.hunks, totalLines };\n } catch (error) {\n console.error(`[review] Failed to expand context for ${request.filePath}:`, error);\n return null;\n }\n}\n\n/**\n * What a review start produced: the payload built from the scanned path, the\n * stats it was measured against (null when the session has no config, in which\n * case no thresholds apply), and whether those stats exceeded a threshold.\n *\n * The payload is deliberately *not* stored on the session: the caller may still\n * need to abandon it (a user declining a large review keeps the review they\n * were already looking at), so committing it is the caller's decision.\n */\nexport interface ReviewStartResult {\n payload: DiffLoadPayload;\n stats: PayloadStats | null;\n exceedsThresholds: boolean;\n}\n\n/**\n * Scan a picked path and build the diff payload for a directory (or single\n * file) review, measured against the session's large-payload thresholds.\n * Nothing is stored on the session — see `ReviewStartResult`.\n */\nexport async function prepareDirectoryReview(\n session: ReviewSession,\n directoryPath: string\n): Promise<ReviewStartResult> {\n console.error('[review] Starting directory review for:', directoryPath);\n\n // Check if the path is a file (not a directory)\n let isFile = false;\n try {\n isFile = fs.statSync(directoryPath).isFile();\n } catch {\n // Failed to stat — proceed as directory\n }\n\n let payload: DiffLoadPayload;\n if (isFile) {\n const files = await scanFile(directoryPath);\n payload = {\n files,\n source: { type: 'file', sourcePath: directoryPath },\n };\n } else {\n // Directory mode: scan all files as new additions\n const ignorePatterns = session.config?.ignore ?? [];\n const files = await scanDirectory(directoryPath, ignorePatterns);\n payload = {\n files,\n source: { type: 'directory', sourcePath: directoryPath },\n };\n }\n\n // Large payload guard — skipped entirely when there is no config.\n if (!session.config) {\n return { payload, stats: null, exceedsThresholds: false };\n }\n const stats = computePayloadStats(\n payload.files.length,\n countTotalLines(payload.files),\n session.config\n );\n return { payload, stats, exceedsThresholds: stats.exceedsAny };\n}\n\n/**\n * Commit a prepared review payload to the session, once the caller has decided\n * it should proceed. Returns the payload to hand to the transport.\n */\nexport function commitReviewStart(\n session: ReviewSession,\n payload: DiffLoadPayload\n): DiffLoadPayload {\n session.diffData = payload;\n return preparePayload(payload);\n}\n","// packages/core/src/git-diff-args.ts\n// Normalization of pass-through git diff arguments.\n\nimport { existsSync } from 'fs';\nimport { resolve } from 'path';\n\n// Only options whose bare spelling consumes the next argument belong here.\n// Optional values (for example --color, --relative and -U) must be attached.\nconst OPTIONS_WITH_SEPARATE_VALUES = new Set([\n '--output',\n '--src-prefix',\n '--dst-prefix',\n '--line-prefix',\n '--output-indicator-new',\n '--output-indicator-old',\n '--output-indicator-context',\n '--inter-hunk-context',\n '--stat-width',\n '--stat-name-width',\n '--stat-graph-width',\n '--stat-count',\n '--diff-algorithm',\n '--word-diff-regex',\n '--ignore-matching-lines',\n '--anchored',\n '--diff-filter',\n '--find-object',\n '--rotate-to',\n '--skip-to',\n '--ws-error-highlight',\n '--color-moved-ws',\n]);\n\nfunction consumesNextArgument(arg: string): boolean {\n if (arg.startsWith('--')) return OPTIONS_WITH_SEPARATE_VALUES.has(arg);\n if (!arg.startsWith('-')) return false;\n // Git accepts short-option groups, such as -pS pattern. Once an option\n // takes a value, the rest of that token is its attached value, if present.\n for (let i = 1; i < arg.length; i++) {\n if ('SGOIl'.includes(arg[i])) return i === arg.length - 1;\n if ('UBMC'.includes(arg[i])) return false; // optional, attached values\n }\n return false;\n}\n\n/** Identify positional arguments without mistaking option values for paths. */\nexport function classifyGitDiffArgs(args: string[]): {\n positionalIndices: number[];\n hasSeparator: boolean;\n} {\n const positionalIndices: number[] = [];\n let hasSeparator = false;\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (!hasSeparator) {\n if (arg === '--') {\n hasSeparator = true;\n continue;\n }\n if (consumesNextArgument(arg)) {\n i++;\n continue;\n }\n if (arg.startsWith('-')) continue;\n }\n positionalIndices.push(i);\n }\n return { positionalIndices, hasSeparator };\n}\n\n/**\n * Insert `--` before the first non-flag positional arg that exists as a\n * filesystem path. This makes the args unambiguous so downstream code\n * (expand-context) never confuses a path for a revision.\n *\n * Idempotent: an explicit `--` separator leaves the args unchanged.\n */\nexport function normalizeGitDiffArgs(args: string[], cwd: string = process.cwd()): string[] {\n const { positionalIndices, hasSeparator } = classifyGitDiffArgs(args);\n if (hasSeparator) return args;\n for (const i of positionalIndices) {\n const arg = args[i];\n // Only positional args can be filesystem paths.\n if (existsSync(resolve(cwd, arg))) {\n return [...args.slice(0, i), '--', ...args.slice(i)];\n }\n }\n return args;\n}\n\n/**\n * Split a configured argument string into argv the way a shell would, so a\n * quoted path or search string survives as one argument.\n *\n * Two callers rely on this: `default-diff-args` from YAML, which people write\n * with shell quoting, and the `git-diff-args` string carried on a git diff\n * source, which `formatGitDiffArgs` writes in the same syntax. Unquoted input\n * splits on whitespace exactly as a plain split did, so older config and older\n * review documents keep parsing identically.\n *\n * Malformed input never throws. An unterminated quote closes at end of input:\n * a broken config line degrades to a best-effort argument list instead of\n * taking startup down with it.\n */\nexport function tokenizeGitDiffArgs(value: string): string[] {\n const args: string[] = [];\n let current = '';\n let started = false;\n let quote: \"'\" | '\"' | null = null;\n\n for (let i = 0; i < value.length; i++) {\n const char = value[i];\n\n if (quote === \"'\") {\n if (char === \"'\") quote = null;\n else current += char;\n continue;\n }\n\n if (quote === '\"') {\n // Inside double quotes only the quote and the backslash are escapable;\n // every other backslash is a literal character, as in POSIX shells.\n if (char === '\\\\' && (value[i + 1] === '\"' || value[i + 1] === '\\\\')) {\n current += value[++i];\n } else if (char === '\"') {\n quote = null;\n } else {\n current += char;\n }\n continue;\n }\n\n if (char === \"'\" || char === '\"') {\n quote = char;\n started = true;\n continue;\n }\n if (char === '\\\\' && i + 1 < value.length) {\n current += value[++i];\n started = true;\n continue;\n }\n if (/\\s/.test(char)) {\n if (started) {\n args.push(current);\n current = '';\n started = false;\n }\n continue;\n }\n current += char;\n started = true;\n }\n\n if (started) args.push(current);\n return args;\n}\n\n/** True when rendering this argument bare would lose its boundary. */\nfunction needsQuoting(arg: string): boolean {\n return arg.length === 0 || /[\\s'\"\\\\]/.test(arg);\n}\n\n/**\n * Render argv as the single string a git diff source carries, such that\n * `tokenizeGitDiffArgs` recovers the exact argument list.\n *\n * Arguments that survive a bare round trip are written bare, so ordinary\n * invocations produce byte-identical output to a plain join and the\n * `git-diff-args` XML attribute does not change shape for them.\n */\nexport function formatGitDiffArgs(args: string[]): string {\n return args.map(arg => (needsQuoting(arg) ? `'${arg.replace(/'/g, \"'\\\\''\")}'` : arg)).join(' ');\n}\n","// packages/core/src/startup-mode.ts\n// Startup mode detection: what the app should review, from the CLI args and the CWD.\n\nimport { existsSync, statSync } from 'fs';\nimport { execFileSync, execSync } from 'child_process';\nimport { resolve } from 'path';\nimport { classifyGitDiffArgs } from './git-diff-args';\n\n/**\n * Check if the current working directory is inside a git repository.\n */\nfunction isInGitRepo(): boolean {\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file is tracked by git (known to the index).\n */\nfunction isGitTracked(filePath: string): boolean {\n try {\n execFileSync('git', ['ls-files', '--error-unmatch', '--', filePath], {\n stdio: 'ignore',\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Determine the startup mode based on git availability and CLI arguments.\n * Returns the DiffSource type to use.\n */\nexport function determineMode(gitDiffArgs: string[]): 'git' | 'directory' | 'file' | 'welcome' {\n const { positionalIndices } = classifyGitDiffArgs(gitDiffArgs);\n const firstPositional = gitDiffArgs[positionalIndices[0]];\n\n // Check if first positional arg is an existing file\n if (firstPositional) {\n const candidate = resolve(process.cwd(), firstPositional);\n try {\n if (existsSync(candidate) && statSync(candidate).isFile()) {\n if (isInGitRepo()) {\n // In git repo: tracked files go through git diff, untracked use file mode\n return isGitTracked(firstPositional) ? 'git' : 'file';\n }\n return 'file';\n }\n } catch {\n // Failed to stat — fall through\n }\n }\n\n if (isInGitRepo()) {\n return 'git';\n }\n\n // Not in a git repo — check if first positional arg is an existing directory\n if (firstPositional) {\n const candidate = resolve(process.cwd(), firstPositional);\n try {\n if (existsSync(candidate) && statSync(candidate).isDirectory()) {\n return 'directory';\n }\n } catch {\n // Failed to stat — fall through to welcome\n }\n }\n\n return 'welcome';\n}\n","// packages/core/src/guide-loader.ts\n// Discovery + tolerant loading of the walkthrough guide sidecar.\n//\n// The guide is orientation garnish on a deterministic tool (see\n// docs/intent/llm-review-guide.md): a missing file is a silent no-op, and\n// an unreadable or invalid one produces exactly one stderr warning and no\n// guide. Nothing in this module may throw out of it — every failure mode\n// resolves to null.\n//\n// Note on startup cost: loadGuide IS awaited before window creation\n// (main.ts Phase 5b), deliberately — `guide:load` piggybacks on the\n// DIFF_REQUEST handler, so the payload must be cached via setGuideData\n// before the renderer's first request arrives. When a guide exists, the\n// xmllint-wasm init and validation delay window paint by a few hundred ms;\n// when none exists the cost is a single failed stat.\n//\n// Discovery is one-shot: the guide is resolved from the startup output\n// path. Changing the output path at runtime does not re-discover.\n\nimport { readFile } from 'fs/promises';\nimport { extname, resolve } from 'path';\nimport { parseGuideXml, reconcileGuide } from './guide-parser';\nimport { AppConfig, GuideLoadPayload } from './types';\n\n/**\n * Derive the guide sidecar path from the resolved output path: strip the\n * last extension and append `.guide.xml` (`review.xml` →\n * `review.guide.xml`). An output filename with no extension gets\n * `.guide.xml` appended verbatim.\n */\nexport function deriveGuidePath(outputPath: string): string {\n const ext = extname(outputPath);\n const base = ext ? outputPath.slice(0, -ext.length) : outputPath;\n return `${base}.guide.xml`;\n}\n\n/**\n * Resolve where to look for the guide: the `guide-file` config override\n * (resolved against cwd, like `output-file`) when set, otherwise the path\n * derived from the resolved output path.\n */\nexport function resolveGuidePath(outputPath: string, config: Pick<AppConfig, 'guideFile'>): string {\n if (config.guideFile) {\n return resolve(process.cwd(), config.guideFile);\n }\n return deriveGuidePath(outputPath);\n}\n\n/**\n * Discover, read, parse, validate, and reconcile the guide sidecar.\n *\n * Returns the display-ready payload, or null when there is no usable\n * guide. Missing file: silent. Unreadable or invalid file: exactly one\n * `console.error()` line (guide path + reason class). Never throws.\n */\nexport async function loadGuide(\n outputPath: string,\n config: Pick<AppConfig, 'guideFile'>,\n diffFilePaths: string[]\n): Promise<GuideLoadPayload | null> {\n let guidePath: string;\n try {\n guidePath = resolveGuidePath(outputPath, config);\n } catch {\n return null;\n }\n\n try {\n let content: string;\n try {\n content = await readFile(guidePath, 'utf-8');\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n // No sidecar next to the output path — the normal case.\n return null;\n }\n console.error(\n `[guide] Ignoring guide at ${guidePath}: unreadable (${code ?? 'unknown error'})`\n );\n return null;\n }\n\n const result = await parseGuideXml(content);\n // Explicit comparison: with strictNullChecks off (see tsconfig),\n // truthiness alone does not narrow the discriminated union.\n if (result.ok === false) {\n console.error(`[guide] Ignoring guide at ${guidePath}: invalid (${result.reason})`);\n return null;\n }\n\n const payload: GuideLoadPayload = {\n groups: reconcileGuide(result.guide, diffFilePaths),\n };\n if (result.guide.overview !== undefined) {\n payload.overview = result.guide.overview;\n }\n return payload;\n } catch (error) {\n // Belt and braces: no failure mode of the guide loader may escape.\n const message = error instanceof Error ? error.message : String(error);\n console.error(`[guide] Ignoring guide at ${guidePath}: invalid (${message})`);\n return null;\n }\n}\n","import type { DiffFile } from './types';\nimport {\n runGitDiffAsync,\n getRepoRootAsync,\n getUntrackedFilesAsync,\n generateUntrackedDiffs,\n} from './git';\nimport { parseDiff } from './diff-parser';\n\nexport interface LoadGitDiffOptions {\n /**\n * Include untracked working-tree files as synthetic additions. Defaults\n * to true (local git mode). Remote mode passes false: a base...head diff\n * of a PR/MR must never pick up unrelated local untracked files.\n */\n includeUntracked?: boolean;\n}\n\nexport async function loadGitDiffWithUntracked(\n gitDiffArgs: string[],\n cwd?: string,\n options: LoadGitDiffOptions = {}\n): Promise<{ files: DiffFile[]; repository: string }> {\n const { includeUntracked = true } = options;\n const repository = await getRepoRootAsync(cwd);\n const rawDiff = await runGitDiffAsync(gitDiffArgs, cwd);\n const files = parseDiff(rawDiff);\n\n if (!includeUntracked) {\n return { files, repository };\n }\n\n // Enumerate at the repository root. `git diff` reports root-relative paths\n // for the whole repository, while `git ls-files` reports cwd-relative paths\n // for the cwd subtree only. Read those cwd-relative names against the root\n // and a nested file resolves to its same-named root neighbour, or to\n // nothing at all.\n const untrackedPaths = await getUntrackedFilesAsync(repository);\n let allFiles = files;\n if (untrackedPaths.length > 0) {\n const untrackedDiffStr = generateUntrackedDiffs(untrackedPaths, repository);\n if (untrackedDiffStr.length > 0) {\n const untrackedFiles = parseDiff(untrackedDiffStr);\n for (const file of untrackedFiles) {\n file.isUntracked = true;\n }\n allFiles = [...files, ...untrackedFiles];\n }\n }\n\n return { files: allFiles, repository };\n}\n","// packages/core/src/staged-untracked.ts\n// Initial-config adjustment for staged-mode reviews.\n\nimport type { AppConfig } from './types';\n\n/**\n * In staged-mode reviews (--staged / --cached), untracked files are not\n * part of the index and should be hidden by default. If the user has\n * explicitly opted in via `show-untracked: true` in their YAML config,\n * respect that choice.\n *\n * Untracked files are still preloaded by the backend so that the toolbar\n * toggle can reveal them instantly without re-running git.\n */\nexport function applyStagedUntrackedDefault(config: AppConfig, gitDiffArgs: string[]): AppConfig {\n const stagedMode = gitDiffArgs.includes('--staged') || gitDiffArgs.includes('--cached');\n if (!stagedMode) return config;\n\n const userExplicitOptIn = config.showUntrackedExplicit && config.showUntracked;\n if (userExplicitOptIn) return config;\n\n return { ...config, showUntracked: false };\n}\n","// packages/core/src/remote-mode.ts\n// Remote PR/MR session bootstrap for the main process.\n//\n// Binding rule: after materialization, remote mode *is* git mode. This\n// module turns a forge URL into the inputs the existing git-mode pipeline\n// already understands — a repo path and a `baseSha...headSha` range — plus\n// the fetched discussion threads (mapped to ReviewComments for the\n// resume:load path) and the remote provenance the serializer records.\n//\n// Reused by both the CLI URL path (main.ts startup) and the splash-screen\n// URL entry (the remote:open-url IPC handler). Every external effect goes\n// through an injectable dependency so unit tests never spawn git/gh/glab.\n\nimport {\n parseForgeUrl,\n ForgeCliUnavailableError,\n createGitHubProvider,\n createGitLabProvider,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n defaultGitRunner,\n mapThreadsToReviewComments,\n createIgnoreFilter,\n} from './index';\nimport type {\n ForgeCommandRunner,\n ForgeName,\n ForgeProvider,\n ForgeThread,\n ForgeUrl,\n ExistingClone,\n MaterializeMode,\n MaterializeResult,\n} from './index';\nimport type {\n DiffFile,\n DiffLoadPayload,\n RemoteDriftInfo,\n RemoteSessionInfo,\n ReviewComment,\n ReviewState,\n} from './types';\nimport { loadGitDiffWithUntracked } from './git-diff-loader';\nimport { formatGitDiffArgs } from './git-diff-args';\n\n/** A materialized remote PR/MR session, ready for the git-mode pipeline. */\nexport interface RemoteSession {\n forgeUrl: ForgeUrl;\n /** Root of the materialized clone; the pipeline's repo path. */\n repoPath: string;\n /** Arguments for the existing git-diff machinery: `[base...head]`. */\n gitDiffArgs: string[];\n mode: MaterializeMode;\n /** Removes the temp clone when one was created; idempotent no-op otherwise. */\n cleanup: () => void;\n /** Provenance + thread-sync status for payloads and the saved review. */\n remote: RemoteSessionInfo;\n /**\n * Forge discussion threads mapped to ReviewComments. Empty when the forge\n * CLI is unavailable. Review-level threads keep the mapper's sentinel\n * `filePath: ''` (REVIEW_LEVEL_FILE_PATH).\n *\n * Mapped here without the reviewed diff, which is not loaded yet, so a\n * `suggestion` fence stays plain body text. {@link bootstrapRemoteDiff}\n * replaces these with the same threads mapped against the loaded files.\n */\n fetchedComments: ReviewComment[];\n /**\n * The threads behind `fetchedComments`, verbatim. Carried so the caller\n * that loads the diff can map them again with it (SR-0063).\n */\n fetchedThreads: ForgeThread[];\n}\n\n/** Injectable seams; defaults are the real core APIs. */\nexport interface RemoteSessionDeps {\n createProvider: (forge: ForgeName, runner: ForgeCommandRunner) => ForgeProvider;\n materialize: (\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner,\n existingClone?: ExistingClone | null\n ) => Promise<MaterializeResult>;\n detectExistingClone: (\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner\n ) => Promise<ExistingClone | null>;\n resolveRemoteDefaultBranch: (\n url: ForgeUrl,\n runner: ForgeCommandRunner,\n existing?: ExistingClone | null\n ) => Promise<string>;\n runner: ForgeCommandRunner;\n /** Loads the diff from the clone. Untracked files are never included. */\n loadDiff: (\n gitDiffArgs: string[],\n cwd: string\n ) => Promise<{ files: DiffFile[]; repository: string }>;\n}\n\nfunction defaultCreateProvider(forge: ForgeName, runner: ForgeCommandRunner): ForgeProvider {\n return forge === 'github' ? createGitHubProvider(runner) : createGitLabProvider(runner);\n}\n\nconst defaultDeps: RemoteSessionDeps = {\n createProvider: defaultCreateProvider,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n runner: defaultGitRunner,\n loadDiff: (gitDiffArgs, cwd) =>\n // A base...head diff of a remote PR/MR must never pick up local\n // untracked files (an existing clone may have unrelated ones).\n loadGitDiffWithUntracked(gitDiffArgs, cwd, { includeUntracked: false }),\n};\n\n/**\n * Materialize a forge PR/MR URL into a local git context and fetch its\n * discussion threads.\n *\n * Fatal failures (unrecognizable URL, materialization errors, base-branch\n * lookup failures other than a missing CLI) throw — callers surface them\n * like any other startup git error. Forge-CLI unavailability is never\n * fatal: the base branch falls back to the git-only default-branch lookup\n * and thread sync degrades to an empty list with a single stderr note.\n */\nexport async function startRemoteSession(\n url: string,\n cwd: string,\n deps: Partial<RemoteSessionDeps> = {}\n): Promise<RemoteSession> {\n const d: RemoteSessionDeps = { ...defaultDeps, ...deps };\n\n const forgeUrl = parseForgeUrl(url);\n if (!forgeUrl) {\n throw new Error(`Not a recognized pull-request or merge-request URL: ${url}`);\n }\n\n const provider = d.createProvider(forgeUrl.forge, d.runner);\n\n let cliAvailable = true;\n let baseBranch: string;\n let existingClone: ExistingClone | null | undefined;\n try {\n baseBranch = await provider.fetchBaseBranch(forgeUrl);\n } catch (error) {\n if (!(error instanceof ForgeCliUnavailableError)) {\n throw error;\n }\n cliAvailable = false;\n console.error(\n `[remote] Forge CLI unavailable (${error.cli}): ${error.message} — ` +\n 'falling back to the remote default branch via git.'\n );\n existingClone = await d.detectExistingClone(forgeUrl, cwd, d.runner);\n baseBranch = await d.resolveRemoteDefaultBranch(forgeUrl, d.runner, existingClone);\n }\n\n const materialized = await d.materialize(forgeUrl, baseBranch, cwd, d.runner, existingClone);\n\n let fetchedThreads: ForgeThread[] = [];\n let threadSyncAvailable = false;\n if (cliAvailable) {\n try {\n fetchedThreads = await provider.fetchThreads(forgeUrl);\n threadSyncAvailable = true;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(\n `[remote] thread sync unavailable — continuing without forge threads: ${message}`\n );\n }\n } else {\n console.error(\n '[remote] thread sync unavailable — forge CLI missing, continuing without forge threads.'\n );\n }\n\n return {\n forgeUrl,\n repoPath: materialized.repoPath,\n gitDiffArgs: [`${materialized.baseSha}...${materialized.headSha}`],\n mode: materialized.mode,\n cleanup: materialized.cleanup,\n remote: {\n remoteUrl: url,\n remoteBaseSha: materialized.baseSha,\n remoteHeadSha: materialized.headSha,\n remoteForge: forgeUrl.forge,\n threadSyncAvailable,\n // A temporary clone is deleted on exit, so nothing may be written\n // into it; the front end needs the fact, not the path.\n temporaryClone: materialized.mode === 'temp-clone',\n },\n fetchedComments: mapThreadsToReviewComments(fetchedThreads),\n fetchedThreads,\n };\n}\n\n/** A remote session plus the ready-to-send git-mode diff payload. */\nexport interface RemoteBootstrapResult {\n session: RemoteSession;\n payload: DiffLoadPayload;\n}\n\n/**\n * Full remote bootstrap: materialize the session, load the diff from the\n * clone through the existing git-diff machinery, apply the ignore filter,\n * map the fetched threads against those files, and shape the git-mode\n * `DiffLoadPayload` (with `remote` provenance attached). Shared by the CLI\n * URL startup path and the splash-screen `remote:open-url` handler.\n */\nexport async function bootstrapRemoteDiff(\n url: string,\n cwd: string,\n ignorePatterns: string[],\n deps: Partial<RemoteSessionDeps> = {}\n): Promise<RemoteBootstrapResult> {\n const d: RemoteSessionDeps = { ...defaultDeps, ...deps };\n const started = await startRemoteSession(url, cwd, d);\n\n // From here on the session may own a temporary clone; if anything below\n // fails the caller never receives the cleanup handle, so release it here.\n let files: DiffFile[];\n let repository: string;\n try {\n ({ files, repository } = await d.loadDiff(started.gitDiffArgs, started.repoPath));\n } catch (error) {\n started.cleanup();\n throw error;\n }\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredFiles = files.filter(f => shouldKeep(f.newPath || f.oldPath));\n\n // The reviewed diff exists only now, and the mapper needs it to anchor a\n // `suggestion` fence. Mapping against the filtered files keeps the\n // comments consistent with the payload the renderer receives.\n const session: RemoteSession = {\n ...started,\n fetchedComments: mapThreadsToReviewComments(started.fetchedThreads, filteredFiles),\n };\n\n return {\n session,\n payload: {\n files: filteredFiles,\n source: {\n type: 'git',\n // Same renderer the git-mode path uses, so expand-context can\n // tokenize this string back into the exact argv.\n gitDiffArgs: formatGitDiffArgs(session.gitDiffArgs),\n repository,\n },\n remote: session.remote,\n },\n };\n}\n\n/**\n * Merge fetched forge threads into a resumed document's comments. The\n * resumed document wins: a fetched thread whose root `remoteId` already\n * appears in the resumed comments is skipped (the resumed copy may carry\n * the user's added replies). Order: resumed comments first, then the\n * non-duplicate fetched threads in fetch order. Inputs are not mutated.\n */\nexport function mergeRemoteThreads(\n resumed: ReviewComment[],\n fetched: ReviewComment[]\n): ReviewComment[] {\n const resumedRemoteIds = new Set(\n resumed.map(c => c.remoteId).filter((id): id is string => id !== undefined)\n );\n return [\n ...resumed,\n ...fetched.filter(c => c.remoteId === undefined || !resumedRemoteIds.has(c.remoteId)),\n ];\n}\n\n/**\n * Return a copy of the state carrying this session's remote provenance, so\n * \"Finish Review\" writes the `remote-*` root attributes. Always records the\n * live session values: the saved document describes the diff that was\n * actually reviewed.\n */\nexport function applyRemoteProvenance(state: ReviewState, remote: RemoteSessionInfo): ReviewState {\n return {\n ...state,\n // The three source shapes are mutually exclusive in the document: the\n // remote-* attributes ARE the source, so the in-session git source\n // (the materialized clone) must not leak into the saved review. The\n // welcome source emits no source attributes, mirroring fetch-comments.\n source: { type: 'welcome' },\n remoteUrl: remote.remoteUrl,\n remoteBaseSha: remote.remoteBaseSha,\n remoteHeadSha: remote.remoteHeadSha,\n remoteForge: remote.remoteForge,\n };\n}\n\n/**\n * Compare a resumed document's recorded `remote-head-sha` with the live\n * head from materialization. Returns `null` when the document recorded no\n * head SHA (nothing to compare).\n */\nexport function computeRemoteDrift(\n recordedHeadSha: string | undefined,\n liveHeadSha: string\n): RemoteDriftInfo | null {\n if (recordedHeadSha === undefined) {\n return null;\n }\n return {\n recordedHeadSha,\n liveHeadSha,\n drifted: recordedHeadSha !== liveHeadSha,\n };\n}\n","// packages/core/src/fetch-comments.ts\n// Headless orchestrator for `self-review fetch-comments <URL>`: materialize\n// the PR/MR, fetch and map its discussion threads, and write a v3 review.xml\n// with remote provenance — no window, nothing on stdout, all logging on\n// stderr. Every collaborator is injectable so the flow is unit-testable; the\n// CLI entry in main.ts stays thin.\n\nimport { writeFileSync } from 'fs';\nimport { resolve } from 'path';\nimport { ForgeCliUnavailableError, parseForgeUrl } from './forge-provider';\nimport type { ForgeCommandRunner, ForgeName, ForgeProvider, ForgeUrl } from './forge-provider';\nimport { createGitHubProvider } from './github-provider';\nimport { createGitLabProvider } from './gitlab-provider';\nimport {\n defaultGitRunner,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n} from './materializer';\nimport type { ExistingClone, MaterializeResult } from './materializer';\nimport { mapThreadsToReviewComments, REVIEW_LEVEL_FILE_PATH } from './thread-mapper';\nimport { parseDiff } from './diff-parser';\nimport { runGitDiffAsync } from './git';\nimport { serializeReview } from './xml-serializer';\nimport { loadConfig } from './config';\nimport type {\n AppConfig,\n DiffFile,\n FileReviewState,\n RemoteForge,\n ReviewComment,\n ReviewState,\n} from './types';\n\n/**\n * Injectable seams for the orchestration. Defaults spawn real processes and\n * touch the real filesystem; tests replace them wholesale.\n */\nexport interface FetchCommentsDeps {\n /** Command runner shared by git, gh and glab invocations. */\n runner: ForgeCommandRunner;\n createProvider: (forge: ForgeName, runner: ForgeCommandRunner) => ForgeProvider;\n materialize: (\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner,\n existingClone?: ExistingClone | null\n ) => Promise<MaterializeResult>;\n detectExistingClone: (\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner\n ) => Promise<ExistingClone | null>;\n resolveRemoteDefaultBranch: (\n url: ForgeUrl,\n runner: ForgeCommandRunner,\n existing?: ExistingClone | null\n ) => Promise<string>;\n loadDiffFiles: (repoPath: string, baseSha: string, headSha: string) => Promise<DiffFile[]>;\n serialize: (state: ReviewState, outputPath: string) => Promise<string>;\n writeFile: (path: string, content: string) => void;\n loadConfig: () => AppConfig;\n now: () => Date;\n}\n\nfunction defaultDeps(): FetchCommentsDeps {\n return {\n runner: defaultGitRunner,\n createProvider: (forge, runner) =>\n forge === 'github' ? createGitHubProvider(runner) : createGitLabProvider(runner),\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n loadDiffFiles: async (repoPath, baseSha, headSha) =>\n // Triple-dot: diff from the merge base, matching how forges present a\n // PR/MR diff. Runs inside the materialized clone.\n parseDiff(await runGitDiffAsync([`${baseSha}...${headSha}`], repoPath)),\n serialize: serializeReview,\n writeFile: (path, content) => writeFileSync(path, content, 'utf-8'),\n loadConfig,\n now: () => new Date(),\n };\n}\n\nexport interface BuildRemoteReviewStateArgs {\n remoteUrl: string;\n forge: RemoteForge;\n baseSha: string;\n headSha: string;\n diffFiles: DiffFile[];\n comments: ReviewComment[];\n timestamp: string;\n}\n\n/**\n * Assemble the ReviewState for a fetched remote review. Pure and\n * deterministic: same inputs, same state.\n *\n * Placement rules:\n * - Every diff file gets a file entry in diff order; fetched threads land on\n * their files, in thread order.\n * - Comments whose path is not in the diff (e.g. outdated anchors on files\n * no longer touched) get a synthetic entry with change-type \"modified\" —\n * the schema requires the attribute and \"modified\" is the least-claiming\n * value for a file we cannot classify.\n * - Review-level threads (sentinel {@link REVIEW_LEVEL_FILE_PATH}) are\n * folded into a single trailing file entry with the sentinel path: the v3\n * schema requires every <comment> inside a <file path>, and the empty\n * path can never collide with a real diff path, so consumers detect these\n * by comparing against the constant. Omitted when there are none.\n * - Every file is viewed=\"false\": fetch-comments reviews nothing, and a\n * viewed mark claims a human looked at the file. A subsequent\n * --resume-from session therefore starts with the full file list pending.\n * - `source` is `{ type: 'welcome' }`: the remote-* root attributes are the\n * review's source shape, and the three shapes (git, directory, remote)\n * are mutually exclusive by contract, so no local source attributes are\n * serialized.\n */\nexport function buildRemoteReviewState(args: BuildRemoteReviewStateArgs): ReviewState {\n const commentsByPath = new Map<string, ReviewComment[]>();\n for (const comment of args.comments) {\n const list = commentsByPath.get(comment.filePath);\n if (list) {\n list.push(comment);\n } else {\n commentsByPath.set(comment.filePath, [comment]);\n }\n }\n\n const files: FileReviewState[] = [];\n const diffPaths = new Set<string>();\n for (const diffFile of args.diffFiles) {\n const path = diffFile.changeType === 'deleted' ? diffFile.oldPath : diffFile.newPath;\n diffPaths.add(path);\n files.push({\n path,\n changeType: diffFile.changeType,\n viewed: false,\n comments: commentsByPath.get(path) ?? [],\n });\n }\n\n // Synthetic entries for anchored comments whose file is not in the diff,\n // in first-appearance order.\n for (const [path, comments] of commentsByPath) {\n if (path === REVIEW_LEVEL_FILE_PATH || diffPaths.has(path)) continue;\n files.push({ path, changeType: 'modified', viewed: false, comments });\n }\n\n const reviewLevel = commentsByPath.get(REVIEW_LEVEL_FILE_PATH);\n if (reviewLevel && reviewLevel.length > 0) {\n files.push({\n path: REVIEW_LEVEL_FILE_PATH,\n changeType: 'modified',\n viewed: false,\n comments: reviewLevel,\n });\n }\n\n return {\n timestamp: args.timestamp,\n source: { type: 'welcome' },\n files,\n remoteUrl: args.remoteUrl,\n remoteBaseSha: args.baseSha,\n remoteHeadSha: args.headSha,\n remoteForge: args.forge,\n };\n}\n\nexport interface FetchCommentsOptions {\n /** Include threads the forge marks resolved (GitLab). Default false. */\n includeResolved?: boolean;\n /** Working directory for clone detection and output resolution. */\n cwd?: string;\n /** Test seams; every omitted member falls back to the real default. */\n deps?: Partial<FetchCommentsDeps>;\n}\n\n/**\n * Run the headless fetch-comments flow end to end. Throws on any failure\n * (the caller prints the message to stderr and exits 1); the temporary\n * clone, when one was created, is removed on both success and failure.\n */\nexport async function runFetchComments(\n url: string,\n options: FetchCommentsOptions = {}\n): Promise<void> {\n const deps: FetchCommentsDeps = { ...defaultDeps(), ...options.deps };\n const cwd = options.cwd ?? process.cwd();\n\n const forgeUrl = parseForgeUrl(url);\n if (forgeUrl === null) {\n throw new Error(\n `Not a recognized pull/merge request URL: ${url}\\n` +\n 'Expected a GitHub PR URL (…/pull/N) or a GitLab MR URL ' +\n '(…/-/merge_requests/N).'\n );\n }\n\n const provider = deps.createProvider(forgeUrl.forge, deps.runner);\n\n let baseBranch: string;\n let existingClone: ExistingClone | null | undefined;\n try {\n baseBranch = await provider.fetchBaseBranch(forgeUrl);\n } catch (error) {\n if (!(error instanceof ForgeCliUnavailableError)) throw error;\n console.error(`[fetch-comments] ${error.message}`);\n console.error(\n `[fetch-comments] ${error.cli} unavailable for the base-branch lookup — ` +\n 'falling back to the remote default branch via git ls-remote.'\n );\n existingClone = await deps.detectExistingClone(forgeUrl, cwd, deps.runner);\n baseBranch = await deps.resolveRemoteDefaultBranch(forgeUrl, deps.runner, existingClone);\n }\n console.error(`[fetch-comments] Base branch: ${baseBranch}`);\n\n const materialized = await deps.materialize(\n forgeUrl,\n baseBranch,\n cwd,\n deps.runner,\n existingClone\n );\n try {\n let threads;\n try {\n threads = await provider.fetchThreads(forgeUrl, {\n includeResolved: options.includeResolved ?? false,\n });\n } catch (error) {\n if (error instanceof ForgeCliUnavailableError) {\n // Fetching comments is this subcommand's entire purpose: no\n // degradation, fail with a clear error.\n throw new Error(\n `Cannot fetch discussion threads: ${error.message}\\n` +\n `fetch-comments requires the ${error.cli} CLI to be installed ` +\n 'and authenticated.'\n );\n }\n throw error;\n }\n console.error(`[fetch-comments] Fetched ${threads.length} threads`);\n\n const diffFiles = await deps.loadDiffFiles(\n materialized.repoPath,\n materialized.baseSha,\n materialized.headSha\n );\n // The diff is what anchors a `suggestion` fence: without it the mapper\n // cannot read the original code a fence proposes to replace.\n const comments = mapThreadsToReviewComments(threads, diffFiles);\n\n const state = buildRemoteReviewState({\n remoteUrl: url,\n forge: forgeUrl.forge,\n baseSha: materialized.baseSha,\n headSha: materialized.headSha,\n diffFiles,\n comments,\n timestamp: deps.now().toISOString(),\n });\n\n const config = deps.loadConfig();\n const outputPath = resolve(cwd, config.outputFile);\n const xml = await deps.serialize(state, outputPath);\n deps.writeFile(outputPath, xml + '\\n');\n console.error(`[fetch-comments] ${comments.length} threads written to ${outputPath}`);\n } finally {\n materialized.cleanup();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAKO,SAAS,UAAU,SAA6B;AACrD,MAAI,CAAC,QAAQ,KAAK,GAAG;AACnB,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,QAAQ,QAAQ,MAAM,IAAI;AAChC,QAAM,QAAoB,CAAC;AAC3B,MAAI,cAAwC;AAC5C,MAAI,cAAwC;AAC5C,MAAI,gBAAgB;AACpB,MAAI,gBAAgB;AACpB,MAAI,gBAAgB;AAEpB,WAAS,YAAkB;AACzB,QACE,gBACC,YAAY,WAAW,YAAY,aACnC,YAAY,YACX,YAAY,MAAO,SAAS,KAC5B,YAAY,eAAe,cAC3B,gBACF;AACA,YAAM,KAAK,WAAuB;AAAA,IACpC;AAAA,EACF;AAEA,WAAS,IAAI,GAAG,IAAI,MAAM,QAA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SAAS,SAAS;AAE9D,UAAM,QAAQ,uBAAuB;AAAA,MACnC,WAAW;AAAA,MACX,OAAO,SAAS;AAAA,MAChB,SAAS,aAAa;AAAA,MACtB,SAAS,aAAa;AAAA,MACtB;AAAA,MACA;AAAA,MACA,WAAW,KAAK,IAAI,EAAE,YAAY;AAAA,IACpC,CAAC;AAED,UAAM,SAAS,KAAK,WAAW;AAC/B,UAAM,iBAAa,uBAAQ,KAAK,OAAO,UAAU;AACjD,UAAM,MAAM,MAAM,KAAK,UAAU,OAAO,UAAU;AAClD,SAAK,UAAU,YAAY,MAAM,IAAI;AACrC,YAAQ,MAAM,oBAAoB,SAAS,MAAM,uBAAuB,UAAU,EAAE;AAAA,EACtF,UAAE;AACA,iBAAa,QAAQ;AAAA,EACvB;AACF;","names":["path","path","import_fs","resolve","import_fast_xml_parser","import_xmllint_wasm","path","import_path","ignore","import_fs","import_path","path","parseYaml","import_child_process","import_util","execFileAsync","import_fs","import_path","fsConstants","import_fs","import_path","file","toTurn","toAnchor","import_child_process","fs","path","resolve","fs","import_path","import_fs","import_path","needsQuoting","path","readGitBlobAsync","stat","runGitDiffAsync","parseDiff","path","import_fs","import_child_process","import_path","import_promises","import_path","import_fs","import_path","defaultDeps","path"]}
|