@self-review/core 2.0.3 → 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,959 @@
1
+ import { RemoteForge, DiffFile, ReviewSourceIdentity, ReviewState, ReviewComment, DiffLoadPayload, GuideLoadPayload, AppConfig, OutputPathInfo, RemoteDriftInfo, DiffHunk, ResumeLoadPayload, LineRange, Suggestion, SuggestionApplyRequest, SuggestionApplyOutcome, ApplyDestinationOutcome } from '@self-review/types';
2
+ import * as nodeFs from 'node:fs';
3
+ import { Stats } from 'node:fs';
4
+ import { FileHandle } from 'node:fs/promises';
5
+
6
+ type SafeFsErrorCode = 'output-is-directory'
7
+ /** EACCES, EPERM or EROFS. */
8
+ | 'permission-denied'
9
+ /** ENOSPC or EDQUOT. */
10
+ | 'no-space'
11
+ /** A symlink sits where this module would read, create or replace a file, or on the way to it. */
12
+ | 'unsafe-link'
13
+ /** Exists, but replacing it would change semantics: hard-linked, not a regular file, or foreign-owned. */
14
+ | 'unsupported-target'
15
+ /** The file at the target is not the one the caller checked. */
16
+ | 'identity-changed'
17
+ /** ENOENT or ENOTDIR. */
18
+ | 'not-found'
19
+ /** A FIFO, socket or device. */
20
+ | 'not-regular' | 'too-large' | 'io-error';
21
+ declare class SafeFsError extends Error {
22
+ readonly code: SafeFsErrorCode;
23
+ readonly path: string;
24
+ readonly cause?: unknown;
25
+ constructor(code: SafeFsErrorCode, path: string, message: string, cause?: unknown);
26
+ }
27
+ interface FileIdentity {
28
+ dev: number;
29
+ ino: number;
30
+ /** Permission bits only (`mode & 0o7777`). */
31
+ mode: number;
32
+ nlink: number;
33
+ size: number;
34
+ mtimeMs: number;
35
+ uid: number;
36
+ gid: number;
37
+ }
38
+ declare function snapshotIdentity(stats: nodeFs.Stats): FileIdentity;
39
+ declare function sameFile(a: FileIdentity, b: FileIdentity): boolean;
40
+ /** The code a caller maps to its own reason; anything unknown is `io-error`. */
41
+ declare function classifyFsError(error: unknown): SafeFsErrorCode;
42
+
43
+ /** Methods retain their receiver. read copies at most length bytes into the caller's buffer. */
44
+ interface AsyncReadHandle {
45
+ stat(): Promise<Stats>;
46
+ read(buffer: Buffer, offset: number, length: number, position: number | null): Promise<{
47
+ bytesRead: number;
48
+ }>;
49
+ close(): Promise<void>;
50
+ }
51
+ interface AsyncReadFsLayer<H extends AsyncReadHandle = AsyncReadHandle> {
52
+ open(target: string, flags: number, mode?: number): Promise<H>;
53
+ lstat(target: string): Promise<Stats>;
54
+ realpath(target: string): Promise<string>;
55
+ }
56
+ /**
57
+ * Explicit promise that read copies the requested chunk without allocating the whole file.
58
+ * This is an adapter contract, not a way to interrupt an arbitrary implementation or syscall.
59
+ */
60
+ interface BoundedAsyncReadFsLayer<H extends AsyncReadHandle = AsyncReadHandle> extends AsyncReadFsLayer<H> {
61
+ readonly readAllocation: 'bounded';
62
+ }
63
+ declare const nodeReadFsLayer: BoundedAsyncReadFsLayer<FileHandle>;
64
+ /** Unlike FsLayer's legacy path, a bounded synchronous reader must implement descriptor reads. */
65
+ type SyncReadFsLayer = Pick<FsLayer, 'openSync' | 'fstatSync' | 'lstatSync' | 'realpathSync' | 'closeSync'> & Required<Pick<FsLayer, 'readSync'>>;
66
+ /**
67
+ * Bounded allocation over the supplied filesystem, including virtual descriptors. Each read yields
68
+ * before its synchronous call. The call itself cannot be preempted; no native-fs fallback is used.
69
+ */
70
+ declare function boundedReadFsFromSync(layer: SyncReadFsLayer, signal?: AbortSignal): BoundedAsyncReadFsLayer;
71
+
72
+ /** Only the handle operations these readers and writers use. Methods retain their receiver. */
73
+ interface AsyncFileHandle extends AsyncReadHandle {
74
+ write(buffer: Uint8Array): Promise<{
75
+ bytesWritten: number;
76
+ }>;
77
+ sync(): Promise<void>;
78
+ chmod(mode: number): Promise<void>;
79
+ chown(uid: number, gid: number): Promise<void>;
80
+ }
81
+ interface AsyncFsLayer extends AsyncReadFsLayer<AsyncFileHandle> {
82
+ /** Resolve on commit; reject only if the rename did not commit. */
83
+ rename(from: string, to: string): Promise<void>;
84
+ unlink(target: string): Promise<void>;
85
+ }
86
+ declare const nodeAsyncFsLayer: AsyncFsLayer;
87
+
88
+ /**
89
+ * Reads under the shared no-follow policy in at most 64 KiB chunks, including growth detection.
90
+ * A supplied adapter owns its read implementation; legacy compatibility may allocate a whole file.
91
+ * Use readContainedFileBounded when the adapter must explicitly promise bounded allocation.
92
+ */
93
+ declare function readContainedFileAsync(root: string, rel: string, maxBytes: number, layer?: AsyncReadFsLayer, signal?: AbortSignal): Promise<Buffer>;
94
+ /**
95
+ * Explicit bounded-read capability. Adapter reads must copy only the requested chunk, without
96
+ * whole-file allocation. Cancellation is checked between calls; in-flight I/O is not preempted.
97
+ */
98
+ declare function readContainedFileBounded(root: string, rel: string, maxBytes: number, layer?: BoundedAsyncReadFsLayer, signal?: AbortSignal): Promise<Buffer>;
99
+ interface AtomicReplaceAsyncOptions extends Omit<AtomicReplaceOptions, 'fs'> {
100
+ fs?: AsyncFsLayer;
101
+ /** Reject with signal.reason before commit. An abort during a successful rename cannot undo it. */
102
+ signal?: AbortSignal;
103
+ }
104
+ /** No-follow open, followed by descriptor/name/physical-containment checks. Caller owns close. */
105
+ declare function openContainedFileAsync<H extends AsyncReadHandle>(root: string, rel: string, layer: AsyncReadFsLayer<H>, signal?: AbortSignal): Promise<{
106
+ handle: H;
107
+ stats: Stats;
108
+ }>;
109
+ declare function openContainedFileAsync(root: string, rel: string, layer?: Pick<AsyncFsLayer, 'open' | 'lstat' | 'realpath'>, signal?: AbortSignal): Promise<{
110
+ handle: AsyncFileHandle;
111
+ stats: Stats;
112
+ }>;
113
+ /** Create, sync and close one unique no-follow asset, removing it on any pre-commit failure. */
114
+ declare function writeExclusiveNoFollowAsync(target: string, bytes: Uint8Array, options?: Pick<AtomicReplaceAsyncOptions, 'fs' | 'signal'>): Promise<FileIdentity>;
115
+ /**
116
+ * Atomic replacement with bounded write chunks and cancellation before rename. The last target
117
+ * check follows staging/fsync. As in atomicReplace, a portable path-check/rename race remains;
118
+ * size/mtime are modification stamps, not a content hash or compare-and-swap guarantee.
119
+ * Once rename succeeds, cleanup and directory sync cannot convert success into refusal.
120
+ */
121
+ declare function atomicReplaceAsync(target: string, bytes: Uint8Array, options?: AtomicReplaceAsyncOptions): Promise<AtomicReplaceResult>;
122
+
123
+ /** The subset of `fs` used here, synchronous so a test can inject a failure at an exact step. */
124
+ interface FsLayer {
125
+ /** Optional asynchronous capabilities over this same filesystem. Never inferred for wrappers. */
126
+ asyncFs?: AsyncFsLayer;
127
+ /** Advisory writability probe. Legacy adapters use their own directory stats and permission bits. */
128
+ accessSync?(path: string, mode: number): void;
129
+ /** Bounded descriptor reads. Legacy adapters retain their readFileSync compatibility path. */
130
+ readSync?(fd: number, buffer: Uint8Array, offset: number, length: number, position: number | null): number;
131
+ openSync(path: string, flags: number, mode?: number): number;
132
+ /** May write fewer bytes than given, as the real one may. */
133
+ writeSync(fd: number, buffer: Uint8Array): number;
134
+ fsyncSync(fd: number): void;
135
+ fchmodSync(fd: number, mode: number): void;
136
+ fchownSync(fd: number, uid: number, gid: number): void;
137
+ closeSync(fd: number): void;
138
+ renameSync(from: string, to: string): void;
139
+ unlinkSync(path: string): void;
140
+ lstatSync(path: string): nodeFs.Stats;
141
+ fstatSync(fd: number): nodeFs.Stats;
142
+ readFileSync(fd: number): Buffer;
143
+ mkdirSync(path: string, mode: number): void;
144
+ realpathSync(path: string): string;
145
+ }
146
+ declare const nodeFsLayer: FsLayer;
147
+ /**
148
+ * Refuse a `rel` whose directories under `root` include a symlink. The leaf is the caller's
149
+ * policy, and a missing component ends the walk: nothing can be linked where nothing is.
150
+ */
151
+ declare function assertNoSymlinkAncestors(root: string, rel: string, fs?: Pick<FsLayer, 'lstatSync'>): void;
152
+ /**
153
+ * No link on the way or at the leaf, no FIFO blocking, regular files only. The walk and the open are
154
+ * separate syscalls, so afterwards the name must still resolve under `root` to the opened inode.
155
+ */
156
+ declare function openContainedFile(root: string, rel: string, fs?: Pick<FsLayer, 'lstatSync' | 'openSync' | 'fstatSync' | 'realpathSync' | 'closeSync'>): {
157
+ fd: number;
158
+ stats: nodeFs.Stats;
159
+ };
160
+ /** Read the whole of a file {@link openContainedFile} accepts, if it fits `maxBytes`. */
161
+ declare function readContainedFile(root: string, rel: string, maxBytes: number, options?: {
162
+ fs?: FsLayer;
163
+ readFs?: BoundedAsyncReadFsLayer;
164
+ signal?: AbortSignal;
165
+ }): Promise<Buffer>;
166
+ type ExclusiveFs = Pick<FsLayer, 'openSync' | 'writeSync' | 'fsyncSync' | 'fchmodSync' | 'fchownSync' | 'closeSync' | 'unlinkSync' | 'fstatSync' | 'lstatSync'>;
167
+ interface WriteExclusiveOptions {
168
+ /** Masked by the umask. Default 0o666. */
169
+ mode?: number;
170
+ /** Applied after creation, bypassing the umask. */
171
+ exactMode?: number;
172
+ /** Applied after creation; failing to is `unsupported-target` and removes the file. */
173
+ exactOwner?: {
174
+ uid: number;
175
+ gid: number;
176
+ };
177
+ fs?: ExclusiveFs;
178
+ }
179
+ /**
180
+ * Create `filePath`, which must not exist, write every byte and sync. A symlink at the path,
181
+ * dangling or not, is `unsafe-link`. Any failure after creation removes the file again.
182
+ */
183
+ declare function writeExclusiveNoFollow(filePath: string, bytes: Uint8Array, options?: WriteExclusiveOptions): FileIdentity;
184
+ interface AtomicReplaceOptions {
185
+ /** Give the replacement the replaced file's permission bits. */
186
+ preserveMode?: boolean;
187
+ /**
188
+ * Give the replacement the replaced file's owner (`rename` swaps the inode). An owner this
189
+ * process may not restore with `fchown` is refused as `unsupported-target` before any write.
190
+ */
191
+ preserveOwner?: boolean;
192
+ /** Refused as `identity-changed` when the target is no longer this file (dev/ino). */
193
+ expectedIdentity?: FileIdentity;
194
+ /** With `expectedIdentity`: also refuse a same-inode rewrite (size or mtime moved). */
195
+ expectUnmodified?: boolean;
196
+ fs?: ExclusiveFs & Pick<FsLayer, 'renameSync' | 'realpathSync'>;
197
+ randomName?: () => string;
198
+ /** Synchronous authorization check immediately before rename. A throw removes staging. */
199
+ beforeCommit?: () => void;
200
+ }
201
+ interface AtomicReplaceResult {
202
+ identity: FileIdentity;
203
+ /** Whether a file existed at `target` before. */
204
+ replaced: boolean;
205
+ }
206
+ /**
207
+ * Replace or create `target` in one rename from a same-directory temp file. The final target
208
+ * check follows staging, including fsync, and checks dev/ino plus size/mtime when requested.
209
+ * A same-size rewrite within timestamp granularity can pass. This is not compare-and-swap:
210
+ * another process can still change the path between the last check and rename. Rename replaces
211
+ * the named entry rather than following a leaf link; callers must secure ancestor directories.
212
+ */
213
+ declare function atomicReplace(target: string, bytes: Uint8Array, options?: AtomicReplaceOptions): AtomicReplaceResult;
214
+ /** `lstat` a replace target under the policy of {@link atomicReplace}; null when absent. */
215
+ declare function inspectReplaceTarget(target: string, fs?: Pick<FsLayer, 'lstatSync'>): FileIdentity | null;
216
+
217
+ /** Synthetic sources can inspect link text without following its destination. */
218
+ interface SourceReadFsLayer extends BoundedAsyncReadFsLayer {
219
+ readlink(target: string): Promise<Buffer>;
220
+ }
221
+ interface ScanEntry {
222
+ readonly name: string;
223
+ isDirectory(): boolean;
224
+ isFile(): boolean;
225
+ }
226
+ /** Caller owns close even when iteration fails or stops early. */
227
+ interface ScanDirectoryHandle extends AsyncIterable<ScanEntry> {
228
+ close(): Promise<void>;
229
+ }
230
+ /** All paths, identities, directory entries and bytes belong to the same filesystem. */
231
+ interface ScanFsLayer extends SourceReadFsLayer {
232
+ stat(target: string): Promise<Stats>;
233
+ opendir(target: string): Promise<ScanDirectoryHandle>;
234
+ }
235
+
236
+ /** Read-only synchronous policy probes, also used by the advisory inspectOutputPath API. */
237
+ type PublicationInspection = Pick<FsLayer, 'lstatSync' | 'realpathSync' | 'accessSync'>;
238
+ /**
239
+ * Explicit publication effects for native wrappers and virtual filesystems. All roles must refer
240
+ * to the same filesystem. Handle reads copy at most the requested length; writes may be partial.
241
+ * Inspection stays synchronous for inspectOutputPath; file I/O and directory creation are awaited.
242
+ * No absent method is filled from the host filesystem. Methods retain their receiver.
243
+ */
244
+ interface PublicationFileSystem {
245
+ inspection: PublicationInspection;
246
+ files: AsyncFsLayer;
247
+ mkdir(target: string, mode: number): Promise<void>;
248
+ currentUid(): number | undefined;
249
+ }
250
+ declare const nodePublicationFileSystem: PublicationFileSystem;
251
+
252
+ /** Per-call diagnostic output. A second string preserves the submitted-state summary's call form. */
253
+ type DiagnosticReporter = (message: string, detail?: string) => void;
254
+
255
+ /** Owns only the directory it creates. Removal is mandatory even after cancellation. */
256
+ interface TemporaryCloneStorage {
257
+ create(): Promise<string>;
258
+ remove(directory: string): Promise<void>;
259
+ removeSync(directory: string): void;
260
+ }
261
+ declare const nodeTemporaryCloneStorage: TemporaryCloneStorage;
262
+
263
+ /** Forges the app knows how to talk to. */
264
+ type ForgeName = RemoteForge;
265
+ /**
266
+ * A parsed pull-request / merge-request web URL.
267
+ *
268
+ * Detection is by URL path shape only (`/pull/N` → GitHub,
269
+ * `/-/merge_requests/N` → GitLab) on any host, so self-hosted instances such
270
+ * as git.drupalcode.org work with zero configuration.
271
+ */
272
+ interface ForgeUrl {
273
+ forge: ForgeName;
274
+ /** Host as it appears in the URL, including a port when present. */
275
+ host: string;
276
+ /**
277
+ * Repository owner. For GitLab this is the full namespace path and may
278
+ * contain slashes (subgroups, e.g. `group/subgroup`); for GitHub it is a
279
+ * single segment.
280
+ */
281
+ owner: string;
282
+ /** Repository name (final path segment before the PR/MR marker). */
283
+ repo: string;
284
+ /** Pull-request number / merge-request IID. */
285
+ number: number;
286
+ }
287
+ /** Which side of the diff a thread anchor points at. */
288
+ type ForgeAnchorSide = 'old' | 'new';
289
+ /**
290
+ * Forge-neutral anchor of a discussion thread onto the diff.
291
+ *
292
+ * The mapper consumes this shape without forge-conditional logic:
293
+ * - `startLine`/`endLine` are equal for single-line anchors.
294
+ * - `startLine`/`endLine` are `null` when the forge supplies a file path but
295
+ * no usable line information (the mapper degrades to a file-level comment;
296
+ * `side` is meaningless in that case and providers should set `'new'`).
297
+ *
298
+ * Revision provenance (the mapper compares it with the reviewed head; providers
299
+ * report only what the forge told them):
300
+ * - `headSha`: head commit the line numbers were computed against, when the
301
+ * forge reports one per note (GitLab), or a provider verifies the head around
302
+ * thread retrieval (GitHub). A suggestion activates only on a match.
303
+ * - `outdated`: the forge's own per-note verdict (GitHub `line: null`). `true`
304
+ * degrades to file-level; `false` vouches for the anchor when no `headSha` exists.
305
+ *
306
+ * An anchor carrying neither is unverifiable: it never activates a suggestion.
307
+ */
308
+ interface ForgeThreadAnchor {
309
+ filePath: string;
310
+ side: ForgeAnchorSide;
311
+ startLine: number | null;
312
+ endLine: number | null;
313
+ headSha?: string;
314
+ outdated?: boolean;
315
+ }
316
+ /** One turn (root comment or reply) in a forge discussion thread. */
317
+ interface ForgeThreadTurn {
318
+ /** Forge-assigned comment/note ID, kept as a string verbatim. */
319
+ remoteId: string;
320
+ /** Forge username of the turn's author. */
321
+ author: string;
322
+ /** Markdown body, passed through verbatim. */
323
+ body: string;
324
+ }
325
+ /**
326
+ * A normalized discussion thread: an ordered root + flat replies.
327
+ *
328
+ * The root turn owns the anchor. `anchor` is `null` for threads with no file
329
+ * association at all (e.g. GitLab non-diff discussions); the mapper turns
330
+ * those into its review-level representation. `replies` preserve the forge's
331
+ * document order — nothing else sorts them.
332
+ */
333
+ interface ForgeThread {
334
+ root: ForgeThreadTurn;
335
+ replies: ForgeThreadTurn[];
336
+ anchor: ForgeThreadAnchor | null;
337
+ }
338
+ /** Options for {@link ForgeProvider.fetchThreads}. */
339
+ interface FetchThreadsOptions {
340
+ /**
341
+ * Include threads the forge marks resolved. Defaults to false where the
342
+ * forge tracks resolution (GitLab); providers without a comparable concept
343
+ * on the fetch path (GitHub REST review comments) may ignore it.
344
+ */
345
+ includeResolved?: boolean;
346
+ /** Pinned materialized head. Providers may verify current anchors against this snapshot. */
347
+ reviewedHeadSha?: string;
348
+ }
349
+ /**
350
+ * Result of running a forge CLI command through {@link ForgeCommandRunner}.
351
+ */
352
+ interface ForgeCommandResult {
353
+ stdout: string;
354
+ stderr: string;
355
+ exitCode: number;
356
+ }
357
+ /**
358
+ * Optional lifetime bounds; either one kills the child and rejects with {@link
359
+ * CommandCancelledError}.
360
+ */
361
+ interface ForgeCommandOptions {
362
+ signal?: AbortSignal;
363
+ timeoutMs?: number;
364
+ /** Working directory, without invoking a shell. */
365
+ cwd?: string;
366
+ /** Combined captured stdout/stderr byte limit, before decoding. */
367
+ maxOutputBytes?: number;
368
+ /** Remote-owned Git operations ignore ambient repository, index, object and namespace selection.
369
+ * Local explicit targets keep their intentionally selected alternate index by default. */
370
+ gitEnvironment?: 'isolated';
371
+ }
372
+ /**
373
+ * Injectable command runner for providers and the materializer. Resolves with
374
+ * the exit code on any completed run; rejects when the binary cannot be spawned
375
+ * and, with a {@link CommandCancelledError}, when cut short by `options`.
376
+ */
377
+ type ForgeCommandRunner = (command: string, args: string[], options?: ForgeCommandOptions) => Promise<ForgeCommandResult>;
378
+ /** Why a command run was cut short. */
379
+ type CommandCancelReason = 'aborted' | 'timeout';
380
+ /**
381
+ * A run ended by its caller's bounds (abort or timeout) after the child was
382
+ * killed. Providers must not fold it into {@link ForgeCliUnavailableError}: a
383
+ * session being torn down must not degrade into a review without threads.
384
+ */
385
+ declare class CommandCancelledError extends Error {
386
+ readonly reason: CommandCancelReason;
387
+ readonly command: string;
388
+ readonly args: readonly string[];
389
+ constructor(reason: CommandCancelReason, command: string, args: readonly string[]);
390
+ }
391
+ /** Matches by name too, so it works across module instances. */
392
+ declare function isCommandCancelled(error: unknown): error is CommandCancelledError;
393
+ /**
394
+ * The conversation plane of a forge. Exactly two capabilities: base-branch
395
+ * lookup and discussion-thread fetching. No diff fetching, no blob fetching,
396
+ * no posting — those concerns live elsewhere.
397
+ *
398
+ * Implementations throw {@link ForgeCliUnavailableError} when their CLI is
399
+ * absent, unauthenticated or returns malformed required response data so callers can degrade
400
+ * visibly. A successful fetch returns all validated pages, never a silently shortened list.
401
+ * Unknown extension fields are ignored. Null/deleted authors use each forge's fallback name.
402
+ * Runners must propagate CommandCancelledError on interruption, including across pagination.
403
+ * Each provider instance is safe for concurrent calls when its supplied runner is also safe.
404
+ */
405
+ interface ForgeProvider {
406
+ readonly forge: ForgeName;
407
+ /** Resolve the PR/MR base (target) branch name. */
408
+ fetchBaseBranch(url: ForgeUrl): Promise<string>;
409
+ /** Fetch the PR/MR discussion threads in normalized form. */
410
+ fetchThreads(url: ForgeUrl, options?: FetchThreadsOptions): Promise<ForgeThread[]>;
411
+ }
412
+ /**
413
+ * Thrown by providers when their CLI is missing (spawn ENOENT) or exits
414
+ * non-zero due to authentication/API failure. Callers catch this to degrade
415
+ * (print to stderr, continue without threads) instead of crashing.
416
+ */
417
+ declare class ForgeCliUnavailableError extends Error {
418
+ readonly forge: ForgeName;
419
+ readonly cli: string;
420
+ constructor(forge: ForgeName, cli: string, message: string);
421
+ }
422
+ /**
423
+ * Parse a forge web URL into a {@link ForgeUrl}, or return `null` for
424
+ * anything that is not a PR/MR URL. Detection is by path shape only, on any
425
+ * http(s) host. Query strings and fragments are ignored.
426
+ */
427
+ declare function parseForgeUrl(url: string): ForgeUrl | null;
428
+
429
+ /**
430
+ * Entries one directory walk (or untracked-file listing) may examine; ignored directories are
431
+ * pruned first.
432
+ */
433
+ declare const MAX_SOURCE_ENTRIES = 50000;
434
+ /** Prefix sampled for a NUL byte to decide a file is binary. */
435
+ declare const BINARY_SNIFF_BYTES: number;
436
+ /**
437
+ * Largest text file read into a synthetic diff; a larger one is listed without content and named in
438
+ * a diagnostic.
439
+ */
440
+ declare const MAX_SOURCE_FILE_BYTES: number;
441
+ /** Total bytes one synthetic-diff build may read, binary sniffs included. */
442
+ declare const MAX_SOURCE_TOTAL_BYTES: number;
443
+ /** Most bytes of `git diff` output captured from one invocation (the child process `maxBuffer`). */
444
+ declare const MAX_GIT_DIFF_OUTPUT_BYTES: number;
445
+ /** Largest guide sidecar the loader will read. */
446
+ declare const MAX_GUIDE_BYTES: number;
447
+ /**
448
+ * Largest review document `--resume-from` will read (text and attachment references, never bytes).
449
+ */
450
+ declare const MAX_RESUME_XML_BYTES: number;
451
+ /** Most attachment occurrences in a review document, including replies and repeated references. */
452
+ declare const MAX_REVIEW_ATTACHMENTS = 1000;
453
+ /** Backwards-compatible name for the same reader/writer document contract. */
454
+ declare const MAX_RESUME_ATTACHMENTS = 1000;
455
+ /** Total newly staged asset bytes per publication. Existing references require no copy or read. */
456
+ declare const MAX_PUBLICATION_ASSET_BYTES: number;
457
+ /** Largest image read for a rendered preview or a comment attachment. */
458
+ declare const MAX_IMAGE_BYTES: number;
459
+ /**
460
+ * The source-loading budgets as one value; overrides are for tests and embedders, never user
461
+ * config.
462
+ */
463
+ interface SourceBudgets {
464
+ maxEntries: number;
465
+ maxFileBytes: number;
466
+ maxTotalBytes: number;
467
+ maxGitDiffOutputBytes: number;
468
+ /** Representation limits are independent of bytes and transport/lazy thresholds. */
469
+ maxFileLines?: number;
470
+ maxTotalLines?: number;
471
+ maxDiffFiles?: number;
472
+ maxDiffHunks?: number;
473
+ maxDiagnostics?: number;
474
+ }
475
+ /** Bounds retained objects even for empty lines, empty hunks and metadata-only files. */
476
+ declare const MAX_SOURCE_FILE_LINES = 100000;
477
+ declare const MAX_SOURCE_TOTAL_LINES = 250000;
478
+ declare const MAX_DIFF_FILES = 10000;
479
+ declare const MAX_DIFF_HUNKS = 50000;
480
+ declare const MAX_DIFF_DIAGNOSTICS = 1000;
481
+ /** Avoid repeating an enormous malicious header in each diagnostic. */
482
+ declare const MAX_DIFF_DIAGNOSTIC_CHARS: number;
483
+ type ResolvedSourceBudgets = Required<SourceBudgets>;
484
+ declare const DEFAULT_SOURCE_BUDGETS: Readonly<ResolvedSourceBudgets>;
485
+ declare function resolveSourceBudgets(overrides?: Partial<SourceBudgets>): ResolvedSourceBudgets;
486
+ /** `5 MiB`, `7.3 MiB`, `812 KiB`, `100 bytes`. */
487
+ declare function formatBytes(bytes: number): string;
488
+
489
+ interface SyntheticDiffOptions {
490
+ /**
491
+ * Only for a path the reviewer named explicitly (single-file review); enumerated paths never
492
+ * follow links.
493
+ */
494
+ followSymlinks?: boolean;
495
+ budgets?: Partial<SourceBudgets>;
496
+ }
497
+ interface SyntheticDiffResult {
498
+ diff: string;
499
+ /**
500
+ * Files listed without content, by literal relative path, with the sentence the viewer shows
501
+ * instead.
502
+ */
503
+ omitted: Map<string, string>;
504
+ diagnostics: string[];
505
+ }
506
+ /**
507
+ * Generate synthetic unified diffs for a list of file paths so they can be
508
+ * parsed by the existing diff parser. Each file is treated as a new addition.
509
+ *
510
+ * @param paths - Literal relative file paths (e.g. "src/foo.ts"), resolved
511
+ * against rootDir and never git-quoted on the way in
512
+ * @param rootDir - Absolute path to the root directory the paths are relative to
513
+ * @returns The diff text, the files listed without content, and diagnostics
514
+ */
515
+ declare function generateSyntheticDiffs(paths: string[], rootDir: string, options?: SyntheticDiffOptions): SyntheticDiffResult;
516
+ interface AsyncSyntheticDiffOptions extends SyntheticDiffOptions {
517
+ /** Used for root resolution and every source inspection/read. */
518
+ readFs?: SourceReadFsLayer;
519
+ signal?: AbortSignal;
520
+ }
521
+ /** Async counterpart with the same ordering, budgets and projection as generateSyntheticDiffs. */
522
+ declare function generateSyntheticDiffsAsync(paths: string[], rootDir: string, options?: AsyncSyntheticDiffOptions): Promise<SyntheticDiffResult>;
523
+ /** Build structured additions directly, with the same projection and budgets as patch output. */
524
+ declare function loadSyntheticFiles(paths: string[], rootDir: string, options?: SyntheticDiffOptions): {
525
+ files: DiffFile[];
526
+ diagnostics: string[];
527
+ };
528
+ /** Async build; cancellation never returns a partial set of files. */
529
+ declare function loadSyntheticFilesAsync(paths: string[], rootDir: string, options?: AsyncSyntheticDiffOptions): Promise<{
530
+ files: DiffFile[];
531
+ diagnostics: string[];
532
+ }>;
533
+
534
+ /** Optional execution effects; existing helper call forms keep their defaults. */
535
+ interface GitExecutionOptions {
536
+ signal?: AbortSignal;
537
+ timeoutMs?: number;
538
+ runner?: ForgeCommandRunner;
539
+ /** Defaults to stderr for compatibility; strict executeGit itself reports by throwing. */
540
+ reportDiagnostic?: DiagnosticReporter;
541
+ }
542
+ declare class GitCommandError extends Error {
543
+ readonly args: readonly string[];
544
+ readonly exitCode: number;
545
+ readonly stderr: string;
546
+ constructor(args: readonly string[], exitCode: number, stderr: string);
547
+ }
548
+ /** Rejects when git is missing or `cwd` is not inside a repository. */
549
+ declare function getRepoRootAsync(cwd?: string, options?: GitExecutionOptions): Promise<string>;
550
+ /**
551
+ * Config overrides, placed before `diff`, that keep output parseable whatever the user's config
552
+ * says.
553
+ */
554
+ declare const PARSER_COMPATIBLE_GIT_CONFIG: readonly string[];
555
+ /** Appended after the user's options so a user `--color=always` or `--no-prefix` loses. */
556
+ declare const PARSER_COMPATIBLE_DIFF_FLAGS: readonly string[];
557
+ /** Inserts the flags after every user option and before `--`. */
558
+ declare function withParserCompatibleDiffArgs(args: readonly string[]): string[];
559
+ /**
560
+ * The one entry point for every `git diff` (load, expansion, remote), so the
561
+ * parser-compatible normalization applies uniformly. Output past `maxOutputBytes`
562
+ * rejects with an error {@link isOutputLimitError} recognizes.
563
+ */
564
+ declare function runGitDiffAsync(args: string[], cwd?: string, maxOutputBytes?: number, options?: GitExecutionOptions): Promise<string>;
565
+ /** Compatibility helper: callers historically receive [] and a warning on listing failure. */
566
+ declare function getUntrackedFilesAsync(repoRoot?: string, options?: GitExecutionOptions): Promise<string[]>;
567
+ /**
568
+ * Generate synthetic unified diffs for untracked files so they can be
569
+ * parsed by the existing diff parser. Untracked symlinks are described by
570
+ * their link text, never followed.
571
+ */
572
+ declare function generateUntrackedDiffs(paths: string[], repoRoot: string, options?: SyntheticDiffOptions): SyntheticDiffResult;
573
+
574
+ declare const loadedReviewBrand: unique symbol;
575
+ /** Opaque host-local load capability. Never include it in XML, IPC or other wire data. */
576
+ interface LoadedReview {
577
+ readonly [loadedReviewBrand]: true;
578
+ }
579
+ /** Returns the original mutable logical identity alias, not a copy or captured handle. */
580
+ declare function loadedReviewIdentity(review: LoadedReview): ReviewSourceIdentity;
581
+ /** A defensive membership copy; changing it cannot authorize another captured read. */
582
+ declare function loadedReviewPaths(review: LoadedReview): ReadonlySet<string>;
583
+
584
+ /** Reference as the resumed document wrote it → absolute path beside that document. Session state only. */
585
+ type AttachmentOrigins = ReadonlyMap<string, string>;
586
+ type AttachmentReadFailureReason = 'not-authorized' | 'not-found' | 'not-regular' | 'unsafe-link' | 'too-large' | 'io-error';
587
+ type AttachmentReadResult = {
588
+ ok: true;
589
+ data: ArrayBuffer;
590
+ } | {
591
+ ok: false;
592
+ reason: AttachmentReadFailureReason;
593
+ message: string;
594
+ };
595
+ /** A physical directory resolved by the host's own filesystem. No native lookup is made. */
596
+ interface ResolvedAttachmentLocation {
597
+ documentDirectory: string;
598
+ }
599
+ /** Origins resolve against the resumed document's directory; an unrecorded reference is never read. */
600
+ declare function resolveAttachmentOrigins(comments: readonly ReviewComment[], resumeDocumentPath: string, location: ResolvedAttachmentLocation): {
601
+ origins: Map<string, string>;
602
+ diagnostics: string[];
603
+ };
604
+ declare function resolveAttachmentOrigins(comments: readonly ReviewComment[], resumeDocumentPath: string): {
605
+ origins: Map<string, string>;
606
+ diagnostics: string[];
607
+ };
608
+ /** Read one asset the caller authorized: the asset directory must not be a link, nor the leaf. */
609
+ interface AttachmentReadOptions {
610
+ fs?: FsLayer;
611
+ /** Bounded read-only adapter, preferred over the legacy fs when both are supplied. */
612
+ readFs?: BoundedAsyncReadFsLayer;
613
+ signal?: AbortSignal;
614
+ /** Remaining aggregate budget, in addition to the fixed per-image limit. */
615
+ maxBytes?: number;
616
+ }
617
+ declare function readAssetFile(assetPath: string, options?: AttachmentReadOptions): Promise<AttachmentReadResult>;
618
+ /** The recorded origin of an imported reference, else the same name in `currentAssetDir`. */
619
+ declare function authorizeAttachmentReference(reference: unknown, origins: AttachmentOrigins, currentAssetDir: string | null): string | null;
620
+ declare class AttachmentRelocationError extends Error {
621
+ readonly reference: string;
622
+ readonly origin: string;
623
+ readonly reason: AttachmentReadFailureReason;
624
+ constructor(reference: string, origin: string, reason: AttachmentReadFailureReason, detail: string);
625
+ }
626
+ /**
627
+ * Give every imported attachment whose origin is not beside `outputPath` its bytes, so the
628
+ * publisher stages a copy. This compatibility API retains at most 64 MiB of attachment bytes;
629
+ * publishReview instead plans references and stages one disk-derived buffer at a time. Unreadable ones throw: the old reference would resolve to the wrong file.
630
+ */
631
+ declare function relocateAttachments(state: ReviewState, origins: AttachmentOrigins, outputPath: string, options?: AttachmentReadOptions): Promise<ReviewState>;
632
+
633
+ /**
634
+ * The state a single review session owns. One desktop application window is
635
+ * one session; two sessions are independent and cannot observe each other.
636
+ */
637
+ interface ReviewSession {
638
+ reviewState: ReviewState | null;
639
+ diffData: DiffLoadPayload | null;
640
+ guideData: GuideLoadPayload | null;
641
+ config: AppConfig | null;
642
+ outputPathInfo: OutputPathInfo | null;
643
+ resumeComments: ReviewComment[];
644
+ resumeViewedFiles: string[];
645
+ resumeRemoteDrift: RemoteDriftInfo | null;
646
+ resumeImportDiagnostics: string[];
647
+ /**
648
+ * Destination directory the user named for this session's applies, or
649
+ * null when none has been named. Only a temporary-clone remote review
650
+ * needs one; see {@link resolveApplyDestination}.
651
+ */
652
+ applyDestinationRoot: string | null;
653
+ /**
654
+ * Old and new path of every file in the committed diff, frozen by {@link commitDiffData}.
655
+ * The authorization set for writes; resumed comments, submitted state and placeholder
656
+ * entries can name other paths and never reach it.
657
+ */
658
+ reviewedPaths: ReadonlySet<string>;
659
+ /**
660
+ * Recorded by {@link commitDiffData}; null until then (and for welcome), when every read of
661
+ * reviewed content refuses.
662
+ */
663
+ sourceIdentity: ReviewSourceIdentity | null;
664
+ /** Host-local captured load, optional for legacy session objects. Never transport this value. */
665
+ loadedReview?: LoadedReview | null;
666
+ /**
667
+ * Resumed reference to absolute path beside *the resumed document*; authorizes reads and tells
668
+ * the publisher which bytes to carry. Never sent to the front end.
669
+ */
670
+ attachmentOrigins: AttachmentOrigins;
671
+ }
672
+ /** Create an empty session. */
673
+ declare function createReviewSession(): ReviewSession;
674
+ /**
675
+ * The one place a diff is committed to a session: captures `reviewedPaths` and
676
+ * records `sourceIdentity`; later `diffData` edits (expanded hunks) leave both alone.
677
+ * The identity comes from the loader, and is `null` only for a payload that
678
+ * reviews nothing (welcome), so reads refuse rather than guess a root.
679
+ */
680
+ declare function commitDiffData(session: Pick<ReviewSession, 'diffData' | 'reviewedPaths' | 'sourceIdentity'>, payload: DiffLoadPayload, identity: ReviewSourceIdentity | null): void;
681
+ /** Commit explicit load evidence while preserving the original payload and identity aliases. */
682
+ declare function commitLoadedReview(session: Pick<ReviewSession, 'diffData' | 'reviewedPaths' | 'sourceIdentity' | 'loadedReview'>, payload: DiffLoadPayload, loadedReview: LoadedReview): void;
683
+ /**
684
+ * The old side is where a deletion or a rename's old name lives. Null when the diff has no such
685
+ * file.
686
+ */
687
+ declare function locateReviewedFile(session: Pick<ReviewSession, 'diffData'>, filePath: string): {
688
+ file: DiffFile;
689
+ side: 'old' | 'new';
690
+ } | null;
691
+ /**
692
+ * Prepare a DiffLoadPayload for IPC transmission.
693
+ * In large-payload mode, strips hunks from files to reduce initial transfer size.
694
+ * The full data stays in the session for on-demand loading via DIFF_LOAD_FILE.
695
+ */
696
+ declare function preparePayload(payload: DiffLoadPayload): DiffLoadPayload;
697
+ /**
698
+ * Resolve what a diff request should deliver: the prepared diff payload and,
699
+ * when one is loaded, the guide that rides with it. Returns null when the
700
+ * session has no diff, so the caller sends nothing at all.
701
+ */
702
+ declare function getDiffLoad(session: Pick<ReviewSession, 'diffData' | 'guideData'>): {
703
+ diff: DiffLoadPayload;
704
+ guide: GuideLoadPayload | null;
705
+ } | null;
706
+ /** The read-only source root; {@link resolveApplyDestination} decides where applies write. */
707
+ declare function resolveSourceBaseDir(session: Pick<ReviewSession, 'sourceIdentity'>): string | null;
708
+ /**
709
+ * Return a single file's hunks for lazy (large-payload) mode, or null when the
710
+ * session has no diff or the diff has no such file.
711
+ */
712
+ declare function getFileHunks(session: Pick<ReviewSession, 'diffData'>, filePath: string): DiffHunk[] | null;
713
+ /**
714
+ * Resolve the config and the output path info that travel with it. Returns null
715
+ * when the session has no config, so the caller sends nothing at all: the
716
+ * renderer distinguishes an absent message from an empty one.
717
+ */
718
+ declare function getConfigLoad(session: Pick<ReviewSession, 'config' | 'outputPathInfo'>): {
719
+ config: AppConfig;
720
+ outputPathInfo: OutputPathInfo | null;
721
+ } | null;
722
+ /**
723
+ * Store a review state submitted by the front end on the session.
724
+ */
725
+ declare function submitReviewState(session: Pick<ReviewSession, 'reviewState'>, state: ReviewState, reportDiagnostic?: DiagnosticReporter): void;
726
+ /**
727
+ * Take the submitted review state off the session, clearing it so it is
728
+ * consumed exactly once. Returns null when nothing has been submitted.
729
+ */
730
+ declare function takeReviewState(session: Pick<ReviewSession, 'reviewState'>): ReviewState | null;
731
+ /**
732
+ * Resolve the resumed comments, viewed files and remote drift for a session.
733
+ * Returns null when there is nothing to resume, so the caller sends nothing
734
+ * at all.
735
+ */
736
+ declare function getResumeLoad(session: Pick<ReviewSession, 'resumeComments' | 'resumeViewedFiles' | 'resumeRemoteDrift' | 'resumeImportDiagnostics'>): ResumeLoadPayload | null;
737
+
738
+ /**
739
+ * Why an apply was refused. Every value is a structural fact about the
740
+ * request or the file — never a fragment of the file's contents, so a
741
+ * refusal is safe to surface in the UI and in logs.
742
+ */
743
+ type ApplyRefusalReason =
744
+ /** The suggestion is file-level: there is nothing to replace. */
745
+ 'no-anchor'
746
+ /**
747
+ * The anchor names deleted lines (`side: 'old'`). Those lines are not in
748
+ * the working file, and the app holds no old→new line mapping, so the
749
+ * target is undefined rather than merely missing.
750
+ */
751
+ | 'old-side-anchor'
752
+ /** Unknown side, non-positive or non-integer bounds, or reversed; checked before any I/O. */
753
+ | 'invalid-anchor'
754
+ /** `destinationRoot` is relative; resolving it would consult the cwd. */
755
+ | 'destination-not-absolute' | 'destination-missing'
756
+ /** `filePath` resolves outside `destinationRoot`. */
757
+ | 'path-escapes-destination' | 'control-file'
758
+ /** A link on the way or at the leaf, a hard-linked or special file, or a swap during the open. */
759
+ | 'unsafe-target'
760
+ /** Replacing the file would change its owner, which this process cannot restore. */
761
+ | 'unsupported-target'
762
+ /** No file at the resolved path. */
763
+ | 'file-missing'
764
+ /** The path exists but could not be read (permissions, a directory, …). */
765
+ | 'file-unreadable'
766
+ /**
767
+ * The file is not valid UTF-8. Rewriting it would round-trip its bytes
768
+ * through a lossy decode and corrupt regions outside the anchor.
769
+ */
770
+ | 'file-not-utf8'
771
+ /** The anchor falls outside the file's line count. */
772
+ | 'anchor-out-of-range'
773
+ /** The anchored lines no longer match `suggestion.originalCode`. */
774
+ | 'context-mismatch'
775
+ /** The file was replaced or rewritten between the read and the commit. */
776
+ | 'file-changed'
777
+ /** The context matched but the write itself failed. */
778
+ | 'write-failed';
779
+ interface ApplySuggestionRequest {
780
+ /**
781
+ * Absolute path of the directory the reviewed files live in. Always
782
+ * supplied by the caller: a git-mode working tree, a directory-mode root,
783
+ * a reused clone, or the destination the user picked for a temporary-clone
784
+ * review. Never derived here.
785
+ */
786
+ destinationRoot: string;
787
+ /** Path of the file to modify, relative to `destinationRoot`. */
788
+ filePath: string;
789
+ /** The comment's anchor. `null` (file-level) is refused. */
790
+ lineRange: LineRange | null;
791
+ suggestion: Suggestion;
792
+ }
793
+ interface ApplySuggestionOptions {
794
+ fs?: FsLayer;
795
+ randomName?: () => string;
796
+ /** Input and resulting output limits, independently enforced. Both default to 5 MiB. */
797
+ maxInputBytes?: number;
798
+ maxOutputBytes?: number;
799
+ /** Last synchronous authorization check before rename; throwing refuses the write. */
800
+ beforeCommit?: () => void;
801
+ }
802
+ interface ApplySuggestionAsyncOptions extends Omit<ApplySuggestionOptions, 'fs'> {
803
+ fs?: AsyncFsLayer;
804
+ /** Check the resolved physical root after resolution and before staging, before any write. */
805
+ validateDestination?: (physicalRoot: string) => void;
806
+ /** Cancellation rejects with signal.reason before commit. A committed write stays applied. */
807
+ signal?: AbortSignal;
808
+ }
809
+ interface ApplySuggestionApplied {
810
+ status: 'applied';
811
+ /** Echoed from the request, so a batch caller can attribute the result. */
812
+ filePath: string;
813
+ absolutePath: string;
814
+ /** How many on-disk lines the proposal replaced. */
815
+ replacedLines: number;
816
+ }
817
+ interface ApplySuggestionRefused {
818
+ status: 'refused';
819
+ filePath: string;
820
+ reason: ApplyRefusalReason;
821
+ /** One sentence naming the refusal, safe to show to the reviewer. */
822
+ detail: string;
823
+ }
824
+ type ApplySuggestionResult = ApplySuggestionApplied | ApplySuggestionRefused;
825
+ /**
826
+ * A `.git` segment at any depth, directory or worktree file: git executes what is in there. `.gitmodules`
827
+ * and the like are reviewed content, gated by diff membership in the session handler instead.
828
+ */
829
+ declare function isRepositoryControlPath(filePath: string): boolean;
830
+ /**
831
+ * Bounded synchronous Apply for existing callers. Only the anchor is decoded and proposal encoded;
832
+ * untouched regions are copied as bytes. Invalid options throw RangeError; refusals are values.
833
+ */
834
+ declare function applySuggestion(request: ApplySuggestionRequest, options?: ApplySuggestionOptions): ApplySuggestionResult;
835
+ /**
836
+ * Promise-based Apply with the same byte budgets, validation and replacement policy as Apply.
837
+ * Bulk reads and writes use native asynchronous I/O in chunks of at most 64 KiB. Operations are
838
+ * independent; competing applies are checked against the inode/stamp they read, not serialized.
839
+ * Cancellation rejects before commit and removes staging. After rename it returns applied even
840
+ * if the signal aborts. The portable final check/rename race is documented in atomicReplaceAsync.
841
+ */
842
+ declare function applySuggestionAsync(request: ApplySuggestionRequest, options?: ApplySuggestionAsyncOptions): Promise<ApplySuggestionResult>;
843
+
844
+ type ApplySuggestionForSessionAsyncOptions = Omit<ApplySuggestionAsyncOptions, 'beforeCommit' | 'validateDestination'>;
845
+ type ApplySession = Pick<ReviewSession, 'diffData' | 'sourceIdentity' | 'applyDestinationRoot' | 'reviewedPaths'>;
846
+ /** Read-only destination policy, independent of source writes. Methods retain their receiver. */
847
+ interface ApplyDestinationInspection {
848
+ realpath(target: string): string;
849
+ isDirectory(target: string): boolean;
850
+ }
851
+ interface SuggestionOperationOptions {
852
+ destinationInspection?: ApplyDestinationInspection;
853
+ reportDiagnostic?: DiagnosticReporter;
854
+ }
855
+ interface ApplySuggestionForSessionOptions extends SuggestionOperationOptions {
856
+ /** Authoritative filesystem for synchronous Apply; never supplemented with native I/O. */
857
+ fs?: FsLayer;
858
+ }
859
+ declare const nodeApplyDestinationInspection: ApplyDestinationInspection;
860
+ /**
861
+ * The directory an apply may write into for this session, or null when the
862
+ * session has none.
863
+ *
864
+ * For every review whose files sit in a place the user controls — a git
865
+ * working tree, a scanned directory, a reused remote clone — that is the
866
+ * root the reviewed paths are relative to, and no one is asked anything.
867
+ *
868
+ * A temporary-clone review is the one exception. Its files live in a
869
+ * directory the app deletes on exit, so the clone is never a destination:
870
+ * the answer is the directory the user named, and null until they name one.
871
+ */
872
+ declare function resolveApplyDestination(session: Pick<ReviewSession, 'diffData' | 'sourceIdentity' | 'applyDestinationRoot'>): string | null;
873
+ /**
874
+ * Record the directory the user named as this session's apply destination.
875
+ *
876
+ * The caller supplies a path the user picked; this decides whether it can
877
+ * be written into and stores it only if so. The temporary clone, and
878
+ * anything inside it, is refused however it was reached — that directory
879
+ * is gone when the review ends, which is the whole reason a destination is
880
+ * asked for.
881
+ */
882
+ declare function setApplyDestination(session: Pick<ReviewSession, 'diffData' | 'sourceIdentity' | 'applyDestinationRoot'>, directoryPath: string, options?: SuggestionOperationOptions): ApplyDestinationOutcome;
883
+ /** Apply synchronously using the session's destination and reviewed-path authorization. */
884
+ declare function applySuggestionForSession(session: ApplySession, request: SuggestionApplyRequest, effects?: ApplySuggestionForSessionOptions): SuggestionApplyOutcome;
885
+ /**
886
+ * Bounded asynchronous Apply. Capture authorization before awaiting filesystem I/O and recheck
887
+ * it synchronously just before rename. Replacing the loaded review, changing its identity or
888
+ * selected destination, or removing membership refuses with file-changed and removes staging.
889
+ * Cancellation rejects with signal.reason before commit, and a committed result stays applied.
890
+ */
891
+ declare function applySuggestionForSessionAsync(session: ApplySession, request: SuggestionApplyRequest, options?: ApplySuggestionForSessionAsyncOptions, effects?: SuggestionOperationOptions): Promise<SuggestionApplyOutcome>;
892
+
893
+ /** One side as the arguments describe it, before resolution; `implicit` is the HEAD git assumes. */
894
+ type GitDiffSideSpec = {
895
+ kind: 'working-tree';
896
+ } | {
897
+ kind: 'index';
898
+ } | {
899
+ kind: 'revision';
900
+ rev: string;
901
+ implicit: boolean;
902
+ } | {
903
+ kind: 'merge-base';
904
+ left: string;
905
+ right: string;
906
+ } | {
907
+ kind: 'unknown';
908
+ reason: string;
909
+ };
910
+ interface GitDiffSides {
911
+ oldSide: GitDiffSideSpec;
912
+ newSide: GitDiffSideSpec;
913
+ }
914
+ /**
915
+ * The two snapshots a `git diff` argv compares. Pure: runs no git and checks no revision.
916
+ * Uses the classifier's arity rules, so `-S --cached` is not a flag. `--no-index`, three
917
+ * or more revisions and `--cached` with a range are `unknown`.
918
+ */
919
+ declare function describeGitDiffSides(argv: readonly string[]): GitDiffSides;
920
+ declare function canonicalSourcePath(target: string): string;
921
+ /**
922
+ * `ReviewSourceIdentity.pathPrefix`: empty for root-relative output, the
923
+ * `--relative=<dir>` directory without trailing slashes, or for bare `--relative`
924
+ * the launch directory under the root (empty when outside the work tree, as in git).
925
+ */
926
+ declare function resolveReviewedPathPrefix(gitDiffArgv: readonly string[], sourceRoot: string, invocationCwd: string, canonical?: (target: string) => string): string;
927
+ /** The one mapping every reader, Apply and re-diff uses, so they all name the same file. */
928
+ declare function rootRelativeReviewedPath(identity: Pick<ReviewSourceIdentity, 'pathPrefix'>, filePath: string): string;
929
+ interface GitSourceIdentityOptions extends GitExecutionOptions {
930
+ /** Supplied source path resolution; never falls back to native realpath. */
931
+ sourcePaths?: LocalSourcePaths;
932
+ repository: string;
933
+ gitDiffArgv: readonly string[];
934
+ /** Defaults to the process's working directory. */
935
+ invocationCwd?: string;
936
+ /** `'remote'` for a materialized PR/MR; the git-mode machinery is the same. */
937
+ mode?: 'git' | 'remote';
938
+ }
939
+ /** Resolves commits once. Unresolvable revisions become `unknown`; cancellation rejects. */
940
+ declare function resolveGitSourceIdentity(options: GitSourceIdentityOptions): Promise<ReviewSourceIdentity>;
941
+ interface LocalSourceIdentityOptions {
942
+ type: 'directory' | 'file';
943
+ sourcePath: string;
944
+ /** Defaults to the process's working directory. */
945
+ invocationCwd?: string;
946
+ }
947
+ /**
948
+ * Everything is an addition, so the old side is `none`. A single-file review follows a
949
+ * symlink the user named, recording its target once; its root is the parent of the path as given.
950
+ */
951
+ declare function resolveLocalSourceIdentity(options: LocalSourceIdentityOptions): ReviewSourceIdentity;
952
+ /** The path role a local load needs; a supplied provider owns every canonicalization. */
953
+ interface LocalSourcePaths {
954
+ realpath(target: string): Promise<string>;
955
+ }
956
+ /** Async identity resolution for supplied sources; the synchronous public form stays native. */
957
+ declare function resolveLocalSourceIdentityAsync(options: LocalSourceIdentityOptions, paths: LocalSourcePaths, signal?: AbortSignal): Promise<ReviewSourceIdentity>;
958
+
959
+ export { type ApplySuggestionAsyncOptions as $, type AsyncFsLayer as A, type BoundedAsyncReadFsLayer as B, nodeTemporaryCloneStorage as C, openContainedFile as D, openContainedFileAsync as E, type FsLayer as F, readContainedFile as G, readContainedFileAsync as H, readContainedFileBounded as I, sameFile as J, snapshotIdentity as K, type LocalSourcePaths as L, writeExclusiveNoFollow as M, writeExclusiveNoFollowAsync as N, type SourceBudgets as O, type PublicationFileSystem as P, type DiagnosticReporter as Q, type GitExecutionOptions as R, type ScanFsLayer as S, type TemporaryCloneStorage as T, type ForgeCommandRunner as U, type ForgeProvider as V, type WriteExclusiveOptions as W, type ForgeThread as X, type ReviewSession as Y, type ApplyRefusalReason as Z, type ApplySuggestionApplied as _, type ApplyDestinationInspection as a, generateSyntheticDiffsAsync as a$, type ApplySuggestionForSessionAsyncOptions as a0, type ApplySuggestionOptions as a1, type ApplySuggestionRefused as a2, type ApplySuggestionRequest as a3, type ApplySuggestionResult as a4, type AsyncSyntheticDiffOptions as a5, type AttachmentOrigins as a6, type AttachmentReadFailureReason as a7, type AttachmentReadOptions as a8, type AttachmentReadResult as a9, MAX_IMAGE_BYTES as aA, MAX_PUBLICATION_ASSET_BYTES as aB, MAX_RESUME_ATTACHMENTS as aC, MAX_RESUME_XML_BYTES as aD, MAX_REVIEW_ATTACHMENTS as aE, MAX_SOURCE_ENTRIES as aF, MAX_SOURCE_FILE_BYTES as aG, MAX_SOURCE_FILE_LINES as aH, MAX_SOURCE_TOTAL_BYTES as aI, MAX_SOURCE_TOTAL_LINES as aJ, PARSER_COMPATIBLE_DIFF_FLAGS as aK, PARSER_COMPATIBLE_GIT_CONFIG as aL, type SuggestionOperationOptions as aM, type SyntheticDiffOptions as aN, type SyntheticDiffResult as aO, applySuggestion as aP, applySuggestionAsync as aQ, applySuggestionForSession as aR, applySuggestionForSessionAsync as aS, authorizeAttachmentReference as aT, canonicalSourcePath as aU, commitDiffData as aV, commitLoadedReview as aW, createReviewSession as aX, describeGitDiffSides as aY, formatBytes as aZ, generateSyntheticDiffs as a_, AttachmentRelocationError as aa, BINARY_SNIFF_BYTES as ab, type CommandCancelReason as ac, CommandCancelledError as ad, DEFAULT_SOURCE_BUDGETS as ae, type FetchThreadsOptions as af, type ForgeAnchorSide as ag, ForgeCliUnavailableError as ah, type ForgeCommandOptions as ai, type ForgeCommandResult as aj, type ForgeName as ak, type ForgeThreadAnchor as al, type ForgeThreadTurn as am, type ForgeUrl as an, GitCommandError as ao, type GitDiffSideSpec as ap, type GitDiffSides as aq, type GitSourceIdentityOptions as ar, type LoadedReview as as, type LocalSourceIdentityOptions as at, MAX_DIFF_DIAGNOSTICS as au, MAX_DIFF_DIAGNOSTIC_CHARS as av, MAX_DIFF_FILES as aw, MAX_DIFF_HUNKS as ax, MAX_GIT_DIFF_OUTPUT_BYTES as ay, MAX_GUIDE_BYTES as az, type AsyncFileHandle as b, generateUntrackedDiffs as b0, getConfigLoad as b1, getDiffLoad as b2, getFileHunks as b3, getRepoRootAsync as b4, getResumeLoad as b5, getUntrackedFilesAsync as b6, isCommandCancelled as b7, isRepositoryControlPath as b8, loadSyntheticFiles as b9, loadSyntheticFilesAsync as ba, loadedReviewIdentity as bb, loadedReviewPaths as bc, locateReviewedFile as bd, parseForgeUrl as be, preparePayload as bf, readAssetFile as bg, relocateAttachments as bh, resolveApplyDestination as bi, resolveAttachmentOrigins as bj, resolveGitSourceIdentity as bk, resolveLocalSourceIdentity as bl, resolveLocalSourceIdentityAsync as bm, resolveReviewedPathPrefix as bn, resolveSourceBaseDir as bo, resolveSourceBudgets as bp, rootRelativeReviewedPath as bq, runGitDiffAsync as br, submitReviewState as bs, takeReviewState as bt, withParserCompatibleDiffArgs as bu, type ResolvedAttachmentLocation as bv, type ApplySuggestionForSessionOptions as bw, setApplyDestination as bx, type AsyncReadFsLayer as c, type AsyncReadHandle as d, type AtomicReplaceAsyncOptions as e, type AtomicReplaceOptions as f, type AtomicReplaceResult as g, type FileIdentity as h, type PublicationInspection as i, SafeFsError as j, type SafeFsErrorCode as k, type ScanDirectoryHandle as l, type ScanEntry as m, type SourceReadFsLayer as n, type SyncReadFsLayer as o, assertNoSymlinkAncestors as p, atomicReplace as q, atomicReplaceAsync as r, boundedReadFsFromSync as s, classifyFsError as t, inspectReplaceTarget as u, nodeApplyDestinationInspection as v, nodeAsyncFsLayer as w, nodeFsLayer as x, nodePublicationFileSystem as y, nodeReadFsLayer as z };