@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 6,600 lines 247 KB
Raw
1 import * as Cache from "effect/Cache";
2 import * as Cause from "effect/Cause";
3 import * as Clock from "effect/Clock";
4 import * as Data from "effect/Data";
5 import * as Deferred from "effect/Deferred";
6 import * as Digest from "effect/crypto/Digest";
7 import * as SecureRandom from "effect/crypto/SecureRandom";
8 import * as DateTime from "effect/DateTime";
9 import * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Hex from "effect/encoding/Hex";
12 import * as Exit from "effect/Exit";
13 import * as Fiber from "effect/Fiber";
14 import * as FileSystem from "effect/FileSystem";
15 import * as Option from "effect/Option";
16 import * as Path from "effect/Path";
17 import * as PlatformError from "effect/PlatformError";
18 import * as Ref from "effect/Ref";
19 import * as Result from "effect/Result";
20 import * as Schema from "effect/Schema";
21 import * as Schedule from "effect/Schedule";
22 import * as Scope from "effect/Scope";
23 import * as Semaphore from "effect/Semaphore";
24 import * as Stream from "effect/Stream";
25 import { ChildProcess, ChildProcessSpawner } from "effect/process";
26
27 import {
28 GitCommandError,
29 type GitCommandFailureReason,
30 T3_PROJECT_FILE_NAME,
31 type ReviewBranchCommitsInput,
32 type ReviewDiffChangeType,
33 type ReviewDiffFileContentsInput,
34 type ReviewDiffPreviewInput,
35 type ReviewDiffFileStat,
36 type ReviewDiffPreviewSource,
37 type VcsRef,
38 } from "@t3tools/contracts";
39 import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
40 import * as HostProcess from "@t3tools/shared/HostProcess";
41 import { compactTraceAttributes } from "@t3tools/shared/observability";
42 import { decodeJsonResult } from "@t3tools/shared/schemaJson";
43 import { resolveSpawnCommand, runsGitWithoutConsole } from "@t3tools/shared/shell";
44 import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
45 import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings";
46 import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
47 import * as GitVcsDriver from "./GitVcsDriver.ts";
48 import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts";
49 import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts";
50 import {
51 explicitBareRepositoryEnv,
52 gitConfigEnv,
53 unsetInheritedRepositoryEnv,
54 } from "./VcsProcess.ts";
55 import { makeWorktreeCheckoutCache } from "./worktreeCheckoutCache.ts";
56 import { removeLinkedWorktree } from "./worktreeRemoval.ts";
57 import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";
58 import {
59 parseRemoteNames,
60 parseRemoteNamesInGitOrder,
61 parseRemoteRefWithRemoteNames,
62 } from "../git/remoteRefs.ts";
63 import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
64 import * as ServerConfig from "../config.ts";
65 import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
66
67 const DEFAULT_TIMEOUT_MS = 30_000;
68 /** T3's record of the branch, named as on the host, that a branch was cut from. */
69 const branchBaseConfigKey = (branch: string) => `branch.${branch}.t3-merge-base`;
70 /**
71 * Where T3 kept that record before it had a key of its own, for every host alike: the GitHub
72 * CLI's key, which branches cut before then still carry instead.
73 */
74 const legacyBranchBaseConfigKey = (branch: string) => `branch.${branch}.gh-merge-base`;
75 // Differently named upstreams are bases, not publish targets; pushing HEAD there would write features to shared branches.
76 const isAliasOfUpstreamHead = (branch: string, upstreamBranch: string, upstreamRef: string) =>
77 branch === upstreamBranch ||
78 (branch.endsWith(`/${upstreamBranch}`) && upstreamRef.endsWith(`/${branch}`));
79 const gitProcesses = Semaphore.makeUnsafe(8);
80 const backgroundGitProcesses = Semaphore.makeUnsafe(2);
81 // The fetch before `git worktree add` downloads everything the remote gained since
82 // the last fetch; on busy repositories that alone outlasts the 30s default.
83 const FETCH_REMOTE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5));
84 const WORKTREE_INDEX_REFRESH_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5));
85 const WORKTREE_REMOVE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5));
86 const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
87 const REF_SNAPSHOT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
88 const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
89 const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000;
90 const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
91 const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
92 const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
93 const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000;
94 const REVIEW_METADATA_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
95 // Temporary-index git add scales poorly (50k files took ~30 s); report incomplete totals above this cap.
96 const REVIEW_UNTRACKED_MAX_FILES = 5_000;
97 // git diff reads every untracked byte (~5 ms/MB), so larger untracked input stays out of the review index.
98 const REVIEW_UNTRACKED_MAX_BYTES = 256 * 1024 * 1024;
99 // The listing walks the whole untracked tree before the cap applies, so a folder whose listing
100 // failed (too many files, output limit, timeout) is not listed again on every status poll.
101 const UNTRACKED_TOTALS_RETRY_MIN_MS = 60_000;
102 const UNTRACKED_TOTALS_RETRY_MAX_MS = 30 * 60_000;
103 const REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
104 // Git's ident clean step (convert.c ident_to_git): `$Id:` up to the next `$` on the same line.
105 const GIT_IDENT_KEYWORD = /\$Id:[^$\n]*\$/g;
106 const REVIEW_BRANCH_COMMIT_LIMIT = 100;
107 const REVIEW_BRANCH_SUBJECT_LIMIT = 300;
108 const REVIEW_BRANCH_COMMIT_MAX_OUTPUT_BYTES = 128 * 1024;
109 // Client patch parsers require a/ and b/ prefixes; override user diff prefix settings.
110 export const PATCH_RENDER_PREFIX_ARGS = ["--src-prefix=a/", "--dst-prefix=b/"] as const;
111 // Client patch parsers drop blank context lines under diff.suppressBlankEmpty and summaries under diff.submodule.
112 const REVIEW_DIFF_ARGS = [
113 "-c",
114 "diff.suppressBlankEmpty=false",
115 "diff",
116 "--find-renames",
117 "--no-color",
118 "--no-ext-diff",
119 "--no-textconv",
120 "--submodule=short",
121 ...PATCH_RENDER_PREFIX_ARGS,
122 ];
123 const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
124 const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
125 const STATUS_UPSTREAM_FETCH_TIMEOUT = Duration.minutes(5);
126
127 const STATUS_UPSTREAM_REFRESH_FAILURE_BASE_COOLDOWN = Duration.seconds(30);
128 const STATUS_UPSTREAM_REFRESH_FAILURE_MAX_COOLDOWN = Duration.minutes(15);
129 const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
130 const REPOSITORY_PATHS_CACHE_CAPACITY = 2_048;
131 const REPOSITORY_PATHS_CACHE_TTL = Duration.minutes(10);
132 const REPOSITORY_PATHS_REFRESH_COALESCE_TTL = Duration.seconds(5);
133 const NON_REPOSITORY_PATHS_CACHE_TTL = Duration.seconds(1);
134 const LIST_REFS_SNAPSHOT_CACHE_CAPACITY = 64;
135 const LIST_REFS_SNAPSHOT_CACHE_TTL = Duration.minutes(2);
136 const LIST_REFS_REFRESH_COALESCE_TTL = Duration.seconds(5);
137 const LIST_REFS_REFRESH_FAILURE_COOLDOWN = Duration.seconds(30);
138 const STATUS_DEFAULT_BRANCH_CACHE_TTL = Duration.minutes(5);
139 const STATUS_ORIGIN_EXISTS_CACHE_TTL = Duration.minutes(5);
140 const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({
141 GCM_INTERACTIVE: "never",
142 GIT_ASKPASS: "",
143 GIT_TERMINAL_PROMPT: "0",
144 SSH_ASKPASS: "",
145 SSH_ASKPASS_REQUIRE: "never",
146 } satisfies NodeJS.ProcessEnv);
147 const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
148 const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
149 const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitStatusDetails>({
150 isRepo: false,
151 hasOriginRemote: false,
152 isDefaultBranch: false,
153 branch: null,
154 upstreamRef: null,
155 hasWorkingTreeChanges: false,
156 workingTree: { files: [], insertions: 0, deletions: 0 },
157 hasUpstream: false,
158 aheadCount: 0,
159 behindCount: 0,
160 aheadOfDefaultCount: 0,
161 });
162 const NON_REPOSITORY_REMOTE_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitRemoteStatusDetails>({
163 isRepo: false,
164 defaultBranch: null,
165 isDefaultBranch: false,
166 branch: null,
167 upstreamRef: null,
168 hasUpstream: false,
169 aheadCount: 0,
170 behindCount: 0,
171 aheadOfDefaultCount: 0,
172 });
173
174 type TraceTailState = {
175 processedChars: number;
176 remainder: string;
177 };
178
179 class StatusRemoteRefreshCacheKey extends Data.Class<{
180 gitCommonDir: string;
181 remoteName: string;
182 }> {}
183
184 function statusUpstreamRefreshFailureCooldown(consecutiveFailures: number): Duration.Duration {
185 const exponent = Math.max(0, consecutiveFailures - 1);
186 const cooldownMs =
187 Duration.toMillis(STATUS_UPSTREAM_REFRESH_FAILURE_BASE_COOLDOWN) * Math.pow(2, exponent);
188 return Duration.min(Duration.millis(cooldownMs), STATUS_UPSTREAM_REFRESH_FAILURE_MAX_COOLDOWN);
189 }
190
191 class GitRefsSnapshotCacheKey extends Data.Class<{
192 gitCommonDir: string;
193 epoch: number;
194 }> {}
195
196 class GitRefsRefreshCacheKey extends Data.Class<{
197 gitCommonDir: string;
198 generation: number;
199 }> {}
200
201 interface GitRepositoryPaths {
202 readonly gitCommonDir: string;
203 readonly worktreeRoot: string | null;
204 readonly isAtRepositoryRoot: boolean | undefined;
205 readonly currentBranch: string | null;
206 }
207
208 interface GitRefsSnapshot {
209 readonly defaultBranch: string | null;
210 readonly localBranches: ReadonlyArray<VcsRef>;
211 readonly remoteBranches: ReadonlyArray<VcsRef>;
212 readonly hasPrimaryRemote: boolean;
213 }
214
215 interface ExecuteGitOptions {
216 stdin?: string | undefined;
217 timeoutMs?: number | null | undefined;
218 allowNonZeroExit?: boolean | undefined;
219 fallbackErrorDetail?: string | undefined;
220 env?: NodeJS.ProcessEnv | undefined;
221 maxOutputBytes?: number | undefined;
222 appendTruncationMarker?: boolean | undefined;
223 keepLineCallbacksAfterTruncation?: boolean | undefined;
224 progress?: GitVcsDriver.ExecuteGitProgress | undefined;
225 writesSharedConfig?: boolean | undefined;
226 }
227
228 function parseBranchAb(value: string): { ahead: number; behind: number } {
229 const match = value.match(/^\+(\d+)\s+-(\d+)$/);
230 if (!match) return { ahead: 0, behind: 0 };
231 return {
232 ahead: Number(match[1] ?? "0"),
233 behind: Number(match[2] ?? "0"),
234 };
235 }
236
237 function rawChangeType(status: string): ReviewDiffChangeType {
238 switch (status[0]) {
239 case "A":
240 return "new";
241 case "D":
242 return "deleted";
243 case "R":
244 return status === "R100" ? "rename-pure" : "rename-changed";
245 default:
246 return "change";
247 }
248 }
249
250 // Parses `--numstat -z`, optionally preceded by `--raw` records that carry each file's change type.
251 function parseReviewNumstat(stdout: string): ReviewDiffFileStat[] {
252 const fields = stdout.split("\0");
253 const changeTypes = new Map<string, ReviewDiffChangeType>();
254 const files: ReviewDiffFileStat[] = [];
255 for (let index = 0; index < fields.length; index++) {
256 const field = fields[index]!;
257 if (field.startsWith(":")) {
258 const status = field.slice(field.lastIndexOf(" ") + 1);
259 if (/^[RC]/.test(status)) index++;
260 changeTypes.set(fields[++index]!, rawChangeType(status));
261 continue;
262 }
263 const match = /^(\d+|-)\t(\d+|-)\t([\s\S]*)$/.exec(field);
264 if (!match) continue;
265 const previousPath = match[3] === "" ? fields[++index]! : null;
266 const path = previousPath !== null ? fields[++index]! : match[3]!;
267 const changeType = changeTypes.get(path);
268 files.push({
269 path,
270 previousPath,
271 ...(changeType === undefined ? {} : { changeType }),
272 additions: match[1] === "-" ? 0 : Number(match[1]),
273 deletions: match[2] === "-" ? 0 : Number(match[2]),
274 });
275 }
276 return files;
277 }
278
279 // Space-separated fields precede the path in each porcelain v2 record type. The path itself
280 // may contain spaces, so it is everything after them.
281 const PORCELAIN_V2_FIELDS_BEFORE_PATH: Record<string, number> = {
282 "1": 8,
283 "2": 9,
284 u: 10,
285 "?": 1,
286 "!": 1,
287 };
288
289 function parsePorcelainPath(record: string): string | null {
290 const fieldsBeforePath = PORCELAIN_V2_FIELDS_BEFORE_PATH[record[0] ?? ""];
291 if (fieldsBeforePath === undefined) return null;
292 const filePath = record.split(" ").slice(fieldsBeforePath).join(" ");
293 return filePath.length > 0 ? filePath : null;
294 }
295
296 function filterBranchesForListQuery(
297 refs: ReadonlyArray<VcsRef>,
298 query?: string,
299 ): ReadonlyArray<VcsRef> {
300 if (!query) {
301 return refs;
302 }
303
304 const normalizedQuery = query.toLowerCase();
305 return refs.filter((refName) => refName.name.toLowerCase().includes(normalizedQuery));
306 }
307
308 function paginateBranches(input: {
309 refs: ReadonlyArray<VcsRef>;
310 cursor?: number | undefined;
311 limit?: number | undefined;
312 }): {
313 refs: ReadonlyArray<VcsRef>;
314 nextCursor: number | null;
315 totalCount: number;
316 } {
317 const cursor = input.cursor ?? 0;
318 const limit = input.limit ?? GIT_LIST_BRANCHES_DEFAULT_LIMIT;
319 const totalCount = input.refs.length;
320 const refs = input.refs.slice(cursor, cursor + limit);
321 const nextCursor = cursor + refs.length < totalCount ? cursor + refs.length : null;
322
323 return {
324 refs,
325 nextCursor,
326 totalCount,
327 };
328 }
329
330 function parseWorktreeBranchPaths(stdout: string): ReadonlyMap<string, string> {
331 const worktreePaths = new Map<string, string>();
332 let currentPath: string | null = null;
333 let currentBranch: string | null = null;
334 let currentPrunable = false;
335
336 const flush = () => {
337 if (currentPath !== null && currentBranch !== null && !currentPrunable) {
338 worktreePaths.set(currentBranch, currentPath);
339 }
340 currentPath = null;
341 currentBranch = null;
342 currentPrunable = false;
343 };
344
345 for (const field of stdout.split("\0")) {
346 if (field === "") {
347 flush();
348 } else if (field.startsWith("worktree ")) {
349 currentPath = field.slice("worktree ".length);
350 } else if (field.startsWith("branch refs/heads/")) {
351 currentBranch = field.slice("branch refs/heads/".length);
352 } else if (field === "prunable" || field.startsWith("prunable ")) {
353 currentPrunable = true;
354 }
355 }
356 flush();
357
358 return worktreePaths;
359 }
360
361 function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
362 const parts = input.split("\0");
363 if (parts.length === 0) return [];
364
365 if (truncated && parts[parts.length - 1]?.length) {
366 parts.pop();
367 }
368
369 return parts.filter((value) => value.length > 0);
370 }
371
372 // Parses "git version 2.24.3 (Apple Git-128)" or "git version 2.45.1.windows.1".
373 const gitSupportsPathspecFromFile = (versionOutput: string): boolean => {
374 const match = /^git version (\d+)\.(\d+)/.exec(versionOutput);
375 if (match === null) return false;
376 const major = Number(match[1]);
377 return major > 2 || (major === 2 && Number(match[2]) >= 25);
378 };
379
380 export function splitNullSeparatedGitStdoutPaths(
381 result: Pick<GitVcsDriver.ExecuteGitResult, "stdout" | "stdoutTruncated">,
382 ): string[] {
383 return splitNullSeparatedPaths(result.stdout, result.stdoutTruncated);
384 }
385
386 // Checkout/worktree add parse leading dashes as options; pre-2.44 Git cannot guard with --end-of-options.
387 // A lone - still means previous checkout.
388 const refuseOptionLikeRefName = (operation: string, cwd: string, refName: string | undefined) =>
389 refName !== undefined && refName !== "-" && refName.startsWith("-")
390 ? Effect.fail(
391 new GitCommandError({
392 operation,
393 command: "git",
394 cwd,
395 detail: "Ref names cannot start with '-'.",
396 }),
397 )
398 : Effect.void;
399
400 function sanitizeRemoteName(value: string): string {
401 const sanitized = value
402 .trim()
403 .replace(/[^A-Za-z0-9._-]+/g, "-")
404 .replace(/^-+|-+$/g, "");
405 return sanitized.length > 0 ? sanitized : "fork";
406 }
407
408 function parseRemoteFetchUrls(stdout: string): Map<string, string> {
409 const remotes = new Map<string, string>();
410 for (const line of stdout.split(/\r?\n/)) {
411 // Git uses a tab before the URL and one space before the direction; both can occur in URLs.
412 // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
413 const match = /^(\S+)\t(.+) \((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(line);
414 if (!match) continue;
415 const [, remoteName = "", remoteUrl = "", direction = ""] = match;
416 if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) {
417 continue;
418 }
419 remotes.set(remoteName, remoteUrl);
420 }
421 return remotes;
422 }
423
424 function parseUpstreamRefWithRemoteNames(
425 upstreamRef: string,
426 remoteNames: ReadonlyArray<string>,
427 ): { upstreamRef: string; remoteName: string; branchName: string } | null {
428 const parsed = parseRemoteRefWithRemoteNames(upstreamRef, remoteNames);
429 if (!parsed) {
430 return null;
431 }
432
433 return {
434 upstreamRef,
435 remoteName: parsed.remoteName,
436 branchName: parsed.branchName,
437 };
438 }
439
440 function parseUpstreamRefByFirstSeparator(
441 upstreamRef: string,
442 ): { upstreamRef: string; remoteName: string; branchName: string } | null {
443 const separatorIndex = upstreamRef.indexOf("/");
444 if (separatorIndex <= 0 || separatorIndex === upstreamRef.length - 1) {
445 return null;
446 }
447
448 const remoteName = upstreamRef.slice(0, separatorIndex).trim();
449 const branchName = upstreamRef.slice(separatorIndex + 1).trim();
450 if (remoteName.length === 0 || branchName.length === 0) {
451 return null;
452 }
453
454 return {
455 upstreamRef,
456 remoteName,
457 branchName,
458 };
459 }
460
461 function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
462 for (const line of stdout.split("\n")) {
463 const trimmedLine = line.trim();
464 if (trimmedLine.length === 0) {
465 continue;
466 }
467 const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
468 const branchName = branchNameRaw?.trim() ?? "";
469 const candidateUpstreamRef = upstreamBranchRaw.trim();
470 if (branchName.length === 0 || candidateUpstreamRef.length === 0) {
471 continue;
472 }
473 if (candidateUpstreamRef === upstreamRef) {
474 return branchName;
475 }
476 }
477
478 return null;
479 }
480
481 function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null {
482 const separatorIndex = branchName.indexOf("/");
483 if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) {
484 return null;
485 }
486 const localBranch = branchName.slice(separatorIndex + 1).trim();
487 return localBranch.length > 0 ? localBranch : null;
488 }
489
490 function gitCommandContext(
491 input: Pick<GitVcsDriver.ExecuteGitInput, "operation" | "cwd" | "args">,
492 ) {
493 return {
494 operation: input.operation,
495 command: "git",
496 cwd: input.cwd,
497 argumentCount: input.args.length,
498 } as const;
499 }
500
501 // Stderr can echo credentials from argv/URLs; classify fixed patterns without exposing matched text.
502 const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray<readonly [RegExp, GitCommandFailureReason]> = [
503 [/would clobber existing tag/i, "tag_would_be_clobbered"],
504 [/is already (?:used by worktree at|checked out at)/i, "branch_checked_out_in_worktree"],
505 [/a branch named .+ already exists/i, "branch_already_exists"],
506 // A ref cannot nest under an existing ref, nor contain one.
507 [/'refs\/[^'\n]+' exists; cannot create 'refs\//i, "ref_name_conflict"],
508 // The same prefix also reports permission errors, which retrying cannot fix.
509 [/could not lock config file .+: File exists/i, "config_locked"],
510 [
511 /(?:authentication failed|could not read Username|could not read Password|permission denied \([a-z-]+(?:,[a-z-]+)*\)|permission denied, please try again)/i,
512 "authentication_failed",
513 ],
514 [/host key verification failed/i, "host_key_unverified"],
515 [
516 /(?:could not read from remote repository|does not appear to be a git repository|repository .+ not found)/i,
517 "remote_unreachable",
518 ],
519 // Unquoted already-exists errors also describe ref/tag collisions; require quoted paths.
520 [/fatal: '[^']+' already exists|destination path .+ already exists/i, "path_already_exists"],
521 // Ambiguous revision/path and pathspec failures can name files, so omit them.
522 // Anchor to a diagnostic line to avoid matching quoted paths in other errors.
523 [
524 /^fatal: (?:invalid reference: |not a valid object name|needed a single revision|bad revision |'.+' is not a commit and a branch '.+' cannot be created from it)/im,
525 "ref_not_found",
526 ],
527 // `[remote rejected]` is only printed for a push. The remote's explanation
528 // follows in parentheses; it is server text, so it is never quoted.
529 [/^[ \t]*![ \t]+\[remote rejected\]/im, "push_rejected_by_remote"],
530 // A fetch into a diverged local branch prints the same `[rejected]` line, but
531 // only a push goes on to report "failed to push some refs".
532 [
533 /^[ \t]*![ \t]+\[rejected\][^\n]*\((?:non-fast-forward|fetch first)\)[\s\S]*^error: failed to push some refs/im,
534 "push_rejected_non_fast_forward",
535 ],
536 ];
537
538 // Reasons the user can act on get a sentence in place of the generic detail.
539 const GIT_FAILURE_REASON_DETAILS: Partial<Record<GitCommandFailureReason, string>> = {
540 push_rejected_by_remote:
541 "The remote rejected the push. Push this branch from a terminal to see the server's message.",
542 push_rejected_non_fast_forward:
543 "The remote has commits this branch doesn't have. Pull or rebase, then push again.",
544 config_locked:
545 "Another Git process kept the repository's config locked. Wait for it to finish, then retry.",
546 };
547
548 function gitFailureDetail(reason: GitCommandFailureReason | null): string {
549 return (
550 (reason === null ? undefined : GIT_FAILURE_REASON_DETAILS[reason]) ??
551 "Git command exited with a non-zero status."
552 );
553 }
554
555 // Existing non-commit objects share the missing-ref fatal diagnostic; Git
556 // distinguishes them with a separate error line.
557 const GIT_NOT_A_COMMIT_PATTERN = /^error: .+(?:, not a commit|expected commit type)/im;
558
559 // Trust only Git's diagnostic prefixes: local hooks can write indistinguishable text.
560 // Exclude `remote:` too, since it prefixes remote hook output as well as server diagnostics.
561 const GIT_DIAGNOSTIC_LINE_PATTERN = /^(?:fatal|error):|^!\s|^\s+!\s/;
562 // SSH credential refusals are unprefixed; Git's later generic error would otherwise misclassify them as unreachable.
563 const SSH_TRANSPORT_REFUSAL_PATTERN =
564 /Permission denied \((?:publickey|password|keyboard-interactive)|Permission denied, please try again|Host key verification failed/i;
565
566 function classifyGitFailure(stderr: string): GitCommandFailureReason | null {
567 const diagnostics = stderr
568 .split(/\r?\n/)
569 .filter(
570 (line) =>
571 GIT_DIAGNOSTIC_LINE_PATTERN.test(line) ||
572 (!/^remote:/.test(line) && SSH_TRANSPORT_REFUSAL_PATTERN.test(line)),
573 )
574 .join("\n");
575 if (diagnostics.length === 0) return null;
576 if (isNonRepositoryGitStderr(diagnostics)) return "not_a_repository";
577 for (const [pattern, reason] of GIT_FAILURE_REASON_PATTERNS) {
578 if (!pattern.test(diagnostics)) continue;
579 if (reason === "ref_not_found" && GIT_NOT_A_COMMIT_PATTERN.test(diagnostics)) continue;
580 return reason;
581 }
582 return null;
583 }
584
585 // `--short` and `--abbrev-ref` print `heads/<name>` when a tag shares the branch's name, so
586 // branch reads take the full ref and strip the prefix themselves.
587 function branchNameFromHeadRef(value: string): string | null {
588 const ref = value.trim();
589 return ref.startsWith("refs/heads/") && ref.length > "refs/heads/".length
590 ? ref.slice("refs/heads/".length)
591 : null;
592 }
593
594 function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null {
595 const trimmed = value.trim();
596 const prefix = `refs/remotes/${remoteName}/`;
597 if (!trimmed.startsWith(prefix)) {
598 return null;
599 }
600 const refName = trimmed.slice(prefix.length).trim();
601 return refName.length > 0 && refName !== "HEAD" ? refName : null;
602 }
603
604 function isMissingGitCwdError(error: GitCommandError): boolean {
605 if (!(error.cause instanceof PlatformError.PlatformError)) {
606 return false;
607 }
608
609 const reason = error.cause.reason;
610 if (reason._tag === "NotFound") {
611 return reason.pathOrDescriptor === error.cwd;
612 }
613
614 return (
615 reason._tag === "BadResource" &&
616 reason.pathOrDescriptor === error.cwd &&
617 typeof reason.cause === "object" &&
618 reason.cause !== null &&
619 "code" in reason.cause &&
620 reason.cause.code === "ENOTDIR"
621 );
622 }
623
624 // Git 2.56+ reports a `.git` gitfile pointing nowhere as "gitfile does not point to a valid
625 // repository"; older releases said "not a git repository". Both mean the cwd is not a repository.
626 const NON_REPOSITORY_STDERR_PHRASES = [
627 "not a git repository",
628 "gitfile does not point to a valid repository",
629 ] as const;
630
631 export function isNonRepositoryGitStderr(stderr: string): boolean {
632 const normalized = stderr.toLowerCase();
633 return NON_REPOSITORY_STDERR_PHRASES.some((phrase) => normalized.includes(phrase));
634 }
635 const UNTRACKED_FILES_SHOWN_CONFIG_VALUES = new Set(["normal", "all", "true", "yes", "on", "1"]);
636 function untrackedFilesHiddenByConfig(value: string | null): boolean {
637 return value !== null && !UNTRACKED_FILES_SHOWN_CONFIG_VALUES.has(value.toLowerCase());
638 }
639 function isUnbornHeadStderr(stderr: string): boolean {
640 const normalized = stderr.toLowerCase();
641 return (
642 normalized.includes("bad revision 'head'") ||
643 (normalized.includes("unknown revision") && normalized.includes("path not in the working tree"))
644 );
645 }
646
647 // Git reports missing worktree registrations and registered-but-deleted paths differently.
648 function isMissingWorktreeStderr(stderr: string): boolean {
649 const normalized = stderr.toLowerCase();
650 return (
651 normalized.includes("is not a working tree") ||
652 normalized.includes("cannot remove working tree")
653 );
654 }
655
656 // Fetch stderr can carry credentials; persist only fixed diagnoses or generic failures.
657 function fetchFailureDetail(stderr: string): string | undefined {
658 const lines = stderr.split(/\r?\n/).map((line) => line.trim());
659 if (
660 lines.some((line) =>
661 /^(?:fatal: (?:Authentication failed|could not read (?:Username|Password))\b|\S+: Permission denied \(publickey)/i.test(
662 line,
663 ),
664 )
665 ) {
666 return "Git could not authenticate with the remote. Check Git credentials or SSH access on the server, then retry.";
667 }
668 if (
669 lines.some((line) =>
670 /^(?:(?:fatal: |ssh: )?Could not resolve host(?:name)?\b|fatal: unable to access .+: (?:Could not resolve host|Failed to connect)\b|ssh: connect to host \S+ port \d+: (?:Connection timed out|Connection refused|Network is unreachable)\b)/i.test(
671 line,
672 ),
673 )
674 ) {
675 return "Git could not reach the remote. Check the server's network connection and remote host, then retry.";
676 }
677 if (
678 lines.some((line) =>
679 /^(?:remote: Repository not found\.?$|fatal: repository .+ not found$|fatal: .+ does not appear to be a git repository$)/i.test(
680 line,
681 ),
682 )
683 ) {
684 return "Git could not access the remote repository. Check the remote URL and repository permissions on the server.";
685 }
686 if (isRefLockFailure(stderr)) {
687 return "Git could not update a local reference. Another Git operation or a stale lock may be blocking the fetch; check the repository on the server, then retry.";
688 }
689 if (lines.some((line) => /^fatal: bad object refs\//i.test(line))) {
690 return "Git found a broken local ref. Check the local repository on the server for a damaged or stray ref, then retry.";
691 }
692 return undefined;
693 }
694
695 // Git 2.53+ reports ref races as fetching-ref failures; older versions say cannot lock ref.
696 function isRefLockFailure(stderr: string): boolean {
697 return stderr
698 .split(/\r?\n/)
699 .some((line) =>
700 /^(?:(?:error|fatal): cannot lock ref\b|fatal: Unable to create ['"].+\.lock['"]:|error: fetching ref \S+ failed: (?:incorrect old value provided|reference already exists)$)/i.test(
701 line.trim(),
702 ),
703 );
704 }
705
706 interface Trace2Monitor {
707 readonly env: NodeJS.ProcessEnv;
708 readonly flush: Effect.Effect<void, never>;
709 }
710
711 const nowUnixNano = DateTime.now.pipe(
712 Effect.map((now) => BigInt(DateTime.toEpochMillis(now)) * 1_000_000n),
713 );
714
715 const addCurrentSpanEvent =
716 /* This helper annotates the existing operation span. */
717 Effect.fnUntraced(
718 function* (name: string, attributes: Record<string, unknown>) {
719 const span = yield* Effect.currentSpan;
720 const timestamp = yield* nowUnixNano;
721 yield* Effect.sync(() => {
722 span.event(name, timestamp, compactTraceAttributes(attributes));
723 });
724 },
725 Effect.catchTags({
726 NoSuchElementError: () => Effect.void,
727 }),
728 );
729
730 // Nested Git processes share the trace file but reuse child IDs in their own sessions.
731 function trace2ChildKey(record: Record<string, unknown>): string | null {
732 const childId = record.child_id;
733 if (typeof childId === "number" || typeof childId === "string") {
734 return typeof record.sid === "string" ? `${record.sid}\n${childId}` : String(childId);
735 }
736 const hookName = record.hook_name;
737 return typeof hookName === "string" && hookName.trim().length > 0 ? hookName.trim() : null;
738 }
739
740 const Trace2Record = Schema.Record(Schema.String, Schema.Unknown);
741 const decodeTrace2Record = decodeJsonResult(Trace2Record);
742
743 const createTrace2Monitor = Effect.fnUntraced(function* (
744 input: Pick<GitVcsDriver.ExecuteGitInput, "operation" | "cwd" | "args">,
745 progress: GitVcsDriver.ExecuteGitProgress | undefined,
746 ): Effect.fn.Return<
747 Trace2Monitor,
748 PlatformError.PlatformError,
749 Scope.Scope | FileSystem.FileSystem | Path.Path
750 > {
751 if (!progress?.onHookStarted && !progress?.onHookFinished) {
752 return {
753 env: {},
754 flush: Effect.void,
755 };
756 }
757
758 const fs = yield* FileSystem.FileSystem;
759 const path = yield* Path.Path;
760 const traceFilePath = yield* fs.makeTempFileScoped({
761 prefix: `t3code-git-trace2-${process.pid}-`,
762 suffix: ".json",
763 });
764 const hookStartByChildKey = new Map<string, { hookName: string; startedAtMs: number }>();
765 const traceTailState = yield* Ref.make<TraceTailState>({
766 processedChars: 0,
767 remainder: "",
768 });
769
770 const handleTraceLine = Effect.fn("handleTraceLine")(function* (line: string) {
771 const trimmedLine = line.trim();
772 if (trimmedLine.length === 0) {
773 return;
774 }
775
776 const traceRecord = decodeTrace2Record(trimmedLine);
777 if (Result.isFailure(traceRecord)) {
778 yield* Effect.logDebug(
779 `GitVcsDriver.trace2: failed to parse trace line for ${input.operation} in ${input.cwd} (${input.args.length} arguments)`,
780 traceRecord.failure,
781 );
782 return;
783 }
784
785 const event = traceRecord.success.event;
786 const childKey = trace2ChildKey(traceRecord.success);
787 if (childKey === null) {
788 return;
789 }
790 const started = hookStartByChildKey.get(childKey);
791 const hookNameFromEvent =
792 typeof traceRecord.success.hook_name === "string" ? traceRecord.success.hook_name.trim() : "";
793 const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? "");
794 if (hookName.length === 0) {
795 return;
796 }
797
798 if (event === "child_start") {
799 if (traceRecord.success.child_class !== "hook") {
800 return;
801 }
802 const now = yield* DateTime.now;
803 hookStartByChildKey.set(childKey, { hookName, startedAtMs: DateTime.toEpochMillis(now) });
804 yield* addCurrentSpanEvent("git.hook.started", {
805 hookName,
806 });
807 if (progress.onHookStarted) {
808 yield* progress.onHookStarted(hookName);
809 }
810 return;
811 }
812
813 if (event === "child_exit" && started) {
814 hookStartByChildKey.delete(childKey);
815 const code = traceRecord.success.code;
816 const exitCode = typeof code === "number" && Number.isInteger(code) ? code : null;
817 const now = yield* DateTime.now;
818 const durationMs = Math.max(0, DateTime.toEpochMillis(now) - started.startedAtMs);
819 yield* addCurrentSpanEvent("git.hook.finished", {
820 hookName: started.hookName,
821 exitCode,
822 durationMs,
823 });
824 if (progress.onHookFinished) {
825 yield* progress.onHookFinished({
826 hookName: started.hookName,
827 exitCode,
828 durationMs,
829 });
830 }
831 }
832 });
833
834 const deltaMutex = yield* Semaphore.make(1);
835 const readTraceDelta = deltaMutex.withPermit(
836 fs.readFileString(traceFilePath).pipe(
837 Effect.flatMap((contents) =>
838 Effect.uninterruptible(
839 Ref.modify(traceTailState, ({ processedChars, remainder }) => {
840 if (contents.length <= processedChars) {
841 return [[], { processedChars, remainder }];
842 }
843
844 const appended = contents.slice(processedChars);
845 const combined = remainder + appended;
846 const lines = combined.split("\n");
847 const nextRemainder = lines.pop() ?? "";
848
849 return [
850 lines.map((line) => line.replace(/\r$/, "")),
851 {
852 processedChars: contents.length,
853 remainder: nextRemainder,
854 },
855 ];
856 }).pipe(
857 Effect.flatMap((lines) => Effect.forEach(lines, handleTraceLine, { discard: true })),
858 ),
859 ),
860 ),
861 Effect.ignore({ log: true }),
862 ),
863 );
864 const traceFileName = path.basename(traceFilePath);
865 yield* Stream.runForEach(fs.watch(traceFilePath), (event) => {
866 const eventPath = event.path;
867 const isTargetTraceEvent =
868 eventPath === traceFilePath ||
869 eventPath === traceFileName ||
870 path.basename(eventPath) === traceFileName;
871 if (!isTargetTraceEvent) return Effect.void;
872 return readTraceDelta;
873 }).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);
874
875 const finalizeTrace2Monitor = Effect.fn("finalizeTrace2Monitor")(function* () {
876 yield* readTraceDelta;
877 const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [
878 remainder.trim(),
879 {
880 processedChars,
881 remainder: "",
882 },
883 ]);
884 if (finalLine.length > 0) {
885 yield* handleTraceLine(finalLine);
886 }
887 });
888
889 yield* Effect.addFinalizer(finalizeTrace2Monitor);
890
891 return {
892 env: {
893 GIT_TRACE2_EVENT: traceFilePath,
894 },
895 flush: readTraceDelta,
896 };
897 });
898
899 const GIT_CHECKOUT_PROGRESS_LINE = /Updating files:\s+(\d+)%\s+\((\d+)\/(\d+)\)/;
900
901 export function parseGitCheckoutProgressLine(
902 line: string,
903 ): { percent: number; completed: number; total: number } | null {
904 const match = GIT_CHECKOUT_PROGRESS_LINE.exec(line);
905 if (!match) return null;
906 const percent = Number(match[1]);
907 const completed = Number(match[2]);
908 const total = Number(match[3]);
909 if (!Number.isFinite(percent) || !Number.isFinite(completed) || !Number.isFinite(total)) {
910 return null;
911 }
912 return { percent: Math.max(0, Math.min(100, percent)), completed, total };
913 }
914
915 const OUTPUT_LINE_SEPARATOR = /\r\n|\r|\n/;
916
917 const collectOutput = Effect.fnUntraced(function* (
918 input: Pick<GitVcsDriver.ExecuteGitInput, "operation" | "cwd" | "args">,
919 stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
920 maxOutputBytes: number,
921 appendTruncationMarker: boolean,
922 onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
923 keepLineCallbacksAfterTruncation = false,
924 ): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> {
925 const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
926 const lineDecoder = keepLineCallbacksAfterTruncation && onLine ? new TextDecoder() : null;
927 let bytes = 0;
928 let text = "";
929 let lineBuffer = "";
930 let truncated = false;
931 // Bound newline-free output; oversized lines are not useful to callbacks.
932 const maxPendingLineBytes = 64 * 1024;
933
934 // Git redraws progress with bare CR; treat it as a line break.
935 const emitCompleteLines = Effect.fnUntraced(function* (flush: boolean) {
936 let separator = OUTPUT_LINE_SEPARATOR.exec(lineBuffer);
937 while (separator) {
938 const line = lineBuffer.slice(0, separator.index);
939 lineBuffer = lineBuffer.slice(separator.index + separator[0].length);
940 if (line.length > 0 && onLine) {
941 yield* onLine(line);
942 }
943 separator = OUTPUT_LINE_SEPARATOR.exec(lineBuffer);
944 }
945
946 if (flush) {
947 const trailing = lineBuffer;
948 lineBuffer = "";
949 if (trailing.length > 0 && onLine) {
950 yield* onLine(trailing);
951 }
952 }
953 });
954
955 const processChunk = Effect.fnUntraced(function* (chunk: Uint8Array) {
956 if (appendTruncationMarker && truncated) {
957 if (lineDecoder) {
958 lineBuffer += lineDecoder.decode(chunk, { stream: true });
959 yield* emitCompleteLines(false);
960 if (lineBuffer.length > maxPendingLineBytes) lineBuffer = "";
961 }
962 return;
963 }
964 const nextBytes = bytes + chunk.byteLength;
965 if (!appendTruncationMarker && nextBytes > maxOutputBytes) {
966 return yield* new GitCommandError({
967 ...gitCommandContext(input),
968 detail: `Git output exceeded ${maxOutputBytes} bytes and was truncated.`,
969 outputLength: nextBytes,
970 });
971 }
972
973 const chunkToDecode =
974 appendTruncationMarker && nextBytes > maxOutputBytes
975 ? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes))
976 : chunk;
977 bytes += chunkToDecode.byteLength;
978 truncated = appendTruncationMarker && nextBytes > maxOutputBytes;
979
980 const decoded = decoder.decode(chunkToDecode, { stream: !truncated });
981 text += decoded;
982 if (onLine) {
983 lineBuffer += lineDecoder ? lineDecoder.decode(chunk, { stream: true }) : decoded;
984 yield* emitCompleteLines(false);
985 }
986 });
987
988 yield* Stream.runForEach(stream, processChunk).pipe(
989 Effect.catchTags({
990 PlatformError: (cause) =>
991 new GitCommandError({
992 ...gitCommandContext(input),
993 detail: "Failed to read Git process output.",
994 cause,
995 }),
996 }),
997 );
998
999 const remainder = truncated ? "" : decoder.decode();
1000 text += remainder;
1001 if (onLine) {
1002 lineBuffer += remainder;
1003 if (lineDecoder) lineBuffer += lineDecoder.decode();
1004 yield* emitCompleteLines(true);
1005 }
1006 return {
1007 text,
1008 truncated,
1009 };
1010 });
1011
1012 /** Windows Git needs core.longpaths beyond MAX_PATH (260); OS LongPathsEnabled alone is insufficient. */
1013 export const windowsLongPathConfigEnv = (
1014 platform: NodeJS.Platform,
1015 env: NodeJS.ProcessEnv,
1016 ): NodeJS.ProcessEnv =>
1017 platform === "win32" ? gitConfigEnv(env, "core.longpaths", "true", platform) : {};
1018
1019 export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* () {
1020 const fileSystem = yield* FileSystem.FileSystem;
1021 const path = yield* Path.Path;
1022 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1023 const { worktreesDir, worktreeCheckoutCacheDir } = yield* ServerConfig.ServerConfig;
1024 const isServerInternalPath = yield* makeIsServerInternalPath;
1025 const digest = yield* Digest.Digest;
1026 const random = yield* SecureRandom.SecureRandom;
1027 const hostPlatform = yield* HostProcess.Platform;
1028 const serviceScope = yield* Effect.scope;
1029 const automaticFetchInterval = yield* VcsAutomaticFetchInterval;
1030 type StatusFetchState = {
1031 phase: "queued" | "running" | "claimed";
1032 claimed: Deferred.Deferred<void>;
1033 finished: Deferred.Deferred<boolean>;
1034 };
1035 const statusFetches = new Map<
1036 string,
1037 {
1038 state: StatusFetchState;
1039 fiber: Fiber.Fiber<void, GitCommandError>;
1040 }
1041 >();
1042 const statusFetchProcesses = yield* Semaphore.make(4);
1043
1044 const executeRaw: GitVcsDriver.GitVcsDriver["Service"]["execute"] = Effect.fnUntraced(
1045 function* (input) {
1046 const commandInput = {
1047 ...input,
1048 args: [...input.args],
1049 } as const;
1050 const timeoutMs = input.timeoutMs === undefined ? DEFAULT_TIMEOUT_MS : input.timeoutMs;
1051 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
1052 const appendTruncationMarker = input.appendTruncationMarker ?? false;
1053
1054 const runGitCommand = Effect.fn("runGitCommand")(function* () {
1055 const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe(
1056 Effect.provideService(Path.Path, path),
1057 Effect.provideService(FileSystem.FileSystem, fileSystem),
1058 Effect.mapError(
1059 (cause) =>
1060 new GitCommandError({
1061 ...gitCommandContext(commandInput),
1062 detail: "Failed to create Git trace monitor.",
1063 cause,
1064 }),
1065 ),
1066 );
1067 const hostEnv = yield* HostProcess.Environment;
1068 const baseEnv = {
1069 ...hostEnv,
1070 ...unsetInheritedRepositoryEnv(hostEnv, hostPlatform),
1071 // Concurrent status polls must not take index.lock to save refreshed indexes.
1072 GIT_OPTIONAL_LOCKS: "0",
1073 ...input.env,
1074 ...trace2Monitor.env,
1075 };
1076 const env = { ...baseEnv, ...explicitBareRepositoryEnv(baseEnv, hostPlatform) };
1077 const spawnEnv = { ...env, ...windowsLongPathConfigEnv(hostPlatform, env) };
1078 const resolved = yield* resolveSpawnCommand("git", [], { env: spawnEnv });
1079 const spawnError = (cause: unknown) =>
1080 new GitCommandError({
1081 ...gitCommandContext(commandInput),
1082 detail: "Failed to spawn Git process.",
1083 cause,
1084 });
1085 // cmd wrappers truncate multiline commits; leave git.cmd handling to Node lookup.
1086 const executable = resolved.shell ? "git" : resolved.command;
1087 const child = yield* commandSpawner
1088 .spawn(
1089 ChildProcess.make(executable, commandInput.args, {
1090 cwd: commandInput.cwd,
1091 env: spawnEnv,
1092 // SIGTERM first lets git remove its lock files; SIGKILL ends one that ignores it.
1093 forceKillAfter: "1 second",
1094 ...(runsGitWithoutConsole(hostPlatform, executable, commandInput.args)
1095 ? { detached: true, windowsHide: true }
1096 : {}),
1097 }),
1098 )
1099 .pipe(
1100 Effect.mapError(spawnError),
1101 // Synchronous spawn throws (such as E2BIG) arrive as defects.
1102 Effect.catchDefect((cause) => Effect.fail(spawnError(cause))),
1103 );
1104
1105 const [stdout, stderr, exitCode] = yield* Effect.all(
1106 [
1107 collectOutput(
1108 commandInput,
1109 child.stdout,
1110 maxOutputBytes,
1111 appendTruncationMarker,
1112 input.progress?.onStdoutLine,
1113 input.keepLineCallbacksAfterTruncation,
1114 ),
1115 collectOutput(
1116 commandInput,
1117 child.stderr,
1118 maxOutputBytes,
1119 appendTruncationMarker,
1120 input.progress?.onStderrLine,
1121 input.keepLineCallbacksAfterTruncation,
1122 ),
1123 child.exitCode.pipe(
1124 Effect.mapError(
1125 (cause) =>
1126 new GitCommandError({
1127 ...gitCommandContext(commandInput),
1128 detail: "Failed to read Git process exit code.",
1129 cause,
1130 }),
1131 ),
1132 ),
1133 input.stdin === undefined
1134 ? Effect.void
1135 : Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(
1136 Effect.mapError(
1137 (cause) =>
1138 new GitCommandError({
1139 ...gitCommandContext(commandInput),
1140 detail: "Failed to write Git process input.",
1141 cause,
1142 }),
1143 ),
1144 ),
1145 ],
1146 { concurrency: "unbounded" },
1147 ).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const));
1148 yield* trace2Monitor.flush;
1149
1150 if (!input.allowNonZeroExit && exitCode !== 0) {
1151 const reason = classifyGitFailure(stderr.text);
1152 return yield* new GitCommandError({
1153 ...gitCommandContext(commandInput),
1154 ...(reason === null ? {} : { reason }),
1155 detail: gitFailureDetail(reason),
1156 exitCode,
1157 stdoutLength: stdout.text.length,
1158 stderrLength: stderr.text.length,
1159 });
1160 }
1161
1162 return {
1163 exitCode,
1164 stdout: stdout.text,
1165 stderr: stderr.text,
1166 stdoutTruncated: stdout.truncated,
1167 stderrTruncated: stderr.truncated,
1168 } satisfies GitVcsDriver.ExecuteGitResult;
1169 });
1170
1171 const execution = runGitCommand().pipe(Effect.scoped);
1172 if (timeoutMs === null) {
1173 return yield* execution;
1174 }
1175
1176 return yield* execution.pipe(
1177 Effect.timeoutOption(timeoutMs),
1178 Effect.flatMap((result) =>
1179 Effect.fromOption(
1180 result,
1181 () =>
1182 new GitCommandError({
1183 ...gitCommandContext(commandInput),
1184 detail: "Git command timed out.",
1185 }),
1186 ),
1187 ),
1188 );
1189 },
1190 );
1191
1192 const sharedConfigLocks = new Map<string, Semaphore.Semaphore>();
1193 const withSharedConfigLock = <A, E>(cwd: string, effect: Effect.Effect<A, E>) =>
1194 resolveRepositoryPaths(cwd).pipe(
1195 Effect.orElseSucceed(() => null),
1196 Effect.flatMap((repositoryPaths) => {
1197 if (repositoryPaths === null) return effect;
1198 let lock = sharedConfigLocks.get(repositoryPaths.gitCommonDir);
1199 if (lock === undefined) {
1200 lock = Semaphore.makeUnsafe(1);
1201 sharedConfigLocks.set(repositoryPaths.gitCommonDir, lock);
1202 }
1203 return lock.withPermit(effect);
1204 }),
1205 );
1206
1207 const execute: GitVcsDriver.GitVcsDriver["Service"]["execute"] = (input) =>
1208 executeRaw(input).pipe(
1209 withMetrics({
1210 counter: gitCommandsTotal,
1211 timer: gitCommandDuration,
1212 attributes: {
1213 operation: input.operation,
1214 },
1215 }),
1216 (execution) =>
1217 input.timeoutMs === null || (input.timeoutMs ?? DEFAULT_TIMEOUT_MS) > DEFAULT_TIMEOUT_MS
1218 ? execution
1219 : Effect.gen(function* () {
1220 const lane = (yield* GitVcsDriver.BackgroundGitWork)
1221 ? backgroundGitProcesses
1222 : gitProcesses;
1223 return yield* lane.withPermits(1)(execution);
1224 }),
1225 Effect.withSpan(input.operation, {
1226 kind: "client",
1227 attributes: {
1228 "git.operation": input.operation,
1229 "git.cwd": input.cwd,
1230 "git.args_count": input.args.length,
1231 },
1232 }),
1233 // Outside the process permit: resolving the repository may itself need one.
1234 (execution) =>
1235 input.writesSharedConfig ? withSharedConfigLock(input.cwd, execution) : execution,
1236 );
1237
1238 const checkoutCache = yield* makeWorktreeCheckoutCache({
1239 cacheDir: worktreeCheckoutCacheDir,
1240 execute,
1241 });
1242
1243 const executeGit = (
1244 operation: string,
1245 cwd: string,
1246 args: readonly string[],
1247 options: ExecuteGitOptions = {},
1248 ): Effect.Effect<GitVcsDriver.ExecuteGitResult, GitCommandError> =>
1249 execute({
1250 operation,
1251 cwd,
1252 args,
1253 ...(options.stdin !== undefined ? { stdin: options.stdin } : {}),
1254 ...(options.env !== undefined ? { env: options.env } : {}),
1255 allowNonZeroExit: true,
1256 ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
1257 ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
1258 ...(options.appendTruncationMarker !== undefined
1259 ? { appendTruncationMarker: options.appendTruncationMarker }
1260 : {}),
1261 ...(options.keepLineCallbacksAfterTruncation
1262 ? { keepLineCallbacksAfterTruncation: true }
1263 : {}),
1264 ...(options.progress ? { progress: options.progress } : {}),
1265 ...(options.writesSharedConfig ? { writesSharedConfig: true } : {}),
1266 }).pipe(
1267 Effect.flatMap((result) => {
1268 if (options.allowNonZeroExit || result.exitCode === 0) {
1269 return Effect.succeed(result);
1270 }
1271 const reason = classifyGitFailure(result.stderr);
1272 return Effect.fail(
1273 new GitCommandError({
1274 ...gitCommandContext({ operation, cwd, args }),
1275 ...(reason === null ? {} : { reason }),
1276 detail: options.fallbackErrorDetail ?? gitFailureDetail(reason),
1277 ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
1278 stdoutLength: result.stdout.length,
1279 stderrLength: result.stderr.length,
1280 }),
1281 );
1282 }),
1283 );
1284
1285 const executeGitWithStableDiagnostics = (
1286 operation: string,
1287 cwd: string,
1288 args: readonly string[],
1289 options: ExecuteGitOptions = {},
1290 ): Effect.Effect<GitVcsDriver.ExecuteGitResult, GitCommandError> =>
1291 executeGit(operation, cwd, args, {
1292 ...options,
1293 env: {
1294 ...options.env,
1295 // English diagnostics without overriding LC_CTYPE, which hooks inherit.
1296 LANGUAGE: "C",
1297 },
1298 });
1299
1300 const runGit = (
1301 operation: string,
1302 cwd: string,
1303 args: readonly string[],
1304 options: ExecuteGitOptions = {},
1305 ): Effect.Effect<void, GitCommandError> =>
1306 executeGit(operation, cwd, args, options).pipe(Effect.asVoid);
1307
1308 const runGitStdout = (
1309 operation: string,
1310 cwd: string,
1311 args: readonly string[],
1312 allowNonZeroExit = false,
1313 ): Effect.Effect<string, GitCommandError> =>
1314 executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(
1315 Effect.map((result) => result.stdout),
1316 );
1317
1318 // Pre-2.36 Git rejects worktree list -z; normalize its line fallback to NUL records.
1319 const executeWorktreeList = Effect.fn("executeWorktreeList")(function* (
1320 operation: string,
1321 cwd: string,
1322 gitArgs: readonly string[],
1323 options: ExecuteGitOptions = {},
1324 ) {
1325 const args = [...gitArgs, "worktree", "list", "--porcelain"];
1326 const result = yield* executeGit(operation, cwd, [...args, "-z"], {
1327 ...options,
1328 allowNonZeroExit: true,
1329 });
1330 if (result.exitCode === 0) return result;
1331 const lineResult = yield* executeGit(operation, cwd, args, options);
1332 return { ...lineResult, stdout: lineResult.stdout.replaceAll("\n", "\0") };
1333 });
1334
1335 const runGitStdoutWithOptions = (
1336 operation: string,
1337 cwd: string,
1338 args: readonly string[],
1339 options: ExecuteGitOptions = {},
1340 ): Effect.Effect<string, GitCommandError> =>
1341 executeGit(operation, cwd, args, options).pipe(
1342 Effect.map((result) =>
1343 result.stdoutTruncated ? `${result.stdout}${OUTPUT_TRUNCATED_MARKER}` : result.stdout,
1344 ),
1345 );
1346
1347 const branchExists = (cwd: string, refName: string): Effect.Effect<boolean, GitCommandError> =>
1348 executeGit(
1349 "GitVcsDriver.branchExists",
1350 cwd,
1351 ["show-ref", "--verify", "--quiet", `refs/heads/${refName}`],
1352 {
1353 allowNonZeroExit: true,
1354 timeoutMs: 5_000,
1355 },
1356 ).pipe(Effect.map((result) => result.exitCode === 0));
1357
1358 const resolveAvailableBranchName = Effect.fn("resolveAvailableBranchName")(function* (
1359 cwd: string,
1360 requestedBranch: string,
1361 ) {
1362 // Exceeding the limit fails the command, so the set is never built from a partial list.
1363 const { stdout } = yield* executeGit(
1364 "GitVcsDriver.resolveAvailableBranchName",
1365 cwd,
1366 ["for-each-ref", "--format=%(refname:strip=2)", "refs/heads/"],
1367 { maxOutputBytes: 16 * 1024 * 1024 },
1368 );
1369 // Reserve case variants too: loose refs can live on case-insensitive filesystems.
1370 const branches = new Set(
1371 stdout
1372 .split("\n")
1373 .filter(Boolean)
1374 .map((name) => name.toLowerCase()),
1375 );
1376 // A branch nested under a name (`t3-fix/child`) blocks it as surely as one with the name.
1377 const blockedNames = new Set(branches);
1378 for (const branch of branches) {
1379 const segments = branch.split("/");
1380 for (let index = 1; index < segments.length; index += 1) {
1381 blockedNames.add(segments.slice(0, index).join("/"));
1382 }
1383 }
1384 // An ancestor ref blocks every suffix beneath it, so flatten to a sibling.
1385 const segments = requestedBranch.split("/");
1386 const blockedByParent = segments.some(
1387 (_, index) => index > 0 && branches.has(segments.slice(0, index).join("/").toLowerCase()),
1388 );
1389 const desiredBranch = blockedByParent ? segments.join("-") : requestedBranch;
1390 if (!blockedNames.has(desiredBranch.toLowerCase())) return desiredBranch;
1391 for (let suffix = 1; suffix <= 100; suffix += 1) {
1392 const candidate = `${desiredBranch}-${suffix}`;
1393 if (!blockedNames.has(candidate.toLowerCase())) return candidate;
1394 }
1395
1396 return yield* new GitCommandError({
1397 ...gitCommandContext({
1398 operation: "GitVcsDriver.renameBranch",
1399 cwd,
1400 args: ["branch", "-m", "--", desiredBranch],
1401 }),
1402 detail: `Could not find an available branch name for '${desiredBranch}'.`,
1403 });
1404 });
1405
1406 // `--abbrev-ref` prints `remotes/origin/<name>` when a local `origin/<name>` branch exists.
1407 const readCurrentUpstreamRef = Effect.fn("readCurrentUpstreamRef")(function* (cwd: string) {
1408 const upstreamRef = yield* runGitStdout(
1409 "GitVcsDriver.resolveCurrentUpstream",
1410 cwd,
1411 ["rev-parse", "--symbolic-full-name", "@{upstream}"],
1412 true,
1413 ).pipe(Effect.map((stdout) => stdout.trim().replace(/^refs\/(?:remotes|heads)\//, "")));
1414
1415 if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
1416 return null;
1417 }
1418 return upstreamRef;
1419 });
1420
1421 const resolveCurrentUpstream = Effect.fn("resolveCurrentUpstream")(function* (
1422 cwd: string,
1423 knownUpstreamRef?: string,
1424 ) {
1425 const upstreamRef = knownUpstreamRef ?? (yield* readCurrentUpstreamRef(cwd));
1426 if (upstreamRef === null) {
1427 return null;
1428 }
1429
1430 const remoteNames = yield* runGitStdout("GitVcsDriver.listRemoteNames", cwd, ["remote"]).pipe(
1431 Effect.map(parseRemoteNames),
1432 Effect.orElseSucceed((): ReadonlyArray<string> => []),
1433 );
1434 return (
1435 parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ??
1436 parseUpstreamRefByFirstSeparator(upstreamRef)
1437 );
1438 });
1439
1440 // Makes Git write new objects to `privateObjects` and read the repository's. Lists every object
1441 // directory Git resolved (`count-objects -v` output) flat, since nesting the repository's objects
1442 // one level deeper can pass Git's depth limit.
1443 const privateObjectDirectoryEnv = (
1444 privateObjects: string,
1445 repositoryObjects: string,
1446 countObjects: string,
1447 ) => {
1448 // Git prints an entry C-quoted when it needs quoting; quote the rest the same way, so a
1449 // path holding the list separator stays one entry (Git 2.11.1+).
1450 const quoted = (entry: string) =>
1451 entry.startsWith('"') ? entry : `"${entry.replace(/[\\"]/g, "\\$&")}"`;
1452 const alternates = [
1453 repositoryObjects,
1454 ...countObjects
1455 .split("\n")
1456 .flatMap((line) =>
1457 line.startsWith("alternate: ") ? [line.slice("alternate: ".length)] : [],
1458 ),
1459 ];
1460 return {
1461 GIT_OBJECT_DIRECTORY: privateObjects,
1462 GIT_ALTERNATE_OBJECT_DIRECTORIES: alternates
1463 .map(quoted)
1464 .join(hostPlatform === "win32" ? ";" : ":"),
1465 } satisfies NodeJS.ProcessEnv;
1466 };
1467
1468 // Moves finished packs and loose objects into the repository, as Git's own quarantine does. A
1469 // pack's index goes last: Git reads a pack as soon as it sees the index.
1470 const adoptPrivateObjects = Effect.fn("GitVcsDriver.adoptPrivateObjects")(function* (
1471 privateObjects: string,
1472 repositoryObjects: string,
1473 ) {
1474 for (const directory of yield* fileSystem.readDirectory(privateObjects)) {
1475 if (directory !== "pack" && !/^[0-9a-f]{2}$/.test(directory)) continue;
1476 const names = (yield* fileSystem.readDirectory(path.join(privateObjects, directory)))
1477 .filter((name) => !name.startsWith("tmp_"))
1478 .toSorted((a, b) => Number(a.endsWith(".idx")) - Number(b.endsWith(".idx")));
1479 if (names.length === 0) continue;
1480 yield* fileSystem.makeDirectory(path.join(repositoryObjects, directory), { recursive: true });
1481 for (const name of names) {
1482 const target = path.join(repositoryObjects, directory, name);
1483 if (yield* fileSystem.exists(target)) continue;
1484 yield* fileSystem.rename(path.join(privateObjects, directory, name), target);
1485 }
1486 }
1487 });
1488
1489 const fetchRemoteForStatus = Effect.fn("GitVcsDriver.fetchRemoteForStatus.wait")(function* (
1490 gitCommonDir: string,
1491 remoteName: string,
1492 ) {
1493 const fetchCwd =
1494 path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
1495 // `--no-auto-gc` (a synonym of `--no-auto-maintenance` that older Git also knows) keeps
1496 // this poll from starting `git gc --auto`. When that gc fails, for example on a repository
1497 // with missing objects, Git retries it on every fetch and leaves a full-size `tmp_pack_*`
1498 // behind each time, so a background poll could fill the disk.
1499 const fetchArgs = (mode: "--dry-run" | "--quiet") => [
1500 "--git-dir",
1501 gitCommonDir,
1502 "fetch",
1503 mode,
1504 "--no-tags",
1505 "--no-auto-gc",
1506 // FETCH_HEAD is written without a lock; overlapping a user's `git pull` makes that pull fail.
1507 "--no-write-fetch-head",
1508 "--",
1509 remoteName,
1510 ];
1511 const objectsPath = path.join(gitCommonDir, "objects");
1512 const fetchOptions = {
1513 fallbackErrorDetail: "Background Git fetch exited with a non-zero status.",
1514 timeoutMs: Duration.toMillis(STATUS_UPSTREAM_FETCH_TIMEOUT),
1515 };
1516 // A failed or killed fetch leaves its partial `tmp_pack_*` behind, and nothing tells it apart
1517 // from another Git process's. So the download goes to a directory only this fetch writes to,
1518 // named like Git's own quarantine so `git gc` prunes one a crash left. A dry run downloads
1519 // without moving refs, which must not point at objects the repository does not hold yet.
1520 const isolatedFetch = Effect.acquireUseRelease(
1521 fileSystem.makeTempDirectory({ directory: objectsPath, prefix: "tmp_objdir-t3code-" }),
1522 Effect.fnUntraced(function* (privateObjects) {
1523 const objectDirectories = yield* runGitStdout(
1524 "GitVcsDriver.fetchRemoteForStatus.alternates",
1525 fetchCwd,
1526 ["--git-dir", gitCommonDir, "count-objects", "-v"],
1527 );
1528 const options = (writableObjects: string) => ({
1529 ...fetchOptions,
1530 env: {
1531 ...STATUS_UPSTREAM_REFRESH_ENV,
1532 ...privateObjectDirectoryEnv(writableObjects, objectsPath, objectDirectories),
1533 },
1534 });
1535 const { stderr } = yield* executeGit(
1536 "GitVcsDriver.fetchRemoteForStatus.download",
1537 fetchCwd,
1538 fetchArgs("--dry-run"),
1539 options(privateObjects),
1540 );
1541 yield* adoptPrivateObjects(privateObjects, objectsPath);
1542 // A dry run names each ref it would move on stderr and is silent when none would.
1543 if (stderr.trim() === "") return;
1544 // This fetch may only move refs to objects the repository now holds. If the remote moved
1545 // on since the dry run it would download, so it gets an object directory where `pack` is
1546 // a file and every transfer is a pack: it then fails, moves nothing, and the next poll
1547 // downloads. Git reports the unreadable `pack` on stderr and carries on.
1548 const sealedObjects = path.join(privateObjects, "sealed");
1549 yield* fileSystem.makeDirectory(sealedObjects);
1550 yield* fileSystem.writeFileString(path.join(sealedObjects, "pack"), "");
1551 yield* executeGit(
1552 "GitVcsDriver.fetchRemoteForStatus",
1553 fetchCwd,
1554 ["-c", "fetch.unpackLimit=1", ...fetchArgs("--quiet")],
1555 options(sealedObjects),
1556 );
1557 }),
1558 (privateObjects) =>
1559 fileSystem
1560 .remove(privateObjects, { recursive: true, force: true })
1561 .pipe(
1562 Effect.catchCause((cause) =>
1563 Effect.logWarning(
1564 "Could not remove a background Git fetch's object directory",
1565 cause,
1566 ),
1567 ),
1568 ),
1569 ).pipe(
1570 Effect.mapError((error) =>
1571 error._tag === "GitCommandError"
1572 ? error
1573 : new GitCommandError({
1574 operation: "GitVcsDriver.fetchRemoteForStatus",
1575 command: "git fetch",
1576 cwd: fetchCwd,
1577 detail: "Background Git fetch could not use its object directory.",
1578 cause: error,
1579 }),
1580 ),
1581 );
1582 const key = `${gitCommonDir}\0${remoteName}`;
1583 const failure = statusRemoteRefreshFailures.get(key);
1584 if (failure && (yield* Clock.currentTimeMillis) < failure.retryAt) return;
1585 const fiber = yield* Effect.uninterruptible(
1586 Effect.gen(function* () {
1587 const pending = statusFetches.get(key);
1588 if (pending) return pending.fiber;
1589 const claimed = yield* Deferred.make<void>();
1590 const finished = yield* Deferred.make<boolean>();
1591 const state: StatusFetchState = { phase: "queued", claimed, finished };
1592 // Frequent poll deadlines and disconnected clients must not interrupt a
1593 // healthy writer. A separate safety limit prevents a hung transport from
1594 // occupying its worker slot indefinitely.
1595 const fetch = isolatedFetch.pipe(
1596 Effect.tap(() =>
1597 Effect.sync(() => {
1598 statusRemoteRefreshFailures.delete(key);
1599 }),
1600 ),
1601 Effect.tapError(() => recordStatusRemoteRefreshFailure(key)),
1602 Effect.tapCause((cause) => Effect.logWarning("Background Git fetch failed", cause)),
1603 );
1604 const started = yield* Effect.raceFirst(
1605 Effect.uninterruptibleMask((restore) =>
1606 Effect.gen(function* () {
1607 if (state.phase !== "queued") return false;
1608 state.phase = "running";
1609 yield* restore(fetch);
1610 return true;
1611 }),
1612 ).pipe(statusFetchProcesses.withPermits(1)),
1613 Deferred.await(claimed).pipe(Effect.as(false)),
1614 ).pipe(
1615 Effect.flatMap((completed) =>
1616 completed
1617 ? Effect.void
1618 : Deferred.await(finished).pipe(
1619 Effect.flatMap((succeeded) =>
1620 succeeded ? Effect.void : fetch.pipe(statusFetchProcesses.withPermits(1)),
1621 ),
1622 ),
1623 ),
1624 Effect.onExit(() =>
1625 Effect.sync(() => {
1626 if (statusFetches.get(key)?.state === state) statusFetches.delete(key);
1627 }),
1628 ),
1629 Effect.forkIn(serviceScope, { startImmediately: false, uninterruptible: false }),
1630 );
1631 statusFetches.set(key, { state, fiber: started });
1632 return started;
1633 }),
1634 );
1635 yield* Effect.annotateCurrentSpan("statusFetch.joining", true);
1636 const result = yield* Fiber.join(fiber).pipe(
1637 Effect.timeoutOption(STATUS_UPSTREAM_REFRESH_TIMEOUT),
1638 );
1639 if (Option.isNone(result)) {
1640 yield* Effect.logDebug(
1641 "Background Git fetch is still running; using the last fetched references.",
1642 );
1643 }
1644 });
1645
1646 const readGitCommonDir = Effect.fn("readGitCommonDir")(function* (cwd: string) {
1647 // Git reports relative paths from the physical cwd, which can differ from a symlink.
1648 const commonDirResult = yield* executeGitWithStableDiagnostics(
1649 "GitVcsDriver.resolveRepositoryPaths.commonDir",
1650 cwd,
1651 ["rev-parse", "--git-common-dir"],
1652 {
1653 timeoutMs: 5_000,
1654 allowNonZeroExit: true,
1655 },
1656 );
1657 if (commonDirResult.exitCode !== 0) {
1658 const stderr = commonDirResult.stderr.trim();
1659 if (isNonRepositoryGitStderr(stderr)) {
1660 return null;
1661 }
1662 return yield* new GitCommandError({
1663 ...gitCommandContext({
1664 operation: "GitVcsDriver.resolveRepositoryPaths.commonDir",
1665 cwd,
1666 args: ["rev-parse", "--git-common-dir"],
1667 }),
1668 detail: "Failed to resolve the Git common directory.",
1669 exitCode: commonDirResult.exitCode,
1670 stdoutLength: commonDirResult.stdout.length,
1671 stderrLength: commonDirResult.stderr.length,
1672 });
1673 }
1674
1675 const commonDirOutput = commonDirResult.stdout.replace(/\n$/, "");
1676 const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd));
1677 const resolvedGitCommonDir = path.isAbsolute(commonDirOutput)
1678 ? path.normalize(commonDirOutput)
1679 : path.resolve(physicalCwd, commonDirOutput);
1680 return yield* fileSystem
1681 .realPath(resolvedGitCommonDir)
1682 .pipe(Effect.orElseSucceed(() => resolvedGitCommonDir));
1683 });
1684
1685 const readWorktreeRoot = Effect.fn("readWorktreeRoot")(function* (cwd: string) {
1686 const result = yield* executeGit(
1687 "GitVcsDriver.resolveRepositoryPaths.worktreeRoot",
1688 cwd,
1689 ["rev-parse", "--show-toplevel"],
1690 {
1691 timeoutMs: 5_000,
1692 allowNonZeroExit: true,
1693 },
1694 );
1695 // Git terminates --show-toplevel with exactly one "\n" on every platform (stdout is
1696 // binary mode on Windows). Whitespace before it belongs to the path and must survive,
1697 // because this root becomes the editor target for every repository-relative status path.
1698 const output = result.stdout.endsWith("\n") ? result.stdout.slice(0, -1) : result.stdout;
1699 return result.exitCode === 0 && output.length > 0
1700 ? path.normalize(path.isAbsolute(output) ? output : path.resolve(cwd, output))
1701 : null;
1702 });
1703
1704 const readCurrentBranch = (operation: string, cwd: string) =>
1705 executeGit(operation, cwd, ["symbolic-ref", "--quiet", "HEAD"], {
1706 timeoutMs: 5_000,
1707 allowNonZeroExit: true,
1708 }).pipe(
1709 Effect.map((result) => (result.exitCode === 0 ? branchNameFromHeadRef(result.stdout) : null)),
1710 );
1711
1712 const resolveRepositoryPathsUncached = Effect.fn("resolveRepositoryPathsUncached")(function* (
1713 cwd: string,
1714 ) {
1715 const gitCommonDir = yield* readGitCommonDir(cwd);
1716 if (gitCommonDir === null) return null;
1717 const [worktreeRoot, currentBranch] = yield* Effect.all(
1718 [
1719 readWorktreeRoot(cwd),
1720 readCurrentBranch("GitVcsDriver.resolveRepositoryPaths.currentBranch", cwd),
1721 ],
1722 { concurrency: 2 },
1723 );
1724 // Git reports physical roots, so resolve project aliases before comparing.
1725 const isAtRepositoryRoot =
1726 worktreeRoot === null
1727 ? undefined
1728 : yield* fileSystem.realPath(cwd).pipe(
1729 Effect.map((physicalCwd) => path.relative(worktreeRoot, physicalCwd) === ""),
1730 Effect.orElseSucceed(() => undefined),
1731 );
1732
1733 return {
1734 gitCommonDir,
1735 worktreeRoot,
1736 isAtRepositoryRoot,
1737 currentBranch,
1738 } satisfies GitRepositoryPaths;
1739 });
1740
1741 const repositoryPathsCache = yield* Cache.makeWith(
1742 (cwd: string) => resolveRepositoryPathsUncached(cwd),
1743 {
1744 capacity: REPOSITORY_PATHS_CACHE_CAPACITY,
1745 timeToLive: Exit.match({
1746 onSuccess: (repositoryPaths) =>
1747 repositoryPaths === null ? NON_REPOSITORY_PATHS_CACHE_TTL : REPOSITORY_PATHS_CACHE_TTL,
1748 onFailure: () => Duration.zero,
1749 }),
1750 },
1751 );
1752 const repositoryPathsRefreshCache = yield* Cache.makeWith(
1753 (cwd: string) =>
1754 Cache.invalidate(repositoryPathsCache, cwd).pipe(
1755 Effect.andThen(Cache.get(repositoryPathsCache, cwd)),
1756 ),
1757 {
1758 capacity: REPOSITORY_PATHS_CACHE_CAPACITY,
1759 timeToLive: Exit.match({
1760 onSuccess: (repositoryPaths) =>
1761 repositoryPaths === null
1762 ? NON_REPOSITORY_PATHS_CACHE_TTL
1763 : REPOSITORY_PATHS_REFRESH_COALESCE_TTL,
1764 onFailure: () => Duration.zero,
1765 }),
1766 },
1767 );
1768 const normalizeRepositoryPathsCacheKey = (cwd: string) => path.normalize(path.resolve(cwd));
1769 const resolveRepositoryPaths = (cwd: string, refresh = false) => {
1770 const cacheKey = normalizeRepositoryPathsCacheKey(cwd);
1771 return Cache.get(refresh ? repositoryPathsRefreshCache : repositoryPathsCache, cacheKey);
1772 };
1773
1774 const resolveReviewRepository = Effect.fn("resolveReviewRepository")(function* (
1775 cwd: string,
1776 needsCurrentBranch: boolean,
1777 ) {
1778 // A cached layout outlives a removed cwd, which must still read as a missing cwd.
1779 if (
1780 !needsCurrentBranch &&
1781 !(yield* fileSystem.exists(cwd).pipe(Effect.orElseSucceed(() => true)))
1782 ) {
1783 return null;
1784 }
1785 const repository = yield* resolveRepositoryPaths(cwd);
1786 if (repository?.worktreeRoot == null) return null;
1787 // The cached branch outlives a checkout made outside T3 Code, so it is read fresh.
1788 const currentBranch = needsCurrentBranch
1789 ? yield* readCurrentBranch("GitVcsDriver.review.currentBranch", cwd)
1790 : null;
1791 return { worktreeRoot: repository.worktreeRoot, currentBranch };
1792 });
1793
1794 const defaultBranchCache = yield* Cache.makeWith(
1795 (gitCommonDir: string) =>
1796 Effect.gen(function* () {
1797 const path = yield* Path.Path;
1798 const fetchCwd =
1799 path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
1800 return yield* resolvePrimaryDefaultBranchName(fetchCwd, ["--git-dir", gitCommonDir]);
1801 }),
1802 {
1803 capacity: 2_048,
1804 timeToLive: Exit.match({
1805 onSuccess: () => STATUS_DEFAULT_BRANCH_CACHE_TTL,
1806 onFailure: () => Duration.zero,
1807 }),
1808 },
1809 );
1810 const primaryRemoteExistsCache = yield* Cache.makeWith(
1811 (gitCommonDir: string) =>
1812 Effect.gen(function* () {
1813 const path = yield* Path.Path;
1814 const fetchCwd =
1815 path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
1816 return yield* executeGit(
1817 "GitVcsDriver.statusDetails.primaryRemoteExists",
1818 fetchCwd,
1819 ["--git-dir", gitCommonDir, "remote"],
1820 { allowNonZeroExit: true },
1821 ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim().length > 0));
1822 }),
1823 {
1824 capacity: 2_048,
1825 timeToLive: Exit.match({
1826 onSuccess: () => STATUS_ORIGIN_EXISTS_CACHE_TTL,
1827 onFailure: () => Duration.zero,
1828 }),
1829 },
1830 );
1831 const invalidateStatusStaticCaches = Effect.fn("GitVcsDriverCore.invalidateStatusStaticCaches")(
1832 function* (cwd: string, gitCommonDir?: string | null) {
1833 const commonDir =
1834 gitCommonDir === undefined
1835 ? yield* readGitCommonDir(cwd).pipe(
1836 Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),
1837 )
1838 : gitCommonDir;
1839 const cacheKey = commonDir ?? normalizeRepositoryPathsCacheKey(cwd);
1840 yield* Cache.invalidate(defaultBranchCache, cacheKey);
1841 yield* Cache.invalidate(primaryRemoteExistsCache, cacheKey);
1842 },
1843 );
1844
1845 const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {
1846 const repositoryPaths = yield* resolveRepositoryPaths(cwd);
1847 if (repositoryPaths !== null) {
1848 return repositoryPaths.gitCommonDir;
1849 }
1850 return yield* new GitCommandError({
1851 ...gitCommandContext({
1852 operation: "GitVcsDriver.resolveGitCommonDir",
1853 cwd,
1854 args: ["rev-parse", "--git-common-dir"],
1855 }),
1856 detail: "Cannot resolve a Git common directory outside a repository.",
1857 });
1858 });
1859
1860 const statusRemoteRefreshFailures = new Map<string, { count: number; retryAt: number }>();
1861 const untrackedTotalsFailures = new Map<
1862 string,
1863 {
1864 readonly roots: string;
1865 readonly count: number;
1866 readonly retryAt: number;
1867 readonly detail: string;
1868 }
1869 >();
1870 // Keyed by cwd: the HEAD and merge base whose totals diff failed, retried after a backoff.
1871 const branchTotalsDiffFailures = new Map<
1872 string,
1873 {
1874 readonly key: string;
1875 readonly count: number;
1876 readonly retryAt: number;
1877 readonly detail: string;
1878 }
1879 >();
1880 const statusRemoteRefreshFailureKey = (cacheKey: StatusRemoteRefreshCacheKey) =>
1881 `${cacheKey.gitCommonDir}\0${cacheKey.remoteName}`;
1882 const recordStatusRemoteRefreshFailure = Effect.fn(
1883 "GitVcsDriver.recordStatusRemoteRefreshFailure",
1884 )(function* (key: string) {
1885 const nextCount = (statusRemoteRefreshFailures.get(key)?.count ?? 0) + 1;
1886 const now = yield* Clock.currentTimeMillis;
1887 statusRemoteRefreshFailures.delete(key);
1888 statusRemoteRefreshFailures.set(key, {
1889 count: nextCount,
1890 retryAt: now + Duration.toMillis(statusUpstreamRefreshFailureCooldown(nextCount)),
1891 });
1892 if (statusRemoteRefreshFailures.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) {
1893 const oldestKey = statusRemoteRefreshFailures.keys().next().value;
1894 if (oldestKey !== undefined) {
1895 statusRemoteRefreshFailures.delete(oldestKey);
1896 }
1897 }
1898 });
1899 const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
1900 cacheKey: StatusRemoteRefreshCacheKey,
1901 ) {
1902 return yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName).pipe(
1903 Effect.as(true as const),
1904 );
1905 });
1906
1907 const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
1908 capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
1909 // Cache/back off failed fetches while status uses old refs; repeated mounts must not cause subprocess storms.
1910 timeToLive: (exit, cacheKey) =>
1911 Exit.isSuccess(exit)
1912 ? STATUS_UPSTREAM_REFRESH_INTERVAL
1913 : statusUpstreamRefreshFailureCooldown(
1914 statusRemoteRefreshFailures.get(statusRemoteRefreshFailureKey(cacheKey))?.count ?? 1,
1915 ),
1916 });
1917
1918 const readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"] = Effect.fn(
1919 "GitVcsDriver.readRefSnapshot",
1920 )(
1921 function* (cwd) {
1922 const result = yield* executeGit(
1923 "GitVcsDriver.readRefSnapshot",
1924 cwd,
1925 ["show-ref", "--head"],
1926 {
1927 allowNonZeroExit: true,
1928 maxOutputBytes: REF_SNAPSHOT_MAX_OUTPUT_BYTES,
1929 },
1930 );
1931 if (result.exitCode !== 0) return null;
1932 const symbolicHead = yield* executeGit(
1933 "GitVcsDriver.readRefSnapshot",
1934 cwd,
1935 ["symbolic-ref", "--quiet", "HEAD"],
1936 { allowNonZeroExit: true },
1937 );
1938 // Exit 1 means detached HEAD; other failures require a full status read.
1939 if (symbolicHead.exitCode !== 0 && symbolicHead.exitCode !== 1) return null;
1940 // Deepening a shallow clone changes ancestry without moving refs.
1941 const shallowPath = path.join(yield* resolveGitCommonDir(cwd), "shallow");
1942 const shallow = (yield* fileSystem.exists(shallowPath))
1943 ? yield* fileSystem.readFileString(shallowPath)
1944 : "";
1945 return `${result.stdout}\0${symbolicHead.stdout}\0${shallow}`;
1946 },
1947 Effect.orElseSucceed(() => null),
1948 );
1949
1950 const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* (
1951 cwd: string,
1952 ) {
1953 if (Duration.isZero(yield* automaticFetchInterval)) return;
1954 const headRef = yield* runGitStdout(
1955 "GitVcsDriver.refreshStatusUpstreamIfStale.headRef",
1956 cwd,
1957 ["symbolic-ref", "--quiet", "HEAD"],
1958 true,
1959 ).pipe(Effect.map((stdout) => stdout.trim()));
1960 if (headRef.length === 0) return;
1961 const remoteName = yield* runGitStdout(
1962 "GitVcsDriver.refreshStatusUpstreamIfStale.upstreamRemote",
1963 cwd,
1964 ["for-each-ref", "--format=%(upstream:remotename)", headRef],
1965 true,
1966 ).pipe(Effect.map((stdout) => stdout.trim()));
1967 // Empty means no upstream; `.` means the upstream is a local branch.
1968 if (remoteName.length === 0 || remoteName === ".") return;
1969 const gitCommonDir = yield* resolveGitCommonDir(cwd);
1970 yield* Cache.get(
1971 statusRemoteRefreshCache,
1972 new StatusRemoteRefreshCacheKey({ gitCommonDir, remoteName }),
1973 ).pipe(Effect.ignore);
1974 if (!(yield* GitVcsDriver.AwaitStatusFetch)) return;
1975 // The cache returns after five seconds while the fetch keeps running.
1976 const pending = statusFetches.get(`${gitCommonDir}\0${remoteName}`);
1977 if (pending) yield* Fiber.await(pending.fiber);
1978 });
1979
1980 const resolveDefaultBranchName = (
1981 cwd: string,
1982 remoteName: string,
1983 gitDirArgs: ReadonlyArray<string> = [],
1984 ): Effect.Effect<string | null, GitCommandError> =>
1985 executeGit(
1986 "GitVcsDriver.resolveDefaultBranchName",
1987 cwd,
1988 // Unlike `symbolic-ref`, this fails when the remote deleted the branch HEAD points at.
1989 [
1990 ...gitDirArgs,
1991 "rev-parse",
1992 "--verify",
1993 "--quiet",
1994 "--symbolic-full-name",
1995 `refs/remotes/${remoteName}/HEAD`,
1996 ],
1997 { allowNonZeroExit: true },
1998 ).pipe(
1999 Effect.map((result) => {
2000 if (result.exitCode !== 0) {
2001 return null;
2002 }
2003 return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName);
2004 }),
2005 );
2006
2007 const remoteBranchExists: GitVcsDriver.GitVcsDriver["Service"]["remoteBranchExists"] = (input) =>
2008 executeGit(
2009 "GitVcsDriver.remoteBranchExists",
2010 input.cwd,
2011 ["show-ref", "--verify", "--quiet", `refs/remotes/${input.remoteName}/${input.refName}`],
2012 {
2013 allowNonZeroExit: true,
2014 },
2015 ).pipe(Effect.map((result) => result.exitCode === 0));
2016
2017 const remoteExists: GitVcsDriver.GitVcsDriver["Service"]["remoteExists"] = (input) =>
2018 executeGit(
2019 "GitVcsDriver.remoteExists",
2020 input.cwd,
2021 ["remote", "get-url", "--", input.remoteName],
2022 {
2023 allowNonZeroExit: true,
2024 },
2025 ).pipe(Effect.map((result) => result.exitCode === 0));
2026
2027 const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
2028 remoteExists({ cwd, remoteName: "origin" });
2029
2030 const listRemoteNames = (
2031 cwd: string,
2032 gitDirArgs: ReadonlyArray<string> = [],
2033 ): Effect.Effect<ReadonlyArray<string>, GitCommandError> =>
2034 runGitStdout("GitVcsDriver.listRemoteNames", cwd, [...gitDirArgs, "remote"]).pipe(
2035 Effect.map(parseRemoteNamesInGitOrder),
2036 );
2037
2038 const resolvePublishBranchName = Effect.fn("resolvePublishBranchName")(function* (
2039 cwd: string,
2040 branchName: string,
2041 ) {
2042 const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.orElseSucceed(() => []));
2043 const parsedRemoteRef = parseRemoteRefWithRemoteNames(branchName, remoteNames);
2044 return parsedRemoteRef?.branchName ?? branchName;
2045 });
2046
2047 // Local-only repositories are normal and status polls them, so the span succeeds with null.
2048 // Callers that need a remote fail in their own span.
2049 const findPrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) {
2050 if (yield* originRemoteExists(cwd)) {
2051 return "origin";
2052 }
2053 const [firstRemote] = yield* listRemoteNames(cwd);
2054 return firstRemote ?? null;
2055 });
2056
2057 const resolvePrimaryDefaultBranchName = Effect.fn("GitVcsDriver.resolvePrimaryDefaultBranchName")(
2058 function* (cwd: string, gitDirArgs: ReadonlyArray<string> = []) {
2059 const originDefault = yield* resolveDefaultBranchName(cwd, "origin", gitDirArgs);
2060 if (originDefault !== null) return originDefault;
2061 const remoteNames = yield* listRemoteNames(cwd, gitDirArgs);
2062 const [firstRemote] = remoteNames;
2063 return firstRemote === undefined || remoteNames.includes("origin")
2064 ? null
2065 : yield* resolveDefaultBranchName(cwd, firstRemote, gitDirArgs);
2066 },
2067 );
2068
2069 const resolvePrimaryRemoteName = (cwd: string) =>
2070 findPrimaryRemoteName(cwd).pipe(
2071 Effect.filterOrFail(
2072 (remoteName): remoteName is string => remoteName !== null,
2073 () =>
2074 new GitCommandError({
2075 ...gitCommandContext({
2076 operation: "GitVcsDriver.resolvePrimaryRemoteName",
2077 cwd,
2078 args: ["remote"],
2079 }),
2080 detail: "No git remote is configured for this repository.",
2081 }),
2082 ),
2083 );
2084
2085 const resolveConfiguredPushRemoteName = Effect.fn("resolveConfiguredPushRemoteName")(function* (
2086 cwd: string,
2087 refName: string,
2088 ) {
2089 const branchPushRemote = yield* runGitStdout(
2090 "GitVcsDriver.resolvePushRemoteName.branchPushRemote",
2091 cwd,
2092 ["config", "--get", `branch.${refName}.pushRemote`],
2093 true,
2094 ).pipe(Effect.map((stdout) => stdout.trim()));
2095 if (branchPushRemote.length > 0) {
2096 return branchPushRemote;
2097 }
2098
2099 const pushDefaultRemote = yield* runGitStdout(
2100 "GitVcsDriver.resolvePushRemoteName.remotePushDefault",
2101 cwd,
2102 ["config", "--get", "remote.pushDefault"],
2103 true,
2104 ).pipe(Effect.map((stdout) => stdout.trim()));
2105 return pushDefaultRemote.length > 0 ? pushDefaultRemote : null;
2106 });
2107
2108 const resolvePushRemoteName = Effect.fn("resolvePushRemoteName")(function* (
2109 cwd: string,
2110 refName: string,
2111 fallbackRemoteName: string | null = null,
2112 ) {
2113 const configuredRemote = yield* resolveConfiguredPushRemoteName(cwd, refName);
2114 if (configuredRemote) {
2115 return configuredRemote;
2116 }
2117
2118 if (fallbackRemoteName) {
2119 return fallbackRemoteName;
2120 }
2121
2122 return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.orElseSucceed(() => null));
2123 });
2124
2125 const remoteRefContainsHead = (cwd: string, remoteRef: string) =>
2126 executeGit(
2127 "GitVcsDriver.pushCurrentBranch.publishContainsHead",
2128 cwd,
2129 ["merge-base", "--is-ancestor", "HEAD", `refs/remotes/${remoteRef}`],
2130 { allowNonZeroExit: true },
2131 ).pipe(
2132 Effect.map((result) => result.exitCode === 0),
2133 Effect.orElseSucceed(() => false),
2134 );
2135
2136 // A fetch reads only the remote's first url, while a push writes every push URL (pushurl, else
2137 // each url). A fetched ref is evidence of the push destination only when those are the same one.
2138 const pushesOnlyToFetchUrl = Effect.fn("GitVcsDriver.pushesOnlyToFetchUrl")(
2139 function* (cwd: string, remoteName: string) {
2140 const [fetchUrl, pushUrls] = yield* Effect.all([
2141 runGitStdout("GitVcsDriver.pushesOnlyToFetchUrl.fetchUrl", cwd, [
2142 "remote",
2143 "get-url",
2144 "--",
2145 remoteName,
2146 ]),
2147 runGitStdout("GitVcsDriver.pushesOnlyToFetchUrl.pushUrls", cwd, [
2148 "remote",
2149 "get-url",
2150 "--push",
2151 "--all",
2152 "--",
2153 remoteName,
2154 ]),
2155 ]);
2156 // Preserve whitespace in URLs and reject ambiguous multiline fetch URLs.
2157 return (
2158 fetchUrl.endsWith("\n") && !fetchUrl.slice(0, -1).includes("\n") && pushUrls === fetchUrl
2159 );
2160 },
2161 Effect.orElseSucceed(() => false),
2162 );
2163
2164 const ensureRemote: GitVcsDriver.GitVcsDriver["Service"]["ensureRemote"] = Effect.fn(
2165 "ensureRemote",
2166 )(function* (input) {
2167 const preferredName = sanitizeRemoteName(input.preferredName);
2168 const normalizedTargetUrl = sourceControlDefinitions.repositoryKeyFromRemote(input.url);
2169 const listRemoteFetchUrls = runGitStdout(
2170 "GitVcsDriver.ensureRemote.listRemoteUrls",
2171 input.cwd,
2172 ["remote", "-v"],
2173 ).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));
2174 const findMatchingRemote = (remoteFetchUrls: Map<string, string>) =>
2175 Array.from(remoteFetchUrls.entries()).find(
2176 ([, remoteUrl]) =>
2177 sourceControlDefinitions.repositoryKeyFromRemote(remoteUrl) === normalizedTargetUrl,
2178 )?.[0];
2179
2180 const remoteFetchUrls = yield* listRemoteFetchUrls;
2181 const existing = findMatchingRemote(remoteFetchUrls);
2182 if (existing !== undefined) return existing;
2183
2184 let remoteName = preferredName;
2185 let suffix = 1;
2186 while (remoteFetchUrls.has(remoteName)) {
2187 remoteName = `${preferredName}-${suffix}`;
2188 suffix += 1;
2189 }
2190
2191 return yield* executeGitWithStableDiagnostics(
2192 "GitVcsDriver.ensureRemote.add",
2193 input.cwd,
2194 ["remote", "add", "--", remoteName, input.url],
2195 { writesSharedConfig: true },
2196 ).pipe(
2197 retryWhileConfigLocked,
2198 Effect.as(remoteName),
2199 // A parallel launch for the same fork may have added it since the listing above.
2200 Effect.catch((error) =>
2201 listRemoteFetchUrls.pipe(
2202 Effect.flatMap((current) => {
2203 const added = findMatchingRemote(current);
2204 return added === undefined ? Effect.fail(error) : Effect.succeed(added);
2205 }),
2206 ),
2207 ),
2208 );
2209 });
2210
2211 const resolveComparisonBaseRef = Effect.fn("resolveComparisonBaseRef")(function* (
2212 cwd: string,
2213 baseRef: string,
2214 ) {
2215 const comparisonRef =
2216 baseRef.startsWith("refs/heads/") || baseRef.startsWith("refs/remotes/")
2217 ? baseRef
2218 : baseRef.includes("/") && !baseRef.startsWith("refs/")
2219 ? `refs/remotes/${baseRef}`
2220 : null;
2221 if (comparisonRef === null) return null;
2222 const resolved = yield* executeGit(
2223 "GitVcsDriver.resolveComparisonBaseRef",
2224 cwd,
2225 ["show-ref", "--verify", "--quiet", comparisonRef],
2226 { allowNonZeroExit: true },
2227 );
2228 return resolved.exitCode === 0 ? { baseRef, comparisonRef } : null;
2229 });
2230
2231 // Tracking may point to a different remote than the primary one. Resolve its
2232 // full ref so a similarly named local branch or tag cannot shadow it.
2233 const resolveTrackedRemoteBaseRef = Effect.fn("resolveTrackedRemoteBaseRef")(function* (
2234 cwd: string,
2235 refName: string,
2236 ) {
2237 const upstream = yield* executeGit(
2238 "GitVcsDriver.resolveTrackedRemoteBaseRef",
2239 cwd,
2240 ["rev-parse", "--symbolic-full-name", `${refName}@{upstream}`],
2241 { allowNonZeroExit: true },
2242 );
2243 const comparisonRef = upstream.stdout.trim();
2244 if (upstream.exitCode !== 0 || !comparisonRef.startsWith("refs/remotes/")) return null;
2245 return { baseRef: comparisonRef.slice("refs/remotes/".length), comparisonRef };
2246 });
2247
2248 const resolveBaseBranchForNoUpstream = Effect.fn("resolveBaseBranchForNoUpstream")(function* (
2249 cwd: string,
2250 refName: string,
2251 options?: {
2252 readonly allowRemoteOfCurrent?: boolean;
2253 readonly knownOriginDefaultBranch?: string | null;
2254 },
2255 ) {
2256 const configuredBaseRef = yield* readConfigValue(cwd, `branch.${refName}.t3-merge-base-ref`);
2257 if (
2258 configuredBaseRef?.startsWith("refs/heads/") ||
2259 configuredBaseRef?.startsWith("refs/remotes/")
2260 ) {
2261 const base = yield* resolveComparisonBaseRef(cwd, configuredBaseRef);
2262 if (base !== null) {
2263 const shortRef = configuredBaseRef.replace(/^refs\/remotes\//, "");
2264 return {
2265 ...base,
2266 baseRef: (yield* branchExists(cwd, shortRef)) ? configuredBaseRef : shortRef,
2267 };
2268 }
2269 }
2270
2271 const configuredBaseBranch = (yield* readBranchBase(cwd, refName)) ?? "";
2272 const configuredBase = yield* resolveComparisonBaseRef(cwd, configuredBaseBranch);
2273 if (
2274 configuredBase !== null &&
2275 configuredBaseBranch.includes("/") &&
2276 !configuredBaseBranch.startsWith("refs/") &&
2277 (yield* branchExists(cwd, configuredBaseBranch))
2278 ) {
2279 const comparisonRef = `refs/heads/${configuredBaseBranch}`;
2280 return { baseRef: comparisonRef, comparisonRef };
2281 }
2282 if (configuredBase !== null) return configuredBase;
2283 if (configuredBaseBranch.length > 0 && configuredBaseBranch !== refName) {
2284 const trackedBase = yield* resolveTrackedRemoteBaseRef(cwd, configuredBaseBranch);
2285 if (trackedBase !== null) return trackedBase;
2286 }
2287
2288 const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe(
2289 Effect.orElseSucceed(() => null),
2290 );
2291 const candidates = [
2292 Effect.succeed(configuredBaseBranch),
2293 primaryRemoteName === null
2294 ? Effect.succeed(null)
2295 : primaryRemoteName === "origin" && options?.knownOriginDefaultBranch != null
2296 ? Effect.succeed(options.knownOriginDefaultBranch)
2297 : resolveDefaultBranchName(cwd, primaryRemoteName),
2298 ...DEFAULT_BASE_BRANCH_CANDIDATES.map(Effect.succeed),
2299 ];
2300
2301 for (const readCandidate of candidates) {
2302 const candidate = yield* readCandidate;
2303 if (!candidate) {
2304 continue;
2305 }
2306
2307 const remotePrefix =
2308 primaryRemoteName && primaryRemoteName !== "origin" ? `${primaryRemoteName}/` : null;
2309 const normalizedCandidate = candidate.startsWith("origin/")
2310 ? candidate.slice("origin/".length)
2311 : remotePrefix && candidate.startsWith(remotePrefix)
2312 ? candidate.slice(remotePrefix.length)
2313 : candidate;
2314 if (normalizedCandidate.length === 0) {
2315 continue;
2316 }
2317 if (normalizedCandidate === refName) {
2318 if (options?.allowRemoteOfCurrent) {
2319 const trackedRemoteBase = yield* resolveTrackedRemoteBaseRef(cwd, refName);
2320 if (trackedRemoteBase !== null) return trackedRemoteBase;
2321 if (
2322 primaryRemoteName &&
2323 (yield* remoteBranchExists({
2324 cwd,
2325 remoteName: primaryRemoteName,
2326 refName: normalizedCandidate,
2327 }))
2328 ) {
2329 return {
2330 baseRef: `${primaryRemoteName}/${normalizedCandidate}`,
2331 comparisonRef: `refs/remotes/${primaryRemoteName}/${normalizedCandidate}`,
2332 };
2333 }
2334 }
2335 continue;
2336 }
2337
2338 if (
2339 primaryRemoteName &&
2340 (yield* remoteBranchExists({
2341 cwd,
2342 remoteName: primaryRemoteName,
2343 refName: normalizedCandidate,
2344 }))
2345 ) {
2346 return {
2347 baseRef: `${primaryRemoteName}/${normalizedCandidate}`,
2348 comparisonRef: `refs/remotes/${primaryRemoteName}/${normalizedCandidate}`,
2349 };
2350 }
2351
2352 if (yield* branchExists(cwd, normalizedCandidate)) {
2353 return { baseRef: normalizedCandidate, comparisonRef: `refs/heads/${normalizedCandidate}` };
2354 }
2355 }
2356
2357 return null;
2358 });
2359
2360 const computeAheadCountAgainstBase = Effect.fn("computeAheadCountAgainstBase")(function* (
2361 cwd: string,
2362 refName: string,
2363 options?: { readonly knownOriginDefaultBranch: string | null },
2364 ) {
2365 const base = yield* resolveBaseBranchForNoUpstream(cwd, refName, options);
2366 if (!base) {
2367 return 0;
2368 }
2369
2370 const result = yield* executeGit(
2371 "GitVcsDriver.computeAheadCountAgainstBase",
2372 cwd,
2373 ["rev-list", "--count", "--end-of-options", `${base.comparisonRef}..HEAD`],
2374 { allowNonZeroExit: true },
2375 );
2376 if (result.exitCode !== 0) {
2377 return 0;
2378 }
2379
2380 const parsed = Number.parseInt(result.stdout.trim(), 10);
2381 return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
2382 });
2383
2384 const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* (cwd: string) {
2385 const branchResult = yield* executeGitWithStableDiagnostics(
2386 "GitVcsDriver.statusDetailsRemote.branch",
2387 cwd,
2388 ["rev-parse", "--symbolic-full-name", "HEAD"],
2389 { allowNonZeroExit: true },
2390 ).pipe(
2391 Effect.catchTags({
2392 GitCommandError: (error) =>
2393 isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error),
2394 }),
2395 );
2396
2397 if (branchResult === null) {
2398 return NON_REPOSITORY_REMOTE_STATUS_DETAILS;
2399 }
2400 let branch: string | null;
2401 if (branchResult.exitCode !== 0) {
2402 if (isNonRepositoryGitStderr(branchResult.stderr)) {
2403 return NON_REPOSITORY_REMOTE_STATUS_DETAILS;
2404 }
2405 if (!isUnbornHeadStderr(branchResult.stderr)) {
2406 return yield* new GitCommandError({
2407 ...gitCommandContext({
2408 operation: "GitVcsDriver.statusDetailsRemote.branch",
2409 cwd,
2410 args: ["rev-parse", "--symbolic-full-name", "HEAD"],
2411 }),
2412 detail: "Git branch lookup failed.",
2413 exitCode: branchResult.exitCode,
2414 stdoutLength: branchResult.stdout.length,
2415 stderrLength: branchResult.stderr.length,
2416 });
2417 }
2418
2419 const branchValue = yield* runGitStdout(
2420 "GitVcsDriver.statusDetailsRemote.unbornBranch",
2421 cwd,
2422 ["symbolic-ref", "--quiet", "HEAD"],
2423 );
2424 branch = branchNameFromHeadRef(branchValue);
2425 } else {
2426 branch = branchNameFromHeadRef(branchResult.stdout);
2427 }
2428 const currentUpstreamRef = yield* readCurrentUpstreamRef(cwd);
2429 let upstreamRef = currentUpstreamRef;
2430 // Trimming a remote that starts with Unicode whitespace can leave a leading slash.
2431 if (currentUpstreamRef?.startsWith("/")) {
2432 upstreamRef = (yield* resolveCurrentUpstream(cwd, currentUpstreamRef))?.upstreamRef ?? null;
2433 }
2434 let aheadCount = 0;
2435 let behindCount = 0;
2436
2437 if (upstreamRef) {
2438 const divergence = yield* executeGit(
2439 "GitVcsDriver.statusDetailsRemote.divergence",
2440 cwd,
2441 ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"],
2442 { allowNonZeroExit: true },
2443 );
2444 if (divergence.exitCode === 0) {
2445 const [aheadRaw, behindRaw] = divergence.stdout.trim().split(/\s+/);
2446 const parsedAhead = Number.parseInt(aheadRaw ?? "0", 10);
2447 const parsedBehind = Number.parseInt(behindRaw ?? "0", 10);
2448 aheadCount = Number.isFinite(parsedAhead) ? Math.max(0, parsedAhead) : 0;
2449 behindCount = Number.isFinite(parsedBehind) ? Math.max(0, parsedBehind) : 0;
2450 }
2451 } else if (branch) {
2452 aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
2453 Effect.orElseSucceed(() => 0),
2454 );
2455 }
2456
2457 const defaultBranch = yield* resolvePrimaryDefaultBranchName(cwd);
2458 const isDefaultBranch =
2459 branch !== null &&
2460 (branch === defaultBranch ||
2461 (defaultBranch === null && (branch === "main" || branch === "master")));
2462 const aheadOfDefaultCount =
2463 branch && !isDefaultBranch
2464 ? upstreamRef === null
2465 ? aheadCount
2466 : yield* computeAheadCountAgainstBase(cwd, branch, {
2467 knownOriginDefaultBranch: defaultBranch,
2468 }).pipe(Effect.orElseSucceed(() => 0))
2469 : 0;
2470
2471 return {
2472 isRepo: true,
2473 defaultBranch,
2474 isDefaultBranch,
2475 branch,
2476 upstreamRef,
2477 hasUpstream: upstreamRef !== null,
2478 aheadCount,
2479 behindCount,
2480 aheadOfDefaultCount,
2481 };
2482 });
2483
2484 const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (
2485 cwd: string,
2486 options?: GitVcsDriver.GitLocalStatusOptions,
2487 ) {
2488 const includeDivergence = options?.includeDivergence !== false;
2489 // Hidden untracked files could not be committed; `all` stays as configured.
2490 const untrackedFilesHidden = untrackedFilesHiddenByConfig(
2491 yield* readConfigValue(cwd, "status.showUntrackedFiles").pipe(
2492 Effect.orElseSucceed(() => null),
2493 ),
2494 );
2495 const statusArgs = [
2496 "status",
2497 "--porcelain=2",
2498 "--branch",
2499 "-z",
2500 ...(untrackedFilesHidden ? ["--untracked-files=normal"] : []),
2501 ...(includeDivergence ? [] : ["--no-ahead-behind"]),
2502 ];
2503 const readPaths = (...args: string[]) =>
2504 executeGitWithStableDiagnostics(
2505 "GitVcsDriver.statusDetails.indexPath",
2506 cwd,
2507 ["rev-parse", ...args],
2508 { allowNonZeroExit: true },
2509 ).pipe(
2510 Effect.catchTags({
2511 GitCommandError: (error) =>
2512 isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error),
2513 }),
2514 );
2515 const paths = yield* readPaths(
2516 "--path-format=absolute",
2517 "--git-path",
2518 "index",
2519 "--git-common-dir",
2520 "--show-toplevel",
2521 );
2522 if (paths === null || (paths.exitCode !== 0 && isNonRepositoryGitStderr(paths.stderr))) {
2523 return NON_REPOSITORY_STATUS_DETAILS;
2524 }
2525 // Older Git may echo the flag. Newlines in paths also require the separate lookups.
2526 const fields = paths.stdout.replace(/\n$/, "").split("\n");
2527 const [index, commonDir, root] =
2528 paths.exitCode === 0 && fields.length === 3 && fields.every(path.isAbsolute) ? fields : [];
2529 const indexResult = index === undefined ? yield* readPaths("--git-path", "index") : undefined;
2530 if (indexResult === null) return NON_REPOSITORY_STATUS_DETAILS;
2531 const indexPath =
2532 index ?? (indexResult?.exitCode === 0 ? indexResult.stdout.replace(/\n$/, "") : undefined);
2533 if (indexPath) {
2534 const lockPath = `${path.resolve(cwd, indexPath)}.lock`;
2535 const lockError = new GitCommandError({
2536 operation: "GitVcsDriver.statusDetails.indexPath",
2537 command: "git",
2538 cwd,
2539 detail: "Git index is locked. Status will resume when the index lock is removed.",
2540 });
2541 // Status can succeed while locked, repeatedly running LFS clean filters without caching.
2542 if (
2543 yield* fileSystem.exists(lockPath).pipe(
2544 Effect.mapError(
2545 (cause) =>
2546 new GitCommandError({
2547 ...lockError,
2548 detail: "Failed to check the Git index lock.",
2549 cause,
2550 }),
2551 ),
2552 )
2553 ) {
2554 return yield* lockError;
2555 }
2556 }
2557 const repositoryPaths =
2558 commonDir && root
2559 ? {
2560 gitCommonDir: yield* fileSystem
2561 .realPath(commonDir)
2562 .pipe(Effect.orElseSucceed(() => path.normalize(commonDir))),
2563 worktreeRoot: path.normalize(root),
2564 }
2565 : yield* resolveRepositoryPaths(cwd).pipe(
2566 Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),
2567 );
2568 const statusCacheKey = repositoryPaths?.gitCommonDir;
2569 const refsGeneration =
2570 statusCacheKey === undefined ? undefined : currentListRefsGeneration(statusCacheKey);
2571 const readStatus = executeGitWithStableDiagnostics(
2572 "GitVcsDriver.statusDetails.status",
2573 cwd,
2574 statusArgs,
2575 {
2576 allowNonZeroExit: true,
2577 maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES,
2578 },
2579 ).pipe(
2580 Effect.catchTags({
2581 GitCommandError: (error) =>
2582 isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error),
2583 }),
2584 );
2585 // Porcelain diff rewrites indexes despite GIT_OPTIONAL_LOCKS=0; plumbing with -M preserves rename detection.
2586 const readNumstat = (ref: string) =>
2587 executeGitWithStableDiagnostics(
2588 "GitVcsDriver.statusDetails.numstat",
2589 cwd,
2590 ["diff-index", "-M", "--numstat", "-z", ref, "--"],
2591 { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES },
2592 );
2593 // diff-index does not read status output, so both spawn together; a non-repository discards it.
2594 const [statusResult, numstatResult, defaultBranch, hasPrimaryRemote] = yield* Effect.all(
2595 [
2596 readStatus,
2597 readNumstat("HEAD").pipe(
2598 Effect.filterOrElse(
2599 (result) => result.exitCode === 0 || !isUnbornHeadStderr(result.stderr),
2600 () => Effect.flatMap(readEmptyTreeHash(cwd), readNumstat),
2601 ),
2602 Effect.flatMap((result) => {
2603 if (result.exitCode === 0) return Effect.succeed(parseReviewNumstat(result.stdout));
2604 return Effect.fail(
2605 new GitCommandError({
2606 ...gitCommandContext({
2607 operation: "GitVcsDriver.statusDetails.numstat",
2608 cwd,
2609 args: ["diff-index", "-M", "--numstat", "-z", "HEAD", "--"],
2610 }),
2611 detail: "git diff-index HEAD --numstat failed.",
2612 exitCode: result.exitCode,
2613 stdoutLength: result.stdout.length,
2614 stderrLength: result.stderr.length,
2615 }),
2616 );
2617 }),
2618 Effect.result,
2619 ),
2620 statusCacheKey
2621 ? Cache.get(defaultBranchCache, statusCacheKey).pipe(Effect.orElseSucceed(() => null))
2622 : resolvePrimaryDefaultBranchName(cwd).pipe(Effect.orElseSucceed(() => null)),
2623 statusCacheKey
2624 ? Cache.get(primaryRemoteExistsCache, statusCacheKey).pipe(
2625 Effect.orElseSucceed(() => false),
2626 )
2627 : listRemoteNames(cwd).pipe(
2628 Effect.map((remoteNames) => remoteNames.length > 0),
2629 Effect.orElseSucceed(() => false),
2630 ),
2631 ],
2632 { concurrency: "unbounded" },
2633 );
2634 if (statusResult === null) {
2635 return NON_REPOSITORY_STATUS_DETAILS;
2636 }
2637
2638 if (statusResult.exitCode !== 0) {
2639 if (isNonRepositoryGitStderr(statusResult.stderr)) {
2640 return NON_REPOSITORY_STATUS_DETAILS;
2641 }
2642 return yield* new GitCommandError({
2643 ...gitCommandContext({
2644 operation: "GitVcsDriver.statusDetails.status",
2645 cwd,
2646 args: statusArgs,
2647 }),
2648 detail: "Git status failed.",
2649 exitCode: statusResult.exitCode,
2650 stdoutLength: statusResult.stdout.length,
2651 stderrLength: statusResult.stderr.length,
2652 });
2653 }
2654
2655 const numstatEntries = yield* Effect.fromResult(numstatResult);
2656 const statusStdout = statusResult.stdout;
2657
2658 let refName: string | null = null;
2659 let upstreamRef: string | null = null;
2660 // Git omits branch.ab when the upstream ref is gone, e.g. deleted after its PR merged,
2661 // and also for an unborn HEAD, which can still track a fetched upstream.
2662 let upstreamRefExists = false;
2663 let isUnbornHead = false;
2664 let headOid: string | null = null;
2665 let aheadCount = 0;
2666 let behindCount = 0;
2667 let aheadOfDefaultCount = 0;
2668 let hasWorkingTreeChanges = false;
2669 const changedFilesWithoutNumstat = new Set<string>();
2670 const untrackedRoots: string[] = [];
2671
2672 const statusRecords = statusStdout.split("\0");
2673 for (let index = 0; index < statusRecords.length; index++) {
2674 const line = statusRecords[index]!;
2675 if (line === "# branch.oid (initial)") {
2676 isUnbornHead = true;
2677 continue;
2678 }
2679 if (line.startsWith("# branch.oid ")) {
2680 headOid = line.slice("# branch.oid ".length).trim();
2681 continue;
2682 }
2683 if (line.startsWith("# branch.head ")) {
2684 const value = line.slice("# branch.head ".length).trim();
2685 // `(unknown)` is printed while HEAD names no resolvable branch, e.g. mid-`git clone`.
2686 refName = value === "(detached)" || value === "(unknown)" ? null : value;
2687 continue;
2688 }
2689 if (line.startsWith("# branch.upstream ")) {
2690 const value = line.slice("# branch.upstream ".length).trim();
2691 upstreamRef = value.length > 0 ? value : null;
2692 continue;
2693 }
2694 if (line.startsWith("# branch.ab ")) {
2695 upstreamRefExists = true;
2696 if (includeDivergence) {
2697 const parsed = parseBranchAb(line.slice("# branch.ab ".length).trim());
2698 aheadCount = parsed.ahead;
2699 behindCount = parsed.behind;
2700 }
2701 continue;
2702 }
2703 if (line.length > 0 && !line.startsWith("#")) {
2704 hasWorkingTreeChanges = true;
2705 const pathValue = parsePorcelainPath(line);
2706 if (pathValue) {
2707 changedFilesWithoutNumstat.add(pathValue);
2708 if (line.startsWith("? ")) untrackedRoots.push(pathValue);
2709 }
2710 // A rename record is followed by its original path as a separate record. Listing it
2711 // keeps the deletion selectable when committing only some files.
2712 if (line.startsWith("2 ")) {
2713 const originalPath = statusRecords[++index];
2714 if (originalPath) changedFilesWithoutNumstat.add(originalPath);
2715 }
2716 }
2717 }
2718
2719 if (commonDir && root && repositoryPaths?.worktreeRoot) {
2720 const { gitCommonDir, worktreeRoot } = repositoryPaths;
2721 const cacheKey = normalizeRepositoryPathsCacheKey(cwd);
2722 if (!(yield* Cache.has(repositoryPathsCache, cacheKey))) {
2723 const isAtRepositoryRoot = yield* fileSystem.realPath(cwd).pipe(
2724 Effect.map((physicalCwd) => path.relative(worktreeRoot, physicalCwd) === ""),
2725 Effect.orElseSucceed(() => undefined),
2726 );
2727 if (
2728 currentListRefsGeneration(gitCommonDir) === refsGeneration &&
2729 !(yield* Cache.has(repositoryPathsCache, cacheKey))
2730 ) {
2731 yield* Cache.set(repositoryPathsCache, cacheKey, {
2732 gitCommonDir,
2733 worktreeRoot,
2734 isAtRepositoryRoot,
2735 currentBranch: refName,
2736 });
2737 }
2738 }
2739 }
2740
2741 if (!upstreamRefExists && !isUnbornHead) upstreamRef = null;
2742
2743 const isDefaultBranch =
2744 refName !== null &&
2745 (refName === defaultBranch ||
2746 (defaultBranch === null && (refName === "main" || refName === "master")));
2747 const needsFallbackAhead = includeDivergence && !upstreamRef && refName !== null;
2748 const needsAheadOfDefault = includeDivergence && refName !== null && !isDefaultBranch;
2749 const [baseAheadCount, branchChanges] = yield* Effect.all(
2750 [
2751 refName !== null && (needsFallbackAhead || needsAheadOfDefault)
2752 ? computeAheadCountAgainstBase(cwd, refName, {
2753 knownOriginDefaultBranch: defaultBranch,
2754 }).pipe(Effect.orElseSucceed(() => 0))
2755 : Effect.succeed(0),
2756 options?.includeBranchChanges
2757 ? readBranchChangeTotals(repositoryPaths?.worktreeRoot ?? cwd, refName, {
2758 knownOriginDefaultBranch: defaultBranch,
2759 untrackedRoots,
2760 headOid,
2761 ...(index ? { indexPath: index } : {}),
2762 }).pipe(Effect.orElseSucceed(() => undefined))
2763 : Effect.undefined,
2764 ],
2765 { concurrency: "unbounded" },
2766 );
2767
2768 if (needsFallbackAhead) {
2769 aheadCount = baseAheadCount;
2770 behindCount = 0;
2771 }
2772 if (needsAheadOfDefault) {
2773 aheadOfDefaultCount = baseAheadCount;
2774 }
2775
2776 const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
2777 for (const entry of numstatEntries) {
2778 const stat = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
2779 stat.insertions += entry.additions;
2780 stat.deletions += entry.deletions;
2781 fileStatMap.set(entry.path, stat);
2782 }
2783
2784 let insertions = 0;
2785 let deletions = 0;
2786 const files = Array.from(fileStatMap.entries()).map(([filePath, stat]) => {
2787 insertions += stat.insertions;
2788 deletions += stat.deletions;
2789 return { path: filePath, insertions: stat.insertions, deletions: stat.deletions };
2790 });
2791
2792 for (const filePath of changedFilesWithoutNumstat) {
2793 if (fileStatMap.has(filePath)) continue;
2794 files.push({ path: filePath, insertions: 0, deletions: 0 });
2795 }
2796 files.sort((a, b) => a.path.localeCompare(b.path));
2797
2798 return {
2799 isRepo: true,
2800 hasOriginRemote: hasPrimaryRemote,
2801 isDefaultBranch,
2802 branch: refName,
2803 upstreamRef,
2804 hasWorkingTreeChanges,
2805 workingTree: {
2806 ...(repositoryPaths?.worktreeRoot ? { rootPath: repositoryPaths.worktreeRoot } : {}),
2807 files,
2808 insertions,
2809 deletions,
2810 },
2811 ...(branchChanges ? { branchChanges } : {}),
2812 hasUpstream: upstreamRef !== null,
2813 aheadCount,
2814 behindCount,
2815 aheadOfDefaultCount,
2816 };
2817 });
2818
2819 const statusDetailsLocal: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsLocal"] = Effect.fn(
2820 "statusDetailsLocal",
2821 )(function* (cwd, options) {
2822 return yield* readStatusDetailsLocal(cwd, options);
2823 });
2824
2825 const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn(
2826 "statusDetails",
2827 )(function* (cwd) {
2828 yield* refreshStatusUpstreamIfStale(cwd).pipe(
2829 Effect.catchTags({
2830 GitCommandError: (error) =>
2831 isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),
2832 }),
2833 Effect.ignoreCause({ log: true }),
2834 );
2835 return yield* readStatusDetailsLocal(cwd);
2836 });
2837
2838 const statusDetailsRemote: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsRemote"] =
2839 Effect.fn("statusDetailsRemote")(function* (cwd, options) {
2840 if (options?.refreshUpstream !== false) {
2841 yield* refreshStatusUpstreamIfStale(cwd).pipe(
2842 Effect.catchTags({
2843 GitCommandError: (error) =>
2844 isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),
2845 }),
2846 Effect.ignoreCause({ log: true }),
2847 );
2848 }
2849 return yield* readStatusDetailsRemote(cwd);
2850 });
2851
2852 const status: GitVcsDriver.GitVcsDriver["Service"]["status"] = (input) =>
2853 statusDetails(input.cwd).pipe(
2854 Effect.map((details) => ({
2855 isRepo: details.isRepo,
2856 hasPrimaryRemote: details.hasOriginRemote,
2857 isDefaultRef: details.isDefaultBranch,
2858 refName: details.branch,
2859 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
2860 workingTree: details.workingTree,
2861 hasUpstream: details.hasUpstream,
2862 aheadCount: details.aheadCount,
2863 behindCount: details.behindCount,
2864 aheadOfDefaultCount: details.aheadOfDefaultCount,
2865 pr: null,
2866 })),
2867 );
2868
2869 // git add takes --pathspec-from-file from Git 2.25; older Git keeps the argument form.
2870 let pathspecFromFileSupported: boolean | undefined;
2871 const supportsPathspecFromFile = Effect.fn("GitVcsDriver.supportsPathspecFromFile")(function* (
2872 cwd: string,
2873 ) {
2874 if (pathspecFromFileSupported !== undefined) return pathspecFromFileSupported;
2875 const version = yield* executeGit("GitVcsDriver.version", cwd, ["version"]).pipe(Effect.option);
2876 if (Option.isNone(version)) return false;
2877 pathspecFromFileSupported = gitSupportsPathspecFromFile(version.value.stdout);
2878 return pathspecFromFileSupported;
2879 });
2880
2881 const stageCommitChanges = Effect.fnUntraced(function* (
2882 cwd: string,
2883 filePaths?: readonly string[],
2884 env?: NodeJS.ProcessEnv,
2885 ) {
2886 const config = env
2887 ? ["-c", "core.splitIndex=false", "-c", "splitIndex.sharedIndexExpire=never"]
2888 : [];
2889 let preserveUnselectedConflicts = false;
2890 if (filePaths && filePaths.length > 0) {
2891 if (env) {
2892 const head = yield* executeGit(
2893 "GitVcsDriver.prepareCommitContext.head",
2894 cwd,
2895 ["rev-parse", "--verify", "--quiet", "HEAD"],
2896 { allowNonZeroExit: true },
2897 );
2898 // Even with GIT_INDEX_FILE, reset clears the repository's merge state.
2899 yield* runGit(
2900 "GitVcsDriver.prepareCommitContext.readTree",
2901 cwd,
2902 [...config, "read-tree", ...(head.exitCode === 0 ? ["HEAD"] : ["--empty"])],
2903 { env },
2904 );
2905 } else {
2906 const inProgressHeads = [
2907 { head: "MERGE_HEAD", operation: "merge" },
2908 { head: "CHERRY_PICK_HEAD", operation: "cherry-pick" },
2909 { head: "REVERT_HEAD", operation: "revert" },
2910 // A conflicted multi-commit `cherry-pick --no-commit` writes only the sequencer; reset
2911 // would clear its unmerged entries, so `--continue` would walk past the conflict.
2912 { head: "sequencer", operation: "cherry-pick or revert" },
2913 ] as const;
2914 const headPaths = yield* runGitStdout("GitVcsDriver.commit.mergeHead", cwd, [
2915 "rev-parse",
2916 ...inProgressHeads.flatMap(({ head }) => ["--git-path", head]),
2917 ]);
2918 const resolvedHeadPaths = headPaths.trim().split("\n");
2919 // Reftable keeps CHERRY_PICK_HEAD and REVERT_HEAD as refs with no file under .git. A
2920 // same-named branch resolves to its full name; an ambiguity warning would blank stdout.
2921 const operationRefs = new Set<string>(["CHERRY_PICK_HEAD", "REVERT_HEAD"]);
2922 const isOperationRef = (head: string) =>
2923 runGitStdout(
2924 "GitVcsDriver.commit.operationRef",
2925 cwd,
2926 [
2927 "-c",
2928 "core.warnAmbiguousRefs=false",
2929 "rev-parse",
2930 "--verify",
2931 "--quiet",
2932 "--symbolic-full-name",
2933 head,
2934 ],
2935 true,
2936 ).pipe(Effect.map((ref) => ref.trim() === head));
2937 const inProgress = yield* Effect.findFirst(inProgressHeads, ({ head }, index) =>
2938 fileSystem.exists(path.resolve(cwd, resolvedHeadPaths[index] ?? "")).pipe(
2939 Effect.filterOrElse(
2940 (exists) => exists || !operationRefs.has(head),
2941 () => isOperationRef(head),
2942 ),
2943 ),
2944 ).pipe(
2945 Effect.mapError(
2946 (cause) =>
2947 new GitCommandError({
2948 operation: "GitVcsDriver.commit.mergeHead",
2949 command: "git commit",
2950 cwd,
2951 detail: "Could not check whether a merge, cherry-pick or revert is in progress.",
2952 cause,
2953 }),
2954 ),
2955 );
2956 // Like git commit --only, reject partial commits before reset can discard their state.
2957 if (Option.isSome(inProgress)) {
2958 const { operation } = inProgress.value;
2959 return yield* new GitCommandError({
2960 operation: "GitVcsDriver.commit",
2961 command: "git commit",
2962 cwd,
2963 detail: `Cannot commit selected files during a ${operation}. Commit all files to finish the ${operation}.`,
2964 });
2965 }
2966 const selectedFiles = new Set(filePaths);
2967 const unmergedPaths = yield* runGitStdoutWithOptions(
2968 "GitVcsDriver.commit.unmergedPaths",
2969 cwd,
2970 ["-c", "diff.relative=false", "diff", "--cached", "--name-only", "--diff-filter=U", "-z"],
2971 { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES },
2972 );
2973 // Reset drops every conflict stage, so keep the index while unselected files are conflicted.
2974 preserveUnselectedConflicts = unmergedPaths
2975 .split("\0")
2976 .some((file) => file.length > 0 && !selectedFiles.has(file));
2977 if (!preserveUnselectedConflicts) {
2978 yield* runGit("GitVcsDriver.commit.reset", cwd, ["reset", "--quiet"]);
2979 }
2980 }
2981 // Status paths are repository-relative, while cwd can be a subdirectory.
2982 const pathspecs = filePaths.map((file) => `:(top,literal)${file}`);
2983 const fromStdin = yield* supportsPathspecFromFile(cwd);
2984 yield* runGit(
2985 "GitVcsDriver.commit.addSelected",
2986 cwd,
2987 fromStdin
2988 ? [...config, "add", "-A", "--pathspec-from-file=-", "--pathspec-file-nul"]
2989 : [...config, "add", "-A", "--", ...pathspecs],
2990 {
2991 ...(env ? { env } : {}),
2992 ...(fromStdin ? { stdin: pathspecs.map((pathspec) => `${pathspec}\0`).join("") } : {}),
2993 },
2994 );
2995 } else {
2996 // add -A marks unmerged paths resolved, so refuse while one still has conflict markers.
2997 const unmergedPaths = (yield* runGitStdoutWithOptions(
2998 "GitVcsDriver.commit.unmergedPaths",
2999 cwd,
3000 ["-c", "diff.relative=false", "diff", "--name-only", "--diff-filter=U", "-z"],
3001 env ? { env } : {},
3002 ))
3003 .split("\0")
3004 .filter((file) => file.length > 0);
3005 if (unmergedPaths.length > 0) {
3006 const check = yield* executeGit(
3007 "GitVcsDriver.commit.conflictMarkers",
3008 cwd,
3009 [
3010 "-c",
3011 "diff.relative=false",
3012 "diff",
3013 "--check",
3014 "--no-color",
3015 "--",
3016 ...unmergedPaths.map((file) => `:(top,literal)${file}`),
3017 ],
3018 {
3019 ...(env ? { env } : {}),
3020 allowNonZeroExit: true,
3021 maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES,
3022 appendTruncationMarker: true,
3023 },
3024 );
3025 const reports = check.stdout.split("\n");
3026 const conflicted: string[] = [];
3027 let emptyTree: string | undefined;
3028 for (const file of unmergedPaths) {
3029 const markerLines = new Set(
3030 reports.flatMap((line) => {
3031 const match = line.startsWith(`${file}:`)
3032 ? /^(\d+): leftover conflict marker$/.exec(line.slice(file.length + 1))
3033 : null;
3034 return match ? [Number(match[1]) - 1] : [];
3035 }),
3036 );
3037 if (markerLines.size === 0) continue;
3038 emptyTree ??= yield* readEmptyTreeHash(cwd);
3039 // --check numbers lines after working-tree-encoding and clean filters; a diff from the
3040 // empty tree prints that view. Read it in full so large resolved files can still commit.
3041 const fileDiff = yield* runGitStdoutWithOptions(
3042 "GitVcsDriver.commit.conflictMarkers",
3043 cwd,
3044 [
3045 "-c",
3046 "diff.relative=false",
3047 "diff",
3048 "--no-color",
3049 "--no-ext-diff",
3050 "--no-textconv",
3051 "--text",
3052 emptyTree,
3053 "--",
3054 `:(top,literal)${file}`,
3055 ],
3056 { ...(env ? { env } : {}), maxOutputBytes: Number.POSITIVE_INFINITY },
3057 ).pipe(
3058 Effect.mapError(
3059 (cause) =>
3060 new GitCommandError({
3061 operation: "GitVcsDriver.commit.conflictMarkers",
3062 command: "git commit",
3063 cwd,
3064 detail: `Could not check ${file} for conflict markers.`,
3065 cause,
3066 }),
3067 ),
3068 );
3069 const diffLines = fileDiff.split("\n");
3070 const lines = diffLines
3071 .slice(diffLines.findIndex((line) => line.startsWith("@@")) + 1)
3072 .filter((line) => line.startsWith("+"))
3073 .map((line) => line.slice(1));
3074 // Git also reports a lone "=======", which is valid content such as a heading underline.
3075 const reported = (marker: string) =>
3076 lines.some((line, index) => markerLines.has(index) && line.startsWith(marker));
3077 if (reported("<") && reported(">")) conflicted.push(file);
3078 }
3079 if (conflicted.length > 0) {
3080 return yield* new GitCommandError({
3081 operation: "GitVcsDriver.commit",
3082 command: "git commit",
3083 cwd,
3084 detail: `Cannot commit with unresolved merge conflicts in ${conflicted.join(", ")}. Resolve them, then commit.`,
3085 });
3086 }
3087 }
3088 yield* runGit(
3089 "GitVcsDriver.commit.addAll",
3090 cwd,
3091 [...config, "add", "-A"],
3092 env ? { env } : {},
3093 );
3094 }
3095 return preserveUnselectedConflicts && filePaths
3096 ? filePaths.map((file) => `:(top,literal)${file}`)
3097 : undefined;
3098 });
3099
3100 const prepareCommitContext: GitVcsDriver.GitVcsDriver["Service"]["prepareCommitContext"] =
3101 Effect.fn("prepareCommitContext")(function* (cwd, filePaths, options) {
3102 return yield* Effect.scoped(
3103 Effect.gen(function* () {
3104 const [indexValue = "", objectsValue = ""] = (yield* runGitStdout(
3105 "GitVcsDriver.prepareCommitContext.gitPaths",
3106 cwd,
3107 ["rev-parse", "--git-path", "index", "--git-path", "objects"],
3108 )).split("\n");
3109 // Git's relative paths use the physical cwd, even when the project uses a symlink.
3110 const physicalCwd = yield* fileSystem.realPath(cwd);
3111 const indexPath = path.resolve(physicalCwd, indexValue.trim());
3112 const directory = yield* fileSystem.makeTempDirectoryScoped({
3113 prefix: "t3code-commit-index-",
3114 });
3115 const tempIndexPath = path.join(directory, "index");
3116 // Staging writes blobs; put them in the temp directory so a draft leaves nothing behind.
3117 const objectDirectories = yield* runGitStdout(
3118 "GitVcsDriver.prepareCommitContext.alternates",
3119 cwd,
3120 ["count-objects", "-v"],
3121 );
3122 const tempObjectsPath = path.join(directory, "objects");
3123 yield* fileSystem.makeDirectory(tempObjectsPath);
3124 const env = {
3125 GIT_INDEX_FILE: tempIndexPath,
3126 ...privateObjectDirectoryEnv(
3127 tempObjectsPath,
3128 path.resolve(physicalCwd, objectsValue.trim()),
3129 objectDirectories,
3130 ),
3131 } satisfies NodeJS.ProcessEnv;
3132 const config = [
3133 "-c",
3134 "core.splitIndex=false",
3135 "-c",
3136 "splitIndex.sharedIndexExpire=never",
3137 ];
3138 if (yield* fileSystem.exists(indexPath)) {
3139 const { mtime } = yield* fileSystem.stat(indexPath);
3140 yield* fileSystem.copyFile(indexPath, tempIndexPath);
3141 const indexTime = Option.isSome(mtime)
3142 ? Math.max(0, Math.floor(mtime.value.getTime() / 1000))
3143 : 0;
3144 yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime);
3145 yield* runGit(
3146 "GitVcsDriver.prepareCommitContext.expandSplitIndex",
3147 cwd,
3148 [...config, "update-index", "--no-split-index"],
3149 { env },
3150 );
3151 } else {
3152 yield* runGit(
3153 "GitVcsDriver.prepareCommitContext.emptyIndex",
3154 cwd,
3155 [...config, "read-tree", "--empty"],
3156 { env },
3157 );
3158 }
3159 yield* stageCommitChanges(cwd, filePaths, env);
3160
3161 const stagedSummary = yield* runGitStdoutWithOptions(
3162 "GitVcsDriver.prepareCommitContext.stagedSummary",
3163 cwd,
3164 // cwd can be a subdirectory; diff.relative would hide changes outside it.
3165 ["-c", "diff.relative=false", "diff", "--cached", "--name-status"],
3166 { env, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES },
3167 ).pipe(Effect.map((stdout) => stdout.trim()));
3168 if (stagedSummary.length === 0) {
3169 // Like git commit, a merge resolved to HEAD's tree still records its merge commit.
3170 const mergeHeadPath = yield* runGitStdout(
3171 "GitVcsDriver.prepareCommitContext.mergeHead",
3172 cwd,
3173 ["rev-parse", "--git-path", "MERGE_HEAD"],
3174 );
3175 if (!(yield* fileSystem.exists(path.resolve(physicalCwd, mergeHeadPath.trim())))) {
3176 return null;
3177 }
3178 }
3179
3180 // A user-supplied message needs change detection, but no patch for generation.
3181 if (options?.includePatch === false) return { stagedSummary, stagedPatch: "" };
3182
3183 const stagedPatch = yield* runGitStdoutWithOptions(
3184 "GitVcsDriver.prepareCommitContext.stagedPatch",
3185 cwd,
3186 [
3187 "-c",
3188 "diff.relative=false",
3189 "diff",
3190 "--no-color",
3191 "--no-ext-diff",
3192 "--no-textconv",
3193 "--cached",
3194 "--patch",
3195 "--minimal",
3196 ],
3197 {
3198 env,
3199 maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES,
3200 appendTruncationMarker: true,
3201 },
3202 );
3203
3204 return {
3205 stagedSummary,
3206 stagedPatch,
3207 };
3208 }),
3209 ).pipe(
3210 Effect.catchTags({
3211 PlatformError: (cause) =>
3212 new GitCommandError({
3213 operation: "GitVcsDriver.prepareCommitContext",
3214 command: "git",
3215 cwd,
3216 detail: "Failed to prepare the temporary commit index.",
3217 cause,
3218 }),
3219 }),
3220 );
3221 });
3222
3223 const commit: GitVcsDriver.GitVcsDriver["Service"]["commit"] = Effect.fn("commit")(function* (
3224 cwd,
3225 subject,
3226 body,
3227 options?: GitVcsDriver.GitCommitOptions,
3228 ) {
3229 const partialCommitPaths =
3230 options?.stage !== undefined
3231 ? yield* stageCommitChanges(cwd, options.stage.filePaths)
3232 : undefined;
3233 const args = ["commit", "-m", subject];
3234 const trimmedBody = body.trim();
3235 if (trimmedBody.length > 0) {
3236 args.push("-m", trimmedBody);
3237 }
3238 const onlyFromStdin = partialCommitPaths ? yield* supportsPathspecFromFile(cwd) : false;
3239 const onlyPathspecArgs = onlyFromStdin
3240 ? ["--pathspec-from-file=-", "--pathspec-file-nul"]
3241 : ["--", ...(partialCommitPaths ?? [])];
3242 const onlyPathspecStdin =
3243 partialCommitPaths && onlyFromStdin
3244 ? { stdin: partialCommitPaths.map((pathspec) => `${pathspec}\0`).join("") }
3245 : {};
3246 if (partialCommitPaths) {
3247 args.push("--only", ...onlyPathspecArgs);
3248 }
3249 const progress =
3250 options?.progress?.onOutputLine === undefined
3251 ? options?.progress
3252 : {
3253 ...options.progress,
3254 onStdoutLine: (line: string) =>
3255 options.progress?.onOutputLine?.({ stream: "stdout", text: line }) ?? Effect.void,
3256 onStderrLine: (line: string) =>
3257 options.progress?.onOutputLine?.({ stream: "stderr", text: line }) ?? Effect.void,
3258 };
3259 yield* executeGit("GitVcsDriver.commit.commit", cwd, args, {
3260 maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES,
3261 ...onlyPathspecStdin,
3262 ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
3263 ...(progress ? { progress } : {}),
3264 }).pipe(Effect.asVoid);
3265 if (partialCommitPaths) {
3266 // --only runs hooks on a temporary index, so a hook's `git add` never reaches the real one.
3267 yield* runGit(
3268 "GitVcsDriver.commit.syncSelectedIndex",
3269 cwd,
3270 ["reset", "--quiet", "HEAD", ...onlyPathspecArgs],
3271 onlyPathspecStdin,
3272 );
3273 }
3274 const commitSha = yield* runGitStdout("GitVcsDriver.commit.revParseHead", cwd, [
3275 "rev-parse",
3276 "HEAD",
3277 ]).pipe(Effect.map((stdout) => stdout.trim()));
3278
3279 return { commitSha };
3280 });
3281
3282 // `push -u` exits 0 without the upstream when another writer holds the config lock.
3283 const recordPushedUpstream = Effect.fn("recordPushedUpstream")(
3284 function* (cwd: string, branch: string, remoteName: string, publishBranch: string) {
3285 // Without a prior upstream, Git ignores a merge ref with no remote, so losing the second
3286 // write leaves none rather than a wrong one.
3287 yield* writeConfigValue({
3288 cwd,
3289 key: `branch.${branch}.merge`,
3290 value: `refs/heads/${publishBranch}`,
3291 });
3292 yield* writeConfigValue({ cwd, key: `branch.${branch}.remote`, value: remoteName });
3293 // Matches what `push -u` sets for a remote upstream.
3294 const autoSetupRebase = yield* readConfigValue(cwd, "branch.autoSetupRebase");
3295 if (autoSetupRebase === "always" || autoSetupRebase === "remote") {
3296 yield* writeConfigValue({ cwd, key: `branch.${branch}.rebase`, value: "true" });
3297 }
3298 return true;
3299 },
3300 Effect.catch((cause) =>
3301 Effect.logWarning("pushed, but could not record the branch upstream", { cause }).pipe(
3302 Effect.as(false),
3303 ),
3304 ),
3305 );
3306
3307 // `publishes` is false only when HEAD goes to the head of its current `upstream`.
3308 const resolvePushDestination = Effect.fn("resolvePushDestination")(function* (
3309 cwd: string,
3310 branch: string,
3311 hasUpstream: boolean,
3312 ) {
3313 if (!hasUpstream) {
3314 // A deleted upstream keeps its config: republish to it when it was this branch's own,
3315 // otherwise it was the base, so keep that before publishing.
3316 let goneUpstream: { remoteName: string; branchName: string } | null = null;
3317 let goneBaseUpstream: { remoteName: string; branchName: string; upstreamRef: string } | null =
3318 null;
3319 const mergeRef = yield* readConfigValue(cwd, `branch.${branch}.merge`);
3320 const mergeBranch = mergeRef?.startsWith("refs/heads/")
3321 ? mergeRef.slice("refs/heads/".length)
3322 : null;
3323 const configuredRemoteName = yield* readConfigValue(cwd, `branch.${branch}.remote`);
3324 if (mergeBranch && configuredRemoteName && configuredRemoteName !== ".") {
3325 if (isAliasOfUpstreamHead(branch, mergeBranch, `${configuredRemoteName}/${mergeBranch}`)) {
3326 goneUpstream = { remoteName: configuredRemoteName, branchName: mergeBranch };
3327 } else {
3328 goneBaseUpstream = {
3329 remoteName: configuredRemoteName,
3330 branchName: mergeBranch,
3331 upstreamRef: `${configuredRemoteName}/${mergeBranch}`,
3332 };
3333 }
3334 }
3335 const remoteName = yield* resolvePushRemoteName(cwd, branch, goneUpstream?.remoteName);
3336 if (!remoteName) return null;
3337 // A gone local upstream still gets the full local name, as below.
3338 const branchName =
3339 goneUpstream?.branchName ??
3340 (configuredRemoteName === "." ? branch : yield* resolvePublishBranchName(cwd, branch));
3341 return {
3342 remoteName,
3343 branchName,
3344 publishes: true,
3345 upstream: goneBaseUpstream,
3346 pushRemote: null,
3347 };
3348 }
3349
3350 if ((yield* readConfigValue(cwd, `branch.${branch}.remote`)) === ".") {
3351 const localUpstream = yield* readCurrentUpstreamRef(cwd).pipe(
3352 Effect.orElseSucceed(() => null),
3353 );
3354 if (localUpstream === null) return null;
3355 // A local upstream is a base; publish under the full local name so `origin/main` never lands on remote `main`.
3356 const remoteName = yield* resolvePushRemoteName(cwd, branch).pipe(
3357 Effect.orElseSucceed(() => null),
3358 );
3359 if (!remoteName) return null;
3360 return {
3361 remoteName,
3362 branchName: branch,
3363 publishes: true,
3364 upstream: { remoteName: ".", branchName: localUpstream, upstreamRef: localUpstream },
3365 pushRemote: null,
3366 };
3367 }
3368
3369 const upstream = yield* resolveCurrentUpstream(cwd).pipe(Effect.orElseSucceed(() => null));
3370 if (!upstream) return null;
3371 if (isAliasOfUpstreamHead(branch, upstream.branchName, upstream.upstreamRef)) {
3372 // A fork workflow pushes to the configured push remote and keeps the upstream for pulls, as plain `git push` does.
3373 const configuredPushRemote = yield* resolveConfiguredPushRemoteName(cwd, branch).pipe(
3374 Effect.orElseSucceed(() => null),
3375 );
3376 const pushRemote =
3377 configuredPushRemote && configuredPushRemote !== upstream.remoteName
3378 ? configuredPushRemote
3379 : null;
3380 return {
3381 remoteName: pushRemote ?? upstream.remoteName,
3382 branchName: upstream.branchName,
3383 publishes: false,
3384 upstream,
3385 pushRemote,
3386 };
3387 }
3388 const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe(
3389 Effect.orElseSucceed(() => null),
3390 );
3391 const branchName = yield* resolvePublishBranchName(cwd, branch);
3392 return {
3393 remoteName: publishRemoteName ?? upstream.remoteName,
3394 branchName,
3395 publishes: true,
3396 upstream,
3397 pushRemote: null,
3398 };
3399 });
3400
3401 const resolvePushTarget: GitVcsDriver.GitVcsDriver["Service"]["resolvePushTarget"] = Effect.fn(
3402 "resolvePushTarget",
3403 )(function* (cwd, current) {
3404 const destination = yield* resolvePushDestination(cwd, current.branch, current.hasUpstream);
3405 return destination
3406 ? {
3407 remoteName: destination.remoteName,
3408 branchName: destination.branchName,
3409 viaPushRemote: destination.pushRemote !== null,
3410 }
3411 : null;
3412 });
3413
3414 const pushCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pushCurrentBranch"] = Effect.fn(
3415 "pushCurrentBranch",
3416 )(function* (cwd, fallbackBranch, options) {
3417 const details = yield* statusDetails(cwd);
3418 const branch = details.branch ?? fallbackBranch;
3419 if (!branch) {
3420 return yield* new GitCommandError({
3421 ...gitCommandContext({
3422 operation: "GitVcsDriver.pushCurrentBranch",
3423 cwd,
3424 args: ["push"],
3425 }),
3426 detail: "Cannot push from detached HEAD.",
3427 });
3428 }
3429
3430 const requestedRemoteName = options?.remoteName?.trim() || null;
3431 if (requestedRemoteName) {
3432 const publishBranch = yield* resolvePublishBranchName(cwd, branch);
3433 yield* executeGitWithStableDiagnostics(
3434 "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote",
3435 cwd,
3436 ["push", "--", requestedRemoteName, `HEAD:refs/heads/${publishBranch}`],
3437 { timeoutMs: null },
3438 );
3439 return {
3440 status: "pushed" as const,
3441 branch,
3442 upstreamBranch: `${requestedRemoteName}/${publishBranch}`,
3443 setUpstream: yield* recordPushedUpstream(cwd, branch, requestedRemoteName, publishBranch),
3444 };
3445 }
3446
3447 const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;
3448 const destination = yield* resolvePushDestination(cwd, branch, details.hasUpstream);
3449 if (hasNoLocalDelta && details.hasUpstream) {
3450 if (!destination?.pushRemote) {
3451 // The tracking ref reflects the fetch URL, so it says nothing about a separate push URL.
3452 if (!destination || (yield* pushesOnlyToFetchUrl(cwd, destination.remoteName))) {
3453 return {
3454 status: "skipped_up_to_date" as const,
3455 branch,
3456 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
3457 };
3458 }
3459 } else {
3460 const { pushRemote, branchName } = destination;
3461 const pushRemoteRef = `${pushRemote}/${branchName}`;
3462 // The local ref can be stale when the branch was deleted or rewound elsewhere.
3463 const pushRemoteHasHead =
3464 (yield* pushesOnlyToFetchUrl(cwd, pushRemote)) &&
3465 (yield* fetchRemoteTrackingBranch({
3466 cwd,
3467 remoteName: pushRemote,
3468 remoteBranch: branchName,
3469 }).pipe(
3470 Effect.andThen(remoteRefContainsHead(cwd, pushRemoteRef)),
3471 Effect.orElseSucceed(() => false),
3472 ));
3473 if (pushRemoteHasHead) {
3474 return {
3475 status: "skipped_up_to_date" as const,
3476 branch,
3477 upstreamBranch: pushRemoteRef,
3478 pushRemote,
3479 };
3480 }
3481 }
3482 } else if (hasNoLocalDelta) {
3483 const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe(
3484 Effect.orElseSucceed(() => null),
3485 );
3486 if (comparableBaseBranch) {
3487 if (!destination) {
3488 return {
3489 status: "skipped_up_to_date" as const,
3490 branch,
3491 };
3492 }
3493
3494 // The configured diff base can contain HEAD while the publish branch is still behind.
3495 if (
3496 (yield* remoteRefContainsHead(
3497 cwd,
3498 `${destination.remoteName}/${destination.branchName}`,
3499 )) &&
3500 (yield* pushesOnlyToFetchUrl(cwd, destination.remoteName))
3501 ) {
3502 return {
3503 status: "skipped_up_to_date" as const,
3504 branch,
3505 };
3506 }
3507 }
3508 }
3509
3510 if (
3511 !destination &&
3512 (!details.hasUpstream || (yield* readConfigValue(cwd, `branch.${branch}.remote`)) === ".")
3513 ) {
3514 return yield* new GitCommandError({
3515 ...gitCommandContext({
3516 operation: "GitVcsDriver.pushCurrentBranch",
3517 cwd,
3518 args: ["push"],
3519 }),
3520 detail: "Cannot push because no git remote is configured for this repository.",
3521 });
3522 }
3523
3524 if (destination?.publishes) {
3525 const { remoteName, branchName: publishBranch, upstream } = destination;
3526 // Publishing retargets the upstream, so preserve its comparison base first.
3527 if (upstream && (yield* readBranchBase(cwd, branch)) === null) {
3528 yield* writeConfigValue({
3529 cwd,
3530 key: branchBaseConfigKey(branch),
3531 value: upstream.branchName,
3532 });
3533 if (!(yield* readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`))) {
3534 yield* writeConfigValue({
3535 cwd,
3536 key: `branch.${branch}.t3-merge-base-ref`,
3537 value:
3538 upstream.remoteName === "."
3539 ? `refs/heads/${upstream.branchName}`
3540 : `refs/remotes/${upstream.upstreamRef}`,
3541 });
3542 }
3543 }
3544 yield* executeGitWithStableDiagnostics(
3545 upstream
3546 ? "GitVcsDriver.pushCurrentBranch.pushOwnBranch"
3547 : "GitVcsDriver.pushCurrentBranch.pushWithUpstream",
3548 cwd,
3549 ["push", "--", remoteName, `HEAD:refs/heads/${publishBranch}`],
3550 { timeoutMs: null },
3551 );
3552 return {
3553 status: "pushed" as const,
3554 branch,
3555 upstreamBranch: `${remoteName}/${publishBranch}`,
3556 setUpstream: yield* recordPushedUpstream(cwd, branch, remoteName, publishBranch),
3557 };
3558 }
3559
3560 if (destination?.upstream) {
3561 yield* executeGitWithStableDiagnostics(
3562 "GitVcsDriver.pushCurrentBranch.pushUpstream",
3563 cwd,
3564 ["push", "--", destination.remoteName, `HEAD:refs/heads/${destination.branchName}`],
3565 { timeoutMs: null },
3566 );
3567 return {
3568 status: "pushed" as const,
3569 branch,
3570 ...(destination.pushRemote
3571 ? {
3572 upstreamBranch: `${destination.remoteName}/${destination.branchName}`,
3573 pushRemote: destination.pushRemote,
3574 }
3575 : { upstreamBranch: destination.upstream.upstreamRef }),
3576 setUpstream: false,
3577 };
3578 }
3579
3580 yield* executeGitWithStableDiagnostics("GitVcsDriver.pushCurrentBranch.push", cwd, ["push"], {
3581 timeoutMs: null,
3582 });
3583 return {
3584 status: "pushed" as const,
3585 branch,
3586 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
3587 setUpstream: false,
3588 };
3589 });
3590
3591 const pullCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pullCurrentBranch"] = Effect.fn(
3592 "pullCurrentBranch",
3593 )(function* (cwd) {
3594 const details = yield* readStatusDetailsLocal(cwd);
3595 const refName = details.branch;
3596 if (!refName) {
3597 return yield* new GitCommandError({
3598 ...gitCommandContext({
3599 operation: "GitVcsDriver.pullCurrentBranch",
3600 cwd,
3601 args: ["pull", "--ff-only"],
3602 }),
3603 detail: "Cannot pull from detached HEAD.",
3604 });
3605 }
3606 if (!details.hasUpstream) {
3607 return yield* new GitCommandError({
3608 ...gitCommandContext({
3609 operation: "GitVcsDriver.pullCurrentBranch",
3610 cwd,
3611 args: ["pull", "--ff-only"],
3612 }),
3613 detail: "Current branch has no upstream configured. Push with upstream first.",
3614 });
3615 }
3616 const remote = yield* readConfigValue(cwd, `branch.${refName}.remote`);
3617 // The upstream-only retry leaves other remote-tracking refs stale, so a claimed status
3618 // fetch must still run after it.
3619 let fetchedUpstreamOnly = false;
3620 if (remote) {
3621 const gitCommonDir = yield* resolveGitCommonDir(cwd);
3622 const pending = statusFetches.get(`${gitCommonDir}\0${remote}`);
3623 // The status wait can finish while its fetch still owns reference locks.
3624 // Let our existing writer finish before starting the pull's fetch.
3625 if (pending) {
3626 const claimed = yield* Effect.uninterruptible(
3627 Effect.gen(function* () {
3628 if (pending.state.phase !== "queued") return false;
3629 pending.state.phase = "claimed";
3630 yield* Effect.addFinalizer((exit) =>
3631 Deferred.succeed(
3632 pending.state.finished,
3633 Exit.isSuccess(exit) && !fetchedUpstreamOnly,
3634 ),
3635 );
3636 yield* Deferred.succeed(pending.state.claimed, undefined);
3637 return true;
3638 }),
3639 );
3640 if (!claimed) yield* Fiber.await(pending.fiber);
3641 }
3642 }
3643 const beforeSha = yield* runGitStdout(
3644 "GitVcsDriver.pullCurrentBranch.beforeSha",
3645 cwd,
3646 ["rev-parse", "HEAD"],
3647 true,
3648 ).pipe(Effect.map((stdout) => stdout.trim()));
3649 // After a successful pull, HEAD before and after decides the result, so its output is not
3650 // needed. A large fast-forward's diffstat can exceed the output cap, which must not fail a
3651 // pull Git applied.
3652 // A deadline would kill git mid-checkout (e.g. a slow LFS smudge) and strand a half-updated tree.
3653 const options = {
3654 timeoutMs: null,
3655 appendTruncationMarker: true,
3656 allowNonZeroExit: true,
3657 };
3658 let args = ["pull", "--ff-only"];
3659 let result = yield* executeGitWithStableDiagnostics(
3660 "GitVcsDriver.pullCurrentBranch.pull",
3661 cwd,
3662 args,
3663 options,
3664 );
3665 if (result.exitCode !== 0 && isRefLockFailure(result.stderr)) {
3666 const [remote, mergeRefs, currentBranch, currentSha] = yield* Effect.all([
3667 readConfigValue(cwd, `branch.${refName}.remote`),
3668 runGitStdout(
3669 "GitVcsDriver.pullCurrentBranch.mergeRefs",
3670 cwd,
3671 ["config", "--get-all", `branch.${refName}.merge`],
3672 true,
3673 ).pipe(Effect.map((stdout) => stdout.trim().split("\n").filter(Boolean))),
3674 runGitStdout(
3675 "GitVcsDriver.pullCurrentBranch.currentBranch",
3676 cwd,
3677 ["symbolic-ref", "--quiet", "HEAD"],
3678 true,
3679 ).pipe(Effect.map(branchNameFromHeadRef)),
3680 runGitStdout("GitVcsDriver.pullCurrentBranch.currentSha", cwd, ["rev-parse", "HEAD"]).pipe(
3681 Effect.map((stdout) => stdout.trim()),
3682 ),
3683 ]);
3684 // A full fetch can fail on an unrelated branch's lock. Keep that fetch as the
3685 // default, but retry only the configured upstream before any checkout movement.
3686 const [mergeRef] = mergeRefs;
3687 if (
3688 remote &&
3689 mergeRef &&
3690 mergeRefs.length === 1 &&
3691 currentBranch === refName &&
3692 currentSha === beforeSha
3693 ) {
3694 args = ["pull", "--ff-only", "--", remote, mergeRef];
3695 fetchedUpstreamOnly = true;
3696 result = yield* executeGitWithStableDiagnostics(
3697 "GitVcsDriver.pullCurrentBranch.pull",
3698 cwd,
3699 args,
3700 options,
3701 );
3702 }
3703 }
3704 if (result.exitCode !== 0) {
3705 const reason = classifyGitFailure(result.stderr);
3706 return yield* new GitCommandError({
3707 ...gitCommandContext({ operation: "GitVcsDriver.pullCurrentBranch.pull", cwd, args }),
3708 ...(reason === null ? {} : { reason }),
3709 detail: fetchFailureDetail(result.stderr) ?? "git pull failed",
3710 exitCode: result.exitCode,
3711 stdoutLength: result.stdout.length,
3712 stderrLength: result.stderr.length,
3713 });
3714 }
3715 const afterSha = yield* runGitStdout(
3716 "GitVcsDriver.pullCurrentBranch.afterSha",
3717 cwd,
3718 ["rev-parse", "HEAD"],
3719 true,
3720 ).pipe(Effect.map((stdout) => stdout.trim()));
3721
3722 const refreshed = yield* readStatusDetailsLocal(cwd);
3723 return {
3724 status:
3725 beforeSha.length > 0 && beforeSha === afterSha
3726 ? ("skipped_up_to_date" as const)
3727 : ("pulled" as const),
3728 refName,
3729 upstreamRef: refreshed.upstreamRef,
3730 };
3731 }, Effect.scoped);
3732
3733 const readRangeContext: GitVcsDriver.GitVcsDriver["Service"]["readRangeContext"] = Effect.fn(
3734 "readRangeContext",
3735 )(function* (cwd, baseRef) {
3736 const commitRange = `${baseRef}..HEAD`;
3737 const diffRange = `${baseRef}...HEAD`;
3738 const [commitSummary, diffSummary, diffPatch] = yield* Effect.all(
3739 [
3740 runGitStdoutWithOptions(
3741 "GitVcsDriver.readRangeContext.log",
3742 cwd,
3743 [
3744 "log",
3745 "--oneline",
3746 "--no-color",
3747 "--no-decorate",
3748 "--no-show-signature",
3749 "--end-of-options",
3750 commitRange,
3751 ],
3752 {
3753 maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES,
3754 appendTruncationMarker: true,
3755 },
3756 ),
3757 runGitStdoutWithOptions(
3758 "GitVcsDriver.readRangeContext.diffStat",
3759 cwd,
3760 [
3761 "-c",
3762 "diff.relative=false",
3763 "diff",
3764 "--stat",
3765 "--no-color",
3766 "--end-of-options",
3767 diffRange,
3768 ],
3769 {
3770 maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES,
3771 appendTruncationMarker: true,
3772 },
3773 ),
3774 runGitStdoutWithOptions(
3775 "GitVcsDriver.readRangeContext.diffPatch",
3776 cwd,
3777 [
3778 "-c",
3779 "diff.relative=false",
3780 "diff",
3781 "--no-color",
3782 "--no-ext-diff",
3783 "--no-textconv",
3784 "--patch",
3785 "--minimal",
3786 "--end-of-options",
3787 diffRange,
3788 ],
3789 {
3790 maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES,
3791 appendTruncationMarker: true,
3792 },
3793 ),
3794 ],
3795 { concurrency: "unbounded" },
3796 );
3797
3798 return {
3799 commitSummary,
3800 diffSummary,
3801 diffPatch,
3802 };
3803 });
3804
3805 const prepareReviewIndex = Effect.fn("prepareReviewIndex")(function* (
3806 cwd: string,
3807 untrackedPaths: ReadonlyArray<string>,
3808 allowPartial: boolean,
3809 knownIndexPath?: string,
3810 ) {
3811 const [stagedDeletionsStdout, indexValue] = yield* Effect.all(
3812 [
3813 runGitStdoutWithOptions(
3814 "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.stagedDeletions",
3815 cwd,
3816 [
3817 "diff",
3818 "--cached",
3819 "--no-renames",
3820 "--name-only",
3821 "--diff-filter=D",
3822 "-z",
3823 "HEAD",
3824 "--",
3825 ],
3826 { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES },
3827 ),
3828 knownIndexPath === undefined
3829 ? runGitStdout("GitVcsDriver.readUnifiedWorkingTreeReviewDiff.indexPath", cwd, [
3830 "rev-parse",
3831 "--git-path",
3832 "index",
3833 ])
3834 : Effect.succeed(knownIndexPath),
3835 ],
3836 { concurrency: 2 },
3837 );
3838 const stagedDeletions = new Set(stagedDeletionsStdout.split("\0").filter(Boolean));
3839 // Staged deletions never enter the index, so their worktree copies must not spend the budget.
3840 // A nested repository (listed with a trailing slash) with no commits cannot be indexed:
3841 // Git before 2.53 fails the add, and later versions accept it and then fail every diff.
3842 const candidates = yield* Effect.filter(
3843 untrackedPaths.filter((relativePath) => !stagedDeletions.has(relativePath)),
3844 (relativePath) =>
3845 relativePath.endsWith("/")
3846 ? executeGit(
3847 "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.nestedRepositoryHead",
3848 path.resolve(cwd, relativePath),
3849 ["rev-parse", "--verify", "--quiet", "HEAD"],
3850 { allowNonZeroExit: true },
3851 ).pipe(Effect.map((result) => result.exitCode !== 1))
3852 : Effect.succeed(true),
3853 { concurrency: 16 },
3854 );
3855 const sizes = yield* Effect.forEach(
3856 candidates,
3857 (relativePath) =>
3858 fileSystem.lstat(path.resolve(cwd, relativePath)).pipe(
3859 Effect.map((info) => (info.type === "File" ? Number(info.size) : 0)),
3860 Effect.orElseSucceed(() => 0),
3861 Effect.map((size) => ({ relativePath, size })),
3862 ),
3863 { concurrency: 16 },
3864 );
3865 // Smallest first, so which files fit does not depend on how their names sort.
3866 const pathsToAdd: string[] = [];
3867 let bytes = 0;
3868 for (const { relativePath, size } of sizes.toSorted((left, right) => left.size - right.size)) {
3869 bytes += size;
3870 if (bytes > REVIEW_UNTRACKED_MAX_BYTES) break;
3871 pathsToAdd.push(relativePath);
3872 }
3873 const omitted = pathsToAdd.length < candidates.length;
3874 if (pathsToAdd.length === 0 || (omitted && !allowPartial)) return { env: undefined, omitted };
3875
3876 const indexPath = knownIndexPath ?? path.resolve(cwd, indexValue.replace(/\n$/, ""));
3877 const tempIndexPath = yield* fileSystem.makeTempFileScoped({
3878 prefix: `t3code-review-index-${process.pid}-`,
3879 });
3880 const indexExists = yield* fileSystem.exists(indexPath);
3881 if (indexExists) {
3882 const { mtime } = yield* fileSystem.stat(indexPath);
3883 yield* fileSystem.copyFile(indexPath, tempIndexPath);
3884 // stat truncates bigint times to ms; floor seconds to avoid making preceding-second files racy.
3885 const indexTime = Option.isSome(mtime)
3886 ? Math.max(0, Math.floor(mtime.value.getTime() / 1000))
3887 : 0;
3888 yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime);
3889 }
3890 const env = { GIT_INDEX_FILE: tempIndexPath } satisfies NodeJS.ProcessEnv;
3891 const tempIndexConfig = [
3892 "-c",
3893 "core.splitIndex=false",
3894 "-c",
3895 "splitIndex.sharedIndexExpire=never",
3896 ];
3897 if (!indexExists) {
3898 yield* executeGit("GitVcsDriver.review.emptyIndex", cwd, ["read-tree", "--empty"], { env });
3899 }
3900 yield* executeGit(
3901 "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.expandSplitIndex",
3902 cwd,
3903 [...tempIndexConfig, "update-index", "--no-split-index"],
3904 { env },
3905 );
3906 yield* executeGit(
3907 "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.addUntracked",
3908 cwd,
3909 [
3910 ...tempIndexConfig,
3911 // Avoid redundant tracked-entry pathspec matching in this disposable index.
3912 "-c",
3913 "core.preloadIndex=false",
3914 // Sparse checkout refuses to add untracked files outside the cone, failing the whole review.
3915 "-c",
3916 "core.sparseCheckout=false",
3917 "--literal-pathspecs",
3918 "add",
3919 "--intent-to-add",
3920 "--pathspec-from-file=-",
3921 "--pathspec-file-nul",
3922 ],
3923 { env, stdin: `${pathsToAdd.join("\0")}\0` },
3924 );
3925 return { env, omitted };
3926 });
3927
3928 const readEmptyTreeHash = Effect.fn("readEmptyTreeHash")(function* (cwd: string) {
3929 const stdout = yield* runGitStdout("GitVcsDriver.review.emptyTree", cwd, [
3930 "hash-object",
3931 "-t",
3932 "tree",
3933 (yield* HostProcess.Platform) === "win32" ? "NUL" : "/dev/null",
3934 ]);
3935 return stdout.trim();
3936 });
3937
3938 const prepareUntrackedReviewIndexOrReason = Effect.fn("prepareUntrackedReviewIndex")(function* (
3939 cwd: string,
3940 pathArgs: ReadonlyArray<string>,
3941 onlyPath: string | undefined,
3942 allowPartial: boolean,
3943 knownIndexPath?: string,
3944 ) {
3945 const untracked = yield* executeGit(
3946 "GitVcsDriver.review.listUntracked",
3947 cwd,
3948 ["ls-files", "--others", "--exclude-standard", "-z", "--", ...pathArgs],
3949 { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES },
3950 ).pipe(
3951 Effect.catchTags({
3952 GitCommandError: (error) =>
3953 Effect.succeed({ unavailable: `Could not list untracked files: ${error.detail}` }),
3954 }),
3955 );
3956 if ("unavailable" in untracked) return untracked;
3957 // ls-files lists a nested repository with a trailing slash; its diff path has none.
3958 const paths = splitNullSeparatedGitStdoutPaths(untracked).filter(
3959 (candidate) =>
3960 onlyPath === undefined || candidate === onlyPath || candidate === `${onlyPath}/`,
3961 );
3962 if (paths.length === 0) return { env: undefined, omitted: false };
3963 if (paths.length > REVIEW_UNTRACKED_MAX_FILES)
3964 return { unavailable: "Too many untracked files to count." };
3965 const index = yield* prepareReviewIndex(cwd, paths, allowPartial, knownIndexPath).pipe(
3966 Effect.catchTags({
3967 PlatformError: (cause) =>
3968 Effect.fail(
3969 new GitCommandError({
3970 operation: "GitVcsDriver.prepareReviewIndex",
3971 cwd,
3972 command: "git diff",
3973 detail: "Could not prepare the review index.",
3974 cause,
3975 }),
3976 ),
3977 }),
3978 );
3979 if (index.omitted && !allowPartial)
3980 return { unavailable: "Untracked files are too large to count." };
3981 return index;
3982 });
3983 const prepareUntrackedReviewIndex = (
3984 cwd: string,
3985 pathArgs: ReadonlyArray<string>,
3986 onlyPath?: string,
3987 ) =>
3988 prepareUntrackedReviewIndexOrReason(cwd, pathArgs, onlyPath, true).pipe(
3989 Effect.map((result) => ("unavailable" in result ? null : result)),
3990 );
3991
3992 const resolveReviewMergeBase = Effect.fn("resolveReviewMergeBase")(function* (
3993 cwd: string,
3994 branch: string | null,
3995 explicitBaseRef?: string,
3996 knownOriginDefaultBranch: string | null = null,
3997 ) {
3998 const base =
3999 explicitBaseRef !== undefined
4000 ? ((yield* resolveComparisonBaseRef(cwd, explicitBaseRef)) ?? {
4001 baseRef: explicitBaseRef,
4002 comparisonRef:
4003 !explicitBaseRef.startsWith("refs/") && (yield* branchExists(cwd, explicitBaseRef))
4004 ? `refs/heads/${explicitBaseRef}`
4005 : explicitBaseRef,
4006 })
4007 : branch
4008 ? yield* resolveBaseBranchForNoUpstream(cwd, branch, {
4009 allowRemoteOfCurrent: true,
4010 knownOriginDefaultBranch,
4011 }).pipe(Effect.orElseSucceed(() => null))
4012 : null;
4013 if (base === null) return { baseRef: null, mergeBase: "HEAD" };
4014 const { baseRef, comparisonRef } = base;
4015 const args = ["merge-base", "--end-of-options", comparisonRef, "HEAD"];
4016 const result = yield* executeGit("GitVcsDriver.resolveReviewMergeBase", cwd, args, {
4017 allowNonZeroExit: true,
4018 });
4019 const mergeBase = result.stdout.trim();
4020 if (result.exitCode !== 0 || mergeBase.length === 0) {
4021 const head = yield* executeGit(
4022 "GitVcsDriver.resolveReviewMergeBase.head",
4023 cwd,
4024 ["rev-parse", "--verify", "--quiet", "HEAD"],
4025 { allowNonZeroExit: true },
4026 );
4027 if (explicitBaseRef === undefined && head.exitCode !== 0) {
4028 return { baseRef: null, mergeBase: "HEAD" };
4029 }
4030 return yield* new GitCommandError({
4031 ...gitCommandContext({ operation: "GitVcsDriver.resolveReviewMergeBase", cwd, args }),
4032 detail: `Could not find a common commit between '${baseRef}' and HEAD.`,
4033 exitCode: result.exitCode,
4034 });
4035 }
4036 return { baseRef, mergeBase };
4037 });
4038
4039 const readBranchChangeTotals = Effect.fn("readBranchChangeTotals")(function* (
4040 cwd: string,
4041 branch: string | null,
4042 options?: {
4043 readonly knownOriginDefaultBranch: string | null;
4044 readonly untrackedRoots: ReadonlyArray<string>;
4045 readonly headOid: string | null;
4046 readonly indexPath?: string;
4047 },
4048 ) {
4049 const resolved = yield* resolveReviewMergeBase(
4050 cwd,
4051 branch,
4052 undefined,
4053 options?.knownOriginDefaultBranch ?? null,
4054 );
4055 // A rename after `git status` read HEAD moves the base config away, so the base was guessed.
4056 const { baseRef, mergeBase } =
4057 branch === null || (yield* branchExists(cwd, branch))
4058 ? resolved
4059 : { baseRef: null, mergeBase: "HEAD" };
4060 // A moved HEAD or merge base skips the backoff and diffs again.
4061 const diffKey = options?.headOid ? `${options.headOid}\0${mergeBase}` : null;
4062 const diffFailure = branchTotalsDiffFailures.get(cwd);
4063 if (
4064 diffFailure !== undefined &&
4065 diffFailure.key === diffKey &&
4066 (yield* Clock.currentTimeMillis) < diffFailure.retryAt
4067 ) {
4068 return yield* new GitCommandError({
4069 operation: "GitVcsDriver.readBranchChangeTotals",
4070 command: "git diff --numstat",
4071 cwd,
4072 detail: diffFailure.detail,
4073 });
4074 }
4075 const roots = options?.untrackedRoots ?? [];
4076 // Bound pathspec matching work and stay below Windows' command-line limit.
4077 const pathspecs =
4078 roots.length <= 128 && roots.reduce((length, root) => length + root.length + 16, 0) < 8_000
4079 ? roots.map((root) => `:(top,literal)${root}`)
4080 : [];
4081 // Changed untracked roots skip the backoff and scan again.
4082 const rootsKey = roots.join("\0");
4083 const remembered = untrackedTotalsFailures.get(cwd);
4084 if (
4085 remembered !== undefined &&
4086 remembered.roots === rootsKey &&
4087 (yield* Clock.currentTimeMillis) < remembered.retryAt
4088 ) {
4089 return yield* new GitCommandError({
4090 operation: "GitVcsDriver.readBranchChangeTotals",
4091 command: "git ls-files",
4092 cwd,
4093 detail: remembered.detail,
4094 });
4095 }
4096 // Status always lists untracked files, so no roots means there are none to scan.
4097 const untracked =
4098 roots.length === 0
4099 ? { env: undefined, omitted: false }
4100 : yield* prepareUntrackedReviewIndexOrReason(
4101 cwd,
4102 pathspecs,
4103 undefined,
4104 false,
4105 options?.indexPath,
4106 );
4107 if ("unavailable" in untracked) {
4108 const count = remembered?.roots === rootsKey ? remembered.count + 1 : 1;
4109 untrackedTotalsFailures.delete(cwd);
4110 untrackedTotalsFailures.set(cwd, {
4111 roots: rootsKey,
4112 count,
4113 retryAt:
4114 (yield* Clock.currentTimeMillis) +
4115 Math.min(UNTRACKED_TOTALS_RETRY_MIN_MS * 2 ** (count - 1), UNTRACKED_TOTALS_RETRY_MAX_MS),
4116 detail: untracked.unavailable,
4117 });
4118 if (untrackedTotalsFailures.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) {
4119 const oldestKey = untrackedTotalsFailures.keys().next().value;
4120 if (oldestKey !== undefined) untrackedTotalsFailures.delete(oldestKey);
4121 }
4122 return yield* new GitCommandError({
4123 operation: "GitVcsDriver.readBranchChangeTotals",
4124 command: "git ls-files",
4125 cwd,
4126 detail: untracked.unavailable,
4127 });
4128 }
4129 untrackedTotalsFailures.delete(cwd);
4130 const readNumstat = (ref: string) =>
4131 executeGit(
4132 "GitVcsDriver.readBranchChangeTotals",
4133 cwd,
4134 // Plumbing: porcelain diff refreshes and rewrites the real index, taking index.lock.
4135 ["diff-index", "-M", "--numstat", "-z", ref, "--"],
4136 {
4137 allowNonZeroExit: true,
4138 maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES,
4139 env: untracked.env,
4140 },
4141 );
4142 let result = yield* readNumstat(mergeBase).pipe(
4143 Effect.tapError((error) =>
4144 Effect.gen(function* () {
4145 if (diffKey === null) return;
4146 const count = diffFailure?.key === diffKey ? diffFailure.count + 1 : 1;
4147 branchTotalsDiffFailures.delete(cwd);
4148 branchTotalsDiffFailures.set(cwd, {
4149 key: diffKey,
4150 count,
4151 retryAt:
4152 (yield* Clock.currentTimeMillis) +
4153 Math.min(
4154 UNTRACKED_TOTALS_RETRY_MIN_MS * 2 ** (count - 1),
4155 UNTRACKED_TOTALS_RETRY_MAX_MS,
4156 ),
4157 detail: error.detail,
4158 });
4159 if (branchTotalsDiffFailures.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) {
4160 const oldestKey = branchTotalsDiffFailures.keys().next().value;
4161 if (oldestKey !== undefined) branchTotalsDiffFailures.delete(oldestKey);
4162 }
4163 }),
4164 ),
4165 );
4166 branchTotalsDiffFailures.delete(cwd);
4167 if (result.exitCode !== 0 && mergeBase === "HEAD" && isUnbornHeadStderr(result.stderr)) {
4168 result = yield* readNumstat(yield* readEmptyTreeHash(cwd));
4169 }
4170 if (result.exitCode !== 0) {
4171 return yield* new GitCommandError({
4172 operation: "GitVcsDriver.readBranchChangeTotals",
4173 command: "git diff --numstat",
4174 cwd,
4175 detail: "Could not read Changes totals.",
4176 exitCode: result.exitCode,
4177 });
4178 }
4179 let insertions = 0;
4180 let deletions = 0;
4181 for (const file of parseReviewNumstat(result.stdout)) {
4182 insertions += file.additions;
4183 deletions += file.deletions;
4184 }
4185 return { baseRef, insertions, deletions };
4186 }, Effect.scoped);
4187
4188 const reviewCommitError = (cwd: string, detail: string) =>
4189 new GitCommandError({
4190 operation: "GitVcsDriver.reviewCommit",
4191 command: "git cat-file",
4192 cwd,
4193 detail,
4194 });
4195
4196 const resolveReviewCommit = Effect.fn("resolveReviewCommit")(function* (
4197 cwd: string,
4198 sha: string,
4199 ) {
4200 if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(sha)) {
4201 return yield* reviewCommitError(cwd, "Selected commit is invalid or no longer available.");
4202 }
4203 const present = yield* executeGit(
4204 "GitVcsDriver.reviewCommit.present",
4205 cwd,
4206 ["cat-file", "-e", `${sha}^{commit}`],
4207 { allowNonZeroExit: true, env: { GIT_NO_LAZY_FETCH: "1" } },
4208 );
4209 if (present.exitCode !== 0) {
4210 return yield* reviewCommitError(cwd, "Selected commit is invalid or no longer available.");
4211 }
4212 // The raw object keeps the parents a shallow clone grafts away, so a boundary is not a root.
4213 const object = yield* runGitStdout("GitVcsDriver.reviewCommit.parents", cwd, [
4214 "cat-file",
4215 "commit",
4216 sha,
4217 ]);
4218 const secondLine = object.split("\n", 2)[1];
4219 const firstParent = secondLine?.startsWith("parent ") ? secondLine.slice(7) : undefined;
4220 if (firstParent !== undefined) {
4221 const parent = yield* executeGit(
4222 "GitVcsDriver.reviewCommit.parent",
4223 cwd,
4224 ["cat-file", "-e", `${firstParent}^{commit}`],
4225 { allowNonZeroExit: true, env: { GIT_NO_LAZY_FETCH: "1" } },
4226 );
4227 if (parent.exitCode !== 0) {
4228 return yield* reviewCommitError(cwd, "Selected commit's parent is not available locally.");
4229 }
4230 }
4231 return { sha: sha.toLowerCase(), parent: firstParent ?? (yield* readEmptyTreeHash(cwd)) };
4232 });
4233
4234 const readReviewCommitMessage = Effect.fn("GitVcsDriver.readReviewCommitMessage")(function* (
4235 cwd: string,
4236 sha: string,
4237 ) {
4238 const result = yield* executeGit(
4239 "GitVcsDriver.readReviewCommitMessage",
4240 cwd,
4241 ["show", "-s", "--no-notes", "--no-show-signature", "--format=%B", sha],
4242 { maxOutputBytes: 8_192, appendTruncationMarker: true },
4243 );
4244 const endOfSubject = result.stdout.indexOf("\n");
4245 return {
4246 subject: result.stdout.slice(0, endOfSubject < 0 ? undefined : endOfSubject).slice(0, 300),
4247 };
4248 });
4249
4250 const getReviewBranchCommits = Effect.fn("getReviewBranchCommits")(function* (
4251 input: ReviewBranchCommitsInput,
4252 ) {
4253 const repository = yield* resolveReviewRepository(input.cwd, true);
4254 if (!repository?.worktreeRoot) return { commits: [], truncated: false };
4255 const cwd = repository.worktreeRoot;
4256 const head = yield* executeGit(
4257 "GitVcsDriver.getReviewBranchCommits.head",
4258 cwd,
4259 ["rev-parse", "--verify", "--quiet", "HEAD"],
4260 { allowNonZeroExit: true },
4261 );
4262 if (head.exitCode !== 0) {
4263 if (head.exitCode === 1 && head.stderr.trim() === "") {
4264 return { commits: [], truncated: false };
4265 }
4266 return yield* reviewCommitError(cwd, "Could not resolve the current branch commit.");
4267 }
4268 const { mergeBase } = yield* resolveReviewMergeBase(
4269 cwd,
4270 repository.currentBranch,
4271 input.baseRef,
4272 );
4273 const result = yield* executeGit(
4274 "GitVcsDriver.getReviewBranchCommits",
4275 cwd,
4276 [
4277 "log",
4278 "-z",
4279 "--no-notes",
4280 "--no-show-signature",
4281 "--format=%H%x00%s%x00%cI",
4282 `--max-count=${REVIEW_BRANCH_COMMIT_LIMIT + 1}`,
4283 `${mergeBase}..HEAD`,
4284 ],
4285 {
4286 maxOutputBytes: REVIEW_BRANCH_COMMIT_MAX_OUTPUT_BYTES,
4287 appendTruncationMarker: true,
4288 },
4289 );
4290 if (!result.stdoutTruncated && result.stdout.length > 0 && !result.stdout.endsWith("\0")) {
4291 return yield* reviewCommitError(cwd, "Could not read branch commit metadata.");
4292 }
4293 const fields = result.stdout.split("\0");
4294 const completeFieldCount = fields.length - 1;
4295 const commits: Array<{ sha: string; subject: string; committedAt: string }> = [];
4296 for (
4297 let index = 0;
4298 index + 2 < completeFieldCount && commits.length <= REVIEW_BRANCH_COMMIT_LIMIT;
4299 index += 3
4300 ) {
4301 const sha = fields[index];
4302 const subject = fields[index + 1];
4303 const committedAt = fields[index + 2];
4304 if (
4305 !sha ||
4306 subject === undefined ||
4307 !committedAt ||
4308 !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(sha)
4309 ) {
4310 return yield* reviewCommitError(cwd, "Could not read branch commit metadata.");
4311 }
4312 commits.push({ sha, subject: subject.slice(0, REVIEW_BRANCH_SUBJECT_LIMIT), committedAt });
4313 }
4314 if (result.stdoutTruncated && commits.length === 0) {
4315 return yield* reviewCommitError(cwd, "Branch commit metadata exceeds the response limit.");
4316 }
4317 return {
4318 commits: commits.slice(0, REVIEW_BRANCH_COMMIT_LIMIT),
4319 truncated: result.stdoutTruncated || commits.length > REVIEW_BRANCH_COMMIT_LIMIT,
4320 };
4321 });
4322
4323 const getReviewDiffPreview = Effect.fn("getReviewDiffPreview")(function* (
4324 input: ReviewDiffPreviewInput,
4325 ) {
4326 const pathArgs = input.file
4327 ? [input.file.path, ...(input.file.previousPath ? [input.file.previousPath] : [])].map(
4328 (path) => `:(top,literal)${path}`,
4329 )
4330 : [];
4331 const patchLimit = input.file
4332 ? REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES
4333 : REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES;
4334 const sourceKind = input.file?.sourceKind ?? input.sourceKind;
4335 const needsCurrentBranch =
4336 input.commitSha === undefined &&
4337 input.file?.sourceKind !== "commit" &&
4338 sourceKind !== "working-tree";
4339 const repository = yield* resolveReviewRepository(input.cwd, needsCurrentBranch).pipe(
4340 Effect.catchTags({
4341 GitCommandError: (error) =>
4342 isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error),
4343 }),
4344 );
4345 if (!repository?.worktreeRoot) {
4346 return {
4347 cwd: input.cwd,
4348 generatedAt: yield* DateTime.now,
4349 sources: [],
4350 };
4351 }
4352
4353 const cwd = repository.worktreeRoot;
4354 const hashDiff = (diff: string, files: ReadonlyArray<ReviewDiffFileStat>) =>
4355 digest.digest(Digest.sha256, new TextEncoder().encode(JSON.stringify([diff, files]))).pipe(
4356 Effect.map(Hex.encode),
4357 Effect.mapError(
4358 (cause) =>
4359 new GitCommandError({
4360 operation: "GitVcsDriver.getReviewDiffPreview.hash",
4361 command: "crypto.digest SHA-256",
4362 cwd,
4363 detail: "Failed to hash review diff.",
4364 cause,
4365 }),
4366 ),
4367 );
4368 if (input.commitSha !== undefined || input.file?.sourceKind === "commit") {
4369 if (!input.commitSha || (input.file && input.file.sourceKind !== "commit")) {
4370 return yield* reviewCommitError(cwd, "Selected commit request is invalid.");
4371 }
4372 const commit = yield* resolveReviewCommit(cwd, input.commitSha);
4373 const { subject } = yield* readReviewCommitMessage(cwd, commit.sha);
4374 const diffArgs = [
4375 ...REVIEW_DIFF_ARGS,
4376 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
4377 ];
4378 const stat = yield* executeGit(
4379 "GitVcsDriver.getReviewDiffPreview.commitStat",
4380 cwd,
4381 [...diffArgs, "--raw", "--numstat", "-z", commit.parent, commit.sha, "--", ...pathArgs],
4382 { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES },
4383 );
4384 const files = parseReviewNumstat(stat.stdout);
4385 const patch =
4386 input.metadataOnly && !input.file
4387 ? { stdout: "", stdoutTruncated: false }
4388 : yield* executeGit(
4389 "GitVcsDriver.getReviewDiffPreview.commitPatch",
4390 cwd,
4391 [...diffArgs, "--patch", commit.parent, commit.sha, "--", ...pathArgs],
4392 { maxOutputBytes: patchLimit, appendTruncationMarker: true },
4393 );
4394 const diffHash = yield* hashDiff(patch.stdout, files);
4395 return {
4396 cwd: input.cwd,
4397 generatedAt: yield* DateTime.now,
4398 sources: [
4399 {
4400 id: commit.sha,
4401 kind: "commit" as const,
4402 title: `Commit ${commit.sha.slice(0, 7)}`,
4403 ...(subject.trim() ? { commitSubject: subject.trim() } : {}),
4404 baseRef: commit.parent,
4405 headRef: commit.sha,
4406 diff: patch.stdout,
4407 files,
4408 diffHash,
4409 truncated: patch.stdoutTruncated,
4410 ...(input.metadataOnly && !input.file ? { patchesDeferred: true } : {}),
4411 },
4412 ],
4413 };
4414 }
4415
4416 const dirtyRef = sourceKind === "branch-range" ? null : "HEAD";
4417 const review =
4418 sourceKind === "working-tree"
4419 ? { baseRef: input.baseRef ?? null, mergeBase: null }
4420 : yield* resolveReviewMergeBase(cwd, repository.currentBranch, input.baseRef);
4421
4422 const diffArgs = [
4423 ...REVIEW_DIFF_ARGS,
4424 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
4425 ];
4426 const readStats = Effect.fn("GitVcsDriver.getReviewDiffPreview.stat")(function* (
4427 ref: string,
4428 env?: NodeJS.ProcessEnv,
4429 ) {
4430 const args = [...diffArgs, "--raw", "--numstat", "-z"];
4431 const result = yield* executeGit(
4432 "GitVcsDriver.getReviewDiffPreview.stat",
4433 cwd,
4434 [...args, ref, "--", ...pathArgs],
4435 { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, env },
4436 );
4437 if (result.exitCode === 0) return { ref, files: parseReviewNumstat(result.stdout) };
4438 if (ref === "HEAD" && isUnbornHeadStderr(result.stderr)) {
4439 const emptyTree = yield* readEmptyTreeHash(cwd);
4440 const stdout = yield* runGitStdoutWithOptions(
4441 "GitVcsDriver.getReviewDiffPreview.unbornStat",
4442 cwd,
4443 [...args, emptyTree, "--", ...pathArgs],
4444 { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, env },
4445 );
4446 return { ref: emptyTree, files: parseReviewNumstat(stdout) };
4447 }
4448 return yield* new GitCommandError({
4449 operation: "GitVcsDriver.getReviewDiffPreview.stat",
4450 cwd,
4451 command: "git diff --numstat",
4452 detail: "Could not read complete diff statistics.",
4453 exitCode: result.exitCode,
4454 });
4455 });
4456 const readTrackedDiff = Effect.fn("GitVcsDriver.getReviewDiffPreview.tracked")(function* (
4457 ref: string | null,
4458 env?: NodeJS.ProcessEnv,
4459 metadataOnly = false,
4460 ) {
4461 if (ref === null) return { stdout: "", stdoutTruncated: false, files: [] };
4462 const stat = yield* readStats(ref, env);
4463 if (metadataOnly || stat.files.length === 0) {
4464 return { stdout: "", stdoutTruncated: false, files: stat.files };
4465 }
4466 const patch = yield* executeGit(
4467 "GitVcsDriver.getReviewDiffPreview.patch",
4468 cwd,
4469 [...diffArgs, "--patch", stat.ref, "--", ...pathArgs],
4470 { maxOutputBytes: patchLimit, appendTruncationMarker: true, env },
4471 );
4472 return { ...patch, files: stat.files };
4473 });
4474 const [dirtyTrackedResult, baseResult] = yield* Effect.gen(function* () {
4475 const untracked = input.trackedOnly
4476 ? { env: undefined, omitted: false }
4477 : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path);
4478 // Untracked files left out make the file list partial, so the bounded patch is sent instead.
4479 const complete = untracked !== null && !untracked.omitted;
4480 const metadataOnly = input.metadataOnly === true && !input.file && complete;
4481 const [dirty, base] =
4482 review.mergeBase === dirtyRef
4483 ? yield* readTrackedDiff(dirtyRef, untracked?.env, metadataOnly).pipe(
4484 Effect.map((result) => [result, result] as const),
4485 )
4486 : yield* Effect.all(
4487 [
4488 readTrackedDiff(dirtyRef, untracked?.env, metadataOnly),
4489 readTrackedDiff(review.mergeBase, untracked?.env, metadataOnly),
4490 ],
4491 { concurrency: 2 },
4492 );
4493 if (complete) return [dirty, base] as const;
4494 const incomplete = (ref: string | null, result: typeof dirty) =>
4495 ref === null ? result : { ...result, files: undefined, stdoutTruncated: true };
4496 return [incomplete(dirtyRef, dirty), incomplete(review.mergeBase, base)] as const;
4497 }).pipe(Effect.scoped);
4498 const dirtyFiles = dirtyTrackedResult.files;
4499 const baseFiles = baseResult.files;
4500 const dirtyDiff = dirtyTrackedResult.stdout;
4501 const baseDiff = baseResult.stdout;
4502 const [dirtyDiffHash, baseDiffHash] = yield* Effect.all([
4503 hashDiff(dirtyDiff, dirtyFiles ?? []),
4504 hashDiff(baseDiff, baseFiles ?? []),
4505 ]);
4506
4507 const sources: ReviewDiffPreviewSource[] = [
4508 {
4509 id: "working-tree",
4510 kind: "working-tree",
4511 title: "Uncommitted",
4512 baseRef: "HEAD",
4513 headRef: null,
4514 diff: dirtyDiff,
4515 ...(dirtyFiles === undefined ? {} : { files: dirtyFiles }),
4516 diffHash: dirtyDiffHash,
4517 truncated: dirtyTrackedResult.stdoutTruncated,
4518 ...(input.metadataOnly && !input.file && dirtyFiles !== undefined
4519 ? { patchesDeferred: true }
4520 : {}),
4521 },
4522 {
4523 id: "branch-range",
4524 kind: "branch-range",
4525 title: review.baseRef ? `Changes vs ${review.baseRef}` : "Changes",
4526 baseRef: review.baseRef,
4527 headRef: repository.currentBranch ?? "HEAD",
4528 diff: baseDiff,
4529 ...(baseFiles === undefined ? {} : { files: baseFiles }),
4530 diffHash: baseDiffHash,
4531 truncated: baseResult.stdoutTruncated,
4532 ...(input.metadataOnly && !input.file && baseFiles !== undefined
4533 ? { patchesDeferred: true }
4534 : {}),
4535 },
4536 ];
4537
4538 return {
4539 cwd: input.cwd,
4540 generatedAt: yield* DateTime.now,
4541 sources: input.sourceKind
4542 ? sources.filter((source) => source.kind === input.sourceKind)
4543 : sources,
4544 ...(input.trackedOnly ? { incomplete: true } : {}),
4545 };
4546 });
4547
4548 const reviewDiffFileError = (
4549 input: ReviewDiffFileContentsInput,
4550 detail: string,
4551 cause?: unknown,
4552 ) =>
4553 new GitCommandError({
4554 operation: "GitVcsDriver.getReviewDiffFileContents",
4555 command: "git",
4556 cwd: input.cwd,
4557 detail,
4558 ...(cause === undefined ? {} : { cause }),
4559 });
4560
4561 const isPathWithinRoot = (root: string, candidate: string) => {
4562 const relative = path.relative(root, candidate);
4563 return (
4564 relative === "" ||
4565 (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
4566 );
4567 };
4568
4569 const readReviewFileAtRevision = Effect.fn("readReviewFileAtRevision")(function* (
4570 input: ReviewDiffFileContentsInput,
4571 revision: string,
4572 relativePath: string,
4573 ) {
4574 const result = yield* executeGit(
4575 "GitVcsDriver.getReviewDiffFileContents.revision",
4576 input.cwd,
4577 ["show", "--end-of-options", `${revision}:${relativePath}`],
4578 { maxOutputBytes: REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES },
4579 );
4580 if (result.stdout.includes("\0")) {
4581 return yield* reviewDiffFileError(input, `Cannot expand binary file '${relativePath}'.`);
4582 }
4583 return result.stdout;
4584 });
4585
4586 const readWorkingTreeReviewFile = Effect.fn("readWorkingTreeReviewFile")(function* (
4587 input: ReviewDiffFileContentsInput,
4588 repositoryRoot: string,
4589 ) {
4590 const fileError = (stage: string, detail: string, cause?: unknown) =>
4591 new GitCommandError({
4592 operation: `GitVcsDriver.getReviewDiffFileContents.workingTree.${stage}`,
4593 command: stage,
4594 cwd: input.cwd,
4595 detail,
4596 ...(cause === undefined ? {} : { cause }),
4597 });
4598 const requestedPath = path.resolve(repositoryRoot, input.newPath);
4599 if (!isPathWithinRoot(repositoryRoot, requestedPath)) {
4600 return yield* fileError(
4601 "path.resolve",
4602 `Diff file '${input.newPath}' resolves outside the review workspace.`,
4603 );
4604 }
4605
4606 const [realRepositoryRoot, realTarget] = yield* Effect.all([
4607 fileSystem.realPath(repositoryRoot),
4608 fileSystem.realPath(requestedPath),
4609 ]).pipe(
4610 Effect.mapError((cause) =>
4611 fileError("fs.realPath", `Could not resolve diff file '${input.newPath}'.`, cause),
4612 ),
4613 );
4614 if (!isPathWithinRoot(realRepositoryRoot, realTarget)) {
4615 return yield* fileError(
4616 "fs.realPath",
4617 `Diff file '${input.newPath}' resolves outside the review workspace.`,
4618 );
4619 }
4620 if (yield* isServerInternalPath(realTarget)) {
4621 return yield* fileError("fs.realPath", `Diff file '${input.newPath}' is not available.`);
4622 }
4623
4624 const info = yield* fileSystem
4625 .stat(realTarget)
4626 .pipe(
4627 Effect.mapError((cause) =>
4628 fileError("fs.stat", `Could not inspect diff file '${input.newPath}'.`, cause),
4629 ),
4630 );
4631 if (info.type !== "File") {
4632 return yield* fileError("fs.stat", `Diff path '${input.newPath}' is not a file.`);
4633 }
4634 if (info.size > BigInt(REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES)) {
4635 return yield* fileError(
4636 "fs.stat",
4637 `Diff file '${input.newPath}' exceeds the 1 MB expansion limit.`,
4638 );
4639 }
4640
4641 const bytes = yield* fileSystem
4642 .readFile(realTarget)
4643 .pipe(
4644 Effect.mapError((cause) =>
4645 fileError("fs.readFile", `Could not read diff file '${input.newPath}'.`, cause),
4646 ),
4647 );
4648 if (bytes.includes(0)) {
4649 return yield* fileError("fs.readFile", `Cannot expand binary file '${input.newPath}'.`);
4650 }
4651 const contents = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes);
4652 if (!contents.includes("$Id:")) return contents;
4653 const collapsed = contents.replace(GIT_IDENT_KEYWORD, () => "$Id$");
4654 if (collapsed === contents) return contents;
4655 // check-attr reports both boolean ident and literal ident=set as "set".
4656 const attribute = yield* runGitStdout(
4657 "GitVcsDriver.getReviewDiffFileContents.workingTree.ident",
4658 repositoryRoot,
4659 ["check-attr", "-z", "ident", "filter", "--", input.newPath],
4660 );
4661 const attributes = attribute.split("\0");
4662 if (attributes[2] !== "set" || attributes[5] !== "unspecified") return contents;
4663
4664 // Literal filter=unspecified is indistinguishable from an absent filter in check-attr.
4665 const filters = yield* executeGit(
4666 "GitVcsDriver.getReviewDiffFileContents.workingTree.filters",
4667 repositoryRoot,
4668 ["config", "--name-only", "--get-regexp", "^filter\\.unspecified\\."],
4669 { allowNonZeroExit: true },
4670 );
4671 if (filters.exitCode !== 1 || filters.stdout.length > 0) return contents;
4672 // Probe a nonoverlapping keyword so ident conversion runs once on the actual file.
4673 const [canonicalHash, collapsedHash] = yield* Effect.all([
4674 runGitStdoutWithOptions(
4675 "GitVcsDriver.getReviewDiffFileContents.workingTree.canonicalHash",
4676 repositoryRoot,
4677 ["hash-object", "--stdin", `--path=${input.newPath}`],
4678 { stdin: "$Id: probe $" },
4679 ),
4680 runGitStdoutWithOptions(
4681 "GitVcsDriver.getReviewDiffFileContents.workingTree.collapsedHash",
4682 repositoryRoot,
4683 ["hash-object", "--stdin", `--path=${input.newPath}`],
4684 { stdin: "$Id$" },
4685 ),
4686 ]);
4687 return canonicalHash === collapsedHash ? collapsed : contents;
4688 });
4689
4690 const getReviewDiffFileContents = Effect.fn("getReviewDiffFileContents")(function* (
4691 input: ReviewDiffFileContentsInput,
4692 ) {
4693 const repositoryRoot = yield* runGitStdout(
4694 "GitVcsDriver.getReviewDiffFileContents.repositoryRoot",
4695 input.cwd,
4696 ["rev-parse", "--show-toplevel"],
4697 ).pipe(Effect.map((value) => value.trim()));
4698 if (repositoryRoot.length === 0) {
4699 return yield* reviewDiffFileError(input, "Could not resolve the Git repository root.");
4700 }
4701 if (input.sourceKind === "commit") {
4702 if (!input.headRef) {
4703 return yield* reviewDiffFileError(input, "Selected commit is no longer available.");
4704 }
4705 const commit = yield* resolveReviewCommit(input.cwd, input.headRef);
4706 if (input.baseRef !== commit.parent) {
4707 return yield* reviewDiffFileError(
4708 input,
4709 "Selected commit changed. Refresh the comparison.",
4710 );
4711 }
4712 const [oldContents, newContents] = yield* Effect.all(
4713 [
4714 input.changeType === "new"
4715 ? Effect.succeed("")
4716 : readReviewFileAtRevision(input, commit.parent, input.oldPath),
4717 input.changeType === "deleted"
4718 ? Effect.succeed("")
4719 : readReviewFileAtRevision(input, commit.sha, input.newPath),
4720 ],
4721 { concurrency: 2 },
4722 );
4723 return { oldContents, newContents };
4724 }
4725 const oldRevision =
4726 input.sourceKind === "working-tree"
4727 ? (input.baseRef ?? "HEAD")
4728 : (yield* resolveReviewMergeBase(input.cwd, null, input.baseRef ?? undefined)).mergeBase;
4729 const [oldContents, newContents] = yield* Effect.all(
4730 [
4731 input.changeType === "new"
4732 ? Effect.succeed("")
4733 : readReviewFileAtRevision(input, oldRevision, input.oldPath),
4734 input.changeType === "deleted"
4735 ? Effect.succeed("")
4736 : readWorkingTreeReviewFile(input, repositoryRoot),
4737 ],
4738 { concurrency: 2 },
4739 );
4740 return { oldContents, newContents };
4741 });
4742
4743 const readConfigValue: GitVcsDriver.GitVcsDriver["Service"]["readConfigValue"] = (cwd, key) =>
4744 runGitStdout("GitVcsDriver.readConfigValue", cwd, ["config", "--get", key], true).pipe(
4745 Effect.map((stdout) => stdout.trim()),
4746 Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
4747 );
4748
4749 // Git never waits for .git/config.lock, and git run outside T3, such as an agent's, can hold it.
4750 // Only writes that are safe to repeat retry.
4751 const retryWhileConfigLocked = <A>(effect: Effect.Effect<A, GitCommandError>) =>
4752 effect.pipe(
4753 Effect.retry({
4754 while: (error) => error.reason === "config_locked",
4755 times: 10,
4756 schedule: Schedule.spaced("50 millis"),
4757 }),
4758 );
4759
4760 const writeConfigValue: GitVcsDriver.GitVcsDriver["Service"]["writeConfigValue"] = Effect.fn(
4761 "writeConfigValue",
4762 )(function* (input) {
4763 yield* executeGitWithStableDiagnostics(
4764 "GitVcsDriver.writeConfigValue",
4765 input.cwd,
4766 ["config", input.key, input.value],
4767 { writesSharedConfig: true },
4768 ).pipe(retryWhileConfigLocked);
4769 });
4770
4771 // `git branch` writes a remote start point's upstream itself and fails outright if the
4772 // config is locked, so tracking is recorded afterwards by a write that retries.
4773 const createBranchAt = Effect.fn("createBranchAt")(function* (
4774 operation: string,
4775 input: GitVcsDriver.GitCreateBranchInput,
4776 fallbackErrorDetail: string,
4777 ) {
4778 // `git branch` does not read a lone - as the previous checkout.
4779 const startPoint = input.startPoint === "-" ? "@{-1}" : input.startPoint;
4780 yield* executeGitWithStableDiagnostics(
4781 operation,
4782 input.cwd,
4783 ["branch", "--no-track", "--", input.branch, startPoint],
4784 { fallbackErrorDetail },
4785 );
4786 const startRef = yield* executeGit(
4787 `${operation}.resolveStartPoint`,
4788 input.cwd,
4789 ["rev-parse", "--symbolic-full-name", startPoint],
4790 { allowNonZeroExit: true },
4791 ).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : "")));
4792 if (!startRef.startsWith("refs/remotes/")) return;
4793 yield* executeGitWithStableDiagnostics(
4794 `${operation}.track`,
4795 input.cwd,
4796 ["branch", `--set-upstream-to=${startRef}`, "--", input.branch],
4797 { writesSharedConfig: true },
4798 ).pipe(
4799 retryWhileConfigLocked,
4800 Effect.catch((cause) =>
4801 Effect.logWarning("created the branch without tracking its start point", { cause }),
4802 ),
4803 );
4804 });
4805
4806 const createBranch: GitVcsDriver.GitVcsDriver["Service"]["createBranch"] = Effect.fn(
4807 "createBranch",
4808 )(function* (input) {
4809 yield* refuseOptionLikeRefName("GitVcsDriver.createBranch", input.cwd, input.startPoint);
4810 yield* createBranchAt("GitVcsDriver.createBranch", input, "git branch create failed");
4811 });
4812
4813 const readBranchBase: GitVcsDriver.GitVcsDriver["Service"]["readBranchBase"] = Effect.fn(
4814 "GitVcsDriver.readBranchBase",
4815 )(function* (cwd, branch) {
4816 const base = yield* readConfigValue(cwd, branchBaseConfigKey(branch));
4817 return base ?? (yield* readConfigValue(cwd, legacyBranchBaseConfigKey(branch)));
4818 });
4819
4820 const resolveBranchBase = Effect.fn("GitVcsDriver.resolveBranchBase")(function* (
4821 cwd: string,
4822 refName: string,
4823 ) {
4824 const result = yield* executeGit(
4825 "GitVcsDriver.resolveBranchName.resolveRef",
4826 cwd,
4827 ["rev-parse", "--symbolic-full-name", "--verify", "--end-of-options", refName],
4828 { allowNonZeroExit: true },
4829 );
4830 if (result.exitCode !== 0) {
4831 const remoteName = yield* resolvePrimaryRemoteName(cwd).pipe(
4832 Effect.orElseSucceed(() => null),
4833 );
4834 return remoteName && (yield* remoteBranchExists({ cwd, remoteName, refName }))
4835 ? { baseRef: `refs/remotes/${remoteName}/${refName}`, branchName: refName }
4836 : null;
4837 }
4838 const ref = result.stdout.trim();
4839 if (ref.startsWith("refs/heads/")) {
4840 const branchName = ref.slice("refs/heads/".length);
4841 return { baseRef: ref, branchName };
4842 }
4843 if (!ref.startsWith("refs/remotes/")) return null;
4844 const remoteNames = yield* listRemoteNames(cwd);
4845 const remoteRef = parseRemoteRefWithRemoteNames(
4846 ref.slice("refs/remotes/".length),
4847 remoteNames.toSorted((left, right) => right.length - left.length),
4848 );
4849 return remoteRef ? { baseRef: ref, branchName: remoteRef.branchName } : null;
4850 });
4851
4852 const resolveBranchName = Effect.fn("GitVcsDriver.resolveBranchName")(function* (
4853 cwd: string,
4854 refName: string,
4855 ) {
4856 const base = yield* resolveBranchBase(cwd, refName);
4857 return base?.branchName ?? null;
4858 });
4859
4860 const readGitRefsSnapshot = Effect.fn("readGitRefsSnapshot")(function* (gitCommonDir: string) {
4861 const fetchCwd =
4862 path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
4863 const gitDirArgs = ["--git-dir", gitCommonDir] as const;
4864 const [refsResult, defaultRefResult, worktreeListResult, remoteNamesResult] = yield* Effect.all(
4865 [
4866 executeGitWithStableDiagnostics(
4867 "GitVcsDriver.listRefs.snapshotRefs",
4868 fetchCwd,
4869 [
4870 ...gitDirArgs,
4871 "for-each-ref",
4872 "--format=%(refname)%09%(committerdate:unix)%09%(symref)%09%(upstream)",
4873 "refs/heads",
4874 "refs/remotes",
4875 ],
4876 {
4877 timeoutMs: 30_000,
4878 maxOutputBytes: 16 * 1024 * 1024,
4879 fallbackErrorDetail: "Git ref snapshot enumeration failed.",
4880 },
4881 ),
4882 executeGit(
4883 "GitVcsDriver.listRefs.defaultRef",
4884 fetchCwd,
4885 [
4886 ...gitDirArgs,
4887 "rev-parse",
4888 "--verify",
4889 "--quiet",
4890 "--symbolic-full-name",
4891 "refs/remotes/origin/HEAD",
4892 ],
4893 {
4894 timeoutMs: 5_000,
4895 allowNonZeroExit: true,
4896 },
4897 ),
4898 executeWorktreeList("GitVcsDriver.listRefs.worktreeList", fetchCwd, gitDirArgs, {
4899 timeoutMs: 30_000,
4900 allowNonZeroExit: true,
4901 maxOutputBytes: 16 * 1024 * 1024,
4902 }),
4903 executeGit("GitVcsDriver.listRefs.remoteNames", fetchCwd, [...gitDirArgs, "remote"], {
4904 timeoutMs: 5_000,
4905 allowNonZeroExit: true,
4906 }),
4907 ],
4908 { concurrency: 2 },
4909 );
4910
4911 const remoteNames =
4912 remoteNamesResult.exitCode === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
4913 if (remoteNamesResult.exitCode !== 0 && remoteNamesResult.stderr.trim().length > 0) {
4914 yield* Effect.logWarning(
4915 `GitVcsDriver.listRefs: remote name lookup returned code ${remoteNamesResult.exitCode} for ${gitCommonDir}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
4916 );
4917 }
4918 const defaultBranch =
4919 defaultRefResult.exitCode === 0
4920 ? parseDefaultBranchFromRemoteHeadRef(defaultRefResult.stdout, "origin")
4921 : null;
4922 const parsedWorktreeEntries =
4923 worktreeListResult.exitCode === 0
4924 ? [...parseWorktreeBranchPaths(worktreeListResult.stdout)].map(
4925 ([branchName, worktreePath]) =>
4926 [branchName, path.normalize(path.resolve(worktreePath))] as const,
4927 )
4928 : [];
4929 // Without `core.worktree`, Git reports a separate git dir as the main checkout.
4930 const normalizedGitCommonDir = path.normalize(path.resolve(gitCommonDir));
4931 const existingWorktreeEntries = yield* Effect.filter(
4932 parsedWorktreeEntries,
4933 ([, worktreePath]) =>
4934 worktreePath === normalizedGitCommonDir
4935 ? Effect.succeed(false)
4936 : fileSystem.stat(worktreePath).pipe(
4937 Effect.as(true),
4938 Effect.orElseSucceed(() => false),
4939 ),
4940 { concurrency: 16 },
4941 );
4942 const worktreeMap = new Map(existingWorktreeEntries);
4943 const localBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = [];
4944 const remoteBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = [];
4945
4946 for (const line of refsResult.stdout.split("\n")) {
4947 if (line.length === 0) continue;
4948 const [fullRefName, lastCommitRaw, symbolicTarget, upstreamRef] = line.split("\t");
4949 if (!fullRefName || symbolicTarget) continue;
4950 const parsedLastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
4951 const lastCommit = Number.isFinite(parsedLastCommit) ? parsedLastCommit : 0;
4952
4953 if (fullRefName.startsWith("refs/heads/")) {
4954 const name = fullRefName.slice("refs/heads/".length);
4955 localBranches.push({
4956 ref: {
4957 name,
4958 current: false,
4959 isRemote: false,
4960 isDefault: name === defaultBranch,
4961 worktreePath: worktreeMap.get(name) ?? null,
4962 ...(upstreamRef ? { upstreamRef } : {}),
4963 },
4964 lastCommit,
4965 });
4966 continue;
4967 }
4968 if (!fullRefName.startsWith("refs/remotes/")) continue;
4969
4970 const name = fullRefName.slice("refs/remotes/".length);
4971 const parsedRemoteRef = parseRemoteRefWithRemoteNames(name, remoteNames);
4972 const remoteBranch: VcsRef = {
4973 name,
4974 current: false,
4975 isRemote: true,
4976 isDefault:
4977 defaultBranch !== null &&
4978 parsedRemoteRef?.remoteName === "origin" &&
4979 parsedRemoteRef.branchName === defaultBranch,
4980 worktreePath: null,
4981 ...(parsedRemoteRef ? { remoteName: parsedRemoteRef.remoteName } : {}),
4982 };
4983 remoteBranches.push({ ref: remoteBranch, lastCommit });
4984 }
4985
4986 const byRecencyThenName = (
4987 left: { readonly ref: VcsRef; readonly lastCommit: number },
4988 right: { readonly ref: VcsRef; readonly lastCommit: number },
4989 ) =>
4990 left.lastCommit !== right.lastCommit
4991 ? right.lastCommit - left.lastCommit
4992 : left.ref.name.localeCompare(right.ref.name);
4993
4994 return {
4995 defaultBranch,
4996 localBranches: localBranches.toSorted(byRecencyThenName).map(({ ref }) => ref),
4997 remoteBranches: remoteBranches.toSorted(byRecencyThenName).map(({ ref }) => ref),
4998 hasPrimaryRemote: remoteNames.length > 0,
4999 } satisfies GitRefsSnapshot;
5000 });
Showing first 5,000 of 6,600 lines. View raw