@self-review/core 1.44.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,9 +1,56 @@
1
- import { DiffFile, ReviewState, ReviewComment, DiffSource, RemoteForge, ReviewGuide, ResolvedGuideGroup, AppConfig, PayloadStats, LineRange, Suggestion, DiffLoadPayload, GuideLoadPayload, OutputPathInfo, RemoteDriftInfo, SuggestionApplyRequest, SuggestionApplyOutcome, ExpandContextRequest, DiffHunk, ResumeLoadPayload, ImageLoadResult, RemoteSessionInfo } from '@self-review/types';
2
- export { AppConfig, Attachment, CategoryDef, ChangeType, CommentConfidence, CommentSeverity, DiffFile, DiffHunk, DiffLine, DiffLineType, DiffLoadPayload, DiffSource, ExpandContextRequest, ExpandContextResponse, FileReviewState, FindInPageRequest, FindInPageResult, GuideFileEntry, GuideGroup, ImageLoadResult, LineRange, OutputPathInfo, PayloadStats, ResolvedGuideFile, ResolvedGuideGroup, ResumeLoadPayload, ReviewComment, ReviewGuide, ReviewState, Suggestion, VersionUpdateInfo } from '@self-review/types';
1
+ import { DiffFile, ReviewState, ReviewComment, DiffSource, RemoteForge, LineRange, ReviewGuide, ResolvedGuideGroup, ReviewSourceIdentity, AppConfig, PayloadStats, Suggestion, DiffLoadPayload, GuideLoadPayload, OutputPathInfo, RemoteDriftInfo, SuggestionApplyRequest, SuggestionApplyOutcome, ExpandContextRequest, DiffHunk, ResumeLoadPayload, ImageLoadResult, RemoteSessionInfo } from '@self-review/types';
2
+ export { AppConfig, ApplyDestinationOutcome, Attachment, CategoryDef, ChangeType, CommentConfidence, CommentSeverity, DiffFile, DiffHunk, DiffLine, DiffLineType, DiffLoadPayload, DiffSource, ExpandContextRequest, ExpandContextResponse, FileReviewState, FindInPageRequest, FindInPageResult, GuideFileEntry, GuideGroup, ImageLoadResult, LineRange, OutputPathInfo, PayloadStats, ResolvedGuideFile, ResolvedGuideGroup, ResumeLoadPayload, ReviewComment, ReviewGuide, ReviewSourceIdentity, ReviewSourceMode, ReviewSourceSide, ReviewState, Suggestion, SuggestionApplyOutcome, SuggestionApplyRequest, VersionUpdateInfo } from '@self-review/types';
3
+ import * as nodeFs from 'node:fs';
3
4
 
5
+ /**
6
+ * The files parsed, plus one diagnostic per piece of input that could not be represented
7
+ * faithfully.
8
+ */
9
+ interface DiffParseResult {
10
+ files: DiffFile[];
11
+ diagnostics: string[];
12
+ }
13
+ /** Parse a unified diff, discarding diagnostics. Prefer {@link parseDiffWithDiagnostics}. */
4
14
  declare function parseDiff(rawDiff: string): DiffFile[];
15
+ /**
16
+ * Parse `git diff` output (a/ b/ prefixes, no color). Every hunk is checked
17
+ * against its `@@` counts; a line over them, a short hunk or an unprefixed line
18
+ * is a diagnostic, never context. Empty lines in an open hunk are the one
19
+ * leniency (`git apply` reads them as empty context). Combined output
20
+ * (`diff --cc`) is reported and skipped.
21
+ */
22
+ declare function parseDiffWithDiagnostics(rawDiff: string): DiffParseResult;
5
23
 
6
- declare function serializeReview(state: ReviewState, outputFilePath: string): Promise<string>;
24
+ declare const ASSET_DIR_NAME = ".self-review-assets";
25
+ interface PlannedAsset {
26
+ /** As emitted in the document: `.self-review-assets/<name>`. */
27
+ relativePath: string;
28
+ absolutePath: string;
29
+ data: ArrayBuffer;
30
+ }
31
+ /**
32
+ * `idPrefix` is already URL-safe; the result must be a bare file name. The publisher injects unique
33
+ * names so a new document never overwrites an asset the previous one references.
34
+ */
35
+ type AssetNamer = (idPrefix: string, index: number, ext: string) => string;
36
+ interface SerializeOptions {
37
+ assetName?: AssetNamer;
38
+ }
39
+ interface SerializedReview {
40
+ /** Validated, without a trailing newline. */
41
+ xml: string;
42
+ /** Blobs the document references that nothing has written yet. */
43
+ assets: PlannedAsset[];
44
+ }
45
+ /**
46
+ * Pure: touches no disk (`publishReview` writes). Built before validation, so an
47
+ * unrepresentable value is refused first.
48
+ *
49
+ * @throws XmlIllegalCharacterError naming the comment/reply and field.
50
+ * @throws ReviewXmlError `schema-invalid`, one violation per `details` line. A validator
51
+ * that fails to load is deliberately not fatal: unvalidated XML after a stderr warning.
52
+ */
53
+ declare function serializeReview(state: ReviewState, outputFilePath: string, options?: SerializeOptions): Promise<SerializedReview>;
7
54
 
