@self-review/core 2.0.4 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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-LSLCQQBN.cjs","../src/forge-definitions.ts","../src/forge-provider.ts","../src/bounded-read.ts","../src/local-loading-lifetime.ts","../src/safe-fs-policy.ts","../src/safe-fs-read.ts","../src/safe-fs-legacy.ts","../src/safe-fs-async.ts","../src/safe-fs.ts","../src/node-scan-fs.ts","../src/publication-fs.ts","../src/remote-temp.ts","../src/command-runner.ts","../src/process-tree.ts","../src/loaded-snapshot.ts","../src/synthetic-diagnostics.ts","../src/synthetic-accounting.ts","../src/git-path-quote.ts","../src/synthetic-emitter.ts","../src/synthetic-text.ts","../src/synthetic-diff.ts","../src/synthetic-source.ts","../src/git-option-policy.ts","../src/git-argument-policy.ts","../src/git-argument-text.ts","../src/git-diff-args.ts","../src/git-argument-paths.ts","../src/diagnostics.ts","../src/effect-diagnostics.ts","../src/git.ts","../src/materializer.ts","../src/review-session.ts","../src/source-identity.ts","../src/suggestion-read.ts","../src/apply-suggestion.ts","../src/suggestion-content.ts","../src/review-suggestions.ts"],"names":["path","yieldToIo","constants","randomBytes","lstatOrNull","fs","snapshot","realpathSync","closeSync","fstatSync","lstatSync","openSync","dirname","relative","needsQuoting","resolve","read","buffer"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACHO,IAAM,kBAAA,EAAoE;AAAA,EAC/E,MAAA,EAAQ;AAAA,IACN,OAAA,EAAS,oDAAA;AAAA,IACT,OAAA,EAAS,CAAA,MAAA,EAAA,GAAU,CAAA,oBAAA,EAAuB,MAAM,CAAA,KAAA;AAAA,EAClD,CAAA;AAAA,EACA,MAAA,EAAQ;AAAA,IACN,OAAA,EAAS,0CAAA;AAAA,IACT,OAAA,EAAS,CAAA,MAAA,EAAA,GAAU,CAAA,UAAA,EAAa,MAAM,CAAA,KAAA;AAAA,EACxC;AACF,CAAA;ADKA;AACA;AE4HO,IAAM,sBAAA,EAAN,MAAA,QAAoC,MAAM;AAAA,EAK/C,WAAA,CAAY,MAAA,EAA6B,OAAA,EAAiB,IAAA,EAAyB;AACjF,IAAA,KAAA;AAAA,MACE,OAAA,IAAW,UAAA,EACP,CAAA,EAAA;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EAAA;AACP,IAAA;AACiB,IAAA;AACtB,EAAA;AACyB,EAAA;AACf,IAAA;AACC,MAAA;AACU,MAAA;AACV,MAAA;AACA,MAAA;AACV,IAAA;AACF,EAAA;AAC0B,EAAA;AAC5B;AAQsB;AAMJ,kBAAA;AACN,EAAA;AACL,IAAA;AACgB,IAAA;AACM,IAAA;AAC3B,EAAA;AACyB,EAAA;AACE,EAAA;AACV,EAAA;AACD,kBAAA;AACU,EAAA;AACX,EAAA;AACM,EAAA;AACL,EAAA;AAGM,EAAA;AACf,EAAA;AACT;AAGE;AAIA,EAAA;AACwB,IAAA;AAGxB,EAAA;AAOsB,EAAA;AACb,IAAA;AACG,MAAA;AACR,MAAA;AACsB,MAAA;AACxB,IAAA;AACF,EAAA;AACO,EAAA;AACG,IAAA;AACR,IAAA;AACe,IAAA;AACA,IAAA;AACjB,EAAA;AACF;ArC2mG8B;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;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-LSLCQQBN.cjs","sourcesContent":[null,"// Pure forge URL and snapshot-ref rules, shared by URL parsing and materialization.\n// GitLab is matched first because namespaces can contain arbitrary nested path segments.\nimport type { RemoteForge } from './types';\n\ninterface ForgeDefinition {\n urlPath: RegExp;\n headRef: (number: number) => string;\n}\n\n// The number terminates its path segment; suffixes such as /files remain supported.\nexport const FORGE_DEFINITIONS: Readonly<Record<RemoteForge, ForgeDefinition>> = {\n gitlab: {\n urlPath: /^\\/(.+)\\/([^/]+)\\/-\\/merge_requests\\/(\\d+)(?=\\/|$)/,\n headRef: number => `refs/merge-requests/${number}/head`,\n },\n github: {\n urlPath: /^\\/([^/]+)\\/([^/]+)\\/pull\\/(\\d+)(?=\\/|$)/,\n headRef: number => `refs/pull/${number}/head`,\n },\n};\n","// forge-provider.ts\n// Conversation-plane forge abstraction: URL parsing with forge detection by\n// path shape, the ForgeProvider interface (base-branch lookup + thread fetch),\n// and the forge-neutral normalized thread types produced by every provider.\n//\n// This module is pure code: no I/O, no child processes. Provider\n// implementations (github-provider.ts, gitlab-provider.ts) do the CLI work\n// through an injectable command runner so they stay unit-testable.\n\nimport type { RemoteForge } from './types';\nimport { FORGE_DEFINITIONS } from './forge-definitions';\n\n/** Forges the app knows how to talk to. */\nexport type ForgeName = RemoteForge;\n\n/**\n * A parsed pull-request / merge-request web URL.\n *\n * Detection is by URL path shape only (`/pull/N` → GitHub,\n * `/-/merge_requests/N` → GitLab) on any host, so self-hosted instances such\n * as git.drupalcode.org work with zero configuration.\n */\nexport interface ForgeUrl {\n forge: ForgeName;\n /** Host as it appears in the URL, including a port when present. */\n host: string;\n /**\n * Repository owner. For GitLab this is the full namespace path and may\n * contain slashes (subgroups, e.g. `group/subgroup`); for GitHub it is a\n * single segment.\n */\n owner: string;\n /** Repository name (final path segment before the PR/MR marker). */\n repo: string;\n /** Pull-request number / merge-request IID. */\n number: number;\n}\n\n/** Which side of the diff a thread anchor points at. */\nexport type ForgeAnchorSide = 'old' | 'new';\n\n/**\n * Forge-neutral anchor of a discussion thread onto the diff.\n *\n * The mapper consumes this shape without forge-conditional logic:\n * - `startLine`/`endLine` are equal for single-line anchors.\n * - `startLine`/`endLine` are `null` when the forge supplies a file path but\n * no usable line information (the mapper degrades to a file-level comment;\n * `side` is meaningless in that case and providers should set `'new'`).\n *\n * Revision provenance (the mapper compares it with the reviewed head; providers\n * report only what the forge told them):\n * - `headSha`: head commit the line numbers were computed against, when the\n * forge reports one per note (GitLab), or a provider verifies the head around\n * thread retrieval (GitHub). A suggestion activates only on a match.\n * - `outdated`: the forge's own per-note verdict (GitHub `line: null`). `true`\n * degrades to file-level; `false` vouches for the anchor when no `headSha` exists.\n *\n * An anchor carrying neither is unverifiable: it never activates a suggestion.\n */\nexport interface ForgeThreadAnchor {\n filePath: string;\n side: ForgeAnchorSide;\n startLine: number | null;\n endLine: number | null;\n headSha?: string;\n outdated?: boolean;\n}\n\n/** One turn (root comment or reply) in a forge discussion thread. */\nexport interface ForgeThreadTurn {\n /** Forge-assigned comment/note ID, kept as a string verbatim. */\n remoteId: string;\n /** Forge username of the turn's author. */\n author: string;\n /** Markdown body, passed through verbatim. */\n body: string;\n}\n\n/**\n * A normalized discussion thread: an ordered root + flat replies.\n *\n * The root turn owns the anchor. `anchor` is `null` for threads with no file\n * association at all (e.g. GitLab non-diff discussions); the mapper turns\n * those into its review-level representation. `replies` preserve the forge's\n * document order — nothing else sorts them.\n */\nexport interface ForgeThread {\n root: ForgeThreadTurn;\n replies: ForgeThreadTurn[];\n anchor: ForgeThreadAnchor | null;\n}\n\n/** Options for {@link ForgeProvider.fetchThreads}. */\nexport interface FetchThreadsOptions {\n /**\n * Include threads the forge marks resolved. Defaults to false where the\n * forge tracks resolution (GitLab); providers without a comparable concept\n * on the fetch path (GitHub REST review comments) may ignore it.\n */\n includeResolved?: boolean;\n /** Pinned materialized head. Providers may verify current anchors against this snapshot. */\n reviewedHeadSha?: string;\n}\n\n/**\n * Result of running a forge CLI command through {@link ForgeCommandRunner}.\n */\nexport interface ForgeCommandResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n}\n\n/**\n * Optional lifetime bounds; either one kills the child and rejects with {@link\n * CommandCancelledError}.\n */\nexport interface ForgeCommandOptions {\n signal?: AbortSignal;\n timeoutMs?: number;\n /** Working directory, without invoking a shell. */\n cwd?: string;\n /** Combined captured stdout/stderr byte limit, before decoding. */\n maxOutputBytes?: number;\n /** Remote-owned Git operations ignore ambient repository, index, object and namespace selection.\n * Local explicit targets keep their intentionally selected alternate index by default. */\n gitEnvironment?: 'isolated';\n}\n\n/**\n * Injectable command runner for providers and the materializer. Resolves with\n * the exit code on any completed run; rejects when the binary cannot be spawned\n * and, with a {@link CommandCancelledError}, when cut short by `options`.\n */\nexport type ForgeCommandRunner = (\n command: string,\n args: string[],\n options?: ForgeCommandOptions\n) => Promise<ForgeCommandResult>;\n\n/** Why a command run was cut short. */\nexport type CommandCancelReason = 'aborted' | 'timeout';\n\n/**\n * A run ended by its caller's bounds (abort or timeout) after the child was\n * killed. Providers must not fold it into {@link ForgeCliUnavailableError}: a\n * session being torn down must not degrade into a review without threads.\n */\nexport class CommandCancelledError extends Error {\n readonly reason: CommandCancelReason;\n readonly command: string;\n readonly args: readonly string[];\n\n constructor(reason: CommandCancelReason, command: string, args: readonly string[]) {\n super(\n reason === 'timeout'\n ? `${command} ${args.join(' ')} timed out and was killed`\n : `${command} ${args.join(' ')} was cancelled`\n );\n this.name = 'CommandCancelledError';\n this.reason = reason;\n this.command = command;\n this.args = args;\n }\n}\n\n/** Matches by name too, so it works across module instances. */\nexport function isCommandCancelled(error: unknown): error is CommandCancelledError {\n return (\n error instanceof CommandCancelledError ||\n (error instanceof Error && error.name === 'CommandCancelledError')\n );\n}\n\n/**\n * The conversation plane of a forge. Exactly two capabilities: base-branch\n * lookup and discussion-thread fetching. No diff fetching, no blob fetching,\n * no posting — those concerns live elsewhere.\n *\n * Implementations throw {@link ForgeCliUnavailableError} when their CLI is\n * absent, unauthenticated or returns malformed required response data so callers can degrade\n * visibly. A successful fetch returns all validated pages, never a silently shortened list.\n * Unknown extension fields are ignored. Null/deleted authors use each forge's fallback name.\n * Runners must propagate CommandCancelledError on interruption, including across pagination.\n * Each provider instance is safe for concurrent calls when its supplied runner is also safe.\n */\nexport interface ForgeProvider {\n readonly forge: ForgeName;\n /** Resolve the PR/MR base (target) branch name. */\n fetchBaseBranch(url: ForgeUrl): Promise<string>;\n /** Fetch the PR/MR discussion threads in normalized form. */\n fetchThreads(url: ForgeUrl, options?: FetchThreadsOptions): Promise<ForgeThread[]>;\n}\n\n/**\n * Thrown by providers when their CLI is missing (spawn ENOENT) or exits\n * non-zero due to authentication/API failure. Callers catch this to degrade\n * (print to stderr, continue without threads) instead of crashing.\n */\nexport class ForgeCliUnavailableError extends Error {\n readonly forge: ForgeName;\n readonly cli: string;\n\n constructor(forge: ForgeName, cli: string, message: string) {\n super(message);\n this.name = 'ForgeCliUnavailableError';\n this.forge = forge;\n this.cli = cli;\n }\n}\n\n/**\n * Parse a forge web URL into a {@link ForgeUrl}, or return `null` for\n * anything that is not a PR/MR URL. Detection is by path shape only, on any\n * http(s) host. Query strings and fragments are ignored.\n */\nexport function parseForgeUrl(url: string): ForgeUrl | null {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return null;\n }\n\n for (const forge of Object.keys(FORGE_DEFINITIONS) as ForgeName[]) {\n const match = FORGE_DEFINITIONS[forge].urlPath.exec(parsed.pathname);\n if (match) {\n const number = Number(match[3]);\n if (!Number.isSafeInteger(number) || number <= 0) return null;\n return {\n forge,\n host: parsed.host,\n owner: match[1],\n repo: match[2],\n number,\n };\n }\n }\n\n return null;\n}\n","// packages/core/src/bounded-read.ts\n// Whole-file reads within a byte budget, decided on the open descriptor before anything is allocated.\n\nimport { closeSync, constants, fstatSync, openSync, read, readSync } from 'fs';\nimport type { Stats } from 'fs';\nimport { open } from 'fs/promises';\nimport { promisify } from 'util';\nimport { checkLoadingCancelled, loadingCheckpoint } from './local-loading-lifetime';\n\n/** Filesystem errors (ENOENT, EACCES, ...) throw. */\nexport type BoundedReadResult =\n | { kind: 'ok'; content: Buffer }\n | { kind: 'too-large'; size: number }\n /** A directory, FIFO, socket or device: nothing was read. */\n | { kind: 'not-regular' };\n\n/** O_NONBLOCK keeps a FIFO from stalling the open until a writer appears; Windows lacks it. */\nexport const READ_FLAGS = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);\n\nexport interface BoundedReadOptions {\n /** Covers the leaf only; ancestors are the caller's job (`openContainedFile`). */\n noFollow?: boolean;\n}\n\nexport interface AsyncBoundedReadOptions extends BoundedReadOptions {\n signal?: AbortSignal;\n}\n\nconst readAsync = promisify(read);\n\nfunction openFlags(options: BoundedReadOptions): number {\n return options.noFollow ? READ_FLAGS | constants.O_NOFOLLOW : READ_FLAGS;\n}\n\nexport async function readFileWithinBudget(\n path: string,\n maxBytes: number,\n options: AsyncBoundedReadOptions = {}\n): Promise<BoundedReadResult> {\n checkLoadingCancelled(options.signal);\n const handle = await open(path, openFlags(options));\n try {\n checkLoadingCancelled(options.signal);\n const stats = await handle.stat();\n checkLoadingCancelled(options.signal);\n if (!stats.isFile()) return { kind: 'not-regular' };\n return await readDescriptorWithinBudget(handle.fd, stats, maxBytes, options);\n } finally {\n try {\n await handle.close();\n } finally {\n checkLoadingCancelled(options.signal);\n }\n }\n}\n\n/** {@link readFileWithinBudget} on a regular file the caller opened and `fstat`ed. */\nexport async function readDescriptorWithinBudget(\n fd: number,\n stats: Stats,\n maxBytes: number,\n options: Pick<AsyncBoundedReadOptions, 'signal'> = {}\n): Promise<Exclude<BoundedReadResult, { kind: 'not-regular' }>> {\n checkLoadingCancelled(options.signal);\n if (stats.size > maxBytes) return { kind: 'too-large', size: stats.size };\n\n let buffer: Buffer = Buffer.alloc(initialCapacity(stats.size, maxBytes));\n let filled = 0;\n for (;;) {\n await loadingCheckpoint(options.signal);\n const { bytesRead } = await readAsync(\n fd,\n buffer,\n filled,\n Math.min(buffer.length - filled, 64 * 1024),\n null\n );\n checkLoadingCancelled(options.signal);\n if (bytesRead === 0) break;\n filled += bytesRead;\n if (filled === buffer.length) {\n // The file grew since fstat: keep going up to budget + 1.\n if (buffer.length > maxBytes) break;\n buffer = grow(buffer, maxBytes);\n }\n }\n if (filled > maxBytes) return { kind: 'too-large', size: Math.max(filled, stats.size) };\n return { kind: 'ok', content: buffer.subarray(0, filled) };\n}\n\nexport function readFileWithinBudgetSync(\n path: string,\n maxBytes: number,\n options: BoundedReadOptions = {}\n): BoundedReadResult {\n const fd = openSync(path, openFlags(options));\n try {\n const stats = fstatSync(fd);\n if (!stats.isFile()) return { kind: 'not-regular' };\n if (stats.size > maxBytes) return { kind: 'too-large', size: stats.size };\n\n let buffer: Buffer = Buffer.alloc(initialCapacity(stats.size, maxBytes));\n let filled = 0;\n for (;;) {\n filled += readInto(fd, buffer, filled, buffer.length - filled);\n if (filled < buffer.length || buffer.length > maxBytes) break;\n buffer = grow(buffer, maxBytes);\n }\n if (filled > maxBytes) return { kind: 'too-large', size: Math.max(filled, stats.size) };\n return { kind: 'ok', content: buffer.subarray(0, filled) };\n } finally {\n closeSync(fd);\n }\n}\n\n/** One byte past the fstat size, so growth since is noticed; never more than budget + 1. */\nfunction initialCapacity(size: number, maxBytes: number): number {\n return Math.min(size, maxBytes) + 1;\n}\n\nfunction grow(buffer: Buffer, maxBytes: number): Buffer {\n const next = Buffer.alloc(Math.min(buffer.length * 2, maxBytes + 1));\n buffer.copy(next);\n return next;\n}\n\n/** Fill `buffer[offset, offset + length)`, stopping early only at end of file. */\nexport function readInto(fd: number, buffer: Buffer, offset: number, length: number): number {\n let filled = 0;\n while (filled < length) {\n const bytesRead = readSync(fd, buffer, offset + filled, length - filled, null);\n if (bytesRead === 0) break;\n filled += bytesRead;\n }\n return filled;\n}\n\n/** Read only through the supplied handle, never a native read on an embedder's descriptor. */\nexport async function readIntoAsync(\n reader: {\n read(\n buffer: Buffer,\n offset: number,\n length: number,\n position: number | null\n ): Promise<{ bytesRead: number }>;\n },\n buffer: Buffer,\n offset: number,\n length: number,\n signal?: AbortSignal\n): Promise<number> {\n checkLoadingCancelled(signal);\n let filled = 0;\n while (filled < length) {\n await loadingCheckpoint(signal);\n const { bytesRead } = await reader.read(\n buffer,\n offset + filled,\n Math.min(length - filled, 64 * 1024),\n null\n );\n checkLoadingCancelled(signal);\n if (bytesRead === 0) break;\n filled += bytesRead;\n }\n return filled;\n}\n","// Cooperative loading checkpoints. Native calls and individual string operations cannot be preempted.\nimport { setImmediate } from 'node:timers/promises';\nimport { CommandCancelledError } from './forge-provider';\n\nexport function checkLoadingCancelled(signal?: AbortSignal): void {\n if (signal?.aborted) {\n throw new CommandCancelledError('aborted', 'self-review', ['load-local-review']);\n }\n}\n\n/** Yield even when the preceding work completed from cache or an immediately resolved promise. */\nexport async function loadingCheckpoint(signal?: AbortSignal): Promise<void> {\n checkLoadingCancelled(signal);\n await setImmediate();\n checkLoadingCancelled(signal);\n}\n","// Shared replacement policy for synchronous and asynchronous filesystem adapters.\nimport type * as nodeFs from 'node:fs';\n\nexport type SafeFsErrorCode =\n | 'output-is-directory'\n /** EACCES, EPERM or EROFS. */\n | 'permission-denied'\n /** ENOSPC or EDQUOT. */\n | 'no-space'\n /** A symlink sits where this module would read, create or replace a file, or on the way to it. */\n | 'unsafe-link'\n /** Exists, but replacing it would change semantics: hard-linked, not a regular file, or foreign-owned. */\n | 'unsupported-target'\n /** The file at the target is not the one the caller checked. */\n | 'identity-changed'\n /** ENOENT or ENOTDIR. */\n | 'not-found'\n /** A FIFO, socket or device. */\n | 'not-regular'\n | 'too-large'\n | 'io-error';\n\nexport class SafeFsError extends Error {\n readonly code: SafeFsErrorCode;\n readonly path: string;\n readonly cause?: unknown;\n\n constructor(code: SafeFsErrorCode, path: string, message: string, cause?: unknown) {\n super(message);\n this.name = 'SafeFsError';\n this.code = code;\n this.path = path;\n if (cause !== undefined) this.cause = cause;\n }\n}\n\nexport interface FileIdentity {\n dev: number;\n ino: number;\n /** Permission bits only (`mode & 0o7777`). */\n mode: number;\n nlink: number;\n size: number;\n mtimeMs: number;\n uid: number;\n gid: number;\n}\n\nexport function snapshotIdentity(stats: nodeFs.Stats): FileIdentity {\n return {\n dev: stats.dev,\n ino: stats.ino,\n mode: stats.mode & 0o7777,\n nlink: stats.nlink,\n size: stats.size,\n mtimeMs: stats.mtimeMs,\n uid: stats.uid,\n gid: stats.gid,\n };\n}\n\nexport function sameFile(a: FileIdentity, b: FileIdentity): boolean {\n return a.dev === b.dev && a.ino === b.ino;\n}\n\n/** A rewrite within the filesystem's timestamp granularity passes; callers compare content too. */\nexport function sameStamp(a: FileIdentity, b: FileIdentity): boolean {\n return a.size === b.size && a.mtimeMs === b.mtimeMs;\n}\n\nconst ERRNO_CODES = new Map<string, SafeFsErrorCode>([\n ['ENOENT', 'not-found'],\n ['ENOTDIR', 'not-found'],\n ['EISDIR', 'output-is-directory'],\n ['EACCES', 'permission-denied'],\n ['EPERM', 'permission-denied'],\n ['EROFS', 'permission-denied'],\n ['ENOSPC', 'no-space'],\n ['EDQUOT', 'no-space'],\n ['ELOOP', 'unsafe-link'],\n]);\n\n/** The code a caller maps to its own reason; anything unknown is `io-error`. */\nexport function classifyFsError(error: unknown): SafeFsErrorCode {\n return ERRNO_CODES.get(errnoOf(error) ?? '') ?? 'io-error';\n}\n\nexport function errnoOf(error: unknown): string | undefined {\n if (error && typeof error === 'object' && 'code' in error) {\n const code = (error as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n }\n return undefined;\n}\n\n/** Wrap a raw fs failure, passing a `SafeFsError` through untouched. */\nexport function toSafeFsError(error: unknown, filePath: string, action: string): SafeFsError {\n if (error instanceof SafeFsError) return error;\n const reason = error instanceof Error ? error.message : String(error);\n return new SafeFsError(\n classifyFsError(error),\n filePath,\n `Cannot ${action} ${filePath}: ${reason}`,\n error\n );\n}\n\nexport function guarded<T>(filePath: string, action: string, fn: () => T): T {\n try {\n return fn();\n } catch (error) {\n throw toSafeFsError(error, filePath, action);\n }\n}\n\n/** Checked before staging and again after the temp file has been written and synced. */\nexport function assertExpectedTarget(\n target: string,\n existing: FileIdentity | null,\n options: {\n expectedIdentity?: FileIdentity;\n expectUnmodified?: boolean;\n preserveMode?: boolean;\n preserveOwner?: boolean;\n }\n): void {\n const expected = options.expectedIdentity;\n if (expected && (!existing || !sameFile(existing, expected))) {\n throw new SafeFsError(\n 'identity-changed',\n target,\n `Refusing to replace ${target}: it is no longer the file that was checked`\n );\n }\n if (\n expected &&\n existing &&\n ((options.preserveMode && expected.mode !== existing.mode) ||\n (options.preserveOwner && (expected.uid !== existing.uid || expected.gid !== existing.gid)))\n ) {\n throw new SafeFsError(\n 'identity-changed',\n target,\n `Refusing to replace ${target}: its permissions or owner changed`\n );\n }\n if (expected && options.expectUnmodified && existing && !sameStamp(existing, expected)) {\n throw new SafeFsError(\n 'identity-changed',\n target,\n `Refusing to replace ${target}: it was modified after it was checked`\n );\n }\n}\n\n/** Undefined when the new file already gets the right owner; only root may give one away. */\nexport function ownerToRestore(\n target: string,\n existing: FileIdentity\n): { uid: number; gid: number } | undefined {\n if (typeof process.geteuid !== 'function' || typeof process.getegid !== 'function')\n return undefined;\n const me = { uid: process.geteuid(), gid: process.getegid() };\n if (existing.uid === me.uid && existing.gid === me.gid) return undefined;\n if (existing.uid !== me.uid && me.uid !== 0) {\n throw new SafeFsError(\n 'unsupported-target',\n target,\n `Refusing to replace ${target}: it is owned by another user (uid ${existing.uid}), and replacing it would change its owner`\n );\n }\n return { uid: existing.uid, gid: existing.gid };\n}\n\nexport function replacementIdentity(target: string, stats: nodeFs.Stats): FileIdentity {\n if (stats.isSymbolicLink()) {\n throw new SafeFsError(\n 'unsafe-link',\n target,\n `Refusing to write ${target}: it is a symbolic link, and this program does not follow links when saving`\n );\n }\n if (stats.isDirectory()) {\n throw new SafeFsError(\n 'output-is-directory',\n target,\n `Cannot write ${target}: it is a directory`\n );\n }\n if (!stats.isFile()) {\n throw new SafeFsError(\n 'unsupported-target',\n target,\n `Cannot write ${target}: it exists but is not a regular file`\n );\n }\n // A rename would detach this name from the other links.\n if (stats.nlink > 1) {\n throw new SafeFsError(\n 'unsupported-target',\n target,\n `Refusing to replace ${target}: it has ${stats.nlink} hard links, and replacing it would silently detach the others`\n );\n }\n return snapshotIdentity(stats);\n}\n","// Read capabilities contain no mutation, ownership or replacement operations.\nimport * as fs from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport { setImmediate as yieldToIo } from 'node:timers/promises';\nimport type { FsLayer } from './safe-fs';\nimport * as path from 'node:path';\nimport { SafeFsError, errnoOf, toSafeFsError } from './safe-fs-policy';\n\n/** Methods retain their receiver. read copies at most length bytes into the caller's buffer. */\nexport interface AsyncReadHandle {\n stat(): Promise<Stats>;\n read(\n buffer: Buffer,\n offset: number,\n length: number,\n position: number | null\n ): Promise<{ bytesRead: number }>;\n close(): Promise<void>;\n}\n\nexport interface AsyncReadFsLayer<H extends AsyncReadHandle = AsyncReadHandle> {\n open(target: string, flags: number, mode?: number): Promise<H>;\n lstat(target: string): Promise<Stats>;\n realpath(target: string): Promise<string>;\n}\n\n/**\n * Explicit promise that read copies the requested chunk without allocating the whole file.\n * This is an adapter contract, not a way to interrupt an arbitrary implementation or syscall.\n */\nexport interface BoundedAsyncReadFsLayer<\n H extends AsyncReadHandle = AsyncReadHandle,\n> extends AsyncReadFsLayer<H> {\n readonly readAllocation: 'bounded';\n}\n\nexport const nodeReadFsLayer: BoundedAsyncReadFsLayer<FileHandle> = {\n readAllocation: 'bounded',\n open: (target, flags, mode) => fs.open(target, flags, mode),\n lstat: target => fs.lstat(target),\n realpath: target => fs.realpath(target),\n};\n\n/** Unlike FsLayer's legacy path, a bounded synchronous reader must implement descriptor reads. */\nexport type SyncReadFsLayer = Pick<\n FsLayer,\n 'openSync' | 'fstatSync' | 'lstatSync' | 'realpathSync' | 'closeSync'\n> &\n Required<Pick<FsLayer, 'readSync'>>;\n\n/**\n * Bounded allocation over the supplied filesystem, including virtual descriptors. Each read yields\n * before its synchronous call. The call itself cannot be preempted; no native-fs fallback is used.\n */\nexport function boundedReadFsFromSync(\n layer: SyncReadFsLayer,\n signal?: AbortSignal\n): BoundedAsyncReadFsLayer {\n return {\n readAllocation: 'bounded',\n async open(target, flags, mode) {\n const fd = layer.openSync(target, flags, mode);\n return {\n async stat() {\n return layer.fstatSync(fd);\n },\n async read(buffer, offset, length, position) {\n await yieldToIo();\n signal?.throwIfAborted();\n return { bytesRead: layer.readSync(fd, buffer, offset, length, position) };\n },\n async close() {\n layer.closeSync(fd);\n },\n };\n },\n async lstat(target) {\n return layer.lstatSync(target);\n },\n async realpath(target) {\n return layer.realpathSync(target);\n },\n };\n}\n\n/** Inspect every parent without following links; the root is the caller's trust boundary. */\nexport async function assertNoSymlinkAncestorsAsync(\n root: string,\n rel: string,\n layer: Pick<AsyncReadFsLayer, 'lstat'>,\n signal?: AbortSignal\n): Promise<void> {\n signal?.throwIfAborted();\n const normalized = path.normalize(rel);\n if (\n path.isAbsolute(normalized) ||\n normalized === '..' ||\n normalized.startsWith(`..${path.sep}`)\n ) {\n throw new SafeFsError(\n 'unsupported-target',\n path.join(root, rel),\n `Refusing ${rel}: it does not stay under ${root}`\n );\n }\n let current = root;\n for (const segment of path.dirname(normalized).split(path.sep)) {\n if (!segment || segment === '.') continue;\n current = path.join(current, segment);\n let stats: Stats;\n try {\n stats = await layer.lstat(current);\n } catch (error) {\n signal?.throwIfAborted();\n if (errnoOf(error) === 'ENOENT') break;\n throw toSafeFsError(error, current, 'inspect');\n }\n signal?.throwIfAborted();\n if (stats.isSymbolicLink()) {\n throw new SafeFsError(\n 'unsafe-link',\n current,\n `Refusing to go through ${current}: it is a symbolic link`\n );\n }\n }\n}\n","// Compatibility only: arbitrary synchronous adapters cannot promise bounded allocation or preemption.\nimport { setImmediate as yieldToIo } from 'node:timers/promises';\nimport type { FsLayer } from './safe-fs';\nimport type { AsyncFsLayer } from './safe-fs-async';\n\n/**\n * Compatibility for supplied synchronous adapters, including virtual descriptors. Each chunk yields\n * to cancellation. Without readSync, the caller's readFileSync allocates the whole file once: that\n * call cannot be preempted or bounded during allocation, so callers check size before and after.\n */\nexport function asyncFsFromSync(layer: FsLayer, signal?: AbortSignal): AsyncFsLayer {\n if (layer.asyncFs) return layer.asyncFs;\n return {\n async open(target, flags, mode) {\n const fd = layer.openSync(target, flags, mode);\n let cached: Buffer | undefined;\n let cursor = 0;\n return {\n async stat() {\n return layer.fstatSync(fd);\n },\n async read(buffer, offset, length, position) {\n await yieldToIo();\n signal?.throwIfAborted();\n if (layer.readSync) {\n return { bytesRead: layer.readSync(fd, buffer, offset, length, position) };\n }\n cached ??= layer.readFileSync(fd);\n const start = position ?? cursor;\n const bytesRead = cached.copy(\n buffer,\n offset,\n start,\n Math.min(start + length, cached.length)\n );\n if (position === null) cursor += bytesRead;\n return { bytesRead };\n },\n async write(buffer) {\n await yieldToIo();\n signal?.throwIfAborted();\n return { bytesWritten: layer.writeSync(fd, buffer) };\n },\n async sync() {\n layer.fsyncSync(fd);\n },\n async chmod(mode) {\n layer.fchmodSync(fd, mode);\n },\n async chown(uid, gid) {\n layer.fchownSync(fd, uid, gid);\n },\n async close() {\n cached = undefined;\n layer.closeSync(fd);\n },\n };\n },\n async lstat(target) {\n return layer.lstatSync(target);\n },\n async realpath(target) {\n return layer.realpathSync(target);\n },\n async rename(from, to) {\n layer.renameSync(from, to);\n },\n async unlink(target) {\n layer.unlinkSync(target);\n },\n };\n}\n","// Promise-based I/O under the same target, identity and ownership policy as safe-fs.\nimport * as fs from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport { constants } from 'node:fs';\nimport * as path from 'node:path';\nimport { randomBytes } from 'node:crypto';\nimport { READ_FLAGS } from './bounded-read';\nimport {\n SafeFsError,\n errnoOf,\n toSafeFsError,\n snapshotIdentity,\n sameFile,\n assertExpectedTarget,\n ownerToRestore,\n replacementIdentity,\n} from './safe-fs-policy';\nimport type { AtomicReplaceOptions, AtomicReplaceResult } from './safe-fs';\nimport { formatBytes } from './input-budgets';\nimport { assertNoSymlinkAncestorsAsync, nodeReadFsLayer } from './safe-fs-read';\nimport type { AsyncReadHandle, AsyncReadFsLayer, BoundedAsyncReadFsLayer } from './safe-fs-read';\n\n/** Only the handle operations these readers and writers use. Methods retain their receiver. */\nexport interface AsyncFileHandle extends AsyncReadHandle {\n write(buffer: Uint8Array): Promise<{ bytesWritten: number }>;\n sync(): Promise<void>;\n chmod(mode: number): Promise<void>;\n chown(uid: number, gid: number): Promise<void>;\n}\n\nexport interface AsyncFsLayer extends AsyncReadFsLayer<AsyncFileHandle> {\n /** Resolve on commit; reject only if the rename did not commit. */\n rename(from: string, to: string): Promise<void>;\n unlink(target: string): Promise<void>;\n}\n\nexport const nodeAsyncFsLayer: AsyncFsLayer = {\n open: (target, flags, mode) => fs.open(target, flags, mode),\n lstat: target => fs.lstat(target),\n realpath: target => fs.realpath(target),\n rename: (from, to) => fs.rename(from, to),\n unlink: target => fs.unlink(target),\n};\n\n// Kept at the original module path for existing consumers.\nexport { asyncFsFromSync } from './safe-fs-legacy';\n\n/**\n * Reads under the shared no-follow policy in at most 64 KiB chunks, including growth detection.\n * A supplied adapter owns its read implementation; legacy compatibility may allocate a whole file.\n * Use readContainedFileBounded when the adapter must explicitly promise bounded allocation.\n */\nexport async function readContainedFileAsync(\n root: string,\n rel: string,\n maxBytes: number,\n layer: AsyncReadFsLayer = nodeReadFsLayer,\n signal?: AbortSignal\n): Promise<Buffer> {\n const { handle, stats } = await openContainedFileAsync(root, rel, layer, signal);\n const target = path.join(root, rel);\n const assertSize = (size: number) => {\n if (size > maxBytes)\n throw new SafeFsError(\n 'too-large',\n target,\n `The file is ${formatBytes(size)}, over the ${formatBytes(maxBytes)} limit`\n );\n };\n try {\n assertSize(stats.size);\n let buffer: Buffer = Buffer.alloc(Math.min(stats.size, maxBytes) + 1);\n let filled = 0;\n for (;;) {\n signal?.throwIfAborted();\n const { bytesRead } = await handle.read(\n buffer,\n filled,\n Math.min(buffer.length - filled, 64 * 1024),\n null\n );\n signal?.throwIfAborted();\n filled += bytesRead;\n assertSize(filled);\n if (bytesRead === 0) break;\n if (filled === buffer.length) {\n const next = Buffer.alloc(Math.min(buffer.length * 2, maxBytes + 1));\n buffer.copy(next);\n buffer = next;\n }\n }\n assertSize((await handle.stat()).size);\n signal?.throwIfAborted();\n return buffer.subarray(0, filled);\n } catch (error) {\n signal?.throwIfAborted();\n throw toSafeFsError(error, target, 'read');\n } finally {\n await quietly(() => handle.close());\n signal?.throwIfAborted();\n }\n}\n\n/**\n * Explicit bounded-read capability. Adapter reads must copy only the requested chunk, without\n * whole-file allocation. Cancellation is checked between calls; in-flight I/O is not preempted.\n */\nexport function readContainedFileBounded(\n root: string,\n rel: string,\n maxBytes: number,\n layer: BoundedAsyncReadFsLayer = nodeReadFsLayer,\n signal?: AbortSignal\n): Promise<Buffer> {\n return readContainedFileAsync(root, rel, maxBytes, layer, signal);\n}\n\nexport interface AtomicReplaceAsyncOptions extends Omit<AtomicReplaceOptions, 'fs'> {\n fs?: AsyncFsLayer;\n /** Reject with signal.reason before commit. An abort during a successful rename cannot undo it. */\n signal?: AbortSignal;\n}\n\nasync function quietly(fn: () => Promise<unknown>): Promise<void> {\n try {\n await fn();\n } catch {\n /* Cleanup must not mask the primary outcome. */\n }\n}\n\nasync function lstatOrNull(target: string, layer: Pick<AsyncFsLayer, 'lstat'>) {\n try {\n return await layer.lstat(target);\n } catch (error) {\n if (errnoOf(error) === 'ENOENT') return null;\n throw toSafeFsError(error, target, 'inspect');\n }\n}\n\nasync function inspectTarget(target: string, layer: Pick<AsyncFsLayer, 'lstat'>) {\n const stats = await lstatOrNull(target, layer);\n return stats === null ? null : replacementIdentity(target, stats);\n}\n\n/** No-follow open, followed by descriptor/name/physical-containment checks. Caller owns close. */\nexport function openContainedFileAsync<H extends AsyncReadHandle>(\n root: string,\n rel: string,\n layer: AsyncReadFsLayer<H>,\n signal?: AbortSignal\n): Promise<{ handle: H; stats: Stats }>;\nexport function openContainedFileAsync(\n root: string,\n rel: string,\n layer?: Pick<AsyncFsLayer, 'open' | 'lstat' | 'realpath'>,\n signal?: AbortSignal\n): Promise<{ handle: AsyncFileHandle; stats: Stats }>;\nexport async function openContainedFileAsync(\n root: string,\n rel: string,\n layer: AsyncReadFsLayer = nodeAsyncFsLayer,\n signal?: AbortSignal\n): Promise<{ handle: AsyncReadHandle; stats: Stats }> {\n signal?.throwIfAborted();\n await assertNoSymlinkAncestorsAsync(root, rel, layer, signal);\n signal?.throwIfAborted();\n const target = path.join(root, rel);\n const handle = await layer.open(target, READ_FLAGS | constants.O_NOFOLLOW).catch(error => {\n signal?.throwIfAborted();\n throw toSafeFsError(error, target, 'open');\n });\n try {\n signal?.throwIfAborted();\n const stats = await handle.stat();\n signal?.throwIfAborted();\n if (stats.isDirectory())\n throw new SafeFsError('output-is-directory', target, `${target} is a directory`);\n if (!stats.isFile())\n throw new SafeFsError('not-regular', target, `${target} is not a regular file`);\n const named = await layer.lstat(target);\n signal?.throwIfAborted();\n const physical = await layer.realpath(target);\n signal?.throwIfAborted();\n const physicalRoot = await layer.realpath(root);\n signal?.throwIfAborted();\n if (!sameFile(named, stats) || physical !== path.join(physicalRoot, rel)) {\n throw new SafeFsError('unsafe-link', target, `${target} changed while it was being opened`);\n }\n return { handle, stats };\n } catch (error) {\n await quietly(() => handle.close());\n signal?.throwIfAborted();\n throw toSafeFsError(error, target, 'open');\n }\n}\n\nasync function writeStagedFile(\n temp: string,\n bytes: Uint8Array,\n layer: Pick<AsyncFsLayer, 'open' | 'lstat' | 'unlink'>,\n options: AtomicReplaceAsyncOptions,\n exactMode: number | undefined,\n exactOwner: { uid: number; gid: number } | undefined\n) {\n options.signal?.throwIfAborted();\n const byteLength = bytes.byteLength;\n const assertLength = () => {\n if (bytes.byteLength !== byteLength)\n throw new SafeFsError(\n 'io-error',\n temp,\n `Cannot write ${temp}: the source buffer changed size`\n );\n };\n let handle: AsyncFileHandle;\n try {\n handle = await layer.open(\n temp,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n 0o666\n );\n } catch (error) {\n if (errnoOf(error) === 'EEXIST' && (await lstatOrNull(temp, layer))?.isSymbolicLink()) {\n throw new SafeFsError(\n 'unsafe-link',\n temp,\n `Refusing to write ${temp}: a symbolic link already sits at that name`\n );\n }\n throw toSafeFsError(error, temp, 'create');\n }\n try {\n let offset = 0;\n assertLength();\n while (offset < byteLength) {\n options.signal?.throwIfAborted();\n assertLength();\n const { bytesWritten } = await handle.write(bytes.subarray(offset, offset + 64 * 1024));\n if (bytesWritten <= 0)\n throw new SafeFsError('io-error', temp, `Cannot write ${temp}: write made no progress`);\n offset += bytesWritten;\n }\n assertLength();\n if (exactOwner !== undefined) {\n try {\n await handle.chown(exactOwner.uid, exactOwner.gid);\n } catch (error) {\n throw new SafeFsError('unsupported-target', temp, `Cannot give ${temp} its owner`, error);\n }\n }\n if (exactMode !== undefined) await handle.chmod(exactMode);\n await handle.sync();\n options.signal?.throwIfAborted();\n const identity = snapshotIdentity(await handle.stat());\n await handle.close();\n return identity;\n } catch (error) {\n await quietly(() => handle.close());\n await quietly(() => layer.unlink(temp));\n throw error;\n }\n}\n\n/** Create, sync and close one unique no-follow asset, removing it on any pre-commit failure. */\nexport async function writeExclusiveNoFollowAsync(\n target: string,\n bytes: Uint8Array,\n options: Pick<AtomicReplaceAsyncOptions, 'fs' | 'signal'> = {}\n) {\n return writeStagedFile(\n target,\n bytes,\n options.fs ?? nodeAsyncFsLayer,\n options,\n undefined,\n undefined\n );\n}\n\n/**\n * Atomic replacement with bounded write chunks and cancellation before rename. The last target\n * check follows staging/fsync. As in atomicReplace, a portable path-check/rename race remains;\n * size/mtime are modification stamps, not a content hash or compare-and-swap guarantee.\n * Once rename succeeds, cleanup and directory sync cannot convert success into refusal.\n */\nexport async function atomicReplaceAsync(\n target: string,\n bytes: Uint8Array,\n options: AtomicReplaceAsyncOptions = {}\n): Promise<AtomicReplaceResult> {\n const layer = options.fs ?? nodeAsyncFsLayer;\n options.signal?.throwIfAborted();\n const parent = await layer.realpath(path.dirname(target)).catch(error => {\n options.signal?.throwIfAborted();\n throw toSafeFsError(error, target, 'resolve parent');\n });\n const existing = await inspectTarget(target, layer);\n assertExpectedTarget(target, existing, options);\n const owner = options.preserveOwner && existing ? ownerToRestore(target, existing) : undefined;\n const random = options.randomName ?? (() => randomBytes(6).toString('hex'));\n const temp = path.join(path.dirname(target), `.${path.basename(target)}.${random()}.tmp`);\n let identity;\n try {\n identity = await writeStagedFile(\n temp,\n bytes,\n layer,\n options,\n options.preserveMode && existing ? existing.mode : undefined,\n owner\n );\n } catch (error) {\n options.signal?.throwIfAborted();\n // Match the sync writer's target-oriented errors while retaining a planted temp-link path.\n const safe = toSafeFsError(error, target, 'write');\n if (safe.code === 'unsupported-target')\n throw new SafeFsError(\n 'unsupported-target',\n target,\n `Refusing to replace ${target}: its owner could not be preserved on the replacement`,\n safe.cause\n );\n if (safe.code !== 'unsafe-link' && safe.cause !== undefined)\n throw toSafeFsError(safe.cause, target, 'write');\n throw safe;\n }\n try {\n if ((await layer.realpath(path.dirname(target))) !== parent) {\n throw new SafeFsError(\n 'identity-changed',\n target,\n `Refusing to replace ${target}: its parent directory moved`\n );\n }\n assertExpectedTarget(target, await inspectTarget(target, layer), options);\n options.signal?.throwIfAborted();\n options.beforeCommit?.();\n options.signal?.throwIfAborted();\n await layer.rename(temp, target);\n } catch (error) {\n await quietly(() => layer.unlink(temp));\n options.signal?.throwIfAborted();\n throw toSafeFsError(error, target, 'replace');\n }\n await quietly(async () => {\n const directory = await layer.open(path.dirname(target), constants.O_RDONLY);\n try {\n await directory.sync();\n } finally {\n await quietly(() => directory.close());\n }\n });\n return { identity, replaced: existing !== null };\n}\n","// packages/core/src/safe-fs.ts\n// No-follow filesystem primitives every core reader and writer goes through. Linux and macOS only:\n// Node does not define `O_NOFOLLOW` on Windows.\n\nimport * as nodeFs from 'node:fs';\nimport { randomBytes } from 'node:crypto';\nimport * as path from 'node:path';\nimport { READ_FLAGS } from './bounded-read';\nimport { asyncFsFromSync, readContainedFileAsync } from './safe-fs-async';\nimport type { AsyncFsLayer } from './safe-fs-async';\nimport type { BoundedAsyncReadFsLayer } from './safe-fs-read';\n\nimport {\n SafeFsError,\n errnoOf,\n toSafeFsError,\n guarded,\n snapshotIdentity,\n sameFile,\n assertExpectedTarget,\n ownerToRestore,\n replacementIdentity,\n} from './safe-fs-policy';\nimport type { FileIdentity } from './safe-fs-policy';\nexport {\n SafeFsError,\n errnoOf,\n toSafeFsError,\n guarded,\n snapshotIdentity,\n sameFile,\n sameStamp,\n classifyFsError,\n} from './safe-fs-policy';\nexport type { SafeFsErrorCode, FileIdentity } from './safe-fs-policy';\n\n/** The subset of `fs` used here, synchronous so a test can inject a failure at an exact step. */\nexport interface FsLayer {\n /** Optional asynchronous capabilities over this same filesystem. Never inferred for wrappers. */\n asyncFs?: AsyncFsLayer;\n /** Advisory writability probe. Legacy adapters use their own directory stats and permission bits. */\n accessSync?(path: string, mode: number): void;\n /** Bounded descriptor reads. Legacy adapters retain their readFileSync compatibility path. */\n readSync?(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number | null\n ): number;\n openSync(path: string, flags: number, mode?: number): number;\n /** May write fewer bytes than given, as the real one may. */\n writeSync(fd: number, buffer: Uint8Array): number;\n fsyncSync(fd: number): void;\n fchmodSync(fd: number, mode: number): void;\n fchownSync(fd: number, uid: number, gid: number): void;\n closeSync(fd: number): void;\n renameSync(from: string, to: string): void;\n unlinkSync(path: string): void;\n lstatSync(path: string): nodeFs.Stats;\n fstatSync(fd: number): nodeFs.Stats;\n readFileSync(fd: number): Buffer;\n mkdirSync(path: string, mode: number): void;\n realpathSync(path: string): string;\n}\n\nexport const nodeFsLayer: FsLayer = {\n accessSync: (target, mode) => nodeFs.accessSync(target, mode),\n readSync: (fd, buffer, offset, length, position) =>\n nodeFs.readSync(fd, buffer, offset, length, position),\n openSync: (p, flags, mode) => nodeFs.openSync(p, flags, mode),\n writeSync: (fd, buffer) => nodeFs.writeSync(fd, buffer),\n fsyncSync: fd => nodeFs.fsyncSync(fd),\n fchmodSync: (fd, mode) => nodeFs.fchmodSync(fd, mode),\n fchownSync: (fd, uid, gid) => nodeFs.fchownSync(fd, uid, gid),\n closeSync: fd => nodeFs.closeSync(fd),\n renameSync: (from, to) => nodeFs.renameSync(from, to),\n unlinkSync: p => nodeFs.unlinkSync(p),\n lstatSync: p => nodeFs.lstatSync(p),\n fstatSync: fd => nodeFs.fstatSync(fd),\n readFileSync: fd => nodeFs.readFileSync(fd),\n mkdirSync: (p, mode) => {\n nodeFs.mkdirSync(p, { mode });\n },\n realpathSync: p => nodeFs.realpathSync(p),\n};\n\nconst { O_WRONLY, O_CREAT, O_EXCL, O_NOFOLLOW, O_RDONLY } = nodeFs.constants;\n\n/** Best effort: a failure here is not worth reporting over the one in flight. */\nfunction quietly(fn: () => void): void {\n try {\n fn();\n } catch {\n // Ignored.\n }\n}\n\nexport function lstatOrNull(\n filePath: string,\n fs: Pick<FsLayer, 'lstatSync'> = nodeFsLayer\n): nodeFs.Stats | null {\n try {\n return fs.lstatSync(filePath);\n } catch (error) {\n if (errnoOf(error) === 'ENOENT') return null;\n throw toSafeFsError(error, filePath, 'inspect');\n }\n}\n\n/**\n * Refuse a `rel` whose directories under `root` include a symlink. The leaf is the caller's\n * policy, and a missing component ends the walk: nothing can be linked where nothing is.\n */\nexport function assertNoSymlinkAncestors(\n root: string,\n rel: string,\n fs: Pick<FsLayer, 'lstatSync'> = nodeFsLayer\n) {\n const normalized = path.normalize(rel);\n if (\n path.isAbsolute(normalized) ||\n normalized === '..' ||\n normalized.startsWith(`..${path.sep}`)\n ) {\n throw new SafeFsError(\n 'unsupported-target',\n path.join(root, rel),\n `Refusing ${rel}: it does not stay under ${root}`\n );\n }\n let current = root;\n for (const segment of path.dirname(normalized).split(path.sep)) {\n if (!segment || segment === '.') continue;\n current = path.join(current, segment);\n const stats = lstatOrNull(current, fs);\n if (stats === null) return;\n if (stats.isSymbolicLink()) {\n throw new SafeFsError(\n 'unsafe-link',\n current,\n `Refusing to go through ${current}: it is a symbolic link`\n );\n }\n }\n}\n\n/**\n * No link on the way or at the leaf, no FIFO blocking, regular files only. The walk and the open are\n * separate syscalls, so afterwards the name must still resolve under `root` to the opened inode.\n */\nexport function openContainedFile(\n root: string,\n rel: string,\n fs: Pick<\n FsLayer,\n 'lstatSync' | 'openSync' | 'fstatSync' | 'realpathSync' | 'closeSync'\n > = nodeFsLayer\n): { fd: number; stats: nodeFs.Stats } {\n assertNoSymlinkAncestors(root, rel, fs);\n const target = path.join(root, rel);\n const fd = guarded(target, 'open', () => fs.openSync(target, READ_FLAGS | O_NOFOLLOW));\n try {\n const stats = fs.fstatSync(fd);\n if (stats.isDirectory()) {\n throw new SafeFsError('output-is-directory', target, `${target} is a directory`);\n }\n if (!stats.isFile()) {\n throw new SafeFsError('not-regular', target, `${target} is not a regular file`);\n }\n if (\n !sameFile(fs.lstatSync(target), stats) ||\n fs.realpathSync(target) !== path.join(fs.realpathSync(root), rel)\n ) {\n throw new SafeFsError('unsafe-link', target, `${target} changed while it was being opened`);\n }\n return { fd, stats };\n } catch (error) {\n quietly(() => fs.closeSync(fd));\n throw toSafeFsError(error, target, 'open');\n }\n}\n\n/** Read the whole of a file {@link openContainedFile} accepts, if it fits `maxBytes`. */\nexport async function readContainedFile(\n root: string,\n rel: string,\n maxBytes: number,\n options: { fs?: FsLayer; readFs?: BoundedAsyncReadFsLayer; signal?: AbortSignal } = {}\n): Promise<Buffer> {\n const layer = options.fs;\n return readContainedFileAsync(\n root,\n rel,\n maxBytes,\n options.readFs ??\n (layer === undefined || layer === nodeFsLayer\n ? undefined\n : asyncFsFromSync(layer, options.signal)),\n options.signal\n );\n}\n\ntype ExclusiveFs = Pick<\n FsLayer,\n | 'openSync'\n | 'writeSync'\n | 'fsyncSync'\n | 'fchmodSync'\n | 'fchownSync'\n | 'closeSync'\n | 'unlinkSync'\n | 'fstatSync'\n | 'lstatSync'\n>;\n\nexport interface WriteExclusiveOptions {\n /** Masked by the umask. Default 0o666. */\n mode?: number;\n /** Applied after creation, bypassing the umask. */\n exactMode?: number;\n /** Applied after creation; failing to is `unsupported-target` and removes the file. */\n exactOwner?: { uid: number; gid: number };\n fs?: ExclusiveFs;\n}\n\n/**\n * Create `filePath`, which must not exist, write every byte and sync. A symlink at the path,\n * dangling or not, is `unsafe-link`. Any failure after creation removes the file again.\n */\nexport function writeExclusiveNoFollow(\n filePath: string,\n bytes: Uint8Array,\n options: WriteExclusiveOptions = {}\n): FileIdentity {\n const fs = options.fs ?? nodeFsLayer;\n let fd: number;\n try {\n fd = fs.openSync(filePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, options.mode ?? 0o666);\n } catch (error) {\n if (errnoOf(error) === 'EEXIST' && isSymlink(filePath, fs)) {\n throw new SafeFsError(\n 'unsafe-link',\n filePath,\n `Refusing to write ${filePath}: a symbolic link already sits at that name`\n );\n }\n throw toSafeFsError(error, filePath, 'create');\n }\n\n try {\n let offset = 0;\n while (offset < bytes.length) {\n const written = fs.writeSync(fd, bytes.subarray(offset));\n if (written <= 0) {\n throw new SafeFsError(\n 'io-error',\n filePath,\n `Cannot write ${filePath}: write made no progress`\n );\n }\n offset += written;\n }\n if (options.exactOwner !== undefined) {\n const { uid, gid } = options.exactOwner;\n try {\n fs.fchownSync(fd, uid, gid);\n } catch (error) {\n throw new SafeFsError(\n 'unsupported-target',\n filePath,\n `Cannot give ${filePath} its owner (uid ${uid}, gid ${gid})`,\n error\n );\n }\n }\n if (options.exactMode !== undefined) fs.fchmodSync(fd, options.exactMode);\n fs.fsyncSync(fd);\n const identity = snapshotIdentity(fs.fstatSync(fd));\n fs.closeSync(fd);\n return identity;\n } catch (error) {\n quietly(() => fs.closeSync(fd));\n unlinkQuietly(filePath, fs);\n throw toSafeFsError(error, filePath, 'write');\n }\n}\n\nexport interface AtomicReplaceOptions {\n /** Give the replacement the replaced file's permission bits. */\n preserveMode?: boolean;\n /**\n * Give the replacement the replaced file's owner (`rename` swaps the inode). An owner this\n * process may not restore with `fchown` is refused as `unsupported-target` before any write.\n */\n preserveOwner?: boolean;\n /** Refused as `identity-changed` when the target is no longer this file (dev/ino). */\n expectedIdentity?: FileIdentity;\n /** With `expectedIdentity`: also refuse a same-inode rewrite (size or mtime moved). */\n expectUnmodified?: boolean;\n fs?: ExclusiveFs & Pick<FsLayer, 'renameSync' | 'realpathSync'>;\n randomName?: () => string;\n /** Synchronous authorization check immediately before rename. A throw removes staging. */\n beforeCommit?: () => void;\n}\n\nexport interface AtomicReplaceResult {\n identity: FileIdentity;\n /** Whether a file existed at `target` before. */\n replaced: boolean;\n}\n\n/**\n * Replace or create `target` in one rename from a same-directory temp file. The final target\n * check follows staging, including fsync, and checks dev/ino plus size/mtime when requested.\n * A same-size rewrite within timestamp granularity can pass. This is not compare-and-swap:\n * another process can still change the path between the last check and rename. Rename replaces\n * the named entry rather than following a leaf link; callers must secure ancestor directories.\n */\nexport function atomicReplace(\n target: string,\n bytes: Uint8Array,\n options: AtomicReplaceOptions = {}\n): AtomicReplaceResult {\n const fs = options.fs ?? nodeFsLayer;\n const parent = guarded(target, 'resolve parent', () => fs.realpathSync(path.dirname(target)));\n const existing = inspectReplaceTarget(target, fs);\n assertExpectedTarget(target, existing, options);\n const exactOwner =\n options.preserveOwner && existing ? ownerToRestore(target, existing) : undefined;\n\n const random = options.randomName ?? defaultRandomName;\n const temp = path.join(path.dirname(target), `.${path.basename(target)}.${random()}.tmp`);\n let identity: FileIdentity;\n try {\n identity = writeExclusiveNoFollow(temp, bytes, {\n fs,\n exactMode: options.preserveMode && existing ? existing.mode : undefined,\n exactOwner,\n });\n } catch (error) {\n // Report the target, not the temp name, unless a link was planted at the temp name.\n if (error instanceof SafeFsError && error.code === 'unsupported-target') {\n throw new SafeFsError(\n 'unsupported-target',\n target,\n `Refusing to replace ${target}: its owner could not be preserved on the replacement`,\n error.cause\n );\n }\n if (error instanceof SafeFsError && error.code !== 'unsafe-link' && error.cause !== undefined) {\n throw toSafeFsError(error.cause, target, 'write');\n }\n throw error;\n }\n try {\n if (fs.realpathSync(path.dirname(target)) !== parent) {\n throw new SafeFsError(\n 'identity-changed',\n target,\n `Refusing to replace ${target}: its parent directory moved`\n );\n }\n assertExpectedTarget(target, inspectReplaceTarget(target, fs), options);\n options.beforeCommit?.();\n } catch (error) {\n unlinkQuietly(temp, fs);\n throw toSafeFsError(error, target, 'replace');\n }\n finishReplace(temp, target, fs);\n return { identity, replaced: existing !== null };\n}\n\nfunction finishReplace(\n temp: string,\n target: string,\n fs: Pick<FsLayer, 'renameSync' | 'unlinkSync' | 'openSync' | 'fsyncSync' | 'closeSync'>\n): void {\n try {\n fs.renameSync(temp, target);\n } catch (error) {\n unlinkQuietly(temp, fs);\n throw toSafeFsError(error, target, 'replace');\n }\n syncDirectoryQuietly(path.dirname(target), fs);\n // Rename commits the inode we already inspected. No fallible work may follow it.\n}\n\n/** `lstat` a replace target under the policy of {@link atomicReplace}; null when absent. */\nexport function inspectReplaceTarget(\n target: string,\n fs: Pick<FsLayer, 'lstatSync'> = nodeFsLayer\n): FileIdentity | null {\n const stats = lstatOrNull(target, fs);\n if (stats === null) return null;\n return replacementIdentity(target, stats);\n}\n\nexport function defaultRandomName(): string {\n return randomBytes(6).toString('hex');\n}\n\nfunction isSymlink(filePath: string, fs: Pick<FsLayer, 'lstatSync'>): boolean {\n try {\n return fs.lstatSync(filePath).isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport function unlinkQuietly(\n filePath: string,\n fs: Pick<FsLayer, 'unlinkSync'> = nodeFsLayer\n): void {\n quietly(() => fs.unlinkSync(filePath));\n}\n\n/** Linux needs a directory fsync for a rename to survive a crash; macOS may refuse it (EINVAL). */\nfunction syncDirectoryQuietly(\n dir: string,\n fs: Pick<FsLayer, 'openSync' | 'fsyncSync' | 'closeSync'>\n): void {\n quietly(() => {\n const fd = fs.openSync(dir, O_RDONLY);\n try {\n fs.fsyncSync(fd);\n } finally {\n quietly(() => fs.closeSync(fd));\n }\n });\n}\n","// Default Node wiring for source reads and directory scans.\nimport { opendir, stat, readlink } from 'fs/promises';\nimport { nodeReadFsLayer } from './safe-fs-read';\nimport type { ScanFsLayer } from './scan-fs';\n\nexport const nodeScanFsLayer: ScanFsLayer = {\n ...nodeReadFsLayer,\n stat: target => stat(target),\n opendir: target => opendir(target),\n readlink: target => readlink(target, { encoding: 'buffer' }),\n};\n","// Publication's filesystem roles. Supplied providers own every path and descriptor operation.\nimport { mkdir } from 'node:fs/promises';\nimport type { FsLayer } from './safe-fs';\nimport { nodeFsLayer } from './safe-fs';\nimport { asyncFsFromSync, nodeAsyncFsLayer } from './safe-fs-async';\nimport type { AsyncFsLayer } from './safe-fs-async';\n\n/** Read-only synchronous policy probes, also used by the advisory inspectOutputPath API. */\nexport type PublicationInspection = Pick<FsLayer, 'lstatSync' | 'realpathSync' | 'accessSync'>;\n\n/**\n * Explicit publication effects for native wrappers and virtual filesystems. All roles must refer\n * to the same filesystem. Handle reads copy at most the requested length; writes may be partial.\n * Inspection stays synchronous for inspectOutputPath; file I/O and directory creation are awaited.\n * No absent method is filled from the host filesystem. Methods retain their receiver.\n */\nexport interface PublicationFileSystem {\n inspection: PublicationInspection;\n files: AsyncFsLayer;\n mkdir(target: string, mode: number): Promise<void>;\n currentUid(): number | undefined;\n}\n\nexport const nodePublicationFileSystem: PublicationFileSystem = {\n inspection: nodeFsLayer,\n files: nodeAsyncFsLayer,\n mkdir: async (target, mode) => {\n await mkdir(target, { mode });\n },\n currentUid: () => process.getuid?.(),\n};\n\n/**\n * The sole legacy boundary. Old adapters and handles need no new members. Without readSync their\n * readFileSync may allocate the entire file and cannot be interrupted during that syscall; the\n * reader retains pre/post size checks. An explicit role takes precedence over legacy fs.\n */\nexport function resolvePublicationFileSystem(options: {\n publicationFs?: PublicationFileSystem;\n fs?: FsLayer;\n signal?: AbortSignal;\n}): PublicationFileSystem {\n if (options.publicationFs) return options.publicationFs;\n const legacy = options.fs;\n // Preserve explicit native callers' existing asynchronous I/O. Keep this exception\n // at the legacy boundary; inferring it for wrappers could bypass a virtual provider.\n if (!legacy || legacy === nodeFsLayer) return nodePublicationFileSystem;\n return {\n inspection: legacy,\n files: asyncFsFromSync(legacy, options.signal),\n async mkdir(target, mode) {\n legacy.mkdirSync(target, mode);\n },\n currentUid: () => process.getuid?.(),\n };\n}\n","// The temporary clone owner supplies creation and both lifetime-specific removal operations.\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\n\n/** Owns only the directory it creates. Removal is mandatory even after cancellation. */\nexport interface TemporaryCloneStorage {\n create(): Promise<string>;\n remove(directory: string): Promise<void>;\n removeSync(directory: string): void;\n}\n\nexport const nodeTemporaryCloneStorage: TemporaryCloneStorage = {\n create: () => fs.promises.mkdtemp(path.join(os.tmpdir(), 'self-review-')),\n remove: directory => fs.promises.rm(directory, { recursive: true, force: true }),\n removeSync: directory => fs.rmSync(directory, { recursive: true, force: true }),\n};\n","// Shared bounded process execution. Resources belong to one call; cancellation settles only\n// after its owned process tree has terminated. Text adapters and binary blob reads share the same lifetime.\nimport { spawn } from 'child_process';\nimport { terminateProcessTree } from './process-tree';\nimport { CommandCancelledError } from './forge-provider';\nimport type {\n CommandCancelReason,\n ForgeCommandOptions,\n ForgeCommandRunner,\n} from './forge-provider';\n\nexport interface BufferedCommandResult {\n stdout: Buffer;\n stderr: Buffer;\n exitCode: number;\n}\n\n/** Same completion, interruption and output-bound contract as ForgeCommandRunner, with raw bytes. */\nexport type BufferedCommandRunner = (\n command: string,\n args: string[],\n options?: ForgeCommandOptions\n) => Promise<BufferedCommandResult>;\n\nconst KILL_GRACE_MS = 2_000;\nconst MAX_OUTPUT_BYTES = 50 * 1024 * 1024;\n\nexport class CommandOutputLimitError extends Error {\n readonly code = 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER';\n constructor(command: string, maxBytes: number) {\n super(`${command} produced more than ${maxBytes} bytes`);\n this.name = 'CommandOutputLimitError';\n }\n}\n\n// Explicit repository targets outrank the surrounding hook's repository location. Keep\n// credential/configuration variables and GIT_INDEX_FILE, which can intentionally select\n// the index used by a partial commit.\nexport function repositoryEnvironment(isolated = false): NodeJS.ProcessEnv {\n const env = { ...process.env };\n for (const key of ['GIT_DIR', 'GIT_COMMON_DIR', 'GIT_WORK_TREE', 'GIT_PREFIX']) delete env[key];\n if (isolated) {\n for (const key of [\n 'GIT_INDEX_FILE',\n 'GIT_OBJECT_DIRECTORY',\n 'GIT_ALTERNATE_OBJECT_DIRECTORIES',\n 'GIT_NAMESPACE',\n 'GIT_CEILING_DIRECTORIES',\n 'GIT_SHALLOW_FILE',\n 'GIT_IMPLICIT_WORK_TREE',\n ])\n delete env[key];\n }\n return env;\n}\n\n/**\n * Default runner: spawns the real binary. Rejects on spawn failure, on output over\n * the buffer cap, and with {@link CommandCancelledError} on abort or timeout (SIGTERM,\n * then SIGKILL after {@link KILL_GRACE_MS}; settles once the owned tree terminated).\n *\n * Deliberately not in its own process group: that would detach the controlling\n * terminal and silently disable git's and ssh's credential prompts.\n */\nexport const runBufferedCommand: BufferedCommandRunner = (command, args, options = {}) =>\n new Promise<BufferedCommandResult>((resolve, reject) => {\n const { signal, timeoutMs } = options;\n if (signal?.aborted) {\n reject(new CommandCancelledError('aborted', command, args));\n return;\n }\n\n const maxOutputBytes = options.maxOutputBytes ?? MAX_OUTPUT_BYTES;\n if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0) {\n reject(new RangeError('maxOutputBytes must be a nonnegative safe integer'));\n return;\n }\n if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs < 0)) {\n reject(new RangeError('timeoutMs must be a nonnegative finite number'));\n return;\n }\n const child = spawn(command, args, {\n stdio: ['ignore', 'pipe', 'pipe'],\n cwd: options.cwd,\n env:\n command === 'git' &&\n (options.gitEnvironment === 'isolated' || options.cwd !== undefined || args.includes('-C'))\n ? repositoryEnvironment(options.gitEnvironment === 'isolated')\n : undefined,\n });\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n let outputBytes = 0;\n let settled = false;\n let cancelled: CommandCancelReason | null = null;\n let overflowed = false;\n let termination: Promise<void> | undefined;\n let timeoutTimer: NodeJS.Timeout | undefined;\n\n const killChild = () => {\n termination ??= terminateProcessTree(child, KILL_GRACE_MS);\n const closePipes = () => {\n child.stdout?.destroy();\n child.stderr?.destroy();\n };\n // A discovery/termination failure must also settle within the shutdown bound.\n // Known processes have been killed by the tree owner before it rejects.\n void termination.then(\n // A naturally exited parent can leave inherited pipes in a reparented helper.\n // Pipe closure must not hold cancellation open after tree shutdown settles.\n closePipes,\n error => {\n closePipes();\n settle(() => reject(error));\n }\n );\n };\n const cancel = (reason: CommandCancelReason) => {\n if (settled || cancelled !== null) return;\n cancelled = reason;\n killChild();\n };\n const onAbort = () => cancel('aborted');\n signal?.addEventListener('abort', onAbort, { once: true });\n if (timeoutMs !== undefined && timeoutMs > 0) {\n timeoutTimer = setTimeout(() => cancel('timeout'), timeoutMs);\n }\n\n const settle = (outcome: () => void) => {\n if (settled) return;\n settled = true;\n if (timeoutTimer) clearTimeout(timeoutTimer);\n signal?.removeEventListener('abort', onAbort);\n outcome();\n };\n\n const collect = (sink: Buffer[]) => (chunk: Buffer) => {\n outputBytes += chunk.length;\n if (outputBytes > maxOutputBytes) {\n if (!overflowed) {\n overflowed = true;\n killChild();\n }\n return;\n }\n sink.push(chunk);\n };\n child.stdout?.on('data', collect(stdout));\n child.stderr?.on('data', collect(stderr));\n\n child.on('error', error => settle(() => reject(error)));\n\n child.on('close', async (code, exitSignal) => {\n try {\n await termination;\n } catch (error) {\n settle(() => reject(error));\n return;\n }\n settle(() => {\n if (cancelled !== null) {\n reject(new CommandCancelledError(cancelled, command, args));\n return;\n }\n if (overflowed) {\n reject(new CommandOutputLimitError(command, maxOutputBytes));\n return;\n }\n let stderrBytes = Buffer.concat(stderr);\n if (code === null && exitSignal) {\n const separator =\n stderrBytes.length === 0 || stderrBytes[stderrBytes.length - 1] === 10 ? '' : '\\n';\n stderrBytes = Buffer.concat([\n stderrBytes,\n Buffer.from(`${separator}(killed by ${exitSignal})\\n`),\n ]);\n }\n resolve({\n stdout: Buffer.concat(stdout),\n stderr: stderrBytes,\n exitCode: code ?? 1,\n });\n });\n });\n });\n\n/** Text view for forge commands and diff metadata. The byte limit is applied before decoding. */\nexport const defaultGitRunner: ForgeCommandRunner = async (command, args, options) => {\n const result = await runBufferedCommand(command, args, options);\n return {\n stdout: result.stdout.toString('utf-8'),\n stderr: result.stderr.toString('utf-8'),\n exitCode: result.exitCode,\n };\n};\n","// POSIX process ownership for bounded commands. Keep the controlling terminal: discover\n// descendants by parent PID instead of putting the command in a detached process group.\nimport { execFile, type ChildProcess } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport { setTimeout as delay } from 'node:timers/promises';\n\ninterface ProcessIdentity {\n pid: number;\n parent: number;\n state: string;\n birth: string;\n}\n\nasync function snapshot(): Promise<ProcessIdentity[]> {\n const output = await new Promise<string>((resolve, reject) => {\n execFile(\n 'ps',\n ['-axo', 'pid=,ppid=,stat=,lstart='],\n { encoding: 'utf8', timeout: 1_000, maxBuffer: 8 * 1024 * 1024 },\n (error, stdout) => (error ? reject(error) : resolve(stdout))\n );\n });\n return output.split('\\n').flatMap(line => {\n const match = /^\\s*(\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(.+)$/.exec(line);\n return match\n ? [{ pid: Number(match[1]), parent: Number(match[2]), state: match[3], birth: match[4] }]\n : [];\n });\n}\n\n// Linux's start ticks distinguish PID reuse even within one second. macOS ps supplies\n// the process start date; retain it and drop identities as soon as they disappear.\nasync function linuxBirth(pid: number): Promise<string> {\n const stat = await readFile(`/proc/${pid}/stat`, 'utf8');\n return stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19];\n}\n\n/**\n * Freeze the parent before discovering its children, then freeze each discovered generation.\n * This closes the fork-during-traversal window without severing terminal credential prompts.\n * TERM gets a grace period; KILL and exit observation also have a bounded deadline.\n */\nexport async function terminateProcessTree(child: ChildProcess, graceMs: number): Promise<void> {\n if (child.pid === undefined) return;\n child.kill('SIGSTOP');\n const owned = new Map<number, ProcessIdentity>();\n const births = new Map<number, string>();\n const signal = async (entry: ProcessIdentity, name: NodeJS.Signals) => {\n try {\n if (process.platform === 'linux' && (await linuxBirth(entry.pid)) !== births.get(entry.pid)) {\n owned.delete(entry.pid);\n return;\n }\n if (process.platform !== 'linux') {\n const current = (await snapshot()).find(process => process.pid === entry.pid);\n if (!current || current.birth !== entry.birth || current.state.startsWith('Z')) {\n owned.delete(entry.pid);\n return;\n }\n }\n process.kill(entry.pid, name);\n } catch (error) {\n if (\n (error as NodeJS.ErrnoException).code !== 'ESRCH' &&\n (error as NodeJS.ErrnoException).code !== 'ENOENT'\n )\n throw error;\n owned.delete(entry.pid);\n }\n };\n try {\n const discoveryDeadline = Date.now() + 2_000;\n while (true) {\n const processes = await snapshot();\n const added: ProcessIdentity[] = [];\n for (const entry of processes) {\n if (owned.has(entry.pid)) continue;\n if (entry.pid !== child.pid && !owned.has(entry.parent)) continue;\n if (entry.state.startsWith('Z')) continue;\n if (process.platform === 'linux') {\n try {\n births.set(entry.pid, await linuxBirth(entry.pid));\n } catch {\n continue;\n } // Exited before discovery; it cannot receive a signal.\n }\n owned.set(entry.pid, entry);\n added.push(entry);\n await signal(entry, 'SIGSTOP');\n }\n if (added.length === 0) break;\n if (Date.now() >= discoveryDeadline) throw new Error('Process tree discovery timed out');\n }\n\n // Leaves first gives parents a chance to reap their children before they exit.\n for (const entry of [...owned.values()].reverse()) await signal(entry, 'SIGTERM');\n for (const entry of [...owned.values()].reverse()) await signal(entry, 'SIGCONT');\n const killAt = Date.now() + graceMs;\n const deadline = killAt + 2_000;\n while (owned.size > 0) {\n const current = new Map((await snapshot()).map(entry => [entry.pid, entry]));\n for (const entry of owned.values()) {\n const live = current.get(entry.pid);\n if (!live || live.birth !== entry.birth || live.state.startsWith('Z')) {\n owned.delete(entry.pid);\n } else if (Date.now() >= killAt) {\n await signal(entry, 'SIGKILL');\n }\n }\n if (owned.size === 0) return;\n if (Date.now() >= deadline) throw new Error('Command process tree did not terminate');\n await delay(25);\n }\n } finally {\n // Also unfreeze/terminate the direct child if discovery itself failed.\n child.kill('SIGKILL');\n for (const entry of owned.values()) await signal(entry, 'SIGKILL');\n }\n}\n","// Load-owned read evidence, separate from the caller's mutable logical source identity.\nimport type { Stats } from 'node:fs';\nimport path from 'node:path';\nimport type { DiffFile, ReviewSourceIdentity } from './types';\nimport type { AsyncReadHandle, BoundedAsyncReadFsLayer } from './safe-fs-read';\nimport { nodeReadFsLayer } from './safe-fs-read';\nimport { SafeFsError } from './safe-fs-policy';\nimport { checkLoadingCancelled } from './local-loading-lifetime';\n\n// Legacy bridge for old loader + three-argument commit/read callers. This evidence belongs only\n// to this exact identity object: spreading or serializing logical identity loses it. New hosts\n// carry LoadedReview separately. Both symbols work across bundled root/operations entry points.\nconst SNAPSHOT = Symbol.for('@self-review/core/loaded-snapshot');\nconst CAPTURE = Symbol.for('@self-review/core/source-capture');\nexport const RELOAD_REVIEW =\n 'The reviewed source changed or could not be captured. Reload the review before reading more content.';\n\nexport function sourceStamp(stats: Stats): string {\n return [stats.dev, stats.ino, stats.mode, stats.size, stats.mtimeMs, stats.ctimeMs].join(':');\n}\n\nexport interface PhysicalCapture {\n readonly target: string;\n readonly stamp: string;\n readonly readFs: BoundedAsyncReadFsLayer;\n}\n\nexport interface IndexCapture {\n readonly target: string;\n readonly stamp: string | null;\n readonly readFs: BoundedAsyncReadFsLayer;\n}\n\nexport interface LoadedReviewSnapshot {\n readonly identityStamp: string;\n readonly physical: ReadonlyMap<string, PhysicalCapture>;\n readonly index: ReadonlyMap<string, string>;\n /** Supplied execution effects stay with the load, including virtual git runners. */\n readonly gitOptions?: import('./git').GitExecutionOptions;\n readonly blobRunner?: import('./command-runner').BufferedCommandRunner;\n readonly indexCapture?: IndexCapture;\n}\n\ntype CapturedIdentity = ReviewSourceIdentity & { [SNAPSHOT]?: LoadedReviewSnapshot };\ntype CapturedFile = DiffFile & { [CAPTURE]?: PhysicalCapture };\n\nexport function identityStamp(identity: ReviewSourceIdentity): string {\n return JSON.stringify([identity, [...(identity.fileSources ?? [])]]);\n}\n\nexport function loadedSnapshot(identity: ReviewSourceIdentity): LoadedReviewSnapshot | undefined {\n return (identity as CapturedIdentity)[SNAPSHOT];\n}\n\nexport function recordLoadedSnapshot(\n identity: ReviewSourceIdentity,\n physical: ReadonlyMap<string, PhysicalCapture>,\n index: ReadonlyMap<string, string> = new Map(),\n gitOptions?: import('./git').GitExecutionOptions,\n blobRunner?: import('./command-runner').BufferedCommandRunner,\n indexCapture?: IndexCapture\n): LoadedReviewSnapshot {\n const snapshot = {\n identityStamp: identityStamp(identity),\n physical,\n index,\n gitOptions,\n blobRunner,\n indexCapture,\n };\n Object.defineProperty(identity, SNAPSHOT, { value: snapshot, configurable: true });\n return snapshot;\n}\n\n// The handle owns no descriptors or source copies. Only this module retains its private evidence.\n// Bundled root/operations aliases share this module; logical and handle copies carry no evidence.\ndeclare const loadedReviewBrand: unique symbol;\n\n/** Opaque host-local load capability. Never include it in XML, IPC or other wire data. */\nexport interface LoadedReview {\n readonly [loadedReviewBrand]: true;\n}\n\ninterface LoadedReviewState {\n readonly identity: ReviewSourceIdentity;\n readonly reviewedPaths: ReadonlySet<string>;\n readonly snapshot: LoadedReviewSnapshot;\n}\n\nconst loadedReviews = new WeakMap<LoadedReview, LoadedReviewState>();\n\n/** Internal constructor: only loaders that observed the source can issue a captured capability. */\nexport function createLoadedReview(\n identity: ReviewSourceIdentity,\n files: readonly DiffFile[],\n snapshot: LoadedReviewSnapshot\n): LoadedReview {\n const paths = new Set(files.flatMap(file => [file.oldPath, file.newPath].filter(Boolean)));\n const state: LoadedReviewState = { identity, reviewedPaths: paths, snapshot };\n const review = Object.freeze({}) as LoadedReview;\n loadedReviews.set(review, state);\n return review;\n}\n\n/** Internal projection: filtering a payload can narrow, but never widen, its captured membership. */\nexport function restrictLoadedReview(\n review: LoadedReview,\n files: readonly DiffFile[]\n): LoadedReview {\n const state = loadedReviewState(review);\n for (const file of files) {\n for (const filePath of [file.oldPath, file.newPath]) {\n if (filePath && !state.reviewedPaths.has(filePath))\n throw new TypeError('A filtered loaded review cannot add a source path');\n }\n }\n return createLoadedReview(state.identity, files, state.snapshot);\n}\n\n/** Internal evidence access; entry aliases share the private registry through their bundled chunk. */\nexport function loadedReviewState(review: LoadedReview): LoadedReviewState {\n const state = loadedReviews.get(review);\n if (!state) throw new TypeError('Expected an original LoadedReview capability');\n return state;\n}\n\n/** Returns the original mutable logical identity alias, not a copy or captured handle. */\nexport function loadedReviewIdentity(review: LoadedReview): ReviewSourceIdentity {\n return loadedReviewState(review).identity;\n}\n\n/** A defensive membership copy; changing it cannot authorize another captured read. */\nexport function loadedReviewPaths(review: LoadedReview): ReadonlySet<string> {\n return new Set(loadedReviewState(review).reviewedPaths);\n}\n\nexport function recordSourceCapture(file: DiffFile, capture: PhysicalCapture | undefined): void {\n if (capture) Object.defineProperty(file, CAPTURE, { value: capture });\n}\n\nexport function sourceCapture(file: DiffFile): PhysicalCapture | undefined {\n return (file as CapturedFile)[CAPTURE];\n}\n\nexport function admitSyntheticSnapshot(\n identity: ReviewSourceIdentity,\n files: readonly DiffFile[]\n): LoadedReview {\n const physical = new Map<string, PhysicalCapture>();\n for (const file of files) {\n const capture = sourceCapture(file);\n if (capture) physical.set(file.newPath || file.oldPath, capture);\n }\n return createLoadedReview(identity, files, recordLoadedSnapshot(identity, physical));\n}\n\n/**\n * Observes the descriptor actually read by synthetic projection, including binary sniff reads.\n * Size/mtime/ctime/device/inode checks detect ordinary source changes, not hostile timestamp or\n * filesystem forgery. No extra source bytes are read or retained, and no writes are performed.\n */\nexport function captureSourceReads(\n layer: BoundedAsyncReadFsLayer = nodeReadFsLayer,\n signal?: AbortSignal,\n onDrift: 'throw' | 'record' = 'throw'\n): {\n readFs: BoundedAsyncReadFsLayer;\n captures: Map<string, PhysicalCapture>;\n drifted: Set<string>;\n} {\n const captures = new Map<string, PhysicalCapture>();\n const drifted = new Set<string>();\n const readFs: BoundedAsyncReadFsLayer = {\n readAllocation: 'bounded',\n realpath: target => layer.realpath(target),\n lstat: target => layer.lstat(target),\n async open(target, flags, mode) {\n const handle = await layer.open(target, flags, mode);\n let stamp: string;\n let physical: string;\n try {\n checkLoadingCancelled(signal);\n stamp = sourceStamp(await handle.stat());\n physical = await layer.realpath(target);\n checkLoadingCancelled(signal);\n } catch (error) {\n await handle.close();\n throw error;\n }\n const wrapped: AsyncReadHandle = {\n stat: () => handle.stat(),\n read: (buffer, offset, length, position) => handle.read(buffer, offset, length, position),\n async close() {\n try {\n checkLoadingCancelled(signal);\n const after = await handle.stat();\n const named = await layer.lstat(physical);\n checkLoadingCancelled(signal);\n if (\n sourceStamp(after) !== stamp ||\n sourceStamp(named) !== stamp ||\n (await layer.realpath(target)) !== physical\n ) {\n throw new SafeFsError('identity-changed', target, RELOAD_REVIEW);\n }\n captures.set(path.resolve(target), { target: physical, stamp, readFs: layer });\n } catch (error) {\n checkLoadingCancelled(signal);\n drifted.add(path.resolve(target));\n if (onDrift === 'throw')\n throw new SafeFsError('identity-changed', target, RELOAD_REVIEW, error);\n } finally {\n await handle.close();\n }\n },\n };\n return wrapped;\n },\n };\n return { readFs, captures, drifted };\n}\n","// Diagnostic wording/order is independent of source classification and output format.\nimport { formatBytes, type ResolvedSourceBudgets } from './input-budgets';\n\nexport interface SyntheticDiagnosticState {\n representationOmissions: string[];\n representationExhausted?: string;\n tooLarge: string[];\n overTotal: string[];\n unreadable: string[];\n}\n\nexport function syntheticDiagnostics(\n state: SyntheticDiagnosticState,\n budgets: ResolvedSourceBudgets\n): string[] {\n const { representationOmissions, representationExhausted, tooLarge, overTotal, unreadable } =\n state;\n const diagnostics: string[] = [];\n if (representationOmissions.length > 0) {\n diagnostics.push(\n `${countFiles(representationOmissions.length)} listed without content because a representation budget ran out: ${listPaths(representationOmissions)}`\n );\n }\n if (representationExhausted) diagnostics.push(representationExhausted);\n if (tooLarge.length > 0) {\n diagnostics.push(\n `${countFiles(tooLarge.length)} over the ${formatBytes(budgets.maxFileBytes)} per-file ` +\n `read budget ${tooLarge.length === 1 ? 'is' : 'are'} listed without content: ` +\n listPaths(tooLarge)\n );\n }\n if (overTotal.length > 0) {\n diagnostics.push(\n `The ${formatBytes(budgets.maxTotalBytes)} total read budget for this review ran out; ` +\n `${countFiles(overTotal.length)} ${overTotal.length === 1 ? 'is' : 'are'} listed ` +\n `without content: ${listPaths(overTotal)}`\n );\n }\n if (unreadable.length > 0) {\n diagnostics.push(\n `${countFiles(unreadable.length)} could not be read and ` +\n `${unreadable.length === 1 ? 'is' : 'are'} not shown: ${listPaths(unreadable)}`\n );\n }\n\n return diagnostics;\n}\n\n/** Preserve the old parser's empty-hunk separator diagnostic without reparsing patch text. */\nexport function createSeparatorDiagnostics(maxDiagnostics: number) {\n let emptyBeforeNextFile: string | undefined;\n const diagnostics: string[] = [];\n return {\n diagnostics,\n next(filePath: string, lineCount?: number) {\n if (emptyBeforeNextFile !== undefined) {\n if (diagnostics.length < maxDiagnostics)\n diagnostics.push(\n `${emptyBeforeNextFile}: line beyond the counts of hunk @@ -0,0 +1,0 @@: \"\"`\n );\n else if (diagnostics.length === maxDiagnostics)\n diagnostics.push(\n 'Further synthetic separator diagnostics omitted: diagnostic representation budget exceeded.'\n );\n }\n emptyBeforeNextFile = lineCount === 0 ? filePath : undefined;\n },\n };\n}\n\nexport function overTotalReason(maxTotalBytes: number): string {\n return (\n `Not loaded: the ${formatBytes(maxTotalBytes)} total read budget for this review ` +\n 'ran out before this file.'\n );\n}\n\nconst LISTED_PATHS = 10;\n\nfunction listPaths(paths: string[]): string {\n const shown = paths.slice(0, LISTED_PATHS).join(', ');\n const rest = paths.length - LISTED_PATHS;\n return rest > 0 ? `${shown}, and ${rest} more` : shown;\n}\n\nfunction countFiles(count: number): string {\n return `${count} ${count === 1 ? 'file' : 'files'}`;\n}\n","// Source classification and accounting. No patch/AST formatting or diagnostic presentation.\nimport type { SyntheticSource } from './synthetic-source';\nimport {\n formatBytes,\n createRepresentationBudget,\n RepresentationLimitError,\n type ResolvedSourceBudgets,\n} from './input-budgets';\nimport {\n overTotalReason,\n syntheticDiagnostics,\n type SyntheticDiagnosticState,\n} from './synthetic-diagnostics';\n\nexport type EmittedSource = Extract<SyntheticSource, { kind: 'text' | 'symlink' | 'binary' }>;\n\nexport function createSourceAccounting(budgets: ResolvedSourceBudgets) {\n const representation = createRepresentationBudget(budgets);\n const state: SyntheticDiagnosticState = {\n representationOmissions: [],\n tooLarge: [],\n overTotal: [],\n unreadable: [],\n };\n const omitted = new Map<string, string>();\n let totalRead = 0;\n let totalExhausted = false;\n\n function admit(\n filePath: string,\n source: SyntheticSource | null\n ): { emit: boolean; source?: EmittedSource } {\n if (state.representationExhausted) {\n state.representationOmissions.push(filePath);\n omitted.set(filePath, state.representationExhausted);\n return { emit: true };\n }\n if (source === null) {\n // Nothing more is read once the aggregate is spent: the cut is one point in the list.\n state.overTotal.push(filePath);\n omitted.set(filePath, overTotalReason(budgets.maxTotalBytes));\n return { emit: true };\n }\n\n totalRead += source.bytesRead;\n\n switch (source.kind) {\n case 'skip':\n return { emit: false };\n case 'unreadable':\n state.unreadable.push(`${filePath} (${source.code})`);\n return { emit: false };\n case 'binary':\n return { emit: true, source };\n case 'too-large':\n state.tooLarge.push(filePath);\n omitted.set(\n filePath,\n `Not loaded: this file is ${formatBytes(source.size)}, over the ` +\n `${formatBytes(budgets.maxFileBytes)} per-file read budget.`\n );\n return { emit: true };\n case 'over-total':\n totalExhausted = true;\n state.overTotal.push(filePath);\n omitted.set(filePath, overTotalReason(budgets.maxTotalBytes));\n return { emit: true };\n case 'symlink':\n case 'text':\n return { emit: true, source };\n }\n }\n\n return {\n representation,\n omitted,\n admit,\n beginFile() {\n try {\n representation.beginFile();\n return true;\n } catch (error) {\n if (!(error instanceof RepresentationLimitError)) throw error;\n state.representationExhausted = `${error.message} Loading stopped; remaining paths were not loaded.`;\n return false;\n }\n },\n omitRepresentation(filePath: string, error: RepresentationLimitError) {\n if (error.aggregate) state.representationExhausted = error.message;\n state.representationOmissions.push(filePath);\n omitted.set(filePath, error.message);\n },\n remaining: () => budgets.maxTotalBytes - totalRead,\n exhausted: () => totalExhausted || state.representationExhausted !== undefined,\n diagnostics: () => syntheticDiagnostics(state, budgets),\n };\n}\n","// Git-compatible path encoding shared by synthetic emitters.\n// C-style escapes git emits for the characters that have one.\nconst C_STYLE_ESCAPES: Record<number, string> = {\n 0x07: '\\\\a',\n 0x08: '\\\\b',\n 0x09: '\\\\t',\n 0x0a: '\\\\n',\n 0x0b: '\\\\v',\n 0x0c: '\\\\f',\n 0x0d: '\\\\r',\n 0x22: '\\\\\"',\n 0x5c: '\\\\\\\\',\n};\n\nfunction needsQuoting(byte: number): boolean {\n return byte < 0x20 || byte >= 0x7f || byte === 0x22 || byte === 0x5c;\n}\n\n/**\n * Encode a path the way git writes it in diff headers. A plain path goes out\n * verbatim. Anything else becomes a double-quoted C-style token with control\n * characters, quotes, backslashes and non-ASCII UTF-8 bytes escaped.\n *\n * This inverts `decodeGitPath` in diff-parser.ts. Without it, a filename\n * containing a newline ends the header line mid-name and the parser recovers\n * a name no file on disk answers to.\n */\nexport function quoteGitPath(path: string): string {\n const bytes = Buffer.from(path, 'utf-8');\n if (!bytes.some(needsQuoting)) return path;\n\n let quoted = '\"';\n for (const byte of bytes) {\n const escape = C_STYLE_ESCAPES[byte];\n if (escape) {\n quoted += escape;\n } else if (byte < 0x20 || byte >= 0x7f) {\n quoted += `\\\\${byte.toString(8).padStart(3, '0')}`;\n } else {\n quoted += String.fromCharCode(byte);\n }\n }\n return `${quoted}\"`;\n}\n","// Patch bytes and structured additions are alternative emitters selected once per projection.\nimport type { DiffFile, DiffLine } from './types';\nimport { quoteGitPath } from './git-path-quote';\nimport type { EmittedSource } from './synthetic-accounting';\nimport type { ProjectedText } from './synthetic-text';\n\nexport function* projectedLines(\n text: ProjectedText\n): Generator<{ content: string; number: number }> {\n let start = 0;\n for (let index = 0; index < text.lineCount; index++) {\n const end = text.text.indexOf('\\n', start);\n const content = text.text.slice(start, end === -1 ? undefined : end);\n start = end + 1;\n yield { content, number: index + 1 };\n }\n}\n\nexport function createFilesEmitter() {\n const files: DiffFile[] = [];\n return {\n *emit(\n filePath: string,\n source?: EmittedSource,\n text?: ProjectedText,\n _mode?: string\n ): Generator<void> {\n const lines: DiffLine[] = [];\n if (text) {\n for (const line of projectedLines(text)) {\n lines.push({\n type: 'addition',\n oldLineNumber: null,\n newLineNumber: line.number,\n content: line.content,\n });\n if (line.number % 256 === 0) yield;\n }\n }\n files.push({\n oldPath: '',\n newPath: filePath,\n changeType: 'added',\n isBinary: source?.kind === 'binary',\n hunks: text\n ? [\n {\n header: text.header,\n oldStart: 0,\n oldLines: 0,\n newStart: 1,\n newLines: text.lineCount,\n lines,\n },\n ]\n : [],\n });\n },\n finish: () => ({ diff: '', files }),\n };\n}\n\nexport function createPatchEmitter() {\n const diffs: string[] = [];\n return {\n *emit(\n filePath: string,\n source?: EmittedSource,\n text?: ProjectedText,\n mode = source?.kind === 'symlink' ? '120000' : '100644'\n ): Generator<void> {\n const patch: string[] = [];\n if (text) {\n for (const line of projectedLines(text)) {\n patch.push(`+${line.content}`);\n if (line.number % 256 === 0) yield;\n }\n }\n const oldHeaderPath = quoteGitPath(`a/${filePath}`);\n const newHeaderPath = quoteGitPath(`b/${filePath}`);\n const header = `diff --git ${oldHeaderPath} ${newHeaderPath}\\nnew file mode ${mode}`;\n diffs.push(\n text\n ? `${header}\\n--- /dev/null\\n+++ ${newHeaderPath}\\n${text.header}\\n` +\n patch.join('\\n') +\n (text.missingNewline ? '\\n\\\' : '')\n : source?.kind === 'binary'\n ? `${header}\\nBinary files /dev/null and ${newHeaderPath} differ`\n : header\n );\n },\n finish: () => ({ diff: diffs.join('\\n'), files: [] as DiffFile[] }),\n };\n}\n","// Bounded text accounting shared by patch and structured emission.\nimport { createRepresentationBudget } from './input-budgets';\n\n/** Decode once for either output; retain CR, BOM and UTF-8 replacement semantics. */\nexport function* projectText(\n content: Buffer,\n representation: ReturnType<typeof createRepresentationBudget>\n) {\n let lineCount = 0;\n // Count before decoding or allocating any line strings/objects. A byte chunk also bounds\n // checkpoint spacing for a single long line. UTF-8 never embeds LF in a multibyte sequence.\n for (let start = 0; start < content.length; start += 64 * 1024) {\n let count = 0;\n const end = Math.min(start + 64 * 1024, content.length);\n for (let i = start; i < end; i++) if (content[i] === 0x0a) count++;\n representation.addLines(count);\n lineCount += count;\n yield;\n }\n const missingNewline = content.length > 0 && content[content.length - 1] !== 0x0a;\n if (missingNewline) {\n representation.addLines(1);\n lineCount++;\n }\n return {\n text: content.toString('utf-8'),\n lineCount,\n header: `@@ -0,0 +1,${lineCount} @@`,\n missingNewline,\n };\n}\n\nexport interface ProjectedText {\n text: string;\n lineCount: number;\n header: string;\n missingNewline: boolean;\n}\n","// packages/core/src/synthetic-diff.ts\n// Generates synthetic unified diffs for files that aren't tracked by git.\n// Reusable by both git untracked file handling and directory-based scanning.\n//\n// Reads are bounded first (input-budgets.ts). A file over budget is still listed, with no\n// content and an `omittedReason`, and named in the diagnostics.\n\nimport { createSourceAccounting, type EmittedSource } from './synthetic-accounting';\nimport { createFilesEmitter, createPatchEmitter } from './synthetic-emitter';\nimport { projectText } from './synthetic-text';\nimport { createSeparatorDiagnostics } from './synthetic-diagnostics';\nexport { quoteGitPath } from './git-path-quote';\nimport { realpathSync } from 'fs';\nimport { join, resolve } from 'path';\nimport type { DiffFile } from './types';\nimport { readSyntheticSource, readSyntheticSourceAsync } from './synthetic-source';\nimport { captureSourceReads, recordSourceCapture, RELOAD_REVIEW } from './loaded-snapshot';\nimport { nodeScanFsLayer } from './node-scan-fs';\nimport type { SyntheticSource } from './synthetic-source';\nimport type { SourceReadFsLayer } from './scan-fs';\nimport { checkLoadingCancelled, loadingCheckpoint } from './local-loading-lifetime';\nexport { readSyntheticSource } from './synthetic-source';\nexport type { SyntheticSource } from './synthetic-source';\nimport {\n resolveSourceBudgets,\n RepresentationLimitError,\n type SourceBudgets,\n type ResolvedSourceBudgets,\n} from './input-budgets';\n\nexport interface SyntheticDiffOptions {\n /**\n * Only for a path the reviewer named explicitly (single-file review); enumerated paths never\n * follow links.\n */\n followSymlinks?: boolean;\n budgets?: Partial<SourceBudgets>;\n}\n\nexport interface SyntheticDiffResult {\n diff: string;\n /**\n * Files listed without content, by literal relative path, with the sentence the viewer shows\n * instead.\n */\n omitted: Map<string, string>;\n diagnostics: string[];\n}\n\n/**\n * Generate synthetic unified diffs for a list of file paths so they can be\n * parsed by the existing diff parser. Each file is treated as a new addition.\n *\n * @param paths - Literal relative file paths (e.g. \"src/foo.ts\"), resolved\n * against rootDir and never git-quoted on the way in\n * @param rootDir - Absolute path to the root directory the paths are relative to\n * @returns The diff text, the files listed without content, and diagnostics\n */\nexport function generateSyntheticDiffs(\n paths: string[],\n rootDir: string,\n options: SyntheticDiffOptions = {}\n): SyntheticDiffResult {\n const { diff, omitted, diagnostics } = projectSources(paths, rootDir, options, 'patch');\n return { diff, omitted, diagnostics };\n}\n\nfunction projectSources(\n paths: string[],\n rootDir: string,\n options: SyntheticDiffOptions,\n output: 'patch' | 'files'\n) {\n const budgets = resolveSourceBudgets(options.budgets);\n const sourceRoot = syntheticRoot(rootDir);\n const projection = createProjection(budgets, output);\n for (const filePath of paths) {\n if (!projection.beginFile()) break;\n const steps = projection.add(\n filePath,\n projection.exhausted()\n ? null\n : readSyntheticSource(join(sourceRoot, filePath), {\n sourceRoot,\n followSymlinks: options.followSymlinks,\n maxFileBytes: budgets.maxFileBytes,\n remainingBytes: projection.remaining(),\n })\n );\n while (!steps.next().done) {\n /* Synchronous compatibility consumer. */\n }\n }\n return projection.finish();\n}\n\nexport interface AsyncSyntheticDiffOptions extends SyntheticDiffOptions {\n /** Used for root resolution and every source inspection/read. */\n readFs?: SourceReadFsLayer;\n signal?: AbortSignal;\n}\n\n/** Async counterpart with the same ordering, budgets and projection as generateSyntheticDiffs. */\nexport async function generateSyntheticDiffsAsync(\n paths: string[],\n rootDir: string,\n options: AsyncSyntheticDiffOptions = {}\n): Promise<SyntheticDiffResult> {\n const { diff, omitted, diagnostics } = await projectSourcesAsync(\n paths,\n rootDir,\n options,\n 'patch'\n );\n return { diff, omitted, diagnostics };\n}\n\nasync function projectSourcesAsync(\n paths: string[],\n rootDir: string,\n options: AsyncSyntheticDiffOptions,\n output: 'patch' | 'files'\n) {\n checkLoadingCancelled(options.signal);\n const budgets = resolveSourceBudgets(options.budgets);\n const sourceRoot = options.readFs\n ? await options.readFs.realpath(rootDir).catch(() => {\n checkLoadingCancelled(options.signal);\n // Preserve per-path read diagnostics without consulting the host filesystem.\n return resolve(rootDir);\n })\n : syntheticRoot(rootDir);\n checkLoadingCancelled(options.signal);\n const originalFs = options.readFs ?? nodeScanFsLayer;\n const capture = captureSourceReads(originalFs, options.signal, 'record');\n const readFs: SourceReadFsLayer = {\n ...capture.readFs,\n readlink: target => originalFs.readlink(target),\n };\n const projection = createProjection(budgets, output);\n for (const filePath of paths) {\n await loadingCheckpoint(options.signal);\n if (!projection.beginFile()) break;\n const source = projection.exhausted()\n ? null\n : await readSyntheticSourceAsync(join(sourceRoot, filePath), {\n sourceRoot,\n readFs,\n followSymlinks: options.followSymlinks,\n maxFileBytes: budgets.maxFileBytes,\n remainingBytes: projection.remaining(),\n signal: options.signal,\n });\n checkLoadingCancelled(options.signal);\n // Preserve existing omission diagnostics when growth already exceeded a source budget.\n if (\n source &&\n (source.kind === 'text' || source.kind === 'binary') &&\n capture.drifted.has(resolve(sourceRoot, filePath))\n )\n throw new Error(RELOAD_REVIEW);\n const steps = projection.add(filePath, source);\n try {\n while (!steps.next().done) await loadingCheckpoint(options.signal);\n } finally {\n steps.return(undefined);\n }\n }\n await loadingCheckpoint(options.signal);\n const result = projection.finish();\n for (const file of result.files) {\n recordSourceCapture(\n file,\n capture.captures.get(resolve(sourceRoot, file.newPath || file.oldPath))\n );\n }\n return result;\n}\n\nfunction syntheticRoot(rootDir: string): string {\n try {\n return realpathSync(rootDir);\n } catch {\n // Preserve per-path disappearance diagnostics when a root vanishes before the read.\n return resolve(rootDir);\n }\n}\n\n/** Coordinate shared accounting and one output emitter, without source I/O. */\nfunction createProjection(budgets: ResolvedSourceBudgets, output: 'patch' | 'files') {\n const accounting = createSourceAccounting(budgets);\n const emitter = output === 'files' ? createFilesEmitter() : createPatchEmitter();\n const separators = createSeparatorDiagnostics(budgets.maxDiagnostics);\n\n function* emit(filePath: string, source?: EmittedSource, mode?: string): Generator<void> {\n const text =\n source && source.kind !== 'binary'\n ? yield* projectText(source.content, accounting.representation)\n : undefined;\n if (text) accounting.representation.addHunk();\n separators.next(filePath, text?.lineCount);\n yield* emitter.emit(filePath, source, text, mode);\n }\n\n function* add(filePath: string, source: SyntheticSource | null): Generator<void> {\n try {\n const admission = accounting.admit(filePath, source);\n if (admission.emit) yield* emit(filePath, admission.source);\n } catch (error) {\n if (!(error instanceof RepresentationLimitError)) throw error;\n accounting.omitRepresentation(filePath, error);\n yield* emit(filePath, undefined, source?.kind === 'symlink' ? '120000' : '100644');\n }\n }\n\n return {\n beginFile: accounting.beginFile,\n add,\n remaining: accounting.remaining,\n exhausted: accounting.exhausted,\n finish() {\n const result = emitter.finish();\n for (const file of result.files) {\n const reason = accounting.omitted.get(file.newPath);\n if (reason !== undefined) file.omittedReason = reason;\n }\n const diagnostics = accounting.diagnostics();\n return {\n ...result,\n omitted: accounting.omitted,\n diagnostics: output === 'files' ? [...diagnostics, ...separators.diagnostics] : diagnostics,\n };\n },\n };\n}\n\n/** Build structured additions directly, with the same projection and budgets as patch output. */\nexport function loadSyntheticFiles(\n paths: string[],\n rootDir: string,\n options: SyntheticDiffOptions = {}\n): { files: DiffFile[]; diagnostics: string[] } {\n const { files, diagnostics } = projectSources(paths, rootDir, options, 'files');\n return { files, diagnostics };\n}\n\n/** Async build; cancellation never returns a partial set of files. */\nexport async function loadSyntheticFilesAsync(\n paths: string[],\n rootDir: string,\n options: AsyncSyntheticDiffOptions = {}\n): Promise<{ files: DiffFile[]; diagnostics: string[] }> {\n const { files, diagnostics } = await projectSourcesAsync(paths, rootDir, options, 'files');\n return { files, diagnostics };\n}\n","// Source reading is separate from diff projection. Both drivers consume the same bounded read plan.\nimport {\n closeSync,\n constants,\n fstatSync,\n lstatSync,\n openSync,\n readlinkSync,\n realpathSync,\n} from 'fs';\nimport { dirname, join, relative } from 'path';\nimport { assertNoSymlinkAncestors, openContainedFile } from './safe-fs';\nimport { openContainedFileAsync } from './safe-fs-async';\nimport { assertNoSymlinkAncestorsAsync, type AsyncReadHandle } from './safe-fs-read';\nimport type { SourceReadFsLayer } from './scan-fs';\nimport { nodeScanFsLayer } from './node-scan-fs';\nimport { readInto, readIntoAsync } from './bounded-read';\nimport { BINARY_SNIFF_BYTES, resolveSourceBudgets } from './input-budgets';\nimport { checkLoadingCancelled, loadingCheckpoint } from './local-loading-lifetime';\n\n/** A bounded look at one path. A symlink carries only its target text, as git stores it. */\nexport type SyntheticSource =\n | { kind: 'skip'; bytesRead: 0 }\n | { kind: 'unreadable'; code: string; bytesRead: number }\n | { kind: 'symlink'; content: Buffer; bytesRead: number }\n | { kind: 'binary'; bytesRead: number }\n | { kind: 'text'; content: Buffer; bytesRead: number }\n | { kind: 'too-large'; size: number; bytesRead: number }\n | { kind: 'over-total'; size: number; bytesRead: number };\n\nexport interface SyntheticSourceOptions {\n followSymlinks?: boolean;\n maxFileBytes?: number;\n remainingBytes?: number;\n sourceRoot?: string;\n}\n\nfunction sourceOptions(options: SyntheticSourceOptions) {\n const budgets = resolveSourceBudgets();\n return {\n ...options,\n maxFileBytes: options.maxFileBytes ?? budgets.maxFileBytes,\n remainingBytes: options.remainingBytes ?? budgets.maxTotalBytes,\n };\n}\n\nfunction readLinkSource(\n fullPath: string,\n root: string,\n rel: string,\n options: ReturnType<typeof sourceOptions>\n): SyntheticSource | null {\n if (!options.followSymlinks) {\n let linkSize: number | undefined;\n try {\n assertNoSymlinkAncestors(root, rel);\n const stats = lstatSync(fullPath);\n if (stats.isSymbolicLink()) linkSize = stats.size;\n } catch (error) {\n return failure(error);\n }\n if (linkSize !== undefined) {\n if (linkSize > options.maxFileBytes)\n return { kind: 'too-large', size: linkSize, bytesRead: 0 };\n if (linkSize > options.remainingBytes)\n return { kind: 'over-total', size: linkSize, bytesRead: 0 };\n // Git stores a link as its target path; never read what it points at.\n try {\n const content = readlinkSync(fullPath, { encoding: 'buffer' });\n assertNoSymlinkAncestors(root, rel);\n if (realpathSync(dirname(fullPath)) !== join(realpathSync(root), dirname(rel))) {\n return { kind: 'unreadable', code: 'unsafe-link', bytesRead: 0 };\n }\n if (content.length > options.maxFileBytes)\n return { kind: 'too-large', size: content.length, bytesRead: content.length };\n if (content.length > options.remainingBytes)\n return { kind: 'over-total', size: content.length, bytesRead: content.length };\n return { kind: 'symlink', content, bytesRead: content.length };\n } catch (error) {\n return failure(error);\n }\n }\n }\n\n return null;\n}\n\ninterface ReadRequest {\n buffer: Buffer;\n offset: number;\n length: number;\n}\n\n/** Nothing past the sniff prefix is read unless measured text fits both budgets. */\nfunction* sourceReads(\n size: number,\n maxFileBytes: number,\n remainingBytes: number\n): Generator<ReadRequest, SyntheticSource, number> {\n let bytesRead = 0;\n const sniffLength = Math.min(size, BINARY_SNIFF_BYTES);\n if (sniffLength > remainingBytes) return { kind: 'over-total', size, bytesRead };\n const sniff = Buffer.alloc(sniffLength);\n bytesRead = yield { buffer: sniff, offset: 0, length: sniffLength };\n if (sniff.subarray(0, bytesRead).includes(0)) return { kind: 'binary', bytesRead };\n if (size > maxFileBytes) return { kind: 'too-large', size, bytesRead };\n if (size > remainingBytes) return { kind: 'over-total', size, bytesRead };\n // Preserve the measured snapshot if the file grows within budget. Never read past its size.\n const content = Buffer.alloc(size);\n sniff.copy(content, 0, 0, bytesRead);\n bytesRead += yield { buffer: content, offset: bytesRead, length: size - bytesRead };\n return { kind: 'text', content: content.subarray(0, bytesRead), bytesRead };\n}\n\nfunction checkGrowth(\n source: SyntheticSource,\n size: number,\n options: ReturnType<typeof sourceOptions>\n): SyntheticSource {\n if (source.kind !== 'text') return source;\n if (size > options.maxFileBytes) return { kind: 'too-large', size, bytesRead: source.bytesRead };\n if (size > options.remainingBytes)\n return { kind: 'over-total', size, bytesRead: source.bytesRead };\n return source;\n}\n\n/** Synchronous compatibility reader. Explicitly named files may follow their leaf symlink. */\nexport function readSyntheticSource(\n fullPath: string,\n input: SyntheticSourceOptions = {}\n): SyntheticSource {\n const options = sourceOptions(input);\n const root = options.sourceRoot ?? dirname(fullPath);\n const rel = relative(root, fullPath);\n const link = readLinkSource(fullPath, root, rel, options);\n if (link) return link;\n let fd: number;\n try {\n fd = options.followSymlinks\n ? openSync(fullPath, constants.O_RDONLY | constants.O_NONBLOCK)\n : openContainedFile(root, rel).fd;\n } catch (error) {\n return failure(error);\n }\n let bytesRead = 0;\n try {\n const stats = fstatSync(fd);\n if (!stats.isFile()) return { kind: 'skip', bytesRead: 0 };\n const reads = sourceReads(stats.size, options.maxFileBytes, options.remainingBytes);\n let step = reads.next();\n while (!step.done) {\n const { buffer, offset, length } = step.value;\n const count = readInto(fd, buffer, offset, length);\n bytesRead += count;\n step = reads.next(count);\n }\n return step.value.kind === 'text'\n ? checkGrowth(step.value, fstatSync(fd).size, options)\n : step.value;\n } catch (error) {\n return failure(error, bytesRead);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Link text follows the same injected filesystem as the subsequent descriptor read. */\nasync function readLinkSourceAsync(\n fullPath: string,\n root: string,\n rel: string,\n options: ReturnType<typeof sourceOptions>,\n layer: SourceReadFsLayer,\n signal?: AbortSignal\n): Promise<SyntheticSource | null> {\n if (options.followSymlinks) return null;\n await assertNoSymlinkAncestorsAsync(root, rel, layer, signal);\n checkLoadingCancelled(signal);\n const stats = await layer.lstat(fullPath);\n checkLoadingCancelled(signal);\n if (!stats.isSymbolicLink()) return null;\n if (stats.size > options.maxFileBytes)\n return { kind: 'too-large', size: stats.size, bytesRead: 0 };\n if (stats.size > options.remainingBytes)\n return { kind: 'over-total', size: stats.size, bytesRead: 0 };\n const content = await layer.readlink(fullPath);\n checkLoadingCancelled(signal);\n await assertNoSymlinkAncestorsAsync(root, rel, layer, signal);\n checkLoadingCancelled(signal);\n const parent = await layer.realpath(dirname(fullPath));\n checkLoadingCancelled(signal);\n const physicalRoot = await layer.realpath(root);\n checkLoadingCancelled(signal);\n if (parent !== join(physicalRoot, dirname(rel)))\n return { kind: 'unreadable', code: 'unsafe-link', bytesRead: 0 };\n if (content.length > options.maxFileBytes)\n return { kind: 'too-large', size: content.length, bytesRead: content.length };\n if (content.length > options.remainingBytes)\n return { kind: 'over-total', size: content.length, bytesRead: content.length };\n return { kind: 'symlink', content, bytesRead: content.length };\n}\n\n/**\n * Owns its handle until close, including cancellation during a native open/read. Native calls\n * cannot be preempted; after they settle, cancellation wins and no partial content is returned.\n */\nexport async function readSyntheticSourceAsync(\n fullPath: string,\n input: SyntheticSourceOptions & { signal?: AbortSignal; readFs?: SourceReadFsLayer } = {}\n): Promise<SyntheticSource> {\n const { signal } = input;\n await loadingCheckpoint(signal);\n const options = sourceOptions(input);\n const root = options.sourceRoot ?? dirname(fullPath);\n const rel = relative(root, fullPath);\n const layer = input.readFs ?? nodeScanFsLayer;\n let handle: AsyncReadHandle | undefined;\n let bytesRead = 0;\n try {\n const link = await readLinkSourceAsync(fullPath, root, rel, options, layer, signal);\n checkLoadingCancelled(signal);\n if (link) return link;\n handle = options.followSymlinks\n ? await layer.open(fullPath, constants.O_RDONLY | constants.O_NONBLOCK)\n : (await openContainedFileAsync(root, rel, layer, signal)).handle;\n checkLoadingCancelled(signal);\n const stats = await handle.stat();\n checkLoadingCancelled(signal);\n if (!stats.isFile()) return { kind: 'skip', bytesRead: 0 };\n const reader = {\n read: async (buffer: Buffer, offset: number, length: number, position: number | null) => {\n const result = await handle!.read(buffer, offset, length, position);\n // Include successful partial reads if a subsequent read fails.\n bytesRead += result.bytesRead;\n return result;\n },\n };\n const reads = sourceReads(stats.size, options.maxFileBytes, options.remainingBytes);\n let step = reads.next();\n while (!step.done) {\n const { buffer, offset, length } = step.value;\n const count = await readIntoAsync(reader, buffer, offset, length, signal);\n step = reads.next(count);\n }\n if (step.value.kind !== 'text') return step.value;\n const after = await handle.stat();\n checkLoadingCancelled(signal);\n return checkGrowth(step.value, after.size, options);\n } catch (error) {\n checkLoadingCancelled(signal);\n return failure(error, bytesRead);\n } finally {\n try {\n if (handle) await handle.close();\n } finally {\n checkLoadingCancelled(signal);\n }\n }\n}\nfunction failure(error: unknown, bytesRead = 0): SyntheticSource {\n const wrapped = error as { cause?: NodeJS.ErrnoException; code?: string } | undefined;\n const code = wrapped?.cause?.code ?? wrapped?.code ?? 'unknown error';\n // Gone or no longer a directory between listing and reading, or a link swapped in (O_NOFOLLOW).\n if (\n ['ENOENT', 'ENOTDIR', 'ELOOP', 'not-found', 'not-regular', 'output-is-directory'].includes(code)\n ) {\n return { kind: 'skip', bytesRead: 0 };\n }\n return { kind: 'unreadable', code, bytesRead };\n}\n","// Exact spellings only. Unknown flags retain pass-through behavior, including negations.\n// Optional values are attached only; required values may consume the next argv element.\ninterface GitDiffOptionPolicy {\n readonly value?: 'required' | 'attached';\n readonly writeCapable?: true;\n readonly unsupportedOutput?: 'always' | 'attached';\n readonly rediff?: 'drop' | 'relative';\n}\n\nconst OPTION_POLICY: Readonly<Record<string, GitDiffOptionPolicy>> = {\n '--output': { value: 'required', writeCapable: true, unsupportedOutput: 'always' },\n '--ext-diff': { writeCapable: true },\n '--textconv': { writeCapable: true },\n '--src-prefix': { value: 'required' },\n '--dst-prefix': { value: 'required' },\n '--line-prefix': { value: 'required', unsupportedOutput: 'always' },\n '--output-indicator-new': { value: 'required', unsupportedOutput: 'always' },\n '--output-indicator-old': { value: 'required', unsupportedOutput: 'always' },\n '--output-indicator-context': { value: 'required', unsupportedOutput: 'always' },\n '--inter-hunk-context': { value: 'required' },\n // Preserve the existing warning policy for these attached stat parameters.\n '--stat-width': { value: 'required', unsupportedOutput: 'attached' },\n '--stat-name-width': { value: 'required', unsupportedOutput: 'attached' },\n '--stat-graph-width': { value: 'required', unsupportedOutput: 'attached' },\n '--stat-count': { value: 'required', unsupportedOutput: 'attached' },\n '--diff-algorithm': { value: 'required' },\n '--word-diff-regex': { value: 'required', unsupportedOutput: 'always' },\n '--ignore-matching-lines': { value: 'required' },\n '--anchored': { value: 'required' },\n '--diff-filter': { value: 'required' },\n '--find-object': { value: 'required' },\n '--rotate-to': { value: 'required', rediff: 'drop' },\n '--skip-to': { value: 'required', rediff: 'drop' },\n '--ws-error-highlight': { value: 'required' },\n '--color-moved-ws': { value: 'required', unsupportedOutput: 'always' },\n '-S': { value: 'required' },\n '-G': { value: 'required' },\n '-O': { value: 'required', rediff: 'drop' },\n '-I': { value: 'required' },\n '-l': { value: 'required' },\n '-U': { value: 'attached', rediff: 'drop' },\n '-B': { value: 'attached' },\n '-M': { value: 'attached' },\n '-C': { value: 'attached' },\n '-W': { rediff: 'drop' },\n '--unified': { value: 'attached', rediff: 'drop' },\n '--function-context': { rediff: 'drop' },\n '--no-function-context': { rediff: 'drop' },\n '--relative': { value: 'attached', rediff: 'relative' },\n '--no-relative': { rediff: 'relative' },\n '--stat': { value: 'attached', unsupportedOutput: 'always' },\n '--numstat': { unsupportedOutput: 'always' },\n '--shortstat': { unsupportedOutput: 'always' },\n '--dirstat': { value: 'attached', unsupportedOutput: 'always' },\n '--dirstat-by-file': { value: 'attached', unsupportedOutput: 'always' },\n '--cumulative': { unsupportedOutput: 'always' },\n '--summary': { unsupportedOutput: 'always' },\n '--name-only': { unsupportedOutput: 'always' },\n '--name-status': { unsupportedOutput: 'always' },\n '--raw': { unsupportedOutput: 'always' },\n '--patch-with-stat': { unsupportedOutput: 'always' },\n '--patch-with-raw': { unsupportedOutput: 'always' },\n '--compact-summary': { unsupportedOutput: 'always' },\n '--word-diff': { value: 'attached', unsupportedOutput: 'always' },\n '--color-words': { value: 'attached', unsupportedOutput: 'always' },\n '--color-moved': { value: 'attached', unsupportedOutput: 'always' },\n '--no-patch': { unsupportedOutput: 'always' },\n '-s': { unsupportedOutput: 'always' },\n '--exit-code': { unsupportedOutput: 'always' },\n '--quiet': { unsupportedOutput: 'always' },\n '--check': { unsupportedOutput: 'always' },\n};\n\n/** A missing entry means no known arity or restriction, never a rejected option. */\nexport function gitDiffOptionPolicy(name: string): GitDiffOptionPolicy {\n return Object.prototype.hasOwnProperty.call(OPTION_POLICY, name) ? OPTION_POLICY[name] : {};\n}\n","// Pure interpretation of argv. Unknown options pass through unchanged.\n\nimport { gitDiffOptionPolicy } from './git-option-policy';\n\n/** True when `arg`'s value is the next argument, which is then neither a flag nor a positional. */\nexport function consumesNextArgument(arg: string): boolean {\n if (arg.startsWith('--')) return gitDiffOptionPolicy(arg).value === 'required';\n if (!arg.startsWith('-')) return false;\n // Git accepts short-option groups, such as -pS pattern. Once an option\n // takes a value, the rest of that token is its attached value, if present.\n for (let i = 1; i < arg.length; i++) {\n if (gitDiffOptionPolicy(`-${arg[i]}`).value === 'required') return i === arg.length - 1;\n if (gitDiffOptionPolicy(`-${arg[i]}`).value === 'attached') return false;\n }\n return false;\n}\n\n/** An effective option, including short options inside a group; values never become options. */\nexport interface GitDiffOption {\n index: number;\n arg: string;\n name: string;\n value?: string;\n}\n\nexport interface ParsedGitDiffArgs {\n options: GitDiffOption[];\n positionalIndices: number[];\n /** The actual separator, excluding an option value spelled `--`. */\n separatorIndex: number | null;\n}\n\n/** One interpretation of option arity, groups and the pathspec boundary for all consumers. */\nexport function parseGitDiffArgs(args: readonly string[]): ParsedGitDiffArgs {\n const options: GitDiffOption[] = [];\n const positionalIndices: number[] = [];\n let separatorIndex: number | null = null;\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (separatorIndex !== null) {\n positionalIndices.push(i);\n } else if (arg === '--') {\n separatorIndex = i;\n } else if (arg.startsWith('--')) {\n const equals = arg.indexOf('=');\n const option: GitDiffOption = {\n index: i,\n arg,\n name: equals < 0 ? arg : arg.slice(0, equals),\n };\n if (equals >= 0) option.value = arg.slice(equals + 1);\n else if (consumesNextArgument(arg) && i + 1 < args.length) {\n option.value = args[++i];\n }\n options.push(option);\n } else if (arg.startsWith('-')) {\n for (let j = 1; j < arg.length; j++) {\n const name = arg[j];\n const option: GitDiffOption = { index: i, arg, name: `-${name}` };\n options.push(option);\n if (\n gitDiffOptionPolicy(`-${name}`).value === 'required' ||\n gitDiffOptionPolicy(`-${name}`).value === 'attached'\n ) {\n if (j + 1 < arg.length) option.value = arg.slice(j + 1);\n else if (gitDiffOptionPolicy(`-${name}`).value === 'required' && i + 1 < args.length) {\n option.value = args[++i];\n }\n break;\n }\n }\n } else {\n positionalIndices.push(i);\n }\n }\n return { options, positionalIndices, separatorIndex };\n}\n\n/** What the paths in `git diff` output are relative to. */\nexport type DiffPathRelativity =\n | { kind: 'root' }\n | { kind: 'cwd' }\n // `directory` is read by git from the repository root.\n | { kind: 'directory'; directory: string };\n\nexport interface SingleFileRediff {\n args: string[];\n /** Resolved from the original arguments; its option is not in `args`. */\n relative: DiffPathRelativity;\n}\n\n/**\n * Remove context and file-order options from a short group, stopping at any attached value.\n */\nfunction withoutDroppedShortOptions(arg: string): string | null {\n let kept = '';\n for (let i = 1; i < arg.length; i++) {\n const option = arg[i];\n const rule = gitDiffOptionPolicy(`-${option}`);\n if (rule.rediff === 'drop') {\n if (rule.value) break;\n continue;\n }\n if (rule.value === 'required' || rule.value === 'attached') {\n kept += arg.slice(i);\n break;\n }\n kept += option;\n }\n return kept === '' ? null : `-${kept}`;\n}\n\n/**\n * The last of `--relative`, `--relative=<dir>` and `--no-relative` before `--` decides.\n * Only arguments count: every git diff forces `diff.relative=false`\n * (`PARSER_COMPATIBLE_GIT_CONFIG`).\n */\nexport function describeDiffPathRelativity(args: readonly string[]): DiffPathRelativity {\n let relative: DiffPathRelativity = { kind: 'root' };\n for (const option of parseGitDiffArgs(args).options) {\n if (option.name === '--relative') {\n relative =\n option.value === undefined\n ? { kind: 'cwd' }\n : { kind: 'directory', directory: option.value };\n } else if (option.name === '--no-relative') relative = { kind: 'root' };\n }\n return relative;\n}\n\n/**\n * Arguments for re-running a review's `git diff` over one file with other context.\n * Removed: context options (a bare `-U` never takes the next argument, so `-U HEAD`\n * keeps `HEAD`), file-order options, `--relative` forms (resolved into `relative`),\n * and `--` with its pathspecs. Everything else is kept in order.\n */\nexport function singleFileRediffArgs(args: readonly string[]): SingleFileRediff {\n const kept: string[] = [];\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--') break;\n const name = arg.split('=', 1)[0];\n const rule = gitDiffOptionPolicy(name);\n if (rule.rediff === 'relative' && (arg === name || rule.value === 'attached')) {\n continue;\n }\n // The value goes wherever its option goes.\n const takesNext = consumesNextArgument(arg) && i + 1 < args.length;\n let option: string | null = arg;\n let keepValue = true;\n if (arg.startsWith('--')) {\n if (gitDiffOptionPolicy(name).rediff === 'drop') option = null;\n keepValue = option !== null;\n } else if (arg.startsWith('-') && arg.length > 1) {\n option = withoutDroppedShortOptions(arg);\n keepValue = option !== null && consumesNextArgument(option);\n }\n if (option !== null) kept.push(option);\n if (takesNext) {\n i++;\n if (keepValue) kept.push(args[i]);\n }\n }\n return { args: kept, relative: describeDiffPathRelativity(args) };\n}\n\n/**\n * Options that make git write a file or run a program, as written. Used to refuse project\n * `default-diff-args`; the reviewer's own arguments are unrestricted.\n */\nexport function findWriteCapableGitDiffOptions(args: readonly string[]): string[] {\n return parseGitDiffArgs(args)\n .options.filter(option => gitDiffOptionPolicy(option.name).writeCapable)\n .map(option => option.arg);\n}\n\n/** Options selecting an output format the parser cannot consume, as the user wrote them. */\nexport function findUnsupportedGitDiffOptions(args: readonly string[]): string[] {\n const offending = parseGitDiffArgs(args).options.filter(option => {\n const output = gitDiffOptionPolicy(option.name).unsupportedOutput;\n return output === 'always' || (output === 'attached' && option.arg.includes('='));\n });\n return [...new Set(offending.map(option => option.index))].map(index => args[index]);\n}\n\n/** Identify positional arguments without mistaking option values for paths. */\nexport function classifyGitDiffArgs(args: string[]): {\n positionalIndices: number[];\n hasSeparator: boolean;\n} {\n const parsed = parseGitDiffArgs(args);\n return {\n positionalIndices: parsed.positionalIndices,\n hasSeparator: parsed.separatorIndex !== null,\n };\n}\n","// Pure argv text conversion. No shell expansion or execution is performed.\n\n/** Scan the established quoting syntax once for both tolerant reads and strict admission. */\nfunction scanGitDiffArgs(value: string): { args: string[]; syntaxError: string | null } {\n const args: string[] = [];\n let current = '';\n let started = false;\n let quote: \"'\" | '\"' | null = null;\n let danglingEscape = false;\n\n for (let i = 0; i < value.length; i++) {\n const char = value[i];\n\n if (quote === \"'\") {\n if (char === \"'\") quote = null;\n else current += char;\n continue;\n }\n\n if (quote === '\"') {\n // Inside double quotes only the quote and the backslash are escapable;\n // every other backslash is a literal character, as in POSIX shells.\n if (char === '\\\\' && (value[i + 1] === '\"' || value[i + 1] === '\\\\')) {\n current += value[++i];\n } else if (char === '\"') {\n quote = null;\n } else {\n current += char;\n }\n continue;\n }\n\n if (char === \"'\" || char === '\"') {\n quote = char;\n started = true;\n continue;\n }\n if (char === '\\\\' && i + 1 < value.length) {\n current += value[++i];\n started = true;\n continue;\n }\n if (/\\s/.test(char)) {\n if (started) {\n args.push(current);\n current = '';\n started = false;\n }\n continue;\n }\n if (char === '\\\\') danglingEscape = true;\n current += char;\n started = true;\n }\n\n if (started) args.push(current);\n const syntaxError =\n quote !== null\n ? `unterminated ${quote === \"'\" ? 'single' : 'double'} quote`\n : danglingEscape\n ? 'trailing escape'\n : null;\n return { args, syntaxError };\n}\n\n/** Legacy/persisted review strings keep their best-effort malformed-input behavior. */\nexport function tokenizeGitDiffArgs(value: string): string[] {\n return scanGitDiffArgs(value).args;\n}\n\n/** Internal configuration admission only; never includes the input in its diagnostic. */\nexport function gitDiffArgsSyntaxError(value: string): string | null {\n return scanGitDiffArgs(value).syntaxError;\n}\n\n/** True when rendering this argument bare would lose its boundary. */\nfunction needsQuoting(arg: string): boolean {\n return arg.length === 0 || /[\\s'\"\\\\]/.test(arg);\n}\n\n/**\n * Render argv as the single string a git diff source carries, such that\n * `tokenizeGitDiffArgs` recovers the exact argument list.\n *\n * Arguments that survive a bare round trip are written bare, so ordinary\n * invocations produce byte-identical output to a plain join and the\n * `git-diff-args` XML attribute does not change shape for them.\n */\nexport function formatGitDiffArgs(args: string[]): string {\n return args.map(arg => (needsQuoting(arg) ? `'${arg.replace(/'/g, \"'\\\\''\")}'` : arg)).join(' ');\n}\n","// Compatibility entry point. Pure policy and text conversion never depend on this Node wrapper.\nimport { existsSync } from 'fs';\nimport { resolve } from 'path';\nimport { normalizeGitDiffPaths } from './git-argument-paths';\n\nexport {\n consumesNextArgument,\n parseGitDiffArgs,\n describeDiffPathRelativity,\n singleFileRediffArgs,\n findWriteCapableGitDiffOptions,\n findUnsupportedGitDiffOptions,\n classifyGitDiffArgs,\n} from './git-argument-policy';\nexport type {\n GitDiffOption,\n ParsedGitDiffArgs,\n DiffPathRelativity,\n SingleFileRediff,\n} from './git-argument-policy';\nexport { tokenizeGitDiffArgs, formatGitDiffArgs } from './git-argument-text';\n\n/** Insert `--` before the first existing positional path, relative to cwd. */\nexport function normalizeGitDiffArgs(args: string[], cwd: string = process.cwd()): string[] {\n return normalizeGitDiffPaths(args, candidate => existsSync(resolve(cwd, candidate)));\n}\n","import { classifyGitDiffArgs } from './git-argument-policy';\n\n/** The probe interprets each positional path in the caller's chosen directory. */\nexport function normalizeGitDiffPaths(\n args: string[],\n pathExists: (path: string) => boolean\n): string[] {\n const { positionalIndices, hasSeparator } = classifyGitDiffArgs(args);\n if (hasSeparator) return args;\n for (const index of positionalIndices) {\n if (pathExists(args[index])) return [...args.slice(0, index), '--', ...args.slice(index)];\n }\n return args;\n}\n","/** Per-call diagnostic output. A second string preserves the submitted-state summary's call form. */\nexport type DiagnosticReporter = (message: string, detail?: string) => void;\n\n/** Compatibility default for hosts that have not supplied their own diagnostic presentation. */\nexport const stderrReporter: DiagnosticReporter = (message, detail) => {\n if (detail === undefined) console.error(message);\n else console.error(message, detail);\n};\n","// Presentation must not replace an operation's result or interrupt mandatory cleanup.\nimport { stderrReporter, type DiagnosticReporter } from './diagnostics';\n\nexport function isolatedReporter(report: DiagnosticReporter = stderrReporter): DiagnosticReporter {\n return (message, detail) => {\n try {\n const result = detail === undefined ? report(message) : report(message, detail);\n void Promise.resolve(result).catch(() => {});\n } catch {\n /* The operation owns its outcome independently of diagnostic presentation. */\n }\n };\n}\n","// Git command execution. Helpers reject rather than exit; front ends report failures.\n\nimport type { DiagnosticReporter } from './diagnostics';\nimport { isolatedReporter } from './effect-diagnostics';\nimport { defaultGitRunner } from './command-runner';\nimport { CommandCancelledError, isCommandCancelled } from './forge-provider';\nimport type { ForgeCommandRunner } from './forge-provider';\nimport {\n generateSyntheticDiffs,\n type SyntheticDiffOptions,\n type SyntheticDiffResult,\n} from './synthetic-diff';\nimport { parseGitDiffArgs } from './git-diff-args';\nimport { MAX_GIT_DIFF_OUTPUT_BYTES } from './input-budgets';\n\n/** Optional execution effects; existing helper call forms keep their defaults. */\nexport interface GitExecutionOptions {\n signal?: AbortSignal;\n timeoutMs?: number;\n runner?: ForgeCommandRunner;\n /** Defaults to stderr for compatibility; strict executeGit itself reports by throwing. */\n reportDiagnostic?: DiagnosticReporter;\n}\n\nexport class GitCommandError extends Error {\n constructor(\n readonly args: readonly string[],\n readonly exitCode: number,\n readonly stderr: string\n ) {\n super(`git ${args.join(' ')} failed: ${stderr.trim() || `exit ${exitCode}`}`);\n this.name = 'GitCommandError';\n }\n}\n\n/** A bounded text git command. Nonzero results reject; cancellation stays typed. */\nexport async function executeGit(\n args: string[],\n cwd?: string,\n options: GitExecutionOptions = {},\n maxOutputBytes = 1024 * 1024\n): Promise<string> {\n if (options.signal?.aborted) throw new CommandCancelledError('aborted', 'git', args);\n const result = await (options.runner ?? defaultGitRunner)('git', args, {\n cwd,\n signal: options.signal,\n timeoutMs: options.timeoutMs ?? 10_000,\n maxOutputBytes,\n });\n if (options.signal?.aborted) throw new CommandCancelledError('aborted', 'git', args);\n if (result.exitCode !== 0) throw new GitCommandError(args, result.exitCode, result.stderr);\n return result.stdout;\n}\n\n/**\n * Strip only the single trailing newline git appends to command output.\n * A plain `.trim()` also eats leading/trailing whitespace that is part of\n * the actual path (e.g. a repository root with a trailing space), reporting\n * a path that does not exist on disk.\n */\nexport function stripTrailingNewline(text: string): string {\n return text.replace(/\\r?\\n$/, '');\n}\n\n/** Rejects when git is missing or `cwd` is not inside a repository. */\nexport async function getRepoRootAsync(\n cwd?: string,\n options: GitExecutionOptions = {}\n): Promise<string> {\n try {\n const stdout = await executeGit(['rev-parse', '--show-toplevel'], cwd, options);\n return stripTrailingNewline(stdout);\n } catch (error) {\n const knownError = error instanceof Error;\n isolatedReporter(options.reportDiagnostic)(\n `Error getting repository root: ${knownError ? error.message : 'unknown error'}`\n );\n throw error;\n }\n}\n\n/**\n * Config overrides, placed before `diff`, that keep output parseable whatever the user's config\n * says.\n */\nexport const PARSER_COMPATIBLE_GIT_CONFIG: readonly string[] = [\n '-c',\n 'color.ui=never',\n '-c',\n 'diff.noprefix=false',\n '-c',\n 'diff.mnemonicPrefix=false',\n // Untracked enumeration, context expansion and Apply all resolve paths against the root.\n '-c',\n 'diff.relative=false',\n];\n\n/** Appended after the user's options so a user `--color=always` or `--no-prefix` loses. */\nexport const PARSER_COMPATIBLE_DIFF_FLAGS: readonly string[] = [\n '--no-color',\n '--no-ext-diff',\n '--no-textconv',\n '--src-prefix=a/',\n '--dst-prefix=b/',\n];\n\n/** Inserts the flags after every user option and before `--`. */\nexport function withParserCompatibleDiffArgs(args: readonly string[]): string[] {\n const separator = parseGitDiffArgs(args).separatorIndex;\n if (separator === null) {\n return [...args, ...PARSER_COMPATIBLE_DIFF_FLAGS];\n }\n return [...args.slice(0, separator), ...PARSER_COMPATIBLE_DIFF_FLAGS, ...args.slice(separator)];\n}\n\n/**\n * The one entry point for every `git diff` (load, expansion, remote), so the\n * parser-compatible normalization applies uniformly. Output past `maxOutputBytes`\n * rejects with an error {@link isOutputLimitError} recognizes.\n */\nexport async function runGitDiffAsync(\n args: string[],\n cwd?: string,\n maxOutputBytes: number = MAX_GIT_DIFF_OUTPUT_BYTES,\n options: GitExecutionOptions = {}\n): Promise<string> {\n try {\n return await executeGit(\n [...PARSER_COMPATIBLE_GIT_CONFIG, 'diff', ...withParserCompatibleDiffArgs(args)],\n cwd,\n { ...options, timeoutMs: options.timeoutMs ?? 30_000 },\n maxOutputBytes\n );\n } catch (error) {\n const knownError = error instanceof Error;\n isolatedReporter(options.reportDiagnostic)(\n `Error running git diff: ${knownError ? error.message : 'unknown error'}`\n );\n throw error;\n }\n}\n\n/**\n * Strict enumeration for loaders (respects .gitignore); failures must reach their diagnostics.\n *\n * Pass the repository root. `git ls-files` reports paths relative to the\n * directory it runs in and lists that subtree only, while `git diff` reports\n * root-relative paths for the whole repository from anywhere inside it. Run\n * anywhere else and the names match neither the diff nor the root the files\n * are read from.\n *\n * `-z` keeps the names literal. NUL termination survives newlines in\n * filenames, and it turns off the C-style quoting git otherwise applies to\n * control characters and non-ASCII bytes.\n */\nexport async function listUntrackedFilesAsync(\n repoRoot?: string,\n options: GitExecutionOptions = {}\n): Promise<string[]> {\n const stdout = await executeGit(\n ['ls-files', '--others', '--exclude-standard', '-z'],\n repoRoot,\n options,\n 10 * 1024 * 1024\n );\n return stdout.split('\\0').filter(name => name.length > 0);\n}\n\n/** Compatibility helper: callers historically receive [] and a warning on listing failure. */\nexport async function getUntrackedFilesAsync(\n repoRoot?: string,\n options: GitExecutionOptions = {}\n): Promise<string[]> {\n try {\n return await listUntrackedFilesAsync(repoRoot, options);\n } catch (error) {\n if (isCommandCancelled(error) && error.reason === 'aborted') throw error;\n isolatedReporter(options.reportDiagnostic)(\n `Warning: Failed to list untracked files: ${error instanceof Error ? error.message : 'unknown error'}`\n );\n return [];\n }\n}\n\n/** True when a child process exceeded `maxBuffer`: a budget hit, not a git failure. */\nexport function isOutputLimitError(error: unknown): boolean {\n return (error as NodeJS.ErrnoException | undefined)?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER';\n}\n\n/**\n * Generate synthetic unified diffs for untracked files so they can be\n * parsed by the existing diff parser. Untracked symlinks are described by\n * their link text, never followed.\n */\nexport function generateUntrackedDiffs(\n paths: string[],\n repoRoot: string,\n options: SyntheticDiffOptions = {}\n): SyntheticDiffResult {\n return generateSyntheticDiffs(paths, repoRoot, { ...options, followSymlinks: false });\n}\n","// materializer.ts\n// Clone-aware diff materializer: turns a parsed forge URL into a local git\n// context. Reuses an existing matching clone (fetch only, no working-tree\n// changes) or creates a disposable blobless clone under the OS temp root,\n// then reports the resolved base/head SHAs so downstream code can run the\n// existing local git-mode pipeline over `baseSha...headSha`.\n//\n// Every run owns its snapshot: base and head are fetched into\n// `refs/self-review/<session>/base|head` and the SHAs read from exactly those refs,\n// so concurrent sessions never see each other's SHAs (R16). Every git command runs\n// under the session's `AbortSignal` and a per-command timeout.\n//\n// All git interaction goes through an injectable command runner (the same\n// shape providers use) so unit tests never spawn real git. This module never\n// talks to a forge API: head refs come from the forges' well-known git refs\n// (`refs/pull/N/head`, `refs/merge-requests/N/head`) over plain git.\n\nimport type { DiagnosticReporter } from './diagnostics';\nimport { isolatedReporter } from './effect-diagnostics';\nimport { randomUUID } from 'crypto';\nimport { nodeTemporaryCloneStorage } from './remote-temp';\nimport type { TemporaryCloneStorage } from './remote-temp';\nexport { nodeTemporaryCloneStorage } from './remote-temp';\nexport type { TemporaryCloneStorage } from './remote-temp';\nimport { stripTrailingNewline } from './git';\nimport { defaultGitRunner } from './command-runner';\nexport { defaultGitRunner } from './command-runner';\nimport { CommandCancelledError } from './forge-provider';\nimport { FORGE_DEFINITIONS } from './forge-definitions';\nimport type {\n ForgeCommandOptions,\n ForgeCommandResult,\n ForgeCommandRunner,\n ForgeUrl,\n} from './forge-provider';\n\n/** How the local git context was obtained. */\nexport type MaterializeMode = 'existing-clone' | 'temp-clone';\n\n/** Result of materializing a forge URL into a local git context. */\nexport interface MaterializeResult {\n /** Root of the git repository to run the diff pipeline in. */\n repoPath: string;\n /** Resolved SHA of the PR/MR base branch tip. */\n baseSha: string;\n /** Resolved SHA of the PR/MR head (the live remote head). */\n headSha: string;\n mode: MaterializeMode;\n /**\n * Refs this session created in a reused clone and deletes on cleanup; empty for a temp clone.\n */\n ownedRefs: readonly string[];\n /**\n * Removes the temp clone (synchronously, before the first await, so an `exit`\n * handler that cannot wait still gets that far) and deletes the session's refs\n * from a reused clone. Idempotent, never rejects; a failed deletion goes to stderr.\n * A caller that opts into cleanupAsync must await that disposal: while it is in flight,\n * cleanup joins the same deletion rather than starting a competing synchronous removal.\n */\n cleanup: () => Promise<void>;\n /** Nonblocking normal disposal; concurrent calls share one attempt and failures can be retried. */\n cleanupAsync?: () => Promise<void>;\n}\n\n/** A local clone whose fetch remote matches the requested forge repository. */\nexport interface ExistingClone {\n repoPath: string;\n remoteName: string;\n}\n\nexport interface MaterializeOptions {\n /** Authoritative owner of temporary clone creation and both removal modes. */\n temporaryClones?: TemporaryCloneStorage;\n /** Per-call progress and cleanup diagnostics. Defaults to stderr; must not throw. */\n reportDiagnostic?: DiagnosticReporter;\n /**\n * Aborting kills the command in flight and rejects with {@link CommandCancelledError}; the temp\n * clone is removed first.\n */\n signal?: AbortSignal;\n /** Defaults to {@link DEFAULT_GIT_COMMAND_TIMEOUT_MS}. */\n commandTimeoutMs?: number;\n}\n\n/**\n * Generous because a blobless clone over a slow link is legitimately slow; tighter hosts abort via\n * the signal.\n */\nexport const DEFAULT_GIT_COMMAND_TIMEOUT_MS = 10 * 60 * 1000;\n\nconst CLEANUP_COMMAND_TIMEOUT_MS = 15_000;\n\nconst AUTH_HINT =\n 'Hint: if this repository is private or requires authentication, run ' +\n '`gh auth setup-git` (GitHub) or `glab auth git-credential` (GitLab) to ' +\n 'wire your CLI credentials into git.';\n\n/** Well-known git ref for the PR/MR head on each forge. */\nfunction headRefFor(url: ForgeUrl): string {\n return FORGE_DEFINITIONS[url.forge].headRef(url.number);\n}\n\n/**\n * HTTPS clone URL for the forge repository. Git's credential machinery\n * (helpers, `gh auth setup-git`) handles auth; no transport selection here.\n */\nfunction cloneUrlFor(url: ForgeUrl): string {\n return `https://${url.host}/${url.owner}/${url.repo}.git`;\n}\n\n/** The refs one session fetches into. Unique per call. */\nfunction sessionRefs(): { base: string; head: string } {\n const session = randomUUID();\n return {\n base: `refs/self-review/${session}/base`,\n head: `refs/self-review/${session}/head`,\n };\n}\n\n/** A git runner bound to one session's bounds: `git <args>` under its signal and timeout. */\ntype SessionGit = (args: string[]) => Promise<ForgeCommandResult>;\n\nfunction bindGit(runner: ForgeCommandRunner, options: MaterializeOptions): SessionGit {\n const commandOptions: ForgeCommandOptions = {\n signal: options.signal,\n gitEnvironment: 'isolated',\n timeoutMs: options.commandTimeoutMs ?? DEFAULT_GIT_COMMAND_TIMEOUT_MS,\n };\n return args => {\n // A scripted runner may ignore the signal; the answer must not depend on the runner.\n if (options.signal?.aborted) {\n return Promise.reject(new CommandCancelledError('aborted', 'git', args));\n }\n return runner('git', args, commandOptions);\n };\n}\n\nfunction gitFailure(what: string, result: ForgeCommandResult, withAuthHint: boolean): Error {\n const stderr = result.stderr.trim();\n const lines = [\n `git ${what} failed (exit code ${result.exitCode})${stderr ? `:\\n${stderr}` : ''}`,\n ];\n if (withAuthHint) {\n lines.push('', AUTH_HINT);\n }\n return new Error(lines.join('\\n'));\n}\n\n/** Strip a trailing `.git` and trailing slashes from a repo path. */\nfunction stripRepoPath(repoPath: string): string {\n return repoPath.replace(/\\/+$/, '').replace(/\\.git$/i, '');\n}\n\n/**\n * Normalize a git remote URL (SSH scp-style, ssh://, http(s)://) into a\n * comparable `{ host, path }` pair, or `null` when unrecognized.\n */\nfunction normalizeRemoteUrl(raw: string): { host: string; path: string } | null {\n const trimmed = raw.trim();\n if (trimmed.includes('://')) {\n try {\n const parsed = new URL(trimmed);\n return {\n host: parsed.host.toLowerCase(),\n path: stripRepoPath(parsed.pathname.replace(/^\\/+/, '')).toLowerCase(),\n };\n } catch {\n return null;\n }\n }\n // scp-style: [user@]host:path\n const scp = /^(?:[^@\\s]+@)?([^:/\\s]+):(.+)$/.exec(trimmed);\n if (scp) {\n return {\n host: scp[1].toLowerCase(),\n path: stripRepoPath(scp[2].replace(/^\\/+/, '')).toLowerCase(),\n };\n }\n return null;\n}\n\n/**\n * Parse `git remote -v` output and return the name of the first remote whose\n * fetch URL matches the forge URL's host and owner/repo, or `null`.\n */\nfunction findMatchingRemote(remoteVOutput: string, url: ForgeUrl): string | null {\n const wantedHost = url.host.toLowerCase();\n const wantedPath = `${url.owner}/${url.repo}`.toLowerCase();\n for (const line of remoteVOutput.split('\\n')) {\n const match = /^(\\S+)\\t(.+?)\\s+\\(fetch\\)$/.exec(line.trim());\n if (!match) continue;\n const normalized = normalizeRemoteUrl(match[2]);\n if (normalized && normalized.host === wantedHost && normalized.path === wantedPath) {\n return match[1];\n }\n }\n return null;\n}\n\nasync function revParse(git: SessionGit, repoPath: string, ref: string): Promise<string> {\n const result = await git(['-C', repoPath, 'rev-parse', ref]);\n if (result.exitCode !== 0) {\n throw gitFailure(`rev-parse ${ref}`, result, false);\n }\n return result.stdout.trim();\n}\n\n/** One fetch into this session's refs, SHAs read back from exactly those refs. */\nasync function fetchSnapshot(\n git: SessionGit,\n repoPath: string,\n remote: string,\n url: ForgeUrl,\n baseBranch: string,\n refs: { base: string; head: string },\n failureLabel: string\n): Promise<{ baseSha: string; headSha: string }> {\n // Forced refspecs are fine: these refs are ours alone.\n const fetch = await git([\n '-C',\n repoPath,\n 'fetch',\n '--refmap=',\n '--no-tags',\n '--no-write-fetch-head',\n '--recurse-submodules=no',\n remote,\n `+refs/heads/${baseBranch}:${refs.base}`,\n `+${headRefFor(url)}:${refs.head}`,\n ]);\n if (fetch.exitCode !== 0) {\n throw gitFailure(failureLabel, fetch, true);\n }\n return {\n baseSha: await revParse(git, repoPath, refs.base),\n headSha: await revParse(git, repoPath, refs.head),\n };\n}\n\n/**\n * Detect an existing clone: when `cwd` is inside a git repository with a\n * remote matching the forge URL, return `{ repoPath, remoteName }`.\n */\nexport async function detectExistingClone(\n url: ForgeUrl,\n cwd: string,\n runner: ForgeCommandRunner = defaultGitRunner,\n options: MaterializeOptions = {}\n): Promise<ExistingClone | null> {\n const git = bindGit(runner, options);\n const toplevel = await git(['-C', cwd, 'rev-parse', '--show-toplevel']);\n if (toplevel.exitCode !== 0) {\n return null;\n }\n // A blanket .trim() would eat whitespace that is part of the actual path\n // (SR-0047, same defect class as SR-0036's git.ts fix), reporting a root\n // short of what's on disk and breaking the `remote -v` call right after.\n const repoPath = stripTrailingNewline(toplevel.stdout);\n const remotes = await git(['-C', repoPath, 'remote', '-v']);\n if (remotes.exitCode !== 0) {\n return null;\n }\n const remoteName = findMatchingRemote(remotes.stdout, url);\n return remoteName === null ? null : { repoPath, remoteName };\n}\n\nasync function materializeIntoExistingClone(\n runner: ForgeCommandRunner,\n options: MaterializeOptions,\n url: ForgeUrl,\n baseBranch: string,\n repoPath: string,\n remoteName: string\n): Promise<MaterializeResult> {\n const reportDiagnostic = isolatedReporter(options.reportDiagnostic);\n reportDiagnostic(`self-review: reusing existing clone at ${repoPath} (remote \"${remoteName}\")`);\n const git = bindGit(runner, options);\n const refs = sessionRefs();\n const ownedRefs = [refs.base, refs.head];\n\n // Not under the session signal: an aborted session must still release its refs.\n const pendingRefs = new Set(ownedRefs);\n let releasing: Promise<void> | undefined;\n const releaseRefs = async (): Promise<void> => {\n for (const ref of pendingRefs) {\n try {\n const result = await runner('git', ['-C', repoPath, 'update-ref', '-d', ref], {\n timeoutMs: CLEANUP_COMMAND_TIMEOUT_MS,\n gitEnvironment: 'isolated',\n });\n if (result.exitCode !== 0) {\n reportCleanupDiagnostic(\n reportDiagnostic,\n `self-review: could not delete ${ref} in ${repoPath}: ${result.stderr.trim()}`\n );\n } else {\n pendingRefs.delete(ref);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n reportCleanupDiagnostic(\n reportDiagnostic,\n `self-review: could not delete ${ref} in ${repoPath}: ${message}`\n );\n }\n }\n };\n\n const cleanup = (): Promise<void> => {\n releasing ??= releaseRefs().finally(() => {\n releasing = undefined;\n });\n return releasing;\n };\n\n // Namespaced refs only: no checkout, branch or working-tree change. A part-way\n // failure may have created one ref, so release them before rethrowing.\n try {\n const { baseSha, headSha } = await fetchSnapshot(\n git,\n repoPath,\n remoteName,\n url,\n baseBranch,\n refs,\n `fetch from remote \"${remoteName}\"`\n );\n return { repoPath, baseSha, headSha, mode: 'existing-clone', ownedRefs, cleanup };\n } catch (error) {\n await cleanup();\n throw error;\n }\n}\n\nasync function materializeIntoTempClone(\n runner: ForgeCommandRunner,\n options: MaterializeOptions,\n url: ForgeUrl,\n baseBranch: string\n): Promise<MaterializeResult> {\n const git = bindGit(runner, options);\n const reportDiagnostic = isolatedReporter(options.reportDiagnostic);\n // This run creates the directory, so cleanup may only ever remove it; it is owned\n // from here on, before any git runs.\n const storage = options.temporaryClones ?? nodeTemporaryCloneStorage;\n const tempDir = await storage.create();\n let removed = false;\n let removing: Promise<void> | undefined;\n const failed = (error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n reportDiagnostic(`self-review: could not remove ${tempDir}: ${message}`);\n };\n const cleanupAsync = (): Promise<void> => {\n if (removed) return Promise.resolve();\n removing ??= Promise.resolve().then(async () => {\n try {\n await storage.remove(tempDir);\n removed = true;\n } catch (error) {\n failed(error);\n } finally {\n removing = undefined;\n }\n });\n return removing;\n };\n const cleanup = (): Promise<void> => {\n if (removed) return Promise.resolve();\n // Do not start a competing recursive deletion when normal disposal is already running.\n if (removing) return removing;\n try {\n storage.removeSync(tempDir);\n removed = true;\n } catch (error) {\n failed(error);\n }\n return Promise.resolve();\n };\n\n try {\n reportDiagnostic(`self-review: created temporary blobless clone at ${tempDir}`);\n const cloneUrl = cloneUrlFor(url);\n // Blobless, never shallow: --depth would break merge-base computation.\n const clone = await git(['clone', '--filter=blob:none', cloneUrl, tempDir]);\n if (clone.exitCode !== 0) {\n throw gitFailure(`clone of ${cloneUrl}`, clone, true);\n }\n const { baseSha, headSha } = await fetchSnapshot(\n git,\n tempDir,\n 'origin',\n url,\n baseBranch,\n sessionRefs(),\n `fetch of ${headRefFor(url)}`\n );\n return {\n repoPath: tempDir,\n baseSha,\n headSha,\n mode: 'temp-clone',\n ownedRefs: [],\n cleanup,\n cleanupAsync,\n };\n } catch (error) {\n await cleanupAsync();\n throw error;\n }\n}\n\n/**\n * Materialize a forge PR/MR into a local git context.\n *\n * When `cwd` is inside a git repository with a remote matching the forge\n * URL (SSH and HTTPS forms recognized, `.git` suffix tolerated), the base\n * branch and PR/MR head refs are fetched into that clone under\n * `refs/self-review/<session>/` (read-only for the working tree; `cleanup()`\n * deletes exactly those two refs). Otherwise a blobless clone is created in a\n * unique directory under the OS temp root and `cleanup()` removes it. Callers\n * that already detected a clone may pass it to skip the git probes.\n *\n * The returned `headSha` is the live remote head, so callers can compare it\n * against a recorded `remote-head-sha` for drift detection.\n */\nexport async function materialize(\n url: ForgeUrl,\n baseBranch: string,\n cwd: string,\n runner: ForgeCommandRunner = defaultGitRunner,\n existingClone?: ExistingClone | null,\n options: MaterializeOptions = {}\n): Promise<MaterializeResult> {\n if (options.signal?.aborted) {\n throw new CommandCancelledError('aborted', 'git', ['materialize', cloneUrlFor(url)]);\n }\n const existing =\n existingClone === undefined\n ? await detectExistingClone(url, cwd, runner, options)\n : existingClone;\n if (existing) {\n return materializeIntoExistingClone(\n runner,\n options,\n url,\n baseBranch,\n existing.repoPath,\n existing.remoteName\n );\n }\n return materializeIntoTempClone(runner, options, url, baseBranch);\n}\n\n/**\n * Git-only fallback for the base branch when no forge CLI is available:\n * resolves the remote's default branch from its HEAD symref via\n * `git ls-remote --symref <remote> HEAD`. When an existing matching clone\n * is supplied, the configured remote is used so its SSH/HTTPS transport\n * and credentials are preserved. Otherwise the forge HTTPS URL is used.\n * No forge API involved.\n */\nexport async function resolveRemoteDefaultBranch(\n url: ForgeUrl,\n runner: ForgeCommandRunner = defaultGitRunner,\n existing: ExistingClone | null = null,\n options: MaterializeOptions = {}\n): Promise<string> {\n const git = bindGit(runner, options);\n const cloneUrl = cloneUrlFor(url);\n const remote = existing?.remoteName ?? cloneUrl;\n // Errors must identify the repository; a bare alias such as \"origin\"\n // does not say which repository the lookup was made against.\n const label = existing ? `${remote} (${cloneUrl})` : cloneUrl;\n const args = existing\n ? ['-C', existing.repoPath, 'ls-remote', '--symref', remote, 'HEAD']\n : ['ls-remote', '--symref', remote, 'HEAD'];\n const result = await git(args);\n if (result.exitCode !== 0) {\n throw gitFailure(`ls-remote of ${label}`, result, true);\n }\n const match = /^ref:\\s+refs\\/heads\\/(\\S+)\\s+HEAD$/m.exec(result.stdout);\n if (!match) {\n throw new Error(\n `Failed to resolve the default branch of ${label}: ` +\n 'git ls-remote returned no HEAD symref.'\n );\n }\n return match[1];\n}\n\n// A presentation failure must never interrupt resource release or replace its primary outcome.\nfunction reportCleanupDiagnostic(report: DiagnosticReporter, message: string): void {\n try {\n report(message);\n } catch {\n /* Cleanup is best effort and never rejects. */\n }\n}\n","// Session-owned state and synchronous payload projections. No filesystem dependencies.\nimport type {\n DiffLoadPayload,\n DiffFile,\n DiffHunk,\n ResumeLoadPayload,\n GuideLoadPayload,\n AppConfig,\n OutputPathInfo,\n ReviewState,\n ReviewComment,\n ReviewSourceIdentity,\n RemoteDriftInfo,\n} from './types';\nimport { loadedReviewIdentity, type LoadedReview } from './loaded-snapshot';\nimport type { AttachmentOrigins } from './attachment-origins';\nimport { stderrReporter, type DiagnosticReporter } from './diagnostics';\nimport { isolatedReporter } from './effect-diagnostics';\nimport { validateReviewState } from './review-state-validation';\n\n/**\n * The state a single review session owns. One desktop application window is\n * one session; two sessions are independent and cannot observe each other.\n */\nexport interface ReviewSession {\n reviewState: ReviewState | null;\n diffData: DiffLoadPayload | null;\n guideData: GuideLoadPayload | null;\n config: AppConfig | null;\n outputPathInfo: OutputPathInfo | null;\n resumeComments: ReviewComment[];\n resumeViewedFiles: string[];\n resumeRemoteDrift: RemoteDriftInfo | null;\n resumeImportDiagnostics: string[];\n /**\n * Destination directory the user named for this session's applies, or\n * null when none has been named. Only a temporary-clone remote review\n * needs one; see {@link resolveApplyDestination}.\n */\n applyDestinationRoot: string | null;\n /**\n * Old and new path of every file in the committed diff, frozen by {@link commitDiffData}.\n * The authorization set for writes; resumed comments, submitted state and placeholder\n * entries can name other paths and never reach it.\n */\n reviewedPaths: ReadonlySet<string>;\n /**\n * Recorded by {@link commitDiffData}; null until then (and for welcome), when every read of\n * reviewed content refuses.\n */\n sourceIdentity: ReviewSourceIdentity | null;\n /** Host-local captured load, optional for legacy session objects. Never transport this value. */\n loadedReview?: LoadedReview | null;\n /**\n * Resumed reference to absolute path beside *the resumed document*; authorizes reads and tells\n * the publisher which bytes to carry. Never sent to the front end.\n */\n attachmentOrigins: AttachmentOrigins;\n}\n\n/** Create an empty session. */\nexport function createReviewSession(): ReviewSession {\n return {\n reviewState: null,\n diffData: null,\n guideData: null,\n config: null,\n outputPathInfo: null,\n resumeComments: [],\n resumeViewedFiles: [],\n resumeRemoteDrift: null,\n resumeImportDiagnostics: [],\n applyDestinationRoot: null,\n reviewedPaths: emptyReviewedPaths(),\n sourceIdentity: null,\n attachmentOrigins: new Map(),\n };\n}\n\nfunction emptyReviewedPaths(): ReadonlySet<string> {\n return freezeSet(new Set<string>());\n}\n\nfunction freezeSet(set: Set<string>): ReadonlySet<string> {\n const frozen = () => {\n throw new TypeError('reviewedPaths is captured when the diff is committed and cannot change');\n };\n Object.defineProperties(set, {\n add: { value: frozen },\n delete: { value: frozen },\n clear: { value: frozen },\n });\n return Object.freeze(set);\n}\n\nfunction reviewedPathsOf(files: readonly DiffFile[]): ReadonlySet<string> {\n const paths = new Set<string>();\n for (const file of files) {\n if (file.newPath) paths.add(file.newPath);\n if (file.oldPath) paths.add(file.oldPath);\n }\n return freezeSet(paths);\n}\n\n/**\n * The one place a diff is committed to a session: captures `reviewedPaths` and\n * records `sourceIdentity`; later `diffData` edits (expanded hunks) leave both alone.\n * The identity comes from the loader, and is `null` only for a payload that\n * reviews nothing (welcome), so reads refuse rather than guess a root.\n */\nexport function commitDiffData(\n session: Pick<ReviewSession, 'diffData' | 'reviewedPaths' | 'sourceIdentity'>,\n payload: DiffLoadPayload,\n identity: ReviewSourceIdentity | null\n): void {\n if ('loadedReview' in session)\n (session as { loadedReview?: LoadedReview | null }).loadedReview = null;\n session.diffData = payload;\n session.reviewedPaths = reviewedPathsOf(payload.files);\n session.sourceIdentity = identity;\n}\n\n/** Commit explicit load evidence while preserving the original payload and identity aliases. */\nexport function commitLoadedReview(\n session: Pick<ReviewSession, 'diffData' | 'reviewedPaths' | 'sourceIdentity' | 'loadedReview'>,\n payload: DiffLoadPayload,\n loadedReview: LoadedReview\n): void {\n const identity = loadedReviewIdentity(loadedReview);\n commitDiffData(session, payload, identity);\n session.loadedReview = loadedReview;\n}\n\n/**\n * The old side is where a deletion or a rename's old name lives. Null when the diff has no such\n * file.\n */\nexport function locateReviewedFile(\n session: Pick<ReviewSession, 'diffData'>,\n filePath: string\n): { file: DiffFile; side: 'old' | 'new' } | null {\n const files = session.diffData?.files ?? [];\n const byNewPath = files.find(f => f.newPath !== '' && f.newPath === filePath);\n if (byNewPath) return { file: byNewPath, side: 'new' };\n const byOldPath = files.find(f => f.oldPath !== '' && f.oldPath === filePath);\n if (byOldPath) return { file: byOldPath, side: 'old' };\n return null;\n}\n\n/**\n * Prepare a DiffLoadPayload for IPC transmission.\n * In large-payload mode, strips hunks from files to reduce initial transfer size.\n * The full data stays in the session for on-demand loading via DIFF_LOAD_FILE.\n */\nexport function preparePayload(payload: DiffLoadPayload): DiffLoadPayload {\n if (payload.isLargePayload) {\n return {\n ...payload,\n files: payload.files.map(f => ({ ...f, hunks: [] as DiffHunk[], contentLoaded: false })),\n };\n }\n return {\n ...payload,\n files: payload.files.map(f => ({ ...f, contentLoaded: true })),\n };\n}\n\n/**\n * Resolve what a diff request should deliver: the prepared diff payload and,\n * when one is loaded, the guide that rides with it. Returns null when the\n * session has no diff, so the caller sends nothing at all.\n */\nexport function getDiffLoad(\n session: Pick<ReviewSession, 'diffData' | 'guideData'>\n): { diff: DiffLoadPayload; guide: GuideLoadPayload | null } | null {\n if (!session.diffData) {\n return null;\n }\n // The guide rides after the diff payload in both normal and\n // large-payload modes — it is metadata-only (paths, names,\n // descriptions) and never triggers eager hunk loading.\n return {\n diff: preparePayload(session.diffData),\n guide: session.guideData,\n };\n}\n\n/** The read-only source root; {@link resolveApplyDestination} decides where applies write. */\nexport function resolveSourceBaseDir(\n session: Pick<ReviewSession, 'sourceIdentity'>\n): string | null {\n return session.sourceIdentity?.sourceRoot ?? null;\n}\n\n/**\n * Return a single file's hunks for lazy (large-payload) mode, or null when the\n * session has no diff or the diff has no such file.\n */\nexport function getFileHunks(\n session: Pick<ReviewSession, 'diffData'>,\n filePath: string\n): DiffHunk[] | null {\n if (!session.diffData) return null;\n const file = session.diffData.files.find(f => (f.newPath || f.oldPath) === filePath);\n if (!file) return null;\n return file.hunks;\n}\n\n/**\n * Resolve the config and the output path info that travel with it. Returns null\n * when the session has no config, so the caller sends nothing at all: the\n * renderer distinguishes an absent message from an empty one.\n */\nexport function getConfigLoad(\n session: Pick<ReviewSession, 'config' | 'outputPathInfo'>\n): { config: AppConfig; outputPathInfo: OutputPathInfo | null } | null {\n if (!session.config) {\n return null;\n }\n return { config: session.config, outputPathInfo: session.outputPathInfo };\n}\n\n/**\n * Store a review state submitted by the front end on the session.\n */\nexport function submitReviewState(\n session: Pick<ReviewSession, 'reviewState'>,\n state: ReviewState,\n reportDiagnostic: DiagnosticReporter = stderrReporter\n): void {\n state = validateReviewState(state);\n isolatedReporter(reportDiagnostic)(\n '[review] Review state submitted:',\n JSON.stringify({\n timestamp: state.timestamp,\n source: state.source,\n fileCount: state.files.length,\n })\n );\n session.reviewState = state;\n}\n\n/**\n * Take the submitted review state off the session, clearing it so it is\n * consumed exactly once. Returns null when nothing has been submitted.\n */\nexport function takeReviewState(session: Pick<ReviewSession, 'reviewState'>): ReviewState | null {\n const state = session.reviewState;\n session.reviewState = null;\n return state;\n}\n\n/**\n * Resolve the resumed comments, viewed files and remote drift for a session.\n * Returns null when there is nothing to resume, so the caller sends nothing\n * at all.\n */\nexport function getResumeLoad(\n session: Pick<\n ReviewSession,\n 'resumeComments' | 'resumeViewedFiles' | 'resumeRemoteDrift' | 'resumeImportDiagnostics'\n >\n): ResumeLoadPayload | null {\n if (\n session.resumeComments.length > 0 ||\n session.resumeViewedFiles.length > 0 ||\n session.resumeRemoteDrift !== null ||\n session.resumeImportDiagnostics.length > 0\n ) {\n const payload: ResumeLoadPayload = {\n comments: session.resumeComments,\n viewedFiles: session.resumeViewedFiles,\n };\n if (session.resumeRemoteDrift !== null) {\n payload.remoteDrift = session.resumeRemoteDrift;\n }\n if (session.resumeImportDiagnostics.length > 0) {\n payload.importDiagnostics = session.resumeImportDiagnostics;\n }\n return payload;\n }\n return null;\n}\n","// Resolves the two snapshots a `git diff` compares, once at load, so later reads (an image\n// preview of a staged review) use those bytes and not the working tree. A shape this\n// module cannot vouch for is `unknown`, and a read from it fails visibly.\n\nimport { realpathSync } from 'fs';\nimport * as path from 'path';\nimport type { ReviewSourceIdentity, ReviewSourceSide } from './types';\nimport { parseGitDiffArgs, describeDiffPathRelativity } from './git-diff-args';\n\nimport { executeGit, type GitExecutionOptions } from './git';\nimport { checkLoadingCancelled } from './local-loading-lifetime';\nimport { isCommandCancelled } from './forge-provider';\n\n/** One side as the arguments describe it, before resolution; `implicit` is the HEAD git assumes. */\nexport type GitDiffSideSpec =\n | { kind: 'working-tree' }\n | { kind: 'index' }\n | { kind: 'revision'; rev: string; implicit: boolean }\n | { kind: 'merge-base'; left: string; right: string }\n | { kind: 'unknown'; reason: string };\n\nexport interface GitDiffSides {\n oldSide: GitDiffSideSpec;\n newSide: GitDiffSideSpec;\n}\n\nconst WORKING_TREE: GitDiffSideSpec = { kind: 'working-tree' };\nconst INDEX: GitDiffSideSpec = { kind: 'index' };\nconst HEAD: GitDiffSideSpec = { kind: 'revision', rev: 'HEAD', implicit: true };\n\nfunction revision(rev: string): GitDiffSideSpec {\n return rev === '' ? HEAD : { kind: 'revision', rev, implicit: false };\n}\n\nfunction mergeBase(left: string, right: string): GitDiffSideSpec {\n return { kind: 'merge-base', left: left || 'HEAD', right: right || 'HEAD' };\n}\n\nfunction unknownSides(reason: string): GitDiffSides {\n return { oldSide: { kind: 'unknown', reason }, newSide: { kind: 'unknown', reason } };\n}\n\n/**\n * The two snapshots a `git diff` argv compares. Pure: runs no git and checks no revision.\n * Uses the classifier's arity rules, so `-S --cached` is not a flag. `--no-index`, three\n * or more revisions and `--cached` with a range are `unknown`.\n */\nexport function describeGitDiffSides(argv: readonly string[]): GitDiffSides {\n const parsed = parseGitDiffArgs(argv);\n const names = new Set(parsed.options.map(option => option.name));\n if (names.has('--no-index')) return unknownSides('--no-index compares paths, not snapshots');\n const revs = parsed.positionalIndices\n .filter(index => parsed.separatorIndex === null || index < parsed.separatorIndex)\n .map(index => argv[index]);\n const cached = names.has('--cached') || names.has('--staged');\n const reverse = names.has('-R');\n const useMergeBase = names.has('--merge-base');\n\n const sides = describeRevisionSides(revs, cached, useMergeBase);\n return reverse ? { oldSide: sides.newSide, newSide: sides.oldSide } : sides;\n}\n\nfunction describeRevisionSides(\n revs: readonly string[],\n cached: boolean,\n useMergeBase: boolean\n): GitDiffSides {\n if (revs.length === 0) {\n if (useMergeBase) return unknownSides('--merge-base requires a revision');\n return cached ? { oldSide: HEAD, newSide: INDEX } : { oldSide: INDEX, newSide: WORKING_TREE };\n }\n\n if (revs.length === 1) {\n const rev = revs[0];\n const symmetric = rev.indexOf('...');\n if (symmetric !== -1) {\n if (cached) return unknownSides('--cached does not accept a revision range');\n const left = rev.slice(0, symmetric);\n const right = rev.slice(symmetric + 3);\n return { oldSide: mergeBase(left, right), newSide: revision(right) };\n }\n const range = rev.indexOf('..');\n if (range !== -1) {\n if (cached) return unknownSides('--cached does not accept a revision range');\n return { oldSide: revision(rev.slice(0, range)), newSide: revision(rev.slice(range + 2)) };\n }\n const oldSide = useMergeBase ? mergeBase(rev, 'HEAD') : revision(rev);\n return { oldSide, newSide: cached ? INDEX : WORKING_TREE };\n }\n\n if (revs.length === 2) {\n if (cached) return unknownSides('--cached does not accept two revisions');\n const [left, right] = revs;\n return {\n oldSide: useMergeBase ? mergeBase(left, right) : revision(left),\n newSide: revision(right),\n };\n }\n\n return unknownSides(`a combined diff of ${revs.length} revisions has no single old side`);\n}\n\nasync function gitOutput(\n repository: string,\n args: string[],\n options: GitExecutionOptions\n): Promise<string | null> {\n try {\n return (await executeGit(args, repository, options)).replace(/\\r?\\n$/, '');\n } catch (error) {\n if (isCommandCancelled(error)) throw error;\n return null;\n }\n}\n\nconst SHA_PATTERN = /^[0-9a-f]{40,64}$/;\n\nasync function resolveCommit(\n repository: string,\n rev: string,\n options: GitExecutionOptions\n): Promise<string | null> {\n // `--end-of-options` keeps a leading `-` from being an option; `^{commit}` refuses a blob or\n // tree.\n const sha = await gitOutput(\n repository,\n ['rev-parse', '--verify', '--quiet', '--end-of-options', `${rev}^{commit}`],\n options\n );\n return sha !== null && SHA_PATTERN.test(sha) ? sha : null;\n}\n\nasync function resolveSide(\n repository: string,\n spec: GitDiffSideSpec,\n options: GitExecutionOptions\n): Promise<ReviewSourceSide> {\n switch (spec.kind) {\n case 'working-tree':\n case 'index':\n case 'unknown':\n return spec;\n case 'revision': {\n const sha = await resolveCommit(repository, spec.rev, options);\n if (sha !== null) return { kind: 'commit', sha };\n // An implicit HEAD resolving to nothing is an unborn branch: the empty tree.\n if (spec.implicit) return { kind: 'none' };\n return { kind: 'unknown', reason: `${spec.rev} does not name a commit` };\n }\n case 'merge-base': {\n const sha = await gitOutput(repository, ['merge-base', spec.left, spec.right], options);\n if (sha !== null && SHA_PATTERN.test(sha)) return { kind: 'commit', sha };\n return {\n kind: 'unknown',\n reason: `no merge base between ${spec.left} and ${spec.right}`,\n };\n }\n }\n}\n\nexport function canonicalSourcePath(target: string): string {\n try {\n return realpathSync(target);\n } catch {\n return path.resolve(target);\n }\n}\n\n/**\n * `ReviewSourceIdentity.pathPrefix`: empty for root-relative output, the\n * `--relative=<dir>` directory without trailing slashes, or for bare `--relative`\n * the launch directory under the root (empty when outside the work tree, as in git).\n */\nexport function resolveReviewedPathPrefix(\n gitDiffArgv: readonly string[],\n sourceRoot: string,\n invocationCwd: string,\n canonical: (target: string) => string = canonicalSourcePath\n): string {\n const relative = describeDiffPathRelativity(gitDiffArgv);\n switch (relative.kind) {\n case 'root':\n return '';\n case 'directory':\n return relative.directory.replace(/\\/+$/, '');\n case 'cwd': {\n const fromRoot = path.relative(canonical(sourceRoot), canonical(invocationCwd));\n if (fromRoot === '' || fromRoot.startsWith('..') || path.isAbsolute(fromRoot)) return '';\n return fromRoot.split(path.sep).join('/');\n }\n }\n}\n\n/** The one mapping every reader, Apply and re-diff uses, so they all name the same file. */\nexport function rootRelativeReviewedPath(\n identity: Pick<ReviewSourceIdentity, 'pathPrefix'>,\n filePath: string\n): string {\n return identity.pathPrefix === '' ? filePath : `${identity.pathPrefix}/${filePath}`;\n}\n\nexport interface GitSourceIdentityOptions extends GitExecutionOptions {\n /** Supplied source path resolution; never falls back to native realpath. */\n sourcePaths?: LocalSourcePaths;\n repository: string;\n gitDiffArgv: readonly string[];\n /** Defaults to the process's working directory. */\n invocationCwd?: string;\n /** `'remote'` for a materialized PR/MR; the git-mode machinery is the same. */\n mode?: 'git' | 'remote';\n}\n\n/** Resolves commits once. Unresolvable revisions become `unknown`; cancellation rejects. */\nexport async function resolveGitSourceIdentity(\n options: GitSourceIdentityOptions\n): Promise<ReviewSourceIdentity> {\n const sides = describeGitDiffSides(options.gitDiffArgv);\n const repository = options.repository;\n const [oldSide, newSide] = await Promise.all([\n resolveSide(repository, sides.oldSide, options),\n resolveSide(repository, sides.newSide, options),\n ]);\n const emptyTreeSha =\n oldSide.kind === 'none' || newSide.kind === 'none'\n ? await gitOutput(repository, ['hash-object', '-t', 'tree', '--stdin'], options)\n : null;\n const invocationCwd = options.invocationCwd ?? process.cwd();\n const sourceRoot = options.sourcePaths\n ? await canonicalLocalPath(repository, options.sourcePaths, options.signal)\n : canonicalSourcePath(repository);\n const physicalCwd =\n options.sourcePaths && describeDiffPathRelativity(options.gitDiffArgv).kind === 'cwd'\n ? await canonicalLocalPath(invocationCwd, options.sourcePaths, options.signal)\n : invocationCwd;\n return {\n mode: options.mode ?? 'git',\n ...(emptyTreeSha !== null && SHA_PATTERN.test(emptyTreeSha) ? { emptyTreeSha } : {}),\n sourceRoot,\n invocationCwd,\n gitDiffArgv: [...options.gitDiffArgv],\n pathPrefix: resolveReviewedPathPrefix(\n options.gitDiffArgv,\n sourceRoot,\n physicalCwd,\n options.sourcePaths ? target => target : canonicalSourcePath\n ),\n oldSide,\n newSide,\n };\n}\n\nexport interface LocalSourceIdentityOptions {\n type: 'directory' | 'file';\n sourcePath: string;\n /** Defaults to the process's working directory. */\n invocationCwd?: string;\n}\n\n/**\n * Everything is an addition, so the old side is `none`. A single-file review follows a\n * symlink the user named, recording its target once; its root is the parent of the path as given.\n */\nexport function resolveLocalSourceIdentity(\n options: LocalSourceIdentityOptions\n): ReviewSourceIdentity {\n return localIdentity(options, canonicalSourcePath);\n}\n\n/** The path role a local load needs; a supplied provider owns every canonicalization. */\nexport interface LocalSourcePaths {\n realpath(target: string): Promise<string>;\n}\n\n/** Async identity resolution for supplied sources; the synchronous public form stays native. */\nexport async function resolveLocalSourceIdentityAsync(\n options: LocalSourceIdentityOptions,\n paths: LocalSourcePaths,\n signal?: AbortSignal\n): Promise<ReviewSourceIdentity> {\n const canonical = (target: string) => canonicalLocalPath(target, paths, signal);\n const root = await canonical(\n options.type === 'file' ? path.dirname(options.sourcePath) : options.sourcePath\n );\n const file = options.type === 'file' ? await canonical(options.sourcePath) : undefined;\n return localIdentity(options, target =>\n target === options.sourcePath && file !== undefined ? file : root\n );\n}\n\nfunction localIdentity(\n options: LocalSourceIdentityOptions,\n canonical: (target: string) => string\n): ReviewSourceIdentity {\n const invocationCwd = options.invocationCwd ?? process.cwd();\n if (options.type === 'directory') {\n return {\n mode: 'directory',\n sourceRoot: canonical(options.sourcePath),\n invocationCwd,\n gitDiffArgv: [],\n pathPrefix: '',\n oldSide: { kind: 'none' },\n newSide: { kind: 'directory' },\n };\n }\n return {\n mode: 'file',\n sourceRoot: canonical(path.dirname(options.sourcePath)),\n invocationCwd,\n gitDiffArgv: [],\n pathPrefix: '',\n oldSide: { kind: 'none' },\n newSide: { kind: 'file', path: canonical(options.sourcePath) },\n };\n}\n\nasync function canonicalLocalPath(\n target: string,\n paths: LocalSourcePaths,\n signal?: AbortSignal\n): Promise<string> {\n checkLoadingCancelled(signal);\n try {\n const result = await paths.realpath(target);\n checkLoadingCancelled(signal);\n return result;\n } catch {\n checkLoadingCancelled(signal);\n // Keep per-path diagnostics without consulting a different filesystem.\n return path.resolve(target);\n }\n}\n","// Native descriptor reads shared by both Apply implementations use at most budget + 1 bytes.\nimport { SafeFsError } from './safe-fs-policy';\n\nexport function inputBudgetError(target: string, maxBytes: number): SafeFsError {\n return new SafeFsError(\n 'too-large',\n target,\n `The destination exceeds the ${maxBytes} byte Apply input limit, so nothing was written.`\n );\n}\n\nexport interface ReadChunk {\n buffer: Buffer;\n offset: number;\n length: number;\n}\n\n/** The drivers supply only the descriptor read; allocation and growth policy are identical. */\nexport function* boundedChunks(\n target: string,\n size: number,\n maxBytes: number\n): Generator<ReadChunk, Buffer, number> {\n if (size > maxBytes) throw inputBudgetError(target, maxBytes);\n let buffer = Buffer.alloc(Math.min(size + 1, maxBytes + 1));\n let filled = 0;\n for (;;) {\n const length = Math.min(buffer.length - filled, 64 * 1024);\n const read = yield { buffer, offset: filled, length };\n if (!Number.isInteger(read) || read < 0 || read > length)\n throw new SafeFsError('io-error', target, 'Invalid descriptor read length.');\n if (read === 0) return buffer.subarray(0, filled);\n filled += read;\n if (filled > maxBytes) throw inputBudgetError(target, maxBytes);\n if (filled === buffer.length) {\n const next = Buffer.alloc(Math.min(Math.max(1, buffer.length * 2), maxBytes + 1));\n buffer.copy(next);\n buffer = next;\n }\n }\n}\n\n/** Descriptor-only bounded role, independent of legacy whole-file readers and mutation methods. */\nexport interface BoundedSuggestionReader {\n readSync(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number | null\n ): number;\n}\n\n/** The compatibility boundary accepts the original optional readSync shape. */\nexport function readSuggestionSync(\n fd: number,\n target: string,\n size: number,\n maxBytes: number,\n layer: {\n readFileSync(fd: number): Buffer;\n readSync?: (\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number | null\n ) => number;\n }\n): Buffer {\n const read = layer.readSync;\n return read\n ? readSuggestionBoundedSync(fd, target, size, maxBytes, {\n readSync: (...args) => read.call(layer, ...args),\n })\n : readLegacySuggestionSync(fd, target, size, maxBytes, layer);\n}\n\n/** Legacy adapters own whole-file allocation; before/after size checks cannot bound that call. */\nfunction readLegacySuggestionSync(\n fd: number,\n target: string,\n size: number,\n maxBytes: number,\n layer: { readFileSync(fd: number): Buffer }\n): Buffer {\n if (size > maxBytes) throw inputBudgetError(target, maxBytes);\n const bytes = layer.readFileSync(fd);\n if (bytes.length > maxBytes) throw inputBudgetError(target, maxBytes);\n return bytes;\n}\n\n/** Native/default adapters and bounded embedders supply only descriptor reads. */\nexport function readSuggestionBoundedSync(\n fd: number,\n target: string,\n size: number,\n maxBytes: number,\n layer: BoundedSuggestionReader\n): Buffer {\n const chunks = boundedChunks(target, size, maxBytes);\n let step = chunks.next();\n while (!step.done) {\n const { buffer, offset, length } = step.value;\n const read = layer.readSync(fd, buffer, offset, length, null);\n step = chunks.next(read);\n }\n return step.value;\n}\n","// apply-suggestion.ts\n// Writes one anchored suggestion into one working file, or refuses and\n// writes nothing. Node-only, Electron-free, and free of process-global\n// state: the caller names the destination root, so nothing here ever\n// consults `process.cwd()`.\n//\n// The engine is deliberately narrow. It performs a byte-for-byte context\n// check and a literal line replacement — no fuzzy matching, no force flag,\n// no staging, no git. Every outcome is reported: a refusal names its reason\n// and leaves the file untouched (PRD Section 5.4.8). Containment and the\n// transactional write live here, not in a transport (audit A3/A4, R04).\n\nimport * as path from 'path';\nimport { constants as bufferConstants } from 'node:buffer';\nimport { MAX_SOURCE_FILE_BYTES } from './input-budgets';\nimport { prepareSuggestionContent } from './suggestion-content';\nimport { readSuggestionSync, boundedChunks } from './suggestion-read';\nimport { atomicReplaceAsync, nodeAsyncFsLayer, openContainedFileAsync } from './safe-fs-async';\nimport type { AsyncFsLayer } from './safe-fs-async';\nimport type { LineRange, Suggestion } from './types';\nimport { validateLineRange } from './anchor-validation';\nimport {\n atomicReplace,\n errnoOf,\n nodeFsLayer,\n openContainedFile,\n snapshotIdentity,\n toSafeFsError,\n} from './safe-fs';\nimport type { FileIdentity, FsLayer, SafeFsErrorCode } from './safe-fs';\n\n/**\n * Why an apply was refused. Every value is a structural fact about the\n * request or the file — never a fragment of the file's contents, so a\n * refusal is safe to surface in the UI and in logs.\n */\nexport type ApplyRefusalReason =\n /** The suggestion is file-level: there is nothing to replace. */\n | 'no-anchor'\n /**\n * The anchor names deleted lines (`side: 'old'`). Those lines are not in\n * the working file, and the app holds no old→new line mapping, so the\n * target is undefined rather than merely missing.\n */\n | 'old-side-anchor'\n /** Unknown side, non-positive or non-integer bounds, or reversed; checked before any I/O. */\n | 'invalid-anchor'\n /** `destinationRoot` is relative; resolving it would consult the cwd. */\n | 'destination-not-absolute'\n | 'destination-missing'\n /** `filePath` resolves outside `destinationRoot`. */\n | 'path-escapes-destination'\n | 'control-file'\n /** A link on the way or at the leaf, a hard-linked or special file, or a swap during the open. */\n | 'unsafe-target'\n /** Replacing the file would change its owner, which this process cannot restore. */\n | 'unsupported-target'\n /** No file at the resolved path. */\n | 'file-missing'\n /** The path exists but could not be read (permissions, a directory, …). */\n | 'file-unreadable'\n /**\n * The file is not valid UTF-8. Rewriting it would round-trip its bytes\n * through a lossy decode and corrupt regions outside the anchor.\n */\n | 'file-not-utf8'\n /** The anchor falls outside the file's line count. */\n | 'anchor-out-of-range'\n /** The anchored lines no longer match `suggestion.originalCode`. */\n | 'context-mismatch'\n /** The file was replaced or rewritten between the read and the commit. */\n | 'file-changed'\n /** The context matched but the write itself failed. */\n | 'write-failed';\n\nexport interface ApplySuggestionRequest {\n /**\n * Absolute path of the directory the reviewed files live in. Always\n * supplied by the caller: a git-mode working tree, a directory-mode root,\n * a reused clone, or the destination the user picked for a temporary-clone\n * review. Never derived here.\n */\n destinationRoot: string;\n /** Path of the file to modify, relative to `destinationRoot`. */\n filePath: string;\n /** The comment's anchor. `null` (file-level) is refused. */\n lineRange: LineRange | null;\n suggestion: Suggestion;\n}\n\nexport interface ApplySuggestionOptions {\n fs?: FsLayer;\n randomName?: () => string;\n /** Input and resulting output limits, independently enforced. Both default to 5 MiB. */\n maxInputBytes?: number;\n maxOutputBytes?: number;\n /** Last synchronous authorization check before rename; throwing refuses the write. */\n beforeCommit?: () => void;\n}\n\nexport interface ApplySuggestionAsyncOptions extends Omit<ApplySuggestionOptions, 'fs'> {\n fs?: AsyncFsLayer;\n /** Check the resolved physical root after resolution and before staging, before any write. */\n validateDestination?: (physicalRoot: string) => void;\n /** Cancellation rejects with signal.reason before commit. A committed write stays applied. */\n signal?: AbortSignal;\n}\n\nexport interface ApplySuggestionApplied {\n status: 'applied';\n /** Echoed from the request, so a batch caller can attribute the result. */\n filePath: string;\n absolutePath: string;\n /** How many on-disk lines the proposal replaced. */\n replacedLines: number;\n}\n\nexport interface ApplySuggestionRefused {\n status: 'refused';\n filePath: string;\n reason: ApplyRefusalReason;\n /** One sentence naming the refusal, safe to show to the reviewer. */\n detail: string;\n}\n\nexport type ApplySuggestionResult = ApplySuggestionApplied | ApplySuggestionRefused;\n\n/**\n * A `.git` segment at any depth, directory or worktree file: git executes what is in there. `.gitmodules`\n * and the like are reviewed content, gated by diff membership in the session handler instead.\n */\nexport function isRepositoryControlPath(filePath: string): boolean {\n return filePath.split(/[\\\\/]+/).some(segment => segment.toLowerCase() === '.git');\n}\n\nfunction refuse(\n filePath: string,\n reason: ApplyRefusalReason,\n detail: string\n): ApplySuggestionRefused {\n return { status: 'refused', filePath, reason, detail };\n}\n\nconst FS_REFUSALS: Partial<Record<SafeFsErrorCode, [ApplyRefusalReason, string]>> = {\n 'not-found': ['file-missing', 'The file is not in the destination directory.'],\n 'unsafe-link': [\n 'unsafe-target',\n 'The path goes through a symbolic link, and this program does not write through links.',\n ],\n 'not-regular': ['unsafe-target', 'The path is not a regular file.'],\n 'output-is-directory': ['file-unreadable', 'The path is a directory, not a file.'],\n 'unsupported-target': [\n 'unsupported-target',\n 'The file is owned by another user, and replacing it would change its owner.',\n ],\n 'identity-changed': [\n 'file-changed',\n 'The file changed on disk after it was read, so nothing was written.',\n ],\n};\n\nfunction refuseFsError(\n filePath: string,\n error: unknown,\n fallback: 'file-unreadable' | 'write-failed'\n): ApplySuggestionRefused {\n const fsError = toSafeFsError(error, filePath, 'access');\n if (fsError.code === 'too-large') return refuse(filePath, fallback, fsError.message);\n const [reason, detail] = FS_REFUSALS[fsError.code] ?? [\n fallback,\n `The file could not be ${fallback === 'write-failed' ? 'written' : 'read'} (${errnoOf(fsError.cause) ?? 'unknown'}).`,\n ];\n return refuse(filePath, reason, detail);\n}\n\n/** Purely lexical, so an escape is refused before the filesystem is consulted. */\nfunction relativeWithinRoot(filePath: string): string | null {\n if (filePath === '' || path.posix.isAbsolute(filePath) || path.win32.isAbsolute(filePath)) {\n return null;\n }\n if (filePath.split('/').some(segment => segment === '..')) return null;\n const normalized = path.posix.normalize(filePath);\n if (normalized === '.' || normalized === '..' || normalized.startsWith('../')) return null;\n return normalized;\n}\n\ninterface OpenedTarget {\n identity: FileIdentity;\n buffer: Buffer;\n}\n\n/** Read through the descriptor that was checked, so the bytes compared are the recorded inode's. */\nfunction openAndRead(\n realRoot: string,\n rel: string,\n filePath: string,\n fs: FsLayer,\n maxInputBytes: number\n): OpenedTarget | ApplySuggestionRefused {\n let opened: ReturnType<typeof openContainedFile>;\n try {\n opened = openContainedFile(realRoot, rel, fs);\n } catch (error) {\n return refuseFsError(filePath, error, 'file-unreadable');\n }\n const { fd, stats } = opened;\n try {\n if (stats.nlink > 1) {\n return refuse(\n filePath,\n 'unsafe-target',\n `The file has ${stats.nlink} hard links, and replacing it would silently detach the others.`\n );\n }\n return {\n identity: snapshotIdentity(stats),\n buffer: readSuggestionSync(fd, path.join(realRoot, rel), stats.size, maxInputBytes, fs),\n };\n } catch (error) {\n return refuseFsError(filePath, error, 'file-unreadable');\n } finally {\n try {\n fs.closeSync(fd);\n } catch {\n // Read-only descriptor; nothing depends on the close.\n }\n }\n}\n\n/**\n * Apply one anchored suggestion to one file under `destinationRoot`.\n *\n * On a byte-for-byte match between the anchored lines and\n * `suggestion.originalCode`, the anchored lines are replaced with\n * `suggestion.proposedCode` and the file is rewritten. Lines outside the\n * anchor keep their exact bytes, including their line terminators, and the\n * file's trailing-newline state is preserved either way. Any other outcome\n * refuses with a reason and writes nothing.\n */\nfunction validateRequest(\n request: ApplySuggestionRequest\n): { rel: string; start: number; end: number } | ApplySuggestionRefused {\n const { destinationRoot, filePath, lineRange } = request;\n if (!lineRange) {\n return refuse(\n filePath,\n 'no-anchor',\n 'This suggestion is file-level, so there are no lines to replace.'\n );\n }\n if (lineRange.side === 'old') {\n return refuse(\n filePath,\n 'old-side-anchor',\n 'This suggestion is anchored to deleted lines, which are not in the working file.'\n );\n }\n if (lineRange.side !== 'new') {\n return refuse(filePath, 'invalid-anchor', 'The anchor does not name a side of the diff.');\n }\n const anchor = validateLineRange(lineRange);\n if (!anchor.ok) {\n return refuse(\n filePath,\n 'invalid-anchor',\n `The anchor is not a usable range: ${anchor.reason}.`\n );\n }\n const { start, end } = anchor.anchor;\n\n if (!path.isAbsolute(destinationRoot)) {\n return refuse(\n filePath,\n 'destination-not-absolute',\n 'The destination directory must be an absolute path.'\n );\n }\n const rel = relativeWithinRoot(filePath);\n if (rel === null) {\n return refuse(\n filePath,\n 'path-escapes-destination',\n 'The file path resolves outside the destination directory.'\n );\n }\n if (isRepositoryControlPath(rel)) {\n return refuse(\n filePath,\n 'control-file',\n 'The path is repository metadata (.git), which is never part of a review.'\n );\n }\n\n return { rel, start, end };\n}\n\n/** Invalid limit options throw RangeError, before any file is opened. */\nfunction limits(options: Pick<ApplySuggestionOptions, 'maxInputBytes' | 'maxOutputBytes'>) {\n const maxInputBytes = options.maxInputBytes ?? MAX_SOURCE_FILE_BYTES;\n const maxOutputBytes = options.maxOutputBytes ?? MAX_SOURCE_FILE_BYTES;\n for (const [name, value] of Object.entries({ maxInputBytes, maxOutputBytes })) {\n if (!Number.isSafeInteger(value) || value < 0 || value >= bufferConstants.MAX_LENGTH) {\n throw new RangeError(\n `${name} must be a nonnegative safe integer below ${bufferConstants.MAX_LENGTH}`\n );\n }\n }\n return { maxInputBytes, maxOutputBytes };\n}\n\n/**\n * Bounded synchronous Apply for existing callers. Only the anchor is decoded and proposal encoded;\n * untouched regions are copied as bytes. Invalid options throw RangeError; refusals are values.\n */\nexport function applySuggestion(\n request: ApplySuggestionRequest,\n options: ApplySuggestionOptions = {}\n): ApplySuggestionResult {\n const checked = validateRequest(request);\n if ('status' in checked) return checked;\n const { rel, start, end } = checked;\n const { destinationRoot, filePath, suggestion } = request;\n const fs = options.fs ?? nodeFsLayer;\n const { maxInputBytes, maxOutputBytes } = limits(options);\n\n let realRoot: string;\n try {\n realRoot = fs.realpathSync(path.resolve(destinationRoot));\n } catch (error) {\n return refuse(\n filePath,\n 'destination-missing',\n `The destination directory could not be resolved (${errnoOf(error) ?? 'unknown'}).`\n );\n }\n const absolutePath = path.join(realRoot, rel);\n\n const opened = openAndRead(realRoot, rel, filePath, fs, maxInputBytes);\n if ('status' in opened) return opened;\n const { identity, buffer } = opened;\n\n const prepared = prepareSuggestionContent(buffer, start, end, suggestion, maxOutputBytes);\n if ('reason' in prepared) return refuse(filePath, prepared.reason, prepared.detail);\n\n try {\n atomicReplace(absolutePath, prepared.bytes, {\n fs,\n preserveMode: true,\n preserveOwner: true,\n expectedIdentity: identity,\n expectUnmodified: true,\n randomName: options.randomName,\n beforeCommit: options.beforeCommit,\n });\n } catch (error) {\n return refuseFsError(filePath, error, 'write-failed');\n }\n\n return { status: 'applied', filePath, absolutePath, replacedLines: prepared.replacedLines };\n}\n\n/**\n * Promise-based Apply with the same byte budgets, validation and replacement policy as Apply.\n * Bulk reads and writes use native asynchronous I/O in chunks of at most 64 KiB. Operations are\n * independent; competing applies are checked against the inode/stamp they read, not serialized.\n * Cancellation rejects before commit and removes staging. After rename it returns applied even\n * if the signal aborts. The portable final check/rename race is documented in atomicReplaceAsync.\n */\nexport async function applySuggestionAsync(\n request: ApplySuggestionRequest,\n options: ApplySuggestionAsyncOptions = {}\n): Promise<ApplySuggestionResult> {\n options = { ...options };\n options.signal?.throwIfAborted();\n // Capture caller-owned data before the first await.\n request = {\n ...request,\n lineRange: request.lineRange && { ...request.lineRange },\n suggestion: { ...request.suggestion },\n };\n const checked = validateRequest(request);\n if ('status' in checked) return checked;\n const { rel, start, end } = checked;\n const { destinationRoot, filePath, suggestion } = request;\n const { maxInputBytes, maxOutputBytes } = limits(options);\n const layer = options.fs ?? nodeAsyncFsLayer;\n let realRoot: string;\n try {\n realRoot = await layer.realpath(path.resolve(destinationRoot));\n options.signal?.throwIfAborted();\n } catch (error) {\n options.signal?.throwIfAborted();\n return refuse(\n filePath,\n 'destination-missing',\n `The destination directory could not be resolved (${errnoOf(error) ?? 'unknown'}).`\n );\n }\n const absolutePath = path.join(realRoot, rel);\n try {\n options.validateDestination?.(realRoot);\n } catch (error) {\n options.signal?.throwIfAborted();\n return refuseFsError(filePath, error, 'write-failed');\n }\n let opened: Awaited<ReturnType<typeof openContainedFileAsync>>;\n try {\n opened = await openContainedFileAsync(realRoot, rel, layer, options.signal);\n } catch (error) {\n options.signal?.throwIfAborted();\n return refuseFsError(filePath, error, 'file-unreadable');\n }\n const { handle, stats } = opened;\n let buffer: Buffer;\n try {\n if (stats.nlink > 1)\n return refuse(\n filePath,\n 'unsafe-target',\n `The file has ${stats.nlink} hard links, and replacing it would silently detach the others.`\n );\n const chunks = boundedChunks(absolutePath, stats.size, maxInputBytes);\n let step = chunks.next();\n while (!step.done) {\n options.signal?.throwIfAborted();\n const { buffer, offset, length } = step.value;\n const { bytesRead } = await handle.read(buffer, offset, length, null);\n options.signal?.throwIfAborted();\n step = chunks.next(bytesRead);\n }\n buffer = step.value;\n } catch (error) {\n options.signal?.throwIfAborted();\n return refuseFsError(filePath, error, 'file-unreadable');\n } finally {\n try {\n await handle.close();\n } catch {\n /* Read-only descriptor; no commit depends on close. */\n }\n options.signal?.throwIfAborted();\n }\n options.signal?.throwIfAborted();\n const prepared = prepareSuggestionContent(buffer, start, end, suggestion, maxOutputBytes);\n if ('reason' in prepared) return refuse(filePath, prepared.reason, prepared.detail);\n try {\n options.validateDestination?.(realRoot);\n await atomicReplaceAsync(absolutePath, prepared.bytes, {\n fs: layer,\n preserveMode: true,\n preserveOwner: true,\n expectedIdentity: snapshotIdentity(stats),\n expectUnmodified: true,\n randomName: options.randomName,\n signal: options.signal,\n beforeCommit: options.beforeCommit,\n });\n } catch (error) {\n options.signal?.throwIfAborted();\n return refuseFsError(filePath, error, 'write-failed');\n }\n return { status: 'applied', filePath, absolutePath, replacedLines: prepared.replacedLines };\n}\n","// Byte-range suggestion edits. No whole-file decoding or per-line arrays.\nimport { isUtf8 } from 'node:buffer';\nimport type { Suggestion } from './types';\nimport type { ApplyRefusalReason } from './apply-suggestion';\nimport { isWellFormedUnicode } from './unicode-text';\n\nexport interface PreparedSuggestion {\n bytes: Buffer;\n replacedLines: number;\n}\n\nexport interface ContentRefusal {\n reason: ApplyRefusalReason;\n detail: string;\n}\n\n/** The LF belongs to the separator, while a CR belongs to the line being compared. */\nfunction locateAnchor(bytes: Buffer, start: number, end: number) {\n let lineCount = 0;\n let startOffset = -1;\n let endOffset = -1;\n let crlf = true;\n for (let offset = 0; offset < bytes.length; ) {\n lineCount++;\n const newline = bytes.indexOf(10, offset);\n const lineEnd = newline === -1 ? bytes.length : newline;\n if (lineCount === start) startOffset = offset;\n if (lineCount >= start && lineCount <= end) {\n if (lineEnd === offset || bytes[lineEnd - 1] !== 13) crlf = false;\n }\n if (lineCount === end) endOffset = lineEnd;\n offset = newline === -1 ? bytes.length : newline + 1;\n }\n return { lineCount, startOffset, endOffset, crlf };\n}\n\n/** One terminator ends the proposal; additional trailing LFs remain actual empty lines. */\nfunction proposalBody(proposed: string): string {\n if (proposed.endsWith('\\r\\n')) return proposed.slice(0, -2);\n return proposed.endsWith('\\n') ? proposed.slice(0, -1) : proposed;\n}\n\nexport function outputBudgetRefusal(maxBytes: number): ContentRefusal {\n return {\n reason: 'write-failed',\n detail: `The proposed file exceeds the ${maxBytes} byte Apply output limit, so nothing was written.`,\n };\n}\n\nexport function prepareSuggestionContent(\n bytes: Buffer,\n start: number,\n end: number,\n suggestion: Suggestion,\n maxOutputBytes: number\n): PreparedSuggestion | ContentRefusal {\n if (!isUtf8(bytes))\n return { reason: 'file-not-utf8', detail: 'The file is not valid UTF-8 text.' };\n const anchor = locateAnchor(bytes, start, end);\n if (end > anchor.lineCount) {\n return {\n reason: 'anchor-out-of-range',\n detail: `Lines ${start}-${end} are outside this file, which has ${anchor.lineCount} line(s).`,\n };\n }\n const original = bytes.subarray(anchor.startOffset, anchor.endOffset);\n // Check the length before encoding a possibly enormous caller-supplied original.\n if (\n suggestion.originalCode.length > original.length ||\n Buffer.byteLength(suggestion.originalCode) !== original.length ||\n original.toString('utf8') !== suggestion.originalCode\n ) {\n return {\n reason: 'context-mismatch',\n detail: `Lines ${start}-${end} no longer match the code this suggestion was written against.`,\n };\n }\n\n const hasReplacement = suggestion.proposedCode !== '';\n const body = proposalBody(suggestion.proposedCode);\n if (body.length > maxOutputBytes || Buffer.byteLength(body) > maxOutputBytes)\n return outputBudgetRefusal(maxOutputBytes);\n if (!isWellFormedUnicode(body))\n return {\n reason: 'write-failed',\n detail: 'The proposed code contains an unpaired Unicode surrogate, so nothing was written.',\n };\n const proposed = Buffer.from(body);\n let extraCrs = 0;\n if (hasReplacement && anchor.crlf) {\n for (let i = 0; i <= proposed.length; i++) {\n if ((i === proposed.length || proposed[i] === 10) && (i === 0 || proposed[i - 1] !== 13))\n extraCrs++;\n }\n }\n const hasPrefix = start > 1;\n const hasSuffix = end < anchor.lineCount;\n const hasOutput = hasPrefix || hasReplacement || hasSuffix;\n const trailingLf = bytes.length > 0 && bytes[bytes.length - 1] === 10;\n const logicalEnd = bytes.length - (trailingLf ? 1 : 0);\n // Keep the prefix's separator only when another line follows it.\n const prefixEnd = hasPrefix ? anchor.startOffset - (hasReplacement || hasSuffix ? 0 : 1) : 0;\n const suffixStart = hasSuffix ? anchor.endOffset + 1 : logicalEnd;\n const separator = hasReplacement && hasSuffix ? 1 : 0;\n const finalLf = hasOutput && trailingLf ? 1 : 0;\n const size =\n prefixEnd + proposed.length + extraCrs + separator + (logicalEnd - suffixStart) + finalLf;\n if (size > maxOutputBytes) return outputBudgetRefusal(maxOutputBytes);\n\n const output = Buffer.allocUnsafe(size);\n let offset = bytes.copy(output, 0, 0, prefixEnd);\n // Copy runs between LFs. This never materializes an array of lines, even for blank-line files.\n for (let from = 0; from < proposed.length; ) {\n const newline = proposed.indexOf(10, from);\n const to = newline === -1 ? proposed.length : newline;\n offset += proposed.copy(output, offset, from, to);\n if (anchor.crlf && hasReplacement && (to === from || proposed[to - 1] !== 13))\n output[offset++] = 13;\n if (newline !== -1) output[offset++] = 10;\n from = newline === -1 ? proposed.length : newline + 1;\n }\n // The final logical line can be empty, including a proposal of exactly one terminator.\n if (\n anchor.crlf &&\n hasReplacement &&\n (proposed.length === 0 || proposed[proposed.length - 1] === 10)\n )\n output[offset++] = 13;\n if (separator) output[offset++] = 10;\n offset += bytes.copy(output, offset, suffixStart, logicalEnd);\n if (finalLf) output[offset++] = 10;\n return { bytes: output, replacedLines: end - start + 1 };\n}\n","// Destination selection and authorization for suggestion writes. Filesystem effects live here.\nimport * as fs from 'fs';\nimport path from 'path';\nimport type {\n SuggestionApplyRequest,\n SuggestionApplyOutcome,\n ApplyDestinationOutcome,\n} from './types';\nimport type { ReviewSession } from './review-session';\nimport { resolveSourceBaseDir } from './review-session';\nimport { rootRelativeReviewedPath } from './source-identity';\nimport { applySuggestion, applySuggestionAsync } from './apply-suggestion';\nimport type {\n ApplySuggestionResult,\n ApplySuggestionAsyncOptions,\n ApplySuggestionRequest,\n} from './apply-suggestion';\nimport { SafeFsError, nodeFsLayer } from './safe-fs';\nimport type { FsLayer } from './safe-fs';\nimport type { DiagnosticReporter } from './diagnostics';\nimport { isolatedReporter } from './effect-diagnostics';\n\nexport type ApplySuggestionForSessionAsyncOptions = Omit<\n ApplySuggestionAsyncOptions,\n 'beforeCommit' | 'validateDestination'\n>;\n\ntype ApplySession = Pick<\n ReviewSession,\n 'diffData' | 'sourceIdentity' | 'applyDestinationRoot' | 'reviewedPaths'\n>;\n\n/** Read-only destination policy, independent of source writes. Methods retain their receiver. */\nexport interface ApplyDestinationInspection {\n realpath(target: string): string;\n isDirectory(target: string): boolean;\n}\n\nexport interface SuggestionOperationOptions {\n destinationInspection?: ApplyDestinationInspection;\n reportDiagnostic?: DiagnosticReporter;\n}\n\nexport interface ApplySuggestionForSessionOptions extends SuggestionOperationOptions {\n /** Authoritative filesystem for synchronous Apply; never supplemented with native I/O. */\n fs?: FsLayer;\n}\n\nexport const nodeApplyDestinationInspection: ApplyDestinationInspection = {\n realpath: target => fs.realpathSync(target),\n isDirectory: target => fs.statSync(target).isDirectory(),\n};\n\n/**\n * True when this session reviews a remote PR/MR that was materialized into\n * a temporary clone. That clone is removed when the app exits, so a write\n * into it is lost the moment the review ends (PRD Section 5.4.8).\n */\nexport function isTemporaryCloneSession(session: Pick<ReviewSession, 'diffData'>): boolean {\n return session.diffData?.remote?.temporaryClone === true;\n}\n\n/** Canonical form of a path, following symlinks when the path exists. */\nfunction canonicalize(target: string, inspection: ApplyDestinationInspection): string {\n try {\n return inspection.realpath(target);\n } catch {\n return path.resolve(target);\n }\n}\n\n/** True when `candidate` is `root` itself or sits anywhere beneath it. */\nfunction isWithin(\n root: string,\n candidate: string,\n inspection: ApplyDestinationInspection\n): boolean {\n const relative = path.relative(\n canonicalize(root, inspection),\n canonicalize(candidate, inspection)\n );\n const escapes = relative === '..' || relative.startsWith(`..${path.sep}`);\n return relative === '' || (!escapes && !path.isAbsolute(relative));\n}\n\n/**\n * The directory an apply may write into for this session, or null when the\n * session has none.\n *\n * For every review whose files sit in a place the user controls — a git\n * working tree, a scanned directory, a reused remote clone — that is the\n * root the reviewed paths are relative to, and no one is asked anything.\n *\n * A temporary-clone review is the one exception. Its files live in a\n * directory the app deletes on exit, so the clone is never a destination:\n * the answer is the directory the user named, and null until they name one.\n */\nexport function resolveApplyDestination(\n session: Pick<ReviewSession, 'diffData' | 'sourceIdentity' | 'applyDestinationRoot'>\n): string | null {\n if (isTemporaryCloneSession(session)) {\n return session.applyDestinationRoot;\n }\n return resolveSourceBaseDir(session);\n}\n\n/**\n * Record the directory the user named as this session's apply destination.\n *\n * The caller supplies a path the user picked; this decides whether it can\n * be written into and stores it only if so. The temporary clone, and\n * anything inside it, is refused however it was reached — that directory\n * is gone when the review ends, which is the whole reason a destination is\n * asked for.\n */\nexport function setApplyDestination(\n session: Pick<ReviewSession, 'diffData' | 'sourceIdentity' | 'applyDestinationRoot'>,\n directoryPath: string,\n options: SuggestionOperationOptions = {}\n): ApplyDestinationOutcome {\n const inspection = options.destinationInspection ?? nodeApplyDestinationInspection;\n if (!path.isAbsolute(directoryPath)) {\n return {\n status: 'rejected',\n reason: 'destination-not-absolute',\n detail: 'Pick a destination by its full path.',\n };\n }\n\n let isDirectory = false;\n try {\n isDirectory = inspection.isDirectory(directoryPath);\n } catch {\n isDirectory = false;\n }\n if (!isDirectory) {\n return {\n status: 'rejected',\n reason: 'destination-not-a-directory',\n detail: 'That destination is not a directory that exists.',\n };\n }\n\n const clonePath = isTemporaryCloneSession(session) ? resolveSourceBaseDir(session) : null;\n if (clonePath && isWithin(clonePath, directoryPath, inspection)) {\n return {\n status: 'rejected',\n reason: 'destination-inside-temporary-clone',\n detail:\n 'That directory is inside the temporary clone, which is deleted when the review ends.',\n };\n }\n\n session.applyDestinationRoot = canonicalize(directoryPath, inspection);\n isolatedReporter(options.reportDiagnostic)(`[suggestion:apply] destination set for this session`);\n return { status: 'chosen', destinationRoot: session.applyDestinationRoot };\n}\n\n/**\n * Apply one suggestion to the reviewed working file, or refuse and write\n * nothing. The engine does the work; this handler names the destination, which\n * the engine never derives, and authorizes the target.\n *\n * Authorization is membership in {@link ReviewSession.reviewedPaths}\n * (`not-reviewed` otherwise), so a resumed document or a client reaching this\n * handler cannot name an unreviewed file. The request is not bound to a\n * comment (the session keeps no registry of live suggestions); the binding is\n * the anchor plus the engine's byte-exact `originalCode` match.\n *\n * The engine gets the path through the identity's prefix, so a `--relative`\n * review of `sub/` writes `sub/<path>`, never the root's same-named file.\n *\n * A refusal travels as a value, never a thrown error.\n */\nfunction prepareSessionApply(\n session: ApplySession,\n request: SuggestionApplyRequest,\n reportDiagnostic: DiagnosticReporter\n): { engineRequest: ApplySuggestionRequest } | SuggestionApplyOutcome {\n const destinationRoot = resolveApplyDestination(session);\n const identity = session.sourceIdentity;\n if (!destinationRoot || identity === null) {\n const temporary = isTemporaryCloneSession(session);\n return {\n status: 'refused',\n filePath: request.filePath,\n reason: temporary ? 'destination-required' : 'no-destination',\n detail: temporary\n ? 'This pull request was cloned into a temporary directory that is deleted when the review ends. Choose a destination directory to apply into.'\n : 'This review has no working directory to write into.',\n };\n }\n\n if (!session.reviewedPaths.has(request.filePath)) {\n reportDiagnostic(`[suggestion:apply] ${request.filePath}: refused (not-reviewed)`);\n return {\n status: 'refused',\n filePath: request.filePath,\n reason: 'not-reviewed',\n detail: 'This file is not part of the reviewed diff, so nothing was written.',\n };\n }\n\n return {\n engineRequest: {\n destinationRoot,\n filePath: rootRelativeReviewedPath(identity, request.filePath),\n lineRange: request.lineRange,\n suggestion: request.suggestion,\n },\n };\n}\n\n/** Capture the mutable public authorization and recheck it at the writer's commit hook. */\nfunction sessionApplyChecks(\n session: ApplySession,\n request: SuggestionApplyRequest,\n engineRequest: ApplySuggestionRequest,\n inspection: ApplyDestinationInspection\n) {\n const identity = session.sourceIdentity;\n const paths = session.reviewedPaths;\n const identityStamp = JSON.stringify(identity);\n const fileSource = JSON.stringify(identity?.fileSources?.get(request.filePath));\n const chosen = session.applyDestinationRoot;\n const temporary = isTemporaryCloneSession(session);\n const validateDestination = (physicalRoot: string) => {\n const destinationRoot = engineRequest.destinationRoot;\n if (\n physicalRoot !== path.resolve(destinationRoot) ||\n canonicalize(destinationRoot, inspection) !== physicalRoot ||\n (temporary && identity && isWithin(identity.sourceRoot, physicalRoot, inspection))\n ) {\n throw new SafeFsError(\n 'identity-changed',\n request.filePath,\n 'The Apply destination no longer belongs to this review.'\n );\n }\n };\n return {\n validateDestination,\n beforeCommit() {\n validateDestination(engineRequest.destinationRoot);\n if (\n session.sourceIdentity !== identity ||\n session.reviewedPaths !== paths ||\n !session.reviewedPaths.has(request.filePath) ||\n JSON.stringify(session.sourceIdentity) !== identityStamp ||\n JSON.stringify(session.sourceIdentity?.fileSources?.get(request.filePath)) !== fileSource ||\n session.applyDestinationRoot !== chosen ||\n isTemporaryCloneSession(session) !== temporary ||\n resolveApplyDestination(session) !== engineRequest.destinationRoot\n ) {\n throw new SafeFsError(\n 'identity-changed',\n request.filePath,\n 'The review or its Apply destination changed before the write could commit.'\n );\n }\n },\n };\n}\n\n/** Apply synchronously using the session's destination and reviewed-path authorization. */\nexport function applySuggestionForSession(\n session: ApplySession,\n request: SuggestionApplyRequest,\n effects: ApplySuggestionForSessionOptions = {}\n): SuggestionApplyOutcome {\n request = {\n ...request,\n lineRange: request.lineRange && { ...request.lineRange },\n suggestion: { ...request.suggestion },\n };\n const reportDiagnostic = isolatedReporter(effects.reportDiagnostic);\n const prepared = prepareSessionApply(session, request, reportDiagnostic);\n if ('status' in prepared) return prepared;\n const layer = effects.fs ?? nodeFsLayer;\n const inspection = effects.destinationInspection ?? {\n realpath: (target: string) => layer.realpathSync(target),\n isDirectory: (target: string) => layer.lstatSync(target).isDirectory(),\n };\n const checks = sessionApplyChecks(session, request, prepared.engineRequest, inspection);\n let destinationChanged = false;\n // The old engine accepts FsLayer and a final hook. Validate its physical root through that\n // same layer, preserving receiver binding for every legacy method and avoiding native fallback.\n // A separate proxy target accepts frozen providers without changing their method descriptors.\n const guardedFs = new Proxy({} as FsLayer, {\n get(_target, member) {\n const target = layer;\n if (member === 'realpathSync')\n return (value: string) => {\n const physical = target.realpathSync(value);\n if (value === path.resolve(prepared.engineRequest.destinationRoot)) {\n try {\n checks.validateDestination(physical);\n } catch (error) {\n destinationChanged = true;\n throw error;\n }\n }\n return physical;\n };\n const value = Reflect.get(target, member, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n let result = applySuggestion(prepared.engineRequest, {\n fs: guardedFs,\n beforeCommit: checks.beforeCommit,\n });\n if (destinationChanged && result.status === 'refused') {\n result = {\n status: 'refused',\n filePath: request.filePath,\n reason: 'file-changed',\n detail: 'The Apply destination no longer belongs to this review.',\n };\n }\n return projectApplyResult(request.filePath, result, reportDiagnostic);\n}\n\n/**\n * Bounded asynchronous Apply. Capture authorization before awaiting filesystem I/O and recheck\n * it synchronously just before rename. Replacing the loaded review, changing its identity or\n * selected destination, or removing membership refuses with file-changed and removes staging.\n * Cancellation rejects with signal.reason before commit, and a committed result stays applied.\n */\nexport async function applySuggestionForSessionAsync(\n session: ApplySession,\n request: SuggestionApplyRequest,\n options: ApplySuggestionForSessionAsyncOptions = {},\n effects: SuggestionOperationOptions = {}\n): Promise<SuggestionApplyOutcome> {\n options.signal?.throwIfAborted();\n request = {\n ...request,\n lineRange: request.lineRange && { ...request.lineRange },\n suggestion: { ...request.suggestion },\n };\n const reportDiagnostic = isolatedReporter(effects.reportDiagnostic);\n const inspection = effects.destinationInspection ?? nodeApplyDestinationInspection;\n const prepared = prepareSessionApply(session, request, reportDiagnostic);\n options.signal?.throwIfAborted();\n if ('status' in prepared) return prepared;\n const checks = sessionApplyChecks(session, request, prepared.engineRequest, inspection);\n const result = await applySuggestionAsync(prepared.engineRequest, { ...options, ...checks });\n const outcome = projectApplyResult(request.filePath, result, reportDiagnostic);\n // Reporting can trigger host cancellation. A refusal has not committed anything; an applied\n // result must remain successful even when cancellation arrives during its diagnostic.\n if (result.status !== 'applied') options.signal?.throwIfAborted();\n return outcome;\n}\n\nfunction projectApplyResult(\n filePath: string,\n result: ApplySuggestionResult,\n reportDiagnostic: DiagnosticReporter\n): SuggestionApplyOutcome {\n reportDiagnostic(\n `[suggestion:apply] ${filePath}: ${\n result.status === 'applied' ? 'applied' : `refused (${result.reason})`\n }`\n );\n\n // Projected field by field rather than passed through. The engine also\n // reports the resolved absolute path, which the front end has no use for\n // and should not be handed; naming the fields here keeps the wire shape\n // exactly what SuggestionApplyOutcome declares, today and after the engine\n // grows a field. The path is the request's, not the engine's root-relative one.\n if (result.status === 'applied') {\n return {\n status: 'applied',\n filePath,\n replacedLines: result.replacedLines,\n };\n }\n return {\n status: 'refused',\n filePath,\n reason: result.reason,\n detail: result.detail,\n };\n}\n"]}