Open History to see the last commit
1import { randomUUID } from "node:crypto";
2import { realpathSync } from "node:fs";
3
4import { Effect, FileSystem, Layer, Path } from "effect";
5import {
6 resolveAutoFeatureBranchName,
7 sanitizeBranchFragment,
8 sanitizeFeatureBranchName,
9} from "@t3tools/shared/git";
10
11import { GitManagerError } from "../Errors.ts";
12import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
13import { GitCore } from "../Services/GitCore.ts";
14import { GitHubCli } from "../Services/GitHubCli.ts";
15import { TextGeneration } from "../Services/TextGeneration.ts";
16
17interface OpenPrInfo {
18 number: number;
19 title: string;
20 url: string;
21 baseRefName: string;
22 headRefName: string;
23}
24
25interface PullRequestInfo extends OpenPrInfo {
26 state: "open" | "closed" | "merged";
27 updatedAt: string | null;
28}
29
30interface ResolvedPullRequest {
31 number: number;
32 title: string;
33 url: string;
34 baseBranch: string;
35 headBranch: string;
36 state: "open" | "closed" | "merged";
37}
38
39interface PullRequestHeadRemoteInfo {
40 isCrossRepository?: boolean;
41 headRepositoryNameWithOwner?: string | null;
42 headRepositoryOwnerLogin?: string | null;
43}
44
45interface BranchHeadContext {
46 localBranch: string;
47 headBranch: string;
48 headSelectors: ReadonlyArray<string>;
49 preferredHeadSelector: string;
50 remoteName: string | null;
51 headRepositoryNameWithOwner: string | null;
52 headRepositoryOwnerLogin: string | null;
53 isCrossRepository: boolean;
54}
55
56function parseRepositoryNameFromPullRequestUrl(url: string): string | null {
57 const trimmed = url.trim();
58 const match = /^https:\/\/github\.com\/[^/]+\/([^/]+)\/pull\/\d+(?:\/.*)?$/i.exec(trimmed);
59 const repositoryName = match?.[1]?.trim() ?? "";
60 return repositoryName.length > 0 ? repositoryName : null;
61}
62
63function resolveHeadRepositoryNameWithOwner(
64 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
65): string | null {
66 const explicitRepository = pullRequest.headRepositoryNameWithOwner?.trim() ?? "";
67 if (explicitRepository.length > 0) {
68 return explicitRepository;
69 }
70
71 if (!pullRequest.isCrossRepository) {
72 return null;
73 }
74
75 const ownerLogin = pullRequest.headRepositoryOwnerLogin?.trim() ?? "";
76 const repositoryName = parseRepositoryNameFromPullRequestUrl(pullRequest.url);
77 if (ownerLogin.length === 0 || !repositoryName) {
78 return null;
79 }
80
81 return `${ownerLogin}/${repositoryName}`;
82}
83
84function resolvePullRequestWorktreeLocalBranchName(
85 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
86): string {
87 if (!pullRequest.isCrossRepository) {
88 return pullRequest.headBranch;
89 }
90
91 const sanitizedHeadBranch = sanitizeBranchFragment(pullRequest.headBranch).trim();
92 const suffix = sanitizedHeadBranch.length > 0 ? sanitizedHeadBranch : "head";
93 return `t3code/pr-${pullRequest.number}/${suffix}`;
94}
95
96function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
97 const trimmed = url?.trim() ?? "";
98 if (trimmed.length === 0) {
99 return null;
100 }
101
102 const match =
103 /^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
104 trimmed,
105 );
106 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
107 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
108}
109
110function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null {
111 const trimmed = nameWithOwner?.trim() ?? "";
112 if (trimmed.length === 0) {
113 return null;
114 }
115 const [ownerLogin] = trimmed.split("/");
116 const normalizedOwnerLogin = ownerLogin?.trim() ?? "";
117 return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null;
118}
119
120function parsePullRequestList(raw: unknown): PullRequestInfo[] {
121 if (!Array.isArray(raw)) return [];
122
123 const parsed: PullRequestInfo[] = [];
124 for (const entry of raw) {
125 if (!entry || typeof entry !== "object") continue;
126 const record = entry as Record<string, unknown>;
127 const number = record.number;
128 const title = record.title;
129 const url = record.url;
130 const baseRefName = record.baseRefName;
131 const headRefName = record.headRefName;
132 const state = record.state;
133 const mergedAt = record.mergedAt;
134 const updatedAt = record.updatedAt;
135 if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
136 continue;
137 }
138 if (
139 typeof title !== "string" ||
140 typeof url !== "string" ||
141 typeof baseRefName !== "string" ||
142 typeof headRefName !== "string"
143 ) {
144 continue;
145 }
146
147 let normalizedState: "open" | "closed" | "merged";
148 if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
149 normalizedState = "merged";
150 } else if (state === "OPEN" || state === undefined || state === null) {
151 normalizedState = "open";
152 } else if (state === "CLOSED") {
153 normalizedState = "closed";
154 } else {
155 continue;
156 }
157
158 parsed.push({
159 number,
160 title,
161 url,
162 baseRefName,
163 headRefName,
164 state: normalizedState,
165 updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
166 });
167 }
168 return parsed;
169}
170
171function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
172 return new GitManagerError({
173 operation,
174 detail,
175 ...(cause !== undefined ? { cause } : {}),
176 });
177}
178
179function limitContext(value: string, maxChars: number): string {
180 if (value.length <= maxChars) return value;
181 return `${value.slice(0, maxChars)}\n\n[truncated]`;
182}
183
184function sanitizeCommitMessage(generated: {
185 subject: string;
186 body: string;
187 branch?: string | undefined;
188}): {
189 subject: string;
190 body: string;
191 branch?: string | undefined;
192} {
193 const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
194 const subject = rawSubject.replace(/[.]+$/g, "").trim();
195 const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
196 return {
197 subject: safeSubject,
198 body: generated.body.trim(),
199 ...(generated.branch !== undefined ? { branch: generated.branch } : {}),
200 };
201}
202
203interface CommitAndBranchSuggestion {
204 subject: string;
205 body: string;
206 branch?: string | undefined;
207 commitMessage: string;
208}
209
210function formatCommitMessage(subject: string, body: string): string {
211 const trimmedBody = body.trim();
212 if (trimmedBody.length === 0) {
213 return subject;
214 }
215 return `${subject}\n\n${trimmedBody}`;
216}
217
218function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
219 const normalized = raw.replace(/\r\n/g, "\n").trim();
220 if (normalized.length === 0) {
221 return null;
222 }
223
224 const [firstLine, ...rest] = normalized.split("\n");
225 const subject = firstLine?.trim() ?? "";
226 if (subject.length === 0) {
227 return null;
228 }
229
230 return {
231 subject,
232 body: rest.join("\n").trim(),
233 };
234}
235
236function extractBranchFromRef(ref: string): string {
237 const normalized = ref.trim();
238
239 if (normalized.startsWith("refs/remotes/")) {
240 const withoutPrefix = normalized.slice("refs/remotes/".length);
241 const firstSlash = withoutPrefix.indexOf("/");
242 if (firstSlash === -1) {
243 return withoutPrefix.trim();
244 }
245 return withoutPrefix.slice(firstSlash + 1).trim();
246 }
247
248 const firstSlash = normalized.indexOf("/");
249 if (firstSlash === -1) {
250 return normalized;
251 }
252 return normalized.slice(firstSlash + 1).trim();
253}
254
255function appendUnique(values: string[], next: string | null | undefined): void {
256 const trimmed = next?.trim() ?? "";
257 if (trimmed.length === 0 || values.includes(trimmed)) {
258 return;
259 }
260 values.push(trimmed);
261}
262
263function toStatusPr(pr: PullRequestInfo): {
264 number: number;
265 title: string;
266 url: string;
267 baseBranch: string;
268 headBranch: string;
269 state: "open" | "closed" | "merged";
270} {
271 return {
272 number: pr.number,
273 title: pr.title,
274 url: pr.url,
275 baseBranch: pr.baseRefName,
276 headBranch: pr.headRefName,
277 state: pr.state,
278 };
279}
280
281function normalizePullRequestReference(reference: string): string {
282 const trimmed = reference.trim();
283 const hashNumber = /^#(\d+)$/.exec(trimmed);
284 return hashNumber?.[1] ?? trimmed;
285}
286
287function canonicalizeExistingPath(value: string): string {
288 try {
289 return realpathSync.native(value);
290 } catch {
291 return value;
292 }
293}
294
295function toResolvedPullRequest(pr: {
296 number: number;
297 title: string;
298 url: string;
299 baseRefName: string;
300 headRefName: string;
301 state?: "open" | "closed" | "merged";
302}): ResolvedPullRequest {
303 return {
304 number: pr.number,
305 title: pr.title,
306 url: pr.url,
307 baseBranch: pr.baseRefName,
308 headBranch: pr.headRefName,
309 state: pr.state ?? "open",
310 };
311}
312
313function shouldPreferSshRemote(url: string | null): boolean {
314 if (!url) return false;
315 const trimmed = url.trim();
316 return trimmed.startsWith("git@") || trimmed.startsWith("ssh://");
317}
318
319function toPullRequestHeadRemoteInfo(pr: {
320 isCrossRepository?: boolean;
321 headRepositoryNameWithOwner?: string | null;
322 headRepositoryOwnerLogin?: string | null;
323}): PullRequestHeadRemoteInfo {
324 return {
325 ...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
326 ...(pr.headRepositoryNameWithOwner !== undefined
327 ? { headRepositoryNameWithOwner: pr.headRepositoryNameWithOwner }
328 : {}),
329 ...(pr.headRepositoryOwnerLogin !== undefined
330 ? { headRepositoryOwnerLogin: pr.headRepositoryOwnerLogin }
331 : {}),
332 };
333}
334
335export const makeGitManager = Effect.gen(function* () {
336 const gitCore = yield* GitCore;
337 const gitHubCli = yield* GitHubCli;
338 const textGeneration = yield* TextGeneration;
339
340 const configurePullRequestHeadUpstream = (
341 cwd: string,
342 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
343 localBranch = pullRequest.headBranch,
344 ) =>
345 Effect.gen(function* () {
346 const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
347 if (repositoryNameWithOwner.length === 0) {
348 return;
349 }
350
351 const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
352 cwd,
353 repository: repositoryNameWithOwner,
354 });
355 const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url");
356 const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
357 const preferredRemoteName =
358 pullRequest.headRepositoryOwnerLogin?.trim() ||
359 repositoryNameWithOwner.split("/")[0]?.trim() ||
360 "fork";
361 const remoteName = yield* gitCore.ensureRemote({
362 cwd,
363 preferredName: preferredRemoteName,
364 url: remoteUrl,
365 });
366
367 yield* gitCore.setBranchUpstream({
368 cwd,
369 branch: localBranch,
370 remoteName,
371 remoteBranch: pullRequest.headBranch,
372 });
373 }).pipe(
374 Effect.catch((error) =>
375 Effect.logWarning(
376 `GitManager.configurePullRequestHeadUpstream: failed to configure upstream for ${localBranch} -> ${pullRequest.headBranch} in ${cwd}: ${error.message}`,
377 ).pipe(Effect.asVoid),
378 ),
379 );
380
381 const materializePullRequestHeadBranch = (
382 cwd: string,
383 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
384 localBranch = pullRequest.headBranch,
385 ) =>
386 Effect.gen(function* () {
387 const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
388
389 if (repositoryNameWithOwner.length === 0) {
390 yield* gitCore.fetchPullRequestBranch({
391 cwd,
392 prNumber: pullRequest.number,
393 branch: localBranch,
394 });
395 return;
396 }
397
398 const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
399 cwd,
400 repository: repositoryNameWithOwner,
401 });
402 const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url");
403 const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
404 const preferredRemoteName =
405 pullRequest.headRepositoryOwnerLogin?.trim() ||
406 repositoryNameWithOwner.split("/")[0]?.trim() ||
407 "fork";
408 const remoteName = yield* gitCore.ensureRemote({
409 cwd,
410 preferredName: preferredRemoteName,
411 url: remoteUrl,
412 });
413
414 yield* gitCore.fetchRemoteBranch({
415 cwd,
416 remoteName,
417 remoteBranch: pullRequest.headBranch,
418 localBranch,
419 });
420 yield* gitCore.setBranchUpstream({
421 cwd,
422 branch: localBranch,
423 remoteName,
424 remoteBranch: pullRequest.headBranch,
425 });
426 }).pipe(
427 Effect.catch(() =>
428 gitCore.fetchPullRequestBranch({
429 cwd,
430 prNumber: pullRequest.number,
431 branch: localBranch,
432 }),
433 ),
434 );
435 const fileSystem = yield* FileSystem.FileSystem;
436 const path = yield* Path.Path;
437
438 const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
439
440 const readConfigValueNullable = (cwd: string, key: string) =>
441 gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
442
443 const resolveRemoteRepositoryContext = (cwd: string, remoteName: string | null) =>
444 Effect.gen(function* () {
445 if (!remoteName) {
446 return {
447 repositoryNameWithOwner: null,
448 ownerLogin: null,
449 };
450 }
451
452 const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
453 const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
454 return {
455 repositoryNameWithOwner,
456 ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
457 };
458 });
459
460 const resolveBranchHeadContext = (
461 cwd: string,
462 details: { branch: string; upstreamRef: string | null },
463 ) =>
464 Effect.gen(function* () {
465 const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`);
466 const headBranchFromUpstream = details.upstreamRef
467 ? extractBranchFromRef(details.upstreamRef)
468 : "";
469 const headBranch =
470 headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch;
471
472 const [remoteRepository, originRepository] = yield* Effect.all(
473 [
474 resolveRemoteRepositoryContext(cwd, remoteName),
475 resolveRemoteRepositoryContext(cwd, "origin"),
476 ],
477 { concurrency: "unbounded" },
478 );
479
480 const isCrossRepository =
481 remoteRepository.repositoryNameWithOwner !== null &&
482 originRepository.repositoryNameWithOwner !== null
483 ? remoteRepository.repositoryNameWithOwner.toLowerCase() !==
484 originRepository.repositoryNameWithOwner.toLowerCase()
485 : remoteName !== null &&
486 remoteName !== "origin" &&
487 remoteRepository.repositoryNameWithOwner !== null;
488
489 const ownerHeadSelector =
490 remoteRepository.ownerLogin && headBranch.length > 0
491 ? `${remoteRepository.ownerLogin}:${headBranch}`
492 : null;
493 const remoteAliasHeadSelector =
494 remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null;
495 const shouldProbeRemoteOwnedSelectors =
496 isCrossRepository || (remoteName !== null && remoteName !== "origin");
497
498 const headSelectors: string[] = [];
499 if (isCrossRepository && shouldProbeRemoteOwnedSelectors) {
500 appendUnique(headSelectors, ownerHeadSelector);
501 appendUnique(
502 headSelectors,
503 remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
504 );
505 }
506 appendUnique(headSelectors, details.branch);
507 appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null);
508 if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) {
509 appendUnique(headSelectors, ownerHeadSelector);
510 appendUnique(
511 headSelectors,
512 remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
513 );
514 }
515
516 return {
517 localBranch: details.branch,
518 headBranch,
519 headSelectors,
520 preferredHeadSelector:
521 ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,
522 remoteName,
523 headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,
524 headRepositoryOwnerLogin: remoteRepository.ownerLogin,
525 isCrossRepository,
526 } satisfies BranchHeadContext;
527 });
528
529 const findOpenPr = (cwd: string, headSelectors: ReadonlyArray<string>) =>
530 Effect.gen(function* () {
531 for (const headSelector of headSelectors) {
532 const pullRequests = yield* gitHubCli.listOpenPullRequests({
533 cwd,
534 headSelector,
535 limit: 1,
536 });
537
538 const [firstPullRequest] = pullRequests;
539 if (firstPullRequest) {
540 return {
541 number: firstPullRequest.number,
542 title: firstPullRequest.title,
543 url: firstPullRequest.url,
544 baseRefName: firstPullRequest.baseRefName,
545 headRefName: firstPullRequest.headRefName,
546 state: "open",
547 updatedAt: null,
548 } satisfies PullRequestInfo;
549 }
550 }
551
552 return null;
553 });
554
555 const findLatestPr = (cwd: string, details: { branch: string; upstreamRef: string | null }) =>
556 Effect.gen(function* () {
557 const headContext = yield* resolveBranchHeadContext(cwd, details);
558 const parsedByNumber = new Map<number, PullRequestInfo>();
559
560 for (const headSelector of headContext.headSelectors) {
561 const stdout = yield* gitHubCli
562 .execute({
563 cwd,
564 args: [
565 "pr",
566 "list",
567 "--head",
568 headSelector,
569 "--state",
570 "all",
571 "--limit",
572 "20",
573 "--json",
574 "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
575 ],
576 })
577 .pipe(Effect.map((result) => result.stdout));
578
579 const raw = stdout.trim();
580 if (raw.length === 0) {
581 continue;
582 }
583
584 const parsedJson = yield* Effect.try({
585 try: () => JSON.parse(raw) as unknown,
586 catch: (cause) =>
587 gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
588 });
589
590 for (const pr of parsePullRequestList(parsedJson)) {
591 parsedByNumber.set(pr.number, pr);
592 }
593 }
594
595 const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => {
596 const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
597 const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
598 return right - left;
599 });
600
601 const latestOpenPr = parsed.find((pr) => pr.state === "open");
602 if (latestOpenPr) {
603 return latestOpenPr;
604 }
605 return parsed[0] ?? null;
606 });
607
608 const resolveBaseBranch = (
609 cwd: string,
610 branch: string,
611 upstreamRef: string | null,
612 headContext: Pick<BranchHeadContext, "isCrossRepository">,
613 ) =>
614 Effect.gen(function* () {
615 const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
616 if (configured) return configured;
617
618 if (upstreamRef && !headContext.isCrossRepository) {
619 const upstreamBranch = extractBranchFromRef(upstreamRef);
620 if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
621 return upstreamBranch;
622 }
623 }
624
625 const defaultFromGh = yield* gitHubCli
626 .getDefaultBranch({ cwd })
627 .pipe(Effect.catch(() => Effect.succeed(null)));
628 if (defaultFromGh) {
629 return defaultFromGh;
630 }
631
632 return "main";
633 });
634
635 const resolveCommitAndBranchSuggestion = (input: {
636 cwd: string;
637 branch: string | null;
638 commitMessage?: string;
639 /** When true, also produce a semantic feature branch name. */
640 includeBranch?: boolean;
641 filePaths?: readonly string[];
642 model?: string;
643 }) =>
644 Effect.gen(function* () {
645 const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
646 if (!context) {
647 return null;
648 }
649
650 const customCommit = parseCustomCommitMessage(input.commitMessage ?? "");
651 if (customCommit) {
652 return {
653 subject: customCommit.subject,
654 body: customCommit.body,
655 ...(input.includeBranch
656 ? { branch: sanitizeFeatureBranchName(customCommit.subject) }
657 : {}),
658 commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),
659 };
660 }
661
662 const generated = yield* textGeneration
663 .generateCommitMessage({
664 cwd: input.cwd,
665 branch: input.branch,
666 stagedSummary: limitContext(context.stagedSummary, 8_000),
667 stagedPatch: limitContext(context.stagedPatch, 50_000),
668 ...(input.includeBranch ? { includeBranch: true } : {}),
669 ...(input.model ? { model: input.model } : {}),
670 })
671 .pipe(Effect.map((result) => sanitizeCommitMessage(result)));
672
673 return {
674 subject: generated.subject,
675 body: generated.body,
676 ...(generated.branch !== undefined ? { branch: generated.branch } : {}),
677 commitMessage: formatCommitMessage(generated.subject, generated.body),
678 };
679 });
680
681 const runCommitStep = (
682 cwd: string,
683 branch: string | null,
684 commitMessage?: string,
685 preResolvedSuggestion?: CommitAndBranchSuggestion,
686 filePaths?: readonly string[],
687 model?: string,
688 ) =>
689 Effect.gen(function* () {
690 const suggestion =
691 preResolvedSuggestion ??
692 (yield* resolveCommitAndBranchSuggestion({
693 cwd,
694 branch,
695 ...(commitMessage ? { commitMessage } : {}),
696 ...(filePaths ? { filePaths } : {}),
697 ...(model ? { model } : {}),
698 }));
699 if (!suggestion) {
700 return { status: "skipped_no_changes" as const };
701 }
702
703 const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
704 return {
705 status: "created" as const,
706 commitSha,
707 subject: suggestion.subject,
708 };
709 });
710
711 const runPrStep = (cwd: string, fallbackBranch: string | null, model?: string) =>
712 Effect.gen(function* () {
713 const details = yield* gitCore.statusDetails(cwd);
714 const branch = details.branch ?? fallbackBranch;
715 if (!branch) {
716 return yield* gitManagerError(
717 "runPrStep",
718 "Cannot create a pull request from detached HEAD.",
719 );
720 }
721 if (!details.hasUpstream) {
722 return yield* gitManagerError(
723 "runPrStep",
724 "Current branch has not been pushed. Push before creating a PR.",
725 );
726 }
727
728 const headContext = yield* resolveBranchHeadContext(cwd, {
729 branch,
730 upstreamRef: details.upstreamRef,
731 });
732
733 const existing = yield* findOpenPr(cwd, headContext.headSelectors);
734 if (existing) {
735 return {
736 status: "opened_existing" as const,
737 url: existing.url,
738 number: existing.number,
739 baseBranch: existing.baseRefName,
740 headBranch: existing.headRefName,
741 title: existing.title,
742 };
743 }
744
745 const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext);
746 const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
747
748 const generated = yield* textGeneration.generatePrContent({
749 cwd,
750 baseBranch,
751 headBranch: headContext.headBranch,
752 commitSummary: limitContext(rangeContext.commitSummary, 20_000),
753 diffSummary: limitContext(rangeContext.diffSummary, 20_000),
754 diffPatch: limitContext(rangeContext.diffPatch, 60_000),
755 ...(model ? { model } : {}),
756 });
757
758 const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
759 yield* fileSystem
760 .writeFileString(bodyFile, generated.body)
761 .pipe(
762 Effect.mapError((cause) =>
763 gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause),
764 ),
765 );
766 yield* gitHubCli
767 .createPullRequest({
768 cwd,
769 baseBranch,
770 headSelector: headContext.preferredHeadSelector,
771 title: generated.title,
772 bodyFile,
773 })
774 .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));
775
776 const created = yield* findOpenPr(cwd, headContext.headSelectors);
777 if (!created) {
778 return {
779 status: "created" as const,
780 baseBranch,
781 headBranch: headContext.headBranch,
782 title: generated.title,
783 };
784 }
785
786 return {
787 status: "created" as const,
788 url: created.url,
789 number: created.number,
790 baseBranch: created.baseRefName,
791 headBranch: created.headRefName,
792 title: created.title,
793 };
794 });
795
796 const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
797 const details = yield* gitCore.statusDetails(input.cwd);
798
799 const pr =
800 details.branch !== null
801 ? yield* findLatestPr(input.cwd, {
802 branch: details.branch,
803 upstreamRef: details.upstreamRef,
804 }).pipe(
805 Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
806 Effect.catch(() => Effect.succeed(null)),
807 )
808 : null;
809
810 return {
811 branch: details.branch,
812 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
813 workingTree: details.workingTree,
814 hasUpstream: details.hasUpstream,
815 aheadCount: details.aheadCount,
816 behindCount: details.behindCount,
817 pr,
818 };
819 });
820
821 const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fnUntraced(
822 function* (input) {
823 const pullRequest = yield* gitHubCli
824 .getPullRequest({
825 cwd: input.cwd,
826 reference: normalizePullRequestReference(input.reference),
827 })
828 .pipe(Effect.map((resolved) => toResolvedPullRequest(resolved)));
829
830 return { pullRequest };
831 },
832 );
833
834 const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fnUntraced(
835 function* (input) {
836 const normalizedReference = normalizePullRequestReference(input.reference);
837 const rootWorktreePath = canonicalizeExistingPath(input.cwd);
838 const pullRequestSummary = yield* gitHubCli.getPullRequest({
839 cwd: input.cwd,
840 reference: normalizedReference,
841 });
842 const pullRequest = toResolvedPullRequest(pullRequestSummary);
843
844 if (input.mode === "local") {
845 yield* gitHubCli.checkoutPullRequest({
846 cwd: input.cwd,
847 reference: normalizedReference,
848 force: true,
849 });
850 const details = yield* gitCore.statusDetails(input.cwd);
851 yield* configurePullRequestHeadUpstream(
852 input.cwd,
853 {
854 ...pullRequest,
855 ...toPullRequestHeadRemoteInfo(pullRequestSummary),
856 },
857 details.branch ?? pullRequest.headBranch,
858 );
859 return {
860 pullRequest,
861 branch: details.branch ?? pullRequest.headBranch,
862 worktreePath: null,
863 };
864 }
865
866 const ensureExistingWorktreeUpstream = (worktreePath: string) =>
867 Effect.gen(function* () {
868 const details = yield* gitCore.statusDetails(worktreePath);
869 yield* configurePullRequestHeadUpstream(
870 worktreePath,
871 {
872 ...pullRequest,
873 ...toPullRequestHeadRemoteInfo(pullRequestSummary),
874 },
875 details.branch ?? pullRequest.headBranch,
876 );
877 });
878
879 const pullRequestWithRemoteInfo = {
880 ...pullRequest,
881 ...toPullRequestHeadRemoteInfo(pullRequestSummary),
882 } as const;
883 const localPullRequestBranch =
884 resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
885
886 const findLocalHeadBranch = (cwd: string) =>
887 gitCore.listBranches({ cwd }).pipe(
888 Effect.map((result) => {
889 const localBranch = result.branches.find(
890 (branch) => !branch.isRemote && branch.name === localPullRequestBranch,
891 );
892 if (localBranch) {
893 return localBranch;
894 }
895 if (localPullRequestBranch === pullRequest.headBranch) {
896 return null;
897 }
898 return (
899 result.branches.find(
900 (branch) =>
901 !branch.isRemote &&
902 branch.name === pullRequest.headBranch &&
903 branch.worktreePath !== null &&
904 canonicalizeExistingPath(branch.worktreePath) !== rootWorktreePath,
905 ) ?? null
906 );
907 }),
908 );
909
910 const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd);
911 const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath
912 ? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
913 : null;
914 if (
915 existingBranchBeforeFetch?.worktreePath &&
916 existingBranchBeforeFetchPath !== rootWorktreePath
917 ) {
918 yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath);
919 return {
920 pullRequest,
921 branch: localPullRequestBranch,
922 worktreePath: existingBranchBeforeFetch.worktreePath,
923 };
924 }
925 if (existingBranchBeforeFetchPath === rootWorktreePath) {
926 return yield* gitManagerError(
927 "preparePullRequestThread",
928 "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.",
929 );
930 }
931
932 yield* materializePullRequestHeadBranch(
933 input.cwd,
934 pullRequestWithRemoteInfo,
935 localPullRequestBranch,
936 );
937
938 const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd);
939 const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath
940 ? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
941 : null;
942 if (
943 existingBranchAfterFetch?.worktreePath &&
944 existingBranchAfterFetchPath !== rootWorktreePath
945 ) {
946 yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath);
947 return {
948 pullRequest,
949 branch: localPullRequestBranch,
950 worktreePath: existingBranchAfterFetch.worktreePath,
951 };
952 }
953 if (existingBranchAfterFetchPath === rootWorktreePath) {
954 return yield* gitManagerError(
955 "preparePullRequestThread",
956 "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.",
957 );
958 }
959
960 const worktree = yield* gitCore.createWorktree({
961 cwd: input.cwd,
962 branch: localPullRequestBranch,
963 path: null,
964 });
965 yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
966
967 return {
968 pullRequest,
969 branch: worktree.worktree.branch,
970 worktreePath: worktree.worktree.path,
971 };
972 },
973 );
974
975 const runFeatureBranchStep = (
976 cwd: string,
977 branch: string | null,
978 commitMessage?: string,
979 filePaths?: readonly string[],
980 model?: string,
981 ) =>
982 Effect.gen(function* () {
983 const suggestion = yield* resolveCommitAndBranchSuggestion({
984 cwd,
985 branch,
986 ...(commitMessage ? { commitMessage } : {}),
987 ...(filePaths ? { filePaths } : {}),
988 includeBranch: true,
989 ...(model ? { model } : {}),
990 });
991 if (!suggestion) {
992 return yield* gitManagerError(
993 "runFeatureBranchStep",
994 "Cannot create a feature branch because there are no changes to commit.",
995 );
996 }
997
998 const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
999 const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
1000 const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
1001
1002 yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
1003 yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
1004
1005 return {
1006 branchStep: { status: "created" as const, name: resolvedBranch },
1007 resolvedCommitMessage: suggestion.commitMessage,
1008 resolvedCommitSuggestion: suggestion,
1009 };
1010 });
1011
1012 const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
1013 function* (input) {
1014 const wantsPush = input.action !== "commit";
1015 const wantsPr = input.action === "commit_push_pr";
1016
1017 const initialStatus = yield* gitCore.statusDetails(input.cwd);
1018 if (!input.featureBranch && wantsPush && !initialStatus.branch) {
1019 return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
1020 }
1021 if (!input.featureBranch && wantsPr && !initialStatus.branch) {
1022 return yield* gitManagerError(
1023 "runStackedAction",
1024 "Cannot create a pull request from detached HEAD.",
1025 );
1026 }
1027
1028 let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
1029 let commitMessageForStep = input.commitMessage;
1030 let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
1031
1032 if (input.featureBranch) {
1033 const result = yield* runFeatureBranchStep(
1034 input.cwd,
1035 initialStatus.branch,
1036 input.commitMessage,
1037 input.filePaths,
1038 input.textGenerationModel,
1039 );
1040 branchStep = result.branchStep;
1041 commitMessageForStep = result.resolvedCommitMessage;
1042 preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
1043 } else {
1044 branchStep = { status: "skipped_not_requested" as const };
1045 }
1046
1047 const currentBranch = branchStep.name ?? initialStatus.branch;
1048
1049 const commit = yield* runCommitStep(
1050 input.cwd,
1051 currentBranch,
1052 commitMessageForStep,
1053 preResolvedCommitSuggestion,
1054 input.filePaths,
1055 input.textGenerationModel,
1056 );
1057
1058 const push = wantsPush
1059 ? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
1060 : { status: "skipped_not_requested" as const };
1061
1062 const pr = wantsPr
1063 ? yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel)
1064 : { status: "skipped_not_requested" as const };
1065
1066 return {
1067 action: input.action,
1068 branch: branchStep,
1069 commit,
1070 push,
1071 pr,
1072 };
1073 },
1074 );
1075
1076 return {
1077 status,
1078 resolvePullRequest,
1079 preparePullRequestThread,
1080 runStackedAction,
1081 } satisfies GitManagerShape;
1082});
1083
1084export const GitManagerLive = Layer.effect(GitManager, makeGitManager);