8
55
  interface ParsedReview {
9
56
  comments: ReviewComment[];
@@ -11,14 +58,291 @@ interface ParsedReview {
11
58
  viewedFiles: string[];
12
59
  gitDiffArgs: string;
13
60
  source: DiffSource;
61
+ /**
62
+ * One line per comment downgraded to file-level feedback, with its suggestion text folded into
63
+ * the body.
64
+ */
65
+ importDiagnostics: string[];
14
66
  remoteUrl?: string;
15
67
  remoteBaseSha?: string;
16
68
  remoteHeadSha?: string;
17
69
  remoteForge?: RemoteForge;
18
70
  }
71
+ /**
72
+ * Sized before it is read, so an oversized document or a FIFO is refused unread.
73
+ *
74
+ * @throws ReviewXmlError `read-failed`, `input-too-large`, or what
75
+ * {@link parseReviewXmlString} throws.
76
+ */
19
77
  declare function parseReviewXml(xmlPath: string): ParsedReview;
78
+ /**
79
+ * Namespace-blind by design: v1, v2 and v3 documents read identically.
80
+ *
81
+ * @throws ReviewXmlError `parse-failed`, `missing-root`, or `input-too-large`
82
+ * (over `MAX_RESUME_ATTACHMENTS`).
83
+ */
20
84
  declare function parseReviewXmlString(xmlContent: string): ParsedReview;
21
85
 
86
+ type ReviewXmlErrorCode = 'read-failed'
87
+ /** Over a safety budget (input-budgets.ts): byte size or attachment count. */
88
+ | 'input-too-large' | 'parse-failed'
89
+ /** Well-formed, but with no `<review>` root element. */
90
+ | 'missing-root'
91
+ /** The generated document does not validate against the v3 XSD. */
92
+ | 'schema-invalid' | 'xml-illegal-character';
93
+ declare class ReviewXmlError extends Error {
94
+ readonly code: ReviewXmlErrorCode;
95
+ readonly cause?: unknown;
96
+ /** One rendered line per problem (e.g. a schema violation with its line number). */
97
+ readonly details: readonly string[];
98
+ constructor(code: ReviewXmlErrorCode, message: string, options?: {
99
+ cause?: unknown;
100
+ details?: readonly string[];
101
+ });
102
+ }
103
+ interface XmlIllegalCharacterLocation {
104
+ /** e.g. `body`, `original-code`, `path`, `author`. */
105
+ field: string;
106
+ filePath?: string;
107
+ commentId?: string;
108
+ replyId?: string;
109
+ }
110
+ /**
111
+ * Thrown before anything is written: no escaped form exists, and dropping the character would
112
+ * change the reviewer's text or a suggestion's code.
113
+ */
114
+ declare class XmlIllegalCharacterError extends ReviewXmlError {
115
+ readonly codePoint: number;
116
+ readonly field: string;
117
+ readonly filePath?: string;
118
+ readonly commentId?: string;
119
+ readonly replyId?: string;
120
+ constructor(codePoint: number, location: XmlIllegalCharacterLocation);
121
+ }
122
+
123
+ type SafeFsErrorCode = 'output-is-directory'
124
+ /** EACCES, EPERM or EROFS. */
125
+ | 'permission-denied'
126
+ /** ENOSPC or EDQUOT. */
127
+ | 'no-space'
128
+ /** A symlink sits where this module would read, create or replace a file, or on the way to it. */
129
+ | 'unsafe-link'
130
+ /** Exists, but replacing it would change semantics: hard-linked, not a regular file, or foreign-owned. */
131
+ | 'unsupported-target'
132
+ /** The file at the target is not the one the caller checked. */
133
+ | 'identity-changed'
134
+ /** ENOENT or ENOTDIR. */
135
+ | 'not-found'
136
+ /** A FIFO, socket or device. */
137
+ | 'not-regular' | 'too-large' | 'io-error';
138
+ declare class SafeFsError extends Error {
139
+ readonly code: SafeFsErrorCode;
140
+ readonly path: string;
141
+ readonly cause?: unknown;
142
+ constructor(code: SafeFsErrorCode, path: string, message: string, cause?: unknown);
143
+ }
144
+ /** The subset of `fs` used here, synchronous so a test can inject a failure at an exact step. */
145
+ interface FsLayer {
146
+ openSync(path: string, flags: number, mode?: number): number;
147
+ /** May write fewer bytes than given, as the real one may. */
148
+ writeSync(fd: number, buffer: Uint8Array): number;
149
+ fsyncSync(fd: number): void;
150
+ fchmodSync(fd: number, mode: number): void;
151
+ fchownSync(fd: number, uid: number, gid: number): void;
152
+ closeSync(fd: number): void;
153
+ renameSync(from: string, to: string): void;
154
+ unlinkSync(path: string): void;
155
+ lstatSync(path: string): nodeFs.Stats;
156
+ fstatSync(fd: number): nodeFs.Stats;
157
+ readFileSync(fd: number): Buffer;
158
+ mkdirSync(path: string, mode: number): void;
159
+ realpathSync(path: string): string;
160
+ }
161
+ declare const nodeFsLayer: FsLayer;
162
+ interface FileIdentity {
163
+ dev: number;
164
+ ino: number;
165
+ /** Permission bits only (`mode & 0o7777`). */
166
+ mode: number;
167
+ nlink: number;
168
+ size: number;
169
+ mtimeMs: number;
170
+ uid: number;
171
+ gid: number;
172
+ }
173
+ declare function snapshotIdentity(stats: nodeFs.Stats): FileIdentity;
174
+ declare function sameFile(a: FileIdentity, b: FileIdentity): boolean;
175
+ /** The code a caller maps to its own reason; anything unknown is `io-error`. */
176
+ declare function classifyFsError(error: unknown): SafeFsErrorCode;
177
+ /**
178
+ * Refuse a `rel` whose directories under `root` include a symlink. The leaf is the caller's
179
+ * policy, and a missing component ends the walk: nothing can be linked where nothing is.
180
+ */
181
+ declare function assertNoSymlinkAncestors(root: string, rel: string, fs?: FsLayer): void;
182
+ interface WriteExclusiveOptions {
183
+ /** Masked by the umask. Default 0o666. */
184
+ mode?: number;
185
+ /** Applied after creation, bypassing the umask. */
186
+ exactMode?: number;
187
+ /** Applied after creation; failing to is `unsupported-target` and removes the file. */
188
+ exactOwner?: {
189
+ uid: number;
190
+ gid: number;
191
+ };
192
+ fs?: FsLayer;
193
+ }
194
+ /**
195
+ * Create `filePath`, which must not exist, write every byte and sync. A symlink at the path,
196
+ * dangling or not, is `unsafe-link`. Any failure after creation removes the file again.
197
+ */
198
+ declare function writeExclusiveNoFollow(filePath: string, bytes: Uint8Array, options?: WriteExclusiveOptions): FileIdentity;
199
+ interface AtomicReplaceOptions {
200
+ /** Give the replacement the replaced file's permission bits. */
201
+ preserveMode?: boolean;
202
+ /**
203
+ * Give the replacement the replaced file's owner (`rename` swaps the inode). An owner this
204
+ * process may not restore with `fchown` is refused as `unsupported-target` before any write.
205
+ */
206
+ preserveOwner?: boolean;
207
+ /** Refused as `identity-changed` when the target is no longer this file (dev/ino). */
208
+ expectedIdentity?: FileIdentity;
209
+ /** With `expectedIdentity`: also refuse a same-inode rewrite (size or mtime moved). */
210
+ expectUnmodified?: boolean;
211
+ fs?: FsLayer;
212
+ randomName?: () => string;
213
+ }
214
+ interface AtomicReplaceResult {
215
+ identity: FileIdentity;
216
+ /** Whether a file existed at `target` before. */
217
+ replaced: boolean;
218
+ }
219
+ /**
220
+ * Replace or create `target` in one `rename` from a same-directory temp file. The `lstat`→`rename`
221
+ * window is accepted: `rename` never follows a link and nothing before it creates through one.
222
+ */
223
+ declare function atomicReplace(target: string, bytes: Uint8Array, options?: AtomicReplaceOptions): AtomicReplaceResult;
224
+ /** `lstat` a replace target under the policy of {@link atomicReplace}; null when absent. */
225
+ declare function inspectReplaceTarget(target: string, fs?: FsLayer): FileIdentity | null;
226
+
227
+ /** Reference as the resumed document wrote it → absolute path beside that document. Session state only. */
228
+ type AttachmentOrigins = ReadonlyMap<string, string>;
229
+ type AttachmentReadFailureReason = 'not-authorized' | 'not-found' | 'not-regular' | 'unsafe-link' | 'too-large' | 'io-error';
230
+ type AttachmentReadResult = {
231
+ ok: true;
232
+ data: ArrayBuffer;
233
+ } | {
234
+ ok: false;
235
+ reason: AttachmentReadFailureReason;
236
+ message: string;
237
+ };
238
+ /** The bare name in `.self-review-assets/<name>`; null for any other shape. */
239
+ declare function parseAttachmentReference(reference: unknown): string | null;
240
+ /** Origins resolve against the resumed document's directory; an unrecorded reference is never read. */
241
+ declare function resolveAttachmentOrigins(comments: readonly ReviewComment[], resumeDocumentPath: string): {
242
+ origins: Map<string, string>;
243
+ diagnostics: string[];
244
+ };
245
+ /** Read one asset the caller authorized: the asset directory must not be a link, nor the leaf. */
246
+ declare function readAssetFile(assetPath: string): Promise<AttachmentReadResult>;
247
+ /** The recorded origin of an imported reference, else the same name in `currentAssetDir`. */
248
+ declare function authorizeAttachmentReference(reference: unknown, origins: AttachmentOrigins, currentAssetDir: string | null): string | null;
249
+ declare class AttachmentRelocationError extends Error {
250
+ readonly reference: string;
251
+ readonly origin: string;
252
+ readonly reason: AttachmentReadFailureReason;
253
+ constructor(reference: string, origin: string, reason: AttachmentReadFailureReason, detail: string);
254
+ }
255
+ /**
256
+ * Give every imported attachment whose origin is not beside `outputPath` its bytes, so the
257
+ * publisher stages a copy. Unreadable ones throw: the old reference would resolve to the wrong file.
258
+ */
259
+ declare function relocateAttachments(state: ReviewState, origins: AttachmentOrigins, outputPath: string): Promise<ReviewState>;
260
+
261
+ type ReviewPublishErrorCode =
262
+ /** `details` lists each XSD violation. */
263
+ 'validation-failed' | 'xml-illegal-character' | 'output-is-directory' | 'permission-denied' | 'no-space'
264
+ /** A link where the publisher would write, or an inherited path resolving outside its base. */
265
+ | 'unsafe-link'
266
+ /** A hard-linked output, or a non-directory or foreign-owned asset directory. */
267
+ | 'unsupported-target'
268
+ /** A resumed attachment that must move cannot be read where its document put it. */
269
+ | 'attachment-unavailable' | 'io-error';
270
+ declare class ReviewPublishError extends Error {
271
+ readonly code: ReviewPublishErrorCode;
272
+ readonly path: string;
273
+ /** One rendered line per problem; empty when the message is all there is. */
274
+ readonly details: readonly string[];
275
+ readonly cause?: unknown;
276
+ constructor(code: ReviewPublishErrorCode, path: string, message: string, options?: {
277
+ details?: readonly string[];
278
+ cause?: unknown;
279
+ });
280
+ }
281
+ /** `inherited` paths come from something a repository can commit, so they must stay inside `baseDir`. */
282
+ type ReviewOutputOrigin = 'explicit' | 'inherited';
283
+ /** Resolved by `resolveOutputTarget` in `startup.ts`. */
284
+ type ReviewOutputTarget = {
285
+ path: string;
286
+ origin: 'explicit';
287
+ } | {
288
+ path: string;
289
+ origin: 'inherited';
290
+ baseDir: string;
291
+ };
292
+ interface PublishReviewCommonOptions {
293
+ fs?: FsLayer;
294
+ randomName?: () => string;
295
+ /** Imported attachments whose origin is elsewhere are copied beside the output (`relocateAttachments`). */
296
+ attachmentOrigins?: AttachmentOrigins;
297
+ }
298
+ type PublishReviewOptions = PublishReviewCommonOptions & ({
299
+ outputOrigin: 'explicit';
300
+ } | {
301
+ outputOrigin: 'inherited';
302
+ baseDir: string;
303
+ });
304
+ interface PublishReviewResult {
305
+ outputPath: string;
306
+ /** The attachment files this publication created. */
307
+ assetPaths: string[];
308
+ }
309
+ /** @throws ReviewPublishError for every failure, document or filesystem. */
310
+ declare function publishReview(state: ReviewState, outputPath: string, options: PublishReviewOptions): Promise<PublishReviewResult>;
311
+ /** The error `publishReview` would throw for the path as it stands; advisory, since the disk can change. */
312
+ declare function inspectOutputPath(outputPath: string, options: PublishReviewOptions): ReviewPublishError | null;
313
+
314
+ type AnchorSide = 'old' | 'new';
315
+ interface LineAnchor {
316
+ side: AnchorSide;
317
+ start: number;
318
+ end: number;
319
+ }
320
+ type AnchorCheck = {
321
+ ok: true;
322
+ anchor: LineAnchor;
323
+ } | {
324
+ ok: false;
325
+ reason: string;
326
+ };
327
+ /** The four raw line fields; `unknown` because XML gives strings and JSON gives anything. */
328
+ interface AnchorFields {
329
+ oldLineStart?: unknown;
330
+ oldLineEnd?: unknown;
331
+ newLineStart?: unknown;
332
+ newLineEnd?: unknown;
333
+ }
334
+ /**
335
+ * Returns `null` when no field is present (a file-level comment), else the first
336
+ * rule broken: positive safe integers (digit strings accepted), exactly one
337
+ * complete side, start <= end, end <= `maxLine`. `reason` is embedded in diagnostics.
338
+ */
339
+ declare function validateLineAnchor(fields: AnchorFields, maxLine?: number): AnchorCheck | null;
340
+ /**
341
+ * Same rules as {@link validateLineAnchor} for a typed range; `NaN`, `0`, `1.5` and `Infinity` are
342
+ * still numbers.
343
+ */
344
+ declare function validateLineRange(range: LineRange, maxLine?: number): AnchorCheck;
345
+
22
346
  declare const GUIDE_XSD_SCHEMA = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sg=\"urn:self-review-guide:v1\"\n targetNamespace=\"urn:self-review-guide:v1\"\n elementFormDefault=\"qualified\"\n>\n\n <!--\n self-review guide XML Schema v1\n ===============================\n Defines the walkthrough guide sidecar for the self-review application.\n This schema is designed to be both machine-validated and fed to an LLM\n so it can author valid guide documents from the schema alone.\n\n Key concepts:\n - A <guide> is a read-only orientation aid generated BEFORE a review\n starts. It lives next to the review output file and is discovered by\n convention; it is never written by the review UI.\n - The optional <overview> is short Markdown prose shown before the\n first file, orienting the reviewer to the change as a whole.\n - Each <group> names a set of files that belong together (for example\n \"Core change\", \"Tests\", \"Generated/mechanical\") and explains, in one\n line, why they are grouped and where they sit in the reading order.\n - Each <file> inside a group points at one diff file by its\n repository-relative path and carries a one-line description of the\n role that file plays in the change.\n\n Ordering:\n - Document order IS the reading order. Groups are presented in the\n order they appear, and files within a group are presented in the\n order they appear. There are no explicit ordering attributes; to\n reorder, reorder the elements.\n\n Presentation only, never suppression:\n - This vocabulary labels and orders content; it cannot hide it. There\n is deliberately no element or attribute that hides, collapses, or\n marks a file as skippable, and none may be added to v1. Files in the\n diff that no group mentions remain fully visible in an implicit\n \"Everything else\" group; files mentioned here but absent from the\n diff are silently ignored.\n\n Tolerance:\n - A missing, stale, or invalid guide degrades the consumer to its\n normal ungrouped view. A guide can therefore never block or fail a\n review, but an invalid guide is silently useless, so authors should\n validate against this schema before writing the file.\n -->\n\n <!-- ===== Root element ===== -->\n\n <xs:element name=\"guide\" type=\"sg:GuideType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review walkthrough guide sidecar. Contains\n an optional overview followed by zero or more ordered groups.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <!-- ===== Complex types ===== -->\n\n <xs:complexType name=\"GuideType\">\n <xs:annotation>\n <xs:documentation>\n The whole walkthrough guide. The optional metadata attributes\n mirror the review schema's provenance attributes so a consumer can\n sanity-check that the guide was generated for the diff it is being\n shown next to; none of them are required and none affect\n presentation.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"overview\" type=\"xs:string\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Review-level orientation prose shown before the first file.\n Markdown formatting is allowed, including fenced code blocks;\n a fenced code block labelled \"mermaid\" may be used for a\n diagram of the change.\n Keep it short: a few sentences saying what the change does and\n where to start reading, not a restatement of every file.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"group\" type=\"sg:GroupType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Ordered reading groups. The first group should hold the files\n the reviewer must understand first (the core of the change);\n later groups hold consequences, tests, and mechanical fallout.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the guide was generated.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments the guide was generated against.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when the guide describes a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root the guide was generated in.\n Present only when the guide describes a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"GroupType\">\n <xs:annotation>\n <xs:documentation>\n A named set of related files with a one-line rationale. Groups are\n labels for orientation, never suppressions: a consumer shows every\n group and every file in it. Position in the document is position\n in the reading order.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"rationale\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n One line explaining why these files form a group and what the\n reviewer should look for in them (e.g., \"The retry wrapper\n everything else calls; read this first\"). Plain text, a single\n sentence; no Markdown, no line breaks.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"file\" type=\"sg:FileEntryType\" minOccurs=\"1\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n The files in this group, in reading order. A group must list\n at least one file; do not author empty placeholder groups.\n Every file in the diff may appear in at most one group, and\n files omitted from every group are not hidden \u2014 the consumer\n shows them in an implicit trailing \"Everything else\" group.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Short display name for the group, e.g. \"Core change\", \"Tests\",\n \"Generated/mechanical\". Shown as the group heading in the file\n tree; keep it to a few words.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileEntryType\">\n <xs:annotation>\n <xs:documentation>\n One file in a group. The path must match a file in the diff being\n reviewed; entries whose path matches nothing in the diff are\n silently dropped by the consumer, so a stale guide degrades\n instead of erroring.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"description\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n One line describing the role this file plays in the change\n (e.g., \"Adds the retry wrapper that everything else calls\").\n Plain text, a single sentence; no Markdown, no line breaks.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root, using the same\n convention as review.xml file paths. For renamed files, use the\n new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n</xs:schema>";
23
347
 
24
348
  /** Display name given to the derived trailing group of unmentioned files. */
@@ -54,22 +378,97 @@ declare function parseGuideXml(xmlContent: string): Promise<GuideParseResult>;
54
378
  */
55
379
  declare function reconcileGuide(guide: ReviewGuide, diffFilePaths: string[]): ResolvedGuideGroup[];
56
380
 
57
- declare function runGitDiff(args: string[]): string;
58
- declare function getRepoRoot(): string;
59
381
  /**
60
- * Lightweight sync validation - checks if git is available and we're in a repo.
61
- * Called BEFORE Electron initialization for early exit path.
382
+ * Entries one directory walk (or untracked-file listing) may examine; ignored directories are
383
+ * pruned first.
384
+ */
385
+ declare const MAX_SOURCE_ENTRIES = 50000;
386
+ /** Prefix sampled for a NUL byte to decide a file is binary. */
387
+ declare const BINARY_SNIFF_BYTES: number;
388
+ /**
389
+ * Largest text file read into a synthetic diff; a larger one is listed without content and named in
390
+ * a diagnostic.
62
391
  */
63
- declare function validateGitAvailable(): void;
392
+ declare const MAX_SOURCE_FILE_BYTES: number;
393
+ /** Total bytes one synthetic-diff build may read, binary sniffs included. */
394
+ declare const MAX_SOURCE_TOTAL_BYTES: number;
395
+ /** Most bytes of `git diff` output captured from one invocation (the child process `maxBuffer`). */
396
+ declare const MAX_GIT_DIFF_OUTPUT_BYTES: number;
397
+ /** Largest guide sidecar the loader will read. */
398
+ declare const MAX_GUIDE_BYTES: number;
399
+ /**
400
+ * Largest review document `--resume-from` will read (text and attachment references, never bytes).
401
+ */
402
+ declare const MAX_RESUME_XML_BYTES: number;
403
+ /** Most attachment references one resumed document may carry; bounds the reads it can ask for. */
404
+ declare const MAX_RESUME_ATTACHMENTS = 1000;
405
+ /** Largest image read for a rendered preview or a comment attachment. */
406
+ declare const MAX_IMAGE_BYTES: number;
407
+ /**
408
+ * The source-loading budgets as one value; overrides are for tests and embedders, never user
409
+ * config.
410
+ */
411
+ interface SourceBudgets {
412
+ maxEntries: number;
413
+ maxFileBytes: number;
414
+ maxTotalBytes: number;
415
+ maxGitDiffOutputBytes: number;
416
+ }
417
+ declare const DEFAULT_SOURCE_BUDGETS: Readonly<SourceBudgets>;
418
+ declare function resolveSourceBudgets(overrides?: Partial<SourceBudgets>): SourceBudgets;
419
+ /** `5 MiB`, `7.3 MiB`, `812 KiB`, `100 bytes`. */
420
+ declare function formatBytes(bytes: number): string;
421
+
422
+ interface SyntheticDiffOptions {
423
+ /**
424
+ * Only for a path the reviewer named explicitly (single-file review); enumerated paths never
425
+ * follow links.
426
+ */
427
+ followSymlinks?: boolean;
428
+ budgets?: Partial<SourceBudgets>;
429
+ }
430
+ interface SyntheticDiffResult {
431
+ diff: string;
432
+ /**
433
+ * Files listed without content, by literal relative path, with the sentence the viewer shows
434
+ * instead.
435
+ */
436
+ omitted: Map<string, string>;
437
+ diagnostics: string[];
438
+ }
64
439
  /**
65
- * Async version of getRepoRoot - called AFTER app.whenReady().
440
+ * Generate synthetic unified diffs for a list of file paths so they can be
441
+ * parsed by the existing diff parser. Each file is treated as a new addition.
442
+ *
443
+ * @param paths - Literal relative file paths (e.g. "src/foo.ts"), resolved
444
+ * against rootDir and never git-quoted on the way in
445
+ * @param rootDir - Absolute path to the root directory the paths are relative to
446
+ * @returns The diff text, the files listed without content, and diagnostics
66
447
  */
448
+ declare function generateSyntheticDiffs(paths: string[], rootDir: string, options?: SyntheticDiffOptions): SyntheticDiffResult;
449
+ /** Builds and parses in one step, setting `omittedReason` on files listed without content. */
450
+ declare function loadSyntheticFiles(paths: string[], rootDir: string, options?: SyntheticDiffOptions): {
451
+ files: DiffFile[];
452
+ diagnostics: string[];
453
+ };
454
+
455
+ /** Rejects when git is missing or `cwd` is not inside a repository. */
67
456
  declare function getRepoRootAsync(cwd?: string): Promise<string>;
68
457
  /**
69
- * Async version of runGitDiff - called AFTER app.whenReady().
70
- * Uses timeout to prevent hanging in CI environments.
458
+ * Config overrides, placed before `diff`, that keep output parseable whatever the user's config
459
+ * says.
460
+ */
461
+ declare const PARSER_COMPATIBLE_GIT_CONFIG: readonly string[];
462
+ /** Appended after the user's options so a user `--color=always` or `--no-prefix` loses. */
463
+ declare const PARSER_COMPATIBLE_DIFF_FLAGS: readonly string[];
464
+ /** Inserts the flags after every user option and before `--`. */
465
+ declare function withParserCompatibleDiffArgs(args: readonly string[]): string[];
466
+ /**
467
+ * The one entry point for every `git diff` (load, expansion, remote), so the
468
+ * parser-compatible normalization applies uniformly. Output past `maxOutputBytes`
469
+ * rejects with an error {@link isOutputLimitError} recognizes.
71
470
  */
72
- declare function runGitDiffAsync(args: string[], cwd?: string): Promise<string>;
471
+ declare function runGitDiffAsync(args: string[], cwd?: string, maxOutputBytes?: number): Promise<string>;
73
472
  /**
74
473
  * Get list of untracked files (respects .gitignore).
75
474
  *
@@ -86,11 +485,10 @@ declare function runGitDiffAsync(args: string[], cwd?: string): Promise<string>;
86
485
  declare function getUntrackedFilesAsync(repoRoot?: string): Promise<string[]>;
87
486
  /**
88
487
  * Generate synthetic unified diffs for untracked files so they can be
89
- * parsed by the existing diff parser.
90
- *
91
- * Delegates to the reusable generateSyntheticDiffs module.
488
+ * parsed by the existing diff parser. Untracked symlinks are described by
489
+ * their link text, never followed.
92
490
  */
93
- declare function generateUntrackedDiffs(paths: string[], repoRoot: string): string;
491
+ declare function generateUntrackedDiffs(paths: string[], repoRoot: string, options?: SyntheticDiffOptions): SyntheticDiffResult;
94
492
 
95
493
  /** Forges the app knows how to talk to. */
96
494
  type ForgeName = 'github' | 'gitlab';
@@ -126,16 +524,23 @@ type ForgeAnchorSide = 'old' | 'new';
126
524
  * - `startLine`/`endLine` are `null` when the forge supplies a file path but
127
525
  * no usable line information (the mapper degrades to a file-level comment;
128
526
  * `side` is meaningless in that case and providers should set `'new'`).
129
- * - `outdated: true` means the forge reports the anchor no longer applies to
130
- * the current head (e.g. GitHub outdated review comments); the line fields
131
- * then hold the historic anchor and the mapper degrades to file-level.
527
+ *
528
+ * Revision provenance (the mapper compares it with the reviewed head; providers
529
+ * report only what the forge told them):
530
+ * - `headSha`: head commit the line numbers were computed against, when the
531
+ * forge reports one per note (GitLab). A suggestion activates only on a match.
532
+ * - `outdated`: the forge's own per-note verdict (GitHub `line: null`). `true`
533
+ * degrades to file-level; `false` vouches for the anchor when no `headSha` exists.
534
+ *
535
+ * An anchor carrying neither is unverifiable: it never activates a suggestion.
132
536
  */
133
537
  interface ForgeThreadAnchor {
134
538
  filePath: string;
135
539
  side: ForgeAnchorSide;
136
540
  startLine: number | null;
137
541
  endLine: number | null;
138
- outdated: boolean;
542
+ headSha?: string;
543
+ outdated?: boolean;
139
544
  }
140
545
  /** One turn (root comment or reply) in a forge discussion thread. */
141
546
  interface ForgeThreadTurn {
@@ -177,12 +582,34 @@ interface ForgeCommandResult {
177
582
  exitCode: number;
178
583
  }
179
584
  /**
180
- * Injectable command runner used by provider implementations, mirroring how
181
- * `git.ts` keeps child-process execution testable. Resolves with the exit
182
- * code on any completed run (including non-zero); rejects only when the
183
- * binary cannot be spawned at all (e.g. ENOENT when the CLI is absent).
585
+ * Optional lifetime bounds; either one kills the child and rejects with {@link
586
+ * CommandCancelledError}.
587
+ */
588
+ interface ForgeCommandOptions {
589
+ signal?: AbortSignal;
590
+ timeoutMs?: number;
591
+ }
592
+ /**
593
+ * Injectable command runner for providers and the materializer. Resolves with
594
+ * the exit code on any completed run; rejects when the binary cannot be spawned
595
+ * and, with a {@link CommandCancelledError}, when cut short by `options`.
596
+ */
597
+ type ForgeCommandRunner = (command: string, args: string[], options?: ForgeCommandOptions) => Promise<ForgeCommandResult>;
598
+ /** Why a command run was cut short. */
599
+ type CommandCancelReason = 'aborted' | 'timeout';
600
+ /**
601
+ * A run ended by its caller's bounds (abort or timeout) after the child was
602
+ * killed. Providers must not fold it into {@link ForgeCliUnavailableError}: a
603
+ * session being torn down must not degrade into a review without threads.
184
604
  */
185
- type ForgeCommandRunner = (command: string, args: string[]) => Promise<ForgeCommandResult>;
605
+ declare class CommandCancelledError extends Error {
606
+ readonly reason: CommandCancelReason;
607
+ readonly command: string;
608
+ readonly args: readonly string[];
609
+ constructor(reason: CommandCancelReason, command: string, args: readonly string[]);
610
+ }
611
+ /** Matches by name too, so it works across module instances. */
612
+ declare function isCommandCancelled(error: unknown): error is CommandCancelledError;
186
613
  /**
187
614
  * The conversation plane of a forge. Exactly two capabilities: base-branch
188
615
  * lookup and discussion-thread fetching. No diff fetching, no blob fetching,
@@ -215,35 +642,164 @@ declare class ForgeCliUnavailableError extends Error {
215
642
  */
216
643
  declare function parseForgeUrl(url: string): ForgeUrl | null;
217
644
 
645
+ interface SourceScanOptions {
646
+ budgets?: Partial<SourceBudgets>;
647
+ }
648
+ interface SourceScanResult {
649
+ files: DiffFile[];
650
+ /** For `DiffLoadPayload.diagnostics`; empty for a clean scan. */
651
+ diagnostics: string[];
652
+ /** `files` is empty when this is true. */
653
+ entryLimitExceeded: boolean;
654
+ }
218
655
  /**
219
- * Generate synthetic unified diffs for a list of file paths so they can be
220
- * parsed by the existing diff parser. Each file is treated as a new addition.
221
- *
222
- * @param paths - Literal relative file paths (e.g. "src/foo.ts"), resolved
223
- * against rootDir and never git-quoted on the way in
224
- * @param rootDir - Absolute path to the root directory the paths are relative to
225
- * @returns A unified diff string covering all provided files
656
+ * Recursively scans `directoryPath`; a directory matching `ignorePatterns` is pruned without being
657
+ * opened.
658
+ */
659
+ declare function scanDirectory(directoryPath: string, ignorePatterns?: string[], options?: SourceScanOptions): Promise<SourceScanResult>;
660
+ /**
661
+ * The reviewer named this path explicitly, so a symlink is read through; the per-file budget still
662
+ * applies.
226
663
  */
227
- declare function generateSyntheticDiffs(paths: string[], rootDir: string): string;
664
+ declare function scanFile(filePath: string, options?: SourceScanOptions): Promise<SourceScanResult>;
665
+
666
+ /** Filesystem errors (ENOENT, EACCES, ...) throw. */
667
+ type BoundedReadResult = {
668
+ kind: 'ok';
669
+ content: Buffer;
670
+ } | {
671
+ kind: 'too-large';
672
+ size: number;
673
+ }
674
+ /** A directory, FIFO, socket or device: nothing was read. */
675
+ | {
676
+ kind: 'not-regular';
677
+ };
678
+ interface BoundedReadOptions {
679
+ /** Covers the leaf only; ancestors are the caller's job (`openContainedFile`). */
680
+ noFollow?: boolean;
681
+ }
682
+ declare function readFileWithinBudget(path: string, maxBytes: number, options?: BoundedReadOptions): Promise<BoundedReadResult>;
683
+ declare function readFileWithinBudgetSync(path: string, maxBytes: number, options?: BoundedReadOptions): BoundedReadResult;
228
684
 
685
+ /** One side as the arguments describe it, before resolution; `implicit` is the HEAD git assumes. */
686
+ type GitDiffSideSpec = {
687
+ kind: 'working-tree';
688
+ } | {
689
+ kind: 'index';
690
+ } | {
691
+ kind: 'revision';
692
+ rev: string;
693
+ implicit: boolean;
694
+ } | {
695
+ kind: 'merge-base';
696
+ left: string;
697
+ right: string;
698
+ } | {
699
+ kind: 'unknown';
700
+ reason: string;
701
+ };
702
+ interface GitDiffSides {
703
+ oldSide: GitDiffSideSpec;
704
+ newSide: GitDiffSideSpec;
705
+ }
229
706
  /**
230
- * Recursively scan a directory and return DiffFile[] with every file
231
- * treated as a new addition (changeType: 'added').
232
- *
233
- * @param directoryPath - Absolute path to the directory to scan
234
- * @param ignorePatterns - Optional gitignore-compatible patterns to exclude files
235
- * @returns Parsed DiffFile array for all files in the directory
707
+ * The two snapshots a `git diff` argv compares. Pure: runs no git and checks no revision.
708
+ * Uses the classifier's arity rules, so `-S --cached` is not a flag. `--no-index`, three
709
+ * or more revisions and `--cached` with a range are `unknown`.
236
710
  */
237
- declare function scanDirectory(directoryPath: string, ignorePatterns?: string[]): Promise<DiffFile[]>;
711
+ declare function describeGitDiffSides(argv: readonly string[]): GitDiffSides;
712
+ declare function canonicalSourcePath(target: string): string;
238
713
  /**
239
- * Scan a single file and return DiffFile[] with the file treated as a new addition.
240
- *
241
- * @param filePath - Absolute path to the file to scan
242
- * @returns Parsed DiffFile array (single element)
714
+ * `ReviewSourceIdentity.pathPrefix`: empty for root-relative output, the
715
+ * `--relative=<dir>` directory without trailing slashes, or for bare `--relative`
716
+ * the launch directory under the root (empty when outside the work tree, as in git).
717
+ */
718
+ declare function resolveReviewedPathPrefix(gitDiffArgv: readonly string[], sourceRoot: string, invocationCwd: string): string;
719
+ /** The one mapping every reader, Apply and re-diff uses, so they all name the same file. */
720
+ declare function rootRelativeReviewedPath(identity: Pick<ReviewSourceIdentity, 'pathPrefix'>, filePath: string): string;
721
+ interface GitSourceIdentityOptions {
722
+ repository: string;
723
+ gitDiffArgv: readonly string[];
724
+ /** Defaults to the process's working directory. */
725
+ invocationCwd?: string;
726
+ /** `'remote'` for a materialized PR/MR; the git-mode machinery is the same. */
727
+ mode?: 'git' | 'remote';
728
+ }
729
+ /** Resolves the compared sides to commit SHAs. Never throws; an unresolvable side is `unknown`. */
730
+ declare function resolveGitSourceIdentity(options: GitSourceIdentityOptions): Promise<ReviewSourceIdentity>;
731
+ interface LocalSourceIdentityOptions {
732
+ type: 'directory' | 'file';
733
+ sourcePath: string;
734
+ /** Defaults to the process's working directory. */
735
+ invocationCwd?: string;
736
+ }
737
+ /**
738
+ * Everything is an addition, so the old side is `none`. A single-file review follows a
739
+ * symlink the user named, recording its target once; its root is the parent of the path as given.
243
740
  */
244
- declare function scanFile(filePath: string): Promise<DiffFile[]>;
741
+ declare function resolveLocalSourceIdentity(options: LocalSourceIdentityOptions): ReviewSourceIdentity;
742
+
743
+ interface ReviewedSnapshot {
744
+ sourceIdentity: ReviewSourceIdentity | null;
745
+ reviewedPaths: ReadonlySet<string>;
746
+ }
747
+ type ReviewedPathRefusal = 'no-source' | 'not-reviewed'
748
+ /** Absolute, empty, or leaving the source root. */
749
+ | 'invalid-path';
750
+ type ReviewedPathAuthorization = {
751
+ ok: true;
752
+ /** Restated from `sourceRoot` through the identity's prefix, normalized. */
753
+ relativePath: string;
754
+ sourceRoot: string;
755
+ } | {
756
+ ok: false;
757
+ reason: ReviewedPathRefusal;
758
+ message: string;
759
+ };
760
+ /** The one path check every front end delegates to; what passes is exactly what the readers open. */
761
+ declare function authorizeReviewedPath(source: ReviewedSnapshot, filePath: string): ReviewedPathAuthorization;
762
+ type SnapshotReadFailure = ReviewedPathRefusal
763
+ /** The side has no content (`none`) or could not be identified (`unknown`). */
764
+ | 'side-unavailable' | 'not-found'
765
+ /** A directory, FIFO, socket or device. */
766
+ | 'not-regular' | 'unsafe-link' | 'too-large' | 'read-failed';
767
+ type SnapshotReadResult = {
768
+ ok: true;
769
+ content: Buffer;
770
+ } | {
771
+ ok: false;
772
+ reason: SnapshotReadFailure;
773
+ message: string;
774
+ };
775
+ interface SnapshotReadOptions {
776
+ /** Defaults to `MAX_SOURCE_FILE_BYTES`. */
777
+ maxBytes?: number;
778
+ }
779
+ /** A blob from the object store, or the file under the physical source root; authorized first. */
780
+ declare function readReviewedContent(source: ReviewedSnapshot, filePath: string, side: 'old' | 'new', options?: SnapshotReadOptions): Promise<SnapshotReadResult>;
245
781
 
246
- declare function loadConfig(): AppConfig;
782
+ /**
783
+ * `project` config is repository data and is trusted less than the reviewer's own `user` config.
784
+ */
785
+ type ConfigValueOrigin = 'default' | 'user' | 'project';
786
+ type ConfigProvenance = Readonly<Record<keyof AppConfig, ConfigValueOrigin>>;
787
+ interface ConfigSource {
788
+ origin: 'user' | 'project';
789
+ path: string;
790
+ }
791
+ interface LoadedConfig {
792
+ config: AppConfig;
793
+ provenance: ConfigProvenance;
794
+ sources: ConfigSource[];
795
+ }
796
+ interface LoadConfigOptions {
797
+ cwd?: string;
798
+ homeDir?: string;
799
+ }
800
+ /** Project overrides user overrides defaults; an invalid value is not attributed to its file. */
801
+ declare function loadConfigWithProvenance(options?: LoadConfigOptions): LoadedConfig;
802
+ declare function loadConfig(options?: LoadConfigOptions): AppConfig;
247
803
 
248
804
  /**
249
805
  * Compute payload statistics and check against configured thresholds.
@@ -293,10 +849,16 @@ type ApplyRefusalReason =
293
849
  * target is undefined rather than merely missing.
294
850
  */
295
851
  | 'old-side-anchor'
852
+ /** Unknown side, non-positive or non-integer bounds, or reversed; checked before any I/O. */
853
+ | 'invalid-anchor'
296
854
  /** `destinationRoot` is relative; resolving it would consult the cwd. */
297
- | 'destination-not-absolute'
855
+ | 'destination-not-absolute' | 'destination-missing'
298
856
  /** `filePath` resolves outside `destinationRoot`. */
299
- | 'path-escapes-destination'
857
+ | 'path-escapes-destination' | 'control-file'
858
+ /** A link on the way or at the leaf, a hard-linked or special file, or a swap during the open. */
859
+ | 'unsafe-target'
860
+ /** Replacing the file would change its owner, which this process cannot restore. */
861
+ | 'unsupported-target'
300
862
  /** No file at the resolved path. */
301
863
  | 'file-missing'
302
864
  /** The path exists but could not be read (permissions, a directory, …). */
@@ -310,6 +872,8 @@ type ApplyRefusalReason =
310
872
  | 'anchor-out-of-range'
311
873
  /** The anchored lines no longer match `suggestion.originalCode`. */
312
874
  | 'context-mismatch'
875
+ /** The file was replaced or rewritten between the read and the commit. */
876
+ | 'file-changed'
313
877
  /** The context matched but the write itself failed. */
314
878
  | 'write-failed';
315
879
  interface ApplySuggestionRequest {
@@ -326,6 +890,10 @@ interface ApplySuggestionRequest {
326
890
  lineRange: LineRange | null;
327
891
  suggestion: Suggestion;
328
892
  }
893
+ interface ApplySuggestionOptions {
894
+ fs?: FsLayer;
895
+ randomName?: () => string;
896
+ }
329
897
  interface ApplySuggestionApplied {
330
898
  status: 'applied';
331
899
  /** Echoed from the request, so a batch caller can attribute the result. */
@@ -342,6 +910,11 @@ interface ApplySuggestionRefused {
342
910
  detail: string;
343
911
  }
344
912
  type ApplySuggestionResult = ApplySuggestionApplied | ApplySuggestionRefused;
913
+ /**
914
+ * A `.git` segment at any depth, directory or worktree file: git executes what is in there. `.gitmodules`
915
+ * and the like are reviewed content, gated by diff membership in the session handler instead.
916
+ */
917
+ declare function isRepositoryControlPath(filePath: string): boolean;
345
918
  /**
346
919
  * Apply one anchored suggestion to one file under `destinationRoot`.
347
920
  *
@@ -352,7 +925,7 @@ type ApplySuggestionResult = ApplySuggestionApplied | ApplySuggestionRefused;
352
925
  * file's trailing-newline state is preserved either way. Any other outcome
353
926
  * refuses with a reason and writes nothing.
354
927
  */
355
- declare function applySuggestion(request: ApplySuggestionRequest): ApplySuggestionResult;
928
+ declare function applySuggestion(request: ApplySuggestionRequest, options?: ApplySuggestionOptions): ApplySuggestionResult;
356
929
 
357
930
  /**
358
931
  * File-type detection utilities.
@@ -405,13 +978,17 @@ declare const REVIEW_LEVEL_FILE_PATH = "";
405
978
  * `category` matches how the XML parser represents a missing category.
406
979
  * - A root body carrying a single ` ```suggestion ` fence becomes a
407
980
  * `Suggestion` anchored to the thread's line range, with `originalCode`
408
- * read out of `diffFiles` at that anchor. Without the reviewed diff there
409
- * is nothing to anchor against, so the default leaves every
410
- * `suggestion: null` exactly as before.
981
+ * read out of `diffFiles` at that anchor, only when the anchor is verified
982
+ * (see {@link AnchorStatus}). Without the diff, every `suggestion` is `null`.
983
+ * - An anchor naming a head other than `reviewedHeadSha` is outdated and
984
+ * degrades to file-level; its body is intact.
985
+ *
986
+ * `reviewedHeadSha` is the head `diffFiles` was taken against; omitted, every
987
+ * revision-naming anchor is unverified.
411
988
  *
412
989
  * Output order is input order. The input is never mutated.
413
990
  */
414
- declare function mapThreadsToReviewComments(threads: ForgeThread[], diffFiles?: DiffFile[]): ReviewComment[];
991
+ declare function mapThreadsToReviewComments(threads: ForgeThread[], diffFiles?: DiffFile[], reviewedHeadSha?: string): ReviewComment[];
415
992
 
416
993
  /**
417
994
  * Create the GitLab {@link ForgeProvider} backed by the `glab` CLI.
@@ -434,43 +1011,64 @@ interface MaterializeResult {
434
1011
  headSha: string;
435
1012
  mode: MaterializeMode;
436
1013
  /**
437
- * Removes the temp clone directory when one was created this run; a no-op
438
- * for the existing-clone mode. Safe to call more than once. Only ever
439
- * deletes a directory this materializer created.
1014
+ * Refs this session created in a reused clone and deletes on cleanup; empty for a temp clone.
440
1015
  */
441
- cleanup: () => void;
1016
+ ownedRefs: readonly string[];
1017
+ /**
1018
+ * Removes the temp clone (synchronously, before the first await, so an `exit`
1019
+ * handler that cannot wait still gets that far) and deletes the session's refs
1020
+ * from a reused clone. Idempotent, never rejects; a failed deletion goes to stderr.
1021
+ */
1022
+ cleanup: () => Promise<void>;
442
1023
  }
443
1024
  /** A local clone whose fetch remote matches the requested forge repository. */
444
1025
  interface ExistingClone {
445
1026
  repoPath: string;
446
1027
  remoteName: string;
447
1028
  }
1029
+ interface MaterializeOptions {
1030
+ /**
1031
+ * Aborting kills the command in flight and rejects with {@link CommandCancelledError}; the temp
1032
+ * clone is removed first.
1033
+ */
1034
+ signal?: AbortSignal;
1035
+ /** Defaults to {@link DEFAULT_GIT_COMMAND_TIMEOUT_MS}. */
1036
+ commandTimeoutMs?: number;
1037
+ }
1038
+ /**
1039
+ * Generous because a blobless clone over a slow link is legitimately slow; tighter hosts abort via
1040
+ * the signal.
1041
+ */
1042
+ declare const DEFAULT_GIT_COMMAND_TIMEOUT_MS: number;
448
1043
  /**
449
- * Default runner: spawns real git. Resolves with the exit code on any
450
- * completed run (including non-zero); rejects only when git cannot be
451
- * spawned at all (e.g. ENOENT).
1044
+ * Default runner: spawns the real binary. Rejects on spawn failure, on output over
1045
+ * the buffer cap, and with {@link CommandCancelledError} on abort or timeout (SIGTERM,
1046
+ * then SIGKILL after {@link KILL_GRACE_MS}; settles once the child exited).
1047
+ *
1048
+ * Deliberately not in its own process group: that would detach the controlling
1049
+ * terminal and silently disable git's and ssh's credential prompts.
452
1050
  */
453
1051
  declare const defaultGitRunner: ForgeCommandRunner;
454
1052
  /**
455
1053
  * Detect an existing clone: when `cwd` is inside a git repository with a
456
1054
  * remote matching the forge URL, return `{ repoPath, remoteName }`.
457
1055
  */
458
- declare function detectExistingClone(url: ForgeUrl, cwd: string, runner?: ForgeCommandRunner): Promise<ExistingClone | null>;
1056
+ declare function detectExistingClone(url: ForgeUrl, cwd: string, runner?: ForgeCommandRunner, options?: MaterializeOptions): Promise<ExistingClone | null>;
459
1057
  /**
460
1058
  * Materialize a forge PR/MR into a local git context.
461
1059
  *
462
1060
  * When `cwd` is inside a git repository with a remote matching the forge
463
1061
  * URL (SSH and HTTPS forms recognized, `.git` suffix tolerated), the base
464
1062
  * branch and PR/MR head refs are fetched into that clone under
465
- * `refs/self-review/*` — read-only for the working tree. Otherwise a
466
- * blobless clone is created in a unique directory under the OS temp root
467
- * and `cleanup()` removes exactly that directory. Callers that already
468
- * detected a clone may pass it to avoid repeating the git probes.
1063
+ * `refs/self-review/<session>/` (read-only for the working tree; `cleanup()`
1064
+ * deletes exactly those two refs). Otherwise a blobless clone is created in a
1065
+ * unique directory under the OS temp root and `cleanup()` removes it. Callers
1066
+ * that already detected a clone may pass it to skip the git probes.
469
1067
  *
470
1068
  * The returned `headSha` is the live remote head, so callers can compare it
471
1069
  * against a recorded `remote-head-sha` for drift detection.
472
1070
  */
473
- declare function materialize(url: ForgeUrl, baseBranch: string, cwd: string, runner?: ForgeCommandRunner, existingClone?: ExistingClone | null): Promise<MaterializeResult>;
1071
+ declare function materialize(url: ForgeUrl, baseBranch: string, cwd: string, runner?: ForgeCommandRunner, existingClone?: ExistingClone | null, options?: MaterializeOptions): Promise<MaterializeResult>;
474
1072
  /**
475
1073
  * Git-only fallback for the base branch when no forge CLI is available:
476
1074
  * resolves the remote's default branch from its HEAD symref via
@@ -479,7 +1077,7 @@ declare function materialize(url: ForgeUrl, baseBranch: string, cwd: string, run
479
1077
  * and credentials are preserved. Otherwise the forge HTTPS URL is used.
480
1078
  * No forge API involved.
481
1079
  */
482
- declare function resolveRemoteDefaultBranch(url: ForgeUrl, runner?: ForgeCommandRunner, existing?: ExistingClone | null): Promise<string>;
1080
+ declare function resolveRemoteDefaultBranch(url: ForgeUrl, runner?: ForgeCommandRunner, existing?: ExistingClone | null, options?: MaterializeOptions): Promise<string>;
483
1081
 
484
1082
  /**
485
1083
  * The state a single review session owns. One desktop application window is
@@ -494,15 +1092,47 @@ interface ReviewSession {
494
1092
  resumeComments: ReviewComment[];
495
1093
  resumeViewedFiles: string[];
496
1094
  resumeRemoteDrift: RemoteDriftInfo | null;
1095
+ resumeImportDiagnostics: string[];
497
1096
  /**
498
1097
  * Destination directory the user named for this session's applies, or
499
1098
  * null when none has been named. Only a temporary-clone remote review
500
1099
  * needs one; see {@link resolveApplyDestination}.
501
1100
  */
502
1101
  applyDestinationRoot: string | null;
1102
+ /**
1103
+ * Old and new path of every file in the committed diff, frozen by {@link commitDiffData}.
1104
+ * The authorization set for writes; resumed comments, submitted state and placeholder
1105
+ * entries can name other paths and never reach it.
1106
+ */
1107
+ reviewedPaths: ReadonlySet<string>;
1108
+ /**
1109
+ * Recorded by {@link commitDiffData}; null until then (and for welcome), when every read of
1110
+ * reviewed content refuses.
1111
+ */
1112
+ sourceIdentity: ReviewSourceIdentity | null;
1113
+ /**
1114
+ * Resumed reference to absolute path beside *the resumed document*; authorizes reads and tells
1115
+ * the publisher which bytes to carry. Never sent to the front end.
1116
+ */
1117
+ attachmentOrigins: AttachmentOrigins;
503
1118
  }
504
1119
  /** Create an empty session. */
505
1120
  declare function createReviewSession(): ReviewSession;
1121
+ /**
1122
+ * The one place a diff is committed to a session: captures `reviewedPaths` and
1123
+ * records `sourceIdentity`; later `diffData` edits (expanded hunks) leave both alone.
1124
+ * The identity comes from the loader, and is `null` only for a payload that
1125
+ * reviews nothing (welcome), so reads refuse rather than guess a root.
1126
+ */
1127
+ declare function commitDiffData(session: ReviewSession, payload: DiffLoadPayload, identity: ReviewSourceIdentity | null): void;
1128
+ /**
1129
+ * The old side is where a deletion or a rename's old name lives. Null when the diff has no such
1130
+ * file.
1131
+ */
1132
+ declare function locateReviewedFile(session: ReviewSession, filePath: string): {
1133
+ file: DiffFile;
1134
+ side: 'old' | 'new';
1135
+ } | null;
506
1136
  /**
507
1137
  * Prepare a DiffLoadPayload for IPC transmission.
508
1138
  * In large-payload mode, strips hunks from files to reduce initial transfer size.
@@ -518,17 +1148,11 @@ declare function getDiffLoad(session: ReviewSession): {
518
1148
  diff: DiffLoadPayload;
519
1149
  guide: GuideLoadPayload | null;
520
1150
  } | null;
521
- /**
522
- * The directory the session's reviewed paths are relative to, or null when the
523
- * session has no diff yet.
524
- *
525
- * Scanner paths are relative to the reviewed directory, or to the reviewed
526
- * file's parent. Git paths are relative to the repository, which in remote
527
- * mode is the materialized clone.
528
- */
1151
+ /** The read-only source root; {@link resolveApplyDestination} decides where applies write. */
529
1152
  declare function resolveSourceBaseDir(session: ReviewSession): string | null;
530
1153
  /**
531
- * Load a binary image as a base64 data URI for the rendered preview.
1154
+ * Reads from the snapshot the review compared, never the current working tree; only reviewed,
1155
+ * previewable paths are read.
532
1156
  */
533
1157
  declare function loadImage(session: ReviewSession, filePath: string): Promise<ImageLoadResult>;
534
1158
  /**
@@ -569,19 +1193,33 @@ declare function takeReviewState(session: ReviewSession): ReviewState | null;
569
1193
  declare function resolveApplyDestination(session: ReviewSession): string | null;
570
1194
  /**
571
1195
  * Apply one suggestion to the reviewed working file, or refuse and write
572
- * nothing. The engine in `apply-suggestion.ts` does the work; this handler
573
- * only names the destination the session reviews, which the engine never
574
- * derives for itself.
1196
+ * nothing. The engine does the work; this handler names the destination, which
1197
+ * the engine never derives, and authorizes the target.
1198
+ *
1199
+ * Authorization is membership in {@link ReviewSession.reviewedPaths}
1200
+ * (`not-reviewed` otherwise), so a resumed document or a client reaching this
1201
+ * handler cannot name an unreviewed file. The request is not bound to a
1202
+ * comment (the session keeps no registry of live suggestions); the binding is
1203
+ * the anchor plus the engine's byte-exact `originalCode` match.
1204
+ *
1205
+ * The engine gets the path through the identity's prefix, so a `--relative`
1206
+ * review of `sub/` writes `sub/<path>`, never the root's same-named file.
575
1207
  *
576
- * A refusal travels as a value, never as a thrown error. The front end
577
- * renders its `detail` next to the suggestion the attempt came from.
1208
+ * A refusal travels as a value, never a thrown error.
578
1209
  */
579
1210
  declare function applySuggestionForSession(session: ReviewSession, request: SuggestionApplyRequest): SuggestionApplyOutcome;
580
1211
  /**
581
- * Read an attachment file from disk, as an ArrayBuffer the front end can use.
582
- * Returns null when the file cannot be read.
1212
+ * Records that resumed attachments live beside the resumed document, whatever the
1213
+ * launch directory or save location. Returns one diagnostic per reference that is
1214
+ * not `.self-review-assets/<name>` and so will never be read.
583
1215
  */
584
- declare function readAttachment(filePath: string): Promise<ArrayBuffer | null>;
1216
+ declare function recordResumedAttachments(session: ReviewSession, comments: readonly ReviewComment[], resumeDocumentPath: string): string[];
1217
+ /**
1218
+ * Read one attachment by its `.self-review-assets/<name>` reference, never a path:
1219
+ * an imported one from its recorded origin, any other from the current output's asset
1220
+ * directory. Anything else is `not-authorized` and touches nothing.
1221
+ */
1222
+ declare function readAttachment(session: ReviewSession, reference: unknown): Promise<AttachmentReadResult>;
585
1223
  /**
586
1224
  * Resolve the resumed comments, viewed files and remote drift for a session.
587
1225
  * Returns null when there is nothing to resume, so the caller sends nothing
@@ -589,10 +1227,14 @@ declare function readAttachment(filePath: string): Promise<ArrayBuffer | null>;
589
1227
  */
590
1228
  declare function getResumeLoad(session: ReviewSession): ResumeLoadPayload | null;
591
1229
  /**
592
- * Expand the context of a single file by re-running git diff with more context
593
- * lines. The expanded hunks are written back to the session's diff data so a
594
- * later file load on the same session sees them. Returns null when the session
595
- * has no git diff, when nothing parses, or when git fails.
1230
+ * Re-run the review's own git diff over one file with more context, via
1231
+ * {@link singleFileRediffArgs}. Git runs at the source root; a `--relative` review is
1232
+ * restated with the prefix resolved at load time, and the file's paths (both, for a
1233
+ * rename or copy, so git pairs them) are root-relative literal pathspecs. The entry
1234
+ * returned is the one matching the file's old and new paths, not git's first.
1235
+ *
1236
+ * Expanded hunks are written back to the session's diff data. Returns null when
1237
+ * there is no git diff or tracked file, git's output lacks the file, or git fails.
596
1238
  */
597
1239
  declare function expandContext(session: ReviewSession, request: ExpandContextRequest): Promise<{
598
1240
  hunks: DiffHunk[];
@@ -609,6 +1251,7 @@ declare function expandContext(session: ReviewSession, request: ExpandContextReq
609
1251
  */
610
1252
  interface ReviewStartResult {
611
1253
  payload: DiffLoadPayload;
1254
+ identity: ReviewSourceIdentity;
612
1255
  stats: PayloadStats | null;
613
1256
  exceedsThresholds: boolean;
614
1257
  }
@@ -622,14 +1265,95 @@ declare function prepareDirectoryReview(session: ReviewSession, directoryPath: s
622
1265
  * Commit a prepared review payload to the session, once the caller has decided
623
1266
  * it should proceed. Returns the payload to hand to the transport.
624
1267
  */
625
- declare function commitReviewStart(session: ReviewSession, payload: DiffLoadPayload): DiffLoadPayload;
1268
+ declare function commitReviewStart(session: ReviewSession, payload: DiffLoadPayload, identity: ReviewSourceIdentity | null): DiffLoadPayload;
626
1269
 
627
1270
  /**
628
- * Determine the startup mode based on git availability and CLI arguments.
629
- * Returns the DiffSource type to use.
1271
+ * What a review starts from; `welcome` means nothing to review (desktop shows its picker, serve
1272
+ * refuses).
1273
+ */
1274
+ type StartupSource = {
1275
+ mode: 'git';
1276
+ } | {
1277
+ mode: 'directory';
1278
+ sourcePath: string;
1279
+ } | {
1280
+ mode: 'file';
1281
+ sourcePath: string;
1282
+ } | {
1283
+ mode: 'welcome';
1284
+ };
1285
+ /**
1286
+ * The candidate is the first *positional* by the shared classifier, so `-S src/x.ts` never selects
1287
+ * a file.
630
1288
  */
1289
+ declare function resolveStartupSource(gitDiffArgs: readonly string[], cwd?: string): StartupSource;
1290
+ /** The mode alone; see {@link resolveStartupSource} for the source path. */
631
1291
  declare function determineMode(gitDiffArgs: string[]): 'git' | 'directory' | 'file' | 'welcome';
632
1292
 
1293
+ /**
1294
+ * A CLI path or the reviewer's user-level `output-file` is explicit and may point anywhere.
1295
+ * Project `output-file` or the default is inherited and contained under `cwd`, since a
1296
+ * repository could otherwise redirect the save (audit A5).
1297
+ */
1298
+ declare function resolveOutputTarget(explicitPath: string | null, loaded: LoadedConfig, cwd: string): ReviewOutputTarget;
1299
+ declare function publishOptionsFor(target: ReviewOutputTarget, attachmentOrigins?: AttachmentOrigins): PublishReviewOptions;
1300
+ /**
1301
+ * Project `default-diff-args` would make git write a file or run a program; thrown before any git
1302
+ * command.
1303
+ */
1304
+ declare class ConfiguredDiffArgsError extends Error {
1305
+ readonly options: readonly string[];
1306
+ readonly configPath: string;
1307
+ constructor(options: readonly string[], configPath: string);
1308
+ }
1309
+ interface ResolvedDiffArgs {
1310
+ gitDiffArgs: string[];
1311
+ origin: 'cli' | ConfigValueOrigin;
1312
+ config: AppConfig;
1313
+ }
1314
+ /**
1315
+ * The CLI's arguments, else `default-diff-args` split with shell quoting. Project-supplied
1316
+ * ones are refused with {@link ConfiguredDiffArgsError} if write-capable; the
1317
+ * reviewer's own are not.
1318
+ */
1319
+ declare function resolveStartupDiffArgs(cliGitDiffArgs: readonly string[], loaded: LoadedConfig, cwd: string): ResolvedDiffArgs;
1320
+ interface LoadedLocalReview {
1321
+ payload: DiffLoadPayload;
1322
+ identity: ReviewSourceIdentity | null;
1323
+ }
1324
+ /**
1325
+ * Diagnostics ride on the payload and go to `log`, so a failed load never reads as empty. A welcome
1326
+ * source yields no identity.
1327
+ */
1328
+ declare function loadLocalReview(source: StartupSource, gitDiffArgs: readonly string[], config: AppConfig, cwd: string, log: (message: string) => void): Promise<LoadedLocalReview>;
1329
+ /**
1330
+ * Throws `ReviewXmlError` for an unreadable document. Returns it for what the host still needs (the
1331
+ * remote head, for drift).
1332
+ */
1333
+ declare function loadResumeDocument(session: ReviewSession, resumePath: string): ParsedReview;
1334
+
1335
+ interface ApplicationOptionsSpec<V extends string, B extends string> {
1336
+ /** Spelling to field. Long flags take `--flag value` or `--flag=value`; short ones `-o value`. */
1337
+ valueFlags: Record<string, V>;
1338
+ booleanFlags?: Record<string, B>;
1339
+ }
1340
+ interface ExtractedApplicationOptions<V extends string, B extends string> {
1341
+ values: Record<V, string | null>;
1342
+ flags: Record<B, boolean>;
1343
+ /** The `git diff` arguments in order, `--` and all that follows included. */
1344
+ rest: string[];
1345
+ }
1346
+ /** A value flag given without a value, or with an empty one. */
1347
+ declare class ApplicationOptionError extends Error {
1348
+ readonly flag: string;
1349
+ constructor(flag: string);
1350
+ }
1351
+ /**
1352
+ * Takes the application's own flags out of `argv`; throws {@link ApplicationOptionError} for a
1353
+ * missing or empty value.
1354
+ */
1355
+ declare function extractApplicationOptions<V extends string, B extends string = never>(argv: readonly string[], spec: ApplicationOptionsSpec<V, B>): ExtractedApplicationOptions<V, B>;
1356
+
633
1357
  /**
634
1358
  * Derive the guide sidecar path from the resolved output path: strip the
635
1359
  * last extension and append `.guide.xml` (`review.xml` →
@@ -659,11 +1383,22 @@ interface LoadGitDiffOptions {
659
1383
  * of a PR/MR must never pick up unrelated local untracked files.
660
1384
  */
661
1385
  includeUntracked?: boolean;
1386
+ budgets?: Partial<SourceBudgets>;
662
1387
  }
663
- declare function loadGitDiffWithUntracked(gitDiffArgs: string[], cwd?: string, options?: LoadGitDiffOptions): Promise<{
1388
+ interface LoadGitDiffResult {
664
1389
  files: DiffFile[];
665
1390
  repository: string;
666
- }>;
1391
+ /** What the diff compared; previews and line counts read this snapshot, not the working tree. */
1392
+ identity: ReviewSourceIdentity;
1393
+ /** What could not be shown faithfully; front ends show these instead of "no changes". */
1394
+ diagnostics: string[];
1395
+ }
1396
+ /**
1397
+ * Tracked wins on a path collision (after `git rm --cached f`, `f` is both a
1398
+ * deletion and untracked); two entries would share React keys and comment state.
1399
+ */
1400
+ declare function dedupeUntrackedByPath(tracked: DiffFile[], untracked: DiffFile[]): DiffFile[];
1401
+ declare function loadGitDiffWithUntracked(gitDiffArgs: string[], cwd?: string, options?: LoadGitDiffOptions): Promise<LoadGitDiffResult>;
667
1402
 
668
1403
  /**
669
1404
  * In staged-mode reviews (--staged / --cached), untracked files are not
@@ -676,6 +1411,35 @@ declare function loadGitDiffWithUntracked(gitDiffArgs: string[], cwd?: string, o
676
1411
  */
677
1412
  declare function applyStagedUntrackedDefault(config: AppConfig, gitDiffArgs: string[]): AppConfig;
678
1413
 
1414
+ /** True when `arg`'s value is the next argument, which is then neither a flag nor a positional. */
1415
+ declare function consumesNextArgument(arg: string): boolean;
1416
+ /** What the paths in `git diff` output are relative to. */
1417
+ type DiffPathRelativity = {
1418
+ kind: 'root';
1419
+ } | {
1420
+ kind: 'cwd';
1421
+ } | {
1422
+ kind: 'directory';
1423
+ directory: string;
1424
+ };
1425
+ /**
1426
+ * The last of `--relative`, `--relative=<dir>` and `--no-relative` before `--` decides.
1427
+ * Only arguments count: every git diff forces `diff.relative=false`
1428
+ * (`PARSER_COMPATIBLE_GIT_CONFIG`).
1429
+ */
1430
+ declare function describeDiffPathRelativity(args: readonly string[]): DiffPathRelativity;
1431
+ /**
1432
+ * Options that make git write a file or run a program, as written. Used to refuse project
1433
+ * `default-diff-args`; the reviewer's own arguments are unrestricted.
1434
+ */
1435
+ declare function findWriteCapableGitDiffOptions(args: readonly string[]): string[];
1436
+ /** Options selecting an output format the parser cannot consume, as the user wrote them. */
1437
+ declare function findUnsupportedGitDiffOptions(args: readonly string[]): string[];
1438
+ /** Identify positional arguments without mistaking option values for paths. */
1439
+ declare function classifyGitDiffArgs(args: string[]): {
1440
+ positionalIndices: number[];
1441
+ hasSeparator: boolean;
1442
+ };
679
1443
  /**
680
1444
  * Insert `--` before the first non-flag positional arg that exists as a
681
1445
  * filesystem path. This makes the args unambiguous so downstream code
@@ -684,48 +1448,82 @@ declare function applyStagedUntrackedDefault(config: AppConfig, gitDiffArgs: str
684
1448
  * Idempotent: an explicit `--` separator leaves the args unchanged.
685
1449
  */
686
1450
  declare function normalizeGitDiffArgs(args: string[], cwd?: string): string[];
1451
+ /**
1452
+ * Split a configured argument string into argv the way a shell would, so a
1453
+ * quoted path or search string survives as one argument.
1454
+ *
1455
+ * Two callers rely on this: `default-diff-args` from YAML, which people write
1456
+ * with shell quoting, and the `git-diff-args` string carried on a git diff
1457
+ * source, which `formatGitDiffArgs` writes in the same syntax. Unquoted input
1458
+ * splits on whitespace exactly as a plain split did, so older config and older
1459
+ * review documents keep parsing identically.
1460
+ *
1461
+ * Malformed input never throws. An unterminated quote closes at end of input:
1462
+ * a broken config line degrades to a best-effort argument list instead of
1463
+ * taking startup down with it.
1464
+ */
1465
+ declare function tokenizeGitDiffArgs(value: string): string[];
1466
+ /**
1467
+ * Render argv as the single string a git diff source carries, such that
1468
+ * `tokenizeGitDiffArgs` recovers the exact argument list.
1469
+ *
1470
+ * Arguments that survive a bare round trip are written bare, so ordinary
1471
+ * invocations produce byte-identical output to a plain join and the
1472
+ * `git-diff-args` XML attribute does not change shape for them.
1473
+ */
1474
+ declare function formatGitDiffArgs(args: string[]): string;
687
1475
 
688
- /** A materialized remote PR/MR session, ready for the git-mode pipeline. */
689
- interface RemoteSession {
1476
+ /**
1477
+ * The git-mode inputs plus the forge threads, before any diff is loaded (so nothing to anchor
1478
+ * suggestions to yet).
1479
+ */
1480
+ interface MaterializedRemoteSession {
690
1481
  forgeUrl: ForgeUrl;
691
1482
  /** Root of the materialized clone; the pipeline's repo path. */
692
1483
  repoPath: string;
693
1484
  /** Arguments for the existing git-diff machinery: `[base...head]`. */
694
1485
  gitDiffArgs: string[];
695
1486
  mode: MaterializeMode;
696
- /** Removes the temp clone when one was created; idempotent no-op otherwise. */
697
- cleanup: () => void;
1487
+ /** Idempotent, never rejects; the receiver of the session must call it. */
1488
+ cleanup: () => Promise<void>;
698
1489
  /** Provenance + thread-sync status for payloads and the saved review. */
699
1490
  remote: RemoteSessionInfo;
700
- /**
701
- * Forge discussion threads mapped to ReviewComments. Empty when the forge
702
- * CLI is unavailable. Review-level threads keep the mapper's sentinel
703
- * `filePath: ''` (REVIEW_LEVEL_FILE_PATH).
704
- *
705
- * Mapped here without the reviewed diff, which is not loaded yet, so a
706
- * `suggestion` fence stays plain body text. {@link bootstrapRemoteDiff}
707
- * replaces these with the same threads mapped against the loaded files.
708
- */
709
- fetchedComments: ReviewComment[];
710
- /**
711
- * The threads behind `fetchedComments`, verbatim. Carried so the caller
712
- * that loads the diff can map them again with it (SR-0063).
713
- */
1491
+ /** Verbatim; empty when thread sync is unavailable. */
714
1492
  fetchedThreads: ForgeThread[];
715
1493
  }
1494
+ /** A session whose diff is loaded and whose threads are mapped against it. */
1495
+ interface RemoteSession extends MaterializedRemoteSession {
1496
+ /** Review-level threads keep the sentinel `filePath: ''` (REVIEW_LEVEL_FILE_PATH). */
1497
+ fetchedComments: ReviewComment[];
1498
+ }
716
1499
  /** Injectable seams; defaults are the real core APIs. */
717
1500
  interface RemoteSessionDeps {
718
1501
  createProvider: (forge: ForgeName, runner: ForgeCommandRunner) => ForgeProvider;
719
- materialize: (url: ForgeUrl, baseBranch: string, cwd: string, runner: ForgeCommandRunner, existingClone?: ExistingClone | null) => Promise<MaterializeResult>;
720
- detectExistingClone: (url: ForgeUrl, cwd: string, runner: ForgeCommandRunner) => Promise<ExistingClone | null>;
721
- resolveRemoteDefaultBranch: (url: ForgeUrl, runner: ForgeCommandRunner, existing?: ExistingClone | null) => Promise<string>;
1502
+ materialize: (url: ForgeUrl, baseBranch: string, cwd: string, runner: ForgeCommandRunner, existingClone?: ExistingClone | null, options?: MaterializeOptions) => Promise<MaterializeResult>;
1503
+ detectExistingClone: (url: ForgeUrl, cwd: string, runner: ForgeCommandRunner, options?: MaterializeOptions) => Promise<ExistingClone | null>;
1504
+ resolveRemoteDefaultBranch: (url: ForgeUrl, runner: ForgeCommandRunner, existing?: ExistingClone | null, options?: MaterializeOptions) => Promise<string>;
722
1505
  runner: ForgeCommandRunner;
723
- /** Loads the diff from the clone. Untracked files are never included. */
1506
+ /** Untracked files are never included. A stand-in may omit `diagnostics` and `identity`. */
724
1507
  loadDiff: (gitDiffArgs: string[], cwd: string) => Promise<{
725
1508
  files: DiffFile[];
726
1509
  repository: string;
1510
+ diagnostics?: string[];
1511
+ identity?: ReviewSourceIdentity;
727
1512
  }>;
728
1513
  }
1514
+ declare const defaultRemoteSessionDeps: RemoteSessionDeps;
1515
+ interface RemoteLifetimeOptions {
1516
+ /** Without one, the session is bounded only by the per-command timeout. */
1517
+ signal?: AbortSignal;
1518
+ }
1519
+ interface StartRemoteSessionOptions extends RemoteLifetimeOptions {
1520
+ includeResolved?: boolean;
1521
+ /**
1522
+ * `'optional'` (default, the app): a failed fetch degrades to no threads.
1523
+ * `'required'` (`fetch-comments`): always attempted, and a failure is fatal.
1524
+ */
1525
+ threads?: 'optional' | 'required';
1526
+ }
729
1527
  /**
730
1528
  * Materialize a forge PR/MR URL into a local git context and fetch its
731
1529
  * discussion threads.
@@ -733,23 +1531,38 @@ interface RemoteSessionDeps {
733
1531
  * Fatal failures (unrecognizable URL, materialization errors, base-branch
734
1532
  * lookup failures other than a missing CLI) throw — callers surface them
735
1533
  * like any other startup git error. Forge-CLI unavailability is never
736
- * fatal: the base branch falls back to the git-only default-branch lookup
737
- * and thread sync degrades to an empty list with a single stderr note.
1534
+ * fatal for the base branch (git-only fallback); for threads see
1535
+ * {@link StartRemoteSessionOptions.threads}.
1536
+ */
1537
+ declare function startRemoteSession(url: string, cwd: string, deps?: Partial<RemoteSessionDeps>, options?: StartRemoteSessionOptions): Promise<MaterializedRemoteSession>;
1538
+ interface RemoteReviewLoad {
1539
+ /** After the ignore configuration. */
1540
+ files: DiffFile[];
1541
+ repository: string;
1542
+ diagnostics: string[];
1543
+ /** `session.fetchedThreads` mapped against `files` and the materialized head. */
1544
+ comments: ReviewComment[];
1545
+ identity?: ReviewSourceIdentity;
1546
+ }
1547
+ /**
1548
+ * Load the diff, apply the ignore configuration and map the threads: the one place
1549
+ * this happens, so the app and `fetch-comments` cannot drift. Mapping against the
1550
+ * filtered files and the materialized head keeps a suggestion on an ignored path
1551
+ * or another head plain text (R05). Does not release the session on failure. An
1552
+ * abort during the load discards the result and throws.
738
1553
  */
739
- declare function startRemoteSession(url: string, cwd: string, deps?: Partial<RemoteSessionDeps>): Promise<RemoteSession>;
1554
+ declare function loadRemoteReview(session: MaterializedRemoteSession, ignorePatterns: string[], loadDiff?: RemoteSessionDeps['loadDiff'], options?: RemoteLifetimeOptions): Promise<RemoteReviewLoad>;
740
1555
  /** A remote session plus the ready-to-send git-mode diff payload. */
741
1556
  interface RemoteBootstrapResult {
742
1557
  session: RemoteSession;
743
1558
  payload: DiffLoadPayload;
1559
+ identity: ReviewSourceIdentity;
744
1560
  }
745
1561
  /**
746
- * Full remote bootstrap: materialize the session, load the diff from the
747
- * clone through the existing git-diff machinery, apply the ignore filter,
748
- * map the fetched threads against those files, and shape the git-mode
749
- * `DiffLoadPayload` (with `remote` provenance attached). Shared by the CLI
750
- * URL startup path and the splash-screen `remote:open-url` handler.
1562
+ * Full remote bootstrap for the app: materialize, {@link loadRemoteReview}, and shape
1563
+ * the git-mode `DiffLoadPayload`. Thread sync degrades rather than failing.
751
1564
  */
752
- declare function bootstrapRemoteDiff(url: string, cwd: string, ignorePatterns: string[], deps?: Partial<RemoteSessionDeps>): Promise<RemoteBootstrapResult>;
1565
+ declare function bootstrapRemoteDiff(url: string, cwd: string, ignorePatterns: string[], deps?: Partial<RemoteSessionDeps>, options?: RemoteLifetimeOptions): Promise<RemoteBootstrapResult>;
753
1566
  /**
754
1567
  * Merge fetched forge threads into a resumed document's comments. The
755
1568
  * resumed document wins: a fetched thread whose root `remoteId` already
@@ -772,21 +1585,10 @@ declare function applyRemoteProvenance(state: ReviewState, remote: RemoteSession
772
1585
  */
773
1586
  declare function computeRemoteDrift(recordedHeadSha: string | undefined, liveHeadSha: string): RemoteDriftInfo | null;
774
1587
 
775
- /**
776
- * Injectable seams for the orchestration. Defaults spawn real processes and
777
- * touch the real filesystem; tests replace them wholesale.
778
- */
779
- interface FetchCommentsDeps {
780
- /** Command runner shared by git, gh and glab invocations. */
781
- runner: ForgeCommandRunner;
782
- createProvider: (forge: ForgeName, runner: ForgeCommandRunner) => ForgeProvider;
783
- materialize: (url: ForgeUrl, baseBranch: string, cwd: string, runner: ForgeCommandRunner, existingClone?: ExistingClone | null) => Promise<MaterializeResult>;
784
- detectExistingClone: (url: ForgeUrl, cwd: string, runner: ForgeCommandRunner) => Promise<ExistingClone | null>;
785
- resolveRemoteDefaultBranch: (url: ForgeUrl, runner: ForgeCommandRunner, existing?: ExistingClone | null) => Promise<string>;
786
- loadDiffFiles: (repoPath: string, baseSha: string, headSha: string) => Promise<DiffFile[]>;
787
- serialize: (state: ReviewState, outputPath: string) => Promise<string>;
788
- writeFile: (path: string, content: string) => void;
789
- loadConfig: () => AppConfig;
1588
+ /** Injectable seams: the app's remote-session seams plus this subcommand's output. */
1589
+ interface FetchCommentsDeps extends RemoteSessionDeps {
1590
+ publish: (state: ReviewState, outputPath: string, options: PublishReviewOptions) => Promise<PublishReviewResult>;
1591
+ loadConfig: () => LoadedConfig;
790
1592
  now: () => Date;
791
1593
  }
792
1594
  interface BuildRemoteReviewStateArgs {
@@ -823,7 +1625,7 @@ interface BuildRemoteReviewStateArgs {
823
1625
  * serialized.
824
1626
  */
825
1627
  declare function buildRemoteReviewState(args: BuildRemoteReviewStateArgs): ReviewState;
826
- interface FetchCommentsOptions {
1628
+ interface FetchCommentsOptions extends RemoteLifetimeOptions {
827
1629
  /** Include threads the forge marks resolved (GitLab). Default false. */
828
1630
  includeResolved?: boolean;
829
1631
  /** Working directory for clone detection and output resolution. */
@@ -834,8 +1636,12 @@ interface FetchCommentsOptions {
834
1636
  /**
835
1637
  * Run the headless fetch-comments flow end to end. Throws on any failure
836
1638
  * (the caller prints the message to stderr and exits 1); the temporary
837
- * clone, when one was created, is removed on both success and failure.
1639
+ * clone, when one was created, is removed on both success and failure, and
1640
+ * the removal has completed by the time the promise settles.
1641
+ *
1642
+ * Fetching comments is the whole point, so threads run under the `'required'`
1643
+ * policy: an unavailable forge CLI is an error, not a degraded review.
838
1644
  */
839
1645
  declare function runFetchComments(url: string, options?: FetchCommentsOptions): Promise<void>;
840
1646
 
841
- export { type ApplyRefusalReason, type ApplySuggestionApplied, type ApplySuggestionRefused, type ApplySuggestionRequest, type ApplySuggestionResult, type BuildRemoteReviewStateArgs, type ExistingClone, type FetchCommentsDeps, type FetchCommentsOptions, type FetchThreadsOptions, type ForgeAnchorSide, ForgeCliUnavailableError, type ForgeCommandResult, type ForgeCommandRunner, type ForgeName, type ForgeProvider, type ForgeThread, type ForgeThreadAnchor, type ForgeThreadTurn, type ForgeUrl, GUIDE_XSD_SCHEMA, type GuideParseResult, IMPLICIT_GUIDE_GROUP_NAME, type LoadGitDiffOptions, type MaterializeMode, type MaterializeResult, REVIEW_LEVEL_FILE_PATH, type RemoteBootstrapResult, type RemoteSession, type RemoteSessionDeps, type RenderedTextMode, type ReviewSession, type ReviewStartResult, applyRemoteProvenance, applyStagedUntrackedDefault, applySuggestion, applySuggestionForSession, bootstrapRemoteDiff, buildRemoteReviewState, checkWritability, commitReviewStart, computePayloadStats, computeRemoteDrift, countTotalLines, createGitHubProvider, createGitLabProvider, createIgnoreFilter, createReviewSession, defaultGitRunner, deriveGuidePath, detectExistingClone, determineMode, expandContext, generateSyntheticDiffs, generateUntrackedDiffs, getConfigLoad, getDiffLoad, getFileHunks, getGitDiffStats, getLanguageFromPath, getRenderedTextMode, getRepoRoot, getRepoRootAsync, getResumeLoad, getUntrackedFilesAsync, isHtmlFile, isMarkdownFile, isPreviewableImage, isPreviewableRenderedText, isPreviewableSvg, loadConfig, loadGitDiffWithUntracked, loadGuide, loadImage, mapThreadsToReviewComments, materialize, mergeRemoteThreads, normalizeGitDiffArgs, parseDiff, parseForgeUrl, parseGuideXml, parseReviewXml, parseReviewXmlString, prepareDirectoryReview, preparePayload, readAttachment, reconcileGuide, resolveApplyDestination, resolveGuidePath, resolveRemoteDefaultBranch, resolveSourceBaseDir, runFetchComments, runGitDiff, runGitDiffAsync, scanDirectory, scanFile, serializeReview, startRemoteSession, submitReviewState, takeReviewState, validateGitAvailable };
1647
+ export { ASSET_DIR_NAME, type AnchorCheck, type AnchorFields, type AnchorSide, ApplicationOptionError, type ApplicationOptionsSpec, type ApplyRefusalReason, type ApplySuggestionApplied, type ApplySuggestionOptions, type ApplySuggestionRefused, type ApplySuggestionRequest, type ApplySuggestionResult, type AssetNamer, type AtomicReplaceOptions, type AtomicReplaceResult, type AttachmentOrigins, type AttachmentReadFailureReason, type AttachmentReadResult, AttachmentRelocationError, BINARY_SNIFF_BYTES, type BoundedReadOptions, type BoundedReadResult, type BuildRemoteReviewStateArgs, type CommandCancelReason, CommandCancelledError, type ConfigProvenance, type ConfigSource, type ConfigValueOrigin, ConfiguredDiffArgsError, DEFAULT_GIT_COMMAND_TIMEOUT_MS, DEFAULT_SOURCE_BUDGETS, type DiffParseResult, type DiffPathRelativity, type ExistingClone, type ExtractedApplicationOptions, type FetchCommentsDeps, type FetchCommentsOptions, type FetchThreadsOptions, type FileIdentity, type ForgeAnchorSide, ForgeCliUnavailableError, type ForgeCommandOptions, type ForgeCommandResult, type ForgeCommandRunner, type ForgeName, type ForgeProvider, type ForgeThread, type ForgeThreadAnchor, type ForgeThreadTurn, type ForgeUrl, type FsLayer, GUIDE_XSD_SCHEMA, type GitDiffSideSpec, type GitDiffSides, type GitSourceIdentityOptions, type GuideParseResult, IMPLICIT_GUIDE_GROUP_NAME, type LineAnchor, type LoadConfigOptions, type LoadGitDiffOptions, type LoadGitDiffResult, type LoadedConfig, type LoadedLocalReview, type LocalSourceIdentityOptions, MAX_GIT_DIFF_OUTPUT_BYTES, MAX_GUIDE_BYTES, MAX_IMAGE_BYTES, MAX_RESUME_ATTACHMENTS, MAX_RESUME_XML_BYTES, MAX_SOURCE_ENTRIES, MAX_SOURCE_FILE_BYTES, MAX_SOURCE_TOTAL_BYTES, type MaterializeMode, type MaterializeOptions, type MaterializeResult, type MaterializedRemoteSession, PARSER_COMPATIBLE_DIFF_FLAGS, PARSER_COMPATIBLE_GIT_CONFIG, type ParsedReview, type PlannedAsset, type PublishReviewOptions, type PublishReviewResult, REVIEW_LEVEL_FILE_PATH, type RemoteBootstrapResult, type RemoteLifetimeOptions, type RemoteReviewLoad, type RemoteSession, type RemoteSessionDeps, type RenderedTextMode, type ResolvedDiffArgs, type ReviewOutputOrigin, type ReviewOutputTarget, ReviewPublishError, type ReviewPublishErrorCode, type ReviewSession, type ReviewStartResult, ReviewXmlError, type ReviewXmlErrorCode, type ReviewedPathAuthorization, type ReviewedPathRefusal, type ReviewedSnapshot, SafeFsError, type SafeFsErrorCode, type SerializeOptions, type SerializedReview, type SnapshotReadFailure, type SnapshotReadOptions, type SnapshotReadResult, type SourceBudgets, type SourceScanOptions, type SourceScanResult, type StartRemoteSessionOptions, type StartupSource, type SyntheticDiffOptions, type SyntheticDiffResult, type WriteExclusiveOptions, XmlIllegalCharacterError, type XmlIllegalCharacterLocation, applyRemoteProvenance, applyStagedUntrackedDefault, applySuggestion, applySuggestionForSession, assertNoSymlinkAncestors, atomicReplace, authorizeAttachmentReference, authorizeReviewedPath, bootstrapRemoteDiff, buildRemoteReviewState, canonicalSourcePath, checkWritability, classifyFsError, classifyGitDiffArgs, commitDiffData, commitReviewStart, computePayloadStats, computeRemoteDrift, consumesNextArgument, countTotalLines, createGitHubProvider, createGitLabProvider, createIgnoreFilter, createReviewSession, dedupeUntrackedByPath, defaultGitRunner, defaultRemoteSessionDeps, deriveGuidePath, describeDiffPathRelativity, describeGitDiffSides, detectExistingClone, determineMode, expandContext, extractApplicationOptions, findUnsupportedGitDiffOptions, findWriteCapableGitDiffOptions, formatBytes, formatGitDiffArgs, generateSyntheticDiffs, generateUntrackedDiffs, getConfigLoad, getDiffLoad, getFileHunks, getGitDiffStats, getLanguageFromPath, getRenderedTextMode, getRepoRootAsync, getResumeLoad, getUntrackedFilesAsync, inspectOutputPath, inspectReplaceTarget, isCommandCancelled, isHtmlFile, isMarkdownFile, isPreviewableImage, isPreviewableRenderedText, isPreviewableSvg, isRepositoryControlPath, loadConfig, loadConfigWithProvenance, loadGitDiffWithUntracked, loadGuide, loadImage, loadLocalReview, loadRemoteReview, loadResumeDocument, loadSyntheticFiles, locateReviewedFile, mapThreadsToReviewComments, materialize, mergeRemoteThreads, nodeFsLayer, normalizeGitDiffArgs, parseAttachmentReference, parseDiff, parseDiffWithDiagnostics, parseForgeUrl, parseGuideXml, parseReviewXml, parseReviewXmlString, prepareDirectoryReview, preparePayload, publishOptionsFor, publishReview, readAssetFile, readAttachment, readFileWithinBudget, readFileWithinBudgetSync, readReviewedContent, reconcileGuide, recordResumedAttachments, relocateAttachments, resolveApplyDestination, resolveAttachmentOrigins, resolveGitSourceIdentity, resolveGuidePath, resolveLocalSourceIdentity, resolveOutputTarget, resolveRemoteDefaultBranch, resolveReviewedPathPrefix, resolveSourceBaseDir, resolveSourceBudgets, resolveStartupDiffArgs, resolveStartupSource, rootRelativeReviewedPath, runFetchComments, runGitDiffAsync, sameFile, scanDirectory, scanFile, serializeReview, snapshotIdentity, startRemoteSession, submitReviewState, takeReviewState, tokenizeGitDiffArgs, validateLineAnchor, validateLineRange, withParserCompatibleDiffArgs, writeExclusiveNoFollow };