@self-review/core 1.43.3 → 1.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { DiffFile, ReviewState, ReviewComment, DiffSource, RemoteForge, ReviewGuide, ResolvedGuideGroup, AppConfig, PayloadStats } from '@self-review/types';
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
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';
3
3
 
4
4
  declare function parseDiff(rawDiff: string): DiffFile[];
@@ -72,8 +72,18 @@ declare function getRepoRootAsync(cwd?: string): Promise<string>;
72
72
  declare function runGitDiffAsync(args: string[], cwd?: string): Promise<string>;
73
73
  /**
74
74
  * Get list of untracked files (respects .gitignore).
75
+ *
76
+ * Pass the repository root. `git ls-files` reports paths relative to the
77
+ * directory it runs in and lists that subtree only, while `git diff` reports
78
+ * root-relative paths for the whole repository from anywhere inside it. Run
79
+ * anywhere else and the names match neither the diff nor the root the files
80
+ * are read from.
81
+ *
82
+ * `-z` keeps the names literal. NUL termination survives newlines in
83
+ * filenames, and it turns off the C-style quoting git otherwise applies to
84
+ * control characters and non-ASCII bytes.
75
85
  */
76
- declare function getUntrackedFilesAsync(cwd?: string): Promise<string[]>;
86
+ declare function getUntrackedFilesAsync(repoRoot?: string): Promise<string[]>;
77
87
  /**
78
88
  * Generate synthetic unified diffs for untracked files so they can be
79
89
  * parsed by the existing diff parser.
@@ -209,8 +219,9 @@ declare function parseForgeUrl(url: string): ForgeUrl | null;
209
219
  * Generate synthetic unified diffs for a list of file paths so they can be
210
220
  * parsed by the existing diff parser. Each file is treated as a new addition.
211
221
  *
212
- * @param paths - Relative file paths (e.g. "src/foo.ts")
213
- * @param rootDir - Absolute path to the root directory containing the files
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
214
225
  * @returns A unified diff string covering all provided files
215
226
  */
216
227
  declare function generateSyntheticDiffs(paths: string[], rootDir: string): string;
@@ -268,6 +279,81 @@ declare function createIgnoreFilter(patterns: string[]): (path: string) => boole
268
279
  */
269
280
  declare function checkWritability(filePath: string): boolean;
270
281
 
282
+ /**
283
+ * Why an apply was refused. Every value is a structural fact about the
284
+ * request or the file — never a fragment of the file's contents, so a
285
+ * refusal is safe to surface in the UI and in logs.
286
+ */
287
+ type ApplyRefusalReason =
288
+ /** The suggestion is file-level: there is nothing to replace. */
289
+ 'no-anchor'
290
+ /**
291
+ * The anchor names deleted lines (`side: 'old'`). Those lines are not in
292
+ * the working file, and the app holds no old→new line mapping, so the
293
+ * target is undefined rather than merely missing.
294
+ */
295
+ | 'old-side-anchor'
296
+ /** `destinationRoot` is relative; resolving it would consult the cwd. */
297
+ | 'destination-not-absolute'
298
+ /** `filePath` resolves outside `destinationRoot`. */
299
+ | 'path-escapes-destination'
300
+ /** No file at the resolved path. */
301
+ | 'file-missing'
302
+ /** The path exists but could not be read (permissions, a directory, …). */
303
+ | 'file-unreadable'
304
+ /**
305
+ * The file is not valid UTF-8. Rewriting it would round-trip its bytes
306
+ * through a lossy decode and corrupt regions outside the anchor.
307
+ */
308
+ | 'file-not-utf8'
309
+ /** The anchor falls outside the file's line count. */
310
+ | 'anchor-out-of-range'
311
+ /** The anchored lines no longer match `suggestion.originalCode`. */
312
+ | 'context-mismatch'
313
+ /** The context matched but the write itself failed. */
314
+ | 'write-failed';
315
+ interface ApplySuggestionRequest {
316
+ /**
317
+ * Absolute path of the directory the reviewed files live in. Always
318
+ * supplied by the caller: a git-mode working tree, a directory-mode root,
319
+ * a reused clone, or the destination the user picked for a temporary-clone
320
+ * review. Never derived here.
321
+ */
322
+ destinationRoot: string;
323
+ /** Path of the file to modify, relative to `destinationRoot`. */
324
+ filePath: string;
325
+ /** The comment's anchor. `null` (file-level) is refused. */
326
+ lineRange: LineRange | null;
327
+ suggestion: Suggestion;
328
+ }
329
+ interface ApplySuggestionApplied {
330
+ status: 'applied';
331
+ /** Echoed from the request, so a batch caller can attribute the result. */
332
+ filePath: string;
333
+ absolutePath: string;
334
+ /** How many on-disk lines the proposal replaced. */
335
+ replacedLines: number;
336
+ }
337
+ interface ApplySuggestionRefused {
338
+ status: 'refused';
339
+ filePath: string;
340
+ reason: ApplyRefusalReason;
341
+ /** One sentence naming the refusal, safe to show to the reviewer. */
342
+ detail: string;
343
+ }
344
+ type ApplySuggestionResult = ApplySuggestionApplied | ApplySuggestionRefused;
345
+ /**
346
+ * Apply one anchored suggestion to one file under `destinationRoot`.
347
+ *
348
+ * On a byte-for-byte match between the anchored lines and
349
+ * `suggestion.originalCode`, the anchored lines are replaced with
350
+ * `suggestion.proposedCode` and the file is rewritten. Lines outside the
351
+ * anchor keep their exact bytes, including their line terminators, and the
352
+ * file's trailing-newline state is preserved either way. Any other outcome
353
+ * refuses with a reason and writes nothing.
354
+ */
355
+ declare function applySuggestion(request: ApplySuggestionRequest): ApplySuggestionResult;
356
+
271
357
  /**
272
358
  * File-type detection utilities.
273
359
  *
@@ -317,10 +403,15 @@ declare const REVIEW_LEVEL_FILE_PATH = "";
317
403
  * - Mapped comments carry no category, severity or confidence: forge
318
404
  * threads have none, and absent means below every threshold. The empty
319
405
  * `category` matches how the XML parser represents a missing category.
406
+ * - A root body carrying a single ` ```suggestion ` fence becomes a
407
+ * `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.
320
411
  *
321
412
  * Output order is input order. The input is never mutated.
322
413
  */
