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

main
ts 3,899 lines 141 KB
Raw
1 import * as Arr from "effect/Array";
2 import * as Cache from "effect/Cache";
3 import * as Clock from "effect/Clock";
4 import * as Config from "effect/Config";
5 import * as Context from "effect/Context";
6 import * as SecureRandom from "effect/crypto/SecureRandom";
7 import * as ByteSize from "effect/ByteSize";
8 import * as DateTime from "effect/DateTime";
9 import * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Exit from "effect/Exit";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Layer from "effect/Layer";
14 import * as Option from "effect/Option";
15 import * as Order from "effect/Order";
16 import * as Path from "effect/Path";
17 import * as PubSub from "effect/PubSub";
18 import * as Ref from "effect/Ref";
19 import * as Schema from "effect/Schema";
20 import * as Scope from "effect/Scope";
21 import * as Semaphore from "effect/Semaphore";
22 import * as Stream from "effect/Stream";
23 import {
24 GitActionProgressEvent,
25 GitActionProgressPhase,
26 GitCommandError,
27 GitPreparePullRequestThreadInput,
28 GitPreparePullRequestThreadResult,
29 GitPullRequestRefInput,
30 GitResolvePullRequestResult,
31 GitRunStackedActionInput,
32 GitRunStackedActionResult,
33 GitStackedAction,
34 VcsStatusInput,
35 type VcsStatusLocalResult,
36 type VcsStatusRemoteResult,
37 VcsStatusResult,
38 ModelSelection,
39 type OrchestrationV2TurnItem,
40 type ProjectId,
41 SourceControlProviderError,
42 type SourceControlWritingStyleSettings,
43 type ThreadId,
44 type ThreadPullRequestKey,
45 type VcsCreateWorktreeInput,
46 type VcsCreateWorktreeResult,
47 } from "@t3tools/contracts";
48 import {
49 hasProjectSettingsOverrides,
50 resolveProjectSettings,
51 } from "@t3tools/shared/projectSettings";
52 import {
53 mergeGitStatusParts,
54 resolveAutoFeatureBranchName,
55 sanitizeBranchFragment,
56 sanitizeFeatureBranchName,
57 } from "@t3tools/shared/git";
58 import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
59 import {
60 type ChangeRequestTerminology,
61 UNKNOWN_SOURCE_CONTROL_CLIENT,
62 } from "@t3tools/source-control-core/shared/definition";
63 import {
64 normalizeThreadPullRequestKey,
65 threadPullRequestKeyOf,
66 } from "../sourceControl/threadPullRequests.ts";
67 import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
68
69 import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts";
70 import {
71 historicalMessage,
72 renderHistory,
73 selectHistory,
74 } from "@t3tools/provider-core/server/handoffBudget";
75 import * as TextGeneration from "../textGeneration/TextGeneration.ts";
76 import {
77 conventionalCommitsTextGenerationPolicy,
78 customTextGenerationPolicy,
79 repositoryConventionsTextGenerationPolicy,
80 } from "../textGeneration/TextGenerationPresets.ts";
81 import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
82 import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
83 import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
84 import * as PullRequestService from "../pullRequest/PullRequestService.ts";
85 import { createdPullRequestKey } from "./linkCreatedPullRequest.ts";
86 import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
87 import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
88 import { detachStackFrame } from "./detachStackFrame.ts";
89 import * as ServerSettings from "../serverSettings.ts";
90 import type { GitManagerServiceError } from "@t3tools/contracts";
91 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
92 import { isNonRepositoryGitStderr } from "../vcs/GitVcsDriverCore.ts";
93 import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
94 import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
95 import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
96 import type { ChangeRequest } from "@t3tools/contracts";
97
98 export interface GitActionProgressReporter {
99 readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
100 }
101
102 export interface GitRunStackedActionOptions {
103 readonly actionId?: string;
104 readonly progressReporter?: GitActionProgressReporter;
105 }
106
107 export interface GitLocalStatusOptions {
108 /** Defaults to true. The branch-wide totals cost about half of a local status read. */
109 readonly includeBranchChanges?: boolean;
110 }
111
112 export interface GitRemoteStatusOptions extends GitVcsDriver.GitRemoteStatusOptions {
113 readonly refreshMissingPullRequest?: boolean;
114 }
115
116 export type GitBranchPullRequest = NonNullable<VcsStatusResult["pr"]> & {
117 readonly repositoryKey: string | null;
118 readonly updatedAt: string | null;
119 readonly closedAt?: string | null;
120 readonly mergedAt?: string | null;
121 readonly headSha?: string | null;
122 };
123
124 interface SourceControlTextGenerationSettings {
125 readonly modelSelection: ModelSelection;
126 readonly projectId: ProjectId | null;
127 readonly style: SourceControlWritingStyleSettings;
128 }
129
130 export interface GitCreatePullRequestResult {
131 readonly status: "created" | "opened_existing";
132 /** Absent when the host accepted the PR but did not list it back yet. */
133 readonly url?: string;
134 readonly number?: number;
135 readonly baseBranch: string;
136 readonly headBranch: string;
137 readonly title: string;
138 }
139
140 export class GitManager extends Context.Service<
141 GitManager,
142 {
143 readonly createWorktree: (
144 input: VcsCreateWorktreeInput,
145 options?: GitVcsDriver.CreateWorktreeOptions,
146 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
147 readonly status: (
148 input: VcsStatusInput,
149 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
150 readonly localStatus: (
151 input: VcsStatusInput,
152 options?: GitLocalStatusOptions,
153 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
154 readonly remoteStatus: (
155 input: VcsStatusInput,
156 options?: GitRemoteStatusOptions,
157 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
158 /**
159 * refresh queries the host; freshGitState rereads only git state and is required before persisting.
160 * A merged or closed answer is confirmed against git state unless confirmTerminal is false;
161 * callers that opt out confirm before acting on it.
162 */
163 readonly branchPullRequest: (
164 input: { readonly cwd: string; readonly branch: string },
165 options?: {
166 readonly refresh?: boolean;
167 readonly freshGitState?: boolean;
168 readonly confirmTerminal?: boolean;
169 },
170 ) => Effect.Effect<GitBranchPullRequest | null, GitManagerServiceError>;
171 /** Whether T3 checked this pull request out onto the branch, which ties it to later threads. */
172 readonly checkedOutPullRequest: (input: {
173 readonly cwd: string;
174 readonly branch: string;
175 readonly url: string;
176 }) => Effect.Effect<boolean>;
177 readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
178 readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
179 readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
180 readonly resolvePullRequest: (
181 input: GitPullRequestRefInput,
182 ) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
183 readonly preparePullRequestThread: (
184 input: GitPreparePullRequestThreadInput,
185 ) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
186 readonly runStackedAction: (
187 input: GitRunStackedActionInput,
188 options?: GitRunStackedActionOptions,
189 ) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
190 /** Pushes the checkout's branch when needed, then opens its PR or returns the one already open. */
191 readonly createPullRequest: (input: {
192 readonly cwd: string;
193 readonly projectId: ProjectId;
194 readonly title: string;
195 readonly body: string;
196 readonly baseBranch?: string | undefined;
197 readonly draft?: boolean | undefined;
198 }) => Effect.Effect<GitCreatePullRequestResult, GitManagerServiceError>;
199 readonly subscribePullRequestStateChanges: Effect.Effect<
200 Stream.Stream<ThreadPullRequestKey>,
201 never,
202 Scope.Scope
203 >;
204 }
205 >()("t3/git/GitManager") {}
206
207 const COMMIT_TIMEOUT_MS = 10 * 60_000;
208 const MAX_PROGRESS_TEXT_LENGTH = 500;
209 const SHORT_SHA_LENGTH = 7;
210 const TOAST_DESCRIPTION_MAX = 72;
211 const STATUS_RESULT_CACHE_TTL = Duration.seconds(1);
212 const STATUS_RESULT_CACHE_CAPACITY = 2_048;
213 const PR_LOOKUP_CACHE_TTL = Duration.seconds(60);
214 const PR_LOOKUP_NO_OPEN_PR_CACHE_TTL = Duration.minutes(5);
215 const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20);
216 const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15);
217 const PR_LOOKUP_CACHE_CAPACITY = 2_048;
218 const PR_LOOKUP_GIT_STATE_TTL = Duration.minutes(5);
219 const SETTLED_PR_LOOKUP_RECHECK_INTERVAL = Duration.minutes(15);
220 // Shared by every background caller (backfill, settlement, cleanup), so startup discovery
221 // cannot fill the git and forge process slots that foreground work also needs.
222 const BRANCH_PR_LOOKUP_CONCURRENCY = 4;
223 const PR_THREAD_CONTEXT_BYTES = 16_000;
224 const PR_THREAD_COMMAND_OUTPUT_CHARS = 2_000;
225 const isSourceControlProviderError = Schema.is(SourceControlProviderError);
226
227 /**
228 * Throttled lookups fail fast, so a flat failure TTL would retry faster than a healthy
229 * lookup refreshes. Backing off per branch keeps a 429 from becoming sustained pressure.
230 */
231 function prLookupFailureTtl(consecutiveFailures: number): Duration.Duration {
232 const exponent = Math.max(0, consecutiveFailures - 1);
233 const backoffMs = Duration.toMillis(PR_LOOKUP_FAILURE_BASE_TTL) * Math.pow(2, exponent);
234 return Duration.min(Duration.millis(backoffMs), PR_LOOKUP_FAILURE_MAX_TTL);
235 }
236 type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
237 type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
238 type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>;
239
240 function isNotGitRepositoryError(error: GitCommandError): boolean {
241 return isNonRepositoryGitStderr(error.message);
242 }
243
244 interface OpenPrInfo {
245 number: number;
246 title: string;
247 url: string;
248 baseRefName: string;
249 headRefName: string;
250 }
251
252 interface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo {
253 state: "open" | "closed" | "merged";
254 isDraft?: boolean;
255 closedAt?: string | null;
256 mergedAt?: string | null;
257 updatedAt: Option.Option<DateTime.Utc>;
258 headSha?: string | undefined;
259 }
260
261 const pullRequestUpdatedAtDescOrder: Order.Order<PullRequestInfo> = Order.mapInput(
262 Order.flip(Option.makeOrder(DateTime.Order)),
263 (pullRequest) => pullRequest.updatedAt,
264 );
265
266 interface ResolvedPullRequest {
267 number: number;
268 title: string;
269 url: string;
270 baseBranch: string;
271 headBranch: string;
272 state: "open" | "closed" | "merged";
273 }
274
275 interface PullRequestHeadRemoteInfo {
276 isCrossRepository?: boolean | undefined;
277 headRepositoryNameWithOwner?: string | null | undefined;
278 headRepositoryOwnerLogin?: string | null | undefined;
279 }
280
281 interface BranchHeadContext {
282 localBranch: string;
283 headBranch: string;
284 headSelectors: ReadonlyArray<string>;
285 preferredHeadSelector: string;
286 remoteName: string | null;
287 headRemoteUrlKey: string | null;
288 targetRemoteUrlKey: string | null;
289 headRepositoryNameWithOwner: string | null;
290 headRepositoryOwnerLogin: string | null;
291 isCrossRepository: boolean;
292 }
293
294 export function pullRequestRepositoryKey(value: string): string | null {
295 const repositoryUrl = sourceControlDefinitions.parseChangeRequestUrl(value)?.link.repositoryUrl;
296 return repositoryUrl === undefined
297 ? null
298 : sourceControlDefinitions.repositoryKeyFromRemote(repositoryUrl);
299 }
300
301 /** Null when the host did not name the repository the head lives in. */
302 function resolveHeadRepositoryNameWithOwner(pullRequest: PullRequestHeadRemoteInfo): string | null {
303 return normalizeOptionalString(pullRequest.headRepositoryNameWithOwner);
304 }
305
306 // Both names `resolvePullRequestWorktreeLocalBranchName` gives a fork pull request's branch.
307 function isPullRequestWorktreeLocalBranchName(branch: string): boolean {
308 return /^t3code[/-]pr-\d+[/-]/u.test(branch);
309 }
310
311 function resolvePullRequestWorktreeLocalBranchName(
312 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
313 localBranches: ReadonlySet<string>,
314 ): string {
315 if (!pullRequest.isCrossRepository) {
316 return pullRequest.headBranch;
317 }
318
319 const sanitizedHeadBranch = sanitizeBranchFragment(pullRequest.headBranch).trim();
320 const suffix = sanitizedHeadBranch.length > 0 ? sanitizedHeadBranch : "head";
321 // Git cannot create a ref whose path is a parent or child of an existing one (`t3code` blocks `t3code/...`).
322 const isCreatable = (name: string) =>
323 !name
324 .split("/")
325 .slice(0, -1)
326 .some((_, index, segments) => localBranches.has(segments.slice(0, index + 1).join("/"))) &&
327 ![...localBranches].some((branch) => branch.startsWith(`${name}/`));
328 const preferred = `t3code/pr-${pullRequest.number}/${suffix}`;
329 if (isCreatable(preferred)) {
330 return preferred;
331 }
332 const flat = `t3code-pr-${pullRequest.number}-${suffix.replaceAll("/", "-")}`;
333 for (let attempt = 1; ; attempt++) {
334 const candidate = attempt === 1 ? flat : `${flat}-${attempt}`;
335 if (isCreatable(candidate)) {
336 return candidate;
337 }
338 }
339 }
340
341 export function parseRepositoryNameWithOwnerFromRemoteUrl(
342 url: string | null,
343 provider?: Pick<
344 SourceControlProvider.SourceControlProvider["Service"],
345 "repositoryNameFromRemoteUrl"
346 >,
347 ): string | null {
348 const trimmed = url?.trim() ?? "";
349 if (trimmed.length === 0) return null;
350 return (
351 provider?.repositoryNameFromRemoteUrl?.(trimmed) ??
352 SourceControlProvider.repositoryPathFromRemoteUrl(trimmed)
353 );
354 }
355
356 function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null {
357 const trimmed = nameWithOwner?.trim() ?? "";
358 if (trimmed.length === 0) {
359 return null;
360 }
361 // The first segment only: a nested path's owner is its top-level group. The full path
362 // distinguishes subgroups.
363 const [ownerLogin] = trimmed.split("/");
364 const normalizedOwnerLogin = ownerLogin?.trim() ?? "";
365 return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null;
366 }
367
368 function normalizeOptionalString(value: string | null | undefined): string | null {
369 const trimmed = value?.trim() ?? "";
370 return trimmed.length > 0 ? trimmed : null;
371 }
372
373 function normalizeOptionalRepositoryNameWithOwner(value: string | null | undefined): string | null {
374 const normalized = normalizeOptionalString(value);
375 return normalized ? normalized.toLowerCase() : null;
376 }
377
378 function normalizeOptionalOwnerLogin(value: string | null | undefined): string | null {
379 const normalized = normalizeOptionalString(value);
380 return normalized ? normalized.toLowerCase() : null;
381 }
382
383 interface PullRequestHeadIdentity {
384 readonly repositoryNameWithOwner: string | null;
385 readonly ownerLogin: string | null;
386 }
387
388 function resolveExpectedHeadIdentity(
389 headContext: Pick<BranchHeadContext, "headRepositoryNameWithOwner" | "headRepositoryOwnerLogin">,
390 ): PullRequestHeadIdentity {
391 const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
392 headContext.headRepositoryNameWithOwner,
393 );
394 return {
395 repositoryNameWithOwner,
396 ownerLogin:
397 normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??
398 parseRepositoryOwnerLogin(repositoryNameWithOwner),
399 };
400 }
401
402 function resolvePullRequestHeadIdentity(pr: PullRequestInfo): PullRequestHeadIdentity {
403 const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
404 resolveHeadRepositoryNameWithOwner(pr),
405 );
406 return {
407 repositoryNameWithOwner,
408 ownerLogin:
409 normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??
410 parseRepositoryOwnerLogin(repositoryNameWithOwner),
411 };
412 }
413
414 export function matchesBranchHeadContext(
415 pr: PullRequestInfo,
416 headContext: Pick<
417 BranchHeadContext,
418 "headBranch" | "headRepositoryNameWithOwner" | "headRepositoryOwnerLogin" | "isCrossRepository"
419 >,
420 ): boolean {
421 if (pr.headRefName !== headContext.headBranch) {
422 return false;
423 }
424
425 const expectedHead = resolveExpectedHeadIdentity(headContext);
426 const pullRequestHead = resolvePullRequestHeadIdentity(pr);
427
428 if (expectedHead.repositoryNameWithOwner) {
429 if (pullRequestHead.repositoryNameWithOwner) {
430 if (expectedHead.repositoryNameWithOwner !== pullRequestHead.repositoryNameWithOwner) {
431 return false;
432 }
433 }
434 if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {
435 if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {
436 return false;
437 }
438 }
439 }
440
441 if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {
442 if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {
443 return false;
444 }
445 }
446
447 if (headContext.isCrossRepository) {
448 if (pr.isCrossRepository === false) {
449 return false;
450 }
451 if (
452 (expectedHead.repositoryNameWithOwner || expectedHead.ownerLogin) &&
453 !pullRequestHead.repositoryNameWithOwner &&
454 !pullRequestHead.ownerLogin
455 ) {
456 return false;
457 }
458 return true;
459 }
460
461 if (pr.isCrossRepository === true) {
462 if (
463 (!expectedHead.repositoryNameWithOwner && !expectedHead.ownerLogin) ||
464 (!pullRequestHead.repositoryNameWithOwner && !pullRequestHead.ownerLogin)
465 ) {
466 return false;
467 }
468 }
469
470 return true;
471 }
472
473 function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
474 return {
475 number: summary.number,
476 title: summary.title,
477 url: summary.url,
478 baseRefName: summary.baseRefName,
479 headRefName: summary.headRefName,
480 ...(summary.headSha !== undefined ? { headSha: summary.headSha } : {}),
481 state: summary.state ?? "open",
482 ...(summary.isDraft === true ? { isDraft: true } : {}),
483 closedAt: summary.closedAt ?? null,
484 mergedAt: summary.mergedAt ?? null,
485 updatedAt: summary.updatedAt,
486 ...(summary.isCrossRepository !== undefined
487 ? { isCrossRepository: summary.isCrossRepository }
488 : {}),
489 ...(summary.headRepositoryNameWithOwner !== undefined
490 ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
491 : {}),
492 ...(summary.headRepositoryOwnerLogin !== undefined
493 ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
494 : {}),
495 };
496 }
497
498 function limitContext(value: string, maxChars: number): string {
499 if (value.length <= maxChars) return value;
500 return `${value.slice(0, maxChars)}\n\n[truncated]`;
501 }
502
503 // Preserve command evidence when selectHistory drops oversized items; test verdicts are at the tail.
504 function limitCommandOutput(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
505 if (item.type !== "command_execution" || item.output === undefined) return item;
506 if (item.output.length <= PR_THREAD_COMMAND_OUTPUT_CHARS) return item;
507 return { ...item, output: `[truncated]\n${item.output.slice(-PR_THREAD_COMMAND_OUTPUT_CHARS)}` };
508 }
509
510 function shortenSha(sha: string | undefined): string | null {
511 if (!sha) return null;
512 return sha.slice(0, SHORT_SHA_LENGTH);
513 }
514
515 function truncateText(
516 value: string | undefined,
517 maxLength = TOAST_DESCRIPTION_MAX,
518 ): string | undefined {
519 if (!value) return undefined;
520 if (value.length <= maxLength) return value;
521 if (maxLength <= 3) return "...".slice(0, maxLength);
522 return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;
523 }
524
525 function withDescription(title: string, description: string | undefined) {
526 return description ? { title, description } : { title };
527 }
528
529 function summarizeGitActionResult(
530 result: Pick<GitRunStackedActionResult, "commit" | "push" | "pr">,
531 terms: ChangeRequestTerminology,
532 ): {
533 title: string;
534 description?: string;
535 } {
536 if (result.pr.status === "created" || result.pr.status === "opened_existing") {
537 const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
538 const title = `${result.pr.status === "created" ? "Created" : "Opened"} ${terms.shortLabel}${prNumber}`;
539 return withDescription(title, truncateText(result.pr.title));
540 }
541
542 if (result.push.status === "pushed") {
543 const shortSha = shortenSha(result.commit.commitSha);
544 const branch = result.push.upstreamBranch ?? result.push.branch;
545 const pushedCommitPart = shortSha ? ` ${shortSha}` : "";
546 const branchPart = branch ? ` to ${branch}` : "";
547 return withDescription(
548 `Pushed${pushedCommitPart}${branchPart}`,
549 truncateText(result.commit.subject),
550 );
551 }
552
553 if (result.commit.status === "created") {
554 const shortSha = shortenSha(result.commit.commitSha);
555 const title = shortSha ? `Committed ${shortSha}` : "Committed changes";
556 return withDescription(title, truncateText(result.commit.subject));
557 }
558
559 return { title: "Done" };
560 }
561
562 // A backstop for models that ignore the preset's lowercase instruction; acronyms and names like GitHub are left alone.
563 const CONVENTIONAL_CAPITALIZED_DESCRIPTION =
564 /^([a-z]+(?:\([^)\n]*\))?!?: )([A-Z][a-z]*)(?![A-Za-z0-9])/;
565
566 function sanitizeCommitMessage(
567 generated: {
568 subject: string;
569 body: string;
570 branch?: string | undefined;
571 },
572 conventionalCommits: boolean,
573 ): {
574 subject: string;
575 body: string;
576 branch?: string | undefined;
577 } {
578 const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
579 const trimmedSubject = rawSubject.replace(/[.]+$/g, "").trim();
580 const subject = conventionalCommits
581 ? trimmedSubject.replace(
582 CONVENTIONAL_CAPITALIZED_DESCRIPTION,
583 (_, prefix: string, word: string) => prefix + word.toLowerCase(),
584 )
585 : trimmedSubject;
586 const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
587 return {
588 subject: safeSubject,
589 body: generated.body.trim(),
590 ...(generated.branch !== undefined ? { branch: generated.branch } : {}),
591 };
592 }
593
594 function sanitizeProgressText(value: string): string | null {
595 const trimmed = value.trim();
596 if (trimmed.length === 0) {
597 return null;
598 }
599 if (trimmed.length <= MAX_PROGRESS_TEXT_LENGTH) {
600 return trimmed;
601 }
602 return trimmed.slice(0, MAX_PROGRESS_TEXT_LENGTH).trimEnd();
603 }
604
605 interface CommitAndBranchSuggestion {
606 subject: string;
607 body: string;
608 branch?: string | undefined;
609 commitMessage: string;
610 }
611
612 function isCommitAction(
613 action: GitStackedAction,
614 ): action is "commit" | "commit_push" | "commit_push_pr" {
615 return action === "commit" || action === "commit_push" || action === "commit_push_pr";
616 }
617
618 function formatCommitMessage(subject: string, body: string): string {
619 const trimmedBody = body.trim();
620 if (trimmedBody.length === 0) {
621 return subject;
622 }
623 return `${subject}\n\n${trimmedBody}`;
624 }
625
626 function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
627 const normalized = raw.replace(/\r\n/g, "\n").trim();
628 if (normalized.length === 0) {
629 return null;
630 }
631
632 const [firstLine, ...rest] = normalized.split("\n");
633 const subject = firstLine?.trim() ?? "";
634 if (subject.length === 0) {
635 return null;
636 }
637
638 return {
639 subject,
640 body: rest.join("\n").trim(),
641 };
642 }
643
644 // A branch remote of "." tracks another local branch, which no change request can have as its head.
645 function publishedRemoteName(branchRemote: string | null): string | null {
646 return branchRemote === "." ? null : branchRemote;
647 }
648
649 function headBranchProbe(
650 provider: SourceControlProvider.SourceControlProvider["Service"],
651 headSelectors: ReadonlyArray<string>,
652 state: "open" | "all",
653 ownerHeadSelector?: string,
654 ) {
655 return (
656 provider.headBranchProbe?.({ headSelectors, state, ownerHeadSelector }) ?? {
657 headSelectors,
658 limit: state === "open" ? 1 : 20,
659 }
660 );
661 }
662
663 function appendUnique(values: string[], next: string | null | undefined): void {
664 const trimmed = next?.trim() ?? "";
665 if (trimmed.length === 0 || values.includes(trimmed)) {
666 return;
667 }
668 values.push(trimmed);
669 }
670
671 function toStatusPr(pr: PullRequestInfo): {
672 number: number;
673 title: string;
674 url: string;
675 baseRef: string;
676 headRef: string;
677 state: "open" | "closed" | "merged";
678 isDraft?: boolean;
679 updatedAt: string | null;
680 } {
681 return {
682 number: pr.number,
683 title: pr.title,
684 url: pr.url,
685 baseRef: pr.baseRefName,
686 headRef: pr.headRefName,
687 state: pr.state,
688 ...(pr.isDraft === true ? { isDraft: true } : {}),
689 updatedAt: Option.match(pr.updatedAt, {
690 onNone: () => null,
691 onSome: (updatedAt) => DateTime.formatIso(updatedAt),
692 }),
693 };
694 }
695
696 function normalizePullRequestReference(reference: string): string {
697 const trimmed = reference.trim();
698 const hashNumber = /^#(\d+)$/.exec(trimmed);
699 return hashNumber?.[1] ?? trimmed;
700 }
701
702 function toResolvedPullRequest(pr: {
703 number: number;
704 title: string;
705 url: string;
706 baseRefName: string;
707 headRefName: string;
708 state?: "open" | "closed" | "merged";
709 }): ResolvedPullRequest {
710 return {
711 number: pr.number,
712 title: pr.title,
713 url: pr.url,
714 baseBranch: pr.baseRefName,
715 headBranch: pr.headRefName,
716 state: pr.state ?? "open",
717 };
718 }
719
720 function shouldPreferSshRemote(url: string | null): boolean {
721 if (!url) return false;
722 return isSshRemoteUrl(url);
723 }
724
725 function toPullRequestHeadRemoteInfo(pr: {
726 isCrossRepository?: boolean | undefined;
727 headRepositoryNameWithOwner?: string | null | undefined;
728 headRepositoryOwnerLogin?: string | null | undefined;
729 }): PullRequestHeadRemoteInfo {
730 return {
731 ...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
732 ...(pr.headRepositoryNameWithOwner !== undefined
733 ? { headRepositoryNameWithOwner: pr.headRepositoryNameWithOwner }
734 : {}),
735 ...(pr.headRepositoryOwnerLogin !== undefined
736 ? { headRepositoryOwnerLogin: pr.headRepositoryOwnerLogin }
737 : {}),
738 };
739 }
740
741 export const make = Effect.gen(function* () {
742 const gitCore = yield* GitVcsDriver.GitVcsDriver;
743 const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
744 const textGeneration = yield* TextGeneration.TextGeneration;
745 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
746 const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
747 const random = yield* SecureRandom.SecureRandom;
748 const fileSystem = yield* FileSystem.FileSystem;
749 const path = yield* Path.Path;
750
751 const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
752 // Git fetches from a remote's first URL; `config --get` returns the last of several.
753 const readRemoteUrl = (cwd: string, remoteName: string) =>
754 gitCore
755 .execute({
756 operation: "GitManager.readRemoteUrl",
757 cwd,
758 args: ["config", "--get-all", `remote.${remoteName}.url`],
759 allowNonZeroExit: true,
760 })
761 .pipe(Effect.map((result) => result.stdout.split("\n", 1)[0]?.trim() || null));
762 const changeRequestTermsFor = Effect.fn("GitManager.changeRequestTermsFor")(function* (
763 cwd: string,
764 ) {
765 return yield* sourceControlProvider(cwd).pipe(
766 Effect.map((provider) => sourceControlDefinitions.get(provider.kind).changeRequest),
767 Effect.orElseSucceed(() => UNKNOWN_SOURCE_CONTROL_CLIENT.changeRequest),
768 );
769 });
770 const serverSettingsService = yield* ServerSettings.ServerSettingsService;
771 const pullRequests = yield* PullRequestService.PullRequestService;
772 const threads = yield* ProjectionStore.ProjectionStoreV2;
773 const projects = yield* ProjectStore.ProjectStoreV2;
774 const projectSettingsFor = Effect.fnUntraced(function* (input: {
775 readonly cwd: string;
776 readonly threadId?: ThreadId | undefined;
777 readonly projectId?: ProjectId | undefined;
778 }) {
779 const settings = yield* serverSettingsService.getSettings;
780 if (!hasProjectSettingsOverrides(settings))
781 return { settings, projectId: null as ProjectId | null };
782 const threadProjectId =
783 input.threadId === undefined
784 ? null
785 : yield* threads.getThreadShell(input.threadId).pipe(
786 Effect.map((thread) => thread?.projectId ?? null),
787 Effect.orElseSucceed(() => null),
788 );
789 const projectId =
790 threadProjectId ??
791 input.projectId ??
792 (yield* projects.findActiveByWorkspaceRoot(input.cwd).pipe(
793 Effect.map((project) => Option.getOrNull(project)?.projectId ?? null),
794 Effect.orElseSucceed(() => null),
795 ));
796 return { settings: resolveProjectSettings(settings, projectId).settings, projectId };
797 });
798 const readThreadContext = Effect.fnUntraced(
799 function* (threadId: ThreadId | undefined) {
800 if (threadId === undefined) return undefined;
801 const { visibleTurnItems } = yield* threads.getThreadProjection(threadId);
802 const selected = selectHistory({
803 messages: visibleTurnItems.flatMap(
804 ({ item }) => historicalMessage(limitCommandOutput(item)) ?? [],
805 ),
806 coverage: "Digest of the thread that made this change, oldest first.",
807 budget: PR_THREAD_CONTEXT_BYTES,
808 });
809 return selected.messages.length === 0
810 ? undefined
811 : renderHistory(selected.messages, selected.context);
812 },
813 (effect, threadId) =>
814 effect.pipe(
815 Effect.catch((error) =>
816 Effect.logWarning("GitManager.readThreadContext failed", {
817 threadId,
818 errorTag: error._tag,
819 }).pipe(Effect.as(undefined)),
820 ),
821 ),
822 );
823 // Hands the base T3 recorded for a branch to the host, whose own tools may keep it elsewhere.
824 // Best-effort: nothing T3 does reads it back from there.
825 const shareBranchBase = Effect.fn("GitManager.shareBranchBase")(function* (
826 cwd: string,
827 branch: string,
828 ) {
829 const baseBranch = yield* gitCore
830 .readBranchBase(cwd, branch)
831 .pipe(Effect.orElseSucceed(() => null));
832 if (baseBranch === null) return;
833 const provider = yield* sourceControlProvider(cwd).pipe(Effect.orElseSucceed(() => null));
834 yield* provider?.recordBranchBase?.({ cwd, branch, baseBranch }) ?? Effect.void;
835 });
836 // Publishing a branch that tracks its base records that base first, even when the push then
837 // fails, so the host hears of it after every successful push rather than the first attempt.
838 const pushCurrentBranch = Effect.fn("GitManager.pushCurrentBranch")(function* (
839 cwd: string,
840 branch: string | null,
841 ) {
842 const result = yield* gitCore.pushCurrentBranch(cwd, branch);
843 if (result.status === "pushed" && result.branch) {
844 yield* shareBranchBase(cwd, result.branch);
845 }
846 return result;
847 });
848 const createPrNeedsPush = Effect.fn("GitManager.createPrNeedsPush")(function* (
849 cwd: string,
850 status: {
851 readonly branch: string | null;
852 readonly hasUpstream: boolean;
853 readonly aheadCount: number;
854 },
855 ) {
856 if (!status.branch) return false;
857 if (!status.hasUpstream || status.aheadCount > 0) return true;
858 // A current upstream says nothing about a separate push remote, which may lack HEAD.
859 const target = yield* gitCore
860 .resolvePushTarget(cwd, { branch: status.branch, hasUpstream: true })
861 .pipe(Effect.orElseSucceed(() => null));
862 return target?.viaPushRemote === true;
863 });
864 const readWorktreeCreationSettings = serverSettingsService.getSettings.pipe(
865 Effect.map((settings) => ({
866 worktreesDirectory: settings.worktreesDirectory,
867 fastCheckout: settings.fastWorktreeCheckout,
868 })),
869 Effect.orElseSucceed(() => ({ worktreesDirectory: "" })),
870 );
871 // Turning fast checkout off deletes its cache right away, not at the next worktree.
872 yield* serverSettingsService.streamChanges.pipe(
873 Stream.map((settings) => settings.fastWorktreeCheckout),
874 Stream.changes,
875 Stream.filter((enabled) => !enabled),
876 Stream.runForEach(() => gitCore.clearWorktreeCheckoutCache),
877 Effect.forkScoped,
878 );
879 const createWorktree: GitManager["Service"]["createWorktree"] = Effect.fn(
880 "GitManager.createWorktree",
881 )(function* (input, options) {
882 const submodules =
883 options?.submodules !== undefined
884 ? options.submodules
885 : yield* projectSettingsFor(input).pipe(
886 Effect.map(({ settings }) => settings.worktreeSubmodules),
887 Effect.orElseSucceed(() => null),
888 );
889 const result = yield* gitCore.createWorktree(input, {
890 ...(yield* readWorktreeCreationSettings),
891 ...options,
892 submodules,
893 });
894 if (input.newRefName && input.baseRefName) {
895 yield* shareBranchBase(input.cwd, input.newRefName);
896 }
897 return result;
898 });
899
900 const readRepositoryInstructions = Effect.fn("GitManager.readRepositoryInstructions")(
901 function* (cwd: string, fileName: string) {
902 const root = yield* fileSystem.realPath(cwd);
903 const instructionPath = yield* fileSystem.realPath(path.join(root, fileName));
904 const relative = path.relative(root, instructionPath);
905 if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) {
906 return "";
907 }
908 const info = yield* fileSystem.stat(instructionPath);
909 if (info.type !== "File" || info.size > ByteSize.bytes(20_000)) {
910 return "";
911 }
912 return (yield* fileSystem.readFileString(instructionPath)).trim();
913 },
914 Effect.orElseSucceed(() => ""),
915 );
916
917 const readRecentCommitSubjects = (cwd: string) =>
918 gitCore
919 .execute({
920 operation: "GitManager.readRecentCommitSubjects",
921 cwd,
922 args: ["log", "-n", "20", "--no-merges", "--no-show-signature", "--pretty=format:%s"],
923 })
924 .pipe(
925 Effect.map((result) =>
926 result.stdout
927 .split("\n")
928 .map((line) => line.trim())
929 .filter((line) => line.length > 0),
930 ),
931 Effect.orElseSucceed(() => []),
932 );
933
934 const resolveStylePolicy = Effect.fn("GitManager.resolveStylePolicy")(function* (
935 cwd: string,
936 settings: SourceControlTextGenerationSettings,
937 ) {
938 switch (settings.style.mode) {
939 case "conventional_commits":
940 return conventionalCommitsTextGenerationPolicy;
941 case "custom":
942 return customTextGenerationPolicy(
943 settings.style.customInstructions
944 ? {
945 commitInstructions: settings.style.customInstructions,
946 changeRequestInstructions: settings.style.customInstructions,
947 }
948 : {},
949 );
950 case "repo_conventions": {
951 const subjects = yield* readRecentCommitSubjects(cwd);
952 const agentInstructions = yield* readRepositoryInstructions(cwd, "AGENTS.md");
953 const isClaudeWriter =
954 settings.modelSelection.instanceId === "claudeAgent" ||
955 (yield* providerRegistry.getProviders).some(
956 (provider) =>
957 provider.instanceId === settings.modelSelection.instanceId &&
958 provider.driver === "claudeAgent",
959 );
960 const claudeInstructions = isClaudeWriter
961 ? yield* readRepositoryInstructions(cwd, "CLAUDE.md")
962 : "";
963 const examples = [
964 ...(subjects.length > 0
965 ? [["Recent commit subjects from this repository:", ...subjects].join("\n")]
966 : []),
967 ...(agentInstructions ? [`Local AGENTS.md:\n${agentInstructions}`] : []),
968 // CLAUDE.md is often a symlink or copy of AGENTS.md; skip the duplicate.
969 ...(claudeInstructions && claudeInstructions !== agentInstructions
970 ? [`Local CLAUDE.md:\n${claudeInstructions}`]
971 : []),
972 ].join("\n\n");
973 if (!examples) {
974 return repositoryConventionsTextGenerationPolicy;
975 }
976 return {
977 ...repositoryConventionsTextGenerationPolicy,
978 commitInstructions: `${repositoryConventionsTextGenerationPolicy.commitInstructions}\n\n${examples}`,
979 changeRequestInstructions: `${repositoryConventionsTextGenerationPolicy.changeRequestInstructions}\n\n${examples}`,
980 };
981 }
982 }
983 });
984 const randomUUIDv4 = (cwd: string) =>
985 random.uuidV4().pipe(
986 Effect.mapError(
987 (cause) =>
988 new GitManagerError({
989 operation: "randomUUIDv4",
990 cwd,
991 detail: "Failed to generate Git operation identifier.",
992 cause,
993 }),
994 ),
995 );
996
997 const createProgressEmitter = (
998 input: { cwd: string; action: GitStackedAction },
999 options?: GitRunStackedActionOptions,
1000 ) =>
1001 (options?.actionId === undefined
1002 ? randomUUIDv4(input.cwd)
1003 : Effect.succeed(options.actionId)
1004 ).pipe(
1005 Effect.map((actionId) => {
1006 const reporter = options?.progressReporter;
1007 const emit = (event: GitActionProgressPayload) =>
1008 reporter
1009 ? reporter.publish({
1010 actionId,
1011 cwd: input.cwd,
1012 action: input.action,
1013 ...event,
1014 } as GitActionProgressEvent)
1015 : Effect.void;
1016
1017 return {
1018 actionId,
1019 emit,
1020 };
1021 }),
1022 );
1023
1024 const pullRequestHostOptions = (url: string) => {
1025 const host = URL.parse(url)?.host;
1026 return host ? { host } : {};
1027 };
1028
1029 const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")(
1030 function* (
1031 cwd: string,
1032 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
1033 localBranch = pullRequest.headBranch,
1034 ) {
1035 const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
1036 if (repositoryNameWithOwner.length === 0 && pullRequest.isCrossRepository !== true) {
1037 const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
1038 yield* gitCore.fetchRemoteTrackingBranch({
1039 cwd,
1040 remoteName,
1041 remoteBranch: pullRequest.headBranch,
1042 });
1043 yield* gitCore.setBranchUpstream({
1044 cwd,
1045 branch: localBranch,
1046 remoteName,
1047 remoteBranch: pullRequest.headBranch,
1048 });
1049 return;
1050 }
1051
1052 if (repositoryNameWithOwner.length === 0) {
1053 return;
1054 }
1055
1056 const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
1057 cwd,
1058 repository: repositoryNameWithOwner,
1059 ...pullRequestHostOptions(pullRequest.url),
1060 });
1061 const originRemoteUrl = yield* readRemoteUrl(cwd, "origin");
1062 const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
1063 const preferredRemoteName =
1064 pullRequest.headRepositoryOwnerLogin?.trim() ||
1065 repositoryNameWithOwner.split("/")[0]?.trim() ||
1066 "fork";
1067 const remoteName = yield* gitCore.ensureRemote({
1068 cwd,
1069 preferredName: preferredRemoteName,
1070 url: remoteUrl,
1071 });
1072
1073 yield* gitCore.fetchRemoteTrackingBranch({
1074 cwd,
1075 remoteName,
1076 remoteBranch: pullRequest.headBranch,
1077 });
1078 yield* gitCore.setBranchUpstream({
1079 cwd,
1080 branch: localBranch,
1081 remoteName,
1082 remoteBranch: pullRequest.headBranch,
1083 });
1084 },
1085 );
1086
1087 const configurePullRequestHeadUpstream = (
1088 cwd: string,
1089 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
1090 localBranch = pullRequest.headBranch,
1091 ) =>
1092 configurePullRequestHeadUpstreamBase(cwd, pullRequest, localBranch).pipe(
1093 Effect.catch((error) =>
1094 Effect.logWarning("GitManager.configurePullRequestHeadUpstream failed", {
1095 cwd,
1096 localBranch,
1097 headBranch: pullRequest.headBranch,
1098 cause: error,
1099 }).pipe(Effect.asVoid),
1100 ),
1101 );
1102
1103 // The kind comes from the provider, not the remote alone: an unrecognised remote can resolve
1104 // to a known host.
1105 const changeRequestHeadRef = Effect.fn("GitManager.changeRequestHeadRef")(function* (
1106 cwd: string,
1107 number: number,
1108 ) {
1109 const provider = yield* sourceControlProvider(cwd);
1110 const ref = sourceControlDefinitions.get(provider.kind).changeRequestHeadRef?.(number);
1111 if (ref === undefined) {
1112 return yield* new GitManagerError({
1113 operation: "changeRequestHeadRef",
1114 cwd,
1115 detail: "This host publishes no ref for a change request's head.",
1116 });
1117 }
1118 return ref;
1119 });
1120
1121 const fetchChangeRequestHeadIntoBranch = Effect.fn("GitManager.fetchChangeRequestHeadIntoBranch")(
1122 function* (cwd: string, number: number, branch: string) {
1123 const ref = yield* changeRequestHeadRef(cwd, number);
1124 yield* gitCore.fetchRefIntoBranch({ cwd, ref, branch });
1125 },
1126 );
1127
1128 const materializePullRequestHeadBranchBase = Effect.fn("materializePullRequestHeadBranch")(
1129 function* (
1130 cwd: string,
1131 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
1132 localBranch = pullRequest.headBranch,
1133 ) {
1134 const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
1135
1136 if (repositoryNameWithOwner.length === 0) {
1137 yield* fetchChangeRequestHeadIntoBranch(cwd, pullRequest.number, localBranch).pipe(
1138 // Fall back to a branch fetch only for an open PR in the primary remote's repository.
1139 // A host can resolve a PR number from another repository, so verify the repository first.
1140 // Closed PR branches may have moved past the head recorded at closure.
1141 Effect.catch((cause) =>
1142 pullRequest.isCrossRepository === true || pullRequest.state !== "open"
1143 ? Effect.fail(cause)
1144 : Effect.gen(function* () {
1145 const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
1146 const remoteUrl = yield* readRemoteUrl(cwd, remoteName);
1147 const pullRequestKey = pullRequestRepositoryKey(pullRequest.url);
1148 if (
1149 remoteUrl === null ||
1150 pullRequestKey === null ||
1151 sourceControlDefinitions.canonicalRepositoryKey(pullRequestKey) !==
1152 sourceControlDefinitions.canonicalRepositoryKey(
1153 sourceControlDefinitions.repositoryKeyFromRemote(remoteUrl),
1154 )
1155 ) {
1156 return yield* cause;
1157 }
1158 yield* gitCore.fetchRemoteBranch({
1159 cwd,
1160 remoteName,
1161 remoteBranch: pullRequest.headBranch,
1162 localBranch,
1163 });
1164 }),
1165 ),
1166 );
1167 return;
1168 }
1169
1170 const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
1171 cwd,
1172 repository: repositoryNameWithOwner,
1173 ...pullRequestHostOptions(pullRequest.url),
1174 });
1175 const originRemoteUrl = yield* readRemoteUrl(cwd, "origin");
1176 const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
1177 const preferredRemoteName =
1178 pullRequest.headRepositoryOwnerLogin?.trim() ||
1179 repositoryNameWithOwner.split("/")[0]?.trim() ||
1180 "fork";
1181 const remoteName = yield* gitCore.ensureRemote({
1182 cwd,
1183 preferredName: preferredRemoteName,
1184 url: remoteUrl,
1185 });
1186
1187 yield* gitCore.fetchRemoteBranch({
1188 cwd,
1189 remoteName,
1190 remoteBranch: pullRequest.headBranch,
1191 localBranch,
1192 });
1193 yield* gitCore.setBranchUpstream({
1194 cwd,
1195 branch: localBranch,
1196 remoteName,
1197 remoteBranch: pullRequest.headBranch,
1198 });
1199 },
1200 );
1201
1202 const materializePullRequestHeadBranch = (
1203 cwd: string,
1204 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
1205 localBranch = pullRequest.headBranch,
1206 ) =>
1207 materializePullRequestHeadBranchBase(cwd, pullRequest, localBranch).pipe(
1208 Effect.catch((primaryCause) =>
1209 fetchChangeRequestHeadIntoBranch(cwd, pullRequest.number, localBranch).pipe(
1210 Effect.mapError(
1211 (fallbackCause) =>
1212 new GitPullRequestMaterializationError({
1213 cwd,
1214 pullRequestNumber: pullRequest.number,
1215 headRepository: resolveHeadRepositoryNameWithOwner(pullRequest),
1216 headBranch: pullRequest.headBranch,
1217 localBranch,
1218 cause: new AggregateError(
1219 [primaryCause, fallbackCause],
1220 `Repository-head and pull-request-ref fetches both failed for pull request #${pullRequest.number}.`,
1221 { cause: primaryCause },
1222 ),
1223 }),
1224 ),
1225 ),
1226 ),
1227 );
1228 const tempDir = yield* Config.String("TMPDIR").pipe(
1229 Config.orElse(() => Config.String("TEMP")),
1230 Config.orElse(() => Config.String("TMP")),
1231 Config.withDefault("/tmp"),
1232 );
1233 const canonicalizeExistingPath = (value: string) =>
1234 fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value));
1235 const normalizeStatusCacheKey = canonicalizeExistingPath;
1236 const nonRepositoryStatusDetails: GitVcsDriver.GitStatusDetails = {
1237 isRepo: false,
1238 hasOriginRemote: false,
1239 isDefaultBranch: false,
1240 branch: null,
1241 upstreamRef: null,
1242 hasWorkingTreeChanges: false,
1243 workingTree: { files: [], insertions: 0, deletions: 0 },
1244 hasUpstream: false,
1245 aheadCount: 0,
1246 behindCount: 0,
1247 aheadOfDefaultCount: 0,
1248 };
1249 const readLocalStatus = Effect.fn("readLocalStatus")(function* (
1250 cwd: string,
1251 includeBranchChanges: boolean,
1252 ) {
1253 const details = yield* gitCore
1254 .statusDetailsLocal(cwd, { includeDivergence: false, includeBranchChanges })
1255 .pipe(
1256 Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)),
1257 );
1258 const hostingProvider = details.isRepo
1259 ? yield* resolveHostingProvider(cwd, details.branch)
1260 : null;
1261
1262 return {
1263 isRepo: details.isRepo,
1264 ...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),
1265 hasPrimaryRemote: details.hasOriginRemote,
1266 isDefaultRef: details.isDefaultBranch,
1267 refName: details.branch,
1268 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
1269 workingTree: details.workingTree,
1270 ...(details.branchChanges ? { branchChanges: details.branchChanges } : {}),
1271 } satisfies VcsStatusLocalResult;
1272 });
1273 const makeLocalStatusResultCache = (includeBranchChanges: boolean) =>
1274 Cache.makeWith((cwd: string) => readLocalStatus(cwd, includeBranchChanges), {
1275 capacity: STATUS_RESULT_CACHE_CAPACITY,
1276 timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
1277 });
1278 // Separate entries, so a read without totals is never served to a caller that shows them.
1279 const localStatusResultCache = yield* makeLocalStatusResultCache(true);
1280 const localStatusWithoutBranchChangesCache = yield* makeLocalStatusResultCache(false);
1281 const invalidateLocalStatusResultCache = (cwd: string) =>
1282 normalizeStatusCacheKey(cwd).pipe(
1283 Effect.flatMap((cacheKey) =>
1284 Effect.all([
1285 Cache.invalidate(localStatusResultCache, cacheKey),
1286 Cache.invalidate(localStatusWithoutBranchChangesCache, cacheKey),
1287 ]),
1288 ),
1289 );
1290 const prLookupEpochByCwd = new Map<string, number>();
1291 const prLookupEpoch = (cwd: string) => prLookupEpochByCwd.get(cwd) ?? 0;
1292 const bumpPrLookupEpoch = (cwd: string) =>
1293 normalizeStatusCacheKey(cwd).pipe(
1294 Effect.map((cacheKey) => {
1295 prLookupEpochByCwd.set(cacheKey, prLookupEpoch(cacheKey) + 1);
1296 }),
1297 );
1298 const prLookupCacheKey = (
1299 cwd: string,
1300 details: {
1301 branch: string;
1302 upstreamRef: string | null;
1303 defaultBranch: string | null;
1304 localBranchExists?: boolean;
1305 remoteName?: string | null;
1306 },
1307 ) =>
1308 [
1309 cwd,
1310 details.branch,
1311 details.upstreamRef ?? "",
1312 details.defaultBranch ?? "",
1313 details.localBranchExists === false ? "0" : "1",
1314 details.remoteName ?? "",
1315 String(prLookupEpoch(cwd)),
1316 ].join("\u0000");
1317 const prLookupFailureStreakByKey = new Map<string, number>();
1318 const nextPrLookupFailureTtl = (key: string) => {
1319 if (
1320 !prLookupFailureStreakByKey.has(key) &&
1321 prLookupFailureStreakByKey.size >= PR_LOOKUP_CACHE_CAPACITY
1322 ) {
1323 const oldestKey = prLookupFailureStreakByKey.keys().next().value;
1324 if (oldestKey !== undefined) {
1325 prLookupFailureStreakByKey.delete(oldestKey);
1326 }
1327 }
1328 const streak = (prLookupFailureStreakByKey.get(key) ?? 0) + 1;
1329 prLookupFailureStreakByKey.set(key, streak);
1330 return prLookupFailureTtl(streak);
1331 };
1332 const pullRequestStateChanges = yield* PubSub.sliding<ThreadPullRequestKey>(64);
1333 const lookupStates = new Map<
1334 string,
1335 { readonly state: PullRequestInfo["state"]; readonly isDraft: boolean }
1336 >();
1337 const noteLookupState = (pr: PullRequestInfo) =>
1338 Effect.suspend(() => {
1339 const parsed = sourceControlDefinitions.parseChangeRequestUrl(pr.url)?.link;
1340 if (parsed === undefined || parsed.number !== pr.number) return Effect.void;
1341 const key = normalizeThreadPullRequestKey(parsed);
1342 const id = threadPullRequestKeyOf(key);
1343 const previous = lookupStates.get(id);
1344 lookupStates.delete(id);
1345 if (lookupStates.size >= PR_LOOKUP_CACHE_CAPACITY) {
1346 const oldest = lookupStates.keys().next().value;
1347 if (oldest !== undefined) lookupStates.delete(oldest);
1348 }
1349 lookupStates.set(id, { state: pr.state, isDraft: pr.isDraft === true });
1350 return (previous?.state ?? "open") === pr.state &&
1351 (previous?.isDraft === true) === (pr.isDraft === true)
1352 ? Effect.void
1353 : PubSub.publish(pullRequestStateChanges, key);
1354 });
1355 const prLookupCache = yield* Cache.makeWith(
1356 (key: string) => {
1357 const [
1358 cwd = "",
1359 branch = "",
1360 upstreamRef = "",
1361 defaultBranch = "",
1362 branchExists = "1",
1363 remoteName = "",
1364 ] = key.split("\u0000");
1365 const details = {
1366 branch,
1367 upstreamRef: upstreamRef.length > 0 ? upstreamRef : null,
1368 defaultBranch: defaultBranch.length > 0 ? defaultBranch : null,
1369 localBranchExists: branchExists !== "0",
1370 ...(remoteName.length > 0 ? { remoteName } : {}),
1371 };
1372 return Effect.gen(function* () {
1373 const { headContext, lookup } = yield* resolveLookupHeadContext(cwd, details);
1374 if (!lookup) {
1375 return { latest: null, headContext };
1376 }
1377 if (
1378 details.localBranchExists &&
1379 (details.upstreamRef === null || headContext.remoteName === null) &&
1380 (yield* isUnpublishedBranch(cwd, headContext))
1381 ) {
1382 return { latest: null, headContext };
1383 }
1384 const latest = yield* findLatestPrForHeadContext(cwd, headContext, details.defaultBranch);
1385 if (latest !== null) yield* noteLookupState(latest);
1386 return { latest, headContext };
1387 });
1388 },
1389 {
1390 capacity: PR_LOOKUP_CACHE_CAPACITY,
1391 timeToLive: (exit, key) => {
1392 if (Exit.isSuccess(exit)) {
1393 prLookupFailureStreakByKey.delete(key);
1394 return exit.value.latest?.state === "open"
1395 ? PR_LOOKUP_CACHE_TTL
1396 : PR_LOOKUP_NO_OPEN_PR_CACHE_TTL;
1397 }
1398 return nextPrLookupFailureTtl(key);
1399 },
1400 },
1401 );
1402 const getPrLookup = (key: string) => detachStackFrame(Cache.get(prLookupCache, key));
1403 interface LastKnownPr {
1404 readonly pr: ReturnType<typeof toStatusPr> | null;
1405 readonly headSha: string | null;
1406 readonly upstreamRef: string | null;
1407 readonly headBranch: string;
1408 readonly remoteName: string | null;
1409 readonly headRemoteUrlKey: string | null;
1410 }
1411 const lastKnownPrByBranchKey = new Map<string, LastKnownPr>();
1412 const rememberLastKnownPr = (branchKey: string, entry: LastKnownPr) => {
1413 if (
1414 !lastKnownPrByBranchKey.has(branchKey) &&
1415 lastKnownPrByBranchKey.size >= PR_LOOKUP_CACHE_CAPACITY
1416 ) {
1417 const oldestKey = lastKnownPrByBranchKey.keys().next().value;
1418 if (oldestKey !== undefined) {
1419 lastKnownPrByBranchKey.delete(oldestKey);
1420 }
1421 }
1422 lastKnownPrByBranchKey.set(branchKey, entry);
1423 };
1424 const resolveLastKnownPr = (
1425 branchKey: string,
1426 current: Pick<LastKnownPr, "upstreamRef" | "headBranch" | "remoteName" | "headRemoteUrlKey">,
1427 ): LastKnownPr | null => {
1428 const lastKnown = lastKnownPrByBranchKey.get(branchKey);
1429 if (!lastKnown) return null;
1430 if (lastKnown.headBranch !== current.headBranch) {
1431 return null;
1432 }
1433
1434 // Config read failures become null; require both remote URLs before treating a mismatch as real.
1435 if (lastKnown.headRemoteUrlKey !== null && current.headRemoteUrlKey !== null) {
1436 return lastKnown.headRemoteUrlKey === current.headRemoteUrlKey ? lastKnown : null;
1437 }
1438
1439 if (
1440 lastKnown.upstreamRef !== null &&
1441 current.upstreamRef !== null &&
1442 lastKnown.remoteName !== null &&
1443 current.remoteName !== null
1444 ) {
1445 return lastKnown.remoteName === current.remoteName ? lastKnown : null;
1446 }
1447 return lastKnown;
1448 };
1449 const lookupStatusPr = Effect.fn("lookupStatusPr")(function* (
1450 cwd: string,
1451 details: {
1452 branch: string;
1453 upstreamRef: string | null;
1454 defaultBranch: string | null;
1455 isDefaultBranch: boolean;
1456 },
1457 refreshMissingPullRequest = false,
1458 ) {
1459 // Upstream changes must not orphan the same branch's fallback value.
1460 const branchKey = `${cwd}\u0000${details.branch}`;
1461 const cacheKey = prLookupCacheKey(cwd, details);
1462 if (refreshMissingPullRequest) {
1463 const cached = yield* Cache.getOption(prLookupCache, cacheKey).pipe(
1464 Effect.orElseSucceed(() => Option.none()),
1465 );
1466 if (Option.isSome(cached) && cached.value.latest === null) {
1467 yield* Cache.invalidate(prLookupCache, cacheKey);
1468 }
1469 }
1470 return yield* getPrLookup(cacheKey).pipe(
1471 Effect.map(({ latest, headContext }) => {
1472 if (!latest) return { pr: null, headSha: null, headContext };
1473 // Merged/closed matches are usually reverse-merge history, not the thread's PR context.
1474 if (details.isDefaultBranch && latest.state !== "open") {
1475 return { pr: null, headSha: null, headContext };
1476 }
1477 return { pr: toStatusPr(latest), headSha: latest.headSha ?? null, headContext };
1478 }),
1479 Effect.tap(({ pr, headSha, headContext }) =>
1480 Effect.sync(() =>
1481 rememberLastKnownPr(branchKey, {
1482 pr,
1483 headSha,
1484 upstreamRef: details.upstreamRef,
1485 headBranch: headContext.headBranch,
1486 remoteName: headContext.remoteName,
1487 headRemoteUrlKey: headContext.headRemoteUrlKey,
1488 }),
1489 ),
1490 ),
1491 Effect.map(({ pr, headSha }) => ({ pr, headSha })),
1492 Effect.catch((error) => {
1493 const fallback = lastKnownPrByBranchKey.get(branchKey)?.pr
1494 ? resolveLookupHeadContext(cwd, details).pipe(
1495 Effect.map(({ headContext }) =>
1496 resolveLastKnownPr(branchKey, {
1497 upstreamRef: details.upstreamRef,
1498 headBranch: headContext.headBranch,
1499 remoteName: headContext.remoteName,
1500 headRemoteUrlKey: headContext.headRemoteUrlKey,
1501 }),
1502 ),
1503 )
1504 : Effect.succeed(null);
1505 return Effect.logWarning("PR lookup failed.").pipe(
1506 Effect.annotateLogs({
1507 operation: "lookupStatusPr",
1508 branch: details.branch,
1509 errorTag:
1510 typeof error === "object" && error !== null && "_tag" in error
1511 ? String(error._tag)
1512 : typeof error,
1513 ...(isSourceControlProviderError(error)
1514 ? {
1515 provider: error.provider,
1516 providerOperation: error.operation,
1517 ...(error.command === undefined ? {} : { providerCommand: error.command }),
1518 errorDetail: error.detail,
1519 }
1520 : {}),
1521 }),
1522 Effect.andThen(fallback),
1523 Effect.map((lastKnown) => ({
1524 pr: lastKnown?.pr ?? null,
1525 headSha: lastKnown?.headSha ?? null,
1526 })),
1527 );
1528 }),
1529 );
1530 });
1531 const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (
1532 cwd: string,
1533 options?: GitRemoteStatusOptions,
1534 ) {
1535 const details = yield* gitCore
1536 .statusDetailsRemote(cwd, options)
1537 .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
1538 if (details === null || !details.isRepo) {
1539 return null;
1540 }
1541
1542 const { pr, headSha } =
1543 details.branch !== null
1544 ? yield* lookupStatusPr(
1545 cwd,
1546 {
1547 branch: details.branch,
1548 upstreamRef: details.upstreamRef,
1549 defaultBranch: details.defaultBranch,
1550 isDefaultBranch: details.isDefaultBranch,
1551 },
1552 options?.refreshMissingPullRequest,
1553 )
1554 : { pr: null, headSha: null };
1555 // Squash and rebase merges land new commits, so HEAD never becomes reachable from the base.
1556 const shippedByMergedPr =
1557 pr?.state === "merged" &&
1558 headSha !== null &&
1559 (yield* Effect.gen(function* () {
1560 const defaultBranch =
1561 details.defaultBranch ??
1562 (yield* gitCore.resolvePrimaryRemoteName(cwd).pipe(
1563 Effect.flatMap((remoteName) => gitCore.resolveDefaultBranchName(cwd, remoteName)),
1564 Effect.orElseSucceed(() => null),
1565 ));
1566 const mergedIntoDefault =
1567 defaultBranch === null
1568 ? pr.baseRef === "main" || pr.baseRef === "master"
1569 : pr.baseRef === defaultBranch;
1570 if (!mergedIntoDefault) return false;
1571 return yield* gitCore.resolveCommit({ cwd, revision: "HEAD" }).pipe(
1572 Effect.map(({ commitSha }) => commitSha === headSha),
1573 Effect.orElseSucceed(() => false),
1574 );
1575 }));
1576
1577 return {
1578 hasUpstream: details.hasUpstream,
1579 // A real upstream delta stays; only the no-upstream fallback counts against the base.
1580 aheadCount: shippedByMergedPr && !details.hasUpstream ? 0 : details.aheadCount,
1581 behindCount: details.behindCount,
1582 aheadOfDefaultCount: shippedByMergedPr ? 0 : details.aheadOfDefaultCount,
1583 pr,
1584 } satisfies VcsStatusRemoteResult;
1585 });
1586 const remoteStatusResultCache = yield* Cache.makeWith((cwd: string) => readRemoteStatus(cwd), {
1587 capacity: STATUS_RESULT_CACHE_CAPACITY,
1588 timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
1589 });
1590 const invalidateRemoteStatusResultCache = (cwd: string) =>
1591 normalizeStatusCacheKey(cwd).pipe(
1592 Effect.flatMap((cacheKey) => Cache.invalidate(remoteStatusResultCache, cacheKey)),
1593 );
1594
1595 const readConfigValueNullable = (cwd: string, key: string) =>
1596 gitCore.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
1597 const readRemoteUrlNullable = (cwd: string, remoteName: string) =>
1598 readRemoteUrl(cwd, remoteName).pipe(Effect.orElseSucceed(() => null));
1599
1600 // Whether the remote's host creates change requests in this remote's repository. A host's tools
1601 // can let configuration, such as gh's default repository, name another one.
1602 const targetsRemote = Effect.fn("targetsRemote")(function* (
1603 cwd: string,
1604 remoteName: string,
1605 remote: { readonly remoteUrl: string | null; readonly repositoryNameWithOwner: string | null },
1606 ) {
1607 const provider =
1608 remote.remoteUrl === null ? null : sourceControlDefinitions.recognizeRemote(remote.remoteUrl);
1609 if (remote.remoteUrl === null || provider === null) return true;
1610 const context = { provider, remoteName, remoteUrl: remote.remoteUrl };
1611 const handle = yield* sourceControlProviders
1612 .resolveHandle({ cwd, context })
1613 .pipe(Effect.orElseSucceed(() => null));
1614 const createsChangeRequestsIn = handle?.provider.createsChangeRequestsIn;
1615 if (createsChangeRequestsIn === undefined) return true;
1616 return yield* createsChangeRequestsIn({
1617 cwd,
1618 context: handle?.context ?? context,
1619 repository: remote.repositoryNameWithOwner,
1620 });
1621 });
1622
1623 const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* (
1624 cwd: string,
1625 branch: string | null,
1626 ) {
1627 const preferredRemoteName =
1628 branch === null
1629 ? "origin"
1630 : ((yield* readConfigValueNullable(cwd, `branch.${branch}.remote`)) ?? "origin");
1631 const remoteUrl =
1632 (yield* readRemoteUrlNullable(cwd, preferredRemoteName)) ??
1633 (yield* readRemoteUrlNullable(cwd, "origin"));
1634
1635 const provider = remoteUrl ? sourceControlDefinitions.recognizeRemote(remoteUrl) : null;
1636 if (!remoteUrl || provider?.kind !== "unknown") return provider;
1637 const handle = yield* sourceControlProviders
1638 .resolveHandle({
1639 cwd,
1640 context: { provider, remoteName: preferredRemoteName, remoteUrl },
1641 })
1642 .pipe(Effect.orElseSucceed(() => null));
1643 return handle?.context?.provider ?? provider;
1644 });
1645
1646 const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
1647 cwd: string,
1648 remoteName: string | null,
1649 ) {
1650 if (!remoteName) {
1651 return {
1652 remoteUrl: null,
1653 remoteUrlKey: null,
1654 repositoryNameWithOwner: null,
1655 ownerLogin: null,
1656 };
1657 }
1658
1659 const remoteUrl = yield* readRemoteUrlNullable(cwd, remoteName);
1660 let repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
1661 if (
1662 remoteUrl !== null &&
1663 /^https?:\/\//iu.test(remoteUrl) &&
1664 (repositoryNameWithOwner?.split("/").length ?? 0) > 2
1665 ) {
1666 const kind = sourceControlDefinitions.recognizeRemote(remoteUrl)?.kind;
1667 const provider =
1668 kind === undefined
1669 ? undefined
1670 : yield* (
1671 kind === "unknown" ? sourceControlProvider(cwd) : sourceControlProviders.get(kind)
1672 ).pipe(Effect.orElseSucceed(() => undefined));
1673 repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl, provider);
1674 }
1675 return {
1676 remoteUrl,
1677 remoteUrlKey: remoteUrl ? sourceControlDefinitions.repositoryKeyFromRemote(remoteUrl) : null,
1678 repositoryNameWithOwner,
1679 ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
1680 };
1681 });
1682
1683 const resolveHeadAndOriginContexts = (cwd: string, remoteName: string | null) =>
1684 remoteName === "origin"
1685 ? resolveRemoteRepositoryContext(cwd, "origin").pipe(
1686 Effect.map((origin) => [origin, origin] as const),
1687 )
1688 : Effect.all(
1689 [
1690 resolveRemoteRepositoryContext(cwd, remoteName),
1691 resolveRemoteRepositoryContext(cwd, "origin"),
1692 ],
1693 { concurrency: "unbounded" },
1694 );
1695
1696 const resolveBranchHeadContext = Effect.fn("resolveBranchHeadContext")(function* (
1697 cwd: string,
1698 details: { branch: string; upstreamRef: string | null; remoteName?: string },
1699 ) {
1700 const branchRemote =
1701 details.remoteName ??
1702 (yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`));
1703 const remoteName = publishedRemoteName(branchRemote);
1704 const headBranchFromUpstream =
1705 details.upstreamRef && branchRemote !== "."
1706 ? extractBranchNameFromRemoteRef(details.upstreamRef, { remoteName })
1707 : "";
1708 const headBranch = headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch;
1709 const shouldProbeLocalBranchSelector =
1710 headBranchFromUpstream.length === 0 || headBranch === details.branch;
1711
1712 const [remoteRepository, originRepository] = yield* resolveHeadAndOriginContexts(
1713 cwd,
1714 remoteName,
1715 );
1716
1717 // With no origin to compare against, the only remote is the repository change requests
1718 // are created in unless the host's own configuration names another, so a branch on it is
1719 // not a fork. With several remotes, or with that other target, it may still be a fork.
1720 const isOnlyRemote =
1721 remoteName !== null &&
1722 remoteName !== "origin" &&
1723 originRepository.remoteUrlKey === null &&
1724 (yield* gitCore
1725 .execute({
1726 operation: "GitManager.resolveBranchHeadContext.remotes",
1727 cwd,
1728 args: ["remote"],
1729 timeoutMs: 5_000,
1730 })
1731 .pipe(
1732 Effect.map(
1733 (result) => result.stdout.split("\n").filter((name) => name.trim().length > 0).length,
1734 ),
1735 Effect.orElseSucceed(() => 0),
1736 )) === 1 &&
1737 (yield* targetsRemote(cwd, remoteName, remoteRepository));
1738 const isForeignRemote = remoteName !== null && remoteName !== "origin" && !isOnlyRemote;
1739
1740 const isCrossRepository =
1741 (remoteRepository.repositoryNameWithOwner !== null &&
1742 originRepository.repositoryNameWithOwner !== null
1743 ? remoteRepository.repositoryNameWithOwner.toLowerCase() !==
1744 originRepository.repositoryNameWithOwner.toLowerCase()
1745 : isForeignRemote && remoteRepository.repositoryNameWithOwner !== null) ||
1746 // A fork as origin, with the host targeting another remote such as upstream.
1747 (remoteName !== null &&
1748 !isOnlyRemote &&
1749 remoteRepository.repositoryNameWithOwner !== null &&
1750 !(yield* targetsRemote(cwd, remoteName, remoteRepository)));
1751
1752 const ownerHeadSelector =
1753 remoteRepository.ownerLogin && headBranch.length > 0
1754 ? `${remoteRepository.ownerLogin}:${headBranch}`
1755 : null;
1756 const remoteAliasHeadSelector =
1757 remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null;
1758 const shouldProbeRemoteOwnedSelectors = isCrossRepository || isForeignRemote;
1759
1760 const headSelectors: string[] = [];
1761 if (isCrossRepository && shouldProbeRemoteOwnedSelectors) {
1762 appendUnique(headSelectors, ownerHeadSelector);
1763 appendUnique(
1764 headSelectors,
1765 remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
1766 );
1767 }
1768 if (shouldProbeLocalBranchSelector) {
1769 appendUnique(headSelectors, details.branch);
1770 }
1771 appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null);
1772 if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) {
1773 appendUnique(headSelectors, ownerHeadSelector);
1774 appendUnique(
1775 headSelectors,
1776 remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
1777 );
1778 }
1779
1780 return {
1781 localBranch: details.branch,
1782 headBranch,
1783 headSelectors,
1784 preferredHeadSelector:
1785 ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,
1786 remoteName,
1787 headRemoteUrlKey:
1788 remoteRepository.remoteUrlKey ??
1789 (remoteName === null ? originRepository.remoteUrlKey : null),
1790 targetRemoteUrlKey: originRepository.remoteUrlKey,
1791 headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,
1792 headRepositoryOwnerLogin: remoteRepository.ownerLogin,
1793 isCrossRepository,
1794 } satisfies BranchHeadContext;
1795 });
1796
1797 // Remote names can contain slashes; match refs literally.
1798 const findRemoteTrackingRemote = Effect.fn("findRemoteTrackingRemote")(function* (
1799 cwd: string,
1800 branch: string,
1801 preferredRemoteName: string | null,
1802 ) {
1803 if (branch.length === 0) return null;
1804 return yield* Effect.gen(function* () {
1805 const remoteNames = (yield* gitCore.execute({
1806 operation: "GitManager.findRemoteTrackingRemote.remotes",
1807 cwd,
1808 args: ["remote"],
1809 timeoutMs: 5_000,
1810 })).stdout
1811 .split("\n")
1812 .map((name) => name.trim())
1813 .filter((name) => name.length > 0);
1814 if (remoteNames.length === 0) return null;
1815 const refs = new Set(
1816 (yield* gitCore.execute({
1817 operation: "GitManager.findRemoteTrackingRemote.refs",
1818 cwd,
1819 args: [
1820 "for-each-ref",
1821 "--format=%(refname)",
1822 ...remoteNames.map((name) => `refs/remotes/${name}/${branch}`),
1823 ],
1824 timeoutMs: 5_000,
1825 })).stdout
1826 .split("\n")
1827 .map((ref) => ref.trim())
1828 .filter((ref) => ref.length > 0),
1829 );
1830 const matching = remoteNames.filter((name) => refs.has(`refs/remotes/${name}/${branch}`));
1831 if (preferredRemoteName !== null && matching.includes(preferredRemoteName)) {
1832 return preferredRemoteName;
1833 }
1834 if (matching.includes("origin")) return "origin";
1835 return matching[0] ?? null;
1836 });
1837 });
1838
1839 const findPublishedBranchRemote = Effect.fn("findPublishedBranchRemote")(function* (
1840 cwd: string,
1841 branch: string,
1842 ) {
1843 const localRef = `refs/heads/${branch}`;
1844 const remoteNames = (yield* gitCore.execute({
1845 operation: "GitManager.findPublishedBranchRemote.remotes",
1846 cwd,
1847 args: ["remote"],
1848 timeoutMs: 5_000,
1849 })).stdout
1850 .split("\n")
1851 .map((name) => name.trim())
1852 .filter((name) => name.length > 0);
1853 if (remoteNames.length === 0) return null;
1854
1855 const refs = yield* gitCore.execute({
1856 operation: "GitManager.findPublishedBranchRemote",
1857 cwd,
1858 args: [
1859 "for-each-ref",
1860 "--format=%(refname)%00%(objectname)",
1861 localRef,
1862 ...remoteNames.map((name) => `refs/remotes/${name}/${branch}`),
1863 ],
1864 timeoutMs: 5_000,
1865 });
1866 const oidByRef = new Map(
1867 refs.stdout
1868 .split("\n")
1869 .map((line) => line.trim().split("\u0000"))
1870 .filter((entry): entry is [string, string] => entry.length === 2),
1871 );
1872 const localOid = oidByRef.get(localRef);
1873 if (!localOid) return null;
1874
1875 const remoteRefs = remoteNames.flatMap((name) => {
1876 const oid = oidByRef.get(`refs/remotes/${name}/${branch}`);
1877 return oid ? [{ name, oid }] : [];
1878 });
1879 const exactRemotes = remoteRefs.filter((remote) => remote.oid === localOid);
1880 if (exactRemotes.length > 1) return null;
1881 let remoteName = exactRemotes[0]?.name;
1882 if (remoteName === undefined) {
1883 const ancestorRemotes = yield* Effect.forEach(
1884 remoteRefs,
1885 (remote) =>
1886 gitCore
1887 .execute({
1888 operation: "GitManager.findPublishedBranchRemote.ancestor",
1889 cwd,
1890 args: ["merge-base", "--is-ancestor", remote.oid, localOid],
1891 allowNonZeroExit: true,
1892 timeoutMs: 5_000,
1893 })
1894 .pipe(
1895 Effect.flatMap((result) => {
1896 // Exit 1 means non-ancestor; other failures must reject inference rather than pick another fork.
1897 if (result.exitCode === 0) return Effect.succeed(remote.name);
1898 if (result.exitCode === 1) return Effect.succeed(null);
1899 return new GitCommandError({
1900 operation: "GitManager.findPublishedBranchRemote.ancestor",
1901 command: "git merge-base --is-ancestor",
1902 cwd,
1903 exitCode: result.exitCode,
1904 detail: "Ancestry probe failed; rejecting ancestry inference.",
1905 });
1906 }),
1907 ),
1908 { concurrency: "unbounded" },
1909 );
1910 const matches = ancestorRemotes.filter((name) => name !== null);
1911 if (matches.length !== 1) return null;
1912 remoteName = matches[0];
1913 }
1914 if (remoteName === undefined) return null;
1915 const remoteUrl = yield* readRemoteUrlNullable(cwd, remoteName);
1916 return remoteUrl === null ? null : remoteName;
1917 });
1918
1919 // worktree add can set the branch's base as upstream; that is not its published PR head.
1920 const resolveLookupHeadContext = Effect.fn("resolveLookupHeadContext")(function* (
1921 cwd: string,
1922 details: {
1923 branch: string;
1924 upstreamRef: string | null;
1925 defaultBranch: string | null;
1926 remoteName?: string;
1927 },
1928 ) {
1929 const headContext = yield* resolveBranchHeadContext(cwd, details);
1930 if (details.upstreamRef === null) {
1931 const remoteName = yield* findPublishedBranchRemote(cwd, details.branch).pipe(
1932 Effect.orElseSucceed(() => null),
1933 );
1934 if (remoteName !== null && remoteName !== headContext.remoteName) {
1935 return {
1936 headContext: yield* resolveBranchHeadContext(cwd, { ...details, remoteName }),
1937 lookup: true,
1938 };
1939 }
1940 }
1941 // A fork's default branch can be a PR head. When that fork is origin it is also where new
1942 // branches start, so only a branch made for a pull request takes it as its head.
1943 const tracksForkHead =
1944 headContext.isCrossRepository &&
1945 (headContext.remoteName !== "origin" || isPullRequestWorktreeLocalBranchName(details.branch));
1946 if (headContext.headBranch === details.branch || tracksForkHead) {
1947 return { headContext, lookup: true };
1948 }
1949 const upstreamHeadIsBase =
1950 headContext.headBranch === details.defaultBranch ||
1951 (details.defaultBranch === null &&
1952 (headContext.headBranch === "main" || headContext.headBranch === "master")) ||
1953 headContext.headBranch ===
1954 (yield* gitCore.readBranchBase(cwd, details.branch).pipe(Effect.orElseSucceed(() => null)));
1955 if (!upstreamHeadIsBase) {
1956 return { headContext, lookup: true };
1957 }
1958 const remoteName = yield* findRemoteTrackingRemote(
1959 cwd,
1960 details.branch,
1961 headContext.remoteName,
1962 ).pipe(Effect.orElseSucceed(() => null));
1963 if (remoteName === null) {
1964 return { headContext, lookup: false };
1965 }
1966 const ownNameContext = yield* resolveBranchHeadContext(cwd, {
1967 branch: details.branch,
1968 upstreamRef: null,
1969 remoteName,
1970 });
1971 return { headContext: ownNameContext, lookup: true };
1972 });
1973
1974 const isUnpublishedBranch = Effect.fn("isUnpublishedBranch")(function* (
1975 cwd: string,
1976 headContext: Pick<BranchHeadContext, "headBranch" | "localBranch">,
1977 ) {
1978 if (headContext.headBranch.length === 0) {
1979 return false;
1980 }
1981 const matchesRef = (pattern: string) =>
1982 gitCore
1983 .execute({
1984 operation: "GitManager.isUnpublishedBranch",
1985 cwd,
1986 args: ["for-each-ref", "--count=1", "--format=%(refname)", pattern],
1987 timeoutMs: 5_000,
1988 })
1989 .pipe(Effect.map((result) => result.stdout.trim().length > 0));
1990
1991 return yield* Effect.gen(function* () {
1992 const [configuredRemote, configuredMerge] = yield* Effect.all(
1993 [
1994 gitCore.readConfigValue(cwd, `branch.${headContext.localBranch}.remote`),
1995 gitCore.readConfigValue(cwd, `branch.${headContext.localBranch}.merge`),
1996 ],
1997 { concurrency: "unbounded" },
1998 );
1999 if (configuredRemote !== null && configuredRemote !== "." && configuredMerge !== null) {
2000 return false;
2001 }
2002
2003 const [tracksAnyRemote, trackedRemote] = yield* Effect.all(
2004 [matchesRef("refs/remotes"), findRemoteTrackingRemote(cwd, headContext.headBranch, null)],
2005 { concurrency: "unbounded" },
2006 );
2007 return tracksAnyRemote && trackedRemote === null;
2008 }).pipe(Effect.orElseSucceed(() => false));
2009 });
2010
2011 const findOpenPr = Effect.fn("findOpenPr")(function* (
2012 cwd: string,
2013 headContext: Pick<
2014 BranchHeadContext,
2015 | "headBranch"
2016 | "headSelectors"
2017 | "headRepositoryNameWithOwner"
2018 | "headRepositoryOwnerLogin"
2019 | "isCrossRepository"
2020 >,
2021 ownerHeadSelector?: string,
2022 ) {
2023 const provider = yield* sourceControlProvider(cwd);
2024 const probe = headBranchProbe(provider, headContext.headSelectors, "open", ownerHeadSelector);
2025 for (const headSelector of probe.headSelectors) {
2026 const pullRequests = yield* provider.listChangeRequests({
2027 cwd,
2028 headSelector,
2029 state: "open",
2030 limit: probe.limit,
2031 });
2032 const normalizedPullRequests = pullRequests.map(toPullRequestInfo);
2033
2034 const firstPullRequest = normalizedPullRequests.find((pullRequest) =>
2035 matchesBranchHeadContext(pullRequest, headContext),
2036 );
2037 if (firstPullRequest) {
2038 return {
2039 ...firstPullRequest,
2040 state: "open",
2041 updatedAt: Option.none(),
2042 } satisfies PullRequestInfo;
2043 }
2044 }
2045
2046 return null;
2047 });
2048
2049 const findLatestPrForHeadContext = Effect.fn("findLatestPrForHeadContext")(function* (
2050 cwd: string,
2051 headContext: BranchHeadContext,
2052 defaultBranch: string | null,
2053 ) {
2054 const parsedByNumber = new Map<number, PullRequestInfo>();
2055
2056 const provider = yield* sourceControlProvider(cwd);
2057 const probe = headBranchProbe(
2058 provider,
2059 headContext.headSelectors,
2060 "all",
2061 headContext.headBranch === defaultBranch && headContext.headRepositoryOwnerLogin
2062 ? `${headContext.headRepositoryOwnerLogin}:${defaultBranch}`
2063 : undefined,
2064 );
2065 let pageWasFull = false;
2066 for (const headSelector of probe.headSelectors) {
2067 const pullRequests = yield* provider.listChangeRequests({
2068 cwd,
2069 headSelector,
2070 state: "all",
2071 limit: probe.limit,
2072 });
2073 pageWasFull ||= pullRequests.length >= probe.limit;
2074
2075 for (const pr of pullRequests.map(toPullRequestInfo)) {
2076 if (!matchesBranchHeadContext(pr, headContext)) {
2077 continue;
2078 }
2079 parsedByNumber.set(pr.number, pr);
2080 }
2081 }
2082
2083 const parsed = Arr.sort(parsedByNumber.values(), pullRequestUpdatedAtDescOrder);
2084
2085 const latestOpenPr = parsed.find((pr) => pr.state === "open");
2086 if (latestOpenPr) {
2087 return latestOpenPr;
2088 }
2089 // Forks reusing the head name can fill the page before the branch's own open PR.
2090 if (pageWasFull) {
2091 const openPr = yield* findOpenPr(
2092 cwd,
2093 headContext,
2094 headContext.headRepositoryOwnerLogin
2095 ? `${headContext.headRepositoryOwnerLogin}:${headContext.headBranch}`
2096 : undefined,
2097 );
2098 if (openPr) return openPr;
2099 }
2100 return parsed[0] ?? null;
2101 });
2102 const buildCompletionToast = Effect.fn("buildCompletionToast")(function* (
2103 cwd: string,
2104 result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
2105 ) {
2106 const terms = yield* changeRequestTermsFor(cwd);
2107 const summary = summarizeGitActionResult(result, terms);
2108 let latestOpenPr: PullRequestInfo | null = null;
2109 let currentBranchIsDefault = false;
2110 let finalBranchContext: {
2111 branch: string;
2112 upstreamRef: string | null;
2113 hasUpstream: boolean;
2114 } | null = null;
2115
2116 const finalStatus =
2117 result.action === "commit"
2118 ? null
2119 : yield* gitCore.statusDetails(cwd).pipe(Effect.orElseSucceed(() => null));
2120 if (finalStatus?.branch) {
2121 finalBranchContext = {
2122 branch: finalStatus.branch,
2123 upstreamRef: finalStatus.upstreamRef,
2124 hasUpstream: finalStatus.hasUpstream,
2125 };
2126 currentBranchIsDefault = finalStatus.isDefaultBranch;
2127 }
2128
2129 const explicitResultPr =
2130 (result.pr.status === "created" || result.pr.status === "opened_existing") && result.pr.url
2131 ? {
2132 url: result.pr.url,
2133 state: "open" as const,
2134 }
2135 : null;
2136 const shouldLookupExistingOpenPr =
2137 (result.action === "commit_push" || result.action === "push") &&
2138 result.push.status === "pushed" &&
2139 result.branch.status !== "created" &&
2140 !currentBranchIsDefault &&
2141 explicitResultPr === null &&
2142 finalBranchContext?.hasUpstream === true;
2143
2144 if (shouldLookupExistingOpenPr && finalBranchContext) {
2145 latestOpenPr = yield* resolveBranchHeadContext(cwd, {
2146 branch: finalBranchContext.branch,
2147 upstreamRef: finalBranchContext.upstreamRef,
2148 }).pipe(
2149 Effect.flatMap((headContext) => findOpenPr(cwd, headContext)),
2150 Effect.orElseSucceed(() => null),
2151 );
2152 }
2153
2154 const openPr = latestOpenPr ?? explicitResultPr;
2155
2156 const cta =
2157 result.action === "commit" && result.commit.status === "created"
2158 ? {
2159 kind: "run_action" as const,
2160 label: "Push",
2161 action: { kind: "push" as const },
2162 }
2163 : (result.action === "push" ||
2164 result.action === "create_pr" ||
2165 result.action === "commit_push" ||
2166 result.action === "commit_push_pr") &&
2167 openPr?.url &&
2168 (!currentBranchIsDefault ||
2169 result.pr.status === "created" ||
2170 result.pr.status === "opened_existing")
2171 ? {
2172 kind: "open_pr" as const,
2173 label: `View ${terms.shortLabel}`,
2174 url: openPr.url,
2175 }
2176 : (result.action === "push" || result.action === "commit_push") &&
2177 result.push.status === "pushed" &&
2178 finalStatus !== null &&
2179 !currentBranchIsDefault
2180 ? {
2181 kind: "run_action" as const,
2182 label: `Create ${terms.shortLabel}`,
2183 action: { kind: "create_pr" as const },
2184 }
2185 : {
2186 kind: "none" as const,
2187 };
2188
2189 return {
2190 ...summary,
2191 cta,
2192 };
2193 });
2194
2195 const resolvePrBase = Effect.fn("resolvePrBase")(function* (
2196 cwd: string,
2197 branch: string,
2198 upstreamRef: string | null,
2199 headContext: Pick<BranchHeadContext, "isCrossRepository" | "remoteName">,
2200 ) {
2201 const configuredRef = yield* gitCore.readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`);
2202 if (configuredRef?.startsWith("refs/heads/") || configuredRef?.startsWith("refs/remotes/")) {
2203 const configuredBranch = yield* gitCore.resolveBranchName(cwd, configuredRef);
2204 if (configuredBranch) return { baseBranch: configuredBranch, baseRef: configuredRef };
2205 }
2206
2207 const configured = yield* gitCore.readBranchBase(cwd, branch);
2208 if (configured) {
2209 const localRef = configured.startsWith("refs/") ? configured : `refs/heads/${configured}`;
2210 const localBranch = yield* gitCore.resolveBranchName(cwd, localRef);
2211 if (localBranch) {
2212 const shadowsRemote =
2213 configured.includes("/") &&
2214 !configured.startsWith("refs/") &&
2215 (yield* gitCore.resolveBranchName(cwd, `refs/remotes/${configured}`)) !== null;
2216 return {
2217 baseBranch: localBranch,
2218 baseRef: configured.startsWith("refs/") || shadowsRemote ? localRef : localBranch,
2219 };
2220 }
2221 if (configured.includes("/") && !configured.startsWith("refs/")) {
2222 const remoteRef = `refs/remotes/${configured}`;
2223 const remoteBranch = yield* gitCore.resolveBranchName(cwd, remoteRef);
2224 if (remoteBranch) return { baseBranch: remoteBranch, baseRef: remoteRef };
2225 }
2226 const configuredBranch = yield* gitCore.resolveBranchName(cwd, configured);
2227 if (configuredBranch) return { baseBranch: configuredBranch, baseRef: configuredBranch };
2228 }
2229
2230 if (upstreamRef && !headContext.isCrossRepository) {
2231 const upstreamBranch = extractBranchNameFromRemoteRef(upstreamRef, {
2232 remoteName: headContext.remoteName,
2233 });
2234 if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
2235 return { baseBranch: upstreamBranch, baseRef: upstreamBranch };
2236 }
2237 }
2238
2239 const defaultFromProvider = yield* sourceControlProvider(cwd).pipe(
2240 Effect.flatMap((provider) => provider.getDefaultBranch({ cwd })),
2241 Effect.orElseSucceed(() => null),
2242 );
2243 if (defaultFromProvider) {
2244 return { baseBranch: defaultFromProvider, baseRef: defaultFromProvider };
2245 }
2246
2247 const defaultFromRemote = yield* gitCore.resolvePrimaryRemoteName(cwd).pipe(
2248 Effect.flatMap((remoteName) => gitCore.resolveDefaultBranchName(cwd, remoteName)),
2249 Effect.orElseSucceed(() => null),
2250 );
2251 if (defaultFromRemote) {
2252 return { baseBranch: defaultFromRemote, baseRef: defaultFromRemote };
2253 }
2254
2255 return { baseBranch: "main", baseRef: "main" };
2256 });
2257
2258 const resolveBaseRangeRef = Effect.fn("resolveBaseRangeRef")(function* (
2259 cwd: string,
2260 baseBranch: string,
2261 ) {
2262 if (baseBranch.startsWith("refs/")) return baseBranch;
2263 const remoteName = yield* gitCore
2264 .resolvePrimaryRemoteName(cwd)
2265 .pipe(Effect.orElseSucceed(() => null));
2266 if (!remoteName) return baseBranch;
2267
2268 return yield* gitCore
2269 .resolveRemoteTrackingCommit({
2270 cwd,
2271 refName: baseBranch,
2272 fallbackRemoteName: remoteName,
2273 })
2274 .pipe(
2275 Effect.map((resolved) => resolved.commitSha),
2276 Effect.orElseSucceed(() => baseBranch),
2277 );
2278 });
2279
2280 const resolveCommitAndBranchSuggestion = Effect.fn("resolveCommitAndBranchSuggestion")(
2281 function* (input: {
2282 cwd: string;
2283 branch: string | null;
2284 commitMessage?: string;
2285 includeBranch?: boolean;
2286 filePaths?: readonly string[];
2287 settings: SourceControlTextGenerationSettings;
2288 }) {
2289 const customCommit = parseCustomCommitMessage(input.commitMessage ?? "");
2290 const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths, {
2291 includePatch: customCommit === null,
2292 });
2293 if (!context) {
2294 return null;
2295 }
2296
2297 if (customCommit) {
2298 return {
2299 subject: customCommit.subject,
2300 body: customCommit.body,
2301 ...(input.includeBranch
2302 ? { branch: sanitizeFeatureBranchName(customCommit.subject) }
2303 : {}),
2304 commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),
2305 };
2306 }
2307
2308 const policy = yield* resolveStylePolicy(input.cwd, input.settings);
2309
2310 const generated = yield* textGeneration
2311 .generateCommitMessage({
2312 cwd: input.cwd,
2313 branch: input.branch,
2314 stagedSummary: limitContext(context.stagedSummary, 8_000),
2315 stagedPatch: limitContext(context.stagedPatch, 50_000),
2316 ...(input.includeBranch ? { includeBranch: true } : {}),
2317 ...(policy ? { policy } : {}),
2318 modelSelection: input.settings.modelSelection,
2319 projectId: input.settings.projectId,
2320 })
2321 .pipe(
2322 Effect.map((result) =>
2323 sanitizeCommitMessage(result, policy?.kind === "conventional_commits"),
2324 ),
2325 );
2326
2327 return {
2328 subject: generated.subject,
2329 body: generated.body,
2330 ...(generated.branch !== undefined ? { branch: generated.branch } : {}),
2331 commitMessage: formatCommitMessage(generated.subject, generated.body),
2332 };
2333 },
2334 );
2335
2336 const runCommitStep = Effect.fn("runCommitStep")(function* (
2337 settings: SourceControlTextGenerationSettings,
2338 cwd: string,
2339 action: "commit" | "commit_push" | "commit_push_pr",
2340 branch: string | null,
2341 commitMessage?: string,
2342 preResolvedSuggestion?: CommitAndBranchSuggestion,
2343 filePaths?: readonly string[],
2344 progressReporter?: GitActionProgressReporter,
2345 actionId?: string,
2346 ) {
2347 const emit = (event: GitActionProgressPayload) =>
2348 progressReporter && actionId
2349 ? progressReporter.publish({
2350 actionId,
2351 cwd,
2352 action,
2353 ...event,
2354 } as GitActionProgressEvent)
2355 : Effect.void;
2356
2357 let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion;
2358 if (!suggestion) {
2359 const needsGeneration = !commitMessage?.trim();
2360 if (needsGeneration) {
2361 yield* emit({
2362 kind: "phase_started",
2363 phase: "commit",
2364 label: "Generating commit message...",
2365 });
2366 }
2367 suggestion = yield* resolveCommitAndBranchSuggestion({
2368 cwd,
2369 branch,
2370 ...(commitMessage ? { commitMessage } : {}),
2371 ...(filePaths ? { filePaths } : {}),
2372 settings,
2373 });
2374 }
2375 if (!suggestion) {
2376 return { status: "skipped_no_changes" as const };
2377 }
2378
2379 yield* emit({
2380 kind: "phase_started",
2381 phase: "commit",
2382 label: "Committing...",
2383 });
2384
2385 let currentHookName: string | null = null;
2386 const commitProgress =
2387 progressReporter && actionId
2388 ? {
2389 onOutputLine: ({ stream, text }: { stream: "stdout" | "stderr"; text: string }) => {
2390 const sanitized = sanitizeProgressText(text);
2391 if (!sanitized) {
2392 return Effect.void;
2393 }
2394 return emit({
2395 kind: "hook_output",
2396 hookName: currentHookName,
2397 stream,
2398 text: sanitized,
2399 });
2400 },
2401 onHookStarted: (hookName: string) => {
2402 currentHookName = hookName;
2403 return emit({
2404 kind: "hook_started",
2405 hookName,
2406 });
2407 },
2408 onHookFinished: ({
2409 hookName,
2410 exitCode,
2411 durationMs,
2412 }: {
2413 hookName: string;
2414 exitCode: number | null;
2415 durationMs: number | null;
2416 }) => {
2417 if (currentHookName === hookName) {
2418 currentHookName = null;
2419 }
2420 return emit({
2421 kind: "hook_finished",
2422 hookName,
2423 exitCode,
2424 durationMs,
2425 });
2426 },
2427 }
2428 : null;
2429 const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, {
2430 timeoutMs: COMMIT_TIMEOUT_MS,
2431 stage: filePaths ? { filePaths } : {},
2432 ...(commitProgress ? { progress: commitProgress } : {}),
2433 });
2434 if (currentHookName !== null) {
2435 yield* emit({
2436 kind: "hook_finished",
2437 hookName: currentHookName,
2438 exitCode: 0,
2439 durationMs: null,
2440 });
2441 currentHookName = null;
2442 }
2443 return {
2444 status: "created" as const,
2445 commitSha,
2446 subject: suggestion.subject,
2447 };
2448 });
2449
2450 const ensurePrHeadIsNotBase = Effect.fn("ensurePrHeadIsNotBase")(function* (
2451 cwd: string,
2452 status: { branch: string; upstreamRef: string | null; hasUpstream: boolean },
2453 changeRequestLabel: string,
2454 ) {
2455 const target = yield* gitCore.resolvePushTarget(cwd, status);
2456 if (!target) return;
2457 const headContext = yield* resolveBranchHeadContext(cwd, {
2458 branch: status.branch,
2459 upstreamRef: `${target.remoteName}/${target.branchName}`,
2460 remoteName: target.remoteName,
2461 });
2462 if (headContext.isCrossRepository) return;
2463 const { baseBranch } = yield* resolvePrBase(
2464 cwd,
2465 status.branch,
2466 status.upstreamRef,
2467 headContext,
2468 );
2469 if (baseBranch !== target.branchName) return;
2470 if (yield* findOpenPr(cwd, headContext)) return;
2471 return yield* new GitManagerError({
2472 operation: "runStackedAction",
2473 cwd,
2474 detail: `${baseBranch} is the base branch. Check out a feature branch to create ${changeRequestLabel}.`,
2475 });
2476 });
2477
2478 const openPrFromBranch = Effect.fn("openPrFromBranch")(function* <E>(
2479 cwd: string,
2480 fallbackBranch: string | null,
2481 emit: GitActionProgressEmitter,
2482 pushRemoteRef: { readonly remoteName: string; readonly upstreamRef: string } | undefined,
2483 requestedBase: string | undefined,
2484 draft: boolean,
2485 content: (input: {
2486 readonly provider: SourceControlProvider.SourceControlProvider["Service"];
2487 readonly baseBranch: string;
2488 readonly baseRef: string;
2489 readonly headBranch: string;
2490 }) => Effect.Effect<{ readonly title: string; readonly body: string }, E>,
2491 ) {
2492 const provider = yield* sourceControlProvider(cwd);
2493 const terms = sourceControlDefinitions.get(provider.kind).changeRequest;
2494 const details = yield* gitCore.statusDetails(cwd);
2495 const branch = details.branch ?? fallbackBranch;
2496 if (!branch) {
2497 return yield* new GitManagerError({
2498 operation: "runPrStep",
2499 cwd,
2500 detail: "Cannot create a pull request from detached HEAD.",
2501 });
2502 }
2503 if (!details.hasUpstream) {
2504 return yield* new GitManagerError({
2505 operation: "runPrStep",
2506 cwd,
2507 detail: "Current branch has not been pushed. Push before creating a PR.",
2508 });
2509 }
2510
2511 // A configured push remote receives the commits while the branch keeps
2512 // tracking its upstream, so the PR head is the push remote's branch.
2513 const headContext = yield* resolveBranchHeadContext(
2514 cwd,
2515 pushRemoteRef ? { branch, ...pushRemoteRef } : { branch, upstreamRef: details.upstreamRef },
2516 );
2517
2518 const existing = yield* findOpenPr(cwd, headContext);
2519 if (existing) {
2520 return {
2521 status: "opened_existing" as const,
2522 url: existing.url,
2523 number: existing.number,
2524 baseBranch: existing.baseRefName,
2525 headBranch: existing.headRefName,
2526 title: existing.title,
2527 };
2528 }
2529
2530 // A PR opened from the remote branch would leave out commits not pushed yet. The ahead
2531 // count is against the upstream, which a push to a separate push remote leaves behind.
2532 if (!pushRemoteRef && details.aheadCount > 0) {
2533 return yield* new GitManagerError({
2534 operation: "runPrStep",
2535 cwd,
2536 detail: `The branch has ${details.aheadCount} unpushed commit${details.aheadCount === 1 ? "" : "s"}. Push before opening the PR.`,
2537 });
2538 }
2539 const resolved = yield* resolvePrBase(cwd, branch, details.upstreamRef, headContext);
2540 const baseBranch = requestedBase ?? resolved.baseBranch;
2541 const generated = yield* content({
2542 provider,
2543 baseBranch,
2544 baseRef: requestedBase ?? resolved.baseRef,
2545 headBranch: headContext.headBranch,
2546 });
2547 const bodyFile = path.join(
2548 tempDir,
2549 `t3code-pr-body-${process.pid}-${yield* randomUUIDv4(cwd)}.md`,
2550 );
2551 yield* fileSystem.writeFileString(bodyFile, generated.body).pipe(
2552 Effect.mapError(
2553 (cause) =>
2554 new GitManagerError({
2555 operation: "runPrStep",
2556 cwd,
2557 detail: "Failed to write pull request body temp file.",
2558 cause,
2559 }),
2560 ),
2561 );
2562 yield* emit({
2563 kind: "phase_started",
2564 phase: "pr",
2565 label: `Creating ${terms.singular}...`,
2566 });
2567 yield* provider
2568 .createChangeRequest({
2569 cwd,
2570 baseRefName: baseBranch,
2571 headSelector: headContext.preferredHeadSelector,
2572 ...(provider.kind === "gitlab" &&
2573 headContext.isCrossRepository &&
2574 headContext.headRepositoryNameWithOwner
2575 ? {
2576 source: {
2577 repository: headContext.headRepositoryNameWithOwner,
2578 refName: headContext.headBranch,
2579 },
2580 }
2581 : {}),
2582 title: generated.title,
2583 bodyFile,
2584 ...(draft ? { draft: true } : {}),
2585 })
2586 .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.ignore)));
2587
2588 // The PR already exists at this point, so a failed lookup only loses its metadata.
2589 const created = yield* findOpenPr(cwd, headContext).pipe(
2590 Effect.catch((error) =>
2591 Effect.logWarning("GitManager.runPrStep lookup after create failed", {
2592 provider: provider.kind,
2593 errorTag: error._tag,
2594 }).pipe(Effect.as(null)),
2595 ),
2596 );
2597 if (!created) {
2598 return {
2599 status: "created" as const,
2600 baseBranch,
2601 headBranch: headContext.headBranch,
2602 title: generated.title,
2603 };
2604 }
2605
2606 return {
2607 status: "created" as const,
2608 url: created.url,
2609 number: created.number,
2610 baseBranch: created.baseRefName,
2611 headBranch: created.headRefName,
2612 title: created.title,
2613 };
2614 });
2615
2616 const runPrStep = (
2617 settings: SourceControlTextGenerationSettings,
2618 cwd: string,
2619 fallbackBranch: string | null,
2620 threadId: ThreadId | undefined,
2621 emit: GitActionProgressEmitter,
2622 pushRemoteRef?: { readonly remoteName: string; readonly upstreamRef: string },
2623 ) =>
2624 openPrFromBranch(
2625 cwd,
2626 fallbackBranch,
2627 emit,
2628 pushRemoteRef,
2629 undefined,
2630 false,
2631 ({ provider, baseBranch, baseRef, headBranch }) =>
2632 Effect.gen(function* () {
2633 const terms = sourceControlDefinitions.get(provider.kind).changeRequest;
2634 yield* emit({
2635 kind: "phase_started",
2636 phase: "pr",
2637 label: `Generating ${terms.shortLabel} content...`,
2638 });
2639 const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseRef);
2640 const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);
2641 const policy = yield* resolveStylePolicy(cwd, settings);
2642 const changeRequestTemplate =
2643 settings.style.followChangeRequestTemplates && provider.readChangeRequestTemplate
2644 ? Option.getOrUndefined(
2645 yield* provider.readChangeRequestTemplate({ cwd, treeish: baseRangeRef }),
2646 )
2647 : undefined;
2648 const threadContext = yield* readThreadContext(threadId);
2649
2650 return yield* textGeneration.generatePrContent({
2651 cwd,
2652 baseBranch,
2653 headBranch,
2654 commitSummary: limitContext(rangeContext.commitSummary, 20_000),
2655 diffSummary: limitContext(rangeContext.diffSummary, 20_000),
2656 diffPatch: limitContext(rangeContext.diffPatch, 60_000),
2657 ...(changeRequestTemplate ? { changeRequestTemplate } : {}),
2658 ...(threadContext ? { threadContext } : {}),
2659 ...(policy ? { policy } : {}),
2660 modelSelection: settings.modelSelection,
2661 projectId: settings.projectId,
2662 });
2663 }),
2664 );
2665
2666 const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn(
2667 "GitManager.createPullRequest",
2668 )(function* (input) {
2669 const status = yield* gitCore.statusDetails(input.cwd);
2670 const needsPush = yield* createPrNeedsPush(input.cwd, status);
2671 if (needsPush && status.branch) {
2672 yield* ensurePrHeadIsNotBase(
2673 input.cwd,
2674 { ...status, branch: status.branch },
2675 (yield* changeRequestTermsFor(input.cwd)).shortLabelWithArticle,
2676 );
2677 }
2678 const push = needsPush
2679 ? yield* pushCurrentBranch(input.cwd, status.branch).pipe(
2680 Effect.mapError(
2681 (cause) =>
2682 new GitManagerError({
2683 operation: "createPullRequest",
2684 cwd: input.cwd,
2685 detail: `Could not push ${status.branch}: ${cause.detail}${cause.reason === undefined ? "" : ` (${cause.reason})`}`,
2686 cause,
2687 }),
2688 ),
2689 )
2690 : null;
2691 const result = yield* Effect.gen(function* () {
2692 // Publishing records the upstream, which the PR step needs to find the head branch.
2693 if (!status.hasUpstream && push?.status === "pushed" && push.setUpstream === false) {
2694 return yield* new GitManagerError({
2695 operation: "createPullRequest",
2696 cwd: input.cwd,
2697 detail: `Pushed ${status.branch} to ${push.upstreamBranch}, but could not record it as the branch's upstream. Set the upstream, then try again.`,
2698 });
2699 }
2700 return yield* openPrFromBranch(
2701 input.cwd,
2702 null,
2703 () => Effect.void,
2704 push && "pushRemote" in push && push.pushRemote && push.upstreamBranch
2705 ? { remoteName: push.pushRemote, upstreamRef: push.upstreamBranch }
2706 : undefined,
2707 input.baseBranch,
2708 input.draft === true,
2709 () => Effect.succeed({ title: input.title, body: input.body }),
2710 );
2711 }).pipe(
2712 // A push changes the ahead count, and a new PR changes the branch's PR lookup, so
2713 // both leave cached status stale whatever the PR step does next.
2714 Effect.onExit((exit) =>
2715 push?.status === "pushed" || (Exit.isSuccess(exit) && exit.value.status === "created")
2716 ? invalidateStatus(input.cwd)
2717 : Effect.void,
2718 ),
2719 );
2720 const openedAsDraft =
2721 result.status === "created" &&
2722 (yield* sourceControlProvider(input.cwd)).createsDraftChangeRequests === true;
2723 if (input.draft === true && !openedAsDraft && !(yield* draftOpened(input, result))) {
2724 // A retry finds the open PR and drafts it then.
2725 return yield* new GitManagerError({
2726 operation: "createPullRequest",
2727 cwd: input.cwd,
2728 detail: "Opened the pull request, but the host does not list it yet to make it a draft.",
2729 });
2730 }
2731 return result;
2732 });
2733
2734 /** A retry after a failed draft finds the PR it opened, so an open one is checked too. */
2735 const draftOpened = Effect.fn("GitManager.draftOpened")(
2736 function* (
2737 input: { readonly cwd: string; readonly projectId: ProjectId },
2738 result: GitCreatePullRequestResult,
2739 ) {
2740 const project = yield* projects.getShell(input.projectId).pipe(
2741 Effect.map(Option.getOrUndefined),
2742 Effect.orElseSucceed(() => undefined),
2743 );
2744 const key = createdPullRequestKey({ pr: result }, project);
2745 if (key === null) return false;
2746 const ref = { projectId: input.projectId, ...key };
2747 const isDraft =
2748 result.status === "opened_existing" &&
2749 (yield* pullRequests.summary({ ...ref, allowStale: false })).isDraft;
2750 if (!isDraft) yield* pullRequests.runAction({ ...ref, action: "draft" });
2751 return true;
2752 },
2753 (effect, input) =>
2754 effect.pipe(
2755 Effect.mapError(
2756 (cause) =>
2757 new GitManagerError({
2758 operation: "createPullRequest",
2759 cwd: input.cwd,
2760 detail: `Opened the pull request, but could not make it a draft: ${cause.message}`,
2761 cause,
2762 }),
2763 ),
2764 ),
2765 );
2766
2767 const localStatus: GitManager["Service"]["localStatus"] = Effect.fn("localStatus")(
2768 function* (input, options) {
2769 const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
2770 return yield* Cache.get(
2771 options?.includeBranchChanges === false
2772 ? localStatusWithoutBranchChangesCache
2773 : localStatusResultCache,
2774 cacheKey,
2775 );
2776 },
2777 );
2778 const remoteStatus: GitManager["Service"]["remoteStatus"] = Effect.fn("remoteStatus")(
2779 function* (input, options) {
2780 const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
2781 if (options?.refreshUpstream === false || options?.refreshMissingPullRequest) {
2782 return yield* readRemoteStatus(cacheKey, options);
2783 }
2784 return yield* Cache.get(remoteStatusResultCache, cacheKey);
2785 },
2786 );
2787 const status: GitManager["Service"]["status"] = Effect.fn("status")(function* (input) {
2788 const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)], {
2789 concurrency: "unbounded",
2790 });
2791 return mergeGitStatusParts(local, remote);
2792 });
2793 // Closed PR results can settle threads or remove worktrees; confirm fresh git state before
2794 // persisting, and before acting when a caller skipped confirmation (`confirmTerminal: false`).
2795 const prLookupGitStateByKey = new Map<
2796 string,
2797 { readonly readAtMs: number; readonly value: string | null }
2798 >();
2799 const rememberPrLookupGitState = Effect.fn("GitManager.rememberPrLookupGitState")(function* <E>(
2800 cwd: string,
2801 key: string,
2802 fresh: boolean,
2803 read: Effect.Effect<string | null, E>,
2804 ) {
2805 const entryKey = `${cwd}\u0000${key}`;
2806 const readAtMs = yield* Clock.currentTimeMillis;
2807 const remembered = prLookupGitStateByKey.get(entryKey);
2808 if (
2809 !fresh &&
2810 remembered !== undefined &&
2811 readAtMs - remembered.readAtMs < Duration.toMillis(PR_LOOKUP_GIT_STATE_TTL)
2812 ) {
2813 return remembered.value;
2814 }
2815 // invalidateStatus bumps the epoch. A read that started before a T3 git
2816 // action, or before a newer read finished, must not replace their state.
2817 const epoch = prLookupEpoch(cwd);
2818 const value = yield* read;
2819 const latest = prLookupGitStateByKey.get(entryKey);
2820 if (prLookupEpoch(cwd) !== epoch || (latest !== undefined && latest.readAtMs > readAtMs)) {
2821 return value;
2822 }
2823 prLookupGitStateByKey.delete(entryKey);
2824 if (prLookupGitStateByKey.size >= PR_LOOKUP_CACHE_CAPACITY) {
2825 const oldestKey = prLookupGitStateByKey.keys().next().value;
2826 if (oldestKey !== undefined) prLookupGitStateByKey.delete(oldestKey);
2827 }
2828 prLookupGitStateByKey.set(entryKey, { readAtMs, value });
2829 return value;
2830 });
2831 const branchPrLookups = yield* Semaphore.make(BRANCH_PR_LOOKUP_CONCURRENCY);
2832 const settledPrLookupByBranchKey = new Map<
2833 string,
2834 { readonly url: string; readonly fingerprint: string; readonly confirmedAtMs: number }
2835 >();
2836 const forgetPrLookupGitState = (cwd: string) =>
2837 normalizeStatusCacheKey(cwd).pipe(
2838 Effect.map((cacheCwd) => {
2839 const prefix = `${cacheCwd}\u0000`;
2840 for (const key of prLookupGitStateByKey.keys()) {
2841 if (key.startsWith(prefix)) prLookupGitStateByKey.delete(key);
2842 }
2843 }),
2844 );
2845 const resolvePrLookupRepositoryIdentity = Effect.fn("resolvePrLookupRepositoryIdentity")(
2846 function* (
2847 cwd: string,
2848 branch: string,
2849 remoteNameOverride: string | undefined,
2850 fresh: boolean,
2851 ) {
2852 const readConfig = (key: string) =>
2853 rememberPrLookupGitState(
2854 cwd,
2855 `config\u0000${key}`,
2856 fresh,
2857 gitCore.readConfigValue(cwd, key),
2858 ).pipe(Effect.orElseSucceed(() => null));
2859 const readRemoteUrlKey = (remoteName: string | null) =>
2860 remoteName === null
2861 ? Effect.succeed(null)
2862 : rememberPrLookupGitState(
2863 cwd,
2864 `remoteUrl\u0000${remoteName}`,
2865 fresh,
2866 readRemoteUrl(cwd, remoteName),
2867 ).pipe(
2868 Effect.orElseSucceed(() => null),
2869 Effect.map((remoteUrl) =>
2870 remoteUrl ? sourceControlDefinitions.repositoryKeyFromRemote(remoteUrl) : null,
2871 ),
2872 );
2873 const remoteName = publishedRemoteName(
2874 remoteNameOverride ?? (yield* readConfig(`branch.${branch}.remote`)),
2875 );
2876 const [headRemoteUrlKey, targetRemoteUrlKey] =
2877 remoteName === "origin"
2878 ? yield* readRemoteUrlKey("origin").pipe(Effect.map((key) => [key, key] as const))
2879 : yield* Effect.all([readRemoteUrlKey(remoteName), readRemoteUrlKey("origin")], {
2880 concurrency: "unbounded",
2881 });
2882 return {
2883 remoteName,
2884 headRemoteUrlKey: headRemoteUrlKey ?? (remoteName === null ? targetRemoteUrlKey : null),
2885 targetRemoteUrlKey,
2886 };
2887 },
2888 );
2889 // objectname lets a settled PR result notice new commits on its branch.
2890 const readPrLookupBranchRef = (cacheCwd: string, branch: string, fresh: boolean) =>
2891 rememberPrLookupGitState(
2892 cacheCwd,
2893 `branchRef\u0000${branch}`,
2894 fresh,
2895 gitCore
2896 .execute({
2897 operation: "GitManager.branchPullRequest.branchRef",
2898 cwd: cacheCwd,
2899 args: [
2900 "for-each-ref",
2901 "--format=%(refname)%00%(upstream:short)%00%(upstream:remotename)%00%(upstream:remoteref)%00%(objectname)",
2902 `refs/heads/${branch}`,
2903 ],
2904 })
2905 .pipe(Effect.map((result) => result.stdout)),
2906 );
2907 const readSettledPrLookupFingerprint = (cacheCwd: string, branch: string) =>
2908 Effect.all(
2909 [
2910 readPrLookupBranchRef(cacheCwd, branch, true),
2911 gitCore
2912 .execute({
2913 operation: "GitManager.branchPullRequest.remoteUrls",
2914 cwd: cacheCwd,
2915 args: ["config", "--get-regexp", "^remote\\..*\\.url$"],
2916 allowNonZeroExit: true,
2917 })
2918 .pipe(Effect.map((result) => result.stdout)),
2919 ],
2920 { concurrency: "unbounded" },
2921 ).pipe(Effect.map((parts) => parts.join("\u0000")));
2922 const lookupBranchPullRequest = Effect.fn("lookupBranchPullRequest")(function* (
2923 cacheCwd: string,
2924 branch: string,
2925 options: { readonly refresh: boolean; readonly freshGitState: boolean },
2926 ) {
2927 const remember = <E>(key: string, read: Effect.Effect<string | null, E>) =>
2928 rememberPrLookupGitState(cacheCwd, key, options.freshGitState, read);
2929 const remotes = yield* remember(
2930 "remotes",
2931 gitCore
2932 .execute({
2933 operation: "GitManager.branchPullRequest.remotes",
2934 cwd: cacheCwd,
2935 args: ["remote"],
2936 })
2937 .pipe(Effect.map((result) => result.stdout)),
2938 );
2939 const remoteNames = (remotes ?? "")
2940 .split("\n")
2941 .map((remoteName) => remoteName.trim())
2942 .filter((remoteName) => remoteName.length > 0);
2943 const [firstRemoteName] = remoteNames;
2944 if (firstRemoteName === undefined) return null;
2945 const branchRef = yield* readPrLookupBranchRef(cacheCwd, branch, options.freshGitState);
2946 const expectedRefName = `refs/heads/${branch}`;
2947 const exactBranch = (branchRef ?? "")
2948 .split("\n")
2949 .find((line) => line.split("\u0000", 1)[0] === expectedRefName);
2950 const [refName = "", savedUpstream = "", savedRemoteName = "", savedRemoteRef = ""] =
2951 exactBranch?.split("\u0000") ?? [];
2952 const localBranchExists = refName.length > 0;
2953 let upstreamRef: string | null = null;
2954 let remoteName: string | null = null;
2955 if (savedUpstream.length > 0) {
2956 if (savedRemoteName.length === 0 || savedRemoteRef.length === 0) {
2957 return yield* new GitManagerError({
2958 operation: "branchPullRequest",
2959 cwd: cacheCwd,
2960 detail: `Saved upstream for ${branch} is incomplete.`,
2961 });
2962 }
2963 remoteName = savedRemoteName;
2964 const upstreamBranch = savedRemoteRef.replace(/^refs\/heads\//, "");
2965 upstreamRef = `${remoteName}/${upstreamBranch}`;
2966 } else if (!localBranchExists) {
2967 const trackingRemotes = yield* remember(
2968 `trackingRemotes\u0000${branch}`,
2969 gitCore
2970 .execute({
2971 operation: "GitManager.branchPullRequest.remoteTrackingRefs",
2972 cwd: cacheCwd,
2973 args: ["for-each-ref", "--format=%(refname)", "refs/remotes"],
2974 })
2975 .pipe(
2976 Effect.map((trackingRefs) => {
2977 const refNames = new Set(
2978 trackingRefs.stdout
2979 .split("\n")
2980 .map((remoteRef) => remoteRef.trim())
2981 .filter((remoteRef) => remoteRef.length > 0),
2982 );
2983 return remoteNames
2984 .filter((candidate) => refNames.has(`refs/remotes/${candidate}/${branch}`))
2985 .join("\n");
2986 }),
2987 ),
2988 );
2989 const matchingRemoteNames = (trackingRemotes ?? "")
2990 .split("\n")
2991 .filter((candidate) => candidate.length > 0);
2992 if (matchingRemoteNames.length > 1) {
2993 return yield* new GitManagerError({
2994 operation: "branchPullRequest",
2995 cwd: cacheCwd,
2996 detail: `Multiple remotes track ${branch}. Its pull request is ambiguous.`,
2997 });
2998 }
2999 remoteName = matchingRemoteNames[0] ?? null;
3000 if (remoteName !== null) {
3001 upstreamRef = `${remoteName}/${branch}`;
3002 }
3003 }
3004 const defaultRemoteName = remoteNames.includes("origin") ? "origin" : firstRemoteName;
3005 const defaultBranch = yield* remember(
3006 `defaultBranch\u0000${defaultRemoteName}`,
3007 gitCore.resolveDefaultBranchName(cacheCwd, defaultRemoteName),
3008 ).pipe(Effect.orElseSucceed(() => null));
3009 const cacheKey = prLookupCacheKey(cacheCwd, {
3010 branch,
3011 upstreamRef,
3012 defaultBranch,
3013 localBranchExists,
3014 ...(localBranchExists ? {} : { remoteName }),
3015 });
3016 if (options.refresh) {
3017 const cached = yield* Cache.getOption(prLookupCache, cacheKey).pipe(
3018 Effect.orElseSucceed(() => Option.none()),
3019 );
3020 if (Option.isSome(cached)) yield* Cache.invalidate(prLookupCache, cacheKey);
3021 }
3022 let cached = yield* getPrLookup(cacheKey);
3023 // Lookup may use a fork instead of the saved upstream; verify the remote actually queried.
3024 const identityRemoteName = (headContext: BranchHeadContext) =>
3025 headContext.remoteName ?? remoteName ?? undefined;
3026 const currentIdentity = yield* resolvePrLookupRepositoryIdentity(
3027 cacheCwd,
3028 branch,
3029 identityRemoteName(cached.headContext),
3030 options.freshGitState,
3031 );
3032 const canVerifyIdentity = (headContext: BranchHeadContext, identity: typeof currentIdentity) =>
3033 !(
3034 (headContext.headRemoteUrlKey !== null && identity.headRemoteUrlKey === null) ||
3035 (headContext.targetRemoteUrlKey !== null && identity.targetRemoteUrlKey === null)
3036 );
3037 const hasSameIdentity = (headContext: BranchHeadContext, identity: typeof currentIdentity) =>
3038 headContext.headRemoteUrlKey === identity.headRemoteUrlKey &&
3039 headContext.targetRemoteUrlKey === identity.targetRemoteUrlKey;
3040 if (!canVerifyIdentity(cached.headContext, currentIdentity)) {
3041 return yield* new GitManagerError({
3042 operation: "branchPullRequest",
3043 cwd: cacheCwd,
3044 detail: `Repository identity for ${branch} could not be verified.`,
3045 });
3046 }
3047 if (!hasSameIdentity(cached.headContext, currentIdentity)) {
3048 yield* Cache.invalidate(prLookupCache, cacheKey);
3049 cached = yield* getPrLookup(cacheKey);
3050 const refreshedIdentity = yield* resolvePrLookupRepositoryIdentity(
3051 cacheCwd,
3052 branch,
3053 identityRemoteName(cached.headContext),
3054 true,
3055 );
3056 if (
3057 !canVerifyIdentity(cached.headContext, refreshedIdentity) ||
3058 !hasSameIdentity(cached.headContext, refreshedIdentity)
3059 ) {
3060 return yield* new GitManagerError({
3061 operation: "branchPullRequest",
3062 cwd: cacheCwd,
3063 detail: `Repository identity for ${branch} changed during pull request lookup.`,
3064 });
3065 }
3066 }
3067 const { latest } = cached;
3068 if (latest === null) return null;
3069 if (
3070 (branch === defaultBranch ||
3071 (defaultBranch === null && (branch === "main" || branch === "master"))) &&
3072 latest.state !== "open"
3073 ) {
3074 return null;
3075 }
3076 return {
3077 ...toStatusPr(latest),
3078 closedAt: latest.closedAt ?? null,
3079 mergedAt: latest.mergedAt ?? null,
3080 headSha: latest.headSha ?? null,
3081 // Hosting CLIs may target upstream; the PR URL identifies its actual repository.
3082 repositoryKey: pullRequestRepositoryKey(latest.url),
3083 };
3084 });
3085
3086 const checkedOutPullRequestKey = (branch: string) => `branch.${branch}.t3-pull-request`;
3087
3088 const branchPullRequest: GitManager["Service"]["branchPullRequest"] = Effect.fn(
3089 "branchPullRequest",
3090 )(function* ({ cwd, branch }, options) {
3091 const cacheCwd = yield* normalizeStatusCacheKey(cwd);
3092 const refresh = options?.refresh === true;
3093 const freshGitState = refresh || options?.freshGitState === true;
3094 const pullRequest = yield* lookupBranchPullRequest(cacheCwd, branch, {
3095 refresh,
3096 freshGitState,
3097 });
3098 if (
3099 pullRequest === null ||
3100 pullRequest.state === "open" ||
3101 freshGitState ||
3102 options?.confirmTerminal === false
3103 ) {
3104 return pullRequest;
3105 }
3106 // A confirmed closed or merged result stays final until the branch or remotes change,
3107 // with a periodic fresh lookup so a new PR from a reused branch still shows up.
3108 const settledKey = `${cacheCwd}\u0000${branch}`;
3109 const now = yield* Clock.currentTimeMillis;
3110 const settled = settledPrLookupByBranchKey.get(settledKey);
3111 // Read before any fresh lookup, so a change made during it forces another one.
3112 const fingerprint = yield* readSettledPrLookupFingerprint(cacheCwd, branch);
3113 if (
3114 settled !== undefined &&
3115 settled.url === pullRequest.url &&
3116 settled.fingerprint === fingerprint &&
3117 now - settled.confirmedAtMs < Duration.toMillis(SETTLED_PR_LOOKUP_RECHECK_INTERVAL)
3118 ) {
3119 return pullRequest;
3120 }
3121 const confirmed = yield* lookupBranchPullRequest(cacheCwd, branch, {
3122 refresh: false,
3123 freshGitState: true,
3124 });
3125 settledPrLookupByBranchKey.delete(settledKey);
3126 if (confirmed !== null && confirmed.state !== "open") {
3127 if (settledPrLookupByBranchKey.size >= PR_LOOKUP_CACHE_CAPACITY) {
3128 const oldestKey = settledPrLookupByBranchKey.keys().next().value;
3129 if (oldestKey !== undefined) settledPrLookupByBranchKey.delete(oldestKey);
3130 }
3131 settledPrLookupByBranchKey.set(settledKey, {
3132 url: confirmed.url,
3133 fingerprint,
3134 confirmedAtMs: now,
3135 });
3136 }
3137 return confirmed;
3138 }, branchPrLookups.withPermits(1));
3139
3140 const checkedOutPullRequest: GitManager["Service"]["checkedOutPullRequest"] = Effect.fn(
3141 "checkedOutPullRequest",
3142 )(function* ({ cwd, branch, url }) {
3143 const checkedOutUrl = yield* gitCore
3144 .readConfigValue(cwd, checkedOutPullRequestKey(branch))
3145 .pipe(Effect.orElseSucceed(() => null));
3146 return checkedOutUrl === url;
3147 });
3148
3149 const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn(
3150 "invalidateLocalStatus",
3151 )(function* (cwd) {
3152 yield* invalidateLocalStatusResultCache(cwd);
3153 });
3154 const invalidateRemoteStatus: GitManager["Service"]["invalidateRemoteStatus"] = Effect.fn(
3155 "invalidateRemoteStatus",
3156 )(function* (cwd) {
3157 yield* invalidateRemoteStatusResultCache(cwd);
3158 });
3159 const invalidateStatus: GitManager["Service"]["invalidateStatus"] = Effect.fn("invalidateStatus")(
3160 function* (cwd) {
3161 yield* invalidateLocalStatusResultCache(cwd);
3162 yield* invalidateRemoteStatusResultCache(cwd);
3163 yield* bumpPrLookupEpoch(cwd);
3164 yield* forgetPrLookupGitState(cwd);
3165 },
3166 );
3167
3168 // A user is waiting on these, so a host's background rate-limit pause must not refuse them.
3169 const asUserAction = Effect.provideService(SourceControlRateLimit.Interactive, true);
3170
3171 const resolvePullRequest: GitManager["Service"]["resolvePullRequest"] = Effect.fn(
3172 "resolvePullRequest",
3173 )(function* (input) {
3174 const pullRequest = yield* (yield* sourceControlProvider(input.cwd))
3175 .getChangeRequest({
3176 cwd: input.cwd,
3177 reference: normalizePullRequestReference(input.reference),
3178 })
3179 .pipe(Effect.map((resolved) => toResolvedPullRequest(resolved)));
3180
3181 return { pullRequest };
3182 }, asUserAction);
3183
3184 const ensureNoTrackedChanges = Effect.fn("ensureNoTrackedChanges")(function* (
3185 cwd: string,
3186 pullRequestNumber: number,
3187 ) {
3188 const trackedChanges = yield* gitCore.execute({
3189 operation: "GitManager.preparePullRequestThread.trackedChanges",
3190 cwd,
3191 args: ["status", "--porcelain", "--untracked-files=no"],
3192 });
3193 if (trackedChanges.stdout.trim().length > 0) {
3194 return yield* new GitManagerError({
3195 operation: "preparePullRequestThread",
3196 cwd,
3197 detail: `This repository has uncommitted changes. Commit or stash them before checking out pull request #${pullRequestNumber} here, or check it out in its own folder.`,
3198 });
3199 }
3200 });
3201
3202 // Some hosts only switch branches on checkout; use the existing lossless refresh to advance them.
3203 const moveToPullRequestHead = (cwd: string, headSha: string | undefined) =>
3204 headSha === undefined || !/^[0-9a-f]{7,64}$/i.test(headSha)
3205 ? Effect.succeed(false)
3206 : gitCore.resolveCommit({ cwd, revision: headSha }).pipe(
3207 Effect.flatMap(({ commitSha }) =>
3208 gitCore.refreshCheckedOutBranch({ cwd, targetCommit: commitSha }),
3209 ),
3210 Effect.map((refreshed) => refreshed.onTarget),
3211 Effect.orElseSucceed(() => false),
3212 );
3213
3214 const preparePullRequestThread: GitManager["Service"]["preparePullRequestThread"] = Effect.fn(
3215 "preparePullRequestThread",
3216 )(function* (input) {
3217 const maybeRunSetupScript = (worktreePath: string) => {
3218 if (!input.threadId) {
3219 return Effect.void;
3220 }
3221 return projectSetupScriptRunner
3222 .runForThread({
3223 threadId: input.threadId,
3224 projectCwd: input.cwd,
3225 worktreePath,
3226 })
3227 .pipe(
3228 Effect.catch((error) =>
3229 Effect.logWarning("GitManager.preparePullRequestThread setup script failed", {
3230 threadId: input.threadId,
3231 worktreePath,
3232 cause: error,
3233 }).pipe(Effect.asVoid),
3234 ),
3235 );
3236 };
3237 return yield* Effect.gen(function* () {
3238 const normalizedReference = normalizePullRequestReference(input.reference);
3239 const rootWorktreePath = yield* canonicalizeExistingPath(input.cwd);
3240 const pullRequestSummary = yield* (yield* sourceControlProvider(input.cwd)).getChangeRequest({
3241 cwd: input.cwd,
3242 reference: normalizedReference,
3243 });
3244 const pullRequest = toResolvedPullRequest(pullRequestSummary);
3245
3246 if (input.mode === "local") {
3247 yield* ensureNoTrackedChanges(input.cwd, pullRequest.number);
3248 yield* (yield* sourceControlProvider(input.cwd)).checkoutChangeRequest({
3249 cwd: input.cwd,
3250 reference: normalizedReference,
3251 });
3252 const details = yield* gitCore.statusDetails(input.cwd);
3253 const branch = details.branch ?? pullRequest.headBranch;
3254 yield* configurePullRequestHeadUpstream(
3255 input.cwd,
3256 {
3257 ...pullRequest,
3258 ...toPullRequestHeadRemoteInfo(pullRequestSummary),
3259 },
3260 branch,
3261 );
3262 return {
3263 pullRequest,
3264 branch,
3265 worktreePath: null,
3266 isOnPullRequestHead: yield* moveToPullRequestHead(input.cwd, pullRequestSummary.headSha),
3267 };
3268 }
3269
3270 const ensureExistingWorktreeUpstream = Effect.fn("ensureExistingWorktreeUpstream")(function* (
3271 worktreePath: string,
3272 ) {
3273 const details = yield* gitCore.statusDetails(worktreePath);
3274 yield* configurePullRequestHeadUpstream(
3275 worktreePath,
3276 {
3277 ...pullRequest,
3278 ...toPullRequestHeadRemoteInfo(pullRequestSummary),
3279 },
3280 details.branch ?? pullRequest.headBranch,
3281 );
3282 });
3283
3284 const pullRequestWithRemoteInfo = {
3285 ...pullRequest,
3286 ...toPullRequestHeadRemoteInfo(pullRequestSummary),
3287 } as const;
3288 const localBranches = pullRequestWithRemoteInfo.isCrossRepository
3289 ? new Set(
3290 (yield* gitCore.execute({
3291 operation: "GitManager.preparePullRequestThread.localBranches",
3292 cwd: input.cwd,
3293 args: ["for-each-ref", "--format=%(refname:lstrip=2)", "refs/heads"],
3294 timeoutMs: 5_000,
3295 })).stdout
3296 .split("\n")
3297 .filter((name) => name.length > 0),
3298 )
3299 : new Set<string>();
3300 const localPullRequestBranch = resolvePullRequestWorktreeLocalBranchName(
3301 pullRequestWithRemoteInfo,
3302 localBranches,
3303 );
3304
3305 // Git refuses to move checked-out branches; advance reused checkouts from inside their worktree.
3306 const reuseExistingWorktree = Effect.fn("reuseExistingWorktree")(function* (
3307 worktreePath: string,
3308 checkedOutBranch: string,
3309 ) {
3310 if (checkedOutBranch !== localPullRequestBranch) {
3311 // Bare-name matches may be unrelated local branches; preserve their work and tracking config.
3312 return {
3313 pullRequest,
3314 branch: localPullRequestBranch,
3315 worktreePath,
3316 isOnPullRequestHead: false,
3317 };
3318 }
3319
3320 // Capture upstream before its forced fetch so rewritten heads remain distinguishable from local commits.
3321 const upstreamCommitBeforeFetch = yield* gitCore
3322 .resolveCommit({ cwd: worktreePath, revision: "@{upstream}" })
3323 .pipe(
3324 Effect.map((resolved) => resolved.commitSha),
3325 Effect.orElseSucceed(() => null),
3326 );
3327
3328 yield* ensureExistingWorktreeUpstream(worktreePath);
3329
3330 // The pull request's own ref, because it is the only thing that certainly names its
3331 // head. The branch's upstream does not: configuring it is best-effort, so a branch cut
3332 // from `origin/main` whose head branch has since been deleted still resolves — and
3333 // following it would move the checkout onto main and call that the pull request.
3334 const refreshed = yield* changeRequestHeadRef(worktreePath, pullRequest.number).pipe(
3335 Effect.flatMap((ref) => gitCore.fetchRefCommit({ cwd: worktreePath, ref })),
3336 // A host that publishes no head ref leaves the remote-tracking branch,
3337 // taken only where it is the head branch's own rather than whatever the checkout
3338 // happened to be cut from.
3339 Effect.catch(() =>
3340 Effect.gen(function* () {
3341 const details = yield* gitCore.statusDetails(worktreePath);
3342 if (
3343 details.upstreamRef === null ||
3344 !details.upstreamRef.endsWith(`/${pullRequest.headBranch}`)
3345 ) {
3346 return yield* new GitManagerError({
3347 operation: "preparePullRequestThread",
3348 cwd: worktreePath,
3349 detail: "The pull request head could not be resolved for this checkout.",
3350 });
3351 }
3352 return yield* gitCore.resolveCommit({
3353 cwd: worktreePath,
3354 revision: details.upstreamRef,
3355 });
3356 }),
3357 ),
3358 Effect.flatMap((target) =>
3359 gitCore.refreshCheckedOutBranch({
3360 cwd: worktreePath,
3361 targetCommit: target.commitSha,
3362 resetWhenHeadCommit: upstreamCommitBeforeFetch,
3363 }),
3364 ),
3365 Effect.catch((error) =>
3366 Effect.logWarning(
3367 "GitManager.preparePullRequestThread reused worktree refresh failed",
3368 {
3369 worktreePath,
3370 localBranch: localPullRequestBranch,
3371 cause: error,
3372 },
3373 ).pipe(Effect.as({ moved: false, onTarget: false })),
3374 ),
3375 );
3376
3377 // Setup can disrupt other threads using this worktree; rerun only when the checkout moved.
3378 if (refreshed.moved) {
3379 yield* maybeRunSetupScript(worktreePath);
3380 }
3381
3382 return {
3383 pullRequest,
3384 branch: localPullRequestBranch,
3385 worktreePath,
3386 isOnPullRequestHead: refreshed.onTarget,
3387 };
3388 });
3389
3390 const findLocalHeadBranch = Effect.fn("findLocalHeadBranch")(function* (cwd: string) {
3391 for (const [index, name] of [
3392 ...new Set([localPullRequestBranch, pullRequest.headBranch]),
3393 ].entries()) {
3394 let cursor: number | undefined;
3395 do {
3396 const result = yield* gitCore.listRefs({
3397 cwd,
3398 refKind: "local",
3399 query: name,
3400 cursor,
3401 refresh: index === 0 && cursor === undefined,
3402 });
3403 for (const branch of result.refs) {
3404 if (branch.name !== name) {
3405 continue;
3406 }
3407 if (name === localPullRequestBranch) {
3408 return branch;
3409 }
3410 if (branch.worktreePath) {
3411 const worktreePath = yield* canonicalizeExistingPath(branch.worktreePath);
3412 if (worktreePath !== rootWorktreePath) {
3413 return branch;
3414 }
3415 }
3416 }
3417 cursor = result.nextCursor ?? undefined;
3418 } while (cursor !== undefined);
3419 }
3420
3421 return null;
3422 });
3423
3424 // Claim the branch before refreshing, but initialize submodules only after selecting its head.
3425 const refreshNewWorktree = Effect.fn("refreshNewWorktree")(function* (cwd: string) {
3426 const upstreamCommitBeforeFetch = yield* gitCore
3427 .resolveCommit({ cwd, revision: "@{upstream}" })
3428 .pipe(
3429 Effect.map((resolved) => resolved.commitSha),
3430 Effect.orElseSucceed(() => null),
3431 );
3432 yield* configurePullRequestHeadUpstream(
3433 cwd,
3434 pullRequestWithRemoteInfo,
3435 localPullRequestBranch,
3436 );
3437 const target = yield* changeRequestHeadRef(cwd, pullRequest.number).pipe(
3438 Effect.flatMap((ref) => gitCore.fetchRefCommit({ cwd, ref })),
3439 Effect.filterOrFail(
3440 (resolved) =>
3441 pullRequestSummary.headSha === undefined ||
3442 resolved.commitSha === pullRequestSummary.headSha,
3443 () =>
3444 new GitManagerError({
3445 operation: "preparePullRequestThread",
3446 cwd,
3447 detail: "The fetched ref does not match the pull request head.",
3448 }),
3449 ),
3450 Effect.catch(() =>
3451 gitCore.resolveCommit({ cwd, revision: "@{upstream}" }).pipe(
3452 Effect.filterOrFail(
3453 (resolved) => resolved.commitSha === pullRequestSummary.headSha,
3454 () =>
3455 new GitManagerError({
3456 operation: "preparePullRequestThread",
3457 cwd,
3458 detail: "The configured upstream does not match the pull request head.",
3459 }),
3460 ),
3461 ),
3462 ),
3463 );
3464 const { commitSha: headCommit } = yield* gitCore.resolveCommit({ cwd, revision: "HEAD" });
3465 // A head that was ever published loses nothing when reset, even if a fetch already moved its upstream.
3466 const gitLines = (args: ReadonlyArray<string>) =>
3467 gitCore
3468 .execute({
3469 operation: "GitManager.preparePullRequestThread.publishedHead",
3470 cwd,
3471 args,
3472 allowNonZeroExit: true,
3473 timeoutMs: 5_000,
3474 })
3475 .pipe(
3476 Effect.map((result) =>
3477 result.exitCode === 0 ? result.stdout.split("\n").filter(Boolean) : [],
3478 ),
3479 );
3480 const publishedHead =
3481 (yield* gitLines(["for-each-ref", "--contains", headCommit, "refs/remotes"])).length >
3482 0 ||
3483 (yield* gitLines(["log", "--walk-reflogs", "--format=%H", "@{upstream}"])).includes(
3484 headCommit,
3485 );
3486 return yield* gitCore
3487 .refreshCheckedOutBranch({
3488 cwd,
3489 targetCommit: target.commitSha,
3490 resetWhenHeadCommit: publishedHead ? headCommit : upstreamCommitBeforeFetch,
3491 })
3492 .pipe(Effect.map((result) => result.onTarget));
3493 });
3494
3495 const createPullRequestWorktree = Effect.fn("createPullRequestWorktree")(function* (
3496 onWorktreeClaimed?: (path: string) => Effect.Effect<void>,
3497 ) {
3498 return yield* gitCore.createWorktree(
3499 {
3500 cwd: input.cwd,
3501 refName: localPullRequestBranch,
3502 path: null,
3503 },
3504 {
3505 ...(onWorktreeClaimed ? { progress: { onWorktreeClaimed } } : {}),
3506 ...(yield* readWorktreeCreationSettings),
3507 submodules: yield* projectSettingsFor(input).pipe(
3508 Effect.map(({ settings }) => settings.worktreeSubmodules),
3509 Effect.orElseSucceed(() => null),
3510 ),
3511 },
3512 );
3513 });
3514
3515 const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd);
3516 const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath
3517 ? yield* canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
3518 : null;
3519 if (
3520 existingBranchBeforeFetch?.worktreePath &&
3521 existingBranchBeforeFetchPath !== rootWorktreePath
3522 ) {
3523 return yield* reuseExistingWorktree(
3524 existingBranchBeforeFetch.worktreePath,
3525 existingBranchBeforeFetch.name,
3526 );
3527 }
3528 if (existingBranchBeforeFetchPath === rootWorktreePath) {
3529 return yield* new GitManagerError({
3530 operation: "preparePullRequestThread",
3531 cwd: input.cwd,
3532 detail:
3533 "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
3534 });
3535 }
3536 // Materializing would force this branch onto the head.
3537 if (existingBranchBeforeFetch !== null) {
3538 let isOnPullRequestHead = false;
3539 const worktree = yield* createPullRequestWorktree((cwd) =>
3540 refreshNewWorktree(cwd).pipe(
3541 Effect.catch((error) =>
3542 Effect.logWarning(
3543 "GitManager.preparePullRequestThread existing branch refresh failed",
3544 {
3545 localBranch: localPullRequestBranch,
3546 cause: error,
3547 },
3548 ).pipe(Effect.as(false)),
3549 ),
3550 Effect.tap((onTarget) =>
3551 Effect.sync(() => {
3552 isOnPullRequestHead = onTarget;
3553 }),
3554 ),
3555 Effect.asVoid,
3556 ),
3557 );
3558 yield* maybeRunSetupScript(worktree.worktree.path);
3559 return {
3560 pullRequest,
3561 branch: worktree.worktree.refName,
3562 worktreePath: worktree.worktree.path,
3563 isOnPullRequestHead,
3564 };
3565 }
3566
3567 yield* materializePullRequestHeadBranch(
3568 input.cwd,
3569 pullRequestWithRemoteInfo,
3570 localPullRequestBranch,
3571 );
3572
3573 const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd);
3574 const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath
3575 ? yield* canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
3576 : null;
3577 if (
3578 existingBranchAfterFetch?.worktreePath &&
3579 existingBranchAfterFetchPath !== rootWorktreePath
3580 ) {
3581 return yield* reuseExistingWorktree(
3582 existingBranchAfterFetch.worktreePath,
3583 existingBranchAfterFetch.name,
3584 );
3585 }
3586 if (existingBranchAfterFetchPath === rootWorktreePath) {
3587 return yield* new GitManagerError({
3588 operation: "preparePullRequestThread",
3589 cwd: input.cwd,
3590 detail:
3591 "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
3592 });
3593 }
3594
3595 const worktree = yield* createPullRequestWorktree();
3596 yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
3597 yield* maybeRunSetupScript(worktree.worktree.path);
3598
3599 return {
3600 pullRequest,
3601 branch: worktree.worktree.refName,
3602 worktreePath: worktree.worktree.path,
3603 isOnPullRequestHead: true,
3604 };
3605 }).pipe(
3606 Effect.tap((result) =>
3607 gitCore
3608 .writeConfigValue({
3609 cwd: input.cwd,
3610 key: checkedOutPullRequestKey(result.branch),
3611 value: result.pullRequest.url,
3612 })
3613 .pipe(
3614 Effect.catch((cause) =>
3615 Effect.logWarning("GitManager.preparePullRequestThread could not mark the branch", {
3616 branch: result.branch,
3617 cause,
3618 }),
3619 ),
3620 ),
3621 ),
3622 Effect.ensuring(invalidateStatus(input.cwd)),
3623 );
3624 }, asUserAction);
3625
3626 const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (
3627 settings: SourceControlTextGenerationSettings,
3628 cwd: string,
3629 branch: string | null,
3630 commitMessage?: string,
3631 filePaths?: readonly string[],
3632 ) {
3633 const suggestion = yield* resolveCommitAndBranchSuggestion({
3634 cwd,
3635 branch,
3636 ...(commitMessage ? { commitMessage } : {}),
3637 ...(filePaths ? { filePaths } : {}),
3638 includeBranch: true,
3639 settings,
3640 });
3641 if (!suggestion) {
3642 return yield* new GitManagerError({
3643 operation: "runFeatureBranchStep",
3644 cwd,
3645 detail: "Cannot create a feature branch because there are no changes to commit.",
3646 });
3647 }
3648
3649 const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
3650 const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
3651 const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
3652
3653 yield* gitCore.createRef({ cwd, refName: resolvedBranch });
3654 yield* Effect.scoped(gitCore.switchRef({ cwd, refName: resolvedBranch }));
3655
3656 return {
3657 branchStep: { status: "created" as const, name: resolvedBranch },
3658 resolvedCommitMessage: suggestion.commitMessage,
3659 resolvedCommitSuggestion: suggestion,
3660 };
3661 });
3662
3663 const runStackedAction: GitManager["Service"]["runStackedAction"] = Effect.fn("runStackedAction")(
3664 function* (input, options) {
3665 const progress = yield* createProgressEmitter(input, options);
3666 const currentPhase = yield* Ref.make<Option.Option<GitActionProgressPhase>>(Option.none());
3667
3668 const runAction = Effect.fn("runStackedAction.runAction")(function* (): Effect.fn.Return<
3669 GitRunStackedActionResult,
3670 GitManagerServiceError
3671 > {
3672 const initialStatus = yield* gitCore.statusDetails(input.cwd);
3673 const wantsCommit = isCommitAction(input.action);
3674 const wantsPush =
3675 input.action === "push" ||
3676 input.action === "commit_push" ||
3677 input.action === "commit_push_pr" ||
3678 (input.action === "create_pr" &&
3679 (!initialStatus.hasUpstream || (yield* createPrNeedsPush(input.cwd, initialStatus))));
3680 const wantsPr = input.action === "create_pr" || input.action === "commit_push_pr";
3681
3682 if (input.featureBranch && !wantsCommit) {
3683 return yield* new GitManagerError({
3684 operation: "runStackedAction",
3685 cwd: input.cwd,
3686 detail: "Feature-branch checkout is only supported for commit actions.",
3687 });
3688 }
3689 const phases: GitActionProgressPhase[] = [
3690 ...(input.featureBranch ? (["branch"] as const) : []),
3691 ...(wantsCommit ? (["commit"] as const) : []),
3692 ...(wantsPush ? (["push"] as const) : []),
3693 ...(wantsPr ? (["pr"] as const) : []),
3694 ];
3695
3696 yield* progress.emit({
3697 kind: "action_started",
3698 phases,
3699 });
3700
3701 if (!input.featureBranch && wantsPush && !initialStatus.branch) {
3702 return yield* new GitManagerError({
3703 operation: "runStackedAction",
3704 cwd: input.cwd,
3705 detail: "Cannot push from detached HEAD.",
3706 });
3707 }
3708 if (!input.featureBranch && wantsPr && !initialStatus.branch) {
3709 return yield* new GitManagerError({
3710 operation: "runStackedAction",
3711 cwd: input.cwd,
3712 detail: "Cannot create a pull request from detached HEAD.",
3713 });
3714 }
3715
3716 let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
3717 let commitMessageForStep = input.commitMessage;
3718 let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
3719
3720 const textGenerationSettings = yield* projectSettingsFor(input).pipe(
3721 Effect.flatMap(({ settings, projectId }) =>
3722 settings.sourceControlWriterModelSelection === null
3723 ? Effect.succeed({
3724 modelSelection: settings.textGenerationModelSelection,
3725 projectId,
3726 style: settings.sourceControlWritingStyle,
3727 })
3728 : providerRegistry.getProviders.pipe(
3729 Effect.map((providers) => ({
3730 modelSelection: ServerSettings.resolveSourceControlWriterModelSelection(
3731 settings,
3732 providers,
3733 projectId,
3734 ),
3735 projectId,
3736 style: settings.sourceControlWritingStyle,
3737 })),
3738 ),
3739 ),
3740 Effect.mapError(
3741 (cause) =>
3742 new GitManagerError({
3743 operation: "runStackedAction",
3744 cwd: input.cwd,
3745 detail: "Failed to get server settings.",
3746 cause,
3747 }),
3748 ),
3749 );
3750
3751 if (input.featureBranch) {
3752 yield* Ref.set(currentPhase, Option.some("branch"));
3753 yield* progress.emit({
3754 kind: "phase_started",
3755 phase: "branch",
3756 label: "Preparing feature branch...",
3757 });
3758 const result = yield* runFeatureBranchStep(
3759 textGenerationSettings,
3760 input.cwd,
3761 initialStatus.branch,
3762 input.commitMessage,
3763 input.filePaths,
3764 );
3765 branchStep = result.branchStep;
3766 commitMessageForStep = result.resolvedCommitMessage;
3767 preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
3768 } else {
3769 branchStep = { status: "skipped_not_requested" as const };
3770 }
3771
3772 const currentBranch = branchStep.name ?? initialStatus.branch;
3773 const commitAction = isCommitAction(input.action) ? input.action : null;
3774 const changeRequestTerms = wantsPr ? yield* changeRequestTermsFor(input.cwd) : null;
3775 // A stale or missing origin/HEAD hides the default branch from status, so check here
3776 // before anything is committed or pushed to it.
3777 if (changeRequestTerms && !input.featureBranch && initialStatus.branch) {
3778 yield* ensurePrHeadIsNotBase(
3779 input.cwd,
3780 { ...initialStatus, branch: initialStatus.branch },
3781 changeRequestTerms.shortLabelWithArticle,
3782 );
3783 }
3784
3785 const commit = commitAction
3786 ? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
3787 Effect.flatMap(() =>
3788 runCommitStep(
3789 textGenerationSettings,
3790 input.cwd,
3791 commitAction,
3792 currentBranch,
3793 commitMessageForStep,
3794 preResolvedCommitSuggestion,
3795 input.filePaths,
3796 options?.progressReporter,
3797 progress.actionId,
3798 ),
3799 ),
3800 )
3801 : { status: "skipped_not_requested" as const };
3802
3803 const push = wantsPush
3804 ? yield* progress
3805 .emit({
3806 kind: "phase_started",
3807 phase: "push",
3808 label: "Pushing...",
3809 })
3810 .pipe(
3811 Effect.tap(() => Ref.set(currentPhase, Option.some("push"))),
3812 Effect.flatMap(() => pushCurrentBranch(input.cwd, currentBranch)),
3813 )
3814 : { status: "skipped_not_requested" as const };
3815
3816 const pr = wantsPr
3817 ? yield* progress
3818 .emit({
3819 kind: "phase_started",
3820 phase: "pr",
3821 label: `Preparing ${changeRequestTerms?.shortLabel ?? "PR"}...`,
3822 })
3823 .pipe(
3824 Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))),
3825 Effect.flatMap(() =>
3826 runPrStep(
3827 textGenerationSettings,
3828 input.cwd,
3829 currentBranch,
3830 input.threadId,
3831 progress.emit,
3832 "pushRemote" in push && push.pushRemote && push.upstreamBranch
3833 ? { remoteName: push.pushRemote, upstreamRef: push.upstreamBranch }
3834 : undefined,
3835 ),
3836 ),
3837 )
3838 : { status: "skipped_not_requested" as const };
3839
3840 const toast = yield* buildCompletionToast(input.cwd, {
3841 action: input.action,
3842 branch: branchStep,
3843 commit,
3844 push,
3845 pr,
3846 });
3847
3848 const result = {
3849 action: input.action,
3850 branch: branchStep,
3851 commit,
3852 push,
3853 pr,
3854 toast,
3855 };
3856 yield* progress.emit({
3857 kind: "action_finished",
3858 result,
3859 });
3860 return result;
3861 });
3862
3863 return yield* runAction().pipe(
3864 Effect.ensuring(invalidateStatus(input.cwd)),
3865 Effect.tapError((error) =>
3866 Effect.flatMap(Ref.get(currentPhase), (phase) =>
3867 progress.emit({
3868 kind: "action_failed",
3869 phase: Option.getOrNull(phase),
3870 message: error.message,
3871 }),
3872 ),
3873 ),
3874 );
3875 },
3876 asUserAction,
3877 );
3878
3879 return GitManager.of({
3880 createWorktree,
3881 localStatus,
3882 remoteStatus,
3883 status,
3884 branchPullRequest,
3885 checkedOutPullRequest,
3886 invalidateLocalStatus,
3887 invalidateRemoteStatus,
3888 invalidateStatus,
3889 resolvePullRequest,
3890 preparePullRequestThread,
3891 runStackedAction,
3892 createPullRequest,
3893 subscribePullRequestStateChanges: PubSub.subscribe(pullRequestStateChanges).pipe(
3894 Effect.map((subscription) => Stream.fromSubscription(subscription)),
3895 ),
3896 });
3897 });
3898
3899 export const layer = Layer.effect(GitManager, make);