Open History to see the last commit
1import { randomUUID } from "node:crypto";
2
3import { Effect, FileSystem, Layer, Path } from "effect";
4import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
5
6import { GitManagerError } from "../Errors.ts";
7import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
8import { GitCore } from "../Services/GitCore.ts";
9import { GitHubCli } from "../Services/GitHubCli.ts";
10import { TextGeneration } from "../Services/TextGeneration.ts";
11
12interface OpenPrInfo {
13 number: number;
14 title: string;
15 url: string;
16 baseRefName: string;
17 headRefName: string;
18}
19
20interface PullRequestInfo extends OpenPrInfo {
21 state: "open" | "closed" | "merged";
22 updatedAt: string | null;
23}
24
25function parsePullRequestList(raw: unknown): PullRequestInfo[] {
26 if (!Array.isArray(raw)) return [];
27
28 const parsed: PullRequestInfo[] = [];
29 for (const entry of raw) {
30 if (!entry || typeof entry !== "object") continue;
31 const record = entry as Record<string, unknown>;
32 const number = record.number;
33 const title = record.title;
34 const url = record.url;
35 const baseRefName = record.baseRefName;
36 const headRefName = record.headRefName;
37 const state = record.state;
38 const mergedAt = record.mergedAt;
39 const updatedAt = record.updatedAt;
40 if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
41 continue;
42 }
43 if (
44 typeof title !== "string" ||
45 typeof url !== "string" ||
46 typeof baseRefName !== "string" ||
47 typeof headRefName !== "string"
48 ) {
49 continue;
50 }
51
52 let normalizedState: "open" | "closed" | "merged";
53 if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
54 normalizedState = "merged";
55 } else if (state === "OPEN" || state === undefined || state === null) {
56 normalizedState = "open";
57 } else if (state === "CLOSED") {
58 normalizedState = "closed";
59 } else {
60 continue;
61 }
62
63 parsed.push({
64 number,
65 title,
66 url,
67 baseRefName,
68 headRefName,
69 state: normalizedState,
70 updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
71 });
72 }
73 return parsed;
74}
75
76function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
77 return new GitManagerError({
78 operation,
79 detail,
80 ...(cause !== undefined ? { cause } : {}),
81 });
82}
83
84function limitContext(value: string, maxChars: number): string {
85 if (value.length <= maxChars) return value;
86 return `${value.slice(0, maxChars)}\n\n[truncated]`;
87}
88
89function sanitizeCommitMessage(generated: {
90 subject: string;
91 body: string;
92 branch?: string | undefined;
93}): {
94 subject: string;
95 body: string;
96 branch?: string | undefined;
97} {
98 const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
99 const subject = rawSubject.replace(/[.]+$/g, "").trim();
100 const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
101 return {
102 subject: safeSubject,
103 body: generated.body.trim(),
104 ...(generated.branch !== undefined ? { branch: generated.branch } : {}),
105 };
106}
107
108interface CommitAndBranchSuggestion {
109 subject: string;
110 body: string;
111 branch?: string | undefined;
112 commitMessage: string;
113}
114
115function formatCommitMessage(subject: string, body: string): string {
116 const trimmedBody = body.trim();
117 if (trimmedBody.length === 0) {
118 return subject;
119 }
120 return `${subject}\n\n${trimmedBody}`;
121}
122
123function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
124 const normalized = raw.replace(/\r\n/g, "\n").trim();
125 if (normalized.length === 0) {
126 return null;
127 }
128
129 const [firstLine, ...rest] = normalized.split("\n");
130 const subject = firstLine?.trim() ?? "";
131 if (subject.length === 0) {
132 return null;
133 }
134
135 return {
136 subject,
137 body: rest.join("\n").trim(),
138 };
139}
140
141function extractBranchFromRef(ref: string): string {
142 const normalized = ref.trim();
143
144 if (normalized.startsWith("refs/remotes/")) {
145 const withoutPrefix = normalized.slice("refs/remotes/".length);
146 const firstSlash = withoutPrefix.indexOf("/");
147 if (firstSlash === -1) {
148 return withoutPrefix.trim();
149 }
150 return withoutPrefix.slice(firstSlash + 1).trim();
151 }
152
153 const firstSlash = normalized.indexOf("/");
154 if (firstSlash === -1) {
155 return normalized;
156 }
157 return normalized.slice(firstSlash + 1).trim();
158}
159
160function toStatusPr(pr: PullRequestInfo): {
161 number: number;
162 title: string;
163 url: string;
164 baseBranch: string;
165 headBranch: string;
166 state: "open" | "closed" | "merged";
167} {
168 return {
169 number: pr.number,
170 title: pr.title,
171 url: pr.url,
172 baseBranch: pr.baseRefName,
173 headBranch: pr.headRefName,
174 state: pr.state,
175 };
176}
177
178export const makeGitManager = Effect.gen(function* () {
179 const gitCore = yield* GitCore;
180 const gitHubCli = yield* GitHubCli;
181 const textGeneration = yield* TextGeneration;
182 const fileSystem = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184
185 const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
186
187 const findOpenPr = (cwd: string, branch: string) =>
188 gitHubCli
189 .listOpenPullRequests({
190 cwd,
191 headBranch: branch,
192 limit: 1,
193 })
194 .pipe(
195 Effect.map((prs) => {
196 const [first] = prs;
197 if (!first) {
198 return null;
199 }
200 return {
201 number: first.number,
202 title: first.title,
203 url: first.url,
204 baseRefName: first.baseRefName,
205 headRefName: first.headRefName,
206 state: "open",
207 updatedAt: null,
208 } satisfies PullRequestInfo;
209 }),
210 );
211
212 const findLatestPr = (cwd: string, branch: string) =>
213 Effect.gen(function* () {
214 const stdout = yield* gitHubCli
215 .execute({
216 cwd,
217 args: [
218 "pr",
219 "list",
220 "--head",
221 branch,
222 "--state",
223 "all",
224 "--limit",
225 "20",
226 "--json",
227 "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
228 ],
229 })
230 .pipe(Effect.map((result) => result.stdout));
231
232 const raw = stdout.trim();
233 if (raw.length === 0) {
234 return null;
235 }
236
237 const parsedJson = yield* Effect.try({
238 try: () => JSON.parse(raw) as unknown,
239 catch: (cause) =>
240 gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
241 });
242
243 const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
244 const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
245 const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
246 return right - left;
247 });
248
249 const latestOpenPr = parsed.find((pr) => pr.state === "open");
250 if (latestOpenPr) {
251 return latestOpenPr;
252 }
253 return parsed[0] ?? null;
254 });
255
256 const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
257 Effect.gen(function* () {
258 const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
259 if (configured) return configured;
260
261 if (upstreamRef) {
262 const upstreamBranch = extractBranchFromRef(upstreamRef);
263 if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
264 return upstreamBranch;
265 }
266 }
267
268 const defaultFromGh = yield* gitHubCli
269 .getDefaultBranch({ cwd })
270 .pipe(Effect.catch(() => Effect.succeed(null)));
271 if (defaultFromGh) {
272 return defaultFromGh;
273 }
274
275 return "main";
276 });
277
278 const resolveCommitAndBranchSuggestion = (input: {
279 cwd: string;
280 branch: string | null;
281 commitMessage?: string;
282 /** When true, also produce a semantic feature branch name. */
283 includeBranch?: boolean;
284 }) =>
285 Effect.gen(function* () {
286 const context = yield* gitCore.prepareCommitContext(input.cwd);
287 if (!context) {
288 return null;
289 }
290
291 const customCommit = parseCustomCommitMessage(input.commitMessage ?? "");
292 if (customCommit) {
293 return {
294 subject: customCommit.subject,
295 body: customCommit.body,
296 ...(input.includeBranch
297 ? { branch: sanitizeFeatureBranchName(customCommit.subject) }
298 : {}),
299 commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),
300 };
301 }
302
303 const generated = yield* textGeneration
304 .generateCommitMessage({
305 cwd: input.cwd,
306 branch: input.branch,
307 stagedSummary: limitContext(context.stagedSummary, 8_000),
308 stagedPatch: limitContext(context.stagedPatch, 50_000),
309 ...(input.includeBranch ? { includeBranch: true } : {}),
310 })
311 .pipe(Effect.map((result) => sanitizeCommitMessage(result)));
312
313 return {
314 subject: generated.subject,
315 body: generated.body,
316 ...(generated.branch !== undefined ? { branch: generated.branch } : {}),
317 commitMessage: formatCommitMessage(generated.subject, generated.body),
318 };
319 });
320
321 const runCommitStep = (
322 cwd: string,
323 branch: string | null,
324 commitMessage?: string,
325 preResolvedSuggestion?: CommitAndBranchSuggestion,
326 ) =>
327 Effect.gen(function* () {
328 const suggestion =
329 preResolvedSuggestion ??
330 (yield* resolveCommitAndBranchSuggestion({
331 cwd,
332 branch,
333 ...(commitMessage ? { commitMessage } : {}),
334 }));
335 if (!suggestion) {
336 return { status: "skipped_no_changes" as const };
337 }
338
339 const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
340 return {
341 status: "created" as const,
342 commitSha,
343 subject: suggestion.subject,
344 };
345 });
346
347 const runPrStep = (cwd: string, fallbackBranch: string | null) =>
348 Effect.gen(function* () {
349 const details = yield* gitCore.statusDetails(cwd);
350 const branch = details.branch ?? fallbackBranch;
351 if (!branch) {
352 return yield* gitManagerError(
353 "runPrStep",
354 "Cannot create a pull request from detached HEAD.",
355 );
356 }
357 if (!details.hasUpstream) {
358 return yield* gitManagerError(
359 "runPrStep",
360 "Current branch has not been pushed. Push before creating a PR.",
361 );
362 }
363
364 const existing = yield* findOpenPr(cwd, branch);
365 if (existing) {
366 return {
367 status: "opened_existing" as const,
368 url: existing.url,
369 number: existing.number,
370 baseBranch: existing.baseRefName,
371 headBranch: existing.headRefName,
372 title: existing.title,
373 };
374 }
375
376 const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef);
377 const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
378
379 const generated = yield* textGeneration.generatePrContent({
380 cwd,
381 baseBranch,
382 headBranch: branch,
383 commitSummary: limitContext(rangeContext.commitSummary, 20_000),
384 diffSummary: limitContext(rangeContext.diffSummary, 20_000),
385 diffPatch: limitContext(rangeContext.diffPatch, 60_000),
386 });
387
388 const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
389 yield* fileSystem
390 .writeFileString(bodyFile, generated.body)
391 .pipe(
392 Effect.mapError((cause) =>
393 gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause),
394 ),
395 );
396 yield* gitHubCli
397 .createPullRequest({
398 cwd,
399 baseBranch,
400 headBranch: branch,
401 title: generated.title,
402 bodyFile,
403 })
404 .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));
405
406 const created = yield* findOpenPr(cwd, branch);
407 if (!created) {
408 return {
409 status: "created" as const,
410 baseBranch,
411 headBranch: branch,
412 title: generated.title,
413 };
414 }
415
416 return {
417 status: "created" as const,
418 url: created.url,
419 number: created.number,
420 baseBranch: created.baseRefName,
421 headBranch: created.headRefName,
422 title: created.title,
423 };
424 });
425
426 const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
427 const details = yield* gitCore.statusDetails(input.cwd);
428
429 const pr =
430 details.branch !== null
431 ? yield* findLatestPr(input.cwd, details.branch).pipe(
432 Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
433 Effect.catch(() => Effect.succeed(null)),
434 )
435 : null;
436
437 return {
438 branch: details.branch,
439 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
440 workingTree: details.workingTree,
441 hasUpstream: details.hasUpstream,
442 aheadCount: details.aheadCount,
443 behindCount: details.behindCount,
444 pr,
445 };
446 });
447
448 const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
449 Effect.gen(function* () {
450 const suggestion = yield* resolveCommitAndBranchSuggestion({
451 cwd,
452 branch,
453 ...(commitMessage ? { commitMessage } : {}),
454 includeBranch: true,
455 });
456 if (!suggestion) {
457 return yield* gitManagerError(
458 "runFeatureBranchStep",
459 "Cannot create a feature branch because there are no changes to commit.",
460 );
461 }
462
463 const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
464 const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
465 const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
466
467 yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
468 yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
469
470 return {
471 branchStep: { status: "created" as const, name: resolvedBranch },
472 resolvedCommitMessage: suggestion.commitMessage,
473 resolvedCommitSuggestion: suggestion,
474 };
475 });
476
477 const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
478 function* (input) {
479 const wantsPush = input.action !== "commit";
480 const wantsPr = input.action === "commit_push_pr";
481
482 const initialStatus = yield* gitCore.statusDetails(input.cwd);
483 if (!input.featureBranch && wantsPush && !initialStatus.branch) {
484 return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
485 }
486 if (!input.featureBranch && wantsPr && !initialStatus.branch) {
487 return yield* gitManagerError(
488 "runStackedAction",
489 "Cannot create a pull request from detached HEAD.",
490 );
491 }
492
493 let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
494 let commitMessageForStep = input.commitMessage;
495 let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
496
497 if (input.featureBranch) {
498 const result = yield* runFeatureBranchStep(
499 input.cwd,
500 initialStatus.branch,
501 input.commitMessage,
502 );
503 branchStep = result.branchStep;
504 commitMessageForStep = result.resolvedCommitMessage;
505 preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
506 } else {
507 branchStep = { status: "skipped_not_requested" as const };
508 }
509
510 const currentBranch = branchStep.name ?? initialStatus.branch;
511
512 const commit = yield* runCommitStep(
513 input.cwd,
514 currentBranch,
515 commitMessageForStep,
516 preResolvedCommitSuggestion,
517 );
518
519 const push = wantsPush
520 ? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
521 : { status: "skipped_not_requested" as const };
522
523 const pr = wantsPr
524 ? yield* runPrStep(input.cwd, currentBranch)
525 : { status: "skipped_not_requested" as const };
526
527 return {
528 action: input.action,
529 branch: branchStep,
530 commit,
531 push,
532 pr,
533 };
534 },
535 );
536
537 return {
538 status,
539 runStackedAction,
540 } satisfies GitManagerShape;
541});
542
543export const GitManagerLive = Layer.effect(GitManager, makeGitManager);