323
- declare function mapThreadsToReviewComments(threads: ForgeThread[]): ReviewComment[];
414
+ declare function mapThreadsToReviewComments(threads: ForgeThread[], diffFiles?: DiffFile[]): ReviewComment[];
324
415
 
325
416
  /**
326
417
  * Create the GitLab {@link ForgeProvider} backed by the `glab` CLI.
@@ -390,4 +481,361 @@ declare function materialize(url: ForgeUrl, baseBranch: string, cwd: string, run
390
481
  */
391
482
  declare function resolveRemoteDefaultBranch(url: ForgeUrl, runner?: ForgeCommandRunner, existing?: ExistingClone | null): Promise<string>;
392
483
 
393
- export { type ExistingClone, 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 MaterializeMode, type MaterializeResult, REVIEW_LEVEL_FILE_PATH, type RenderedTextMode, checkWritability, computePayloadStats, countTotalLines, createGitHubProvider, createGitLabProvider, createIgnoreFilter, defaultGitRunner, detectExistingClone, generateSyntheticDiffs, generateUntrackedDiffs, getGitDiffStats, getLanguageFromPath, getRenderedTextMode, getRepoRoot, getRepoRootAsync, getUntrackedFilesAsync, isHtmlFile, isMarkdownFile, isPreviewableImage, isPreviewableRenderedText, isPreviewableSvg, loadConfig, mapThreadsToReviewComments, materialize, parseDiff, parseForgeUrl, parseGuideXml, parseReviewXml, parseReviewXmlString, reconcileGuide, resolveRemoteDefaultBranch, runGitDiff, runGitDiffAsync, scanDirectory, scanFile, serializeReview, validateGitAvailable };
484
+ /**
485
+ * The state a single review session owns. One desktop application window is
486
+ * one session; two sessions are independent and cannot observe each other.
487
+ */
488
+ interface ReviewSession {
489
+ reviewState: ReviewState | null;
490
+ diffData: DiffLoadPayload | null;
491
+ guideData: GuideLoadPayload | null;
492
+ config: AppConfig | null;
493
+ outputPathInfo: OutputPathInfo | null;
494
+ resumeComments: ReviewComment[];
495
+ resumeViewedFiles: string[];
496
+ resumeRemoteDrift: RemoteDriftInfo | null;
497
+ /**
498
+ * Destination directory the user named for this session's applies, or
499
+ * null when none has been named. Only a temporary-clone remote review
500
+ * needs one; see {@link resolveApplyDestination}.
501
+ */
502
+ applyDestinationRoot: string | null;
503
+ }
504
+ /** Create an empty session. */
505
+ declare function createReviewSession(): ReviewSession;
506
+ /**
507
+ * Prepare a DiffLoadPayload for IPC transmission.
508
+ * In large-payload mode, strips hunks from files to reduce initial transfer size.
509
+ * The full data stays in the session for on-demand loading via DIFF_LOAD_FILE.
510
+ */
511
+ declare function preparePayload(payload: DiffLoadPayload): DiffLoadPayload;
512
+ /**
513
+ * Resolve what a diff request should deliver: the prepared diff payload and,
514
+ * when one is loaded, the guide that rides with it. Returns null when the
515
+ * session has no diff, so the caller sends nothing at all.
516
+ */
517
+ declare function getDiffLoad(session: ReviewSession): {
518
+ diff: DiffLoadPayload;
519
+ guide: GuideLoadPayload | null;
520
+ } | 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
+ */
529
+ declare function resolveSourceBaseDir(session: ReviewSession): string | null;
530
+ /**
531
+ * Load a binary image as a base64 data URI for the rendered preview.
532
+ */
533
+ declare function loadImage(session: ReviewSession, filePath: string): Promise<ImageLoadResult>;
534
+ /**
535
+ * Return a single file's hunks for lazy (large-payload) mode, or null when the
536
+ * session has no diff or the diff has no such file.
537
+ */
538
+ declare function getFileHunks(session: ReviewSession, filePath: string): DiffHunk[] | null;
539
+ /**
540
+ * Resolve the config and the output path info that travel with it. Returns null
541
+ * when the session has no config, so the caller sends nothing at all: the
542
+ * renderer distinguishes an absent message from an empty one.
543
+ */
544
+ declare function getConfigLoad(session: ReviewSession): {
545
+ config: AppConfig;
546
+ outputPathInfo: OutputPathInfo | null;
547
+ } | null;
548
+ /**
549
+ * Store a review state submitted by the front end on the session.
550
+ */
551
+ declare function submitReviewState(session: ReviewSession, state: ReviewState): void;
552
+ /**
553
+ * Take the submitted review state off the session, clearing it so it is
554
+ * consumed exactly once. Returns null when nothing has been submitted.
555
+ */
556
+ declare function takeReviewState(session: ReviewSession): ReviewState | null;
557
+ /**
558
+ * The directory an apply may write into for this session, or null when the
559
+ * session has none.
560
+ *
561
+ * For every review whose files sit in a place the user controls — a git
562
+ * working tree, a scanned directory, a reused remote clone — that is the
563
+ * root the reviewed paths are relative to, and no one is asked anything.
564
+ *
565
+ * A temporary-clone review is the one exception. Its files live in a
566
+ * directory the app deletes on exit, so the clone is never a destination:
567
+ * the answer is the directory the user named, and null until they name one.
568
+ */
569
+ declare function resolveApplyDestination(session: ReviewSession): string | null;
570
+ /**
571
+ * 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.
575
+ *
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.
578
+ */
579
+ declare function applySuggestionForSession(session: ReviewSession, request: SuggestionApplyRequest): SuggestionApplyOutcome;
580
+ /**
581
+ * Read an attachment file from disk, as an ArrayBuffer the front end can use.
582
+ * Returns null when the file cannot be read.
583
+ */
584
+ declare function readAttachment(filePath: string): Promise<ArrayBuffer | null>;
585
+ /**
586
+ * Resolve the resumed comments, viewed files and remote drift for a session.
587
+ * Returns null when there is nothing to resume, so the caller sends nothing
588
+ * at all.
589
+ */
590
+ declare function getResumeLoad(session: ReviewSession): ResumeLoadPayload | null;
591
+ /**
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.
596
+ */
597
+ declare function expandContext(session: ReviewSession, request: ExpandContextRequest): Promise<{
598
+ hunks: DiffHunk[];
599
+ totalLines: number;
600
+ } | null>;
601
+ /**
602
+ * What a review start produced: the payload built from the scanned path, the
603
+ * stats it was measured against (null when the session has no config, in which
604
+ * case no thresholds apply), and whether those stats exceeded a threshold.
605
+ *
606
+ * The payload is deliberately *not* stored on the session: the caller may still
607
+ * need to abandon it (a user declining a large review keeps the review they
608
+ * were already looking at), so committing it is the caller's decision.
609
+ */
610
+ interface ReviewStartResult {
611
+ payload: DiffLoadPayload;
612
+ stats: PayloadStats | null;
613
+ exceedsThresholds: boolean;
614
+ }
615
+ /**
616
+ * Scan a picked path and build the diff payload for a directory (or single
617
+ * file) review, measured against the session's large-payload thresholds.
618
+ * Nothing is stored on the session — see `ReviewStartResult`.
619
+ */
620
+ declare function prepareDirectoryReview(session: ReviewSession, directoryPath: string): Promise<ReviewStartResult>;
621
+ /**
622
+ * Commit a prepared review payload to the session, once the caller has decided
623
+ * it should proceed. Returns the payload to hand to the transport.
624
+ */
625
+ declare function commitReviewStart(session: ReviewSession, payload: DiffLoadPayload): DiffLoadPayload;
626
+
627
+ /**
628
+ * Determine the startup mode based on git availability and CLI arguments.
629
+ * Returns the DiffSource type to use.
630
+ */
631
+ declare function determineMode(gitDiffArgs: string[]): 'git' | 'directory' | 'file' | 'welcome';
632
+
633
+ /**
634
+ * Derive the guide sidecar path from the resolved output path: strip the
635
+ * last extension and append `.guide.xml` (`review.xml` →
636
+ * `review.guide.xml`). An output filename with no extension gets
637
+ * `.guide.xml` appended verbatim.
638
+ */
639
+ declare function deriveGuidePath(outputPath: string): string;
640
+ /**
641
+ * Resolve where to look for the guide: the `guide-file` config override
642
+ * (resolved against cwd, like `output-file`) when set, otherwise the path
643
+ * derived from the resolved output path.
644
+ */
645
+ declare function resolveGuidePath(outputPath: string, config: Pick<AppConfig, 'guideFile'>): string;
646
+ /**
647
+ * Discover, read, parse, validate, and reconcile the guide sidecar.
648
+ *
649
+ * Returns the display-ready payload, or null when there is no usable
650
+ * guide. Missing file: silent. Unreadable or invalid file: exactly one
651
+ * `console.error()` line (guide path + reason class). Never throws.
652
+ */
653
+ declare function loadGuide(outputPath: string, config: Pick<AppConfig, 'guideFile'>, diffFilePaths: string[]): Promise<GuideLoadPayload | null>;
654
+
655
+ interface LoadGitDiffOptions {
656
+ /**
657
+ * Include untracked working-tree files as synthetic additions. Defaults
658
+ * to true (local git mode). Remote mode passes false: a base...head diff
659
+ * of a PR/MR must never pick up unrelated local untracked files.
660
+ */
661
+ includeUntracked?: boolean;
662
+ }
663
+ declare function loadGitDiffWithUntracked(gitDiffArgs: string[], cwd?: string, options?: LoadGitDiffOptions): Promise<{
664
+ files: DiffFile[];
665
+ repository: string;
666
+ }>;
667
+
668
+ /**
669
+ * In staged-mode reviews (--staged / --cached), untracked files are not
670
+ * part of the index and should be hidden by default. If the user has
671
+ * explicitly opted in via `show-untracked: true` in their YAML config,
672
+ * respect that choice.
673
+ *
674
+ * Untracked files are still preloaded by the backend so that the toolbar
675
+ * toggle can reveal them instantly without re-running git.
676
+ */
677
+ declare function applyStagedUntrackedDefault(config: AppConfig, gitDiffArgs: string[]): AppConfig;
678
+
679
+ /**
680
+ * Insert `--` before the first non-flag positional arg that exists as a
681
+ * filesystem path. This makes the args unambiguous so downstream code
682
+ * (expand-context) never confuses a path for a revision.
683
+ *
684
+ * Idempotent: an explicit `--` separator leaves the args unchanged.
685
+ */
686
+ declare function normalizeGitDiffArgs(args: string[], cwd?: string): string[];
687
+
688
+ /** A materialized remote PR/MR session, ready for the git-mode pipeline. */
689
+ interface RemoteSession {
690
+ forgeUrl: ForgeUrl;
691
+ /** Root of the materialized clone; the pipeline's repo path. */
692
+ repoPath: string;
693
+ /** Arguments for the existing git-diff machinery: `[base...head]`. */
694
+ gitDiffArgs: string[];
695
+ mode: MaterializeMode;
696
+ /** Removes the temp clone when one was created; idempotent no-op otherwise. */
697
+ cleanup: () => void;
698
+ /** Provenance + thread-sync status for payloads and the saved review. */
699
+ 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
+ */
714
+ fetchedThreads: ForgeThread[];
715
+ }
716
+ /** Injectable seams; defaults are the real core APIs. */
717
+ interface RemoteSessionDeps {
718
+ 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>;
722
+ runner: ForgeCommandRunner;
723
+ /** Loads the diff from the clone. Untracked files are never included. */
724
+ loadDiff: (gitDiffArgs: string[], cwd: string) => Promise<{
725
+ files: DiffFile[];
726
+ repository: string;
727
+ }>;
728
+ }
729
+ /**
730
+ * Materialize a forge PR/MR URL into a local git context and fetch its
731
+ * discussion threads.
732
+ *
733
+ * Fatal failures (unrecognizable URL, materialization errors, base-branch
734
+ * lookup failures other than a missing CLI) throw — callers surface them
735
+ * 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.
738
+ */
739
+ declare function startRemoteSession(url: string, cwd: string, deps?: Partial<RemoteSessionDeps>): Promise<RemoteSession>;
740
+ /** A remote session plus the ready-to-send git-mode diff payload. */
741
+ interface RemoteBootstrapResult {
742
+ session: RemoteSession;
743
+ payload: DiffLoadPayload;
744
+ }
745
+ /**
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.
751
+ */
752
+ declare function bootstrapRemoteDiff(url: string, cwd: string, ignorePatterns: string[], deps?: Partial<RemoteSessionDeps>): Promise<RemoteBootstrapResult>;
753
+ /**
754
+ * Merge fetched forge threads into a resumed document's comments. The
755
+ * resumed document wins: a fetched thread whose root `remoteId` already
756
+ * appears in the resumed comments is skipped (the resumed copy may carry
757
+ * the user's added replies). Order: resumed comments first, then the
758
+ * non-duplicate fetched threads in fetch order. Inputs are not mutated.
759
+ */
760
+ declare function mergeRemoteThreads(resumed: ReviewComment[], fetched: ReviewComment[]): ReviewComment[];
761
+ /**
762
+ * Return a copy of the state carrying this session's remote provenance, so
763
+ * "Finish Review" writes the `remote-*` root attributes. Always records the
764
+ * live session values: the saved document describes the diff that was
765
+ * actually reviewed.
766
+ */
767
+ declare function applyRemoteProvenance(state: ReviewState, remote: RemoteSessionInfo): ReviewState;
768
+ /**
769
+ * Compare a resumed document's recorded `remote-head-sha` with the live
770
+ * head from materialization. Returns `null` when the document recorded no
771
+ * head SHA (nothing to compare).
772
+ */
773
+ declare function computeRemoteDrift(recordedHeadSha: string | undefined, liveHeadSha: string): RemoteDriftInfo | null;
774
+
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;
790
+ now: () => Date;
791
+ }
792
+ interface BuildRemoteReviewStateArgs {
793
+ remoteUrl: string;
794
+ forge: RemoteForge;
795
+ baseSha: string;
796
+ headSha: string;
797
+ diffFiles: DiffFile[];
798
+ comments: ReviewComment[];
799
+ timestamp: string;
800
+ }
801
+ /**
802
+ * Assemble the ReviewState for a fetched remote review. Pure and
803
+ * deterministic: same inputs, same state.
804
+ *
805
+ * Placement rules:
806
+ * - Every diff file gets a file entry in diff order; fetched threads land on
807
+ * their files, in thread order.
808
+ * - Comments whose path is not in the diff (e.g. outdated anchors on files
809
+ * no longer touched) get a synthetic entry with change-type "modified" —
810
+ * the schema requires the attribute and "modified" is the least-claiming
811
+ * value for a file we cannot classify.
812
+ * - Review-level threads (sentinel {@link REVIEW_LEVEL_FILE_PATH}) are
813
+ * folded into a single trailing file entry with the sentinel path: the v3
814
+ * schema requires every <comment> inside a <file path>, and the empty
815
+ * path can never collide with a real diff path, so consumers detect these
816
+ * by comparing against the constant. Omitted when there are none.
817
+ * - Every file is viewed="false": fetch-comments reviews nothing, and a
818
+ * viewed mark claims a human looked at the file. A subsequent
819
+ * --resume-from session therefore starts with the full file list pending.
820
+ * - `source` is `{ type: 'welcome' }`: the remote-* root attributes are the
821
+ * review's source shape, and the three shapes (git, directory, remote)
822
+ * are mutually exclusive by contract, so no local source attributes are
823
+ * serialized.
824
+ */
825
+ declare function buildRemoteReviewState(args: BuildRemoteReviewStateArgs): ReviewState;
826
+ interface FetchCommentsOptions {
827
+ /** Include threads the forge marks resolved (GitLab). Default false. */
828
+ includeResolved?: boolean;
829
+ /** Working directory for clone detection and output resolution. */
830
+ cwd?: string;
831
+ /** Test seams; every omitted member falls back to the real default. */
832
+ deps?: Partial<FetchCommentsDeps>;
833
+ }
834
+ /**
835
+ * Run the headless fetch-comments flow end to end. Throws on any failure
836
+ * (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.
838
+ */
839
+ declare function runFetchComments(url: string, options?: FetchCommentsOptions): Promise<void>;
840
+
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 };