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

GitManager.ts

1,314 lines40.6 KB

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