@self-review/core 2.0.4 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +441 -0
  2. package/dist/chunk-5SGPWHGH.cjs +106 -0
  3. package/dist/chunk-5SGPWHGH.cjs.map +1 -0
  4. package/dist/chunk-6OEFXBIZ.cjs +5212 -0
  5. package/dist/chunk-6OEFXBIZ.cjs.map +1 -0
  6. package/dist/chunk-6X3PJHP5.cjs +416 -0
  7. package/dist/chunk-6X3PJHP5.cjs.map +1 -0
  8. package/dist/chunk-CJQEOLI3.js +37 -0
  9. package/dist/chunk-CJQEOLI3.js.map +1 -0
  10. package/dist/chunk-IG2YF5LH.js +416 -0
  11. package/dist/chunk-IG2YF5LH.js.map +1 -0
  12. package/dist/chunk-IX226KG4.js +106 -0
  13. package/dist/chunk-IX226KG4.js.map +1 -0
  14. package/dist/chunk-LSLCQQBN.cjs +3684 -0
  15. package/dist/chunk-LSLCQQBN.cjs.map +1 -0
  16. package/dist/chunk-MOYO4RIX.js +3684 -0
  17. package/dist/chunk-MOYO4RIX.js.map +1 -0
  18. package/dist/chunk-TOUYY7I6.js +5212 -0
  19. package/dist/chunk-TOUYY7I6.js.map +1 -0
  20. package/dist/chunk-VOYTFLPH.cjs +37 -0
  21. package/dist/chunk-VOYTFLPH.cjs.map +1 -0
  22. package/dist/filesystem.cjs +56 -0
  23. package/dist/filesystem.cjs.map +1 -0
  24. package/dist/filesystem.d.cts +22 -0
  25. package/dist/filesystem.d.ts +22 -0
  26. package/dist/filesystem.js +56 -0
  27. package/dist/index.cjs +348 -6192
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +80 -1332
  30. package/dist/index.d.ts +80 -1332
  31. package/dist/index.js +234 -5172
  32. package/dist/index.js.map +1 -1
  33. package/dist/node-scan-fs-CaufzUZR.d.cts +5 -0
  34. package/dist/node-scan-fs-DcHI_BYB.d.ts +5 -0
  35. package/dist/operations-Bqhi9EBH.d.ts +765 -0
  36. package/dist/operations-UyiUD2Nx.d.cts +765 -0
  37. package/dist/operations.cjs +91 -0
  38. package/dist/operations.cjs.map +1 -0
  39. package/dist/operations.d.cts +6 -0
  40. package/dist/operations.d.ts +6 -0
  41. package/dist/operations.js +91 -0
  42. package/dist/resume-worker.cjs +152 -0
  43. package/dist/resume-worker.cjs.map +1 -0
  44. package/dist/resume-worker.d.cts +56 -0
  45. package/dist/resume-worker.d.ts +56 -0
  46. package/dist/resume-worker.js +152 -0
  47. package/dist/resume-worker.js.map +1 -0
  48. package/dist/review-request-validation-VJG7XZiE.d.cts +62 -0
  49. package/dist/review-request-validation-VJG7XZiE.d.ts +62 -0
  50. package/dist/review-xml-decoder-COgRtfkf.d.cts +33 -0
  51. package/dist/review-xml-decoder-COgRtfkf.d.ts +33 -0
  52. package/dist/source-identity-CQpAzugz.d.cts +959 -0
  53. package/dist/source-identity-CQpAzugz.d.ts +959 -0
  54. package/dist/validation.cjs +67 -0
  55. package/dist/validation.cjs.map +1 -0
  56. package/dist/validation.d.cts +30 -0
  57. package/dist/validation.d.ts +30 -0
  58. package/dist/validation.js +67 -0
  59. package/dist/validation.js.map +1 -0
  60. package/package.json +44 -3
  61. package/dist/chunk-4YO2MI6B.js +0 -269
  62. package/dist/chunk-4YO2MI6B.js.map +0 -1
  63. package/dist/chunk-QHS36X6T.js +0 -450
  64. package/dist/chunk-QHS36X6T.js.map +0 -1
  65. package/dist/diff-parser-B6S3KG5T.js +0 -9
  66. package/dist/git-N5HVNPKQ.js +0 -24
  67. /package/dist/{diff-parser-B6S3KG5T.js.map → filesystem.js.map} +0 -0
  68. /package/dist/{git-N5HVNPKQ.js.map → operations.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/self-review/self-review/packages/core/dist/chunk-6OEFXBIZ.cjs","../src/diff-parser-core.ts","../src/diff-parser-async.ts","../src/attachment-planner.ts","../src/review-schema.ts","../src/review-xml-validator.ts","../src/xml-text.ts","../src/xml-writer.ts","../src/xml-serializer.ts","../src/review-xml-decoder.ts","../src/review-transient-id.ts","../src/review-xml-reader.ts","../src/xml-parser.ts","../src/fs-utils.ts","../src/attachment-origin-plan.ts","../src/attachment-origins.ts","../src/review-publisher.ts","../src/guide-schema.ts","../src/guide-parser.ts","../src/ignore-filter.ts","../src/directory-scanner.ts","../src/snapshot-reader.ts","../src/config.ts","../src/config-reader.ts","../src/payload-sizing.ts","../src/file-type-utils.ts","../src/forge-payload.ts","../src/github-provider.ts","../src/thread-mapper.ts","../src/gitlab-provider.ts","../src/review-content.ts","../src/pinned-comparison.ts","../src/git-diff-loader.ts","../src/loaded-git-review.ts","../src/index-capture.ts","../src/comparison-paths.ts","../src/snapshot-verification.ts","../src/review-context.ts","../src/review-start.ts","../src/startup-mode.ts","../src/staged-untracked.ts","../src/startup.ts","../src/guide-loader.ts","../src/remote-feedback.ts","../src/forge-catalog.ts","../src/remote-mode.ts","../src/fetch-comments.ts"],"names":["path","fsConstants","dirname","join","relative","resolve"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACpEO,QAAA,EAAU,cAAA,CACf,OAAA,EACA,QAAA,EAA4B,CAAC,CAA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AAA;AACxC,IAAA;AACH,EAAA;AAI+B,EAAA;AACU,IAAA;AACR,IAAA;AACjC,EAAA;AAEuC,EAAA;AACI,EAAA;AAC9B,IAAA;AACH,MAAA;AACM,MAAA;AACJ,MAAA;AACE,MAAA;AACX,IAAA;AACH,EAAA;AAEO,EAAA;AACW,IAAA;AACU,IAAA;AAC1B,IAAA;AACgB,IAAA;AACI,IAAA;AACA,IAAA;AACF,IAAA;AACpB,EAAA;AACF;AAyBmC;AAE8B,EAAA;AACxB,EAAA;AACN,EAAA;AACO,EAAA;AACtB,IAAA;AACS,IAAA;AACQ,IAAA;AACnC,EAAA;AAI8C,EAAA;AACzC,IAAA;AACyC,IAAA;AACnC,IAAA;AACV,EAAA;AACG,EAAA;AACe,IAAA;AAEoB,IAAA;AACnC,MAAA;AACiC,MAAA;AAClC,IAAA;AAC2B,IAAA;AACU,IAAA;AACN,IAAA;AACb,MAAA;AACnB,IAAA;AAEqC,IAAA;AACxB,MAAA;AACa,MAAA;AACA,MAAA;AACA,MAAA;AACN,MAAA;AACD,MAAA;AACiB,MAAA;AACnC,IAAA;AAGwC,IAAA;AACZ,IAAA;AACK,MAAA;AAClC,IAAA;AACuC,IAAA;AACV,MAAA;AACM,MAAA;AACM,MAAA;AACxC,IAAA;AACG,IAAA;AACF,MAAA;AACsC,QAAA;AACtC,MAAA;AACM,IAAA;AAER,IAAA;AACA,EAAA;AACsB,IAAA;AACxB,EAAA;AAC6B,EAAA;AACgB,IAAA;AAC7C,EAAA;AACF;A9CkzJgD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/self-review/self-review/packages/core/dist/chunk-6OEFXBIZ.cjs","sourcesContent":[null,"// Shared browser-safe parsing state machine. Drivers choose whether checkpoints yield to the host.\n\nimport type { DiffFile, DiffHunk, ChangeType } from './types';\nimport {\n MAX_DIFF_DIAGNOSTIC_CHARS,\n createRepresentationBudget,\n resolveSourceBudgets,\n RepresentationLimitError,\n type SourceBudgets,\n} from './input-budgets';\n\nexport interface DiffParseOptions {\n budgets?: Partial<SourceBudgets>;\n}\n\n/**\n * The files parsed, plus one diagnostic per piece of input that could not be represented\n * faithfully.\n */\nexport interface DiffParseResult {\n files: DiffFile[];\n diagnostics: string[];\n}\n\n/**\n * Parse `git diff` output (a/ b/ prefixes, no color). Every hunk is checked\n * against its `@@` counts; a line over them, a short hunk or an unprefixed line\n * is a diagnostic, never context. Empty lines in an open hunk are the one\n * leniency (`git apply` reads them as empty context). Combined output\n * (`diff --cc`) is reported and skipped.\n */\nexport function* parseDiffSteps(\n rawDiff: string,\n options: DiffParseOptions = {},\n refuse?: (message: string) => never\n): Generator<void, DiffParseResult> {\n const budgets = resolveSourceBudgets(options.budgets);\n const representation = createRepresentationBudget(budgets);\n const diagnostics: string[] = [];\n function diagnose(message: string) {\n if (diagnostics.length >= budgets.maxDiagnostics)\n throw new RepresentationLimitError(true, `${budgets.maxDiagnostics}-diagnostic`);\n if (message.length > MAX_DIFF_DIAGNOSTIC_CHARS)\n throw new RepresentationLimitError(true, `${MAX_DIFF_DIAGNOSTIC_CHARS}-character diagnostic`);\n diagnostics.push(message);\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 remainingOld = 0;\n let remainingNew = 0;\n let hasModeChange = false;\n // Inside a binary patch body or an unsupported combined section.\n let skippingSection = false;\n\n function fileLabel(): string {\n return currentFile?.newPath || currentFile?.oldPath || '<unknown file>';\n }\n\n function flushHunk(): void {\n if (currentHunk && currentHunk.header && currentFile) {\n if (remainingOld > 0 || remainingNew > 0) {\n diagnose(\n `${fileLabel()}: hunk ${currentHunk.header} ended ${remainingOld} old and ` +\n `${remainingNew} new lines short of its declared counts`\n );\n }\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n currentHunk = null;\n remainingOld = 0;\n remainingNew = 0;\n }\n\n function flushFile(): void {\n flushHunk();\n if (\n currentFile &&\n (currentFile.oldPath || currentFile.newPath) &&\n (currentFile.isBinary ||\n currentFile.hunks!.length > 0 ||\n currentFile.changeType !== 'modified' ||\n hasModeChange ||\n currentFile.omittedReason)\n ) {\n files.push(currentFile as DiffFile);\n }\n currentFile = null;\n hasModeChange = false;\n skippingSection = false;\n }\n\n for (const line of patchLines(rawDiff)) {\n if (line === null) {\n yield;\n continue;\n }\n\n try {\n // Start of a new file\n if (line.startsWith('diff --git ')) {\n flushFile();\n\n representation.beginFile();\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 currentFile = {\n oldPath: gitPaths.oldPath,\n newPath: gitPaths.newPath,\n changeType: 'modified' as ChangeType,\n isBinary: false,\n hunks: [],\n };\n continue;\n }\n\n // Two parents against one result: no DiffFile can carry it.\n const combined = line.match(/^diff --(?:cc|combined) (.*)$/);\n if (combined) {\n flushFile();\n const path = stripPrefix(decodeGitPath(combined[1]));\n diagnose(`${path}: combined (merge conflict) diff output is not supported`);\n skippingSection = true;\n continue;\n }\n\n if (skippingSection || !currentFile || currentFile.omittedReason) 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 if (line.startsWith('copy from ')) {\n currentFile.changeType = 'copied';\n currentFile.oldPath = decodeGitPath(line.substring('copy from '.length));\n continue;\n }\n\n if (line.startsWith('copy to ')) {\n currentFile.newPath = decodeGitPath(line.substring('copy 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 // `--binary` emits a base85 body after this marker; skip it.\n if (line === 'GIT binary patch') {\n currentFile.isBinary = true;\n skippingSection = true;\n continue;\n }\n\n // Parse hunk header\n if (line.startsWith('@@')) {\n flushHunk();\n\n // Parse hunk header: @@ -oldStart,oldLines +newStart,newLines @@ context\n const match = line.match(/^@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(.*)$/);\n if (!match) {\n diagnose(`${fileLabel()}: unrecognized hunk header \"${line}\"`);\n continue;\n }\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\n if (\n ![oldStart, oldLines, newStart, newLines, oldStart + oldLines, newStart + newLines].every(\n Number.isSafeInteger\n )\n ) {\n throw new RepresentationLimitError(false, 'safe-integer hunk coordinate');\n }\n if (Math.max(oldLines, newLines) > budgets.maxFileLines) {\n throw new RepresentationLimitError(false, `${budgets.maxFileLines}-line per-file`);\n }\n representation.addHunk();\n currentHunk = {\n header: line,\n oldStart,\n oldLines,\n newStart,\n newLines,\n lines: [],\n };\n\n oldLineNumber = oldStart;\n newLineNumber = newStart;\n remainingOld = oldLines;\n remainingNew = newLines;\n continue;\n }\n\n // Before the first hunk: file metadata.\n if (!currentHunk || !currentHunk.lines) continue;\n\n if (line.startsWith('\\\\')) {\n continue;\n }\n\n const marker = line.length === 0 ? ' ' : line[0];\n const content = line.length === 0 ? '' : line.substring(1);\n\n if (marker === '+') {\n if (remainingNew <= 0) {\n diagnose(\n `${fileLabel()}: line beyond the counts of hunk ${currentHunk.header}: \"${line}\"`\n );\n continue;\n }\n representation.addLines(1);\n currentHunk.lines.push({\n type: 'addition',\n oldLineNumber: null,\n newLineNumber: newLineNumber,\n content,\n });\n newLineNumber++;\n remainingNew--;\n } else if (marker === '-') {\n if (remainingOld <= 0) {\n diagnose(\n `${fileLabel()}: line beyond the counts of hunk ${currentHunk.header}: \"${line}\"`\n );\n continue;\n }\n representation.addLines(1);\n currentHunk.lines.push({\n type: 'deletion',\n oldLineNumber: oldLineNumber,\n newLineNumber: null,\n content,\n });\n oldLineNumber++;\n remainingOld--;\n } else if (marker === ' ') {\n if (remainingOld <= 0 || remainingNew <= 0) {\n diagnose(\n `${fileLabel()}: line beyond the counts of hunk ${currentHunk.header}: \"${line}\"`\n );\n continue;\n }\n representation.addLines(1);\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content,\n });\n oldLineNumber++;\n newLineNumber++;\n remainingOld--;\n remainingNew--;\n } else {\n diagnose(`${fileLabel()}: unrecognized line inside hunk ${currentHunk.header}: \"${line}\"`);\n }\n } catch (error) {\n if (!(error instanceof RepresentationLimitError)) throw error;\n refuse?.(error.message);\n // Never retain a partial file as if its hunks were complete.\n currentHunk = null;\n remainingOld = remainingNew = 0;\n if (currentFile) {\n currentFile.hunks = [];\n currentFile.omittedReason = error.message;\n }\n if (error.aggregate) {\n diagnostics.push(`${error.message} Parsing stopped; remaining input was not loaded.`);\n break;\n }\n if (\n diagnostics.length >= budgets.maxDiagnostics ||\n fileLabel().length + error.message.length + 2 > MAX_DIFF_DIAGNOSTIC_CHARS\n ) {\n diagnostics.push(\n 'Not loaded: diagnostic representation budget exceeded. Parsing stopped; remaining input was not loaded.'\n );\n break;\n }\n diagnose(`${fileLabel()}: ${error.message}`);\n }\n }\n\n // Save the last hunk and file\n try {\n flushFile();\n } catch (error) {\n if (!(error instanceof RepresentationLimitError)) throw error;\n refuse?.(error.message);\n if (currentFile) {\n currentFile.hunks = [];\n currentFile.omittedReason = error.message;\n }\n currentHunk = null;\n diagnostics.push(`${error.message} Parsing stopped; remaining input was not loaded.`);\n flushFile();\n }\n\n return { files, diagnostics };\n}\n\n/**\n * Scan bounded pieces without allocating a complete lines array. Null marks a checkpoint after\n * at most 256 lines or a 64 Ki code-unit string slice, including while scanning a single long line.\n * Joining a long line and processing its header/content remain synchronous string operations.\n */\nfunction* patchLines(rawDiff: string): Generator<string | null> {\n const chunkChars = 64 * 1024;\n let parts: string[] = [];\n let linesSinceCheckpoint = 0;\n for (let offset = 0; offset < rawDiff.length; offset += chunkChars) {\n const chunk = rawDiff.slice(offset, offset + chunkChars);\n let start = 0;\n for (;;) {\n const end = chunk.indexOf('\\n', start);\n if (end === -1) break;\n const tail = chunk.slice(start, end);\n if (parts.length > 0) {\n parts.push(tail);\n yield parts.join('');\n parts = [];\n } else {\n yield tail;\n }\n start = end + 1;\n if (++linesSinceCheckpoint === 256) {\n yield null;\n linesSinceCheckpoint = 0;\n }\n }\n if (start < chunk.length) parts.push(chunk.slice(start));\n yield null;\n linesSinceCheckpoint = 0;\n }\n // Git's trailing newline terminates the last line; it does not introduce an empty one.\n if (parts.length > 0) yield parts.join('');\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\n// `TextDecoder`, not `Buffer`: this parser also runs in the browser (browser.ts).\nconst OCTAL_PATH_DECODER = new TextDecoder('utf-8');\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 let count = 0;\n for (let i = 0; i < escape.length; i++) if (escape[i] === '\\\\') count++;\n const bytes = new Uint8Array(count);\n const octals = /\\\\([0-7]{1,3})/g;\n let match: RegExpExecArray | null;\n let index = 0;\n while ((match = octals.exec(escape)) !== null) bytes[index++] = parseInt(match[1], 8);\n return OCTAL_PATH_DECODER.decode(bytes);\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 let boundary: RegExpExecArray | null = null;\n const separators = / [bwico]\\//g;\n let match: RegExpExecArray | null;\n while ((match = separators.exec(paths)) !== null) {\n boundary ??= match;\n if (\n stripPrefix(paths.substring(0, match.index)) === stripPrefix(paths.substring(match.index + 1))\n ) {\n boundary = match;\n break;\n }\n }\n if (!boundary) {\n // diff.noprefix: unambiguous only as two bare tokens naming the same path.\n const space = paths.indexOf(' ');\n if (\n space > 0 &&\n space === paths.lastIndexOf(' ') &&\n paths.slice(0, space) === paths.slice(space + 1)\n ) {\n return { oldPath: paths.slice(0, space), newPath: paths.slice(space + 1) };\n }\n return { oldPath: '', newPath: '' };\n }\n\n return {\n oldPath: stripPrefix(paths.substring(0, boundary.index)),\n newPath: stripPrefix(paths.substring(boundary.index! + 1)),\n };\n}\n","import { parseDiffSteps, type DiffParseResult, type DiffParseOptions } from './diff-parser-core';\nimport { loadingCheckpoint, checkLoadingCancelled } from './local-loading-lifetime';\n\n/**\n * Parse captured patch output cooperatively. Rejects with CommandCancelledError on abort and\n * never exposes partial files. Input and the resulting AST remain in memory. Individual string\n * operations and one line's parsing cannot be preempted; checkpoints bound scanning and groups\n * of lines, not the CPU time of a pathological header or a single very long line.\n */\nexport async function parseDiffWithDiagnosticsAsync(\n rawDiff: string,\n options: DiffParseOptions & { signal?: AbortSignal } = {}\n): Promise<DiffParseResult> {\n checkLoadingCancelled(options.signal);\n const parser = parseDiffSteps(rawDiff, options);\n try {\n let step = parser.next();\n while (!step.done) {\n await loadingCheckpoint(options.signal);\n step = parser.next();\n }\n checkLoadingCancelled(options.signal);\n return step.value;\n } finally {\n parser.return({ files: [], diagnostics: [] });\n }\n}\n","// Pure attachment naming and document planning. Never reads or writes files.\nimport * as path from 'node:path';\nimport type { Attachment, ReviewState } from './types';\n\nfunction extFromMediaType(mediaType: string): string {\n // Same reasoning as `assetNameComponent`: anything not in the map falls\n // back to png, including a value that is not a string at all.\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\n/**\n * Reduce an id to something that can only ever name a file *inside* the asset\n * directory.\n *\n * A comment id is not trusted input. The desktop gets its ReviewState from its\n * own renderer, but the serve front end accepts a whole document over HTTP, so\n * `../../x` in an id would walk this function's write out of the asset\n * directory and onto an arbitrary path. Every id this app generates is a UUID,\n * so restricting the prefix to the URL-safe alphabet renames nothing in\n * practice and leaves existing asset names byte-identical.\n */\nfunction assetNameComponent(idPrefix: string): string {\n // Coerced rather than assumed: this runs before the document is validated\n // against anything, so a caller that omits an id reaches here with\n // `undefined`, and a bare `.replace` would turn that into a crash *after*\n // the review has already been taken off the session — losing it. The\n // serializer's job here is to name a file, not to police the document.\n return String(idPrefix ?? '').replace(/[^A-Za-z0-9_-]/g, '_');\n}\n\nexport const ASSET_DIR_NAME = '.self-review-assets';\n\nexport interface PlannedAsset {\n /** As emitted in the document: `.self-review-assets/<name>`. */\n relativePath: string;\n absolutePath: string;\n data: ArrayBuffer;\n}\n\n/**\n * `idPrefix` is already URL-safe; the result must be a bare file name. The publisher injects unique\n * names so a new document never overwrites an asset the previous one references.\n */\nexport type AssetNamer = (idPrefix: string, index: number, ext: string) => string;\n\nexport interface SerializedReview {\n /** Validated, without a trailing newline. */\n xml: string;\n /** Blobs the document references that nothing has written yet. */\n assets: PlannedAsset[];\n}\n\nexport const defaultAssetName: AssetNamer = (idPrefix, index, ext) => `${idPrefix}-${index}.${ext}`;\n\ninterface AssetLocation {\n relativePath: string;\n absolutePath: string;\n}\n\ntype AssetSource = { data: ArrayBuffer } | { origin: string; reference: string };\nexport type PublicationAsset = AssetLocation & AssetSource;\n\n/** Public serialization keeps its existing in-memory planned-asset result. */\nexport function planAttachments(\n state: ReviewState,\n outputFilePath: string,\n assetName: AssetNamer\n): { state: ReviewState; assets: PlannedAsset[] } {\n return planDocument(state, outputFilePath, assetName, attachment =>\n attachment.data ? { data: attachment.data } : null\n );\n}\n\n/** Plan imported references without loading their bytes. Repeated origins share one new asset. */\nexport function planPublicationAttachments(\n state: ReviewState,\n outputFilePath: string,\n assetName: AssetNamer,\n origins: ReadonlyMap<string, string>,\n targetAssetDir: string\n): { state: ReviewState; assets: PublicationAsset[] } {\n return planDocument<AssetSource>(state, outputFilePath, assetName, attachment => {\n if (attachment.data) return { data: attachment.data };\n const origin = origins.get(attachment.fileName);\n return origin === undefined || path.dirname(origin) === targetAssetDir\n ? null\n : { origin, reference: attachment.fileName };\n });\n}\n\nfunction planDocument<T extends AssetSource>(\n state: ReviewState,\n outputFilePath: string,\n assetName: AssetNamer,\n sourceFor: (attachment: Attachment) => T | null\n): { state: ReviewState; assets: (AssetLocation & T)[] } {\n const assetDir = path.join(path.dirname(outputFilePath), ASSET_DIR_NAME);\n const assets: (AssetLocation & T)[] = [];\n const imported = new Map<string, AssetLocation & T>();\n const planList = (attachments: Attachment[] | undefined, idPrefix: string) =>\n attachments?.map((attachment, index) => {\n const source = sourceFor(attachment);\n if (source === null) return attachment;\n let asset = 'origin' in source ? imported.get(source.origin) : undefined;\n if (!asset) {\n const name = assetName(\n assetNameComponent(idPrefix),\n index,\n extFromMediaType(attachment.mediaType)\n );\n const absolutePath = path.join(assetDir, name);\n if (path.dirname(path.resolve(absolutePath)) !== path.resolve(assetDir)) {\n throw new Error(`Refusing to write an attachment outside ${assetDir}: ${name}`);\n }\n asset = { ...source, absolutePath, relativePath: `${ASSET_DIR_NAME}/${name}` };\n assets.push(asset);\n if ('origin' in source) imported.set(source.origin, asset);\n }\n return { ...attachment, fileName: asset.relativePath, data: undefined };\n });\n const files = state.files.map(file => ({\n ...file,\n comments: file.comments.map(comment => ({\n ...comment,\n attachments: planList(comment.attachments, comment.id),\n ...(comment.replies\n ? {\n replies: comment.replies.map(reply => ({\n ...reply,\n attachments: planList(reply.attachments, `${comment.id}-r-${reply.id}`),\n })),\n }\n : {}),\n })),\n }));\n return { state: { ...state, files }, assets };\n}\n","// Embed the XSD schema for validation.\n// This MUST stay byte-identical to the on-disk canonical copy\n// (.agents/skills/self-review-apply/assets/self-review-v3.xsd);\n// the sync test in xsd-schema.test.ts enforces it.\nexport const XSD_SCHEMA = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sr=\"urn:self-review:v3\"\n targetNamespace=\"urn:self-review:v3\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review XML Schema v3\n =========================\n Defines the output format for the self-review application.\n This schema is designed to be both machine-validated and\n fed to an LLM so it can understand the structure of review feedback.\n\n Key concepts:\n - A <review> contains one <file> per file in the diff.\n - A <file> contains zero or more <comment> elements.\n - A <comment> with no line attributes is a file-level comment.\n - A <comment> with old-line-start/old-line-end refers to lines\n in the pre-change version of the file (typically deleted lines).\n - A <comment> with new-line-start/new-line-end refers to lines\n in the post-change version of the file (added or context lines).\n - Exactly one pair (old-line-* or new-line-*) should be present\n for line-level comments. This constraint cannot be expressed in\n XSD 1.0 and is enforced by the application.\n - A <comment> may carry an ordered list of <reply> children, which\n are turns in a conversation about that comment.\n\n Changes from v1:\n - <comment> gained two optional attributes, severity and confidence,\n so an automated consumer can threshold on findings instead of\n applying all of them or none of them. See CommentType.\n\n Changes from v2:\n - <comment> gained an optional, unbounded <reply> child, so a finding\n and the responses to it form a single legible thread instead of a\n set of disconnected assertions. See ReplyType.\n\n Amended in place (still v3):\n - The review root gained optional remote-url, remote-base-sha,\n remote-head-sha and remote-forge attributes, and <comment> and\n <reply> gained an optional remote-id attribute, so a review taken\n against a remote pull/merge request records its provenance. Purely\n additive: a document carrying none of them is unchanged. See\n ReviewType.\n -->\n\n <!-- ===== Root element ===== -->\n\n <xs:element name=\"review\" type=\"sr:ReviewType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review output file. Contains one file element\n per file in the git diff, including files with no comments.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <!-- ===== Complex types ===== -->\n\n <xs:complexType name=\"ReviewType\">\n <xs:sequence>\n <xs:element name=\"file\" type=\"sr:FileType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the review was completed (window closed).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments that were passed to self-review on the CLI.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root where self-review was invoked.\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"source-path\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the directory being reviewed.\n Present only when reviewing a directory (non-git mode).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-url\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n URL of the remote pull/merge request this review was taken\n against. Example: \"https://github.com/owner/repo/pull/42\".\n Present only when reviewing a remote PR/MR.\n\n The remote-* attributes form a third source shape alongside\n git-diff-args/repository (local git diff) and source-path\n (directory review). The three shapes are mutually exclusive;\n XSD 1.0 cannot express that constraint, so it is enforced by\n the application.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-base-sha\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Commit SHA the remote diff was computed from (the base of the\n PR/MR at fetch time). Together with remote-head-sha it pins the\n review to the exact diff it was written against, so a consumer\n can detect drift when the remote branch moves.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-head-sha\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Commit SHA of the head of the remote PR/MR branch at fetch time.\n See remote-base-sha for how the pair supports drift detection.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-forge\" type=\"sr:RemoteForgeEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Which forge hosts the remote PR/MR. Names the id space of the\n remote-id attributes on comments and replies, and selects the\n API machinery a future posting feature would use.\n Present only when reviewing a remote PR/MR.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileType\">\n <xs:annotation>\n <xs:documentation>\n Represents a single file in the diff. Files with no comments\n appear as empty elements. The path is relative to the repository root.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"comment\" type=\"sr:CommentType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root. For renamed files,\n this is the new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"change-type\" type=\"sr:ChangeTypeEnum\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n The type of change: added, modified, deleted, renamed, or copied.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"viewed\" type=\"xs:boolean\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Whether the reviewer marked this file as reviewed.\n true = the reviewer looked at this file.\n false = the reviewer did not mark this file as viewed.\n This helps an AI agent distinguish \"reviewed with no comments\"\n from \"not yet reviewed.\"\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"CommentType\">\n <xs:annotation>\n <xs:documentation>\n A review comment. Three forms:\n\n 1. File-level comment: no line attributes present.\n Applies to the file as a whole.\n\n 2. Comment on new/added/context lines: new-line-start and\n new-line-end are present. These reference line numbers in the\n post-change version of the file.\n\n 3. Comment on old/deleted lines: old-line-start and old-line-end\n are present. These reference line numbers in the pre-change\n version of the file.\n\n For single-line comments, start and end are equal.\n Exactly one pair (old or new) should be present for line-level\n comments. Both pairs absent = file-level comment.\n\n The category child says what kind of finding this is. The severity\n and confidence attributes say how much weight to put on it: severity\n is how consequential the finding is if it is real, confidence is how\n sure the author is that it is real. They are independent, and an\n automated consumer is expected to threshold on both.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The comment text. May contain markdown formatting.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"category\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n Required category tag for this comment (e.g., \"bug\", \"style\",\n \"nit\", \"question\", \"security\"). Categories are defined in the\n project-level .self-review.yaml configuration. Every comment\n must have a category to help AI agents prioritize and triage\n feedback.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"suggestion\" type=\"sr:SuggestionType\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Optional code replacement proposal. When present, the AI agent\n should replace the original-code with the proposed-code at the\n referenced line range.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment. The path attribute references an image file\n stored in the .self-review-assets/ directory alongside the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"reply\" type=\"sr:ReplyType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional ordered list of replies to this comment. The comment\n itself is the root of the thread; each reply is a later turn in\n the conversation about it.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"old-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the pre-change (old) version of the file.\n Use for comments on deleted lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"old-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the pre-change (old) version.\n Must be >= old-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the post-change (new) version of the file.\n Use for comments on added or context (unchanged) lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the post-change (new) version.\n Must be >= new-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"author\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The author of this comment. When present, indicates the comment\n was generated by a bot or LLM (e.g., \"Claude Sonnet 4.6\").\n When absent, the comment is assumed to be authored by the human\n reviewer.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"severity\" type=\"sr:SeverityEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n How consequential this finding is if it turns out to be real.\n Judge the impact of the problem, not how confident you are that\n the problem exists, and not how much work the fix is.\n\n This attribute has no schema default on purpose. When it is\n absent, a consumer must treat the comment as falling below any\n severity floor it applies, i.e. absent never satisfies a\n threshold. Comments written by a human in the self-review UI\n normally carry no severity.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"confidence\" type=\"sr:ConfidenceEnum\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n How sure the author is that this finding is real, i.e. that it\n describes an actual defect in the code as written rather than a\n hypothetical one.\n\n Confidence is about the evidence, not about how strongly the\n comment is worded. A finding whose argument depends on a\n constraint that is not visible in the diff, on a caller that was\n not read, or on a failure scenario that was imagined rather than\n traced, is low confidence however plausible its prose sounds.\n LLM reviewers systematically overstate certainty here; a\n consumer thresholding on this attribute is relying on it being\n lowered honestly.\n\n This attribute has no schema default on purpose. When it is\n absent, a consumer must treat the comment as falling below any\n confidence floor it applies, i.e. absent never satisfies a\n threshold.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-id\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Identifier of the remote discussion thread or comment this\n comment was fetched from, in the id space of the forge named by\n remote-forge on the review root. Provenance and forward\n machinery: it lets a consumer trace the finding back to its\n origin, and a future posting feature reply to the existing\n thread instead of opening a new one. Absent on comments\n authored locally.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"ReplyType\">\n <xs:annotation>\n <xs:documentation>\n A reply to a review comment. Replies turn a finding into a\n conversation: the comment asserts something, a reply answers it, a\n later reply answers that.\n\n Four rules govern replies. Only the first is beyond what XSD 1.0\n can express, and it is enforced by the application and by the\n skills that author these documents. Rules 2 to 4 are enforced by\n the content model below; they are spelled out anyway, because the\n reason for a constraint is what an author needs in order to write\n a good reply, and a validator only ever reports the constraint:\n\n 1. Replies are ordered. Document order is conversation order, and\n it is the only ordering signal. There are no timestamps and no\n identifiers: the earlier reply is the earlier turn.\n\n 2. Replies are flat. A reply is never nested inside another reply.\n A reply that addresses an earlier reply says so in its body.\n\n 3. A reply carries no thresholding metadata. There is no category,\n no severity and no confidence on a reply. Those are properties\n of the finding, and the finding is the root comment, whose\n severity and confidence govern the whole thread.\n\n 4. A reply carries no suggestion. A concrete counter-proposal goes\n in the reply body as a fenced code block. Allowing a suggestion\n on both the root and a reply would force every consumer to\n invent its own precedence rule.\n\n When a machine consumes a thread, the last human turn is the\n tie-breaker over any earlier machine assertion.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The reply text. May contain markdown formatting, including\n fenced code blocks, which is where a counter-proposal goes\n since replies carry no suggestion element.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment, identical in form and semantics to\n a comment attachment. The path attribute references an image\n file stored in the .self-review-assets/ directory alongside\n the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"author\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The author of this reply, with the same semantics as\n CommentType/@author. When present, the reply was generated by a\n bot or LLM (e.g., \"Claude Opus 5\"). When absent, the reply is\n the human reviewer's.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"remote-id\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Identifier of the remote comment this reply was fetched from,\n with the same semantics as CommentType/@remote-id: an id in the\n forge's own id space, kept for provenance and for a future\n posting feature. Absent on replies authored locally.\n\n A remote-id is not an ordering signal. Document order remains\n conversation order, exactly as rule 1 above states.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"SuggestionType\">\n <xs:annotation>\n <xs:documentation>\n A code replacement proposal. The original-code is the literal text\n currently at the referenced lines. The proposed-code is what the\n reviewer suggests it should be replaced with. The AI agent can apply\n this by performing a text substitution.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"original-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The existing code at the referenced line range, copied verbatim\n from the diff. Used by the AI agent to locate the replacement\n target via text matching.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"proposed-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The replacement code proposed by the reviewer. The AI agent\n should substitute original-code with this text.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n\n <xs:complexType name=\"AttachmentType\">\n <xs:annotation>\n <xs:documentation>\n Reference to an image file attached to a review comment. The file is stored\n alongside the XML output in the .self-review-assets/ directory.\n </xs:documentation>\n </xs:annotation>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>Relative path from the XML file to the image file.</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"media-type\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>MIME type of the image (e.g., image/png, image/jpeg).</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <!-- ===== Simple types ===== -->\n\n <xs:simpleType name=\"ChangeTypeEnum\">\n <xs:annotation>\n <xs:documentation>\n The type of change a file underwent in the diff.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"added\">\n <xs:annotation>\n <xs:documentation>New file that did not exist before.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"modified\">\n <xs:annotation>\n <xs:documentation>Existing file with content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"deleted\">\n <xs:annotation>\n <xs:documentation>File was removed.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"renamed\">\n <xs:annotation>\n <xs:documentation>File was moved or renamed, with or without content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"copied\">\n <xs:annotation>\n <xs:documentation>File was copied from another path (git copy detection), with or without content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"SeverityEnum\">\n <xs:annotation>\n <xs:documentation>\n How consequential a finding is if it is real. Ordered from most to\n least consequential: critical, major, minor, info.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"critical\">\n <xs:annotation>\n <xs:documentation>\n Causes data loss, a security hole, or a crash or corruption on a\n path that real usage reaches. Shipping this is not acceptable.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"major\">\n <xs:annotation>\n <xs:documentation>\n Produces wrong behaviour, or breaks a documented contract, on a\n path that real usage reaches. The code does not do what it is\n supposed to do, but nothing is destroyed and there is no security\n impact.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"minor\">\n <xs:annotation>\n <xs:documentation>\n Real but bounded: a mishandled edge case that is unlikely to be\n hit, a missing test, a leak of something cheap, or a maintenance\n hazard that will cost time later. Behaviour is correct today.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"info\">\n <xs:annotation>\n <xs:documentation>\n No defect. Style, naming, phrasing, a question for the author, or\n a note recorded for context. Nothing is wrong if this is never\n acted on.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"ConfidenceEnum\">\n <xs:annotation>\n <xs:documentation>\n How sure the author is that a finding is real. Ordered from most to\n least sure: high, medium, low.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"high\">\n <xs:annotation>\n <xs:documentation>\n The evidence is in the code that was read. The failure can be\n traced from the diff itself, and no assumption about unseen code,\n unseen callers, or unstated requirements is needed to reach it.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"medium\">\n <xs:annotation>\n <xs:documentation>\n Likely real, but it rests on one assumption that was not verified,\n such as how a caller behaves, what a dependency guarantees, or\n what the intended requirement was. Stating that assumption in the\n body is expected at this level.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"low\">\n <xs:annotation>\n <xs:documentation>\n Speculative. The failure scenario was imagined rather than traced,\n or the finding depends on a constraint the author invented, or the\n author could not tell intent from the code. Worth a human's eyes,\n not worth acting on unattended.\n </xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n <xs:simpleType name=\"RemoteForgeEnum\">\n <xs:annotation>\n <xs:documentation>\n The forge hosting a remote pull/merge request.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"github\">\n <xs:annotation>\n <xs:documentation>A GitHub pull request.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"gitlab\">\n <xs:annotation>\n <xs:documentation>A GitLab merge request.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n</xs:schema>`;\n","// Review XML validation, including the historical infrastructure-failure fallback.\nimport type { DiagnosticReporter } from './diagnostics';\nimport { isolatedReporter } from './effect-diagnostics';\nimport { XSD_SCHEMA } from './review-schema';\nimport { ReviewXmlError } from './xml-errors';\n\n/** A supplied validator is authoritative; throws mean unavailable infrastructure, not invalid XML. */\nexport type ReviewSchemaValidator = (\n xml: string,\n schema: string\n) =>\n | { valid: boolean; errors?: readonly unknown[] }\n | Promise<{ valid: boolean; errors?: readonly unknown[] }>;\n\nconst defaultSchemaValidator: ReviewSchemaValidator = async (xml, schema) => {\n const { validateXML } = await import('xmllint-wasm');\n return validateXML({\n xml: [{ fileName: 'review.xml', contents: xml }],\n schema: [{ fileName: 'self-review-v3.xsd', contents: schema }],\n });\n};\n\nexport function validateAgainstSchema(\n xml: string,\n reportDiagnostic: DiagnosticReporter | undefined,\n validateSchema: ReviewSchemaValidator | undefined\n): Promise<void>;\n/** Retain the original reflected parameters as well as the original call form. */\nexport function validateAgainstSchema(\n xml: string,\n reportDiagnostic?: DiagnosticReporter\n): Promise<void>;\nexport async function validateAgainstSchema(\n xml: string,\n reportDiagnostic: DiagnosticReporter | undefined = undefined,\n validateSchema: ReviewSchemaValidator = defaultSchemaValidator\n): Promise<void> {\n const report = isolatedReporter(reportDiagnostic);\n let validationResult: Awaited<ReturnType<ReviewSchemaValidator>>;\n try {\n validationResult = await validateSchema(xml, XSD_SCHEMA);\n } catch (error) {\n // Infrastructure failure (e.g. WASM load): losing a finished review is the worse outcome.\n if (error instanceof Error) {\n report(\n `[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`\n );\n } else {\n report('[main] XML validation infrastructure failed - emitting XML without validation');\n }\n return;\n }\n\n if (!validationResult.valid) {\n let details: string[];\n try {\n details = (validationResult.errors || []).map(formatSchemaError);\n } catch {\n // Formatting an effect's diagnostic must not replace an established schema refusal.\n details = ['Schema error details could not be formatted.'];\n }\n report('XML validation failed:');\n details.forEach(detail => report(` ${detail}`));\n throw new ReviewXmlError(\n 'schema-invalid',\n `Generated XML does not conform to schema${details.length ? `: ${details.join('; ')}` : ''}`,\n { details }\n );\n }\n}\n\nfunction formatSchemaError(err: unknown): string {\n if (typeof err === 'string') return err;\n if (err && typeof err === 'object') {\n const { message, loc } = err as { message?: unknown; loc?: { lineNumber?: unknown } | null };\n const text = typeof message === 'string' ? message : JSON.stringify(err);\n const line = loc && typeof loc === 'object' ? loc.lineNumber : undefined;\n return typeof line === 'number' ? `line ${line}: ${text}` : text;\n }\n return String(err);\n}\n","// The one encode/decode contract for review XML text. A conformant parser turns a raw CR(LF)\n// in content into LF (XML 1.0 s2.11) and a raw LF or TAB in an attribute into a space (s3.3.3),\n// so the serializer writes those as character references and the parser decodes them back,\n// once: a single pass over the five predefined entities and numeric references, never its own\n// output. Typed `&#13;` is written `&amp;#13;` and returns as `&#13;`. The library parser's\n// entity processing is off.\n\nexport interface IllegalXmlCharacter {\n codePoint: number;\n /** UTF-16 index of the offending code unit. */\n index: number;\n}\n\n/** XML 1.0 `Char`; everything else has no serialization, escaped or not. */\nfunction isLegalXmlCodePoint(cp: number): boolean {\n return (\n cp === 0x9 ||\n cp === 0xa ||\n cp === 0xd ||\n (cp >= 0x20 && cp <= 0xd7ff) ||\n (cp >= 0xe000 && cp <= 0xfffd) ||\n (cp >= 0x10000 && cp <= 0x10ffff)\n );\n}\n\n/**\n * The first character XML cannot carry, or `null`. A well-formed surrogate pair passes; a lone one\n * is reported.\n */\nexport function findIllegalXmlCharacter(str: string): IllegalXmlCharacter | null {\n for (let i = 0; i < str.length; i++) {\n const unit = str.charCodeAt(i);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const low = i + 1 < str.length ? str.charCodeAt(i + 1) : 0;\n if (low >= 0xdc00 && low <= 0xdfff) {\n i++;\n continue;\n }\n return { codePoint: unit, index: i };\n }\n if (!isLegalXmlCodePoint(unit)) {\n return { codePoint: unit, index: i };\n }\n }\n return null;\n}\n\n/** LF and TAB stay raw: content normalization preserves them. */\nexport function escapeXmlText(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;')\n .replace(/\\r/g, '&#13;');\n}\n\n/**\n * Also escapes LF and TAB, which attribute normalization turns into spaces (git filenames can\n * contain them).\n */\nexport function escapeXmlAttribute(str: string): string {\n return escapeXmlText(str).replace(/\\n/g, '&#10;').replace(/\\t/g, '&#9;');\n}\n\nconst PREDEFINED: Record<string, string> = {\n lt: '<',\n gt: '>',\n amp: '&',\n quot: '\"',\n apos: \"'\",\n};\n\n/** A reference to a forbidden code point stays literal. */\nexport function decodeXmlEntities(raw: string): string {\n return raw.replace(\n /&(lt|gt|amp|quot|apos|#\\d{1,8}|#x[0-9a-fA-F]{1,8});/g,\n (match, ref: string) => {\n if (ref[0] !== '#') return PREDEFINED[ref];\n const cp = ref[1] === 'x' ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);\n return isLegalXmlCodePoint(cp) ? String.fromCodePoint(cp) : match;\n }\n );\n}\n","// Internal review XML writer. Charge encoded bytes before retaining or escaping a value;\n// only a document that fits is joined. No file I/O or schema validation happens here.\nimport { MAX_RESUME_XML_BYTES, formatBytes } from './input-budgets';\nimport { ReviewXmlError, XmlIllegalCharacterError } from './xml-errors';\nimport type { XmlIllegalCharacterLocation } from './xml-errors';\nimport { escapeXmlAttribute, escapeXmlText, findIllegalXmlCharacter } from './xml-text';\n\nexport class ReviewXmlWriter {\n private readonly parts: string[] = [];\n // Publication appends one LF; the returned XML still has no trailing newline.\n private bytes = 1;\n\n append(literal: string): void {\n this.charge(Buffer.byteLength(literal, 'utf8'));\n this.parts.push(literal);\n }\n\n attribute(name: string, value: string, location: XmlIllegalCharacterLocation): void {\n this.append(` ${name}=\"`);\n this.escaped(value, location, true);\n this.append('\"');\n }\n\n element(\n indent: string,\n name: string,\n value: string,\n location: XmlIllegalCharacterLocation\n ): void {\n this.append(`${indent}<${name}>`);\n this.escaped(value, location, false);\n this.append(`</${name}>\\n`);\n }\n\n finish(): string {\n return this.parts.join('');\n }\n\n private escaped(value: string, location: XmlIllegalCharacterLocation, attribute: boolean): void {\n const illegal = findIllegalXmlCharacter(value);\n if (illegal) throw new XmlIllegalCharacterError(illegal.codePoint, location);\n // Every escaped code unit costs at least one byte. No large encoding or escaped\n // duplicate is allocated before this lower bound and the exact byte charges pass.\n if (value.length > MAX_RESUME_XML_BYTES - this.bytes) this.tooLarge();\n for (let i = 0; i < value.length; i++) {\n const unit = value.charCodeAt(i);\n let bytes: number;\n switch (unit) {\n case 38:\n bytes = 5;\n break; // &amp;\n case 60:\n case 62:\n bytes = 4;\n break; // &lt; &gt;\n case 34:\n case 39:\n bytes = 6;\n break; // &quot; &apos;\n case 13:\n bytes = 5;\n break; // &#13;\n case 10:\n bytes = attribute ? 5 : 1;\n break; // &#10;\n case 9:\n bytes = attribute ? 4 : 1;\n break; // &#9;\n default:\n if (unit <= 0x7f) bytes = 1;\n else if (unit <= 0x7ff) bytes = 2;\n else if (unit >= 0xd800 && unit <= 0xdbff) {\n // Already checked: high surrogates always have a matching low surrogate.\n bytes = 4;\n i++;\n } else bytes = 3;\n }\n this.charge(bytes);\n }\n this.parts.push(attribute ? escapeXmlAttribute(value) : escapeXmlText(value));\n }\n\n private charge(bytes: number): void {\n if (bytes > MAX_RESUME_XML_BYTES - this.bytes) this.tooLarge();\n this.bytes += bytes;\n }\n\n private tooLarge(): never {\n const message =\n `The serialized review exceeds the ${formatBytes(MAX_RESUME_XML_BYTES)} review document ` +\n 'limit including its final newline';\n throw new ReviewXmlError('input-too-large', message, { details: [message] });\n }\n}\n","// Serialize ReviewState to bounded XML and validate against XSD. No file I/O.\n\nimport type { DiagnosticReporter } from './diagnostics';\nimport { validateReviewForSerialization } from './review-state-validation';\nimport { ReviewState, FileReviewState, ReviewComment, Reply, Attachment } from './types';\nimport { planAttachments, defaultAssetName } from './attachment-planner';\nimport type { AssetNamer, SerializedReview } from './attachment-planner';\nimport { validateAgainstSchema, type ReviewSchemaValidator } from './review-xml-validator';\nimport type { XmlIllegalCharacterLocation } from './xml-errors';\nimport { ReviewXmlWriter } from './xml-writer';\n\nexport { XSD_SCHEMA } from './review-schema';\nexport { ASSET_DIR_NAME } from './attachment-planner';\nexport type { PlannedAsset, AssetNamer, SerializedReview } from './attachment-planner';\n\nexport interface SerializeOptions {\n /** Defaults to stderr for validation diagnostics. */\n reportDiagnostic?: DiagnosticReporter;\n assetName?: AssetNamer;\n /** Optional authoritative schema effect; omitted calls use xmllint. */\n validateSchema?: ReviewSchemaValidator;\n}\n\n/**\n * Pure: touches no disk (`publishReview` writes). Built before validation, so an\n * unrepresentable value is refused first.\n *\n * @throws XmlIllegalCharacterError naming the comment/reply and field.\n * @throws ReviewXmlError `input-too-large` before escaped output exceeds the resume byte\n * budget (including publication’s final newline), or `schema-invalid`, one violation per\n * `details` line. A validator that fails to load is deliberately not fatal: unvalidated XML\n * after a stderr warning.\n */\nexport async function serializeReview(\n state: ReviewState,\n outputFilePath: string,\n options: SerializeOptions = {}\n): Promise<SerializedReview> {\n state = validateReviewForSerialization(state);\n const staged = planAttachments(state, outputFilePath, options.assetName ?? defaultAssetName);\n const xml = await serializePlannedReview(\n staged.state,\n options.reportDiagnostic,\n options.validateSchema\n );\n return { xml, assets: staged.assets };\n}\n\n/** Internal publication path: references are already planned, so disk bytes never enter this module. */\nexport function serializePlannedReview(\n state: ReviewState,\n reportDiagnostic: DiagnosticReporter | undefined,\n validateSchema: ReviewSchemaValidator | undefined\n): Promise<string>;\nexport function serializePlannedReview(\n state: ReviewState,\n reportDiagnostic?: DiagnosticReporter\n): Promise<string>;\nexport async function serializePlannedReview(\n state: ReviewState,\n reportDiagnostic?: DiagnosticReporter,\n validateSchema: ReviewSchemaValidator | undefined = undefined\n): Promise<string> {\n const xml = buildXml(state);\n await validateAgainstSchema(xml, reportDiagnostic, validateSchema);\n return xml;\n}\n\nfunction writeSourceAttributes(writer: ReviewXmlWriter, state: ReviewState): void {\n const source = state.source;\n if (source.type === 'git') {\n writer.attribute('git-diff-args', source.gitDiffArgs, { field: 'git-diff-args' });\n writer.attribute('repository', source.repository, { field: 'repository' });\n } else if (source.type === 'directory' || source.type === 'file') {\n writer.attribute('source-path', source.sourcePath, { field: 'source-path' });\n }\n}\n\nfunction buildXml(state: ReviewState): string {\n const writer = new ReviewXmlWriter();\n writer.append('<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n');\n writer.append('<review xmlns=\"urn:self-review:v3\"');\n writer.attribute('timestamp', state.timestamp, { field: 'timestamp' });\n writeSourceAttributes(writer, state);\n // Absent provenance stays omitted, preserving purely local output byte for byte.\n if (state.remoteUrl) writer.attribute('remote-url', state.remoteUrl, { field: 'remote-url' });\n if (state.remoteBaseSha)\n writer.attribute('remote-base-sha', state.remoteBaseSha, { field: 'remote-base-sha' });\n if (state.remoteHeadSha)\n writer.attribute('remote-head-sha', state.remoteHeadSha, { field: 'remote-head-sha' });\n if (state.remoteForge) writer.append(` remote-forge=\"${state.remoteForge}\"`);\n writer.append('>\\n');\n for (const file of state.files) writeFileXml(writer, file);\n writer.append('</review>');\n return writer.finish();\n}\n\nfunction writeFileXml(writer: ReviewXmlWriter, file: FileReviewState): void {\n writer.append(' <file');\n writer.attribute('path', file.path, { field: 'path', filePath: file.path });\n writer.append(` change-type=\"${file.changeType}\" viewed=\"${file.viewed}\"`);\n if (file.comments.length === 0) {\n writer.append(' />\\n');\n return;\n }\n writer.append('>\\n');\n for (const comment of file.comments) writeCommentXml(writer, comment, file.path);\n writer.append(' </file>\\n');\n}\n\nfunction writeCommentXml(writer: ReviewXmlWriter, comment: ReviewComment, filePath: string): void {\n const at = (field: string): XmlIllegalCharacterLocation => ({\n field,\n filePath,\n commentId: comment.id,\n });\n writer.append(' <comment');\n if (comment.lineRange) {\n const side = comment.lineRange.side === 'old' ? 'old' : 'new';\n writer.append(` ${side}-line-start=\"${comment.lineRange.start}\"`);\n writer.append(` ${side}-line-end=\"${comment.lineRange.end}\"`);\n }\n if (comment.author) writer.attribute('author', comment.author, at('author'));\n if (comment.severity) writer.append(` severity=\"${comment.severity}\"`);\n if (comment.confidence) writer.append(` confidence=\"${comment.confidence}\"`);\n if (comment.remoteId) writer.attribute('remote-id', comment.remoteId, at('remote-id'));\n writer.append('>\\n');\n writer.element(' ', 'body', comment.body, at('body'));\n writer.element(' ', 'category', comment.category, at('category'));\n if (comment.suggestion) {\n writer.append(' <suggestion>\\n');\n writer.element(\n ' ',\n 'original-code',\n comment.suggestion.originalCode,\n at('original-code')\n );\n writer.element(\n ' ',\n 'proposed-code',\n comment.suggestion.proposedCode,\n at('proposed-code')\n );\n writer.append(' </suggestion>\\n');\n }\n writeAttachments(writer, comment.attachments, ' ', at('attachment'));\n for (const reply of comment.replies ?? []) writeReplyXml(writer, reply, filePath, comment.id);\n writer.append(' </comment>\\n');\n}\n\n/** The same attachment form is used under a comment and a reply. */\nfunction writeAttachments(\n writer: ReviewXmlWriter,\n attachments: Attachment[] | undefined,\n indent: string,\n owner: XmlIllegalCharacterLocation\n): void {\n for (const attachment of attachments ?? []) {\n writer.append(`${indent}<attachment`);\n writer.attribute('path', attachment.fileName, { ...owner, field: 'attachment path' });\n writer.attribute('media-type', attachment.mediaType, {\n ...owner,\n field: 'attachment media-type',\n });\n writer.append(' />\\n');\n }\n}\n\n/** Replies stay flat and ordered; the root comment owns anchors and classification. */\nfunction writeReplyXml(\n writer: ReviewXmlWriter,\n reply: Reply,\n filePath: string,\n commentId: string\n): void {\n const at = (field: string): XmlIllegalCharacterLocation => ({\n field,\n filePath,\n commentId,\n replyId: reply.id,\n });\n writer.append(' <reply');\n if (reply.author) writer.attribute('author', reply.author, at('author'));\n if (reply.remoteId) writer.attribute('remote-id', reply.remoteId, at('remote-id'));\n writer.append('>\\n');\n writer.element(' ', 'body', reply.body, at('body'));\n writeAttachments(writer, reply.attachments, ' ', at('attachment'));\n writer.append(' </reply>\\n');\n}\n","// Decode review XML into ReviewComment[] without file access. Text is lossless (no coercion,\n// one decoding pass, see xml-text.ts). An unreadable document throws ReviewXmlError; a comment\n// with an unusable anchor or suggestion is kept as file-level feedback and reported in\n// `importDiagnostics`.\n\nimport { XMLParser, XMLValidator } from 'fast-xml-parser';\nimport { formatBytes, MAX_REVIEW_ATTACHMENTS, MAX_RESUME_XML_BYTES } from './input-budgets';\nimport {\n ReviewComment,\n Suggestion,\n LineRange,\n DiffSource,\n CommentSeverity,\n CommentConfidence,\n RemoteForge,\n Attachment,\n Reply,\n} from './types';\nimport { validateLineAnchor } from './anchor-validation';\nimport { ReviewXmlError } from './xml-errors';\nimport { decodeXmlEntities } from './xml-text';\nimport { createTransientReviewId } from './review-transient-id';\n\nexport interface ReviewXmlDecoderOptions {\n /** Called once per comment and reply, in document order. */\n createId?: () => string;\n}\n\nconst SEVERITY_VALUES: readonly CommentSeverity[] = ['critical', 'major', 'minor', 'info'];\nconst CONFIDENCE_VALUES: readonly CommentConfidence[] = ['high', 'medium', 'low'];\nconst REMOTE_FORGE_VALUES: readonly RemoteForge[] = ['github', 'gitlab'];\n\nexport interface ParsedReview {\n comments: ReviewComment[];\n /** Paths of files the previous review marked as done (`viewed=\"true\"`). */\n viewedFiles: string[];\n gitDiffArgs: string;\n source: DiffSource;\n /**\n * One line per comment downgraded to file-level feedback, with its suggestion text folded into\n * the body.\n */\n importDiagnostics: string[];\n // Remote provenance, read tolerantly off the review root. Undefined when\n // the document carries no remote attributes, i.e. every pre-remote and\n // purely local review.\n remoteUrl?: string;\n remoteBaseSha?: string;\n remoteHeadSha?: string;\n remoteForge?: RemoteForge;\n}\n\n/**\n * Namespace-blind by design: v1, v2 and v3 documents read identically.\n *\n * @throws ReviewXmlError `parse-failed`, `missing-root`, or `input-too-large`\n * (over `MAX_RESUME_XML_BYTES` in UTF-8, or `MAX_REVIEW_ATTACHMENTS`).\n * Oversized strings are refused before XML validation or parsing, like file input.\n * Parsing remains synchronous; this byte budget does not make it preemptible.\n */\nexport function parseReviewXmlString(\n xmlContent: string,\n options: ReviewXmlDecoderOptions = {}\n): ParsedReview {\n const createId = options.createId ?? createTransientReviewId;\n // UTF-8 needs at least one byte per UTF-16 code unit. Refuse obviously oversized strings\n // immediately; byteLength counts the remaining bounded input without an encoding buffer.\n if (\n xmlContent.length > MAX_RESUME_XML_BYTES ||\n Buffer.byteLength(xmlContent, 'utf8') > MAX_RESUME_XML_BYTES\n ) {\n throw new ReviewXmlError(\n 'input-too-large',\n `The review document exceeds the ${formatBytes(MAX_RESUME_XML_BYTES)} UTF-8 limit`\n );\n }\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n allowBooleanAttributes: true,\n trimValues: false,\n // Lossless: `00123`, `1e3` and `false` stay text, and decodeXmlEntities is the only decoding.\n parseTagValue: false,\n parseAttributeValue: false,\n processEntities: false,\n preserveOrder: true,\n cdataPropName: '#cdata',\n removeNSPrefix: true,\n });\n\n // The parser is lenient (garbage still yields an object), so check well-formedness first for a\n // located message.\n const wellFormed = XMLValidator.validate(xmlContent);\n if (wellFormed !== true) {\n const { msg, line, col } = wellFormed.err;\n const where = col !== undefined ? `line ${line}, column ${col}` : `line ${line}`;\n throw new ReviewXmlError('parse-failed', `Invalid XML: ${msg} (${where})`);\n }\n\n let result: Record<string, unknown>;\n try {\n result = orderedChildren(parser.parse(xmlContent) as OrderedNode[]);\n } catch (error) {\n throw new ReviewXmlError('parse-failed', `Invalid XML: ${messageOf(error)}`, { cause: error });\n }\n\n const review = result.review as Record<string, unknown> | undefined;\n if (!review || typeof review !== 'object') {\n throw new ReviewXmlError('missing-root', 'Invalid XML: missing <review> root element');\n }\n\n const gitDiffArgs = attribute(review, '@_git-diff-args') ?? '';\n const source = parseSource(review);\n const comments: ReviewComment[] = [];\n const viewedFiles: string[] = [];\n const importDiagnostics: string[] = [];\n\n for (const file of toChildArray(review.file)) {\n // Only a missing attribute skips: the empty string is the review-level sentinel path and must\n // round-trip.\n const filePath = attribute(file, '@_path');\n if (filePath === undefined) continue;\n\n if (parseViewed(file['@_viewed'])) {\n viewedFiles.push(filePath);\n }\n\n toChildArray(file.comment).forEach((comment, index) => {\n comments.push(parseComment(comment, filePath, index + 1, importDiagnostics, createId));\n });\n }\n\n // Bounds the reads one document can ask for; refuse rather than drop attachments.\n const attachmentCount = countAttachments(comments);\n if (attachmentCount > MAX_REVIEW_ATTACHMENTS) {\n throw new ReviewXmlError(\n 'input-too-large',\n `The review document carries ${attachmentCount} attachments, over the limit of ` +\n `${MAX_REVIEW_ATTACHMENTS} for a review document`\n );\n }\n\n return {\n comments,\n viewedFiles,\n gitDiffArgs,\n source,\n importDiagnostics,\n remoteUrl: attribute(review, '@_remote-url'),\n remoteBaseSha: attribute(review, '@_remote-base-sha'),\n remoteHeadSha: attribute(review, '@_remote-head-sha'),\n remoteForge: parseEnumAttribute(review['@_remote-forge'], REMOTE_FORGE_VALUES),\n };\n}\n\n/**\n * A comment whose anchor or suggestion cannot be honoured is downgraded to file-level\n * feedback, not dropped: its suggestion text is folded into the body so it is readable but\n * never an Apply target. The diagnostic names it by ordinal (and remote-id) within the file.\n */\nfunction parseComment(\n comment: Record<string, unknown>,\n filePath: string,\n ordinal: number,\n diagnostics: string[],\n createId: () => string\n): ReviewComment {\n const anchor = validateLineAnchor({\n oldLineStart: attribute(comment, '@_old-line-start'),\n oldLineEnd: attribute(comment, '@_old-line-end'),\n newLineStart: attribute(comment, '@_new-line-start'),\n newLineEnd: attribute(comment, '@_new-line-end'),\n });\n const lineRange: LineRange | null = anchor?.ok ? anchor.anchor : null;\n const suggestion = parseSuggestion(comment, lineRange);\n\n let body = text(comment, 'body') ?? '';\n let reason: string | null = null;\n if (anchor && !anchor.ok) {\n reason = anchor.reason;\n } else if (suggestion && !suggestion.ok) {\n reason = suggestion.reason;\n }\n if (reason !== null) {\n if (suggestion) body = foldSuggestionIntoBody(body, suggestion.text, reason);\n const remoteId = attribute(comment, '@_remote-id');\n const label =\n remoteId !== undefined ? `comment ${ordinal} (remote-id ${remoteId})` : `comment ${ordinal}`;\n diagnostics.push(`${filePath}: ${label} anchor ${reason}; kept as file-level feedback`);\n }\n\n const reviewComment: ReviewComment = {\n id: createId(),\n filePath,\n lineRange: reason === null ? lineRange : null,\n body,\n category: text(comment, 'category') ?? '',\n suggestion: suggestion?.ok ? suggestion.suggestion : null,\n author: optionalAuthor(comment),\n severity: parseEnumAttribute(comment['@_severity'], SEVERITY_VALUES),\n confidence: parseEnumAttribute(comment['@_confidence'], CONFIDENCE_VALUES),\n remoteId: attribute(comment, '@_remote-id'),\n };\n\n const attachments = parseAttachments(comment, reviewComment.id);\n if (attachments) reviewComment.attachments = attachments;\n\n const replies = parseReplies(comment, createId);\n if (replies) reviewComment.replies = replies;\n\n return reviewComment;\n}\n\ntype SuggestionRead =\n | { ok: true; suggestion: Suggestion; text: SuggestionText }\n | { ok: false; reason: string; text: SuggestionText };\n\ninterface SuggestionText {\n original?: string;\n proposed?: string;\n}\n\n/**\n * Usable only with both code elements as plain text and a valid anchor (Apply replaces the anchored\n * lines). Other shapes report whatever text they carried.\n */\nfunction parseSuggestion(\n comment: Record<string, unknown>,\n lineRange: LineRange | null\n): SuggestionRead | null {\n const raw = comment.suggestion;\n if (raw === undefined || raw === null) return null;\n\n const node = typeof raw === 'object' ? (raw as Record<string, unknown>) : {};\n const original = text(node, 'original-code');\n const proposed = text(node, 'proposed-code');\n const text_: SuggestionText = { original, proposed };\n\n if ('original-code' in node && original === undefined) {\n return { ok: false, reason: 'suggestion original-code is not plain text', text: text_ };\n }\n if ('proposed-code' in node && proposed === undefined) {\n return { ok: false, reason: 'suggestion proposed-code is not plain text', text: text_ };\n }\n if (original === undefined || proposed === undefined) {\n return {\n ok: false,\n reason: 'suggestion is missing original-code or proposed-code',\n text: text_,\n };\n }\n if (lineRange === null) {\n return { ok: false, reason: 'suggestion has no line anchor', text: text_ };\n }\n return { ok: true, suggestion: { originalCode: original, proposedCode: proposed }, text: text_ };\n}\n\n/**\n * The fence is one backtick longer than the longest run in the code, so nested fences render\n * intact.\n */\nfunction foldSuggestionIntoBody(body: string, code: SuggestionText, reason: string): string {\n const parts = [body, '', `_Imported suggestion could not be anchored (${reason})._`];\n if (code.original !== undefined) parts.push('Original:', ...fenced(code.original));\n if (code.proposed !== undefined) parts.push('Proposed:', ...fenced(code.proposed));\n return parts.join('\\n');\n}\n\nfunction fenced(code: string): string[] {\n let longestRun = 0;\n let run = 0;\n for (let i = 0; i < code.length; i++) {\n if (code.charCodeAt(i) === 96) {\n run++;\n if (run > longestRun) longestRun = run;\n } else {\n run = 0;\n }\n }\n const fence = '`'.repeat(Math.max(3, longestRun + 1));\n return [fence, code, fence];\n}\n\n/**\n * Read an enumerated attribute, dropping values the schema does not define.\n *\n * An unrecognised value becomes undefined rather than being passed through:\n * undefined is the fail-safe reading (below every threshold floor), and it\n * keeps a resumed review serializable, since the serializer validates its\n * output against the XSD before writing.\n */\nfunction parseEnumAttribute<T extends string>(raw: unknown, allowed: readonly T[]): T | undefined {\n if (raw === undefined || raw === null) return undefined;\n const value = decodeXmlEntities(String(raw));\n return allowed.includes(value as T) ? (value as T) : undefined;\n}\n\n/** Decoded text, or undefined when absent; the empty string is a value. */\nfunction attribute(node: Record<string, unknown>, key: string): string | undefined {\n const raw = node[key];\n if (raw === undefined || raw === null) return undefined;\n // A boolean attribute (`<file viewed>`) parses as `true`.\n return decodeXmlEntities(typeof raw === 'string' ? raw : String(raw));\n}\n\n/** Decoded child text, or undefined when absent or not plain text. */\nfunction text(node: Record<string, unknown>, key: string): string | undefined {\n const raw = node[key];\n if (typeof raw === 'string') return raw;\n return undefined;\n}\n\n/** Ordered parsing keeps CDATA distinct until text has been decoded exactly once. */\ntype OrderedNode = { [key: string]: OrderedNode[] | string | Record<string, unknown> };\n\nfunction orderedChildren(children: OrderedNode[]): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const child of children) {\n const name = Object.keys(child).find(key => key !== ':@');\n if (!name || name.startsWith('#') || name.startsWith('?')) continue;\n const segments = child[name] as OrderedNode[];\n const attributes = child[':@'] as Record<string, unknown> | undefined;\n const hasElements = segments.some(segment =>\n Object.keys(segment).some(key => key !== '#text' && key !== '#cdata')\n );\n const value =\n hasElements || attributes\n ? { ...orderedChildren(segments), ...attributes }\n : segments\n .map(segment => {\n if ('#cdata' in segment) {\n return (segment['#cdata'] as OrderedNode[]).map(part => part['#text']).join('');\n }\n return decodeXmlEntities(String(segment['#text'] ?? ''));\n })\n .join('');\n if (name in result) {\n const previous = result[name];\n if (Array.isArray(previous)) previous.push(value);\n else result[name] = [previous, value];\n } else {\n result[name] = value;\n }\n }\n return result;\n}\n\n/** Absent means human, so an empty author reads as absent. */\nfunction optionalAuthor(node: Record<string, unknown>): string | undefined {\n const author = attribute(node, '@_author');\n return author === undefined || author === '' ? undefined : author;\n}\n\n/**\n * Read the `viewed` attribute of a <file> element.\n *\n * Anything other than an explicit true reads as not viewed: the attribute is\n * optional, and treating an unknown value as \"already reviewed\" would silently\n * hide files from the resumed review.\n */\nfunction parseViewed(raw: unknown): boolean {\n return raw === true || String(raw) === 'true';\n}\n\nfunction parseSource(review: Record<string, unknown>): DiffSource {\n const sourcePath = attribute(review, '@_source-path');\n if (sourcePath) {\n return { type: 'directory', sourcePath };\n }\n\n const gitDiffArgs = attribute(review, '@_git-diff-args');\n const repository = attribute(review, '@_repository');\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: gitDiffArgs ?? '',\n repository: repository ?? '',\n };\n }\n\n return { type: 'welcome' };\n}\n\n/**\n * Normalize a repeatable child element into an array.\n *\n * fast-xml-parser collapses a single occurrence into a bare object and only\n * produces an array from two or more, so every repeatable child in this file\n * has to be widened before it can be iterated. An absent child yields an empty\n * array.\n */\nfunction toChildArray(raw: unknown): Record<string, unknown>[] {\n if (Array.isArray(raw)) return raw as Record<string, unknown>[];\n if (raw === undefined || raw === null) return [];\n return [raw as Record<string, unknown>];\n}\n\n/**\n * Read `<attachment>` children of a comment or a reply.\n *\n * Attachment ids are synthetic: nothing in the document names them, so they are\n * derived from the id of their owner, which is why the prefix is a parameter\n * rather than read off the node. Returns undefined rather than [] when there\n * are none, matching the optional field on the type.\n */\nfunction parseAttachments(\n node: Record<string, unknown>,\n idPrefix: string\n): Attachment[] | undefined {\n const raw = toChildArray(node.attachment);\n if (raw.length === 0) return undefined;\n\n return raw.map((att, i) => ({\n id: `${idPrefix}-att-${i}`,\n fileName: attribute(att, '@_path') ?? '',\n mediaType: attribute(att, '@_media-type') ?? 'image/png',\n }));\n}\n\n/**\n * Read `<reply>` children in document order.\n *\n * Document order is conversation order: a reply carries no timestamp and no\n * identifier, so the order of this array is the only ordering signal a thread\n * ever has. Returns undefined rather than [] when there are none, so a\n * reply-free comment keeps exactly the shape it had before threads existed.\n */\nfunction parseReplies(\n comment: Record<string, unknown>,\n createId: () => string\n): Reply[] | undefined {\n const raw = toChildArray(comment.reply);\n if (raw.length === 0) return undefined;\n\n return raw.map(node => {\n const id = createId();\n const reply: Reply = {\n id,\n body: text(node, 'body') ?? '',\n author: optionalAuthor(node),\n remoteId: attribute(node, '@_remote-id'),\n };\n\n const attachments = parseAttachments(node, id);\n if (attachments) reply.attachments = attachments;\n\n return reply;\n });\n}\n\n/** Attachment references across every comment and reply. */\nfunction countAttachments(comments: ReviewComment[]): number {\n let count = 0;\n for (const comment of comments) {\n count += comment.attachments?.length ?? 0;\n for (const reply of comment.replies ?? []) {\n count += reply.attachments?.length ?? 0;\n }\n }\n return count;\n}\n\nfunction messageOf(error: unknown): string {\n if (error instanceof Error) return error.message;\n return typeof error === 'string' ? error : JSON.stringify(error);\n}\n","/** Compatibility IDs are transient and deliberately carry no document identity. */\nexport function createTransientReviewId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// Bounded file acquisition is separate from document decoding.\nimport { readFileWithinBudgetSync, type BoundedReadResult } from './bounded-read';\nimport { formatBytes, MAX_RESUME_XML_BYTES } from './input-budgets';\nimport { ReviewXmlError } from './xml-errors';\n\nexport interface ReviewXmlReader {\n /** Must bound allocation and refuse non-regular inputs without blocking. Errors throw. */\n read(path: string, maxBytes: number): BoundedReadResult;\n}\n\nconst nativeReader: ReviewXmlReader = { read: readFileWithinBudgetSync };\n\nexport function readReviewXmlFile(xmlPath: string, reader: ReviewXmlReader = nativeReader): string {\n let read: BoundedReadResult;\n try {\n read = reader.read(xmlPath, MAX_RESUME_XML_BYTES);\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : typeof error === 'string'\n ? error\n : JSON.stringify(error);\n throw new ReviewXmlError('read-failed', `Could not read ${xmlPath}: ${message}`, {\n cause: error,\n });\n }\n if (read.kind === 'not-regular') {\n throw new ReviewXmlError('read-failed', `Could not read ${xmlPath}: not a regular file`);\n }\n if (read.kind === 'too-large') {\n throw new ReviewXmlError(\n 'input-too-large',\n `Could not read ${xmlPath}: it is ${formatBytes(read.size)}, over the ` +\n `${formatBytes(MAX_RESUME_XML_BYTES)} limit for a review document`\n );\n }\n return read.content.toString('utf-8');\n}\n","// Compatibility entry point: file acquisition and document decoding have separate owners.\nimport {\n parseReviewXmlString,\n type ParsedReview,\n type ReviewXmlDecoderOptions,\n} from './review-xml-decoder';\nimport { readReviewXmlFile, type ReviewXmlReader } from './review-xml-reader';\n\nexport { parseReviewXmlString } from './review-xml-decoder';\nexport type { ParsedReview, ReviewXmlDecoderOptions } from './review-xml-decoder';\nexport type { ReviewXmlReader } from './review-xml-reader';\n\nexport interface ParseReviewXmlOptions extends ReviewXmlDecoderOptions {\n /** Authoritative when supplied; native filesystem reads are never used as a fallback. */\n reader?: ReviewXmlReader;\n}\n\n/** Sized before reading; preserves the string decoder's typed errors and read-failed errors. */\nexport function parseReviewXml(xmlPath: string, options: ParseReviewXmlOptions = {}): ParsedReview {\n return parseReviewXmlString(readReviewXmlFile(xmlPath, options.reader), options);\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';\nimport type { FsLayer } from './safe-fs';\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(\n filePath: string,\n fs?: Pick<FsLayer, 'accessSync' | 'lstatSync'>\n): boolean {\n try {\n const dir = dirname(filePath);\n if (fs === undefined) accessSync(dir, fsConstants.W_OK);\n else if (fs.accessSync) fs.accessSync(dir, fsConstants.W_OK);\n else {\n // Advisory only: legacy virtual adapters have no access syscall. Never probe the host disk.\n const stats = fs.lstatSync(dir);\n if (!stats.isDirectory()) return false;\n const uid = process.getuid?.();\n if (uid === 0) return true;\n const groups = process.getgroups?.() ?? [];\n const bits = uid === stats.uid ? 0o200 : groups.includes(stats.gid) ? 0o020 : 0o002;\n return (stats.mode & bits) !== 0;\n }\n return true;\n } catch {\n return false;\n }\n}\n","// Pure attachment reference policy and origin planning. No filesystem acquisition or runtime Core classes.\nimport * as path from 'node:path';\nimport type { ReviewComment } from './types';\nimport { ASSET_DIR_NAME } from './attachment-planner';\n\n/** The bare name in `.self-review-assets/<name>`; null for any other shape. */\nexport function parseAttachmentReference(reference: unknown): string | null {\n if (typeof reference !== 'string') return null;\n const prefix = `${ASSET_DIR_NAME}/`;\n if (!reference.startsWith(prefix)) return null;\n const name = reference.slice(prefix.length);\n if (name === '' || name === '.' || name === '..') return null;\n if (/[/\\\\\\0]/.test(name)) return null;\n return name;\n}\n\nexport function* attachmentLists(comments: readonly ReviewComment[]) {\n for (const comment of comments) {\n if (comment.attachments) yield { comment, attachments: comment.attachments };\n for (const reply of comment.replies ?? []) {\n if (reply.attachments) yield { comment, attachments: reply.attachments };\n }\n }\n}\n\n/** The caller supplies a physically resolved directory from its own filesystem. No lookup occurs. */\nexport function resolveAttachmentOriginsAtDirectory(\n comments: readonly ReviewComment[],\n directory: string\n): { origins: Map<string, string>; diagnostics: string[] } {\n if (!path.isAbsolute(directory))\n throw new TypeError('Attachment document directory must be absolute');\n const assetDir = path.join(directory, ASSET_DIR_NAME);\n const origins = new Map<string, string>();\n const diagnostics: string[] = [];\n for (const { comment, attachments } of attachmentLists(comments)) {\n for (const attachment of attachments) {\n const name = parseAttachmentReference(attachment.fileName);\n if (name === null) {\n diagnostics.push(\n `${comment.filePath || '(review)'}: attachment \"${attachment.fileName}\" is not in the ` +\n `document's ${ASSET_DIR_NAME} directory; it will not be loaded`\n );\n continue;\n }\n origins.set(attachment.fileName, path.join(assetDir, name));\n }\n }\n return { origins, diagnostics };\n}\n","// packages/core/src/attachment-origins.ts\n// Where resumed attachment bytes live, which references may be read, and how they follow a relocated output.\n\nimport * as path from 'path';\nimport { MAX_IMAGE_BYTES, MAX_PUBLICATION_ASSET_BYTES } from './input-budgets';\nimport { validateReviewForSerialization } from './review-state-validation';\nimport { readContainedFile, toSafeFsError } from './safe-fs';\nimport { canonicalSourcePath } from './source-identity';\nimport type { SafeFsErrorCode, FsLayer } from './safe-fs';\nimport type { BoundedAsyncReadFsLayer } from './safe-fs-read';\nimport { ASSET_DIR_NAME } from './attachment-planner';\nimport type { Attachment, ReviewComment, ReviewState } from './types';\nimport {\n attachmentLists,\n parseAttachmentReference,\n resolveAttachmentOriginsAtDirectory,\n} from './attachment-origin-plan';\nexport { parseAttachmentReference } from './attachment-origin-plan';\n\n/** Reference as the resumed document wrote it → absolute path beside that document. Session state only. */\nexport type AttachmentOrigins = ReadonlyMap<string, string>;\n\nexport type AttachmentReadFailureReason =\n | 'not-authorized'\n | 'not-found'\n | 'not-regular'\n | 'unsafe-link'\n | 'too-large'\n | 'io-error';\n\nexport type AttachmentReadResult =\n | { ok: true; data: ArrayBuffer }\n | { ok: false; reason: AttachmentReadFailureReason; message: string };\n\n/** A physical directory resolved by the host's own filesystem. No native lookup is made. */\nexport interface ResolvedAttachmentLocation {\n documentDirectory: string;\n}\n\n/** Origins resolve against the resumed document's directory; an unrecorded reference is never read. */\nexport function resolveAttachmentOrigins(\n comments: readonly ReviewComment[],\n resumeDocumentPath: string,\n location: ResolvedAttachmentLocation\n): { origins: Map<string, string>; diagnostics: string[] };\nexport function resolveAttachmentOrigins(\n comments: readonly ReviewComment[],\n resumeDocumentPath: string\n): { origins: Map<string, string>; diagnostics: string[] };\nexport function resolveAttachmentOrigins(\n comments: readonly ReviewComment[],\n resumeDocumentPath: string,\n location: ResolvedAttachmentLocation | undefined = undefined\n): { origins: Map<string, string>; diagnostics: string[] } {\n const directory =\n location === undefined\n ? canonicalSourcePath(path.dirname(path.resolve(resumeDocumentPath)))\n : location.documentDirectory;\n return resolveAttachmentOriginsAtDirectory(comments, directory);\n}\n\nconst READ_FAILURES: Partial<Record<SafeFsErrorCode, AttachmentReadFailureReason>> = {\n 'not-found': 'not-found',\n 'unsafe-link': 'unsafe-link',\n 'output-is-directory': 'not-regular',\n 'not-regular': 'not-regular',\n 'too-large': 'too-large',\n};\n\n/** Read one asset the caller authorized: the asset directory must not be a link, nor the leaf. */\nexport interface AttachmentReadOptions {\n fs?: FsLayer;\n /** Bounded read-only adapter, preferred over the legacy fs when both are supplied. */\n readFs?: BoundedAsyncReadFsLayer;\n signal?: AbortSignal;\n /** Remaining aggregate budget, in addition to the fixed per-image limit. */\n maxBytes?: number;\n}\n\nexport async function readAssetFile(\n assetPath: string,\n options: AttachmentReadOptions = {}\n): Promise<AttachmentReadResult> {\n options.signal?.throwIfAborted();\n const assetDir = path.dirname(assetPath);\n const rel = path.join(path.basename(assetDir), path.basename(assetPath));\n try {\n const content = await readContainedFile(\n path.dirname(assetDir),\n rel,\n Math.min(MAX_IMAGE_BYTES, options.maxBytes ?? MAX_IMAGE_BYTES),\n options\n );\n options.signal?.throwIfAborted();\n const data = content.buffer.slice(content.byteOffset, content.byteOffset + content.byteLength);\n return { ok: true, data: data as ArrayBuffer };\n } catch (error) {\n options.signal?.throwIfAborted();\n const fsError = toSafeFsError(error, assetPath, 'read');\n return {\n ok: false,\n reason: READ_FAILURES[fsError.code] ?? 'io-error',\n message: fsError.message,\n };\n }\n}\n\n/** The recorded origin of an imported reference, else the same name in `currentAssetDir`. */\nexport function authorizeAttachmentReference(\n reference: unknown,\n origins: AttachmentOrigins,\n currentAssetDir: string | null\n): string | null {\n const name = parseAttachmentReference(reference);\n if (name === null) return null;\n const origin = origins.get(reference as string);\n if (origin !== undefined) return origin;\n return currentAssetDir ? path.join(currentAssetDir, name) : null;\n}\n\nexport class AttachmentRelocationError extends Error {\n readonly reference: string;\n readonly origin: string;\n readonly reason: AttachmentReadFailureReason;\n\n constructor(\n reference: string,\n origin: string,\n reason: AttachmentReadFailureReason,\n detail: string\n ) {\n super(\n `Attachment ${reference} from the resumed review could not be copied beside the new output: ${detail}. ` +\n `Save next to the resumed review, or remove that attachment, and save again.`\n );\n this.name = 'AttachmentRelocationError';\n this.reference = reference;\n this.origin = origin;\n this.reason = reason;\n }\n}\n\n/**\n * Give every imported attachment whose origin is not beside `outputPath` its bytes, so the\n * publisher stages a copy. This compatibility API retains at most 64 MiB of attachment bytes;\n * publishReview instead plans references and stages one disk-derived buffer at a time. Unreadable ones throw: the old reference would resolve to the wrong file.\n */\nexport async function relocateAttachments(\n state: ReviewState,\n origins: AttachmentOrigins,\n outputPath: string,\n options: AttachmentReadOptions = {}\n): Promise<ReviewState> {\n options.signal?.throwIfAborted();\n state = validateReviewForSerialization(state);\n if (origins.size === 0) return state;\n const outputDir = path.dirname(path.resolve(outputPath));\n const targetRoot = options.readFs\n ? await options.readFs.realpath(outputDir).catch(error => {\n options.signal?.throwIfAborted();\n throw error;\n })\n : options.fs\n ? options.fs.realpathSync(outputDir)\n : canonicalSourcePath(outputDir);\n options.signal?.throwIfAborted();\n const targetAssetDir = path.join(targetRoot, ASSET_DIR_NAME);\n let remaining = MAX_PUBLICATION_ASSET_BYTES;\n for (const file of state.files) {\n for (const { attachments } of attachmentLists(file.comments)) {\n for (const attachment of attachments) {\n if (attachment.data) remaining -= new Uint8Array(attachment.data).byteLength;\n }\n }\n }\n const read = new Map<string, ArrayBuffer>();\n\n const relocate = async (attachments: Attachment[]): Promise<Attachment[]> => {\n const result: Attachment[] = [];\n for (const attachment of attachments) {\n options.signal?.throwIfAborted();\n const origin = attachment.data ? undefined : origins.get(attachment.fileName);\n if (origin === undefined || path.dirname(origin) === targetAssetDir) {\n result.push(attachment);\n continue;\n }\n let data = read.get(origin);\n if (data === undefined) {\n const outcome = await readAssetFile(origin, { ...options, maxBytes: remaining });\n if (!outcome.ok) {\n throw new AttachmentRelocationError(\n attachment.fileName,\n origin,\n outcome.reason,\n outcome.message\n );\n }\n data = outcome.data;\n remaining -= data.byteLength;\n read.set(origin, data);\n }\n result.push({ ...attachment, data });\n }\n return result;\n };\n\n const files = [];\n for (const file of state.files) {\n const comments = [];\n for (const comment of file.comments) {\n const next: ReviewComment = { ...comment };\n if (comment.attachments) next.attachments = await relocate(comment.attachments);\n if (comment.replies) {\n next.replies = [];\n for (const reply of comment.replies) {\n next.replies.push(\n reply.attachments ? { ...reply, attachments: await relocate(reply.attachments) } : reply\n );\n }\n }\n comments.push(next);\n }\n files.push({ ...file, comments });\n }\n options.signal?.throwIfAborted();\n return { ...state, files };\n}\n","// packages/core/src/review-publisher.ts\n// The one way a review document reaches the disk. Order is the contract: build and validate,\n// stage new assets, then rename the XML into place; a failure before the rename leaves the old files.\n\nimport type { DiagnosticReporter } from './diagnostics';\nimport { isolatedReporter } from './effect-diagnostics';\nimport { resolvePublicationFileSystem } from './publication-fs';\nimport type { PublicationFileSystem, PublicationInspection } from './publication-fs';\nimport * as path from 'node:path';\nimport * as nativeInspection from 'node:fs/promises';\nimport { constants as fsConstants, type Stats } from 'node:fs';\nimport { errnoOf, replacementIdentity } from './safe-fs-policy';\nimport { validateReviewForSerialization } from './review-state-validation';\nimport { ReviewXmlError, XmlIllegalCharacterError } from './xml-errors';\nimport { checkWritability } from './fs-utils';\nimport { serializePlannedReview } from './xml-serializer';\nimport type { ReviewSchemaValidator } from './review-xml-validator';\nimport { ASSET_DIR_NAME, planPublicationAttachments } from './attachment-planner';\nimport type { PublicationAsset } from './attachment-planner';\nimport { MAX_IMAGE_BYTES, MAX_PUBLICATION_ASSET_BYTES, formatBytes } from './input-budgets';\nimport {\n atomicReplaceAsync,\n readContainedFileAsync,\n writeExclusiveNoFollowAsync,\n} from './safe-fs-async';\nimport {\n SafeFsError,\n defaultRandomName,\n guarded,\n inspectReplaceTarget,\n lstatOrNull,\n toSafeFsError,\n} from './safe-fs';\nimport type { FsLayer, SafeFsErrorCode } from './safe-fs';\nimport { AttachmentRelocationError } from './attachment-origins';\nimport type { AttachmentOrigins } from './attachment-origins';\nimport type { ReviewState } from './types';\n\nexport type ReviewPublishErrorCode =\n /** `details` lists each XSD violation. */\n | 'validation-failed'\n | 'xml-illegal-character'\n | 'output-is-directory'\n | 'permission-denied'\n | 'no-space'\n /** A link where the publisher would write, or an inherited path resolving outside its base. */\n | 'unsafe-link'\n /** A hard-linked output, or a non-directory or foreign-owned asset directory. */\n | 'unsupported-target'\n /** A resumed attachment that must move cannot be read where its document put it. */\n | 'attachment-unavailable'\n | 'io-error';\n\nexport class ReviewPublishError extends Error {\n readonly code: ReviewPublishErrorCode;\n readonly path: string;\n /** One rendered line per problem; empty when the message is all there is. */\n readonly details: readonly string[];\n readonly cause?: unknown;\n\n constructor(\n code: ReviewPublishErrorCode,\n path: string,\n message: string,\n options: { details?: readonly string[]; cause?: unknown } = {}\n ) {\n super(message);\n this.name = 'ReviewPublishError';\n this.code = code;\n this.path = path;\n this.details = options.details ?? [];\n if (options.cause !== undefined) this.cause = options.cause;\n }\n}\n\n/** `inherited` paths come from something a repository can commit, so they must stay inside `baseDir`. */\nexport type ReviewOutputOrigin = 'explicit' | 'inherited';\n\n/** Resolved by `resolveOutputTarget` in `startup.ts`. */\nexport type ReviewOutputTarget =\n | { path: string; origin: 'explicit' }\n | { path: string; origin: 'inherited'; baseDir: string };\n\ninterface PublishReviewCommonOptions {\n /** Per-call diagnostics, including XML validation. Defaults to stderr. Must not throw. */\n reportDiagnostic?: DiagnosticReporter;\n /** Optional authoritative schema effect, before staging any asset or XML. */\n validateSchema?: ReviewSchemaValidator;\n fs?: FsLayer;\n /** Explicit asynchronous effects, authoritative over fs when both are supplied. */\n publicationFs?: PublicationFileSystem;\n randomName?: () => string;\n /** Imported attachments whose origin is elsewhere are copied beside the output (`relocateAttachments`). */\n attachmentOrigins?: AttachmentOrigins;\n /** Checked during preparation, between bounded read/write chunks and immediately before rename.\n * Legacy synchronous adapters cannot preempt a single syscall; without readSync their readFileSync\n * allocation is guarded by pre/post size checks rather than a hard allocation bound. Cancellation throws\n * ReviewPublishError (`io-error`, with the signal reason as cause). A completed\n * rename is never rolled back. */\n signal?: AbortSignal;\n}\n\nexport type PublishReviewOptions = PublishReviewCommonOptions &\n (\n | { outputOrigin: 'explicit' }\n | {\n outputOrigin: 'inherited';\n baseDir: string;\n }\n );\n\nexport interface PublishReviewResult {\n outputPath: string;\n /** The attachment files this publication created. */\n assetPaths: string[];\n}\n\n/** @throws ReviewPublishError for every failure, document or filesystem. */\nexport async function publishReview(\n state: ReviewState,\n outputPath: string,\n options: PublishReviewOptions\n): Promise<PublishReviewResult> {\n const effects = resolvePublicationFileSystem(options);\n const fs = effects.inspection;\n const asyncFs = effects.files;\n const reportDiagnostic = isolatedReporter(options.reportDiagnostic);\n const randomName = options.randomName ?? defaultRandomName;\n const target = path.resolve(outputPath);\n const outputDir = path.dirname(target);\n const assetDir = path.join(outputDir, ASSET_DIR_NAME);\n const assertActive = () => {\n if (options.signal?.aborted) {\n throw new ReviewPublishError(\n 'io-error',\n target,\n `Publication of ${target} was cancelled before saving`,\n { cause: options.signal.reason }\n );\n }\n };\n assertActive();\n\n // 1. The document and the output policy, from reads alone.\n let xml: string;\n let assets: PublicationAsset[];\n try {\n state = validateReviewForSerialization(state);\n checkOutputPolicy(target, options, fs);\n const targetAssetDir = options.attachmentOrigins?.size\n ? path.join(fs.realpathSync(outputDir), ASSET_DIR_NAME)\n : assetDir;\n const plan = planPublicationAttachments(\n state,\n target,\n uniqueAssetNamer(assetDir, fs, randomName),\n options.attachmentOrigins ?? new Map(),\n targetAssetDir\n );\n assets = plan.assets;\n xml = await serializePlannedReview(plan.state, reportDiagnostic, options.validateSchema);\n assertActive();\n checkOutputPolicy(target, options, fs);\n } catch (error) {\n assertActive();\n throw toPublishError(error, target);\n }\n\n // 2. Only references are retained by the plan. Disk-derived bytes live for one asset at a time.\n const staged: string[] = [];\n let remaining = MAX_PUBLICATION_ASSET_BYTES;\n try {\n // Recheck mutable/resizable buffers after asynchronous validation. Fix each view's length so\n // later growth cannot increase what an in-flight write consumes.\n const inline = new Map<PublicationAsset, Uint8Array>();\n for (const asset of assets) {\n if ('data' in asset) {\n const length = new Uint8Array(asset.data).byteLength;\n if (length > MAX_IMAGE_BYTES || length > remaining) {\n const message =\n `Attachment bytes exceed the ${formatBytes(MAX_IMAGE_BYTES)} per-image or ` +\n `${formatBytes(MAX_PUBLICATION_ASSET_BYTES)} publication asset limit`;\n throw new ReviewXmlError('invalid-state', message, { details: [message] });\n }\n inline.set(asset, new Uint8Array(asset.data, 0, length));\n remaining -= length;\n }\n }\n for (const asset of assets) {\n assertActive();\n let bytes: Uint8Array;\n if ('data' in asset) bytes = inline.get(asset)!;\n else {\n try {\n const content = await readContainedFileAsync(\n path.dirname(path.dirname(asset.origin)),\n path.join(path.basename(path.dirname(asset.origin)), path.basename(asset.origin)),\n Math.min(MAX_IMAGE_BYTES, remaining),\n asyncFs,\n options.signal\n );\n bytes = content;\n } catch (error) {\n assertActive();\n const safe = toSafeFsError(error, asset.origin, 'read');\n const reason = attachmentReadReason(safe.code);\n throw new AttachmentRelocationError(\n asset.reference,\n asset.origin,\n reason,\n reason === 'too-large' && remaining < MAX_IMAGE_BYTES\n ? `The publication asset budget has ${formatBytes(remaining)} remaining. ${safe.message}`\n : safe.message\n );\n }\n assertActive();\n remaining -= bytes.byteLength;\n }\n assertActive();\n await ensureAssetDirectory(outputDir, effects);\n await writeExclusiveNoFollowAsync(asset.absolutePath, bytes, {\n fs: asyncFs,\n signal: options.signal,\n });\n staged.push(asset.absolutePath);\n }\n assertActive();\n // 3. Rename is the commit boundary. No abort check or fallible cleanup may follow success.\n await atomicReplaceAsync(target, Buffer.from(xml + '\\n', 'utf-8'), {\n fs: asyncFs,\n signal: options.signal,\n beforeCommit: assertActive,\n preserveMode: true,\n randomName,\n });\n } catch (error) {\n for (const file of staged) {\n try {\n await asyncFs.unlink(file);\n } catch {\n /* Rollback must not replace the primary failure. */\n }\n }\n // Async I/O may throw the signal reason directly. Preserve the public cancellation error.\n assertActive();\n throw toPublishError(error, target);\n }\n\n if (staged.length > 0) {\n reportDiagnostic(`[main] Wrote ${staged.length} attachment file(s) to ${assetDir}`);\n }\n return { outputPath: target, assetPaths: staged };\n}\n\n/** The error `publishReview` would throw for the path as it stands; advisory, since the disk can change. */\nexport function inspectOutputPath(\n outputPath: string,\n options: PublishReviewOptions\n): ReviewPublishError | null {\n const fs = resolvePublicationFileSystem(options).inspection;\n const target = path.resolve(outputPath);\n try {\n checkOutputPolicy(target, options, fs);\n } catch (error) {\n return toPublishError(error, target);\n }\n if (!checkWritability(target, fs)) {\n return outputPermissionError(target);\n }\n return null;\n}\n\n/** Read-only location and permission effects. Every supplied method retains its receiver. */\nexport interface OutputPathInspection {\n realpath(target: string): Promise<string>;\n lstat(target: string): Promise<Stats>;\n /** Advisory permission check for the parent, without creating or opening an output file. */\n isWritable(directory: string): Promise<boolean>;\n}\n\nexport type AsyncInspectOutputPathOptions = (\n | { outputOrigin: 'explicit' }\n | { outputOrigin: 'inherited'; baseDir: string }\n) & {\n /** Authoritative for all probes. No native retry or missing-method fallback. */\n inspection?: OutputPathInspection;\n signal?: AbortSignal;\n /** Legacy synchronous providers must keep using inspectOutputPath. */\n fs?: never;\n publicationFs?: never;\n};\n\nexport const nodeOutputPathInspection: OutputPathInspection = {\n realpath: target => nativeInspection.realpath(target),\n lstat: target => nativeInspection.lstat(target),\n async isWritable(directory) {\n try {\n await nativeInspection.access(directory, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n },\n};\n\n/**\n * Asynchronous advisory inspection with the same path policy as inspectOutputPath. Cancellation\n * rejects with the signal reason only after an admitted probe settles. Provider errors are mapped\n * like publication errors; an existing ReviewPublishError retains its identity. Final publication\n * still rechecks the path. Legacy synchronous providers cannot supply this asynchronous role.\n */\nexport async function inspectOutputPathAsync(\n outputPath: string,\n options: AsyncInspectOutputPathOptions\n): Promise<ReviewPublishError | null> {\n const target = path.resolve(outputPath);\n const outputDir = path.dirname(target);\n const fs = options.inspection ?? nodeOutputPathInspection;\n const checkCancelled = () => options.signal?.throwIfAborted();\n const probe = async <T>(location: string, action: string, read: () => Promise<T>): Promise<T> => {\n checkCancelled();\n try {\n const result = await read();\n checkCancelled();\n return result;\n } catch (error) {\n checkCancelled();\n // Keep the host's typed error identity before translating raw filesystem failures.\n if (error instanceof ReviewPublishError) throw error;\n throw toSafeFsError(error, location, action);\n }\n };\n checkCancelled();\n try {\n // JavaScript callers may pass old option bags. Refuse rather than inspect the native disk\n // while their supplied filesystem is silently ignored.\n if (options.fs !== undefined || options.publicationFs !== undefined) {\n throw new ReviewPublishError(\n 'io-error',\n target,\n 'Asynchronous output inspection requires the read-only inspection capability'\n );\n }\n if (options.outputOrigin === 'inherited') {\n const base = path.resolve(options.baseDir);\n const physicalBase = await probe(base, 'resolve', () => fs.realpath(base));\n const physicalDir = await probe(outputDir, 'resolve', () => fs.realpath(outputDir));\n assertOutputDirectoryContained(target, physicalBase, physicalDir);\n }\n let stats: Stats | null;\n try {\n stats = await probe(target, 'inspect', () => fs.lstat(target));\n } catch (error) {\n if (error instanceof SafeFsError && errnoOf(error.cause) === 'ENOENT') stats = null;\n else throw error;\n }\n if (stats !== null) replacementIdentity(target, stats);\n const writable = await probe(outputDir, 'check writability', () => fs.isWritable(outputDir));\n checkCancelled();\n if (!writable) {\n return outputPermissionError(target);\n }\n return null;\n } catch (error) {\n checkCancelled();\n return toPublishError(error, target);\n }\n}\n\nfunction outputPermissionError(target: string): ReviewPublishError {\n return new ReviewPublishError(\n 'permission-denied',\n target,\n `Cannot write ${target}: ${path.dirname(target)} does not exist or is not writable`\n );\n}\n\nfunction assertOutputDirectoryContained(\n target: string,\n physicalBase: string,\n physicalDir: string\n): void {\n const rel = path.relative(physicalBase, physicalDir);\n if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {\n throw new SafeFsError(\n 'unsafe-link',\n target,\n `Refusing to write ${target}: the configured output directory resolves to ${physicalDir}, outside ${physicalBase}. ` +\n 'Choose the output path explicitly to save there.'\n );\n }\n}\n\n/** A file at a drawn name means another draw; a link there is a trap and is refused. */\nfunction uniqueAssetNamer(\n assetDir: string,\n fs: Pick<PublicationInspection, 'lstatSync'>,\n randomName: () => string\n) {\n const chosen = new Set<string>();\n return (idPrefix: string, _index: number, ext: string): string => {\n for (let attempt = 0; attempt < 16; attempt++) {\n const name = `${idPrefix}-${randomName()}.${ext}`;\n if (chosen.has(name)) continue;\n const candidate = path.join(assetDir, name);\n const stats = lstatOrNull(candidate, fs);\n if (stats?.isSymbolicLink()) {\n throw new SafeFsError(\n 'unsafe-link',\n candidate,\n `Refusing to write attachment ${candidate}: a symbolic link already sits at that name`\n );\n }\n if (stats === null) {\n chosen.add(name);\n return name;\n }\n }\n throw new SafeFsError(\n 'io-error',\n assetDir,\n `Could not find a free attachment name under ${assetDir} after 16 attempts`\n );\n };\n}\n\n/** The leaf and, for an inherited path, the containment checks. Reads only. */\nfunction checkOutputPolicy(\n target: string,\n options: PublishReviewOptions,\n fs: PublicationInspection\n): void {\n if (options.outputOrigin === 'inherited') {\n const base = path.resolve(options.baseDir);\n const outputDir = path.dirname(target);\n const physicalBase = guarded(base, 'resolve', () => fs.realpathSync(base));\n const physicalDir = guarded(outputDir, 'resolve', () => fs.realpathSync(outputDir));\n assertOutputDirectoryContained(target, physicalBase, physicalDir);\n }\n // Checked now as well as at write time, so no asset is staged for a document that cannot be published.\n inspectReplaceTarget(target, fs);\n}\n\n/** A real directory this user owns. `mkdir` is not recursive: a missing output directory fails the save anyway. */\nasync function ensureAssetDirectory(\n outputDir: string,\n effects: PublicationFileSystem\n): Promise<void> {\n const fs = effects.inspection;\n const assetDir = path.join(outputDir, ASSET_DIR_NAME);\n let stats = lstatOrNull(assetDir, fs);\n if (stats === null) {\n await effects.mkdir(assetDir, 0o755).catch(error => {\n throw toSafeFsError(error, assetDir, 'create attachment directory');\n });\n stats = guarded(assetDir, 'inspect', () => fs.lstatSync(assetDir));\n }\n\n if (stats.isSymbolicLink()) {\n throw new SafeFsError(\n 'unsafe-link',\n assetDir,\n `Refusing to write attachments through ${assetDir}: it is a symbolic link`\n );\n }\n if (!stats.isDirectory()) {\n throw new SafeFsError(\n 'unsupported-target',\n assetDir,\n `Cannot write attachments: ${assetDir} exists but is not a directory`\n );\n }\n const uid = effects.currentUid();\n if (uid !== undefined && stats.uid !== uid) {\n throw new SafeFsError(\n 'unsupported-target',\n assetDir,\n `Refusing to write attachments into ${assetDir}: it is owned by another user`\n );\n }\n}\n\nconst SAFE_FS_TO_PUBLISH: Partial<Record<SafeFsErrorCode, ReviewPublishErrorCode>> = {\n 'output-is-directory': 'output-is-directory',\n 'permission-denied': 'permission-denied',\n 'no-space': 'no-space',\n 'unsafe-link': 'unsafe-link',\n 'unsupported-target': 'unsupported-target',\n};\n\nfunction toPublishError(error: unknown, target: string): ReviewPublishError {\n if (error instanceof ReviewPublishError) return error;\n // atomicReplace wraps a refused rename in a filesystem error. Keep the\n // publisher's typed cancellation rather than relabeling it as an I/O failure.\n if (error instanceof SafeFsError && error.cause instanceof ReviewPublishError) return error.cause;\n if (error instanceof AttachmentRelocationError) {\n return new ReviewPublishError('attachment-unavailable', error.origin, error.message, {\n details: [error.message],\n cause: error,\n });\n }\n if (error instanceof XmlIllegalCharacterError) {\n return new ReviewPublishError('xml-illegal-character', target, error.message, {\n details: [error.message],\n cause: error,\n });\n }\n if (error instanceof ReviewXmlError) {\n return new ReviewPublishError('validation-failed', target, error.message, {\n details: error.details,\n cause: error,\n });\n }\n const fsError = toSafeFsError(error, target, 'write');\n const code = SAFE_FS_TO_PUBLISH[fsError.code] ?? 'io-error';\n return new ReviewPublishError(code, fsError.path, fsError.message, {\n cause: fsError.cause ?? fsError,\n });\n}\n\nfunction attachmentReadReason(code: SafeFsErrorCode) {\n switch (code) {\n case 'not-found':\n case 'unsafe-link':\n case 'too-large':\n case 'not-regular':\n return code;\n case 'output-is-directory':\n return 'not-regular';\n default:\n return 'io-error';\n }\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","// 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","// Scans a directory (or one file) into DiffFile[], every file a new addition.\n// The walk is bounded (input-budgets.ts): ignored directories are never opened, and\n// hitting `maxEntries` yields no files rather than a shorter review that looks complete.\n// Only regular files are reviewed; links are never followed out of the tree.\n\nimport { stderrReporter, type DiagnosticReporter } from './diagnostics';\nimport { basename, dirname, join } from 'path';\nimport { SafeFsError, sameFile } from './safe-fs';\nimport { assertNoSymlinkAncestorsAsync } from './safe-fs-read';\nimport type { ScanFsLayer } from './scan-fs';\nimport { nodeScanFsLayer } from './node-scan-fs';\nimport { DiffFile } from './types';\nimport { loadSyntheticFilesAsync } from './synthetic-diff';\nimport { checkLoadingCancelled, loadingCheckpoint } from './local-loading-lifetime';\nimport { createIgnoreFilter } from './ignore-filter';\nimport { resolveSourceBudgets, type SourceBudgets } from './input-budgets';\n\nexport interface SourceScanOptions {\n /** Read-only scan and descriptor capability; never falls back to the host filesystem. */\n scanFs?: ScanFsLayer;\n /** Defaults to stderr. Payload diagnostics are retained independently of presentation. */\n reportDiagnostic?: DiagnosticReporter;\n budgets?: Partial<SourceBudgets>;\n /** Rejects with CommandCancelledError, including ordinary Error abort reasons. */\n signal?: AbortSignal;\n}\n\nexport interface SourceScanResult {\n files: DiffFile[];\n /** For `DiffLoadPayload.diagnostics`; empty for a clean scan. */\n diagnostics: string[];\n /** `files` is empty when this is true. */\n entryLimitExceeded: boolean;\n}\n\n/**\n * Recursively scans `directoryPath`; a directory matching `ignorePatterns` is pruned without being\n * opened.\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = [],\n options: SourceScanOptions = {}\n): Promise<SourceScanResult> {\n checkLoadingCancelled(options.signal);\n const layer = options.scanFs ?? nodeScanFsLayer;\n const budgets = resolveSourceBudgets(options.budgets);\n\n let root: string;\n try {\n const dirStat = await layer.stat(directoryPath);\n checkLoadingCancelled(options.signal);\n if (!dirStat.isDirectory()) {\n return failed(\n options.reportDiagnostic,\n `Cannot review \"${directoryPath}\": it is not a directory.`\n );\n }\n root = await layer.realpath(directoryPath);\n checkLoadingCancelled(options.signal);\n } catch (error) {\n checkLoadingCancelled(options.signal);\n return failed(\n options.reportDiagnostic,\n `Cannot read directory \"${directoryPath}\": ${messageOf(error)}`\n );\n }\n\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n let walk: WalkResult;\n try {\n walk = await walkDirectory(root, shouldKeep, budgets.maxEntries, layer, options.signal);\n } catch (error) {\n checkLoadingCancelled(options.signal);\n return failed(\n options.reportDiagnostic,\n `Cannot read directory \"${directoryPath}\": ${messageOf(error)}`\n );\n }\n\n checkLoadingCancelled(options.signal);\n if (walk.limitExceeded) {\n (options.reportDiagnostic ?? stderrReporter)(\n `[scan] Stopped scanning ${directoryPath} after ${budgets.maxEntries} entries`\n );\n return {\n files: [],\n diagnostics: [\n `\"${directoryPath}\" has more than ${budgets.maxEntries.toLocaleString('en-US')} ` +\n 'entries outside ignored directories, so it was not loaded. Review a ' +\n 'subdirectory, or add ignore patterns (the `ignore` config key) for build ' +\n 'output and dependency folders.',\n ],\n entryLimitExceeded: true,\n };\n }\n\n // Sort for deterministic output\n walk.files.sort();\n if (walk.files.length === 0) {\n return { files: [], diagnostics: [], entryLimitExceeded: false };\n }\n\n const { files, diagnostics } = await loadSyntheticFilesAsync(walk.files, root, {\n readFs: layer,\n budgets: options.budgets,\n signal: options.signal,\n });\n return { files, diagnostics, entryLimitExceeded: false };\n}\n\n/**\n * The reviewer named this path explicitly, so a symlink is read through; the per-file budget still\n * applies.\n */\nexport async function scanFile(\n filePath: string,\n options: SourceScanOptions = {}\n): Promise<SourceScanResult> {\n checkLoadingCancelled(options.signal);\n const layer = options.scanFs ?? nodeScanFsLayer;\n try {\n const fileStat = await layer.stat(filePath);\n checkLoadingCancelled(options.signal);\n if (!fileStat.isFile()) {\n return failed(\n options.reportDiagnostic,\n `Cannot review \"${filePath}\": it is not a regular file.`\n );\n }\n } catch (error) {\n checkLoadingCancelled(options.signal);\n return failed(options.reportDiagnostic, `Cannot read file \"${filePath}\": ${messageOf(error)}`);\n }\n\n const { files, diagnostics } = await loadSyntheticFilesAsync(\n [basename(filePath)],\n dirname(filePath),\n {\n followSymlinks: true,\n readFs: layer,\n budgets: options.budgets,\n signal: options.signal,\n }\n );\n return { files, diagnostics, entryLimitExceeded: false };\n}\n\ninterface WalkResult {\n files: string[];\n limitExceeded: boolean;\n}\n\nasync function walkDirectory(\n root: string,\n shouldKeep: (path: string) => boolean,\n maxEntries: number,\n layer: ScanFsLayer,\n signal?: AbortSignal\n): Promise<WalkResult> {\n const files: string[] = [];\n // Relative directory paths still to open; '' is the root itself.\n const pending: string[] = [''];\n let examined = 0;\n\n while (pending.length > 0) {\n await loadingCheckpoint(signal);\n const relativeDir = pending.pop()!;\n const target = join(root, relativeDir);\n const before = await inspectDirectory(root, relativeDir, layer, signal);\n checkLoadingCancelled(signal);\n const dir = await layer.opendir(target);\n try {\n checkLoadingCancelled(signal);\n // opendir yields: a queued directory or one of its ancestors may have changed.\n const after = await inspectDirectory(root, relativeDir, layer, signal);\n if (!sameFile(before, after)) {\n throw new SafeFsError('identity-changed', target, `${target} changed while opening`);\n }\n for await (const entry of dir) {\n await loadingCheckpoint(signal);\n examined++;\n if (examined > maxEntries) return { files, limitExceeded: true };\n\n const relativePath = relativeDir === '' ? entry.name : `${relativeDir}/${entry.name}`;\n if (entry.isDirectory()) {\n // The trailing slash lets `node_modules/`-style patterns match.\n if (shouldKeep(`${relativePath}/`)) pending.push(relativePath);\n } else if (entry.isFile()) {\n if (shouldKeep(relativePath)) files.push(relativePath);\n }\n }\n } finally {\n // Breaking out of the iterator already closes the handle; a second close throws\n // ERR_DIR_CLOSED.\n await dir.close().catch(() => {});\n }\n }\n\n return { files, limitExceeded: false };\n}\n\nfunction failed(\n reportDiagnostic: DiagnosticReporter = stderrReporter,\n message: string\n): SourceScanResult {\n reportDiagnostic(`[scan] ${message}`);\n return { files: [], diagnostics: [message], entryLimitExceeded: false };\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nasync function inspectDirectory(\n root: string,\n rel: string,\n layer: ScanFsLayer,\n signal?: AbortSignal\n) {\n const target = join(root, rel);\n // Include the directory itself in the ancestor walk.\n await assertNoSymlinkAncestorsAsync(root, join(rel, '.self-review-entry'), layer, signal);\n checkLoadingCancelled(signal);\n const stats = await layer.lstat(target);\n checkLoadingCancelled(signal);\n if (!stats.isDirectory() || (await layer.realpath(target)) !== target) {\n throw new SafeFsError('unsafe-link', target, `${target} is no longer a contained directory`);\n }\n checkLoadingCancelled(signal);\n return stats;\n}\n","// packages/core/src/snapshot-reader.ts\n// Authorized side reads. First-party loaded evidence pins index objects and detects source drift.\n\nimport { runBufferedCommand, type BufferedCommandRunner } from './command-runner';\nimport { CommandCancelledError, isCommandCancelled } from './forge-provider';\nimport * as path from 'path';\nimport type { ReviewSourceIdentity, ReviewSourceSide } from './types';\nimport { MAX_SOURCE_FILE_BYTES } from './input-budgets';\nimport { errnoOf, toSafeFsError } from './safe-fs';\nimport type { SafeFsErrorCode } from './safe-fs';\nimport { rootRelativeReviewedPath } from './source-identity';\nimport { readContainedFileBounded } from './safe-fs-async';\nimport { nodeReadFsLayer, type BoundedAsyncReadFsLayer } from './safe-fs-read';\nimport {\n identityStamp,\n loadedSnapshot,\n loadedReviewState,\n type LoadedReview,\n sourceStamp,\n captureSourceReads,\n RELOAD_REVIEW,\n} from './loaded-snapshot';\nimport type { PhysicalCapture } from './loaded-snapshot';\n\nexport interface ReviewedSnapshot {\n /** Explicit load evidence. A logical identity copy alone has only legacy live semantics. */\n loadedReview?: LoadedReview | null;\n sourceIdentity: ReviewSourceIdentity | null;\n reviewedPaths: ReadonlySet<string>;\n}\n\nexport type ReviewedPathRefusal =\n | 'no-source'\n | 'not-reviewed'\n /** Absolute, empty, or leaving the source root. */\n | 'invalid-path';\n\nexport type ReviewedPathAuthorization =\n | {\n ok: true;\n /** Restated from `sourceRoot` through the identity's prefix, normalized. */\n relativePath: string;\n sourceRoot: string;\n }\n | { ok: false; reason: ReviewedPathRefusal; message: string };\n\n/** The one path check every front end delegates to; what passes is exactly what the readers open. */\nexport function authorizeReviewedPath(\n source: ReviewedSnapshot,\n filePath: string\n): ReviewedPathAuthorization {\n const identity = source.sourceIdentity;\n if (identity === null) {\n return { ok: false, reason: 'no-source', message: 'No review has been loaded.' };\n }\n const invalid: ReviewedPathAuthorization = {\n ok: false,\n reason: 'invalid-path',\n message: 'This path does not stay inside the reviewed source.',\n };\n // The path as sent must be sound before a prefix is put in front of it:\n // `<prefix>//etc/passwd` would normalize into a relative path.\n if (normalizeReviewedPath(filePath) === null) return invalid;\n if (!source.reviewedPaths.has(filePath)) {\n return {\n ok: false,\n reason: 'not-reviewed',\n message: 'This file is not part of the reviewed diff.',\n };\n }\n const relativePath = normalizeReviewedPath(rootRelativeReviewedPath(identity, filePath));\n if (relativePath === null) return invalid;\n return { ok: true, relativePath, sourceRoot: identity.sourceRoot };\n}\n\n/** Diff paths are `/`-separated on every platform; a backslash is an ordinary character. */\nfunction normalizeReviewedPath(filePath: string): string | null {\n if (filePath === '' || filePath.includes('\\0') || path.posix.isAbsolute(filePath)) return null;\n const normalized = path.posix.normalize(filePath);\n if (normalized === '.' || normalized === '..' || normalized.startsWith('../')) return null;\n if (normalized.split('/').includes('..')) return null;\n return normalized;\n}\n\nexport type SnapshotReadFailure =\n | ReviewedPathRefusal\n /** The side has no content (`none`) or could not be identified (`unknown`). */\n | 'side-unavailable'\n | 'not-found'\n /** A directory, FIFO, socket or device. */\n | 'not-regular'\n | 'unsafe-link'\n | 'too-large'\n | 'read-failed';\n\nexport type SnapshotReadResult =\n | { ok: true; content: Buffer }\n | { ok: false; reason: SnapshotReadFailure; message: string };\n\nexport interface SnapshotReadOptions {\n /** Defaults to `MAX_SOURCE_FILE_BYTES`. */\n maxBytes?: number;\n /** Aborts git children; a physical read closes its bounded descriptor before rejecting. */\n signal?: AbortSignal;\n timeoutMs?: number;\n runner?: BufferedCommandRunner;\n /** Bounded reader for legacy identities. Captured reads require the load's own reader. */\n readFs?: BoundedAsyncReadFsLayer;\n}\n\nfunction failure(reason: SnapshotReadFailure, message: string): SnapshotReadResult {\n return { ok: false, reason, message };\n}\n\n/** A blob from the object store, or the file under the physical source root; authorized first. */\nexport async function readReviewedContent(\n source: ReviewedSnapshot,\n filePath: string,\n side: 'old' | 'new',\n options: SnapshotReadOptions = {}\n): Promise<SnapshotReadResult> {\n const authorized = authorizeReviewedPath(source, filePath);\n if (!authorized.ok) return failure(authorized.reason, authorized.message);\n const throwIfAborted = () => {\n if (options.signal?.aborted)\n throw new CommandCancelledError('aborted', 'self-review', [\n 'read-reviewed-content',\n filePath,\n ]);\n };\n throwIfAborted();\n const identity = source.sourceIdentity!;\n const sides = identity.fileSources?.get(filePath) ?? identity;\n const descriptor = side === 'old' ? sides.oldSide : sides.newSide;\n const maxBytes = options.maxBytes ?? MAX_SOURCE_FILE_BYTES;\n const explicit = source.loadedReview ? loadedReviewState(source.loadedReview) : undefined;\n if (explicit && (explicit.identity !== identity || !explicit.reviewedPaths.has(filePath)))\n return failure('read-failed', RELOAD_REVIEW);\n const captured = explicit?.snapshot ?? loadedSnapshot(identity);\n if (captured && captured.identityStamp !== identityStamp(identity)) {\n return failure('read-failed', RELOAD_REVIEW);\n }\n if (captured && (descriptor.kind === 'index' || descriptor.kind === 'commit')) {\n if (captured.gitOptions?.runner && !captured.blobRunner && !options.runner) {\n return failure(\n 'read-failed',\n 'The supplied git source needs a binary snapshot runner for blob reads.'\n );\n }\n const spec =\n descriptor.kind === 'index'\n ? captured.index.get(filePath)\n : `${descriptor.sha}:${authorized.relativePath}`;\n const result = spec\n ? await readGitBlob(authorized.sourceRoot, spec, maxBytes, {\n ...options,\n runner: options.runner ?? captured.blobRunner,\n })\n : failure('side-unavailable', 'No stage-zero blob was captured for this side of the review.');\n throwIfAborted();\n return captured.identityStamp === identityStamp(identity)\n ? result\n : failure('read-failed', RELOAD_REVIEW);\n }\n const physical = ['working-tree', 'directory', 'file'].includes(descriptor.kind);\n if (captured && physical && !captured.physical.has(filePath)) {\n return failure('read-failed', RELOAD_REVIEW);\n }\n const result = await readSide(\n descriptor,\n authorized.sourceRoot,\n authorized.relativePath,\n maxBytes,\n options,\n captured?.physical.get(filePath)\n );\n throwIfAborted();\n if (captured && captured.identityStamp !== identityStamp(identity))\n return failure('read-failed', RELOAD_REVIEW);\n return result;\n}\n\n/** Read through an original load capability; structural/serialized identities are not accepted. */\nexport function readLoadedReviewContent(\n loadedReview: LoadedReview,\n filePath: string,\n side: 'old' | 'new',\n options: SnapshotReadOptions = {}\n): Promise<SnapshotReadResult> {\n const state = loadedReviewState(loadedReview);\n return readReviewedContent(\n { sourceIdentity: state.identity, reviewedPaths: state.reviewedPaths, loadedReview },\n filePath,\n side,\n options\n );\n}\n\nasync function readSide(\n descriptor: ReviewSourceSide,\n sourceRoot: string,\n relativePath: string,\n maxBytes: number,\n options: SnapshotReadOptions,\n capture?: PhysicalCapture\n): Promise<SnapshotReadResult> {\n switch (descriptor.kind) {\n case 'working-tree':\n case 'directory':\n return readPhysicalFile(sourceRoot, relativePath, maxBytes, options, capture);\n case 'file': {\n // Walked from the filesystem root: the path was physical at load, so any link now is new.\n const fsRoot = path.parse(descriptor.path).root;\n return readPhysicalFile(\n fsRoot,\n path.relative(fsRoot, descriptor.path),\n maxBytes,\n options,\n capture\n );\n }\n case 'index':\n // `:path` alone would read a leading `<n>:` in the path as a stage number.\n return readGitBlob(sourceRoot, `:0:${relativePath}`, maxBytes, options);\n case 'commit':\n return readGitBlob(sourceRoot, `${descriptor.sha}:${relativePath}`, maxBytes, options);\n case 'none':\n return failure('side-unavailable', 'This side of the review has no content.');\n case 'unknown':\n return failure(\n 'side-unavailable',\n `This side of the review could not be identified: ${descriptor.reason}.`\n );\n }\n}\n\nasync function readPhysicalFile(\n root: string,\n relativePath: string,\n maxBytes: number,\n options: SnapshotReadOptions,\n capture?: PhysicalCapture\n): Promise<SnapshotReadResult> {\n try {\n if (capture && options.readFs && options.readFs !== capture.readFs)\n return failure('read-failed', RELOAD_REVIEW);\n const layer = options.readFs ?? capture?.readFs ?? nodeReadFsLayer;\n const target = path.join(root, relativePath);\n const verify = async () => {\n if (\n capture &&\n (capture.target !== target || sourceStamp(await layer.lstat(target)) !== capture.stamp)\n ) {\n throw new Error(RELOAD_REVIEW);\n }\n };\n await verify();\n const observation = captureSourceReads(layer, options.signal);\n const content = await readContainedFileBounded(\n root,\n relativePath,\n maxBytes,\n observation.readFs,\n options.signal\n );\n if (capture && observation.captures.get(target)?.stamp !== capture.stamp)\n throw new Error(RELOAD_REVIEW);\n await verify();\n return { ok: true, content };\n } catch (error) {\n if (options.signal?.aborted)\n throw new CommandCancelledError('aborted', 'self-review', ['read-reviewed-content']);\n const fsError = toSafeFsError(error, relativePath, 'read');\n if (capture && fsError.code !== 'too-large') return failure('read-failed', RELOAD_REVIEW);\n const [reason, message = fsError.message] = FS_FAILURES[fsError.code] ?? ['read-failed'];\n return failure(reason, message);\n }\n}\n\nconst FS_FAILURES: Partial<Record<SafeFsErrorCode, [SnapshotReadFailure, string?]>> = {\n 'not-found': ['not-found', 'The file does not exist on this side of the review.'],\n 'unsafe-link': ['unsafe-link', 'The path goes through a symbolic link.'],\n 'output-is-directory': ['not-regular', 'The path is a directory.'],\n 'not-regular': ['not-regular', 'The path is not a regular file.'],\n 'unsupported-target': ['invalid-path', 'This path does not stay inside the reviewed source.'],\n 'too-large': ['too-large'],\n};\n\n/** `cat-file blob`, not `show`: it refuses a tree and never smudges, so the bytes are the ones git compared. */\nasync function readGitBlob(\n root: string,\n spec: string,\n maxBytes: number,\n options: SnapshotReadOptions\n): Promise<SnapshotReadResult> {\n try {\n const result = await (options.runner ?? runBufferedCommand)('git', ['cat-file', 'blob', spec], {\n cwd: root,\n maxOutputBytes: maxBytes + 1,\n timeoutMs: options.timeoutMs ?? 30_000,\n signal: options.signal,\n });\n if (result.exitCode !== 0) {\n const detail = result.stderr.toString('utf-8').trim();\n if (/does not exist|not a valid object name|invalid object name|not a blob/i.test(detail)) {\n return failure('not-found', 'The file does not exist on this side of the review.');\n }\n return failure('read-failed', `git cat-file failed: ${detail || `exit ${result.exitCode}`}`);\n }\n if (result.stdout.length > maxBytes)\n return failure('too-large', `The blob is over the ${maxBytes}-byte limit.`);\n return { ok: true, content: result.stdout };\n } catch (error) {\n if (isCommandCancelled(error) && error.reason === 'aborted') throw error;\n if (errnoOf(error) === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {\n return failure('too-large', `The blob is over the ${maxBytes}-byte limit.`);\n }\n return failure(\n 'read-failed',\n `git cat-file failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n}\n","// YAML configuration loading and merging\n\nimport { join } from 'path';\nimport { parse as parseYaml } from 'yaml';\nimport { AppConfig } from './types';\nimport type { DiagnosticReporter } from './diagnostics';\nimport { isolatedReporter } from './effect-diagnostics';\nimport { createDefaultConfig } from '../../config/src/index';\nimport { gitDiffArgsSyntaxError } from './git-argument-text';\nimport { nativeConfigEffects } from './config-reader';\nimport type { BoundedReadOptions, BoundedReadResult } from './bounded-read';\nimport { normalizeConfigFontSize } from './config-font-size';\n\n// Privately owned reference values, independent of the public compatibility snapshots.\nconst defaults = createDefaultConfig();\n\n/**\n * `project` config is repository data and is trusted less than the reviewer's own `user` config.\n */\nexport type ConfigValueOrigin = 'default' | 'user' | 'project';\n\nexport type ConfigProvenance = Readonly<Record<keyof AppConfig, ConfigValueOrigin>>;\n\nexport interface ConfigSource {\n origin: 'user' | 'project';\n path: string;\n}\n\nexport interface LoadedConfig {\n config: AppConfig;\n provenance: ConfigProvenance;\n sources: ConfigSource[];\n}\n\n/** Synchronous startup effects. A supplied implementation owns every read and location lookup. */\nexport interface ConfigEffects {\n exists(path: string): boolean;\n read(path: string, maxBytes: number, options: BoundedReadOptions): BoundedReadResult;\n homeDir(): string;\n cwd(): string;\n}\n\nexport interface LoadConfigOptions {\n effects?: ConfigEffects;\n cwd?: string;\n homeDir?: string;\n /** Defaults to stderr; supply a callback to collect diagnostics without printing. */\n reportDiagnostic?: DiagnosticReporter;\n}\n\n/** Configuration is small startup input, bounded before YAML parsing. */\nexport const MAX_CONFIG_BYTES = 1024 * 1024;\n\nconst CONFIG_KEYS = Object.keys(defaults) as (keyof AppConfig)[];\n\n/**\n * Project overrides user overrides defaults; an invalid value is not attributed to its file.\n * The deprecated `output-format` key is retained verbatim for compatibility. Publication always\n * produces XML. Unsupported values warn without rejecting the configuration or changing provenance.\n */\nexport function loadConfigWithProvenance(options: LoadConfigOptions = {}): LoadedConfig {\n const reportDiagnostic = isolatedReporter(options.reportDiagnostic);\n const effects = options.effects ?? nativeConfigEffects;\n let config = createDefaultConfig();\n const provenance = Object.fromEntries(CONFIG_KEYS.map(key => [key, 'default'])) as Record<\n keyof AppConfig,\n ConfigValueOrigin\n >;\n // `guideFile` has no default, so it is missing from CONFIG_KEYS.\n provenance.guideFile = 'default';\n const sources: ConfigSource[] = [];\n\n const files: ConfigSource[] = [\n {\n origin: 'user',\n path: join(options.homeDir ?? effects.homeDir(), '.config', 'self-review', 'config.yaml'),\n },\n { origin: 'project', path: join(options.cwd ?? effects.cwd(), '.self-review.yaml') },\n ];\n for (const source of files) {\n if (!effects.exists(source.path)) continue;\n try {\n const override = loadYamlConfig(\n source.path,\n source.origin === 'project',\n reportDiagnostic,\n effects\n );\n config = mergeConfig(config, override);\n for (const key of Object.keys(override) as (keyof AppConfig)[]) {\n provenance[key] = source.origin;\n }\n sources.push(source);\n } catch (error) {\n reportDiagnostic(\n `Warning: Failed to load ${source.origin} config from ${source.path}: ${error}`\n );\n }\n }\n\n return { config, provenance, sources };\n}\n\n/** Load merged configuration; `output-format` is deprecated and publication always uses XML. */\nexport function loadConfig(options: LoadConfigOptions = {}): AppConfig {\n return loadConfigWithProvenance(options).config;\n}\n\n// Do not invoke YAML mappings' coercion properties or expand aliased collections for a warning.\nfunction describeConfigValue(value: unknown): string {\n return value !== null && typeof value === 'object'\n ? Object.prototype.toString.call(value)\n : String(value);\n}\n\nfunction loadYamlConfig(\n path: string,\n noFollow: boolean,\n reportDiagnostic: DiagnosticReporter,\n reader: Pick<ConfigEffects, 'read'>\n): Partial<AppConfig> {\n // Project data cannot redirect startup reads through a link. User config may link\n // to another regular file, but the same byte and nonblocking limits apply.\n const read = reader.read(path, MAX_CONFIG_BYTES, { noFollow });\n if (read.kind === 'not-regular') throw new Error('Config is not a regular file');\n if (read.kind === 'too-large') {\n throw new Error(`Config exceeds the ${MAX_CONFIG_BYTES}-byte limit`);\n }\n const content = read.content.toString('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 reportDiagnostic(\n `Warning: Invalid theme value \"${describeConfigValue(raw.theme)}\", using default`\n );\n }\n }\n\n if ('diff-view' in raw) {\n if (['split', 'unified'].includes(raw['diff-view'])) {\n config.diffView = raw['diff-view'];\n } else {\n reportDiagnostic(\n `Warning: Invalid diff-view value \"${describeConfigValue(raw['diff-view'])}\", using default`\n );\n }\n }\n\n if ('font-size' in raw && typeof raw['font-size'] === 'number') {\n const normalized = normalizeConfigFontSize({ fontSize: raw['font-size'] }, defaults.fontSize);\n if (normalized.diagnostic) reportDiagnostic(normalized.diagnostic);\n else config.fontSize = normalized.config.fontSize;\n }\n\n if ('output-format' in raw && typeof raw['output-format'] === 'string') {\n config.outputFormat = raw['output-format'];\n if (config.outputFormat !== 'xml') {\n reportDiagnostic(\n 'Warning: output-format is deprecated; only XML output is supported. The configured value is retained for compatibility.'\n );\n }\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 reportDiagnostic(\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 const syntaxError = gitDiffArgsSyntaxError(raw['default-diff-args']);\n if (syntaxError === null) {\n config.defaultDiffArgs = raw['default-diff-args'];\n } else {\n reportDiagnostic(\n `Warning: Invalid default-diff-args: ${syntaxError}; keeping the inherited value`\n );\n }\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 for (const [key, property] of [\n ['max-files', 'maxFiles'],\n ['max-total-lines', 'maxTotalLines'],\n ] as const) {\n if (!(key in raw)) continue;\n const value = raw[key];\n // Threshold comparisons support fractions; only zero explicitly disables a dimension.\n if (\n typeof value === 'number' &&\n Number.isFinite(value) &&\n value >= 0 &&\n value <= Number.MAX_SAFE_INTEGER\n ) {\n config[property] = value;\n } else {\n reportDiagnostic(\n `Warning: Invalid ${key} value \"${describeConfigValue(value)}\", expected a finite number between 0 and ${Number.MAX_SAFE_INTEGER}; keeping the inherited value`\n );\n }\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","// Native defaults for the optional configuration effects boundary.\nimport { existsSync } from 'fs';\nimport { homedir } from 'os';\nimport { readFileWithinBudgetSync } from './bounded-read';\nimport type { ConfigEffects } from './config';\n\nexport const nativeConfigEffects: ConfigEffects = {\n exists: existsSync,\n read: readFileWithinBudgetSync,\n homeDir: homedir,\n cwd: () => process.cwd(),\n};\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { stderrReporter } from './diagnostics';\nimport { executeGit, type GitExecutionOptions } from './git';\nimport { isCommandCancelled } from './forge-provider';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\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: Pick<AppConfig, 'maxFiles' | 'maxTotalLines'>\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\nexport interface GitDiffStats {\n fileCount: number;\n totalLines: number;\n}\n\nexport type GitDiffStatsResult =\n | { available: true; stats: GitDiffStats }\n | { available: false; error: unknown };\n\n/**\n * Bounded --numstat lookup. Unavailable statistics are distinct from a genuinely empty diff.\n * Abort and timeout reject with CommandCancelledError instead of becoming an empty result.\n */\nexport async function getGitDiffStatsResult(\n args: string[],\n repoRoot: string,\n options: GitExecutionOptions = {}\n): Promise<GitDiffStatsResult> {\n try {\n const stdout = await executeGit(\n ['diff', '--numstat', ...args],\n repoRoot,\n { ...options, timeoutMs: options.timeoutMs ?? 15_000 },\n 10 * 1024 * 1024\n );\n let fileCount = 0;\n let totalLines = 0;\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 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 return { available: true, stats: { fileCount, totalLines } };\n } catch (error) {\n if (isCommandCancelled(error)) throw error;\n return { available: false, error };\n }\n}\n\n/**\n * Compatibility lookup: failures still warn and return zeros so existing guards do not block.\n * Use getGitDiffStatsResult to distinguish failure from an empty diff. Cancellation requested\n * through the additive execution options propagates; the historical default timeout falls back.\n */\nexport async function getGitDiffStats(\n args: string[],\n repoRoot: string,\n options: GitExecutionOptions = {}\n): Promise<GitDiffStats> {\n let error: unknown;\n try {\n const result = await getGitDiffStatsResult(args, repoRoot, options);\n if (result.available) return result.stats;\n error = result.error;\n } catch (caught) {\n if (options.signal || options.timeoutMs !== undefined) throw caught;\n error = caught;\n }\n (options.reportDiagnostic ?? stderrReporter)(\n `[payload-sizing] Failed to get git diff stats: ${error instanceof Error ? error.message : 'unknown error'}`\n );\n return { fileCount: 0, totalLines: 0 };\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","// Shared checks for the small JSON subsets consumed by the two forge adapters.\n// Unknown extension fields are ignored; optional API metadata may be absent or null.\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nexport function isOptionalString(value: unknown): boolean {\n return value === undefined || value === null || typeof value === 'string';\n}\n\nexport function isOptionalNumber(value: unknown): boolean {\n return (\n value === undefined || value === null || (typeof value === 'number' && Number.isFinite(value))\n );\n}\n\nexport function isOptionalBoolean(value: unknown): boolean {\n return value === undefined || value === null || typeof value === 'boolean';\n}\n\nexport function isNumericId(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\n/** Semantically unusable numeric anchors stay visible as file-level discussion. */\nexport function hasUsableLines(start: number | null, end: number | null): boolean {\n return (\n start !== null &&\n end !== null &&\n Number.isSafeInteger(start) &&\n Number.isSafeInteger(end) &&\n start > 0 &&\n end > 0\n );\n}\n","// github-provider.ts\n// GitHub implementation of the ForgeProvider interface, backed entirely by\n// the `gh` CLI through an injectable command runner (never the network\n// directly). Read-only: only `gh pr view` and `gh api` GET calls.\n//\n// GitHub Enterprise-style hosts are honored by passing the URL's host (which\n// may include a port) verbatim to gh: as the HOST/OWNER/REPO form for\n// `pr view --repo` and as `--hostname` for `gh api`. gh's own host handling\n// takes it from there (auth per host, API base URL).\n\nimport {\n ForgeCliUnavailableError,\n isCommandCancelled,\n type FetchThreadsOptions,\n type ForgeCommandResult,\n type ForgeCommandRunner,\n type ForgeProvider,\n type ForgeThread,\n type ForgeThreadAnchor,\n type ForgeUrl,\n} from './forge-provider';\n\nimport {\n isRecord,\n isOptionalString,\n isOptionalNumber,\n isNumericId,\n hasUsableLines,\n} from './forge-payload';\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?: string | null;\n line?: number | null;\n start_line?: number | null;\n original_line?: number | null;\n original_start_line?: number | null;\n}\n\n/** Validate the consumed fields before normalizing any page. Extra API fields are allowed. */\nfunction isReviewComment(value: unknown): value is GitHubReviewComment {\n if (!isRecord(value)) return false;\n return (\n isNumericId(value.id) &&\n (value.in_reply_to_id == null || isNumericId(value.in_reply_to_id)) &&\n (value.user == null || (isRecord(value.user) && typeof value.user.login === 'string')) &&\n typeof value.body === 'string' &&\n typeof value.path === 'string' &&\n isOptionalString(value.side) &&\n ['line', 'start_line', 'original_line', 'original_start_line'].every(key =>\n isOptionalNumber(value[key])\n )\n );\n}\n\nconst GH_CLI = 'gh';\n\n/**\n * Run a gh command, translating both failure modes into the typed\n * unavailable error: a runner rejection means the CLI could not be spawned\n * (e.g. ENOENT when gh is absent), a non-zero exit means gh ran but failed\n * (unauthenticated, API error). Callers degrade on this error, never crash.\n */\nasync function runGh(runCommand: ForgeCommandRunner, args: string[]): Promise<string> {\n let result: ForgeCommandResult;\n try {\n result = await runCommand(GH_CLI, args);\n } catch (error) {\n // A run cut short by the session's own bounds is not a missing CLI.\n if (isCommandCancelled(error)) throw error;\n const detail = error instanceof Error ? error.message : String(error);\n throw new ForgeCliUnavailableError('github', GH_CLI, `Failed to run the gh CLI: ${detail}`);\n }\n if (result.exitCode !== 0) {\n const detail = result.stderr.trim() || `exit code ${result.exitCode}`;\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `gh exited with code ${result.exitCode}: ${detail}`\n );\n }\n return result.stdout;\n}\n\n/**\n * Parse gh JSON output, surfacing malformed output as the typed unavailable\n * error so callers keep a single degradation path.\n */\nfunction parseGhJson(stdout: string, context: string): unknown {\n try {\n return JSON.parse(stdout);\n } catch {\n throw new ForgeCliUnavailableError(\n 'github',\n GH_CLI,\n `gh returned unparseable JSON for ${context}`\n );\n }\n}\n\n/**\n * Normalize one review comment's anchor. GitHub reports `line: null` when\n * the comment no longer applies to the head diff (outdated); the\n * `original_*` fields then retain the historic anchor.\n *\n * GitHub re-anchors comments on each push, so `line: null` is the forge's own\n * outdated verdict. `commit_id` can lag re-anchoring, so the provider verifies\n * the PR head around retrieval instead of trusting each comment's recorded commit.\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 ?? null);\n const startLine = outdated\n ? (comment.original_start_line ?? comment.original_line ?? null)\n : (comment.start_line ?? comment.line ?? null);\n const hasLines =\n hasUsableLines(startLine, endLine) &&\n (comment.side == null || comment.side === 'LEFT' || comment.side === 'RIGHT');\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/** An unavailable head read leaves discussion visible but cannot vouch for line numbers. */\nasync function readHead(\n runCommand: ForgeCommandRunner,\n url: ForgeUrl\n): Promise<string | undefined> {\n try {\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 'headRefOid',\n ]);\n const parsed = parseGhJson(stdout, 'pull request head');\n return isRecord(parsed) &&\n typeof parsed.headRefOid === 'string' &&\n /^[a-f0-9]{40}$/i.test(parsed.headRefOid)\n ? parsed.headRefOid\n : undefined;\n } catch (error) {\n if (isCommandCancelled(error)) throw error;\n return undefined;\n }\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');\n if (\n !isRecord(parsed) ||\n typeof parsed.baseRefName !== 'string' ||\n parsed.baseRefName === ''\n ) {\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 expectedHead = options?.reviewedHeadSha;\n const before = expectedHead === undefined ? undefined : await readHead(runCommand, url);\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 (\n !Array.isArray(pages) ||\n !pages.every(page => Array.isArray(page) && page.every(isReviewComment))\n ) {\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: GitHubReviewComment[] = pages.flat(1);\n const threads = groupIntoThreads(comments);\n if (expectedHead !== undefined) {\n const after = await readHead(runCommand, url);\n const verified = before === expectedHead && after === expectedHead;\n for (const thread of threads) {\n if (thread.anchor) {\n thread.anchor = verified\n ? { ...thread.anchor, headSha: expectedHead }\n : { ...thread.anchor, outdated: true };\n }\n }\n }\n return threads;\n },\n };\n}\n","// thread-mapper.ts\n// Deterministic mapper from forge-neutral discussion threads to the v3\n// ReviewComment model. Pure code: no I/O, no randomness, no timestamps —\n// the same input always yields byte-identical output, and it contains no\n// forge-conditional logic (anything forge-specific belongs in the\n// providers). Fetch direction only.\n\nimport type { ForgeThread, ForgeThreadAnchor, ForgeThreadTurn } from './forge-provider';\nimport type { DiffFile, LineRange, Reply, ReviewComment, Suggestion } from './types';\n\n/**\n * Sentinel `filePath` for review-level threads (threads with no file\n * association at all, e.g. GitLab non-diff discussions).\n *\n * The v3 schema has no review-level comment element — every `<comment>`\n * lives inside a `<file path>` — so the mapper degrades these threads to\n * file-level comments on this sentinel path, the closest legal shape.\n * The empty string can never collide with a repository-relative diff path,\n * so consumers (the fetch-comments orchestrator, the app's remote mode)\n * detect review-level comments by comparing against this constant and\n * decide their placement (e.g. a synthetic review-level file entry).\n */\nexport const REVIEW_LEVEL_FILE_PATH = '';\n\n/**\n * How an anchor's line numbers relate to the reviewed head (R05).\n * - `outdated`: forge says so, or `headSha` differs from the reviewed head. Degrades to\n * file-level, since lines of another revision would yield the wrong `originalCode`.\n * - `verified`: names the reviewed head, or the forge vouches for it. The only\n * status that activates a suggestion.\n * - `unverified`: nothing ties it to a revision. Line placement kept, no suggestion.\n */\ntype AnchorStatus = 'verified' | 'unverified' | 'outdated';\n\nfunction classifyAnchor(\n anchor: ForgeThreadAnchor,\n reviewedHeadSha: string | undefined\n): AnchorStatus {\n if (anchor.outdated === true) {\n return 'outdated';\n }\n if (anchor.headSha !== undefined) {\n if (reviewedHeadSha === undefined) return 'unverified';\n return anchor.headSha === reviewedHeadSha ? 'verified' : 'outdated';\n }\n return anchor.outdated === false ? 'verified' : 'unverified';\n}\n\n/**\n * Map an anchor to the model's line range, honoring the exactly-one-pair\n * rule: the single `LineRange.side` selects which pair the serializer\n * emits (`'new'` → `new-line-*`, `'old'` → `old-line-*`), so a comment can\n * never carry both.\n *\n * Returns `null` (file-level) when the anchor is outdated, has no usable\n * line information, or carries non-positive lines (the XSD requires\n * `xs:positiveInteger`, and the serializer must never receive an\n * unserializable range). Reversed bounds are normalized rather than\n * rejected so a defective provider payload still maps deterministically.\n */\nfunction mapAnchorToLineRange(anchor: ForgeThreadAnchor, status: AnchorStatus): LineRange | null {\n if (status === 'outdated') {\n return null;\n }\n const { startLine, endLine } = anchor;\n if (startLine === null || endLine === null) {\n return null;\n }\n if (startLine < 1 || endLine < 1) {\n return null;\n }\n return {\n side: anchor.side,\n start: Math.min(startLine, endLine),\n end: Math.max(startLine, endLine),\n };\n}\n\n/**\n * Internal ids are in-memory render keys the app normally generates\n * randomly on parse. The mapper must be deterministic, so it derives them\n * from the forge-assigned ids instead.\n */\nfunction internalId(turn: ForgeThreadTurn): string {\n return `remote-${turn.remoteId}`;\n}\n\n/**\n * Opening line of a fenced code block: up to three spaces of indent, then\n * three or more backticks or tildes, then the info string. A fence indented\n * four spaces or more is an indented code block, not a fence.\n */\nconst FENCE_OPEN = /^( {0,3})(`{3,}|~{3,})(.*)$/;\n\n/** Drop a single trailing CR so a CRLF body yields LF-terminated lines. */\nfunction stripCr(line: string): string {\n return line.endsWith('\\r') ? line.slice(0, -1) : line;\n}\n\n/** Remove up to `width` leading spaces, the way CommonMark unindents a fence. */\nfunction stripIndent(line: string, width: number): string {\n let i = 0;\n while (i < width && line[i] === ' ') i++;\n return line.slice(i);\n}\n\n/** A closing fence: the same character, at least as long, nothing after it. */\nfunction isClosingFence(line: string, marker: string): boolean {\n const match = FENCE_OPEN.exec(line);\n return (\n match !== null &&\n match[2][0] === marker[0] &&\n match[2].length >= marker.length &&\n match[3].trim() === ''\n );\n}\n\n/**\n * Collect the bodies of every top-level ` ```suggestion ` block in a\n * markdown body, in document order.\n *\n * Fences are walked in order so a `suggestion` fence nested inside another\n * code block is never mistaken for a real one. The info string must be the\n * bare word `suggestion`: GitLab's range form (`suggestion:-1+2`) widens the\n * anchor by an amount this mapper cannot verify against the diff, so it is\n * deliberately not recognized and leaves the thread without a suggestion.\n */\nfunction findSuggestionBlocks(body: string): string[] {\n const lines = body.split('\\n').map(stripCr);\n const blocks: string[] = [];\n let i = 0;\n while (i < lines.length) {\n const open = FENCE_OPEN.exec(lines[i]);\n if (!open) {\n i++;\n continue;\n }\n const [, indent, marker, info] = open;\n // A backtick fence's info string may not contain a backtick.\n if (marker[0] === '`' && info.includes('`')) {\n i++;\n continue;\n }\n const content: string[] = [];\n let j = i + 1;\n for (; j < lines.length && !isClosingFence(lines[j], marker); j++) {\n content.push(stripIndent(lines[j], indent.length));\n }\n if (info.trim().toLowerCase() === 'suggestion') {\n blocks.push(content.join('\\n'));\n }\n // An unclosed fence runs to the end of the body, as GitHub renders it.\n i = j + 1;\n }\n return blocks;\n}\n\n/**\n * Read the reviewed lines the anchor points at, straight out of the diff.\n *\n * Returns `null` unless the diff covers the whole range: a partially covered\n * anchor would produce an `originalCode` that matches nothing, and the apply\n * engine's byte-for-byte check would refuse it anyway. Taking the text from\n * the diff rather than from the thread body is what makes the extracted\n * suggestion anchored rather than merely quoted.\n */\nfunction readAnchoredLines(\n diffFiles: DiffFile[],\n filePath: string,\n range: LineRange\n): string | null {\n const sidePath = (file: DiffFile) => (range.side === 'old' ? file.oldPath : file.newPath);\n const file =\n diffFiles.find(f => sidePath(f) === filePath) ??\n diffFiles.find(f => f.oldPath === filePath || f.newPath === filePath);\n if (!file) return null;\n\n const found: string[] = [];\n for (const hunk of file.hunks) {\n for (const line of hunk.lines) {\n const number = range.side === 'old' ? line.oldLineNumber : line.newLineNumber;\n if (number !== null && number >= range.start && number <= range.end) {\n found.push(line.content);\n }\n }\n }\n return found.length === range.end - range.start + 1 ? found.join('\\n') : null;\n}\n\n/**\n * Turn a `suggestion` fence in a thread's root body into an anchored\n * {@link Suggestion}, or `null` when there is nothing safe to anchor.\n *\n * `null` covers every uncertain case: no fence, more than one fence (keeping\n * the first would drop the rest), a file-level, outdated or unverified anchor\n * (see {@link AnchorStatus}), and an anchor the reviewed diff does not cover.\n */\nfunction extractSuggestion(\n body: string,\n filePath: string,\n range: LineRange | null,\n status: AnchorStatus,\n diffFiles: DiffFile[]\n): Suggestion | null {\n if (!range || status !== 'verified') return null;\n const blocks = findSuggestionBlocks(body);\n if (blocks.length !== 1) return null;\n const originalCode = readAnchoredLines(diffFiles, filePath, range);\n if (originalCode === null) return null;\n return { originalCode, proposedCode: blocks[0] };\n}\n\nfunction mapReply(turn: ForgeThreadTurn): Reply {\n return {\n id: internalId(turn),\n body: turn.body,\n author: turn.author,\n remoteId: turn.remoteId,\n };\n}\n\n/**\n * Convert normalized forge threads into v3 `ReviewComment` threads.\n *\n * - The root turn becomes the root comment and owns the anchor; subsequent\n * turns become flat replies in document order (nothing sorts them).\n * - Forge usernames land in `author`, forge thread/comment ids in\n * `remoteId`, markdown bodies pass through verbatim.\n * - Outdated or line-less anchors degrade to file-level comments\n * (`lineRange: null`); anchor-less threads degrade to file-level\n * comments on {@link REVIEW_LEVEL_FILE_PATH}. The degradation is\n * structural, never textual.\n * - Mapped comments carry no category, severity or confidence: forge\n * threads have none, and absent means below every threshold. The empty\n * `category` matches how the XML parser represents a missing category.\n * - A root body carrying a single ` ```suggestion ` fence becomes a\n * `Suggestion` anchored to the thread's line range, with `originalCode`\n * read out of `diffFiles` at that anchor, only when the anchor is verified\n * (see {@link AnchorStatus}). Without the diff, every `suggestion` is `null`.\n * - An anchor naming a head other than `reviewedHeadSha` is outdated and\n * degrades to file-level; its body is intact.\n *\n * `reviewedHeadSha` is the head `diffFiles` was taken against; omitted, every\n * revision-naming anchor is unverified.\n *\n * Output order is input order. The input is never mutated.\n */\nexport function mapThreadsToReviewComments(\n threads: ForgeThread[],\n diffFiles: DiffFile[] = [],\n reviewedHeadSha?: string\n): ReviewComment[] {\n return threads.map(thread => {\n const filePath = thread.anchor?.filePath ?? REVIEW_LEVEL_FILE_PATH;\n const status = thread.anchor ? classifyAnchor(thread.anchor, reviewedHeadSha) : 'unverified';\n const lineRange = thread.anchor ? mapAnchorToLineRange(thread.anchor, status) : null;\n const comment: ReviewComment = {\n id: internalId(thread.root),\n filePath,\n lineRange,\n body: thread.root.body,\n category: '',\n suggestion: extractSuggestion(thread.root.body, filePath, lineRange, status, diffFiles),\n author: thread.root.author,\n remoteId: thread.root.remoteId,\n };\n if (thread.replies.length > 0) {\n comment.replies = thread.replies.map(mapReply);\n }\n return comment;\n });\n}\n","// gitlab-provider.ts\n// ForgeProvider implementation for GitLab (gitlab.com and self-hosted) backed\n// by the read-only `glab` CLI. All child-process execution goes through an\n// injected ForgeCommandRunner so the provider stays unit-testable and no real\n// `glab` calls happen in tests. Only GET-style commands are issued (`glab\n// api`); nothing is ever posted.\n\nimport {\n ForgeCliUnavailableError,\n isCommandCancelled,\n type FetchThreadsOptions,\n type ForgeAnchorSide,\n type ForgeCommandRunner,\n type ForgeProvider,\n type ForgeThread,\n type ForgeThreadAnchor,\n type ForgeThreadTurn,\n type ForgeUrl,\n} from './forge-provider';\n\nimport {\n isRecord,\n isOptionalString,\n isOptionalNumber,\n isOptionalBoolean,\n isNumericId,\n hasUsableLines,\n} from './forge-payload';\n\nconst GLAB_CLI = 'glab';\n\n// --- Minimal shapes of the GitLab API payloads we consume ---------------\n\ninterface GitLabLineRangeEdge {\n old_line?: number | null;\n new_line?: number | null;\n}\n\ninterface GitLabPosition {\n head_sha?: string | null;\n old_path?: string | null;\n new_path?: string | null;\n old_line?: number | null;\n new_line?: number | null;\n line_range?: {\n start?: GitLabLineRangeEdge | null;\n end?: GitLabLineRangeEdge | null;\n } | null;\n}\n\ninterface GitLabNote {\n id: number | string;\n body?: string | null;\n author?: { username?: string | null } | null;\n system?: boolean | null;\n resolvable?: boolean | null;\n resolved?: boolean | null;\n position?: GitLabPosition | null;\n}\n\ninterface GitLabDiscussion {\n id: string;\n notes: GitLabNote[];\n}\n\nfunction isLineEdge(value: unknown): value is GitLabLineRangeEdge {\n return isRecord(value) && isOptionalNumber(value.old_line) && isOptionalNumber(value.new_line);\n}\n\nfunction isPosition(value: unknown): value is GitLabPosition {\n if (!isRecord(value) || !isLineEdge(value)) return false;\n if (!['head_sha', 'old_path', 'new_path'].every(key => isOptionalString(value[key])))\n return false;\n const range = value.line_range;\n return (\n range == null ||\n (isRecord(range) &&\n (range.start == null || isLineEdge(range.start)) &&\n (range.end == null || isLineEdge(range.end)))\n );\n}\n\nfunction isNote(value: unknown): value is GitLabNote {\n if (!isRecord(value)) return false;\n return (\n (isNumericId(value.id) || (typeof value.id === 'string' && value.id.length > 0)) &&\n isOptionalString(value.body) &&\n (value.author == null || (isRecord(value.author) && isOptionalString(value.author.username))) &&\n ['system', 'resolvable', 'resolved'].every(key => isOptionalBoolean(value[key])) &&\n (value.position == null || isPosition(value.position))\n );\n}\n\nfunction isDiscussion(value: unknown): value is GitLabDiscussion {\n return (\n isRecord(value) &&\n typeof value.id === 'string' &&\n Array.isArray(value.notes) &&\n value.notes.every(isNote)\n );\n}\n\n// --- CLI plumbing -------------------------------------------------------\n\n/** URL-encode the full project path; subgroup slashes become %2F. */\nfunction encodeProjectPath(url: ForgeUrl): string {\n return encodeURIComponent(`${url.owner}/${url.repo}`);\n}\n\nfunction unavailable(message: string): ForgeCliUnavailableError {\n return new ForgeCliUnavailableError('gitlab', GLAB_CLI, message);\n}\n\n/**\n * Run `glab api <endpoint>` against the URL's host and return raw stdout.\n * Spawn failures (ENOENT) and non-zero exits (unauthenticated, API errors)\n * both surface as {@link ForgeCliUnavailableError}.\n */\nasync function runGlabApi(\n runCommand: ForgeCommandRunner,\n url: ForgeUrl,\n endpoint: string,\n extraArgs: string[] = []\n): Promise<string> {\n const args = ['api', endpoint, '--hostname', url.host, ...extraArgs];\n let result;\n try {\n result = await runCommand(GLAB_CLI, args);\n } catch (error) {\n // A run cut short by the session's own bounds is not a missing CLI.\n if (isCommandCancelled(error)) throw error;\n const detail = error instanceof Error ? error.message : String(error);\n throw unavailable(`glab CLI could not be spawned: ${detail}`);\n }\n if (result.exitCode !== 0) {\n const detail = result.stderr.trim() || `exit code ${result.exitCode}`;\n throw unavailable(`glab api ${endpoint} failed: ${detail}`);\n }\n return result.stdout;\n}\n\n/**\n * Parse stdout that may contain several concatenated top-level JSON\n * documents, as `glab api --paginate` emits one array per page. A simple\n * bracket/string scanner keeps `][` sequences inside note bodies from\n * breaking the split.\n */\nfunction parseJsonDocuments(text: string): unknown[] {\n const documents: unknown[] = [];\n let depth = 0;\n let inString = false;\n let escaped = false;\n let start = -1;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === '\\\\') {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (start < 0) {\n if (/\\s/.test(ch)) continue;\n if (ch !== '[' && ch !== '{') throw new Error('unexpected text outside JSON document');\n }\n if (ch === '\"') {\n inString = true;\n } else if (ch === '[' || ch === '{') {\n if (depth === 0) start = i;\n depth += 1;\n } else if (ch === ']' || ch === '}') {\n depth -= 1;\n if (depth === 0 && start >= 0) {\n documents.push(JSON.parse(text.slice(start, i + 1)));\n start = -1;\n }\n }\n }\n if (depth !== 0 || inString) {\n throw new Error('truncated JSON document');\n }\n return documents;\n}\n\n// --- Normalization ------------------------------------------------------\n\nfunction toTurn(note: GitLabNote): ForgeThreadTurn {\n return {\n remoteId: String(note.id),\n author: note.author?.username ?? 'unknown',\n body: note.body ?? '',\n };\n}\n\n/**\n * A discussion counts as resolved when it has at least one resolvable note\n * and every resolvable note is resolved. Discussions with no resolvable\n * notes (non-diff discussions) are never \"resolved\".\n */\nfunction isDiscussionResolved(notes: GitLabNote[]): boolean {\n const resolvable = notes.filter(note => note.resolvable === true);\n return resolvable.length > 0 && resolvable.every(note => note.resolved === true);\n}\n\n/**\n * Build the neutral anchor from a GitLab position object, or `null` when the\n * note has no position (non-diff discussion) or the position carries no\n * usable file path.\n *\n * Side selection: `new_line` present → `'new'` (using `new_path`), otherwise\n * `old_line` present → `'old'` (using `old_path`). A position with a path\n * but neither line (e.g. `position_type: \"file\"`) becomes a file-level\n * anchor with null lines and side `'new'`, per the neutral shape's contract.\n * Multi-line `line_range` edges are read on the side chosen above, falling\n * back to the single-line position when an edge lacks that side's line.\n *\n * GitLab exposes outdatedness only as `position.head_sha`, so the anchor carries\n * `headSha` verbatim and no `outdated` verdict; the mapper compares it with the\n * reviewed head, and a position naming no head stays unverifiable.\n */\nfunction toAnchor(position: GitLabPosition | null | undefined): ForgeThreadAnchor | null {\n if (!position) return null;\n\n const side: ForgeAnchorSide =\n typeof position.old_line === 'number' && typeof position.new_line !== 'number' ? 'old' : 'new';\n const pathForSide = side === 'old' ? position.old_path : position.new_path;\n const filePath = pathForSide ?? position.new_path ?? position.old_path;\n if (!filePath) return null;\n\n const lineOf = (edge: GitLabLineRangeEdge | null | undefined): number | null => {\n const value = side === 'old' ? edge?.old_line : edge?.new_line;\n return typeof value === 'number' ? value : null;\n };\n\n const positionLine = lineOf(position);\n const startLine = lineOf(position.line_range?.start) ?? positionLine;\n const endLine = lineOf(position.line_range?.end) ?? positionLine;\n\n const usable = hasUsableLines(startLine, endLine);\n const anchor: ForgeThreadAnchor = {\n filePath,\n side: usable ? side : 'new',\n startLine: usable ? startLine : null,\n endLine: usable ? endLine : null,\n };\n if (typeof position.head_sha === 'string' && position.head_sha.length > 0) {\n anchor.headSha = position.head_sha;\n }\n return anchor;\n}\n\n/**\n * Normalize one GitLab discussion into the forge-neutral thread shape, or\n * `null` when nothing user-authored remains after dropping system notes.\n * The first surviving note roots the thread and owns the anchor; the rest\n * are ordered replies (GitLab document order is preserved verbatim).\n */\nfunction toThread(discussion: GitLabDiscussion): ForgeThread | null {\n const notes = discussion.notes.filter(note => note.system !== true);\n if (notes.length === 0) return null;\n const [rootNote, ...replyNotes] = notes;\n return {\n root: toTurn(rootNote),\n replies: replyNotes.map(toTurn),\n anchor: toAnchor(rootNote.position),\n };\n}\n\n// --- Provider -----------------------------------------------------------\n\n/**\n * Create the GitLab {@link ForgeProvider} backed by the `glab` CLI.\n *\n * The URL's host is forwarded via `--hostname`, so self-hosted instances\n * (e.g. git.drupalcode.org) work with zero configuration beyond `glab auth`.\n * Resolved discussions are excluded unless `includeResolved` is set.\n */\nexport function createGitLabProvider(runCommand: ForgeCommandRunner): ForgeProvider {\n return {\n forge: 'gitlab',\n\n async fetchBaseBranch(url: ForgeUrl): Promise<string> {\n const endpoint = `projects/${encodeProjectPath(url)}/merge_requests/${url.number}`;\n const stdout = await runGlabApi(runCommand, url, endpoint);\n let mr: unknown;\n try {\n mr = JSON.parse(stdout);\n } catch {\n throw unavailable(`glab api ${endpoint} returned unparseable JSON`);\n }\n const targetBranch = isRecord(mr) ? mr.target_branch : undefined;\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 pages: unknown[];\n try {\n pages = parseJsonDocuments(stdout);\n if (pages.length === 0) throw new Error('no JSON documents in output');\n } catch {\n throw unavailable(`glab api ${endpoint} returned unparseable JSON`);\n }\n const discussions: GitLabDiscussion[] = [];\n for (const page of pages) {\n if (!Array.isArray(page) || !page.every(isDiscussion)) {\n throw unavailable(\n `glab api ${endpoint} returned an unexpected payload shape for discussions`\n );\n }\n for (const discussion of page) discussions.push(discussion);\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","// Snapshot image previews and authorized attachment reads for a review session.\nimport path from 'path';\nimport { CommandCancelledError } from './forge-provider';\nimport type { ImageLoadResult, ReviewComment } from './types';\nimport type { ReviewSession } from './review-session';\nimport { locateReviewedFile } from './review-session';\nimport { MAX_IMAGE_BYTES } from './input-budgets';\nimport { isPreviewableImage } from './file-type-utils';\nimport { readReviewedContent } from './snapshot-reader';\nimport {\n authorizeAttachmentReference,\n readAssetFile,\n resolveAttachmentOrigins,\n} from './attachment-origins';\nimport type { ResolvedAttachmentLocation, AttachmentReadResult } from './attachment-origins';\nimport { ASSET_DIR_NAME } from './xml-serializer';\nimport type { DiagnosticReporter } from './diagnostics';\nimport { isolatedReporter } from './effect-diagnostics';\n\nconst IMAGE_MIME_TYPES: Record<string, string> = {\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.bmp': 'image/bmp',\n};\n\nexport interface LoadImageOptions {\n signal?: AbortSignal;\n timeoutMs?: number;\n /** Defaults to stderr. Reporter failures never change the read outcome. */\n reportDiagnostic?: DiagnosticReporter;\n}\n\n/**\n * Reads a reviewed, previewable path. First-party loads pin index blobs and verify physical\n * source evidence; legacy injected identities retain live descriptor reads.\n */\nexport async function loadImage(\n session: Pick<ReviewSession, 'reviewedPaths' | 'diffData' | 'sourceIdentity' | 'loadedReview'>,\n filePath: string,\n options: LoadImageOptions = {}\n): Promise<ImageLoadResult> {\n if (!session.reviewedPaths.has(filePath)) {\n return { error: 'Image preview unavailable — this file is not part of the reviewed diff.' };\n }\n if (!isPreviewableImage(filePath)) {\n return { error: 'Image preview unavailable — this file is not a previewable image.' };\n }\n const located = locateReviewedFile(session, filePath);\n const side = located?.side ?? 'new';\n\n const { sourceIdentity, reviewedPaths, loadedReview } = session;\n const result = await readReviewedContent(\n { sourceIdentity, reviewedPaths, loadedReview },\n filePath,\n side,\n {\n ...options,\n maxBytes: MAX_IMAGE_BYTES,\n }\n );\n if (\n session.sourceIdentity !== sourceIdentity ||\n session.reviewedPaths !== reviewedPaths ||\n session.loadedReview !== loadedReview\n )\n return { error: 'Image preview unavailable — the loaded review changed.' };\n if (!result.ok) {\n if (result.reason === 'too-large') {\n return { error: 'File too large to preview (>10 MB)' };\n }\n isolatedReporter(options.reportDiagnostic)(\n `[review] Image preview unavailable for ${filePath}: ${result.message}`\n );\n return { error: `Image preview unavailable — ${result.message}` };\n }\n const mimeType = IMAGE_MIME_TYPES[path.posix.extname(filePath).toLowerCase()];\n return { dataUri: `data:${mimeType};base64,${result.content.toString('base64')}` };\n}\n\n/**\n * Records that resumed attachments live beside the resumed document, whatever the\n * launch directory or save location. Returns one diagnostic per reference that is\n * not `.self-review-assets/<name>` and so will never be read.\n */\nexport function recordResumedAttachments(\n session: Pick<ReviewSession, 'attachmentOrigins'>,\n comments: readonly ReviewComment[],\n resumeDocumentPath: string,\n location: ResolvedAttachmentLocation\n): string[];\nexport function recordResumedAttachments(\n session: Pick<ReviewSession, 'attachmentOrigins'>,\n comments: readonly ReviewComment[],\n resumeDocumentPath: string\n): string[];\nexport function recordResumedAttachments(\n session: Pick<ReviewSession, 'attachmentOrigins'>,\n comments: readonly ReviewComment[],\n resumeDocumentPath: string,\n location: ResolvedAttachmentLocation | undefined = undefined\n): string[] {\n const { origins, diagnostics } =\n location === undefined\n ? resolveAttachmentOrigins(comments, resumeDocumentPath)\n : resolveAttachmentOrigins(comments, resumeDocumentPath, location);\n session.attachmentOrigins = origins;\n return diagnostics;\n}\n\n/** Authorized asset reads only. Implementations enforce no-follow, regular-file and byte limits. */\nexport interface AttachmentReader {\n readAssetFile(\n assetPath: string,\n options: { signal?: AbortSignal }\n ): Promise<AttachmentReadResult>;\n}\n\nexport interface ReadAttachmentOptions {\n signal?: AbortSignal;\n /** Authoritative when supplied. Failures never retry through the native reader. */\n attachmentReader?: AttachmentReader;\n /** Defaults to stderr. Throwing or rejecting reporters cannot change the read outcome. */\n reportDiagnostic?: DiagnosticReporter;\n}\n\n// Refusals accept unknown input. Do not invoke toJSON/getters or serialize an unbounded object.\nfunction refusedReferenceLabel(reference: unknown): string {\n if (typeof reference === 'string') return JSON.stringify(reference.slice(0, 512));\n if (reference === null) return 'null';\n return `[${typeof reference}]`;\n}\n\n/**\n * Read one attachment by its `.self-review-assets/<name>` reference, never a path:\n * an imported one from its recorded origin, any other from the current output's asset\n * directory. Anything else is `not-authorized` and touches nothing.\n */\nexport async function readAttachment(\n session: Pick<ReviewSession, 'outputPathInfo' | 'attachmentOrigins'>,\n reference: unknown,\n options: ReadAttachmentOptions = {}\n): Promise<AttachmentReadResult> {\n const checkCancelled = () => {\n if (options.signal?.aborted)\n throw new CommandCancelledError('aborted', 'self-review', ['read-attachment']);\n };\n checkCancelled();\n const reportDiagnostic = isolatedReporter(options.reportDiagnostic);\n const outputPath = session.outputPathInfo?.resolvedOutputPath;\n const currentAssetDir = outputPath ? path.join(path.dirname(outputPath), ASSET_DIR_NAME) : null;\n const assetPath = authorizeAttachmentReference(\n reference,\n session.attachmentOrigins,\n currentAssetDir\n );\n if (assetPath === null) {\n reportDiagnostic(`[attachment:read] Refused: ${refusedReferenceLabel(reference)}`);\n checkCancelled();\n return {\n ok: false,\n reason: 'not-authorized',\n message: `Attachments are read only from the review's ${ASSET_DIR_NAME} directory`,\n };\n }\n let result: AttachmentReadResult;\n try {\n result = options.attachmentReader\n ? await options.attachmentReader.readAssetFile(assetPath, { signal: options.signal })\n : await readAssetFile(assetPath, { signal: options.signal });\n } catch (error) {\n checkCancelled();\n throw error;\n }\n checkCancelled();\n if (!result.ok) {\n reportDiagnostic(`[attachment:read] ${result.reason}: ${result.message}`);\n checkCancelled();\n }\n return result;\n}\n","// Reuse the loaded snapshots for the initial patch and later context expansion.\n// Recorded argv retains the reviewer's original symbolic revisions and options.\nimport type { ReviewSourceIdentity } from './types';\nimport { parseGitDiffArgs } from './git-diff-args';\nimport { describeGitDiffSides } from './source-identity';\n\nexport class UnresolvedComparisonError extends Error {\n constructor(reason: string) {\n super(`Cannot pin git diff comparison: ${reason}`);\n this.name = 'UnresolvedComparisonError';\n }\n}\n\n/**\n * Execution argv for a resolved comparison. Keeps flags and pathspecs, replaces revision\n * positionals with SHAs and removes --merge-base, whose result is already the old commit.\n * Unknown comparison shapes retain their argv so the parser can diagnose them. A supported\n * revision that failed to resolve refuses execution instead of racing its symbolic ref.\n */\nexport function pinnedGitDiffArgs(identity: ReviewSourceIdentity): string[] {\n const argv = identity.gitDiffArgv;\n const described = describeGitDiffSides(argv);\n if (described.oldSide.kind === 'unknown' || described.newSide.kind === 'unknown')\n return [...argv];\n for (const side of [identity.oldSide, identity.newSide]) {\n if (side.kind === 'unknown') throw new UnresolvedComparisonError(side.reason);\n }\n const parsed = parseGitDiffArgs(argv);\n const reverse = parsed.options.some(option => option.name === '-R');\n const sides = reverse\n ? [identity.newSide, identity.oldSide]\n : [identity.oldSide, identity.newSide];\n const revisions = sides.flatMap(side => {\n if (side.kind === 'commit') return [side.sha];\n if (side.kind === 'none') {\n if (!identity.emptyTreeSha)\n throw new UnresolvedComparisonError('the empty tree could not be identified');\n return [identity.emptyTreeSha];\n }\n return [];\n });\n const end = parsed.separatorIndex ?? argv.length;\n const dropped = new Set(parsed.positionalIndices.filter(index => index < end));\n for (const option of parsed.options) {\n if (option.name === '--merge-base') dropped.add(option.index);\n }\n return [\n ...argv.slice(0, end).filter((_, index) => !dropped.has(index)),\n ...revisions,\n ...argv.slice(end),\n ];\n}\n","import type { SourceReadFsLayer } from './scan-fs';\nimport type { LocalSourcePaths } from './source-identity';\nimport type { DiffFile, ReviewSourceIdentity } from './types';\nimport {\n runGitDiffAsync,\n getRepoRootAsync,\n listUntrackedFilesAsync,\n type GitExecutionOptions,\n isOutputLimitError,\n} from './git';\nimport { parseDiffWithDiagnosticsAsync } from './diff-parser-async';\nimport { findUnsupportedGitDiffOptions } from './git-diff-args';\nimport { loadSyntheticFilesAsync } from './synthetic-diff';\nimport { formatBytes, resolveSourceBudgets, type SourceBudgets } from './input-budgets';\nimport { isCommandCancelled } from './forge-provider';\nimport { checkLoadingCancelled } from './local-loading-lifetime';\nimport { pinnedGitDiffArgs } from './pinned-comparison';\nimport { resolveGitSourceIdentity } from './source-identity';\n\nexport interface LoadGitDiffOptions extends GitExecutionOptions {\n /** Supplied bounded source reads, including untracked additions. */\n readFs?: SourceReadFsLayer;\n sourcePaths?: LocalSourcePaths;\n /**\n * Include untracked working-tree files as synthetic additions. Defaults\n * to true (local git mode). Remote mode passes false: a base...head diff\n * of a PR/MR must never pick up unrelated local untracked files.\n */\n includeUntracked?: boolean;\n budgets?: Partial<SourceBudgets>;\n /** Effective application ignore filter, in the same namespace as tracked diff paths. */\n shouldKeep?: (path: string) => boolean;\n}\n\nexport interface LoadGitDiffResult {\n files: DiffFile[];\n repository: string;\n /** What the diff compared; previews and line counts read this snapshot, not the working tree. */\n identity: ReviewSourceIdentity;\n /** What could not be shown faithfully; front ends show these instead of \"no changes\". */\n diagnostics: string[];\n}\n\n/** The path a diff entry is keyed by throughout the review. */\nfunction entryPath(file: DiffFile): string {\n return file.newPath || file.oldPath;\n}\n\n/**\n * Tracked wins on a path collision (after `git rm --cached f`, `f` is both a\n * deletion and untracked); two entries would share React keys and comment state.\n */\nexport function dedupeUntrackedByPath(tracked: DiffFile[], untracked: DiffFile[]): DiffFile[] {\n const seen = new Set(tracked.map(entryPath));\n return untracked.filter(file => !seen.has(entryPath(file)));\n}\n\nexport async function loadGitDiffWithUntracked(\n gitDiffArgs: string[],\n cwd?: string,\n options: LoadGitDiffOptions = {}\n): Promise<LoadGitDiffResult> {\n checkLoadingCancelled(options.signal);\n const { includeUntracked = true } = options;\n const budgets = resolveSourceBudgets(options.budgets);\n const repository = await getRepoRootAsync(cwd, options);\n // Resolve once, then execute against those same commits if a symbolic ref moves.\n const identity = await resolveGitSourceIdentity({\n repository,\n gitDiffArgv: gitDiffArgs,\n invocationCwd: cwd ?? process.cwd(),\n signal: options.signal,\n runner: options.runner,\n timeoutMs: options.timeoutMs,\n sourcePaths: options.sourcePaths ?? options.readFs,\n });\n\n // Such output would parse as an empty review; name the flag and skip git.\n const unsupported = findUnsupportedGitDiffOptions(gitDiffArgs);\n if (unsupported.length > 0) {\n return {\n files: [],\n repository,\n identity,\n diagnostics: unsupported.map(\n flag =>\n `Unsupported git diff option ${flag}: self-review reads patch output only; ` +\n 'remove it to review the changes.'\n ),\n };\n }\n\n let rawDiff: string;\n try {\n rawDiff = await runGitDiffAsync(\n pinnedGitDiffArgs(identity),\n cwd,\n budgets.maxGitDiffOutputBytes,\n options\n );\n } catch (error) {\n if (!isOutputLimitError(error)) throw error;\n // A truncated diff must never be parsed as the review.\n return {\n files: [],\n repository,\n identity,\n diagnostics: [\n `git diff produced more than ${formatBytes(budgets.maxGitDiffOutputBytes)} of output, ` +\n 'the most self-review reads from one diff, so nothing was loaded. Narrow the ' +\n 'diff with a pathspec (for example `-- src/`) or a smaller revision range.',\n ],\n };\n }\n checkLoadingCancelled(options.signal);\n const { files, diagnostics } = await parseDiffWithDiagnosticsAsync(rawDiff, {\n signal: options.signal,\n budgets,\n });\n checkLoadingCancelled(options.signal);\n\n if (!includeUntracked) {\n return { files, repository, identity, diagnostics };\n }\n\n // Enumerate and read against the physical root, then name entries exactly like the\n // tracked patch. Filter before counting entries or spending synthetic read budgets.\n let listed: string[];\n try {\n listed = await listUntrackedFilesAsync(repository, options);\n } catch (error) {\n checkLoadingCancelled(options.signal);\n if (isCommandCancelled(error) && error.reason === 'aborted') throw error;\n diagnostics.push(\n `Untracked files could not be listed; only tracked changes are shown: ${error instanceof Error ? error.message : String(error)}`\n );\n return { files, repository, identity, diagnostics };\n }\n checkLoadingCancelled(options.signal);\n const prefix = identity.pathPrefix === '' ? '' : `${identity.pathPrefix}/`;\n const reviewPath = (rootPath: string) => rootPath.slice(prefix.length);\n const trackedPaths = new Set(files.map(entryPath));\n const untrackedPaths = listed.filter(\n filePath =>\n filePath.startsWith(prefix) &&\n (options.shouldKeep?.(reviewPath(filePath)) ?? true) &&\n !trackedPaths.has(reviewPath(filePath))\n );\n if (untrackedPaths.length > budgets.maxEntries) {\n diagnostics.push(\n `${untrackedPaths.length.toLocaleString('en-US')} untracked files exceed the ` +\n `${budgets.maxEntries.toLocaleString('en-US')}-file limit, so none of them were ` +\n 'loaded; only tracked changes are shown. Ignore build output and dependency ' +\n 'folders in .gitignore, or stage the files you mean to review.'\n );\n return { files, repository, identity, diagnostics };\n }\n\n let allFiles = files;\n if (untrackedPaths.length > 0) {\n if (options.sourcePaths && !options.readFs)\n throw new TypeError('The supplied git source needs a SourceReadFsLayer for untracked reads');\n const untracked = await loadSyntheticFilesAsync(untrackedPaths, repository, {\n followSymlinks: false,\n readFs: options.readFs,\n budgets: {\n ...budgets,\n maxDiffFiles: Math.max(0, budgets.maxDiffFiles - files.length),\n maxDiffHunks: Math.max(\n 0,\n budgets.maxDiffHunks - files.reduce((n, f) => n + f.hunks.length, 0)\n ),\n maxTotalLines: Math.max(\n 0,\n budgets.maxTotalLines -\n files.reduce((n, f) => n + f.hunks.reduce((m, h) => m + h.lines.length, 0), 0)\n ),\n },\n signal: options.signal,\n });\n diagnostics.push(...untracked.diagnostics);\n for (const file of untracked.files) {\n if (file.newPath) file.newPath = reviewPath(file.newPath);\n if (file.oldPath) file.oldPath = reviewPath(file.oldPath);\n }\n const untrackedFiles = dedupeUntrackedByPath(files, untracked.files);\n for (const file of untrackedFiles) {\n file.isUntracked = true;\n }\n // A normal working-tree comparison already reads synthetic additions from the\n // right place. Only store overrides when tracked files use another new side.\n if (untrackedFiles.length > 0 && identity.newSide.kind !== 'working-tree') {\n identity.fileSources = new Map(\n untrackedFiles.map(file => [\n entryPath(file),\n {\n oldSide: { kind: 'none' as const },\n newSide: { kind: 'working-tree' as const },\n },\n ])\n );\n }\n allFiles = [...files, ...untrackedFiles];\n }\n\n checkLoadingCancelled(options.signal);\n return { files: allFiles, repository, identity, diagnostics };\n}\n","// First-party git loading brackets mutable reads with bounded, read-only source evidence.\nimport path from 'node:path';\nimport type { SourceReadFsLayer } from './scan-fs';\nimport { nodeScanFsLayer } from './node-scan-fs';\nimport { captureIndex, verifyIndexCapture } from './index-capture';\nimport { executeGit, getRepoRootAsync } from './git';\nimport { loadGitDiffWithUntracked } from './git-diff-loader';\nimport type { LoadGitDiffOptions, LoadGitDiffResult } from './git-diff-loader';\nimport { describeGitDiffSides, rootRelativeReviewedPath } from './source-identity';\nimport { resolveSourceBudgets } from './input-budgets';\nimport { findUnsupportedGitDiffOptions } from './git-diff-args';\nimport { comparisonPaths } from './comparison-paths';\nimport { assertNoSymlinkAncestorsAsync, nodeReadFsLayer } from './safe-fs-read';\nimport type { BoundedAsyncReadFsLayer } from './safe-fs-read';\nimport { checkLoadingCancelled, loadingCheckpoint } from './local-loading-lifetime';\nimport {\n recordLoadedSnapshot,\n createLoadedReview,\n type LoadedReview,\n sourceStamp,\n sourceCapture,\n RELOAD_REVIEW,\n type PhysicalCapture,\n} from './loaded-snapshot';\n\n/** Exact stage-zero object names, with NUL-delimited literal paths (including tabs/newlines). */\nexport async function readIndexManifest(\n root: string,\n options: LoadGitDiffOptions = {},\n paths?: readonly string[]\n): Promise<Map<string, string>> {\n const budgets = resolveSourceBudgets(options.budgets);\n const manifest = new Map<string, string>();\n // Literal path batches bound argv size; unrelated index entries never spend capture budgets.\n const batches: string[][] = [];\n if (paths === undefined) batches.push([]);\n else {\n let batch: string[] = [];\n let bytes = 0;\n for (const filePath of paths) {\n const literal = `:(literal)${filePath}`;\n const length = Buffer.byteLength(literal) + 1;\n if (batch.length && (batch.length >= 64 || bytes + length > 16_384)) {\n batches.push(batch);\n batch = [];\n bytes = 0;\n }\n batch.push(literal);\n bytes += length;\n }\n if (batch.length) batches.push(batch);\n }\n let remaining = budgets.maxGitDiffOutputBytes;\n for (const batch of batches) {\n await loadingCheckpoint(options.signal);\n if (remaining <= 0) throw new Error('Index capture exceeds the byte budget');\n const text = await executeGit(\n ['ls-files', '--stage', '-z', '--', ...batch],\n root,\n options,\n remaining\n );\n remaining -= Buffer.byteLength(text);\n let start = 0;\n while (start < text.length) {\n await loadingCheckpoint(options.signal);\n const end = text.indexOf('\\0', start);\n if (end === -1) throw new Error('Invalid index manifest');\n const record = text.slice(start, end);\n const match = /^([0-7]{6}) ([0-9a-f]{40,64}) ([0-3])\\t([\\s\\S]*)$/.exec(record);\n if (!match) throw new Error('Invalid index manifest');\n if (match[3] === '0') manifest.set(match[4], match[2]);\n // Conflict paths still need physical drift checks, but have no stage-zero blob to read.\n else if (!manifest.has(match[4])) manifest.set(match[4], '');\n start = end + 1;\n }\n }\n return manifest;\n}\n\nexport async function inspectPhysicalSource(\n root: string,\n relative: string,\n readFs: BoundedAsyncReadFsLayer,\n signal?: AbortSignal\n): Promise<PhysicalCapture | undefined> {\n try {\n await assertNoSymlinkAncestorsAsync(root, relative, readFs, signal);\n checkLoadingCancelled(signal);\n const target = path.join(root, relative);\n const stats = await readFs.lstat(target);\n checkLoadingCancelled(signal);\n if (!stats.isFile() || (await readFs.realpath(target)) !== target) return undefined;\n return { target, stamp: sourceStamp(stats), readFs };\n } catch {\n checkLoadingCancelled(signal);\n return undefined;\n }\n}\n\n/** Source loading and later physical reads must belong to the same supplied filesystem. */\nexport interface GitSnapshotDependencies {\n readonly readFs: BoundedAsyncReadFsLayer;\n /** Needed when the standard diff loader also reads untracked source/link content. */\n readonly sourceFs?: SourceReadFsLayer;\n loadDiff: typeof loadGitDiffWithUntracked;\n}\n\nconst nodeSnapshotDependencies: GitSnapshotDependencies = {\n readFs: nodeReadFsLayer,\n sourceFs: nodeScanFsLayer,\n loadDiff: loadGitDiffWithUntracked,\n};\n\n/**\n * Stronger loader for hosts; the original loadGitDiffWithUntracked call form stays live for legacy\n * embedders. Mutable paths are inspected before diff execution, never first captured afterward.\n */\nexport async function loadGitReviewSnapshot(\n args: string[],\n cwd?: string,\n options: LoadGitDiffOptions & {\n snapshotRunner?: import('./command-runner').BufferedCommandRunner;\n } = {},\n dependencies: GitSnapshotDependencies = nodeSnapshotDependencies\n): Promise<LoadGitDiffResult & { loadedReview?: LoadedReview }> {\n const readFs = options.readFs ?? dependencies.readFs;\n const sourceFs = options.readFs ?? dependencies.sourceFs;\n const loadOptions = { ...options, readFs: sourceFs, sourcePaths: options.sourcePaths ?? readFs };\n if (findUnsupportedGitDiffOptions(args).length > 0)\n return dependencies.loadDiff(args, cwd, loadOptions);\n const root = await getRepoRootAsync(cwd, options);\n const sides = describeGitDiffSides(args);\n const usesIndex = [sides.oldSide, sides.newSide].some(side => side.kind === 'index');\n const usesWorking = [sides.oldSide, sides.newSide].some(side => side.kind === 'working-tree');\n const indexCapture = usesIndex ? await captureIndex(root, readFs, options) : undefined;\n const selected =\n usesIndex || usesWorking\n ? await comparisonPaths(args, cwd ?? root, options)\n : new Set<string>();\n const before =\n usesIndex || usesWorking\n ? await readIndexManifest(root, options, [...selected])\n : new Map<string, string>();\n const physical = new Map<string, PhysicalCapture>();\n if (usesWorking) {\n for (const filePath of before.keys()) {\n await loadingCheckpoint(options.signal);\n const capture = await inspectPhysicalSource(root, filePath, readFs, options.signal);\n if (capture) physical.set(filePath, capture);\n }\n }\n const result = await dependencies.loadDiff(args, cwd, loadOptions);\n const after = usesIndex ? await readIndexManifest(root, options, [...selected]) : before;\n if (indexCapture && !(await verifyIndexCapture(indexCapture, options.signal)))\n throw new Error(RELOAD_REVIEW);\n const admitted = new Map<string, PhysicalCapture>();\n const index = new Map<string, string>();\n for (const file of result.files) {\n await loadingCheckpoint(options.signal);\n for (const filePath of new Set([file.oldPath, file.newPath].filter(Boolean))) {\n const relative = rootRelativeReviewedPath(result.identity, filePath);\n if ((usesIndex || usesWorking) && !file.isUntracked && !selected.has(relative))\n throw new Error(RELOAD_REVIEW);\n if (usesIndex && before.get(relative) !== after.get(relative)) throw new Error(RELOAD_REVIEW);\n const oid = before.get(relative);\n if (oid) index.set(filePath, oid);\n if (file.isUntracked) {\n const capture = sourceCapture(file);\n if (capture) admitted.set(filePath, capture);\n } else if (usesWorking) {\n const capture = physical.get(relative);\n const current = await inspectPhysicalSource(root, relative, readFs, options.signal);\n if (capture?.stamp !== current?.stamp) throw new Error(RELOAD_REVIEW);\n if (capture) admitted.set(filePath, capture);\n }\n }\n }\n const snapshot = recordLoadedSnapshot(\n result.identity,\n admitted,\n index,\n options,\n options.snapshotRunner,\n indexCapture\n );\n return { ...result, loadedReview: createLoadedReview(result.identity, result.files, snapshot) };\n}\n","// Index replacement evidence detects restage/restore cycles even when the final OIDs match.\nimport path from 'node:path';\nimport { executeGit, stripTrailingNewline, type GitExecutionOptions } from './git';\nimport { assertNoSymlinkAncestorsAsync } from './safe-fs-read';\nimport type { BoundedAsyncReadFsLayer } from './safe-fs-read';\nimport { errnoOf } from './safe-fs-policy';\nimport { checkLoadingCancelled } from './local-loading-lifetime';\nimport { sourceStamp, RELOAD_REVIEW, type IndexCapture } from './loaded-snapshot';\n\nasync function indexStamp(\n target: string,\n readFs: BoundedAsyncReadFsLayer,\n signal?: AbortSignal\n): Promise<string | null> {\n try {\n if (!path.isAbsolute(target)) throw new Error(RELOAD_REVIEW);\n const root = path.parse(target).root;\n await assertNoSymlinkAncestorsAsync(root, path.relative(root, target), readFs, signal);\n const stats = await readFs.lstat(target);\n checkLoadingCancelled(signal);\n if (!stats.isFile() || (await readFs.realpath(target)) !== target)\n throw new Error(RELOAD_REVIEW);\n return sourceStamp(stats);\n } catch (error) {\n checkLoadingCancelled(signal);\n // Unborn repositories can legitimately have no index until their first staged file.\n if (errnoOf(error) === 'ENOENT') return null;\n throw error;\n }\n}\n\nexport async function captureIndex(\n root: string,\n readFs: BoundedAsyncReadFsLayer,\n options: GitExecutionOptions\n): Promise<IndexCapture> {\n const target = stripTrailingNewline(\n await executeGit(['rev-parse', '--path-format=absolute', '--git-path', 'index'], root, options)\n );\n return { target, readFs, stamp: await indexStamp(target, readFs, options.signal) };\n}\n\nexport async function verifyIndexCapture(\n capture: IndexCapture,\n signal?: AbortSignal\n): Promise<boolean> {\n return (await indexStamp(capture.target, capture.readFs, signal)) === capture.stamp;\n}\n","// Read-only discovery for metadata capture. Preserve Git's pathspec and rename interpretation.\nimport { executeGit, PARSER_COMPATIBLE_GIT_CONFIG, withParserCompatibleDiffArgs } from './git';\nimport type { LoadGitDiffOptions } from './git-diff-loader';\nimport { parseGitDiffArgs } from './git-argument-policy';\nimport { resolveSourceBudgets } from './input-budgets';\nimport { loadingCheckpoint } from './local-loading-lifetime';\n\nexport async function comparisonPaths(\n args: string[],\n cwd: string,\n options: LoadGitDiffOptions\n): Promise<Set<string>> {\n const normalized = withParserCompatibleDiffArgs(args);\n const boundary = parseGitDiffArgs(normalized).separatorIndex ?? normalized.length;\n const text = await executeGit(\n [\n '--no-optional-locks',\n ...PARSER_COMPATIBLE_GIT_CONFIG,\n 'diff',\n ...normalized.slice(0, boundary),\n '--name-status',\n '-z',\n '--no-relative',\n ...normalized.slice(boundary),\n ],\n cwd,\n { ...options, timeoutMs: options.timeoutMs ?? 30_000 },\n resolveSourceBudgets(options.budgets).maxGitDiffOutputBytes\n );\n const fields = text === '' ? [] : text.split('\\0');\n if (fields.length && fields.pop() !== '') throw new Error('Invalid comparison path list');\n const paths = new Set<string>();\n for (let index = 0; index < fields.length; ) {\n await loadingCheckpoint(options.signal);\n const status = fields[index++];\n if (!/^[ACDMRTUXB][0-9]*$/.test(status)) throw new Error('Invalid comparison path status');\n const count = status.startsWith('R') || status.startsWith('C') ? 2 : 1;\n for (let part = 0; part < count; part++) {\n const filePath = fields[index++];\n if (!filePath) throw new Error('Missing comparison path');\n paths.add(filePath);\n }\n }\n return paths;\n}\n","// Re-diff uses live git inputs, so verify both compared sides before and after execution.\nimport type { DiffFile, ReviewSourceIdentity } from './types';\nimport { rootRelativeReviewedPath } from './source-identity';\nimport { inspectPhysicalSource, readIndexManifest } from './loaded-git-review';\nimport {\n identityStamp,\n loadedSnapshot,\n loadedReviewState,\n type LoadedReview,\n} from './loaded-snapshot';\nimport { checkLoadingCancelled } from './local-loading-lifetime';\nimport { verifyIndexCapture } from './index-capture';\n\n/** Legacy injected identities retain their documented live-read behavior. */\nexport async function verifyLoadedComparison(\n identity: ReviewSourceIdentity,\n file: DiffFile,\n signal?: AbortSignal,\n loadedReview?: LoadedReview | null\n): Promise<boolean> {\n const explicit = loadedReview ? loadedReviewState(loadedReview) : undefined;\n if (explicit && explicit.identity !== identity) return false;\n const snapshot = explicit?.snapshot ?? loadedSnapshot(identity);\n if (!snapshot) return true;\n if (snapshot.identityStamp !== identityStamp(identity)) return false;\n const sides = identity.fileSources?.get(file.newPath || file.oldPath) ?? identity;\n const paths = [\n { filePath: file.oldPath, side: sides.oldSide },\n { filePath: file.newPath, side: sides.newSide },\n ].filter(entry => entry.filePath !== '');\n try {\n const index = paths.some(entry => entry.side.kind === 'index')\n ? await readIndexManifest(\n identity.sourceRoot,\n { ...snapshot.gitOptions, signal },\n paths.map(entry => rootRelativeReviewedPath(identity, entry.filePath))\n )\n : null;\n if (snapshot.indexCapture && !(await verifyIndexCapture(snapshot.indexCapture, signal)))\n return false;\n for (const { filePath, side } of paths) {\n const relative = rootRelativeReviewedPath(identity, filePath);\n if (\n side.kind === 'index' &&\n (index?.get(relative) || undefined) !== snapshot.index.get(filePath)\n )\n return false;\n if (side.kind === 'working-tree' || side.kind === 'directory' || side.kind === 'file') {\n const capture = snapshot.physical.get(filePath);\n if (!capture) return false;\n const current = await inspectPhysicalSource(\n identity.sourceRoot,\n relative,\n capture.readFs,\n signal\n );\n if (current?.stamp !== capture.stamp) return false;\n }\n }\n return snapshot.identityStamp === identityStamp(identity);\n } catch {\n checkLoadingCancelled(signal);\n return false;\n }\n}\n","// Re-diff preparation/execution and guarded merging into the same committed review.\nimport { CommandCancelledError, isCommandCancelled } from './forge-provider';\nimport type { GitExecutionOptions } from './git';\nimport type { DiffFile, DiffHunk, ExpandContextRequest, ReviewSourceIdentity } from './types';\nimport type { ReviewSession } from './review-session';\nimport { singleFileRediffArgs } from './git-diff-args';\nimport { pinnedGitDiffArgs } from './pinned-comparison';\nimport { runGitDiffAsync } from './git';\nimport { parseDiffWithDiagnosticsAsync } from './diff-parser-async';\nimport { loadingCheckpoint } from './local-loading-lifetime';\nimport {\n MAX_GIT_DIFF_OUTPUT_BYTES,\n resolveSourceBudgets,\n type SourceBudgets,\n} from './input-budgets';\nimport { readReviewedContent } from './snapshot-reader';\nimport type { ReviewedSnapshot } from './snapshot-reader';\nimport { rootRelativeReviewedPath } from './source-identity';\nimport { loadedSnapshot, loadedReviewState, RELOAD_REVIEW } from './loaded-snapshot';\nimport { verifyLoadedComparison } from './snapshot-verification';\n\n/** The effects expansion needs; callers and tests can supply runners/readers without module mocks. */\nexport interface ContextExpansionDependencies {\n runDiff(args: string[], cwd: string, options?: GitExecutionOptions): Promise<string>;\n readContent: typeof readReviewedContent;\n report(message: string, error?: unknown): void;\n}\n\nconst nodeExpansionDependencies: ContextExpansionDependencies = {\n runDiff: (args, cwd, options) =>\n options && Object.keys(options).length > 0\n ? runGitDiffAsync(args, cwd, undefined, options)\n : runGitDiffAsync(args, cwd),\n readContent: readReviewedContent,\n report(message, error) {\n if (error === undefined) console.error(message);\n else console.error(message, error);\n },\n};\n\n/** Legacy read failures yield an unknown count; captured read failures abort expansion. */\nasync function countReviewedLines(\n session: ReviewedSnapshot,\n file: DiffFile,\n dependencies: ContextExpansionDependencies,\n options: GitExecutionOptions\n): Promise<number | null> {\n const side = file.newPath ? 'new' : 'old';\n const filePath = side === 'new' ? file.newPath : file.oldPath;\n const result = await dependencies.readContent(session, filePath, side, {\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n maxBytes: MAX_GIT_DIFF_OUTPUT_BYTES,\n });\n if (!result.ok) {\n dependencies.report(`[review] Line count unavailable for ${filePath}: ${result.message}`);\n return session.loadedReview ||\n (session.sourceIdentity && loadedSnapshot(session.sourceIdentity))\n ? null\n : 0;\n }\n return countLines(result.content, options.signal);\n}\n\nasync function countLines(content: Buffer, signal?: AbortSignal): Promise<number> {\n let newlines = 0;\n for (let i = 0; i < content.length; i++) {\n if (i % (64 * 1024) === 0) await loadingCheckpoint(signal);\n if (content[i] === 0x0a) newlines++;\n }\n return content.length > 0 && content[content.length - 1] === 0x0a ? newlines : newlines + 1;\n}\n\n/**\n * Re-run the review's own git diff over one file with more context, via\n * {@link singleFileRediffArgs}. Git runs at the source root; a `--relative` review is\n * restated with the prefix resolved at load time, and the file's paths (both, for a\n * rename or copy, so git pairs them) are root-relative literal pathspecs. The entry\n * returned is the one matching the file's old and new paths, not git's first.\n *\n * Expanded hunks are written back to the session's diff data. Returns null when\n * there is no git diff or tracked file, git's output lacks the file, or git fails.\n */\nexport async function expandContext(\n session: Pick<ReviewSession, 'diffData' | 'sourceIdentity' | 'reviewedPaths' | 'loadedReview'>,\n request: ExpandContextRequest,\n dependencies: ContextExpansionDependencies = nodeExpansionDependencies,\n options: GitExecutionOptions & { budgets?: Partial<SourceBudgets> } = {}\n): Promise<{ hunks: DiffHunk[]; totalLines: number } | null> {\n const checkCancelled = () => {\n if (options.signal?.aborted)\n throw new CommandCancelledError('aborted', 'self-review', ['expand-context']);\n };\n checkCancelled();\n const diffData = session.diffData;\n const identity = session.sourceIdentity;\n if (!diffData || diffData.source.type !== 'git' || identity === null) {\n return null;\n }\n if (identity.mode !== 'git' && identity.mode !== 'remote') {\n return null;\n }\n if (!Number.isSafeInteger(request.contextLines) || request.contextLines < 0) {\n return null;\n }\n // Untracked files are synthetic additions git never compared.\n const target = diffData.files.find(\n f => !f.isUntracked && (f.newPath || f.oldPath) === request.filePath\n );\n if (!target) {\n return null;\n }\n\n if (target.omittedReason) {\n dependencies.report(`[review] Cannot expand ${request.filePath}: ${target.omittedReason}`);\n return null;\n }\n const replacesFile = (file: DiffFile) =>\n !file.omittedReason && file.oldPath === target.oldPath && file.newPath === target.newPath;\n const budgets = resolveSourceBudgets(options.budgets);\n let otherLines = 0;\n let otherHunks = 0;\n for (const file of diffData.files) {\n if (replacesFile(file)) continue;\n otherHunks += file.hunks.length;\n for (const hunk of file.hunks) otherLines += hunk.lines.length;\n }\n if (\n otherLines > budgets.maxTotalLines ||\n otherHunks > budgets.maxDiffHunks ||\n diffData.files.length > budgets.maxDiffFiles\n ) {\n dependencies.report(\n `[review] Cannot expand ${request.filePath}: review exceeds the aggregate representation budget`\n );\n return null;\n }\n\n // commitDiffData installs a fresh authorization set even when the payload/identity are reused.\n const reviewedPaths = session.reviewedPaths;\n const loadedReview = session.loadedReview;\n const snapshot: ReviewedSnapshot = { sourceIdentity: identity, reviewedPaths, loadedReview };\n const isCurrent = () =>\n session.reviewedPaths === reviewedPaths &&\n session.sourceIdentity === identity &&\n session.loadedReview === loadedReview;\n try {\n const verify = async () => {\n if (await verifyLoadedComparison(identity, target, options.signal, loadedReview)) return true;\n dependencies.report(`[review] Cannot expand ${request.filePath}: ${RELOAD_REVIEW}`);\n return false;\n };\n if (((loadedReview || loadedSnapshot(identity)) && !(await verify())) || !isCurrent())\n return null;\n const args = contextDiffArgs(identity, target, request.contextLines);\n const captured = loadedReview\n ? loadedReviewState(loadedReview).snapshot\n : loadedSnapshot(identity);\n // The source runner survives the load; its per-load abort signal does not.\n const { signal: _loadSignal, ...sourceEffects } = captured?.gitOptions ?? {};\n const rawDiff = await dependencies.runDiff(args, identity.sourceRoot, {\n ...sourceEffects,\n ...options,\n });\n checkCancelled();\n if (!isCurrent()) return null;\n const parsed = await parseDiffWithDiagnosticsAsync(rawDiff, {\n signal: options.signal,\n budgets: {\n ...budgets,\n maxTotalLines: budgets.maxTotalLines - otherLines,\n maxDiffHunks: budgets.maxDiffHunks - otherHunks,\n },\n });\n checkCancelled();\n if (!isCurrent()) return null;\n const expandedFile = parsed.files.find(\n f => f.oldPath === target.oldPath && f.newPath === target.newPath\n );\n if (expandedFile?.omittedReason) {\n dependencies.report(\n `[review] Cannot expand ${request.filePath}: ${expandedFile.omittedReason}`\n );\n return null;\n }\n if (!expandedFile) {\n dependencies.report(\n `[review] Expanded diff for ${request.filePath} did not contain the file`\n );\n return null;\n }\n\n // The reviewed side's length, for gap detection; zero keeps the bars visible.\n const totalLines = await countReviewedLines(snapshot, target, dependencies, options);\n checkCancelled();\n if (totalLines === null || !(await verify()) || !isCurrent() || !session.diffData) return null;\n\n let currentLines = 0;\n let currentHunks = 0;\n for (const file of session.diffData.files) {\n const replacement = replacesFile(file) ? expandedFile : file;\n currentHunks += replacement.hunks.length;\n for (const hunk of replacement.hunks) currentLines += hunk.lines.length;\n }\n if (currentLines > budgets.maxTotalLines || currentHunks > budgets.maxDiffHunks) {\n dependencies.report(\n `[review] Cannot expand ${request.filePath}: aggregate representation budget exceeded`\n );\n return null;\n }\n session.diffData = {\n ...session.diffData,\n files: session.diffData.files.map(f =>\n replacesFile(f) ? { ...f, hunks: expandedFile.hunks } : f\n ),\n };\n\n return { hunks: expandedFile.hunks, totalLines };\n } catch (error) {\n if (isCommandCancelled(error)) throw error;\n dependencies.report(`[review] Failed to expand context for ${request.filePath}:`, error);\n return null;\n }\n}\n\n/** Restate one file's comparison at the captured source root, with literal root-relative paths. */\nfunction contextDiffArgs(\n identity: ReviewSourceIdentity,\n target: DiffFile,\n contextLines: number\n): string[] {\n const rediff = singleFileRediffArgs(pinnedGitDiffArgs(identity));\n const prefix = identity.pathPrefix;\n const paths = [...new Set([target.oldPath, target.newPath].filter(p => p !== ''))];\n return [\n ...rediff.args,\n ...(prefix === '' ? [] : [`--relative=${prefix}`]),\n `-U${contextLines}`,\n '--',\n ...paths.map(p => `:(top,literal)${rootRelativeReviewedPath(identity, p)}`),\n ];\n}\n","// Prepare directory/file reviews without committing until the host accepts their payload size.\nimport { nodeScanFsLayer } from './node-scan-fs';\nimport { admitSyntheticSnapshot, type LoadedReview } from './loaded-snapshot';\nimport { isolatedReporter } from './effect-diagnostics';\nimport { checkLoadingCancelled } from './local-loading-lifetime';\nimport type { SourceScanOptions } from './directory-scanner';\nimport type { DiffLoadPayload, ReviewSourceIdentity, PayloadStats } from './types';\nimport type { ReviewSession } from './review-session';\nimport { commitDiffData, commitLoadedReview, preparePayload } from './review-session';\nimport { scanDirectory, scanFile } from './directory-scanner';\nimport { computePayloadStats, countTotalLines } from './payload-sizing';\nimport { resolveLocalSourceIdentityAsync } from './source-identity';\n\n/**\n * What a review start produced: the payload built from the scanned path, the\n * stats it was measured against (null when the session has no config, in which\n * case no thresholds apply), and whether those stats exceeded a threshold.\n *\n * The payload is deliberately *not* stored on the session: the caller may still\n * need to abandon it (a user declining a large review keeps the review they\n * were already looking at), so committing it is the caller's decision.\n */\nexport interface ReviewStartResult {\n payload: DiffLoadPayload;\n identity: ReviewSourceIdentity;\n /** Host-local evidence to pass to commitLoadedReview. Never put this on a wire payload. */\n loadedReview?: LoadedReview;\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: Pick<ReviewSession, 'config'>,\n directoryPath: string,\n options: SourceScanOptions = {}\n): Promise<ReviewStartResult> {\n checkLoadingCancelled(options.signal);\n const reportDiagnostic = isolatedReporter(options.reportDiagnostic);\n const scanFs = options.scanFs ?? nodeScanFsLayer;\n reportDiagnostic('[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 = (await scanFs.stat(directoryPath)).isFile();\n } catch {\n // Failed to stat — proceed as directory\n }\n\n checkLoadingCancelled(options.signal);\n\n // Scan diagnostics ride on the payload so a failed load never looks empty.\n const scan = isFile\n ? await scanFile(directoryPath, { ...options, reportDiagnostic })\n : await scanDirectory(directoryPath, session.config?.ignore ?? [], {\n ...options,\n reportDiagnostic,\n });\n checkLoadingCancelled(options.signal);\n const type = isFile ? 'file' : 'directory';\n const payload: DiffLoadPayload = {\n files: scan.files,\n source: { type, sourcePath: directoryPath },\n ...(scan.diagnostics.length > 0 ? { diagnostics: scan.diagnostics } : {}),\n };\n const identity = await resolveLocalSourceIdentityAsync(\n { type, sourcePath: directoryPath },\n scanFs,\n options.signal\n );\n checkLoadingCancelled(options.signal);\n const loadedReview = admitSyntheticSnapshot(identity, scan.files);\n\n // Large payload guard — skipped entirely when there is no config.\n if (!session.config) {\n return { payload, identity, loadedReview, stats: null, exceedsThresholds: false };\n }\n const stats = computePayloadStats(\n payload.files.length,\n countTotalLines(payload.files),\n session.config\n );\n return { payload, identity, loadedReview, 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: Pick<ReviewSession, 'diffData' | 'reviewedPaths' | 'sourceIdentity' | 'loadedReview'>,\n payload: DiffLoadPayload,\n identity: ReviewSourceIdentity | null,\n loadedReview: LoadedReview | undefined = undefined\n): DiffLoadPayload {\n if (loadedReview) commitLoadedReview(session, payload, loadedReview);\n else commitDiffData(session, payload, identity);\n return preparePayload(payload);\n}\n","// packages/core/src/startup-mode.ts\n// Startup mode detection: what the app should review, from the CLI args and the CWD.\n\nimport { statSync } from 'fs';\nimport { stat } from 'fs/promises';\nimport { execFileSync } from 'child_process';\nimport { repositoryEnvironment } from './command-runner';\nimport { executeGit, type GitExecutionOptions } from './git';\nimport { CommandCancelledError, isCommandCancelled } from './forge-provider';\nimport { resolve } from 'path';\nimport { classifyGitDiffArgs } from './git-diff-args';\n\nconst PROBE_TIMEOUT_MS = 10_000;\nconst PROBE_OUTPUT_BYTES = 1024 * 1024;\n\n/** Bounded compatibility path for callers that still need synchronous mode detection. */\nfunction probeSync(args: string[], cwd: string): boolean {\n try {\n execFileSync('git', args, {\n stdio: 'ignore',\n cwd,\n env: repositoryEnvironment(),\n timeout: PROBE_TIMEOUT_MS,\n killSignal: 'SIGKILL',\n maxBuffer: PROBE_OUTPUT_BYTES,\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/** Missing git and non-repositories retain the welcome/file fallback; interruption propagates. */\nasync function probeAsync(\n args: string[],\n cwd: string,\n options: GitExecutionOptions\n): Promise<boolean> {\n try {\n await executeGit(args, cwd, options, PROBE_OUTPUT_BYTES);\n return true;\n } catch (error) {\n if (isCommandCancelled(error)) throw error;\n checkCancellation(options, args);\n return false;\n }\n}\n\nfunction firstCandidate(gitDiffArgs: readonly string[], cwd: string) {\n const { positionalIndices } = classifyGitDiffArgs([...gitDiffArgs]);\n const positional = gitDiffArgs[positionalIndices[0]];\n return { positional, candidate: positional ? resolve(cwd, positional) : null };\n}\n\n/**\n * What a review starts from; `welcome` means nothing to review (desktop shows its picker, serve\n * refuses).\n */\nexport type StartupSource =\n | { mode: 'git' }\n | { mode: 'directory'; sourcePath: string }\n | { mode: 'file'; sourcePath: string }\n | { mode: 'welcome' };\n\n/**\n * The candidate is the first *positional* by the shared classifier, so `-S src/x.ts` never selects\n * a file.\n */\nexport function resolveStartupSource(\n gitDiffArgs: readonly string[],\n cwd: string = process.cwd()\n): StartupSource {\n const { positional: firstPositional, candidate } = firstCandidate(gitDiffArgs, cwd);\n\n // Tracked files go through git diff, others are scanned.\n if (candidate && firstPositional && isExisting(candidate, 'file')) {\n if (probeSync(['rev-parse', '--git-dir'], cwd)) {\n return probeSync(['ls-files', '--error-unmatch', '--', firstPositional], cwd)\n ? { mode: 'git' }\n : { mode: 'file', sourcePath: candidate };\n }\n return { mode: 'file', sourcePath: candidate };\n }\n\n if (probeSync(['rev-parse', '--git-dir'], cwd)) {\n return { mode: 'git' };\n }\n\n if (candidate && isExisting(candidate, 'directory')) {\n return { mode: 'directory', sourcePath: candidate };\n }\n\n return { mode: 'welcome' };\n}\n\nfunction isExisting(candidate: string, kind: 'file' | 'directory'): boolean {\n try {\n const stats = statSync(candidate);\n return kind === 'file' ? stats.isFile() : stats.isDirectory();\n } catch {\n return false;\n }\n}\n\n/** The mode alone; see {@link resolveStartupSource} for the source path. */\nexport function determineMode(gitDiffArgs: string[]): 'git' | 'directory' | 'file' | 'welcome' {\n return resolveStartupSource(gitDiffArgs).mode;\n}\n\n/** Classification metadata only; content loading uses its own filesystem roles. */\nexport interface StartupPathStats {\n isFile(): boolean;\n isDirectory(): boolean;\n}\n\n/** An authoritative path probe. A refusal or failure never retries against the native filesystem. */\nexport interface StartupPathProbe {\n stat(path: string): Promise<StartupPathStats | null>;\n}\n\nexport interface StartupSourceOptions extends GitExecutionOptions {\n sourceProbe?: StartupPathProbe;\n}\n\nfunction checkCancellation(\n options: GitExecutionOptions,\n args: string[] = ['rev-parse', '--git-dir']\n): void {\n if (options.signal?.aborted) throw new CommandCancelledError('aborted', 'git', args);\n}\n\nasync function candidateStat(candidate: string, options: StartupSourceOptions) {\n checkCancellation(options);\n try {\n const stats = options.sourceProbe\n ? await options.sourceProbe.stat(candidate)\n : await stat(candidate);\n checkCancellation(options);\n return stats;\n } catch (error) {\n if (isCommandCancelled(error)) throw error;\n checkCancellation(options);\n return null;\n }\n}\n\n/**\n * Nonblocking startup probes for hosts. Commands use the shared bounded runner and its\n * explicit-repository environment, including a deliberately selected local alternate index.\n * Abort and timeout reject with CommandCancelledError; ordinary probe failures keep the\n * synchronous API's file/directory/welcome fallback. timeoutMs bounds each command.\n * sourceProbe supplies classification metadata only and retains its receiver. Native stat and\n * supplied probes are joined before cancellation propagates; neither can be forcibly preempted.\n */\nexport async function resolveStartupSourceAsync(\n gitDiffArgs: readonly string[],\n cwd: string = process.cwd(),\n options: StartupSourceOptions = {}\n): Promise<StartupSource> {\n checkCancellation(options);\n const { positional, candidate } = firstCandidate(gitDiffArgs, cwd);\n const candidateStats = candidate ? await candidateStat(candidate, options) : null;\n const inRepository = await probeAsync(['rev-parse', '--git-dir'], cwd, options);\n if (candidate && positional && candidateStats?.isFile()) {\n const tracked =\n inRepository &&\n (await probeAsync(['ls-files', '--error-unmatch', '--', positional], cwd, options));\n return tracked ? { mode: 'git' } : { mode: 'file', sourcePath: candidate };\n }\n if (inRepository) return { mode: 'git' };\n if (candidate && candidateStats?.isDirectory()) {\n return { mode: 'directory', sourcePath: candidate };\n }\n return { mode: 'welcome' };\n}\n","// packages/core/src/staged-untracked.ts\n// Initial-config adjustment for staged-mode reviews.\n\nimport { parseGitDiffArgs } from './git-diff-args';\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 = parseGitDiffArgs(gitDiffArgs).options.some(\n option => option.name === '--staged' || option.name === '--cached'\n );\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","// Startup decisions that must come out the same in desktop and serve (audit R15); each host\n// keeps its own transport and dialogs.\n//\n// The command lines differ on purpose. Both take `--resume-from <file>` (or `=<file>`), stop\n// reading their own flags at `--`, and pass everything else to `git diff`. Beyond that:\n//\n// | Flag or input | Desktop (`self-review`) | Serve\n// (`self-review-serve`) |\n// | ------------------------------------- | ------------------------------------ |\n// ---------------------------------- |\n// | `--output <file>`, `-o`, `--output=` | no (save dialog changes the path) | yes (fixed for\n// the process) |\n// | `--help`/`-h`, `--version`/`-v` | yes | yes\n// |\n// | forge PR/MR URL as first positional | yes (remote GUI mode) | no (passed to\n// git) |\n// | `fetch-comments <url> [--all-threads]`| yes (headless subcommand, args[0]) | no\n// |\n// | leading Chromium switches | dropped (the launcher's, not git's) | n/a\n// |\n// | nothing to review (`welcome`) | directory picker | startup error\n// |\n\nimport { resolve } from 'path';\nimport { isolatedReporter } from './effect-diagnostics';\nimport type { LoadGitDiffOptions } from './git-diff-loader';\nimport type { BufferedCommandRunner } from './command-runner';\nimport { checkLoadingCancelled } from './local-loading-lifetime';\nimport type { AppConfig, DiffLoadPayload, ReviewSourceIdentity } from './types';\nimport type { ConfigValueOrigin, LoadedConfig } from './config';\nimport type { PublishReviewOptions, ReviewOutputTarget } from './review-publisher';\nimport type { ResolvedAttachmentLocation, AttachmentOrigins } from './attachment-origins';\nimport {\n findWriteCapableGitDiffOptions,\n formatGitDiffArgs,\n normalizeGitDiffArgs,\n tokenizeGitDiffArgs,\n} from './git-diff-args';\nimport { applyStagedUntrackedDefault } from './staged-untracked';\nimport { loadGitReviewSnapshot, type GitSnapshotDependencies } from './loaded-git-review';\nimport { admitSyntheticSnapshot, restrictLoadedReview, type LoadedReview } from './loaded-snapshot';\nimport { createIgnoreFilter } from './ignore-filter';\nimport { scanDirectory, scanFile } from './directory-scanner';\nimport { resolveLocalSourceIdentityAsync } from './source-identity';\nimport { nodeScanFsLayer } from './node-scan-fs';\nimport type { ScanFsLayer } from './scan-fs';\nimport type { StartupSource } from './startup-mode';\nimport { parseReviewXml } from './xml-parser';\nimport type { ParsedReview, ReviewXmlReader } from './xml-parser';\nimport { recordResumedAttachments } from './review-handlers';\nimport type { ReviewSession } from './review-handlers';\n\n/**\n * A CLI path or the reviewer's user-level `output-file` is explicit and may point anywhere.\n * Project `output-file` or the default is inherited and contained under `cwd`, since a\n * repository could otherwise redirect the save (audit A5).\n */\nexport function resolveOutputTarget(\n explicitPath: string | null,\n loaded: LoadedConfig,\n cwd: string\n): ReviewOutputTarget {\n if (explicitPath !== null) {\n return { path: resolve(cwd, explicitPath), origin: 'explicit' };\n }\n const path = resolve(cwd, loaded.config.outputFile);\n if (loaded.provenance.outputFile === 'user') {\n return { path, origin: 'explicit' };\n }\n return { path, origin: 'inherited', baseDir: cwd };\n}\n\nexport function publishOptionsFor(\n target: ReviewOutputTarget,\n attachmentOrigins?: AttachmentOrigins\n): PublishReviewOptions {\n return target.origin === 'explicit'\n ? { outputOrigin: 'explicit', attachmentOrigins }\n : { outputOrigin: 'inherited', baseDir: target.baseDir, attachmentOrigins };\n}\n\n/**\n * Project `default-diff-args` would make git write a file or run a program; thrown before any git\n * command.\n */\nexport class ConfiguredDiffArgsError extends Error {\n readonly options: readonly string[];\n readonly configPath: string;\n\n constructor(options: readonly string[], configPath: string) {\n super(\n `Refusing default-diff-args from ${configPath}: ${options.join(' ')} ` +\n 'would make git write a file or run an external program. A committed project ' +\n 'configuration may not supply such options; pass them on the command line instead.'\n );\n this.name = 'ConfiguredDiffArgsError';\n this.options = [...options];\n this.configPath = configPath;\n }\n}\n\nexport interface ResolvedDiffArgs {\n gitDiffArgs: string[];\n origin: 'cli' | ConfigValueOrigin;\n config: AppConfig;\n}\n\n/**\n * The CLI's arguments, else `default-diff-args` split with shell quoting. Project-supplied\n * ones are refused with {@link ConfiguredDiffArgsError} if write-capable; the\n * reviewer's own are not.\n */\nexport function resolveStartupDiffArgs(\n cliGitDiffArgs: readonly string[],\n loaded: LoadedConfig,\n cwd: string\n): ResolvedDiffArgs {\n let gitDiffArgs = [...cliGitDiffArgs];\n let origin: ResolvedDiffArgs['origin'] = 'cli';\n if (gitDiffArgs.length === 0 && loaded.config.defaultDiffArgs) {\n gitDiffArgs = tokenizeGitDiffArgs(loaded.config.defaultDiffArgs);\n origin = loaded.provenance.defaultDiffArgs;\n if (origin === 'project') {\n const offending = findWriteCapableGitDiffOptions(gitDiffArgs);\n if (offending.length > 0) {\n const source = loaded.sources.find(s => s.origin === 'project');\n throw new ConfiguredDiffArgsError(offending, source?.path ?? '.self-review.yaml');\n }\n }\n }\n gitDiffArgs = normalizeGitDiffArgs(gitDiffArgs, cwd);\n return {\n gitDiffArgs,\n origin,\n config: applyStagedUntrackedDefault(loaded.config, gitDiffArgs),\n };\n}\n\nexport interface LoadedLocalReview {\n payload: DiffLoadPayload;\n identity: ReviewSourceIdentity | null;\n /** Host-local capture; optional so original injected loaders remain source compatible. */\n loadedReview?: LoadedReview | null;\n}\n\n/** Local source effects. A supplied scan owns paths, enumeration and bounded reads together. */\nexport interface LocalReviewDependencies {\n scanFs?: ScanFsLayer;\n gitSnapshot?: GitSnapshotDependencies;\n}\n\nexport interface LocalReviewLoadOptions extends LoadGitDiffOptions {\n /** Binary blob runner belonging to a supplied Git source. */\n snapshotRunner?: BufferedCommandRunner;\n}\n\n/**\n * Diagnostics ride on the payload and go to `log`, so a failed load never reads as empty. A welcome\n * source yields no identity.\n */\nexport async function loadLocalReview(\n source: StartupSource,\n gitDiffArgs: readonly string[],\n config: Pick<AppConfig, 'ignore'>,\n cwd: string,\n log: (message: string) => void,\n options: LocalReviewLoadOptions = {},\n dependencies: LocalReviewDependencies = {}\n): Promise<LoadedLocalReview> {\n log = isolatedReporter(log);\n const checkCancelled = () => checkLoadingCancelled(options.signal);\n checkCancelled();\n if (source.mode === 'git') {\n const shouldKeep = createIgnoreFilter(config.ignore);\n const { files, repository, diagnostics, identity, loadedReview } = await loadGitReviewSnapshot(\n [...gitDiffArgs],\n cwd,\n { ...options, shouldKeep },\n dependencies.gitSnapshot\n );\n checkCancelled();\n for (const diagnostic of diagnostics) log(`Diff diagnostic: ${diagnostic}`);\n checkCancelled();\n const keptFiles = files.filter(f => shouldKeep(f.newPath || f.oldPath));\n return {\n payload: {\n files: keptFiles,\n source: {\n type: 'git',\n // Quoted so the argv is recoverable exactly from the document's git-diff-args.\n gitDiffArgs: formatGitDiffArgs([...gitDiffArgs]),\n repository,\n },\n ...(diagnostics.length > 0 ? { diagnostics } : {}),\n },\n identity,\n loadedReview: loadedReview ? restrictLoadedReview(loadedReview, keptFiles) : undefined,\n };\n }\n\n if (source.mode === 'file' || source.mode === 'directory') {\n const scanFs = dependencies.scanFs ?? nodeScanFsLayer;\n const scanOptions = {\n scanFs,\n budgets: options.budgets,\n signal: options.signal,\n reportDiagnostic: log,\n };\n const scan =\n source.mode === 'file'\n ? await scanFile(source.sourcePath, scanOptions)\n : await scanDirectory(source.sourcePath, config.ignore, scanOptions);\n checkCancelled();\n for (const diagnostic of scan.diagnostics) log(`Diff diagnostic: ${diagnostic}`);\n checkCancelled();\n const identity = await resolveLocalSourceIdentityAsync(\n {\n type: source.mode,\n sourcePath: source.sourcePath,\n invocationCwd: dependencies.scanFs ? cwd : undefined,\n },\n scanFs,\n options.signal\n );\n checkCancelled();\n const loadedReview = admitSyntheticSnapshot(identity, scan.files);\n return {\n payload: {\n files: scan.files,\n source: { type: source.mode, sourcePath: source.sourcePath },\n ...(scan.diagnostics.length > 0 ? { diagnostics: scan.diagnostics } : {}),\n },\n identity,\n loadedReview,\n };\n }\n\n return { payload: { files: [], source: { type: 'welcome' } }, identity: null };\n}\n\n/**\n * Throws `ReviewXmlError` for an unreadable document. Returns it for what the host still needs (the\n * remote head, for drift).\n */\nexport interface ResumeDocumentOptions extends ResolvedAttachmentLocation {\n reader?: ReviewXmlReader;\n signal?: AbortSignal;\n}\n\nexport function loadResumeDocument(\n session: ReviewSession,\n resumePath: string,\n options: ResumeDocumentOptions\n): ParsedReview;\nexport function loadResumeDocument(session: ReviewSession, resumePath: string): ParsedReview;\nexport function loadResumeDocument(\n session: ReviewSession,\n resumePath: string,\n options: ResumeDocumentOptions | undefined = undefined\n): ParsedReview {\n options?.signal?.throwIfAborted();\n let parsed: ParsedReview;\n try {\n parsed = parseReviewXml(resumePath, options);\n } catch (error) {\n options?.signal?.throwIfAborted();\n throw error;\n }\n return options === undefined\n ? adoptResumeDocument(session, parsed, resumePath)\n : adoptResumeDocument(session, parsed, resumePath, options);\n}\n\n/** Adopt an already parsed document, retaining the same attachment provenance as sync loading. */\nexport function adoptResumeDocument(\n session: ReviewSession,\n parsed: ParsedReview,\n resumePath: string,\n options: ResolvedAttachmentLocation & { signal?: AbortSignal }\n): ParsedReview;\nexport function adoptResumeDocument(\n session: ReviewSession,\n parsed: ParsedReview,\n resumePath: string\n): ParsedReview;\nexport function adoptResumeDocument(\n session: ReviewSession,\n parsed: ParsedReview,\n resumePath: string,\n options: (ResolvedAttachmentLocation & { signal?: AbortSignal }) | undefined = undefined\n): ParsedReview {\n options?.signal?.throwIfAborted();\n const attachments = { attachmentOrigins: session.attachmentOrigins };\n const attachmentDiagnostics =\n options === undefined\n ? recordResumedAttachments(attachments, parsed.comments, resumePath)\n : recordResumedAttachments(attachments, parsed.comments, resumePath, options);\n options?.signal?.throwIfAborted();\n session.attachmentOrigins = attachments.attachmentOrigins;\n session.resumeComments = parsed.comments;\n session.resumeViewedFiles = parsed.viewedFiles;\n session.resumeImportDiagnostics = [...parsed.importDiagnostics, ...attachmentDiagnostics];\n return parsed;\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. Ordinary guide failures resolve to null; cancellation through an\n// explicitly supplied startup signal propagates to its owner.\n//\n// Note on startup cost: loadGuide IS awaited before window creation\n// (main.ts Phase 5b), deliberately — `guide:load` piggybacks on the\n// DIFF_REQUEST handler, so the payload must be cached via setGuideData\n// before the renderer's first request arrives. When a guide exists, the\n// xmllint-wasm init and validation delay window paint by a few hundred ms;\n// when none exists the cost is a single failed open.\n//\n// Discovery is one-shot: the guide is resolved from the startup output\n// path. Changing the output path at runtime does not re-discover.\n\nimport { extname, resolve } from 'path';\nimport { readFileWithinBudget } from './bounded-read';\nimport type { AsyncBoundedReadOptions, BoundedReadResult } from './bounded-read';\nimport { parseGuideXml, reconcileGuide } from './guide-parser';\nimport { formatBytes, MAX_GUIDE_BYTES } from './input-budgets';\nimport { AppConfig, GuideLoadPayload } from './types';\nimport type { DiagnosticReporter } from './diagnostics';\nimport { isolatedReporter } from './effect-diagnostics';\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(\n outputPath: string,\n config: Pick<AppConfig, 'guideFile'>,\n cwd?: string\n): string {\n if (config.guideFile) {\n return resolve(cwd ?? process.cwd(), config.guideFile);\n }\n return deriveGuidePath(outputPath);\n}\n\n/**\n * Owns bounded guide reads, including regular-file checks, growth detection and handle cleanup.\n * Must reject filesystem errors with Node-style errno codes and settle after cleanup on abort.\n * Methods retain their receiver. A supplied reader is authoritative; native I/O is never retried.\n */\nexport interface BoundedGuideReader {\n read(\n path: string,\n maxBytes: number,\n options?: AsyncBoundedReadOptions\n ): Promise<BoundedReadResult>;\n}\n\nconst nativeGuideReader: BoundedGuideReader = { read: readFileWithinBudget };\n\nexport interface LoadGuideOptions {\n /** Defaults to the native bounded reader. The caller owns the reader; it owns opened handles. */\n reader?: BoundedGuideReader;\n /** Resolution directory for a relative guide-file. Defaults to process.cwd(). */\n cwd?: string;\n /** Defaults to stderr; missing guides are always silent. */\n reportDiagnostic?: DiagnosticReporter;\n /** Cancels bounded reading and refuses obsolete validation; shared validation is not preempted. */\n signal?: AbortSignal;\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 * `reportDiagnostic()` line (guide path + reason class). An explicitly supplied\n * startup signal propagates cancellation; ordinary guide failures never throw.\n */\nexport async function loadGuide(\n outputPath: string,\n config: Pick<AppConfig, 'guideFile'>,\n diffFilePaths: string[],\n options: LoadGuideOptions = {}\n): Promise<GuideLoadPayload | null> {\n const reportDiagnostic = isolatedReporter(options.reportDiagnostic);\n options.signal?.throwIfAborted();\n let guidePath: string;\n try {\n guidePath = resolveGuidePath(outputPath, config, options.cwd);\n } catch {\n options.signal?.throwIfAborted();\n return null;\n }\n\n try {\n // Refused on fstat size / non-regular file before any read, so a FIFO cannot block.\n let content: string;\n try {\n const reader = options.reader ?? nativeGuideReader;\n let read = await (options.signal\n ? reader.read(guidePath, MAX_GUIDE_BYTES, { signal: options.signal })\n : reader.read(guidePath, MAX_GUIDE_BYTES));\n options.signal?.throwIfAborted();\n // Enforce the parse budget even if a supplied reader under-enforces its allocation contract.\n if (read.kind === 'ok' && read.content.length > MAX_GUIDE_BYTES) {\n read = { kind: 'too-large', size: read.content.length };\n }\n if (read.kind === 'too-large') {\n reportDiagnostic(\n `[guide] Ignoring guide at ${guidePath}: too large (${formatBytes(read.size)}, ` +\n `over the ${formatBytes(MAX_GUIDE_BYTES)} guide budget)`\n );\n return null;\n }\n if (read.kind === 'not-regular') {\n reportDiagnostic(`[guide] Ignoring guide at ${guidePath}: unreadable (not a regular file)`);\n return null;\n }\n content = read.content.toString('utf-8');\n } catch (error) {\n options.signal?.throwIfAborted();\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 reportDiagnostic(\n `[guide] Ignoring guide at ${guidePath}: unreadable (${code ?? 'unknown error'})`\n );\n return null;\n }\n\n const result = await parseGuideXml(content);\n options.signal?.throwIfAborted();\n // Explicit comparison: with strictNullChecks off (see tsconfig),\n // truthiness alone does not narrow the discriminated union.\n if (result.ok === false) {\n reportDiagnostic(`[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 options.signal?.throwIfAborted();\n // Optional-guide failures remain nonfatal; cancellation belongs to startup.\n const message = error instanceof Error ? error.message : String(error);\n reportDiagnostic(`[guide] Ignoring guide at ${guidePath}: invalid (${message})`);\n return null;\n }\n}\n","// Pure merge, provenance and drift policy for remote feedback. No resource acquisition.\nimport type { ReviewComment, ReviewState, RemoteSessionInfo, RemoteDriftInfo } from './types';\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","// Runtime composition depends on pure definitions. URL/ref parsing never imports providers.\nimport { FORGE_DEFINITIONS } from './forge-definitions';\nimport { createGitHubProvider } from './github-provider';\nimport { createGitLabProvider } from './gitlab-provider';\nimport type { ForgeCommandRunner, ForgeName, ForgeProvider } from './forge-provider';\n\nconst factories = {\n gitlab: createGitLabProvider,\n github: createGitHubProvider,\n} satisfies Record<ForgeName, (runner: ForgeCommandRunner) => ForgeProvider>;\n\n// Derive the order and URL/ref metadata from the same definitions used by pure consumers.\nexport const FORGE_CATALOG = Object.fromEntries(\n (Object.keys(FORGE_DEFINITIONS) as ForgeName[]).map(forge => [\n forge,\n { ...FORGE_DEFINITIONS[forge], createProvider: factories[forge] },\n ])\n) as Readonly<\n Record<\n ForgeName,\n (typeof FORGE_DEFINITIONS)[ForgeName] & {\n createProvider: (runner: ForgeCommandRunner) => ForgeProvider;\n }\n >\n>;\n\nexport function createForgeProvider(forge: ForgeName, runner: ForgeCommandRunner): ForgeProvider {\n return FORGE_CATALOG[forge].createProvider(runner);\n}\n","// packages/core/src/remote-mode.ts\n// Remote PR/MR session bootstrap, shared by every front end.\n//\n// Binding rule: after materialization, remote mode *is* git mode. This\n// module turns a forge URL into the inputs the existing git-mode pipeline\n// already understands — a repo path and a `baseSha...headSha` range — plus\n// the fetched discussion threads and the remote provenance the serializer\n// records. `loadRemoteReview` then loads the diff and maps the threads against it,\n// so the app and `fetch-comments` produce the same comments. Every external effect\n// is injectable so unit tests never spawn git/gh/glab.\n//\n// Lifetime: one session, one `AbortSignal`. Aborting kills the command in flight\n// and rejects with `CommandCancelledError`; whatever the session acquired is\n// released first. A returned session hands its `cleanup` to the caller.\n\nimport {\n CommandCancelledError,\n ForgeCliUnavailableError,\n isCommandCancelled,\n parseForgeUrl,\n} from './forge-provider';\nimport type {\n ForgeCommandRunner,\n ForgeName,\n ForgeProvider,\n ForgeThread,\n ForgeUrl,\n} from './forge-provider';\nimport { createForgeProvider } from './forge-catalog';\nimport {\n DEFAULT_GIT_COMMAND_TIMEOUT_MS,\n defaultGitRunner,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n} from './materializer';\nimport type {\n ExistingClone,\n MaterializeMode,\n MaterializeOptions,\n MaterializeResult,\n} from './materializer';\nimport { mapThreadsToReviewComments } from './thread-mapper';\nimport { createIgnoreFilter } from './ignore-filter';\nimport type {\n DiffFile,\n DiffLoadPayload,\n RemoteSessionInfo,\n ReviewComment,\n ReviewSourceIdentity,\n} from './types';\nimport { loadGitDiffWithUntracked } from './git-diff-loader';\nimport { formatGitDiffArgs } from './git-diff-args';\nimport { canonicalSourcePath } from './source-identity';\nimport type { DiagnosticReporter } from './diagnostics';\nimport { isolatedReporter } from './effect-diagnostics';\n\n/**\n * The git-mode inputs plus the forge threads, before any diff is loaded (so nothing to anchor\n * suggestions to yet).\n */\nexport interface MaterializedRemoteSession {\n forgeUrl: ForgeUrl;\n /** Root of the materialized clone; the pipeline's repo path. */\n repoPath: string;\n /** Arguments for the existing git-diff machinery: `[base...head]`. */\n gitDiffArgs: string[];\n mode: MaterializeMode;\n /** Idempotent, never rejects; the receiver of the session must call it. */\n cleanup: () => Promise<void>;\n /** Legacy synchronous-first removal, for an exit handler that cannot await normal disposal. */\n cleanupForExit?: () => Promise<void>;\n /** Provenance + thread-sync status for payloads and the saved review. */\n remote: RemoteSessionInfo;\n /** Verbatim; empty when thread sync is unavailable. */\n fetchedThreads: ForgeThread[];\n}\n\n/** A session whose diff is loaded and whose threads are mapped against it. */\nexport interface RemoteSession extends MaterializedRemoteSession {\n /** Review-level threads keep the sentinel `filePath: ''` (REVIEW_LEVEL_FILE_PATH). */\n fetchedComments: ReviewComment[];\n}\n\n/** Injectable seams; defaults are the real core APIs. */\nexport interface RemoteSessionDeps {\n createProvider: (forge: ForgeName, runner: ForgeCommandRunner) => ForgeProvider;\n materialize: (\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner,\n existingClone?: ExistingClone | null,\n options?: MaterializeOptions\n ) => Promise<MaterializeResult>;\n detectExistingClone: (\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner,\n options?: MaterializeOptions\n ) => Promise<ExistingClone | null>;\n resolveRemoteDefaultBranch: (\n url: ForgeUrl,\n runner: ForgeCommandRunner,\n existing?: ExistingClone | null,\n options?: MaterializeOptions\n ) => Promise<string>;\n runner: ForgeCommandRunner;\n /** Untracked files are never included. A stand-in may omit `diagnostics` and `identity`. */\n loadDiff: (\n gitDiffArgs: string[],\n cwd: string,\n options?: RemoteLifetimeOptions\n ) => Promise<{\n files: DiffFile[];\n repository: string;\n diagnostics?: string[];\n identity?: ReviewSourceIdentity;\n }>;\n}\n\n/** Puts `gh`/`glab` under the session's bounds too, so a startup deadline can reach them. */\nfunction bindSessionRunner(runner: ForgeCommandRunner, signal?: AbortSignal): ForgeCommandRunner {\n return (command, args, options) => {\n if (signal?.aborted) {\n return Promise.reject(new CommandCancelledError('aborted', command, args));\n }\n return runner(command, args, {\n signal,\n timeoutMs: DEFAULT_GIT_COMMAND_TIMEOUT_MS,\n ...options,\n });\n };\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined, stage: string): void {\n if (signal?.aborted) {\n throw new CommandCancelledError('aborted', 'self-review', [stage]);\n }\n}\n\nexport const defaultRemoteSessionDeps: RemoteSessionDeps = {\n createProvider: createForgeProvider,\n detectExistingClone,\n materialize,\n resolveRemoteDefaultBranch,\n runner: defaultGitRunner,\n loadDiff: (gitDiffArgs, cwd, options) =>\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, {\n includeUntracked: false,\n signal: options?.signal,\n runner: (command, args, execution) =>\n defaultGitRunner(command, args, {\n ...execution,\n gitEnvironment: 'isolated',\n }),\n }),\n};\n\nexport interface RemoteLifetimeOptions {\n /** Defaults to stderr, with the existing remote diagnostic text and call form. */\n reportDiagnostic?: DiagnosticReporter;\n /** Passed unchanged to materialization; no host storage is used when supplied. */\n temporaryClones?: MaterializeOptions['temporaryClones'];\n /** Without one, the session is bounded only by the per-command timeout. */\n signal?: AbortSignal;\n}\n\nexport interface StartRemoteSessionOptions extends RemoteLifetimeOptions {\n includeResolved?: boolean;\n /**\n * `'optional'` (default, the app): a failed fetch degrades to no threads.\n * `'required'` (`fetch-comments`): always attempted, and a failure is fatal.\n */\n threads?: 'optional' | 'required';\n}\n\n/**\n * Materialize a forge PR/MR URL into a local git context and fetch its\n * discussion threads.\n *\n * Fatal failures (unrecognizable URL, materialization errors, base-branch\n * lookup failures other than a missing CLI) throw — callers surface them\n * like any other startup git error. Forge-CLI unavailability is never\n * fatal for the base branch (git-only fallback); for threads see\n * {@link StartRemoteSessionOptions.threads}.\n */\nexport async function startRemoteSession(\n url: string,\n cwd: string,\n deps: Partial<RemoteSessionDeps> = {},\n options: StartRemoteSessionOptions = {}\n): Promise<MaterializedRemoteSession> {\n const d: RemoteSessionDeps = { ...defaultRemoteSessionDeps, ...deps };\n const reportDiagnostic = isolatedReporter(options.reportDiagnostic);\n const threadsRequired = options.threads === 'required';\n const { signal } = options;\n const lifetime: MaterializeOptions = {\n signal,\n ...(options.temporaryClones ? { temporaryClones: options.temporaryClones } : {}),\n ...(options.reportDiagnostic ? { reportDiagnostic } : {}),\n };\n throwIfAborted(signal, 'start');\n\n const forgeUrl = parseForgeUrl(url);\n if (!forgeUrl) {\n throw new Error(\n `Not a recognized pull-request or merge-request URL: ${url}\\n` +\n 'Expected a GitHub PR URL (…/pull/N) or a GitLab MR URL (…/-/merge_requests/N).'\n );\n }\n\n const provider = d.createProvider(forgeUrl.forge, bindSessionRunner(d.runner, signal));\n\n let cliAvailable = true;\n let baseBranch: string;\n let existingClone: ExistingClone | null | undefined;\n try {\n baseBranch = await provider.fetchBaseBranch(forgeUrl);\n } catch (error) {\n if (!(error instanceof ForgeCliUnavailableError)) {\n throw error;\n }\n cliAvailable = false;\n reportDiagnostic(\n `[remote] Forge CLI unavailable (${error.cli}): ${error.message} — ` +\n 'falling back to the remote default branch via git.'\n );\n existingClone = await d.detectExistingClone(forgeUrl, cwd, d.runner, lifetime);\n baseBranch = await d.resolveRemoteDefaultBranch(forgeUrl, d.runner, existingClone, lifetime);\n }\n reportDiagnostic(`[remote] Base branch: ${baseBranch}`);\n\n const materialized = await d.materialize(\n forgeUrl,\n baseBranch,\n cwd,\n d.runner,\n existingClone,\n lifetime\n );\n\n // The caller gets the cleanup handle only with a session, so anything ending the call before that\n // releases here.\n try {\n let fetchedThreads: ForgeThread[] = [];\n let threadSyncAvailable = false;\n if (cliAvailable || threadsRequired) {\n try {\n fetchedThreads = await provider.fetchThreads(forgeUrl, {\n includeResolved: options.includeResolved ?? false,\n reviewedHeadSha: materialized.headSha,\n });\n threadSyncAvailable = true;\n } catch (error) {\n // A cancelled fetch ends the session under either policy.\n if (threadsRequired || isCommandCancelled(error)) {\n if (error instanceof ForgeCliUnavailableError) {\n throw new Error(\n `Cannot fetch discussion threads: ${error.message}\\n` +\n `This requires the ${error.cli} CLI to be installed and authenticated.`\n );\n }\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n reportDiagnostic(\n `[remote] thread sync unavailable — continuing without forge threads: ${message}`\n );\n }\n } else {\n reportDiagnostic(\n '[remote] thread sync unavailable — forge CLI missing, continuing without forge threads.'\n );\n }\n throwIfAborted(signal, 'threads');\n\n return {\n forgeUrl,\n repoPath: materialized.repoPath,\n gitDiffArgs: [`${materialized.baseSha}...${materialized.headSha}`],\n mode: materialized.mode,\n cleanup: materialized.cleanupAsync ?? materialized.cleanup,\n cleanupForExit: materialized.cleanup,\n remote: {\n remoteUrl: url,\n remoteBaseSha: materialized.baseSha,\n remoteHeadSha: materialized.headSha,\n remoteForge: forgeUrl.forge,\n threadSyncAvailable,\n // A temporary clone is deleted on exit, so nothing may be written\n // into it; the front end needs the fact, not the path.\n temporaryClone: materialized.mode === 'temp-clone',\n },\n fetchedThreads,\n };\n } catch (error) {\n await (materialized.cleanupAsync ?? materialized.cleanup)();\n throw error;\n }\n}\n\nexport interface RemoteReviewLoad {\n /** After the ignore configuration. */\n files: DiffFile[];\n repository: string;\n diagnostics: string[];\n /** `session.fetchedThreads` mapped against `files` and the materialized head. */\n comments: ReviewComment[];\n identity?: ReviewSourceIdentity;\n}\n\n/**\n * Load the diff, apply the ignore configuration and map the threads: the one place\n * this happens, so the app and `fetch-comments` cannot drift. Mapping against the\n * filtered files and the materialized head keeps a suggestion on an ignored path\n * or another head plain text (R05). Does not release the session on failure. An\n * abort during the load discards the result and throws.\n */\nexport async function loadRemoteReview(\n session: MaterializedRemoteSession,\n ignorePatterns: string[],\n loadDiff: RemoteSessionDeps['loadDiff'] = defaultRemoteSessionDeps.loadDiff,\n options: RemoteLifetimeOptions = {}\n): Promise<RemoteReviewLoad> {\n throwIfAborted(options.signal, 'load');\n const { files, repository, diagnostics, identity } = await loadDiff(\n session.gitDiffArgs,\n session.repoPath,\n options\n );\n throwIfAborted(options.signal, 'load');\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredFiles = files.filter(f => shouldKeep(f.newPath || f.oldPath));\n return {\n files: filteredFiles,\n repository,\n diagnostics: diagnostics ?? [],\n comments: mapThreadsToReviewComments(\n session.fetchedThreads,\n filteredFiles,\n session.remote.remoteHeadSha\n ),\n ...(identity ? { identity } : {}),\n };\n}\n\n/** A remote session plus the ready-to-send git-mode diff payload. */\nexport interface RemoteBootstrapResult {\n session: RemoteSession;\n payload: DiffLoadPayload;\n identity: ReviewSourceIdentity;\n}\n\n/**\n * The loader's identity relabelled as remote, with the user's launch directory rather than the\n * clone's; a stand-in loader still yields the head, with the merge base unknown.\n */\nfunction remoteSourceIdentity(\n started: MaterializedRemoteSession,\n loaded: RemoteReviewLoad,\n cwd: string\n): ReviewSourceIdentity {\n const resolved = loaded.identity ?? {\n sourceRoot: canonicalSourcePath(loaded.repository),\n gitDiffArgv: [...started.gitDiffArgs],\n pathPrefix: '',\n oldSide: { kind: 'unknown' as const, reason: 'the merge base was not resolved' },\n newSide: { kind: 'commit' as const, sha: started.remote.remoteHeadSha },\n };\n return { ...resolved, mode: 'remote', invocationCwd: cwd };\n}\n\n/**\n * Full remote bootstrap for the app: materialize, {@link loadRemoteReview}, and shape\n * the git-mode `DiffLoadPayload`. Thread sync degrades rather than failing.\n */\nexport async function bootstrapRemoteDiff(\n url: string,\n cwd: string,\n ignorePatterns: string[],\n deps: Partial<RemoteSessionDeps> = {},\n options: RemoteLifetimeOptions = {}\n): Promise<RemoteBootstrapResult> {\n const d: RemoteSessionDeps = { ...defaultRemoteSessionDeps, ...deps };\n const reportDiagnostic = isolatedReporter(options.reportDiagnostic);\n const started = await startRemoteSession(url, cwd, d, {\n signal: options.signal,\n temporaryClones: options.temporaryClones,\n reportDiagnostic,\n });\n\n // The caller gets the cleanup handle only with the result, so any failure before that releases\n // here.\n try {\n const loaded = await loadRemoteReview(started, ignorePatterns, d.loadDiff, options);\n for (const diagnostic of loaded.diagnostics) {\n reportDiagnostic(`[remote] Diff diagnostic: ${diagnostic}`);\n }\n\n const session: RemoteSession = { ...started, fetchedComments: loaded.comments };\n return {\n session,\n identity: remoteSourceIdentity(started, loaded, cwd),\n payload: {\n files: loaded.files,\n source: {\n type: 'git',\n // Same renderer the git-mode path uses, so expand-context can\n // tokenize this string back into the exact argv.\n gitDiffArgs: formatGitDiffArgs(session.gitDiffArgs),\n repository: loaded.repository,\n },\n remote: session.remote,\n // So the renderer never mistakes a failed load for \"no changes\".\n ...(loaded.diagnostics.length > 0 ? { diagnostics: loaded.diagnostics } : {}),\n },\n };\n } catch (error) {\n await started.cleanup();\n throw error;\n }\n}\n\nexport { mergeRemoteThreads, applyRemoteProvenance, computeRemoteDrift } from './remote-feedback';\n","// packages/core/src/fetch-comments.ts\n// Headless orchestrator for `self-review fetch-comments <URL>`: materialize\n// the PR/MR, fetch and map its discussion threads, and write a v3 review.xml\n// with remote provenance — no window, nothing on stdout, all logging on\n// stderr. Shares its load/filter/map steps with the app (remote-mode.ts); only the\n// thread-fetch policy differs (the app degrades, this fails).\n//\n// No overall deadline: bounded by the per-command timeout and the caller's `signal`.\n// The in-flight command tree is killed and owned resources are released. Publication checks\n// cancellation before rename; interruption after rename keeps the saved document.\n\nimport { stderrReporter } from './diagnostics';\nimport { CommandCancelledError } from './forge-provider';\nimport { REVIEW_LEVEL_FILE_PATH } from './thread-mapper';\nimport { publishReview } from './review-publisher';\nimport type { PublishReviewOptions, PublishReviewResult } from './review-publisher';\nimport { loadConfigWithProvenance } from './config';\nimport type { LoadedConfig, LoadConfigOptions } from './config';\nimport { publishOptionsFor, resolveOutputTarget } from './startup';\nimport { defaultRemoteSessionDeps, loadRemoteReview, startRemoteSession } from './remote-mode';\nimport type { RemoteLifetimeOptions, RemoteSessionDeps } from './remote-mode';\nimport type { DiffFile, FileReviewState, RemoteForge, ReviewComment, ReviewState } from './types';\n\n/** Injectable seams: the app's remote-session seams plus this subcommand's output. */\nexport interface FetchCommentsDeps extends RemoteSessionDeps {\n publish: (\n state: ReviewState,\n outputPath: string,\n options: PublishReviewOptions\n ) => Promise<PublishReviewResult>;\n loadConfig: (options?: LoadConfigOptions) => LoadedConfig;\n now: () => Date;\n}\n\nfunction defaultDeps(): FetchCommentsDeps {\n return {\n ...defaultRemoteSessionDeps,\n publish: publishReview,\n loadConfig: loadConfigWithProvenance,\n now: () => new Date(),\n };\n}\n\nexport interface BuildRemoteReviewStateArgs {\n remoteUrl: string;\n forge: RemoteForge;\n baseSha: string;\n headSha: string;\n diffFiles: DiffFile[];\n comments: ReviewComment[];\n timestamp: string;\n}\n\n/**\n * Assemble the ReviewState for a fetched remote review. Pure and\n * deterministic: same inputs, same state.\n *\n * Placement rules:\n * - Every diff file gets a file entry in diff order; fetched threads land on\n * their files, in thread order.\n * - Comments whose path is not in the diff (e.g. outdated anchors on files\n * no longer touched) get a synthetic entry with change-type \"modified\" —\n * the schema requires the attribute and \"modified\" is the least-claiming\n * value for a file we cannot classify.\n * - Review-level threads (sentinel {@link REVIEW_LEVEL_FILE_PATH}) are\n * folded into a single trailing file entry with the sentinel path: the v3\n * schema requires every <comment> inside a <file path>, and the empty\n * path can never collide with a real diff path, so consumers detect these\n * by comparing against the constant. Omitted when there are none.\n * - Every file is viewed=\"false\": fetch-comments reviews nothing, and a\n * viewed mark claims a human looked at the file. A subsequent\n * --resume-from session therefore starts with the full file list pending.\n * - `source` is `{ type: 'welcome' }`: the remote-* root attributes are the\n * review's source shape, and the three shapes (git, directory, remote)\n * are mutually exclusive by contract, so no local source attributes are\n * serialized.\n */\nexport function buildRemoteReviewState(args: BuildRemoteReviewStateArgs): ReviewState {\n const commentsByPath = new Map<string, ReviewComment[]>();\n for (const comment of args.comments) {\n const list = commentsByPath.get(comment.filePath);\n if (list) {\n list.push(comment);\n } else {\n commentsByPath.set(comment.filePath, [comment]);\n }\n }\n\n const files: FileReviewState[] = [];\n const diffPaths = new Set<string>();\n for (const diffFile of args.diffFiles) {\n const path = diffFile.changeType === 'deleted' ? diffFile.oldPath : diffFile.newPath;\n diffPaths.add(path);\n files.push({\n path,\n changeType: diffFile.changeType,\n viewed: false,\n comments: commentsByPath.get(path) ?? [],\n });\n }\n\n // Synthetic entries for anchored comments whose file is not in the diff,\n // in first-appearance order.\n for (const [path, comments] of commentsByPath) {\n if (path === REVIEW_LEVEL_FILE_PATH || diffPaths.has(path)) continue;\n files.push({ path, changeType: 'modified', viewed: false, comments });\n }\n\n const reviewLevel = commentsByPath.get(REVIEW_LEVEL_FILE_PATH);\n if (reviewLevel && reviewLevel.length > 0) {\n files.push({\n path: REVIEW_LEVEL_FILE_PATH,\n changeType: 'modified',\n viewed: false,\n comments: reviewLevel,\n });\n }\n\n return {\n timestamp: args.timestamp,\n source: { type: 'welcome' },\n files,\n remoteUrl: args.remoteUrl,\n remoteBaseSha: args.baseSha,\n remoteHeadSha: args.headSha,\n remoteForge: args.forge,\n };\n}\n\nexport interface FetchCommentsOptions extends RemoteLifetimeOptions {\n /** Include threads the forge marks resolved (GitLab). Default false. */\n includeResolved?: boolean;\n /** Working directory for clone detection and output resolution. */\n cwd?: string;\n /** Test seams; every omitted member falls back to the real default. */\n deps?: Partial<FetchCommentsDeps>;\n}\n\n/**\n * Run the headless fetch-comments flow end to end. Throws on any failure\n * (the caller prints the message to stderr and exits 1); the temporary\n * clone, when one was created, is removed on both success and failure, and\n * the removal has completed by the time the promise settles.\n *\n * A supplied reportDiagnostic owns progress, configuration, loading and materialization diagnostics.\n * Errors still reject for the host to present. Reporters must not throw.\n *\n * Fetching comments is the whole point, so threads run under the `'required'`\n * policy: an unavailable forge CLI is an error, not a degraded review.\n */\nexport async function runFetchComments(\n url: string,\n options: FetchCommentsOptions = {}\n): Promise<void> {\n const deps: FetchCommentsDeps = { ...defaultDeps(), ...options.deps };\n const cwd = options.cwd ?? process.cwd();\n const reportDiagnostic = options.reportDiagnostic ?? stderrReporter;\n const lifetime: RemoteLifetimeOptions = {\n signal: options.signal,\n temporaryClones: options.temporaryClones,\n ...(options.reportDiagnostic ? { reportDiagnostic } : {}),\n };\n\n // startRemoteSession cleans up after its own failure; once it returns, this try/finally owns the\n // session.\n const session = await startRemoteSession(url, cwd, deps, {\n ...lifetime,\n includeResolved: options.includeResolved ?? false,\n threads: 'required',\n });\n try {\n reportDiagnostic(`[fetch-comments] Fetched ${session.fetchedThreads.length} threads`);\n\n const loadedConfig = deps.loadConfig({\n cwd,\n ...(options.reportDiagnostic ? { reportDiagnostic } : {}),\n });\n const config = loadedConfig.config;\n const loaded = await loadRemoteReview(session, config.ignore ?? [], deps.loadDiff, lifetime);\n for (const diagnostic of loaded.diagnostics) {\n reportDiagnostic(`[fetch-comments] Diff diagnostic: ${diagnostic}`);\n }\n\n const state = buildRemoteReviewState({\n remoteUrl: url,\n forge: session.forgeUrl.forge,\n baseSha: session.remote.remoteBaseSha,\n headSha: session.remote.remoteHeadSha,\n diffFiles: loaded.files,\n comments: loaded.comments,\n timestamp: deps.now().toISOString(),\n });\n\n // No flag names the output, so config provenance decides its trust (as in the app and serve).\n const target = resolveOutputTarget(null, loadedConfig, cwd);\n if (options.signal?.aborted) {\n throw new CommandCancelledError('aborted', 'self-review', ['publish']);\n }\n await deps.publish(state, target.path, {\n ...publishOptionsFor(target),\n ...(options.reportDiagnostic ? { reportDiagnostic } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n try {\n reportDiagnostic(\n `[fetch-comments] ${loaded.comments.length} threads written to ${target.path}`\n );\n } catch {\n /* Presentation cannot change an already committed publication's outcome. */\n }\n } finally {\n await session.cleanup();\n }\n if (options.signal?.aborted) {\n throw new CommandCancelledError('aborted', 'self-review', ['fetch-comments']);\n }\n}\n"]}