Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitManager.ts

1,282 lines40.1 KB

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