Open History to see the last commit
1import fs from "node:fs";
2import os from "node:os";
3import path from "node:path";
4
5import {
6 gitPullInputSchema,
7 gitPullResultSchema,
8 gitStatusInputSchema,
9 gitStatusResultSchema,
10 type GitCheckoutInput,
11 type GitCreateBranchInput,
12 type GitCreateWorktreeInput,
13 type GitCreateWorktreeResult,
14 type GitInitInput,
15 type GitListBranchesInput,
16 type GitListBranchesResult,
17 type GitPullInput,
18 type GitPullResult,
19 type GitRemoveWorktreeInput,
20 type GitStatusInput,
21 type GitStatusResult,
22} from "@t3tools/contracts";
23import { type ProcessRunResult, runProcess } from "./processRunner";
24
25export interface TerminalCommandInput {
26 command: string;
27 cwd: string;
28 timeoutMs?: number;
29 maxOutputBytes?: number;
30}
31
32export type TerminalCommandResult = ProcessRunResult;
33
34export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
35 upstreamRef: string | null;
36}
37
38export interface GitPreparedCommitContext {
39 stagedSummary: string;
40 stagedPatch: string;
41}
42
43export interface GitPushResult {
44 status: "pushed" | "skipped_up_to_date";
45 branch: string;
46 upstreamBranch?: string | undefined;
47 setUpstream?: boolean | undefined;
48}
49
50export interface GitRangeContext {
51 commitSummary: string;
52 diffSummary: string;
53 diffPatch: string;
54}
55
56interface RunGitOptions {
57 timeoutMs?: number | undefined;
58 allowNonZeroExit?: boolean | undefined;
59}
60
61interface ExecuteGitOptions {
62 timeoutMs?: number | undefined;
63 allowNonZeroExit?: boolean | undefined;
64 fallbackErrorMessage?: string | undefined;
65}
66
67const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
68const STATUS_UPSTREAM_REFRESH_INTERVAL_MS = 15_000;
69const STATUS_UPSTREAM_REFRESH_TIMEOUT_MS = 5_000;
70
71/** Spawn git directly with an argv array — no shell, no quoting needed. */
72function runGit(
73 args: readonly string[],
74 cwd: string,
75 timeoutMs = 30_000,
76): Promise<ProcessRunResult> {
77 return runProcess("git", args, {
78 cwd,
79 timeoutMs,
80 allowNonZeroExit: true,
81 maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
82 outputMode: "truncate",
83 });
84}
85
86function trimStdout(value: string): string {
87 return value.trim();
88}
89
90function parseBranchAb(value: string): { ahead: number; behind: number } {
91 const match = value.match(/^\+(\d+)\s+-(\d+)$/);
92 if (!match) return { ahead: 0, behind: 0 };
93 return {
94 ahead: Number(match[1] ?? "0"),
95 behind: Number(match[2] ?? "0"),
96 };
97}
98
99function parseNumstatEntries(
100 stdout: string,
101): Array<{ path: string; insertions: number; deletions: number }> {
102 const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
103 for (const line of stdout.split(/\r?\n/g)) {
104 if (line.trim().length === 0) continue;
105 const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
106 const rawPath =
107 pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
108 if (rawPath.length === 0) continue;
109 const added = Number.parseInt(addedRaw ?? "0", 10);
110 const deleted = Number.parseInt(deletedRaw ?? "0", 10);
111 const renameArrowIndex = rawPath.indexOf(" => ");
112 const normalizedPath =
113 renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
114 entries.push({
115 path: normalizedPath.length > 0 ? normalizedPath : rawPath,
116 insertions: Number.isFinite(added) ? added : 0,
117 deletions: Number.isFinite(deleted) ? deleted : 0,
118 });
119 }
120 return entries;
121}
122
123function parsePorcelainPath(line: string): string | null {
124 if (line.startsWith("? ") || line.startsWith("! ")) {
125 const simple = line.slice(2).trim();
126 return simple.length > 0 ? simple : null;
127 }
128
129 if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
130 return null;
131 }
132
133 const tabIndex = line.indexOf("\t");
134 if (tabIndex >= 0) {
135 const fromTab = line.slice(tabIndex + 1);
136 const [path] = fromTab.split("\t");
137 return path?.trim().length ? path.trim() : null;
138 }
139
140 const parts = line.trim().split(/\s+/g);
141 const path = parts.at(-1) ?? "";
142 return path.length > 0 ? path : null;
143}
144
145function commandLabel(args: readonly string[]): string {
146 return `git ${args.join(" ")}`;
147}
148
149function normalizeGitSpawnError(cwd: string, error: unknown): Error {
150 if (!(error instanceof Error)) {
151 return new Error("Failed to run git command.");
152 }
153 if (!fs.existsSync(cwd)) {
154 return new Error(`Working directory does not exist: ${cwd}`);
155 }
156 if (error.message.includes("Command not found: git")) {
157 return new Error("Git is required but not available on PATH.");
158 }
159 return new Error(`Failed to run git command: ${error.message}`);
160}
161
162function normalizeGitExecutionError(args: readonly string[], result: TerminalCommandResult): Error {
163 const stderr = result.stderr.trim();
164 if (stderr.toLowerCase().includes("not a git repository")) {
165 return new Error("Current folder is not a git repository.");
166 }
167 if (result.timedOut) {
168 return new Error(`${commandLabel(args)} timed out.`);
169 }
170 const detail =
171 stderr.length > 0 ? stderr : `code=${result.code ?? "null"}, signal=${result.signal ?? "null"}`;
172 return new Error(`${commandLabel(args)} failed: ${detail}`);
173}
174
175async function runGitOrThrow(
176 cwd: string,
177 args: readonly string[],
178 options: RunGitOptions = {},
179): Promise<TerminalCommandResult> {
180 let result: TerminalCommandResult;
181 try {
182 result = await runGit(args, cwd, options.timeoutMs);
183 } catch (error) {
184 throw normalizeGitSpawnError(cwd, error);
185 }
186
187 if (result.timedOut) {
188 throw normalizeGitExecutionError(args, result);
189 }
190 if (!options.allowNonZeroExit && result.code !== 0) {
191 throw normalizeGitExecutionError(args, result);
192 }
193 return result;
194}
195
196async function executeGit(
197 cwd: string,
198 args: readonly string[],
199 options: ExecuteGitOptions = {},
200): Promise<TerminalCommandResult> {
201 const result = await runGitOrThrow(cwd, args, {
202 timeoutMs: options.timeoutMs,
203 allowNonZeroExit: true,
204 });
205
206 if (options.allowNonZeroExit || result.code === 0) {
207 return result;
208 }
209
210 const stderr = result.stderr.trim();
211 if (stderr.length > 0) {
212 throw new Error(stderr);
213 }
214 if (options.fallbackErrorMessage) {
215 throw new Error(options.fallbackErrorMessage);
216 }
217 throw normalizeGitExecutionError(args, result);
218}
219
220export class GitCoreService {
221 private readonly lastUpstreamRefreshAt = new Map<string, number>();
222
223 async status(raw: GitStatusInput): Promise<GitStatusResult> {
224 const input = gitStatusInputSchema.parse(raw);
225 const details = await this.statusDetails(input.cwd);
226 return gitStatusResultSchema.parse({
227 branch: details.branch,
228 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
229 workingTree: details.workingTree,
230 hasUpstream: details.hasUpstream,
231 aheadCount: details.aheadCount,
232 behindCount: details.behindCount,
233 openPr: null,
234 });
235 }
236
237 async statusDetails(cwd: string): Promise<GitStatusDetails> {
238 await this.refreshStatusUpstreamIfStale(cwd).catch(() => undefined);
239
240 const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
241 this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
242 this.gitStdout(cwd, ["diff", "--numstat"]),
243 this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
244 ]);
245
246 let branch: string | null = null;
247 let upstreamRef: string | null = null;
248 let aheadCount = 0;
249 let behindCount = 0;
250 let hasWorkingTreeChanges = false;
251 const changedFilesWithoutNumstat = new Set<string>();
252
253 for (const line of statusStdout.split(/\r?\n/g)) {
254 if (line.startsWith("# branch.head ")) {
255 const value = line.slice("# branch.head ".length).trim();
256 branch = value.startsWith("(") ? null : value;
257 continue;
258 }
259 if (line.startsWith("# branch.upstream ")) {
260 const value = line.slice("# branch.upstream ".length).trim();
261 upstreamRef = value.length > 0 ? value : null;
262 continue;
263 }
264 if (line.startsWith("# branch.ab ")) {
265 const value = line.slice("# branch.ab ".length).trim();
266 const parsed = parseBranchAb(value);
267 aheadCount = parsed.ahead;
268 behindCount = parsed.behind;
269 continue;
270 }
271 if (line.trim().length > 0 && !line.startsWith("#")) {
272 hasWorkingTreeChanges = true;
273 const pathValue = parsePorcelainPath(line);
274 if (pathValue) changedFilesWithoutNumstat.add(pathValue);
275 }
276 }
277 const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
278 const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
279 const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
280 for (const entry of [...stagedEntries, ...unstagedEntries]) {
281 const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
282 existing.insertions += entry.insertions;
283 existing.deletions += entry.deletions;
284 fileStatMap.set(entry.path, existing);
285 }
286
287 let insertions = 0;
288 let deletions = 0;
289 const files = Array.from(fileStatMap.entries())
290 .map(([path, stat]) => {
291 insertions += stat.insertions;
292 deletions += stat.deletions;
293 return { path, insertions: stat.insertions, deletions: stat.deletions };
294 })
295 .toSorted((a, b) => a.path.localeCompare(b.path));
296
297 for (const filePath of changedFilesWithoutNumstat) {
298 if (fileStatMap.has(filePath)) continue;
299 files.push({ path: filePath, insertions: 0, deletions: 0 });
300 }
301 files.sort((a, b) => a.path.localeCompare(b.path));
302
303 return {
304 branch,
305 upstreamRef,
306 hasWorkingTreeChanges,
307 workingTree: {
308 files,
309 insertions,
310 deletions,
311 },
312 hasUpstream: upstreamRef !== null,
313 aheadCount,
314 behindCount,
315 };
316 }
317
318 async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
319 await this.git(cwd, ["add", "-A"]);
320
321 const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
322 if (trimStdout(stagedSummary).length === 0) {
323 return null;
324 }
325
326 const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);
327
328 return {
329 stagedSummary,
330 stagedPatch,
331 };
332 }
333
334 async commit(cwd: string, subject: string, body: string): Promise<{ commitSha: string }> {
335 const args = ["commit", "-m", subject];
336 const trimmedBody = body.trim();
337 if (trimmedBody.length > 0) {
338 args.push("-m", trimmedBody);
339 }
340 await this.git(cwd, args);
341 const commitSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"]));
342 return { commitSha };
343 }
344
345 async pushCurrentBranch(cwd: string, fallbackBranch: string | null): Promise<GitPushResult> {
346 const details = await this.statusDetails(cwd);
347 const branch = details.branch ?? fallbackBranch;
348 if (!branch) {
349 throw new Error("Cannot push from detached HEAD.");
350 }
351
352 if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
353 return {
354 status: "skipped_up_to_date",
355 branch,
356 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
357 };
358 }
359
360 if (!details.hasUpstream) {
361 await this.git(cwd, ["push", "-u", "origin", branch]);
362 return {
363 status: "pushed",
364 branch,
365 upstreamBranch: `origin/${branch}`,
366 setUpstream: true,
367 };
368 }
369
370 await this.git(cwd, ["push"]);
371 return {
372 status: "pushed",
373 branch,
374 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
375 setUpstream: false,
376 };
377 }
378
379 async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
380 const details = await this.statusDetails(cwd);
381 const branch = details.branch;
382 if (!branch) {
383 throw new Error("Cannot pull from detached HEAD.");
384 }
385 if (!details.hasUpstream) {
386 throw new Error("Current branch has no upstream configured. Push with upstream first.");
387 }
388 const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
389 await executeGit(cwd, ["pull", "--ff-only"], {
390 timeoutMs: 30_000,
391 fallbackErrorMessage: "git pull failed",
392 });
393 const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
394 const refreshed = await this.statusDetails(cwd);
395 return gitPullResultSchema.parse({
396 status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
397 branch,
398 ...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
399 });
400 }
401
402 async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
403 const range = `${baseBranch}..HEAD`;
404 const [commitSummary, diffSummary, diffPatch] = await Promise.all([
405 this.gitStdout(cwd, ["log", "--oneline", range]),
406 this.gitStdout(cwd, ["diff", "--stat", range]),
407 this.gitStdout(cwd, ["diff", "--patch", "--minimal", range]),
408 ]);
409
410 return {
411 commitSummary,
412 diffSummary,
413 diffPatch,
414 };
415 }
416
417 async readConfigValue(cwd: string, key: string): Promise<string | null> {
418 const stdout = await this.gitStdout(cwd, ["config", "--get", key], true);
419 const value = trimStdout(stdout);
420 return value.length > 0 ? value : null;
421 }
422
423 private async readBranchRecency(cwd: string): Promise<Map<string, number>> {
424 const branchRecency = await executeGit(
425 cwd,
426 ["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
427 {
428 timeoutMs: 15_000,
429 allowNonZeroExit: true,
430 },
431 );
432
433 const branchLastCommit = new Map<string, number>();
434 if (branchRecency.code !== 0) {
435 return branchLastCommit;
436 }
437
438 for (const line of branchRecency.stdout.split("\n")) {
439 if (line.length === 0) {
440 continue;
441 }
442 const [name, lastCommitRaw] = line.split("\t");
443 if (!name) {
444 continue;
445 }
446 const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
447 branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
448 }
449
450 return branchLastCommit;
451 }
452
453 async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
454 const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
455 () => new Map<string, number>(),
456 );
457 const result = await executeGit(input.cwd, ["branch", "--no-color"], {
458 timeoutMs: 10_000,
459 allowNonZeroExit: true,
460 });
461
462 if (result.code !== 0) {
463 const stderr = result.stderr.trim();
464 if (stderr.toLowerCase().includes("not a git repository")) {
465 return { branches: [], isRepo: false };
466 }
467 throw new Error(stderr || "git branch failed");
468 }
469
470 const [defaultRef, worktreeList, branchLastCommit] = await Promise.all([
471 executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
472 timeoutMs: 5_000,
473 allowNonZeroExit: true,
474 }),
475 executeGit(input.cwd, ["worktree", "list", "--porcelain"], {
476 timeoutMs: 5_000,
477 allowNonZeroExit: true,
478 }),
479 branchRecencyPromise,
480 ]);
481 const defaultBranch =
482 defaultRef.code === 0
483 ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
484 : null;
485
486 const worktreeMap = new Map<string, string>();
487 if (worktreeList.code === 0) {
488 let currentPath: string | null = null;
489 for (const line of worktreeList.stdout.split("\n")) {
490 if (line.startsWith("worktree ")) {
491 const candidatePath = line.slice("worktree ".length);
492 currentPath = fs.existsSync(candidatePath) ? candidatePath : null;
493 } else if (line.startsWith("branch refs/heads/") && currentPath) {
494 worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
495 } else if (line === "") {
496 currentPath = null;
497 }
498 }
499 }
500
501 const branches = result.stdout
502 .split("\n")
503 .map((line) => line.trim())
504 .filter((line) => line.length > 0)
505 .map((line) => {
506 const name = line.replace(/^[*+]\s+/, "");
507 return {
508 name,
509 current: line.startsWith("* "),
510 isDefault: name === defaultBranch,
511 worktreePath: worktreeMap.get(name) ?? null,
512 };
513 })
514 .toSorted((a, b) => {
515 const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
516 const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
517 if (aPriority !== bPriority) return aPriority - bPriority;
518
519 const aLastCommit = branchLastCommit.get(a.name) ?? 0;
520 const bLastCommit = branchLastCommit.get(b.name) ?? 0;
521 if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
522 return a.name.localeCompare(b.name);
523 });
524
525 return { branches, isRepo: true };
526 }
527
528 async createWorktree(input: GitCreateWorktreeInput): Promise<GitCreateWorktreeResult> {
529 const sanitizedBranch = input.newBranch.replace(/\//g, "-");
530 const repoName = path.basename(input.cwd);
531 const worktreePath =
532 input.path ?? path.join(os.homedir(), ".t3", "worktrees", repoName, sanitizedBranch);
533
534 await executeGit(
535 input.cwd,
536 ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
537 { fallbackErrorMessage: "git worktree add failed" },
538 );
539
540 return {
541 worktree: {
542 path: worktreePath,
543 branch: input.newBranch,
544 },
545 };
546 }
547
548 async removeWorktree(input: GitRemoveWorktreeInput): Promise<void> {
549 await executeGit(input.cwd, ["worktree", "remove", input.path], {
550 timeoutMs: 15_000,
551 fallbackErrorMessage: "git worktree remove failed",
552 });
553 }
554
555 async createBranch(input: GitCreateBranchInput): Promise<void> {
556 await executeGit(input.cwd, ["branch", input.branch], {
557 timeoutMs: 10_000,
558 fallbackErrorMessage: "git branch create failed",
559 });
560 }
561
562 private async resolveCurrentUpstream(
563 cwd: string,
564 ): Promise<{ upstreamRef: string; remoteName: string; upstreamBranch: string } | null> {
565 const upstreamRef = trimStdout(
566 await this.gitStdout(
567 cwd,
568 ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
569 true,
570 ),
571 );
572 if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
573 return null;
574 }
575
576 const separatorIndex = upstreamRef.indexOf("/");
577 if (separatorIndex <= 0) {
578 return null;
579 }
580 const remoteName = upstreamRef.slice(0, separatorIndex);
581 const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
582 if (remoteName.length === 0) {
583 return null;
584 }
585 if (upstreamBranch.length === 0) {
586 return null;
587 }
588
589 return {
590 upstreamRef,
591 remoteName,
592 upstreamBranch,
593 };
594 }
595
596 private async fetchUpstreamRef(
597 cwd: string,
598 upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
599 ): Promise<void> {
600 const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
601 await this.git(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], true);
602 }
603
604 private async fetchUpstreamRefForStatus(
605 cwd: string,
606 upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
607 ): Promise<void> {
608 const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
609 await executeGit(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], {
610 allowNonZeroExit: true,
611 timeoutMs: STATUS_UPSTREAM_REFRESH_TIMEOUT_MS,
612 });
613 }
614
615 private async refreshStatusUpstreamIfStale(cwd: string): Promise<void> {
616 const upstream = await this.resolveCurrentUpstream(cwd);
617 if (!upstream) {
618 return;
619 }
620
621 const cacheKey = `${cwd}\u0000${upstream.upstreamRef}`;
622 const now = Date.now();
623 const lastRefreshAt = this.lastUpstreamRefreshAt.get(cacheKey) ?? 0;
624 if (now - lastRefreshAt < STATUS_UPSTREAM_REFRESH_INTERVAL_MS) {
625 return;
626 }
627
628 // Record attempt time first to avoid repeated fetch spikes when status is polled often.
629 this.lastUpstreamRefreshAt.set(cacheKey, now);
630 await this.fetchUpstreamRefForStatus(cwd, upstream);
631 }
632
633 private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
634 const upstream = await this.resolveCurrentUpstream(cwd);
635 if (!upstream) {
636 return;
637 }
638 await this.fetchUpstreamRef(cwd, upstream);
639 }
640
641 async checkoutBranch(input: GitCheckoutInput): Promise<void> {
642 await executeGit(input.cwd, ["checkout", input.branch], {
643 timeoutMs: 10_000,
644 fallbackErrorMessage: "git checkout failed",
645 });
646 // Refresh upstream refs in the background so checkout remains responsive.
647 void this.refreshCheckedOutBranchUpstream(input.cwd).catch(() => undefined);
648 }
649
650 async initRepo(input: GitInitInput): Promise<void> {
651 await executeGit(input.cwd, ["init"], {
652 timeoutMs: 10_000,
653 fallbackErrorMessage: "git init failed",
654 });
655 }
656
657 async git(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<void> {
658 await executeGit(cwd, args, { allowNonZeroExit });
659 }
660
661 async gitStdout(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<string> {
662 const result = await executeGit(cwd, args, { allowNonZeroExit });
663 return result.stdout;
664 }
665}
666
667const defaultGitCoreService = new GitCoreService();
668
669export async function runTerminalCommand(
670 input: TerminalCommandInput,
671): Promise<TerminalCommandResult> {
672 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
673 const shellPath =
674 process.platform === "win32"
675 ? (process.env.ComSpec ?? "cmd.exe")
676 : (process.env.SHELL ?? "/bin/sh");
677
678 const args =
679 process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
680
681 const result = await runProcess(shellPath, args, {
682 cwd: input.cwd,
683 timeoutMs: input.timeoutMs ?? 30_000,
684 allowNonZeroExit: true,
685 maxBufferBytes: maxOutputBytes,
686 outputMode: "truncate",
687 });
688
689 if (!result.stdoutTruncated && !result.stderrTruncated) {
690 return result;
691 }
692
693 return {
694 ...result,
695 stderr: `${result.stderr}\n[output truncated at ${maxOutputBytes} bytes]`,
696 };
697}
698
699export async function listGitBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
700 return defaultGitCoreService.listBranches(input);
701}
702
703export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
704 const input = gitPullInputSchema.parse(raw);
705 return defaultGitCoreService.pullCurrentBranch(input.cwd);
706}
707
708export async function createGitWorktree(
709 input: GitCreateWorktreeInput,
710): Promise<GitCreateWorktreeResult> {
711 return defaultGitCoreService.createWorktree(input);
712}
713
714export async function removeGitWorktree(input: GitRemoveWorktreeInput): Promise<void> {
715 await defaultGitCoreService.removeWorktree(input);
716}
717
718export async function createGitBranch(input: GitCreateBranchInput): Promise<void> {
719 await defaultGitCoreService.createBranch(input);
720}
721
722export async function checkoutGitBranch(input: GitCheckoutInput): Promise<void> {
723 await defaultGitCoreService.checkoutBranch(input);
724}
725
726export async function initGitRepo(input: GitInitInput): Promise<void> {
727 await defaultGitCoreService.initRepo(input);
728}