Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
Merge origin/main into codething/4efb5794
Julius Marmingee8dfc42f4446
diff --cc apps/server/src/git/Layers/GitCore.tsindex 000000000,fdbf3c8bc..b5fb6b507mode 000000,100644..100644--- a/apps/server/src/git/Layers/GitCore.ts+++ b/apps/server/src/git/Layers/GitCore.ts@@@ -1,0 -1,759 +1,759 @@@+ import { Cache, Data, Duration, Effect, Exit, FileSystem, Layer, Path } from "effect";++ import { GitCommandError } from "../Errors.ts";+ import { GitService } from "../Services/GitService.ts";+ import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";++ const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);+ const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);+ const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;++ class StatusUpstreamRefreshCacheKey extends Data.Class<{+ cwd: string;+ upstreamRef: string;+ remoteName: string;+ upstreamBranch: string;+ }> {}++ interface ExecuteGitOptions {+ timeoutMs?: number | undefined;+ allowNonZeroExit?: boolean | undefined;+ fallbackErrorMessage?: string | undefined;+ }++ function parseBranchAb(value: string): { ahead: number; behind: number } {+ const match = value.match(/^\+(\d+)\s+-(\d+)$/);+ if (!match) return { ahead: 0, behind: 0 };+ return {+ ahead: Number(match[1] ?? "0"),+ behind: Number(match[2] ?? "0"),+ };+ }++ function parseNumstatEntries(+ stdout: string,+ ): Array<{ path: string; insertions: number; deletions: number }> {+ const entries: Array<{ path: string; insertions: number; deletions: number }> = [];+ for (const line of stdout.split(/\r?\n/g)) {+ if (line.trim().length === 0) continue;+ const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");+ const rawPath =+ pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();+ if (rawPath.length === 0) continue;+ const added = Number.parseInt(addedRaw ?? "0", 10);+ const deleted = Number.parseInt(deletedRaw ?? "0", 10);+ const renameArrowIndex = rawPath.indexOf(" => ");+ const normalizedPath =+ renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;+ entries.push({+ path: normalizedPath.length > 0 ? normalizedPath : rawPath,+ insertions: Number.isFinite(added) ? added : 0,+ deletions: Number.isFinite(deleted) ? deleted : 0,+ });+ }+ return entries;+ }++ function parsePorcelainPath(line: string): string | null {+ if (line.startsWith("? ") || line.startsWith("! ")) {+ const simple = line.slice(2).trim();+ return simple.length > 0 ? simple : null;+ }++ if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {+ return null;+ }++ const tabIndex = line.indexOf("\t");+ if (tabIndex >= 0) {+ const fromTab = line.slice(tabIndex + 1);+ const [filePath] = fromTab.split("\t");+ return filePath?.trim().length ? filePath.trim() : null;+ }++ const parts = line.trim().split(/\s+/g);+ const filePath = parts.at(-1) ?? "";+ return filePath.length > 0 ? filePath : null;+ }++ function commandLabel(args: readonly string[]): string {+ return `git ${args.join(" ")}`;+ }++ function createGitCommandError(+ operation: string,+ cwd: string,+ args: readonly string[],+ detail: string,+ cause?: unknown,+ ): GitCommandError {+ return new GitCommandError({+ operation,+ command: commandLabel(args),+ cwd,+ detail,+ ...(cause !== undefined ? { cause } : {}),+ });+ }++ const makeGitCore = Effect.gen(function* () {+ const git = yield* GitService;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;++ const executeGit = (+ operation: string,+ cwd: string,+ args: readonly string[],+ options: ExecuteGitOptions = {},+ ): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> =>+ git+ .execute({+ operation,+ cwd,+ args,+ allowNonZeroExit: true,+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),+ })+ .pipe(+ Effect.flatMap((result) => {+ if (options.allowNonZeroExit || result.code === 0) {+ return Effect.succeed(result);+ }+ const stderr = result.stderr.trim();+ if (stderr.length > 0) {+ return Effect.fail(createGitCommandError(operation, cwd, args, stderr));+ }+ if (options.fallbackErrorMessage) {+ return Effect.fail(+ createGitCommandError(operation, cwd, args, options.fallbackErrorMessage),+ );+ }+ return Effect.fail(+ createGitCommandError(+ operation,+ cwd,+ args,+ `${commandLabel(args)} failed: code=${result.code ?? "null"}`,+ ),+ );+ }),+ );++ const runGit = (+ operation: string,+ cwd: string,+ args: readonly string[],+ allowNonZeroExit = false,+ ): Effect.Effect<void, GitCommandError> =>+ executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid);++ const runGitStdout = (+ operation: string,+ cwd: string,+ args: readonly string[],+ allowNonZeroExit = false,+ ): Effect.Effect<string, GitCommandError> =>+ executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(+ Effect.map((result) => result.stdout),+ );++ const resolveCurrentUpstream = (+ cwd: string,+ ): Effect.Effect<+ { upstreamRef: string; remoteName: string; upstreamBranch: string } | null,+ GitCommandError+ > =>+ Effect.gen(function* () {+ const upstreamRef = yield* runGitStdout(+ "GitCore.resolveCurrentUpstream",+ cwd,+ ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],+ true,+ ).pipe(Effect.map((stdout) => stdout.trim()));++ if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {+ return null;+ }++ const separatorIndex = upstreamRef.indexOf("/");+ if (separatorIndex <= 0) {+ return null;+ }+ const remoteName = upstreamRef.slice(0, separatorIndex);+ const upstreamBranch = upstreamRef.slice(separatorIndex + 1);+ if (remoteName.length === 0 || upstreamBranch.length === 0) {+ return null;+ }++ return {+ upstreamRef,+ remoteName,+ upstreamBranch,+ };+ });++ const fetchUpstreamRef = (+ cwd: string,+ upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },+ ): Effect.Effect<void, GitCommandError> => {+ const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;+ return runGit(+ "GitCore.fetchUpstreamRef",+ cwd,+ ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],+ true,+ );+ };++ const fetchUpstreamRefForStatus = (+ cwd: string,+ upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },+ ): Effect.Effect<void, GitCommandError> => {+ const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;+ return executeGit(+ "GitCore.fetchUpstreamRefForStatus",+ cwd,+ ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],+ {+ allowNonZeroExit: true,+ timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),+ },+ ).pipe(Effect.asVoid);+ };++ const statusUpstreamRefreshCache = yield* Cache.makeWith({+ capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,+ lookup: (cacheKey: StatusUpstreamRefreshCacheKey) =>+ Effect.gen(function* () {+ yield* fetchUpstreamRefForStatus(cacheKey.cwd, {+ upstreamRef: cacheKey.upstreamRef,+ remoteName: cacheKey.remoteName,+ upstreamBranch: cacheKey.upstreamBranch,+ });+ return true as const;+ }),+ // Keep successful refreshes warm; drop failures immediately so next request can retry.+ timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero),+ });++ const refreshStatusUpstreamIfStale = (cwd: string): Effect.Effect<void, GitCommandError> =>+ Effect.gen(function* () {+ const upstream = yield* resolveCurrentUpstream(cwd);+ if (!upstream) return;+ yield* Cache.get(+ statusUpstreamRefreshCache,+ new StatusUpstreamRefreshCacheKey({+ cwd,+ upstreamRef: upstream.upstreamRef,+ remoteName: upstream.remoteName,+ upstreamBranch: upstream.upstreamBranch,+ }),+ );+ });++ const refreshCheckedOutBranchUpstream = (cwd: string): Effect.Effect<void, GitCommandError> =>+ Effect.gen(function* () {+ const upstream = yield* resolveCurrentUpstream(cwd);+ if (!upstream) return;+ yield* fetchUpstreamRef(cwd, upstream);+ });++ const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>+ Effect.gen(function* () {+ const branchRecency = yield* executeGit(+ "GitCore.readBranchRecency",+ cwd,+ ["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],+ {+ timeoutMs: 15_000,+ allowNonZeroExit: true,+ },+ );++ const branchLastCommit = new Map<string, number>();+ if (branchRecency.code !== 0) {+ return branchLastCommit;+ }++ for (const line of branchRecency.stdout.split("\n")) {+ if (line.length === 0) {+ continue;+ }+ const [name, lastCommitRaw] = line.split("\t");+ if (!name) {+ continue;+ }+ const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);+ branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);+ }++ return branchLastCommit;+ });++ const statusDetails: GitCoreShape["statusDetails"] = (cwd) =>+ Effect.gen(function* () {+ yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.catch(() => Effect.void));++ const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(+ [+ runGitStdout("GitCore.statusDetails.status", cwd, [+ "status",+ "--porcelain=2",+ "--branch",+ ]),+ runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),+ runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [+ "diff",+ "--cached",+ "--numstat",+ ]),+ ],+ { concurrency: "unbounded" },+ );++ let branch: string | null = null;+ let upstreamRef: string | null = null;+ let aheadCount = 0;+ let behindCount = 0;+ let hasWorkingTreeChanges = false;+ const changedFilesWithoutNumstat = new Set<string>();++ for (const line of statusStdout.split(/\r?\n/g)) {+ if (line.startsWith("# branch.head ")) {+ const value = line.slice("# branch.head ".length).trim();+ branch = value.startsWith("(") ? null : value;+ continue;+ }+ if (line.startsWith("# branch.upstream ")) {+ const value = line.slice("# branch.upstream ".length).trim();+ upstreamRef = value.length > 0 ? value : null;+ continue;+ }+ if (line.startsWith("# branch.ab ")) {+ const value = line.slice("# branch.ab ".length).trim();+ const parsed = parseBranchAb(value);+ aheadCount = parsed.ahead;+ behindCount = parsed.behind;+ continue;+ }+ if (line.trim().length > 0 && !line.startsWith("#")) {+ hasWorkingTreeChanges = true;+ const pathValue = parsePorcelainPath(line);+ if (pathValue) changedFilesWithoutNumstat.add(pathValue);+ }+ }+ const stagedEntries = parseNumstatEntries(stagedNumstatStdout);+ const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);+ const fileStatMap = new Map<string, { insertions: number; deletions: number }>();+ for (const entry of [...stagedEntries, ...unstagedEntries]) {+ const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };+ existing.insertions += entry.insertions;+ existing.deletions += entry.deletions;+ fileStatMap.set(entry.path, existing);+ }++ let insertions = 0;+ let deletions = 0;+ const files = Array.from(fileStatMap.entries())+ .map(([filePath, stat]) => {+ insertions += stat.insertions;+ deletions += stat.deletions;+ return { path: filePath, insertions: stat.insertions, deletions: stat.deletions };+ })+ .toSorted((a, b) => a.path.localeCompare(b.path));++ for (const filePath of changedFilesWithoutNumstat) {+ if (fileStatMap.has(filePath)) continue;+ files.push({ path: filePath, insertions: 0, deletions: 0 });+ }+ files.sort((a, b) => a.path.localeCompare(b.path));++ return {+ branch,+ upstreamRef,+ hasWorkingTreeChanges,+ workingTree: {+ files,+ insertions,+ deletions,+ },+ hasUpstream: upstreamRef !== null,+ aheadCount,+ behindCount,+ };+ });++ const status: GitCoreShape["status"] = (input) =>+ statusDetails(input.cwd).pipe(+ Effect.map((details) => ({+ branch: details.branch,+ hasWorkingTreeChanges: details.hasWorkingTreeChanges,+ workingTree: details.workingTree,+ hasUpstream: details.hasUpstream,+ aheadCount: details.aheadCount,+ behindCount: details.behindCount,- openPr: null,++ pr: null,+ })),+ );++ const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd) =>+ Effect.gen(function* () {+ yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);++ const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [+ "diff",+ "--cached",+ "--name-status",+ ]).pipe(Effect.map((stdout) => stdout.trim()));+ if (stagedSummary.length === 0) {+ return null;+ }++ const stagedPatch = yield* runGitStdout("GitCore.prepareCommitContext.stagedPatch", cwd, [+ "diff",+ "--cached",+ "--patch",+ "--minimal",+ ]);++ return {+ stagedSummary,+ stagedPatch,+ };+ });++ const commit: GitCoreShape["commit"] = (cwd, subject, body) =>+ Effect.gen(function* () {+ const args = ["commit", "-m", subject];+ const trimmedBody = body.trim();+ if (trimmedBody.length > 0) {+ args.push("-m", trimmedBody);+ }+ yield* runGit("GitCore.commit.commit", cwd, args);+ const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [+ "rev-parse",+ "HEAD",+ ]).pipe(Effect.map((stdout) => stdout.trim()));++ return { commitSha };+ });++ const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = (cwd, fallbackBranch) =>+ Effect.gen(function* () {+ const details = yield* statusDetails(cwd);+ const branch = details.branch ?? fallbackBranch;+ if (!branch) {+ return yield* createGitCommandError(+ "GitCore.pushCurrentBranch",+ cwd,+ ["push"],+ "Cannot push from detached HEAD.",+ );+ }++ if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {+ return {+ status: "skipped_up_to_date" as const,+ branch,+ ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),+ };+ }++ if (!details.hasUpstream) {+ yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [+ "push",+ "-u",+ "origin",+ branch,+ ]);+ return {+ status: "pushed" as const,+ branch,+ upstreamBranch: `origin/${branch}`,+ setUpstream: true,+ };+ }++ yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]);+ return {+ status: "pushed" as const,+ branch,+ ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),+ setUpstream: false,+ };+ });++ const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = (cwd) =>+ Effect.gen(function* () {+ const details = yield* statusDetails(cwd);+ const branch = details.branch;+ if (!branch) {+ return yield* createGitCommandError(+ "GitCore.pullCurrentBranch",+ cwd,+ ["pull", "--ff-only"],+ "Cannot pull from detached HEAD.",+ );+ }+ if (!details.hasUpstream) {+ return yield* createGitCommandError(+ "GitCore.pullCurrentBranch",+ cwd,+ ["pull", "--ff-only"],+ "Current branch has no upstream configured. Push with upstream first.",+ );+ }+ const beforeSha = yield* runGitStdout(+ "GitCore.pullCurrentBranch.beforeSha",+ cwd,+ ["rev-parse", "HEAD"],+ true,+ ).pipe(Effect.map((stdout) => stdout.trim()));+ yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], {+ timeoutMs: 30_000,+ fallbackErrorMessage: "git pull failed",+ });+ const afterSha = yield* runGitStdout(+ "GitCore.pullCurrentBranch.afterSha",+ cwd,+ ["rev-parse", "HEAD"],+ true,+ ).pipe(Effect.map((stdout) => stdout.trim()));++ const refreshed = yield* statusDetails(cwd);+ return {+ status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",+ branch,+ upstreamBranch: refreshed.upstreamRef,+ };+ });++ const readRangeContext: GitCoreShape["readRangeContext"] = (cwd, baseBranch) =>+ Effect.gen(function* () {+ const range = `${baseBranch}..HEAD`;+ const [commitSummary, diffSummary, diffPatch] = yield* Effect.all(+ [+ runGitStdout("GitCore.readRangeContext.log", cwd, ["log", "--oneline", range]),+ runGitStdout("GitCore.readRangeContext.diffStat", cwd, ["diff", "--stat", range]),+ runGitStdout("GitCore.readRangeContext.diffPatch", cwd, [+ "diff",+ "--patch",+ "--minimal",+ range,+ ]),+ ],+ { concurrency: "unbounded" },+ );++ return {+ commitSummary,+ diffSummary,+ diffPatch,+ };+ });++ const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) =>+ runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe(+ Effect.map((stdout) => stdout.trim()),+ Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),+ );++ const listBranches: GitCoreShape["listBranches"] = (input) =>+ Effect.gen(function* () {+ const branchRecencyPromise = readBranchRecency(input.cwd).pipe(+ Effect.catch(() => Effect.succeed(new Map<string, number>())),+ );+ const result = yield* executeGit(+ "GitCore.listBranches.branchNoColor",+ input.cwd,+ ["branch", "--no-color"],+ {+ timeoutMs: 10_000,+ allowNonZeroExit: true,+ },+ );++ if (result.code !== 0) {+ const stderr = result.stderr.trim();+ if (stderr.toLowerCase().includes("not a git repository")) {+ return { branches: [], isRepo: false };+ }+ return yield* createGitCommandError(+ "GitCore.listBranches",+ input.cwd,+ ["branch", "--no-color"],+ stderr || "git branch failed",+ );+ }++ const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(+ [+ executeGit(+ "GitCore.listBranches.defaultRef",+ input.cwd,+ ["symbolic-ref", "refs/remotes/origin/HEAD"],+ {+ timeoutMs: 5_000,+ allowNonZeroExit: true,+ },+ ),+ executeGit(+ "GitCore.listBranches.worktreeList",+ input.cwd,+ ["worktree", "list", "--porcelain"],+ {+ timeoutMs: 5_000,+ allowNonZeroExit: true,+ },+ ),+ branchRecencyPromise,+ ],+ { concurrency: "unbounded" },+ );++ const defaultBranch =+ defaultRef.code === 0+ ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")+ : null;++ const worktreeMap = new Map<string, string>();+ if (worktreeList.code === 0) {+ let currentPath: string | null = null;+ for (const line of worktreeList.stdout.split("\n")) {+ if (line.startsWith("worktree ")) {+ const candidatePath = line.slice("worktree ".length);+ const exists = yield* fileSystem.stat(candidatePath).pipe(+ Effect.map(() => true),+ Effect.catch(() => Effect.succeed(false)),+ );+ currentPath = exists ? candidatePath : null;+ } else if (line.startsWith("branch refs/heads/") && currentPath) {+ worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);+ } else if (line === "") {+ currentPath = null;+ }+ }+ }++ const branches = result.stdout+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0)+ .map((line) => {+ const name = line.replace(/^[*+]\s+/, "");+ return {+ name,+ current: line.startsWith("* "),+ isDefault: name === defaultBranch,+ worktreePath: worktreeMap.get(name) ?? null,+ };+ })+ .toSorted((a, b) => {+ const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;+ const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;+ if (aPriority !== bPriority) return aPriority - bPriority;++ const aLastCommit = branchLastCommit.get(a.name) ?? 0;+ const bLastCommit = branchLastCommit.get(b.name) ?? 0;+ if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;+ return a.name.localeCompare(b.name);+ });++ return { branches, isRepo: true };+ });++ const createWorktree: GitCoreShape["createWorktree"] = (input) =>+ Effect.gen(function* () {+ const sanitizedBranch = input.newBranch.replace(/\//g, "-");+ const repoName = path.basename(input.cwd);+ const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";+ const worktreePath =+ input.path ?? path.join(homeDir, ".t3", "worktrees", repoName, sanitizedBranch);++ yield* executeGit(+ "GitCore.createWorktree",+ input.cwd,+ ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],+ {+ fallbackErrorMessage: "git worktree add failed",+ },+ );++ return {+ worktree: {+ path: worktreePath,+ branch: input.newBranch,+ },+ };+ });++ const removeWorktree: GitCoreShape["removeWorktree"] = (input) =>+ Effect.gen(function* () {+ const args = ["worktree", "remove"];+ if (input.force) {+ args.push("--force");+ }+ args.push(input.path);+ yield* executeGit("GitCore.removeWorktree", input.cwd, args, {+ timeoutMs: 15_000,+ fallbackErrorMessage: "git worktree remove failed",+ }).pipe(+ Effect.mapError((error) =>+ createGitCommandError(+ "GitCore.removeWorktree",+ input.cwd,+ args,+ `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,+ error,+ ),+ ),+ );+ });++ const createBranch: GitCoreShape["createBranch"] = (input) =>+ executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {+ timeoutMs: 10_000,+ fallbackErrorMessage: "git branch create failed",+ }).pipe(Effect.asVoid);++ const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>+ Effect.gen(function* () {+ yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {+ timeoutMs: 10_000,+ fallbackErrorMessage: "git checkout failed",+ });++ // Refresh upstream refs in the background so checkout remains responsive.+ yield* Effect.sync(() => {+ void Effect.runPromise(+ refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),+ );+ });+ });++ const initRepo: GitCoreShape["initRepo"] = (input) =>+ executeGit("GitCore.initRepo", input.cwd, ["init"], {+ timeoutMs: 10_000,+ fallbackErrorMessage: "git init failed",+ }).pipe(Effect.asVoid);++ return {+ status,+ statusDetails,+ prepareCommitContext,+ commit,+ pushCurrentBranch,+ pullCurrentBranch,+ readRangeContext,+ readConfigValue,+ listBranches,+ createWorktree,+ removeWorktree,+ createBranch,+ checkoutBranch,+ initRepo,+ } satisfies GitCoreShape;+ });++ export const GitCoreLive = Layer.effect(GitCore, makeGitCore);diff --cc apps/server/src/git/Layers/GitManager.test.tsindex 000000000,56c783924..b8d0ad1aamode 000000,100644..100644--- a/apps/server/src/git/Layers/GitManager.test.ts+++ b/apps/server/src/git/Layers/GitManager.test.ts@@@ -1,0 -1,641 +1,680 @@@+ import fs from "node:fs";+ import path from "node:path";++ import * as NodeServices from "@effect/platform-node/NodeServices";+ import { it } from "@effect/vitest";+ import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";+ import { expect } from "vitest";++ import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";+ import { type GitManagerShape } from "../Services/GitManager.ts";+ import {+ type GitHubCliShape,+ type GitHubPullRequestSummary,+ GitHubCli,+ } from "../Services/GitHubCli.ts";+ import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";+ import { GitServiceLive } from "./GitService.ts";+ import { GitService } from "../Services/GitService.ts";+ import { GitCoreLive } from "./GitCore.ts";+ import { makeGitManager } from "./GitManager.ts";++ interface FakeGhScenario {+ prListSequence?: string[];+ createdPrUrl?: string;+ defaultBranch?: string;+ failWith?: GitHubCliError;+ }++ interface FakeGitTextGeneration {+ generateCommitMessage: (input: {+ cwd: string;+ branch: string | null;+ stagedSummary: string;+ stagedPatch: string;+ }) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;+ generatePrContent: (input: {+ cwd: string;+ baseBranch: string;+ headBranch: string;+ commitSummary: string;+ diffSummary: string;+ diffPatch: string;+ }) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;+ }++ function makeTempDir(+ prefix: string,+ ): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {+ return Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ return yield* fileSystem.makeTempDirectoryScoped({ prefix });+ });+ }++ function runGit(+ cwd: string,+ args: readonly string[],+ allowNonZeroExit = false,+ ): Effect.Effect<+ { readonly code: number; readonly stdout: string; readonly stderr: string },+ GitCommandError,+ GitService+ > {+ return Effect.gen(function* () {+ const gitService = yield* GitService;+ return yield* gitService.execute({+ operation: "GitManager.test.runGit",+ cwd,+ args,+ allowNonZeroExit,+ });+ });+ }++ function initRepo(+ cwd: string,+ ): Effect.Effect<void, PlatformError.PlatformError | GitCommandError, FileSystem.FileSystem | Scope.Scope | GitService> {+ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ yield* runGit(cwd, ["init", "--initial-branch=main"]);+ yield* runGit(cwd, ["config", "user.email", "[email protected]"]);+ yield* runGit(cwd, ["config", "user.name", "Test User"]);+ yield* fs.writeFileString(path.join(cwd, "README.md"), "hello\n");+ yield* runGit(cwd, ["add", "README.md"]);+ yield* runGit(cwd, ["commit", "-m", "Initial commit"]);+ });+ }++ function createBareRemote(): Effect.Effect<+ string,+ PlatformError.PlatformError | GitCommandError,+ FileSystem.FileSystem | Scope.Scope | GitService+ > {+ return Effect.gen(function* () {+ const remoteDir = yield* makeTempDir("t3code-git-remote-");+ yield* runGit(remoteDir, ["init", "--bare"]);+ return remoteDir;+ });+ }++ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {+ const implementation: FakeGitTextGeneration = {+ generateCommitMessage: () =>+ Effect.succeed({+ subject: "Implement stacked git actions",+ body: "",+ }),+ generatePrContent: () =>+ Effect.succeed({+ title: "Add stacked git actions",+ body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",+ }),+ ...overrides,+ };++ return {+ generateCommitMessage: (input) =>+ implementation.generateCommitMessage(input).pipe(+ Effect.mapError(+ (cause) =>+ new TextGenerationError({+ operation: "generateCommitMessage",+ detail: "fake text generation failed",+ ...(cause !== undefined ? { cause } : {}),+ }),+ ),+ ),+ generatePrContent: (input) =>+ implementation.generatePrContent(input).pipe(+ Effect.mapError(+ (cause) =>+ new TextGenerationError({+ operation: "generatePrContent",+ detail: "fake text generation failed",+ ...(cause !== undefined ? { cause } : {}),+ }),+ ),+ ),+ };+ }++ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {+ service: GitHubCliShape;+ ghCalls: string[];+ } {+ const prListQueue = [...(scenario.prListSequence ?? [])];+ const ghCalls: string[] = [];++ const execute: GitHubCliShape["execute"] = (input) => {+ const args = [...input.args];+ ghCalls.push(args.join(" "));++ if (scenario.failWith) {+ return Effect.fail(scenario.failWith);+ }++ if (args[0] === "pr" && args[1] === "list") {+ const stdout = (prListQueue.shift() ?? "[]") + "\n";+ return Effect.succeed({+ stdout,+ stderr: "",+ code: 0,+ signal: null,+ timedOut: false,+ });+ }++ if (args[0] === "pr" && args[1] === "create") {+ return Effect.succeed({+ stdout:+ (scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",+ stderr: "",+ code: 0,+ signal: null,+ timedOut: false,+ });+ }++ if (args[0] === "pr" && args[1] === "view") {+ return Effect.succeed({+ stdout: "",+ stderr: "",+ code: 0,+ signal: null,+ timedOut: false,+ });+ }++ if (args[0] === "repo" && args[1] === "view") {+ return Effect.succeed({+ stdout: `${scenario.defaultBranch ?? "main"}\n`,+ stderr: "",+ code: 0,+ signal: null,+ timedOut: false,+ });+ }++ return Effect.fail(+ new GitHubCliError({+ operation: "execute",+ detail: `Unexpected gh command: ${args.join(" ")}`,+ }),+ );+ };++ return {+ service: {+ execute,+ listOpenPullRequests: (input) =>+ execute({+ cwd: input.cwd,+ args: [+ "pr",+ "list",+ "--head",+ input.headBranch,+ "--state",+ "open",+ "--limit",+ String(input.limit ?? 1),+ "--json",+ "number,title,url,baseRefName,headRefName",+ ],+ }).pipe(+ Effect.map(+ (result) => JSON.parse(result.stdout) as ReadonlyArray<GitHubPullRequestSummary>,+ ),+ ),+ createPullRequest: (input) =>+ execute({+ cwd: input.cwd,+ args: [+ "pr",+ "create",+ "--base",+ input.baseBranch,+ "--head",+ input.headBranch,+ "--title",+ input.title,+ "--body-file",+ input.bodyFile,+ ],+ }).pipe(Effect.asVoid),+ getDefaultBranch: (input) =>+ execute({+ cwd: input.cwd,+ args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],+ }).pipe(+ Effect.map((result) => {+ const value = result.stdout.trim();+ return value.length > 0 ? value : null;+ }),+ ),+ },+ ghCalls,+ };+ }++ function runStackedAction(+ manager: GitManagerShape,+ input: {+ cwd: string;+ action: "commit" | "commit_push" | "commit_push_pr";+ commitMessage?: string;+ },+ ) {+ return manager.runStackedAction(input);+ }++ function makeManager(input?: {+ ghScenario?: FakeGhScenario;+ textGeneration?: Partial<FakeGitTextGeneration>;+ }) {+ const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);+ const textGeneration = createTextGeneration(input?.textGeneration);++ const gitCoreLayer = GitCoreLive.pipe(+ Layer.provideMerge(GitServiceLive),+ Layer.provideMerge(NodeServices.layer),+ );++ const managerLayer = Layer.mergeAll(+ Layer.succeed(GitHubCli, gitHubCli),+ Layer.succeed(TextGeneration, textGeneration),+ gitCoreLayer,+ NodeServices.layer,+ );++ return makeGitManager.pipe(+ Effect.provide(managerLayer),+ Effect.map((manager) => ({ manager, ghCalls })),+ );+ }++ const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);++ it.layer(GitManagerTestLayer)("GitManager", (it) => {- it.effect("status includes open PR metadata when branch already has an open PR", () =>++ it.effect("status includes PR metadata when branch already has an open PR", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]);+ const remoteDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);+ yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]);++ const { manager } = yield* makeManager({+ ghScenario: {+ prListSequence: [+ JSON.stringify([+ {+ number: 13,+ title: "Existing PR",+ url: "https://github.com/pingdotgg/codething-mvp/pull/13",+ baseRefName: "main",+ headRefName: "feature/status-open-pr",+ },+ ]),+ ],+ },+ });++ const status = yield* manager.status({ cwd: repoDir });+ expect(status.branch).toBe("feature/status-open-pr");- expect(status.openPr).toEqual({++ expect(status.pr).toEqual({+ number: 13,+ title: "Existing PR",+ url: "https://github.com/pingdotgg/codething-mvp/pull/13",+ baseBranch: "main",+ headBranch: "feature/status-open-pr",++ state: "open",+ });+ }),+ );+- it.effect("status is resilient to gh lookup failures and returns openPr null", () =>++ it.effect("status returns merged PR state when latest PR was merged", () =>++ Effect.gen(function* () {++ const repoDir = yield* makeTempDir("t3code-git-manager-");++ yield* initRepo(repoDir);++ yield* runGit(repoDir, ["checkout", "-b", "feature/status-merged-pr"]);++++ const { manager } = yield* makeManager({++ ghScenario: {++ prListSequence: [++ JSON.stringify([++ {++ number: 22,++ title: "Merged PR",++ url: "https://github.com/pingdotgg/codething-mvp/pull/22",++ baseRefName: "main",++ headRefName: "feature/status-merged-pr",++ state: "MERGED",++ mergedAt: "2026-01-30T10:00:00Z",++ updatedAt: "2026-01-30T10:00:00Z",++ },++ ]),++ ],++ },++ });++++ const status = yield* manager.status({ cwd: repoDir });++ expect(status.branch).toBe("feature/status-merged-pr");++ expect(status.pr).toEqual({++ number: 22,++ title: "Merged PR",++ url: "https://github.com/pingdotgg/codething-mvp/pull/22",++ baseBranch: "main",++ headBranch: "feature/status-merged-pr",++ state: "merged",++ });++ }),++ );++++ it.effect("status is resilient to gh lookup failures and returns pr null", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ yield* runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);+ const remoteDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);+ yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);++ const { manager } = yield* makeManager({+ ghScenario: {+ failWith: new GitHubCliError({+ operation: "execute",+ detail: "GitHub CLI (`gh`) is required but not available on PATH.",+ }),+ },+ });++ const status = yield* manager.status({ cwd: repoDir });+ expect(status.branch).toBe("feature/status-no-gh");- expect(status.openPr).toBeNull();++ expect(status.pr).toBeNull();+ }),+ );++ it.effect("creates a commit when working tree is dirty", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");++ const { manager } = yield* makeManager();+ const result = yield* runStackedAction(manager, {+ cwd: repoDir,+ action: "commit",+ });++ expect(result.commit.status).toBe("created");+ expect(result.push.status).toBe("skipped_not_requested");+ expect(result.pr.status).toBe("skipped_not_requested");+ expect(+ yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(+ Effect.map((result) => result.stdout.trim()),+ ),+ ).toBe("Implement stacked git actions");+ }),+ );++ it.effect("uses custom commit message when provided", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");+ let generatedCount = 0;++ const { manager } = yield* makeManager({+ textGeneration: {+ generateCommitMessage: () =>+ Effect.sync(() => {+ generatedCount += 1;+ return {+ subject: "this should not be used",+ body: "",+ };+ }),+ },+ });+ const result = yield* runStackedAction(manager, {+ cwd: repoDir,+ action: "commit",+ commitMessage: "feat: custom summary line\n\n- details from user",+ });++ expect(result.commit.status).toBe("created");+ expect(result.commit.subject).toBe("feat: custom summary line");+ expect(generatedCount).toBe(0);+ expect(+ yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(+ Effect.map((result) => result.stdout.trim()),+ ),+ ).toBe("feat: custom summary line");+ expect(+ yield* runGit(repoDir, ["log", "-1", "--pretty=%b"]).pipe(+ Effect.map((result) => result.stdout.trim()),+ ),+ ).toContain("- details from user");+ }),+ );++ it.effect("skips commit when there are no uncommitted changes", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);++ const { manager } = yield* makeManager();+ const result = yield* runStackedAction(manager, {+ cwd: repoDir,+ action: "commit",+ });++ expect(result.commit.status).toBe("skipped_no_changes");+ expect(result.push.status).toBe("skipped_not_requested");+ expect(result.pr.status).toBe("skipped_not_requested");+ }),+ );++ it.effect("commits and pushes with upstream auto-setup when needed", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ yield* runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);+ const remoteDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);+ fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");++ const { manager } = yield* makeManager();+ const result = yield* runStackedAction(manager, {+ cwd: repoDir,+ action: "commit_push",+ });++ expect(result.commit.status).toBe("created");+ expect(result.push.status).toBe("pushed");+ expect(result.push.setUpstream).toBe(true);+ expect(+ yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(+ Effect.map((result) => result.stdout.trim()),+ ),+ ).toBe("origin/feature/stacked-flow");+ }),+ );++ it.effect("skips push when branch is already up to date", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ yield* runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]);+ const remoteDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);+ yield* runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]);++ const { manager } = yield* makeManager();+ const result = yield* runStackedAction(manager, {+ cwd: repoDir,+ action: "commit_push",+ });++ expect(result.commit.status).toBe("skipped_no_changes");+ expect(result.push.status).toBe("skipped_up_to_date");+ }),+ );++ it.effect("returns existing PR metadata for commit/push/pr action", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ yield* runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);+ const remoteDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);+ yield* runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);++ const { manager, ghCalls } = yield* makeManager({+ ghScenario: {+ prListSequence: [+ JSON.stringify([+ {+ number: 42,+ title: "Existing PR",+ url: "https://github.com/pingdotgg/codething-mvp/pull/42",+ baseRefName: "main",+ headRefName: "feature/existing-pr",+ },+ ]),+ ],+ },+ });+ const result = yield* runStackedAction(manager, {+ cwd: repoDir,+ action: "commit_push_pr",+ });++ expect(result.pr.status).toBe("opened_existing");+ expect(result.pr.number).toBe(42);+ expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);+ }),+ );++ it.effect("creates PR when one does not already exist", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ yield* runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);+ const remoteDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);+ fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");+ yield* runGit(repoDir, ["add", "changes.txt"]);+ yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);+ yield* runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);+ yield* runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);++ const { manager, ghCalls } = yield* makeManager({+ ghScenario: {+ prListSequence: [+ "[]",+ JSON.stringify([+ {+ number: 88,+ title: "Add stacked git actions",+ url: "https://github.com/pingdotgg/codething-mvp/pull/88",+ baseRefName: "main",+ headRefName: "feature-create-pr",+ },+ ]),+ ],+ },+ });+ const result = yield* runStackedAction(manager, {+ cwd: repoDir,+ action: "commit_push_pr",+ });++ expect(result.pr.status).toBe("created");+ expect(result.pr.number).toBe(88);+ expect(+ ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),+ ).toBe(true);+ expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);+ }),+ );++ it.effect("rejects push/pr actions from detached HEAD", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ yield* runGit(repoDir, ["checkout", "--detach", "HEAD"]);++ const { manager } = yield* makeManager();+ const errorMessage = yield* runStackedAction(manager, {+ cwd: repoDir,+ action: "commit_push",+ }).pipe(+ Effect.flip,+ Effect.map((error) => error.message),+ );+ expect(errorMessage).toContain("detached HEAD");+ }),+ );++ it.effect("surfaces missing gh binary errors", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ yield* runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]);+ const remoteDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);+ yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]);++ const { manager } = yield* makeManager({+ ghScenario: {+ failWith: new GitHubCliError({+ operation: "execute",+ detail: "GitHub CLI (`gh`) is required but not available on PATH.",+ }),+ },+ });++ const errorMessage = yield* runStackedAction(manager, {+ cwd: repoDir,+ action: "commit_push_pr",+ }).pipe(+ Effect.flip,+ Effect.map((error) => error.message),+ );+ expect(errorMessage).toContain("GitHub CLI (`gh`) is required");+ }),+ );++ it.effect("surfaces gh auth errors with guidance", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ yield* runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]);+ const remoteDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);+ yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]);++ const { manager } = yield* makeManager({+ ghScenario: {+ failWith: new GitHubCliError({+ operation: "execute",+ detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",+ }),+ },+ });++ const errorMessage = yield* runStackedAction(manager, {+ cwd: repoDir,+ action: "commit_push_pr",+ }).pipe(+ Effect.flip,+ Effect.map((error) => error.message),+ );+ expect(errorMessage).toContain("gh auth login");+ }),+ );+ });diff --cc apps/server/src/git/Layers/GitManager.tsindex 000000000,54be186ef..5deaf6ed4mode 000000,100644..100644--- a/apps/server/src/git/Layers/GitManager.ts+++ b/apps/server/src/git/Layers/GitManager.ts@@@ -1,0 -1,321 +1,420 @@@+ import { randomUUID } from "node:crypto";++ import { Effect, FileSystem, Layer, Path } from "effect";++ import { GitManagerError } from "../Errors.ts";+ import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";+ import { GitCore } from "../Services/GitCore.ts";+ import { GitHubCli } from "../Services/GitHubCli.ts";+ import { TextGeneration } from "../Services/TextGeneration.ts";++ interface OpenPrInfo {+ number: number;+ title: string;+ url: string;+ baseRefName: string;+ headRefName: string;+ }+++interface PullRequestInfo extends OpenPrInfo {++ state: "open" | "closed" | "merged";++ updatedAt: string | null;++}++++function parsePullRequestList(raw: unknown): PullRequestInfo[] {++ if (!Array.isArray(raw)) return [];++++ const parsed: PullRequestInfo[] = [];++ for (const entry of raw) {++ if (!entry || typeof entry !== "object") continue;++ const record = entry as Record<string, unknown>;++ const number = record.number;++ const title = record.title;++ const url = record.url;++ const baseRefName = record.baseRefName;++ const headRefName = record.headRefName;++ const state = record.state;++ const mergedAt = record.mergedAt;++ const updatedAt = record.updatedAt;++ if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {++ continue;++ }++ if (++ typeof title !== "string" ||++ typeof url !== "string" ||++ typeof baseRefName !== "string" ||++ typeof headRefName !== "string"++ ) {++ continue;++ }++++ let normalizedState: "open" | "closed" | "merged";++ if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {++ normalizedState = "merged";++ } else if (state === "OPEN" || state === undefined || state === null) {++ normalizedState = "open";++ } else if (state === "CLOSED") {++ normalizedState = "closed";++ } else {++ continue;++ }++++ parsed.push({++ number,++ title,++ url,++ baseRefName,++ headRefName,++ state: normalizedState,++ updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,++ });++ }++ return parsed;++}+++ function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {+ return new GitManagerError({+ operation,+ detail,+ ...(cause !== undefined ? { cause } : {}),+ });+ }++ function limitContext(value: string, maxChars: number): string {+ if (value.length <= maxChars) return value;+ return `${value.slice(0, maxChars)}\n\n[truncated]`;+ }++ function sanitizeCommitMessage(generated: { subject: string; body: string }): {+ subject: string;+ body: string;+ } {+ const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";+ const subject = rawSubject.replace(/[.]+$/g, "").trim();+ const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";+ return {+ subject: safeSubject,+ body: generated.body.trim(),+ };+ }++ function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {+ const normalized = raw.replace(/\r\n/g, "\n").trim();+ if (normalized.length === 0) {+ return null;+ }++ const [firstLine, ...rest] = normalized.split("\n");+ const subject = firstLine?.trim() ?? "";+ if (subject.length === 0) {+ return null;+ }++ return {+ subject,+ body: rest.join("\n").trim(),+ };+ }++ function extractBranchFromRef(ref: string): string {+ const normalized = ref.trim();++ if (normalized.startsWith("refs/remotes/")) {+ const withoutPrefix = normalized.slice("refs/remotes/".length);+ const firstSlash = withoutPrefix.indexOf("/");+ if (firstSlash === -1) {+ return withoutPrefix.trim();+ }+ return withoutPrefix.slice(firstSlash + 1).trim();+ }++ const firstSlash = normalized.indexOf("/");+ if (firstSlash === -1) {+ return normalized;+ }+ return normalized.slice(firstSlash + 1).trim();+ }+-function toStatusOpenPr(pr: OpenPrInfo): {++function toStatusPr(pr: PullRequestInfo): {+ number: number;+ title: string;+ url: string;+ baseBranch: string;+ headBranch: string;++ state: "open" | "closed" | "merged";+ } {+ return {+ number: pr.number,+ title: pr.title,+ url: pr.url,+ baseBranch: pr.baseRefName,+ headBranch: pr.headRefName,++ state: pr.state,+ };+ }++ export const makeGitManager = Effect.gen(function* () {+ const gitCore = yield* GitCore;+ const gitHubCli = yield* GitHubCli;+ const textGeneration = yield* TextGeneration;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;++ const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";++ const findOpenPr = (cwd: string, branch: string) =>+ gitHubCli+ .listOpenPullRequests({+ cwd,+ headBranch: branch,+ limit: 1,+ })+ .pipe(+ Effect.map((prs) => {+ const [first] = prs;+ if (!first) {+ return null;+ }+ return {+ number: first.number,+ title: first.title,+ url: first.url,+ baseRefName: first.baseRefName,+ headRefName: first.headRefName,- } satisfies OpenPrInfo;++ state: "open",++ updatedAt: null,++ } satisfies PullRequestInfo;+ }),+ );+++ const findLatestPr = (cwd: string, branch: string) =>++ Effect.gen(function* () {++ const stdout = yield* gitHubCli++ .execute({++ cwd,++ args: [++ "pr",++ "list",++ "--head",++ branch,++ "--state",++ "all",++ "--limit",++ "20",++ "--json",++ "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",++ ],++ })++ .pipe(Effect.map((result) => result.stdout));++++ const raw = stdout.trim();++ if (raw.length === 0) {++ return null;++ }++++ const parsedJson = yield* Effect.try({++ try: () => JSON.parse(raw) as unknown,++ catch: (cause) =>++ gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),++ });++++ const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {++ const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;++ const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;++ return right - left;++ });++ return parsed[0] ?? null;++ });+++ const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>+ Effect.gen(function* () {+ const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);+ if (configured) return configured;++ if (upstreamRef) {+ const upstreamBranch = extractBranchFromRef(upstreamRef);+ if (upstreamBranch.length > 0 && upstreamBranch !== branch) {+ return upstreamBranch;+ }+ }++ const defaultFromGh = yield* gitHubCli+ .getDefaultBranch({ cwd })+ .pipe(Effect.catch(() => Effect.succeed(null)));+ if (defaultFromGh) {+ return defaultFromGh;+ }++ return "main";+ });++ const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>+ Effect.gen(function* () {+ const context = yield* gitCore.prepareCommitContext(cwd);+ if (!context) {+ return { status: "skipped_no_changes" as const };+ }++ let generated = parseCustomCommitMessage(commitMessage ?? "");+ if (!generated) {+ generated = yield* textGeneration+ .generateCommitMessage({+ cwd,+ branch,+ stagedSummary: limitContext(context.stagedSummary, 8_000),+ stagedPatch: limitContext(context.stagedPatch, 50_000),+ })+ .pipe(Effect.map((result) => sanitizeCommitMessage(result)));+ }++ const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);+ return {+ status: "created" as const,+ commitSha,+ subject: generated.subject,+ };+ });++ const runPrStep = (cwd: string, fallbackBranch: string | null) =>+ Effect.gen(function* () {+ const details = yield* gitCore.statusDetails(cwd);+ const branch = details.branch ?? fallbackBranch;+ if (!branch) {+ return yield* gitManagerError(+ "runPrStep",+ "Cannot create a pull request from detached HEAD.",+ );+ }+ if (!details.hasUpstream) {+ return yield* gitManagerError(+ "runPrStep",+ "Current branch has not been pushed. Push before creating a PR.",+ );+ }++ const existing = yield* findOpenPr(cwd, branch);+ if (existing) {+ return {+ status: "opened_existing" as const,+ url: existing.url,+ number: existing.number,+ baseBranch: existing.baseRefName,+ headBranch: existing.headRefName,+ title: existing.title,+ };+ }++ const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef);+ const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);++ const generated = yield* textGeneration.generatePrContent({+ cwd,+ baseBranch,+ headBranch: branch,+ commitSummary: limitContext(rangeContext.commitSummary, 20_000),+ diffSummary: limitContext(rangeContext.diffSummary, 20_000),+ diffPatch: limitContext(rangeContext.diffPatch, 60_000),+ });++ const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);+ yield* fileSystem+ .writeFileString(bodyFile, generated.body)+ .pipe(+ Effect.mapError((cause) =>+ gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause),+ ),+ );+ yield* gitHubCli+ .createPullRequest({+ cwd,+ baseBranch,+ headBranch: branch,+ title: generated.title,+ bodyFile,+ })+ .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));++ const created = yield* findOpenPr(cwd, branch);+ if (!created) {+ return {+ status: "created" as const,+ baseBranch,+ headBranch: branch,+ title: generated.title,+ };+ }++ return {+ status: "created" as const,+ url: created.url,+ number: created.number,+ baseBranch: created.baseRefName,+ headBranch: created.headRefName,+ title: created.title,+ };+ });++ const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {+ const details = yield* gitCore.statusDetails(input.cwd);+- const openPr =- details.branch && details.hasUpstream- ? yield* findOpenPr(input.cwd, details.branch).pipe(- Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),++ const pr =++ details.branch !== null++ ? yield* findLatestPr(input.cwd, details.branch).pipe(++ Effect.map((latest) => (latest ? toStatusPr(latest) : null)),+ Effect.catch(() => Effect.succeed(null)),+ )+ : null;++ return {+ branch: details.branch,+ hasWorkingTreeChanges: details.hasWorkingTreeChanges,+ workingTree: details.workingTree,+ hasUpstream: details.hasUpstream,+ aheadCount: details.aheadCount,+ behindCount: details.behindCount,- openPr,++ pr,+ };+ });++ const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(+ function* (input) {+ const wantsPush = input.action !== "commit";+ const wantsPr = input.action === "commit_push_pr";++ const initialStatus = yield* gitCore.statusDetails(input.cwd);+ if (wantsPush && !initialStatus.branch) {+ return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");+ }+ if (wantsPr && !initialStatus.branch) {+ return yield* gitManagerError(+ "runStackedAction",+ "Cannot create a pull request from detached HEAD.",+ );+ }++ const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);++ const push = wantsPush+ ? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)+ : { status: "skipped_not_requested" as const };++ const pr = wantsPr+ ? yield* runPrStep(input.cwd, initialStatus.branch)+ : { status: "skipped_not_requested" as const };++ return {+ action: input.action,+ commit,+ push,+ pr,+ };+ },+ );++ return {+ status,+ runStackedAction,+ } satisfies GitManagerShape;+ });++ export const GitManagerLive = Layer.effect(GitManager, makeGitManager);diff --cc apps/server/src/git/Services/GitCore.tsindex 000000000,4e1b3fc5b..d2544de90mode 000000,100644..100644--- a/apps/server/src/git/Services/GitCore.ts+++ b/apps/server/src/git/Services/GitCore.ts@@@ -1,0 -1,148 +1,148 @@@+ /**+ * GitCore - Effect service contract for low-level Git operations.+ *+ * Wraps core repository primitives used by higher-level orchestration+ * services and WebSocket routes.+ *+ * @module GitCore+ */+ import { ServiceMap } from "effect";+ import type { Effect } from "effect";+ import type {+ GitCheckoutInput,+ GitCreateBranchInput,+ GitCreateWorktreeInput,+ GitCreateWorktreeResult,+ GitInitInput,+ GitListBranchesInput,+ GitListBranchesResult,+ GitPullResult,+ GitRemoveWorktreeInput,+ GitStatusInput,+ GitStatusResult,+ } from "@t3tools/contracts";++ import type { GitCommandError } from "../Errors.ts";+-export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {++export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {+ upstreamRef: string | null;+ }++ export interface GitPreparedCommitContext {+ stagedSummary: string;+ stagedPatch: string;+ }++ export interface GitPushResult {+ status: "pushed" | "skipped_up_to_date";+ branch: string;+ upstreamBranch?: string | undefined;+ setUpstream?: boolean | undefined;+ }++ export interface GitRangeContext {+ commitSummary: string;+ diffSummary: string;+ diffPatch: string;+ }++ /**+ * GitCoreShape - Service API for low-level Git repository interactions.+ */+ export interface GitCoreShape {+ /**+ * Read Git status for a repository.+ */+ readonly status: (input: GitStatusInput) => Effect.Effect<GitStatusResult, GitCommandError>;++ /**+ * Read detailed working tree / branch status for a repository.+ */+ readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;++ /**+ * Build staged change context for commit generation.+ */+ readonly prepareCommitContext: (+ cwd: string,+ ) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;++ /**+ * Create a commit with provided subject/body.+ */+ readonly commit: (+ cwd: string,+ subject: string,+ body: string,+ ) => Effect.Effect<{ commitSha: string }, GitCommandError>;++ /**+ * Push current branch, setting upstream if needed.+ */+ readonly pushCurrentBranch: (+ cwd: string,+ fallbackBranch: string | null,+ ) => Effect.Effect<GitPushResult, GitCommandError>;++ /**+ * Collect commit/diff context between base branch and current HEAD.+ */+ readonly readRangeContext: (+ cwd: string,+ baseBranch: string,+ ) => Effect.Effect<GitRangeContext, GitCommandError>;++ /**+ * Read a Git config value from the local repository.+ */+ readonly readConfigValue: (+ cwd: string,+ key: string,+ ) => Effect.Effect<string | null, GitCommandError>;++ /**+ * List local branches and branch metadata.+ */+ readonly listBranches: (+ input: GitListBranchesInput,+ ) => Effect.Effect<GitListBranchesResult, GitCommandError>;++ /**+ * Pull current branch from upstream using fast-forward only.+ */+ readonly pullCurrentBranch: (cwd: string) => Effect.Effect<GitPullResult, GitCommandError>;++ /**+ * Create a worktree and branch from a base branch.+ */+ readonly createWorktree: (+ input: GitCreateWorktreeInput,+ ) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>;++ /**+ * Remove an existing worktree.+ */+ readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;++ /**+ * Create a local branch.+ */+ readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect<void, GitCommandError>;++ /**+ * Checkout an existing branch and refresh its upstream metadata in background.+ */+ readonly checkoutBranch: (input: GitCheckoutInput) => Effect.Effect<void, GitCommandError>;++ /**+ * Initialize a repository in the provided directory.+ */+ readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;+ }++ /**+ * GitCore - Service tag for low-level Git repository operations.+ */+ export class GitCore extends ServiceMap.Service<GitCore, GitCoreShape>()(+ "t3/git/Services/GitCore",+ ) {}diff --cc apps/server/src/wsServer.test.tsindex 6e1b8c0b6,494c45516..2e78484c1--- a/apps/server/src/wsServer.test.ts+++ b/apps/server/src/wsServer.test.ts@@@ -994,20 -1412,15 +1412,15 @@@ describe("WebSocket Server", () =>hasUpstream: false,aheadCount: 0,behindCount: 0,- openPr: null,+ pr: null,- });- expect(gitManager.status).toHaveBeenCalledWith({ cwd: "/test" });- });-- it("returns errors from git.runStackedAction", async () => {- const gitManager = {- status: vi.fn(),- runStackedAction: vi.fn().mockRejectedValue(new Error("Cannot push from detached HEAD.")),};- server = createTestServer({ cwd: "/test", gitManager });- await server.start();- const addr = server.httpServer.address();+ const status = vi.fn(() => Effect.succeed(statusResult));+ const runStackedAction = vi.fn(() => Effect.void as any);+ const gitManager: GitManagerShape = { status, runStackedAction };++ server = await createTestServer({ cwd: "/test", gitManager });+ const addr = server.address();const port = typeof addr === "object" && addr !== null ? addr.port : 0;const ws = await connectWs(port);diff --cc apps/web/src/components/GitActionsControl.tsxindex ed55c5cce,a75d4697a..694ecbc05--- a/apps/web/src/components/GitActionsControl.tsx+++ b/apps/web/src/components/GitActionsControl.tsx@@@ -236,8 -236,7 +236,7 @@@ export default function GitActionsContrdata: threadToastData,});});- }, [api, gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);-- }, [gitStatusForActions?.openPr?.url, threadToastData]);++ }, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);const runGitActionWithToast = useCallback(async ({action,@@@ -362,11 -361,11 +363,11 @@@});}},+[- api,gitStatusForActions?.branch,gitStatusForActions?.hasWorkingTreeChanges,- gitStatusForActions?.openPr?.url,+ gitStatusForActions?.pr,isDefaultBranch,maybeConfirmPushToDefaultBranch,runImmediateGitActionMutation,diff --cc apps/web/src/components/Sidebar.tsxindex 34ffe14f0,35fd56265..de4030668--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@@ -1,29 -1,42 +1,43 @@@- import {- GitPullRequestIcon,- MonitorIcon,- MoonIcon,- SunIcon,- TerminalIcon,- } from "lucide-react";-import { ChevronRightIcon, FolderIcon, TerminalIcon } from "lucide-react";++import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";import { useCallback, useEffect, useMemo, useState } from "react";- import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";+ import {+ DEFAULT_MODEL,+ ProjectId,+ ThreadId,++ type GitStatusResult,+ type ResolvedKeybindingsConfig,+ } from "@t3tools/contracts";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";- import { gitStatusResultSchema, type GitStatusResult } from "@t3tools/contracts";import { useNavigate, useParams } from "@tanstack/react-router";import { useAppSettings } from "../appSettings";import { isElectron } from "../env";import { APP_STAGE_LABEL } from "../branding";- import { DEFAULT_MODEL } from "../model-logic";- import { derivePendingApprovals } from "../session-logic";+ import { newCommandId, newProjectId, newThreadId } from "../lib/utils";import { useStore } from "../store";import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";- import { type Project, type Thread } from "../types";- import { useNativeApi } from "../hooks/useNativeApi";+ import { type Thread } from "../types";+ import { derivePendingApprovals } from "../session-logic";-import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";+import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";import { serverConfigQueryOptions } from "../lib/serverReactQuery";+ import { readNativeApi } from "../nativeApi";import { toastManager } from "./ui/toast";+ import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";+ import {+ SidebarContent,+ SidebarFooter,+ SidebarGroup,+ SidebarHeader,+ SidebarMenu,+ SidebarMenuButton,+ SidebarMenuItem,+ SidebarMenuSub,+ SidebarMenuSubButton,+ SidebarMenuSubItem,+ SidebarSeparator,+ SidebarTrigger,+ } from "./ui/sidebar";import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";- import { createThread } from "../threadFactory";+ import { isNonEmpty as isNonEmptyString } from "effect/String";const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];@@@ -57,16 -63,9 +64,16 @@@ interface TerminalStatusIndicatorpulse: boolean;}+interface PrStatusIndicator {+ label: "PR open" | "PR closed" | "PR merged";+ colorClass: string;+}++type ThreadPrState = NonNullable<GitStatusResult["pr"]>["state"] | null;+function hasUnseenCompletion(thread: Thread): boolean {- if (!thread.latestTurnCompletedAt) return false;- const completedAt = Date.parse(thread.latestTurnCompletedAt);+ if (!thread.latestTurn?.completedAt) return false;+ const completedAt = Date.parse(thread.latestTurn.completedAt);if (Number.isNaN(completedAt)) return false;if (!thread.lastVisitedAt) return true;@@@ -118,37 -114,75 +122,97 @@@ function threadStatusPill(thread: Threareturn null;}+ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {+ if (thread.runningTerminalIds.length === 0) {+ return null;+ }+ return {+ label: "Terminal process running",+ colorClass: "text-teal-600 dark:text-teal-300/90",+ pulse: true,+ };+ }++function prStatusIndicator(prState: ThreadPrState): PrStatusIndicator | null {+ if (prState === "open") {+ return {+ label: "PR open",+ colorClass: "text-emerald-600 dark:text-emerald-300/90",+ };+ }+ if (prState === "closed") {+ return {+ label: "PR closed",+ colorClass: "text-zinc-500 dark:text-zinc-400/80",+ };+ }+ if (prState === "merged") {+ return {+ label: "PR merged",+ colorClass: "text-violet-600 dark:text-violet-300/90",+ };+ }+ return null;+}+- function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {- if (thread.runningTerminalIds.length === 0) {- return null;+ function T3Wordmark() {+ return (+ <svg+ aria-label="T3"+ className="h-3 w-auto shrink-0 text-foreground"+ viewBox="15.5309 37 94.3941 56.96"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z"+ fill="currentColor"+ />+ </svg>+ );+ }++ /**+ * Derives the server's HTTP origin (scheme + host + port) from the same+ * sources WsTransport uses, converting ws(s) to http(s).+ */+ function getServerHttpOrigin(): string {+ const bridgeUrl = window.desktopBridge?.getWsUrl();+ const envUrl = import.meta.env.VITE_WS_URL as string | undefined;+ const wsUrl =+ bridgeUrl && bridgeUrl.length > 0+ ? bridgeUrl+ : envUrl && envUrl.length > 0+ ? envUrl+ : `ws://${window.location.hostname}:${window.location.port}`;+ // Parse to extract just the origin, dropping path/query (e.g. ?token=…)+ const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");+ try {+ return new URL(httpUrl).origin;+ } catch {+ return httpUrl;}- return {- label: "Terminal process running",- colorClass: "text-teal-600 dark:text-teal-300/90",- pulse: true,- };+ }++ const serverHttpOrigin = getServerHttpOrigin();++ function ProjectFavicon({ cwd }: { cwd: string }) {+ const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");++ const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;++ if (status === "error") {+ return <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/50" />;+ }++ return (+ <img+ src={src}+ alt=""+ className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loading" ? "hidden" : ""}`}+ onLoad={() => setStatus("loaded")}+ onError={() => setStatus("error")}+ />+ );}export default function Sidebar() {@@@ -177,62 -210,6 +240,58 @@@}return map;}, [state.threads]);+ const projectCwdById = useMemo(+ () => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),+ [state.projects],+ );+ const threadGitTargets = useMemo(+ () =>+ state.threads.map((thread) => ({+ threadId: thread.id,+ branch: thread.branch,+ cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,+ })),+ [projectCwdById, state.threads],+ );+ const threadGitStatusCwds = useMemo(+ () =>+ [+ ...new Set(+ threadGitTargets+ .filter((target) => target.branch !== null)+ .map((target) => target.cwd)+ .filter((cwd): cwd is string => cwd !== null),+ ),+ ],+ [threadGitTargets],+ );+ const threadGitStatusQueries = useQueries({- queries: threadGitStatusCwds.map((cwd) => {- const base = gitStatusQueryOptions(api, cwd);- return {- ...base,- enabled: Boolean(base.enabled),- staleTime: 30_000,- refetchInterval: 60_000,- };- }),++ queries: threadGitStatusCwds.map((cwd) => ({++ ...gitStatusQueryOptions(cwd),++ staleTime: 30_000,++ refetchInterval: 60_000,++ })),+ });+ const prStateByThreadId = useMemo(() => {+ const statusByCwd = new Map<string, GitStatusResult>();+ for (let index = 0; index < threadGitStatusCwds.length; index += 1) {+ const cwd = threadGitStatusCwds[index];+ if (!cwd) continue;- const parsed = gitStatusResultSchema.safeParse(threadGitStatusQueries[index]?.data);- if (parsed.success) {- statusByCwd.set(cwd, parsed.data);++ const status = threadGitStatusQueries[index]?.data;++ if (status) {++ statusByCwd.set(cwd, status);+ }+ }+- const map = new Map<string, ThreadPrState>();++ const map = new Map<ThreadId, ThreadPrState>();+ for (const target of threadGitTargets) {+ const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;+ const branchMatches =+ target.branch !== null && status?.branch !== null && status?.branch === target.branch;+ map.set(target.threadId, branchMatches ? status?.pr?.state ?? null : null);+ }+ return map;+ }, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);const handleNewThread = useCallback((@@@ -540,224 -523,262 +605,273 @@@};}, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);- return (- <aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">- {/* Branding */}- <div- className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}- >- <div className="flex min-w-0 flex-1 items-center gap-2">- <span className="truncate text-sm font-semibold tracking-tight text-foreground">- T3 <span className="font-normal text-muted-foreground">Code</span>- </span>- <span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">- {APP_STAGE_LABEL}- </span>- </div>- </div>+ const onCreateThreadClick = () => {+ if (state.projects.length === 0) {+ setAddingProject(true);+ return;+ }+ const firstProject = state.projects[0];+ if (firstProject) void handleNewThread(firstProject.id);+ };- {/* New thread (global) */}- <div className="px-3 pb-3">- <button- type="button"- className="flex w-full items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent"- onClick={() => {- if (state.projects.length === 0) {- setAddingProject(true);- return;- }- const firstProject = state.projects[0];- if (firstProject) handleNewThread(firstProject.id);- }}- >- <span className="text-foreground">+</span>- New thread- </button>+ const wordmark = (+ <div className={`flex items-center gap-2 ${isElectron ? "-translate-y-px" : ""}`}>+ <SidebarTrigger className="shrink-0 md:hidden" />+ <div className="flex min-w-0 flex-1 items-center gap-1">+ <T3Wordmark />+ <span className="truncate text-base font-medium tracking-tight text-muted-foreground">+ Code+ </span>+ <span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">+ {APP_STAGE_LABEL}+ </span></div>+ </div>+ );- {/* Project list */}- <nav className="flex-1 overflow-y-auto px-2">- {state.projects.map((project) => {- const threads = state.threads- .filter((t) => t.projectId === project.id)- .toSorted((a, b) => {- const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();- if (byDate !== 0) return byDate;- return b.id.localeCompare(a.id);- });- return (- <div key={project.id} className="mb-1">- {/* Project header */}- <button- type="button"- className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"- onClick={() => dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })}- onContextMenu={(e) => {- e.preventDefault();- void handleProjectContextMenu(project.id, {- x: e.clientX,- y: e.clientY,- });- }}- >- <span className="text-[10px] text-muted-foreground/70">- {project.expanded ? "▼" : "▶"}- </span>- <span className="flex-1 truncate text-xs font-medium text-foreground/90">- {project.name}- </span>- <span className="text-[10px] text-muted-foreground/60">{threads.length}</span>- </button>+ const newThreadButton = (+ <button+ type="button"+ className="flex w-full items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent"+ onClick={onCreateThreadClick}+ >+ <span className="text-foreground">+</span>+ New thread+ </button>+ );- {/* Threads */}- {project.expanded && (- <div className="ml-2 border-l border-border/80 pl-2">- {threads.map((thread) => {- const isActive = routeThreadId === thread.id;- const threadStatus = threadStatusPill(- thread,- pendingApprovalByThreadId.get(thread.id) === true,- );- const terminalStatus = terminalStatusIndicator(thread);- const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);- return (- <button- key={thread.id}- type="button"- className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 ${- isActive- ? "bg-accent text-foreground"- : "text-muted-foreground hover:bg-secondary"+ return (+ <>+ {isElectron ? (+ <>+ <SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[88px]">+ {wordmark}+ </SidebarHeader>+ <div className="px-4 pb-2">{newThreadButton}</div>+ </>+ ) : (+ <SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">+ {wordmark}+ {newThreadButton}+ </SidebarHeader>+ )}++ <SidebarContent className="gap-0">+ <SidebarGroup className="px-2 py-2">+ <SidebarMenu>+ {state.projects.map((project) => {+ const threads = state.threads+ .filter((thread) => thread.projectId === project.id)+ .toSorted((a, b) => {+ const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();+ if (byDate !== 0) return byDate;+ return b.id.localeCompare(a.id);+ });++ return (+ <Collapsible+ key={project.id}+ className="group/collapsible"+ open={project.expanded}+ onOpenChange={(open) => {+ if (open === project.expanded) return;+ dispatch({ type: "TOGGLE_PROJECT", projectId: project.id });+ }}+ >+ <SidebarMenuItem>+ <CollapsibleTrigger+ render={+ <SidebarMenuButton+ size="sm"+ className="gap-2 px-2 py-1.5 text-left hover:bg-accent"+ />+ }+ onContextMenu={(event) => {+ event.preventDefault();+ void handleProjectContextMenu(project.id, {+ x: event.clientX,+ y: event.clientY,+ });+ }}+ >+ <ChevronRightIcon+ className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${+ project.expanded ? "rotate-90" : ""}`}- onClick={() => {- void navigate({- to: "/$threadId",- params: { threadId: thread.id },- });- }}- onContextMenu={(e) => {- e.preventDefault();- void handleThreadContextMenu(thread.id, {- x: e.clientX,- y: e.clientY,- });- }}- >- <div className="flex min-w-0 flex-1 items-center gap-1.5">- {threadStatus && (- <span- className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}- >- <span- className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${- threadStatus.pulse ? "animate-pulse" : ""+ />+ <ProjectFavicon cwd={project.cwd} />+ <span className="flex-1 truncate text-xs font-medium text-foreground/90">+ {project.name}+ </span>+ <span className="text-[10px] text-muted-foreground/60">{threads.length}</span>+ </CollapsibleTrigger>++ <CollapsibleContent>+ <SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">+ {threads.map((thread) => {+ const isActive = routeThreadId === thread.id;+ const threadStatus = threadStatusPill(+ thread,+ pendingApprovalByThreadId.get(thread.id) === true,+ );++ const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);+ const terminalStatus = terminalStatusIndicator(thread);++ return (+ <SidebarMenuSubItem key={thread.id} className="w-full">+ <SidebarMenuSubButton+ render={<button type="button" />}+ size="sm"+ isActive={isActive}+ className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${+ isActive+ ? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"+ : "text-muted-foreground"}`}- />- <span className="hidden md:inline">{threadStatus.label}</span>- </span>- )}- <span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>- </div>- <div className="ml-2 flex shrink-0 items-center gap-1.5">- {prStatus && (- <span- role="img"- aria-label={prStatus.label}- title={prStatus.label}- className={`inline-flex items-center justify-center ${prStatus.colorClass}`}- >- <GitPullRequestIcon className="size-3" />- </span>- )}- {terminalStatus && (- <span- role="img"- aria-label={terminalStatus.label}- title={terminalStatus.label}- className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}- >- <TerminalIcon- className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}- />- </span>- )}- <span className="text-[10px] text-muted-foreground/40">- {formatRelativeTime(thread.createdAt)}- </span>- </div>- </button>- );- })}-- {/* New thread within project */}- <button- type="button"- className="flex w-full items-center gap-1 px-2 py-1 text-[10px] text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground/80"- onClick={() => handleNewThread(project.id)}- >- <span>+</span> New thread- </button>- </div>- )}+ onClick={() => {+ void navigate({+ to: "/$threadId",+ params: { threadId: thread.id },+ });+ }}+ onContextMenu={(event) => {+ event.preventDefault();+ void handleThreadContextMenu(thread.id, {+ x: event.clientX,+ y: event.clientY,+ });+ }}+ >+ <div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">+ {threadStatus && (+ <span+ className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}+ >+ <span+ className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${+ threadStatus.pulse ? "animate-pulse" : ""+ }`}+ />+ <span className="hidden md:inline">{threadStatus.label}</span>+ </span>+ )}+ <span className="min-w-0 flex-1 truncate text-xs">+ {thread.title}+ </span>+ </div>+ <div className="ml-auto flex shrink-0 items-center gap-1.5">++ {prStatus && (++ <span++ role="img"++ aria-label={prStatus.label}++ title={prStatus.label}++ className={`inline-flex items-center justify-center ${prStatus.colorClass}`}++ >++ <GitPullRequestIcon className="size-3" />++ </span>++ )}+ {terminalStatus && (+ <span+ role="img"+ aria-label={terminalStatus.label}+ title={terminalStatus.label}+ className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}+ >+ <TerminalIcon+ className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}+ />+ </span>+ )}+ <span+ className={`text-[10px] ${+ isActive ? "text-foreground/65" : "text-muted-foreground/40"+ }`}+ >+ {formatRelativeTime(thread.createdAt)}+ </span>+ </div>+ </SidebarMenuSubButton>+ </SidebarMenuSubItem>+ );+ })}++ <SidebarMenuSubItem className="w-full">+ <SidebarMenuSubButton+ render={<button type="button" />}+ size="sm"+ className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"+ onClick={() => {+ void handleNewThread(project.id);+ }}+ >+ <span>+</span>+ <span>New thread</span>+ </SidebarMenuSubButton>+ </SidebarMenuSubItem>+ </SidebarMenuSub>+ </CollapsibleContent>+ </SidebarMenuItem>+ </Collapsible>+ );+ })}+ </SidebarMenu>++ {state.projects.length === 0 && !addingProject && (+ <div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">+ No projects yet.+ <br />+ Add one to get started.</div>- );- })}-- {state.projects.length === 0 && !addingProject && (- <div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">- No projects yet.- <br />- Add one to get started.- </div>- )}- </nav>-- {/* Add project form */}- {addingProject ? (- <div className="border-t border-border p-3">- <p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">- Add project- </p>- <input- className="mb-2 w-full rounded-md border border-border bg-secondary px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:border-ring focus:outline-none"- placeholder="/path/to/project"- value={newCwd}- onChange={(e) => setNewCwd(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") handleAddProject();- if (e.key === "Escape") setAddingProject(false);- }}- />- {isElectron && api && (- <button- type="button"- className="mb-2 flex w-full items-center justify-center rounded-md border border-border px-2 py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60"- onClick={() => void handlePickFolder()}- disabled={isPickingFolder || isAddingProject}- >- {isPickingFolder ? "Picking folder..." : "Browse for folder"}- </button>)}- <div className="flex gap-2">- <button- type="button"- className="flex-1 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90"- onClick={handleAddProject}- disabled={isAddingProject}- >- {isAddingProject ? "Adding..." : "Add"}- </button>- <button- type="button"- className="flex-1 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground/80 transition-colors duration-150 hover:bg-secondary"- onClick={() => setAddingProject(false)}- >- Cancel- </button>- </div>- </div>- ) : (- <div className="border-t border-border p-3">+ </SidebarGroup>+ </SidebarContent>++ <SidebarSeparator />+ <SidebarFooter className="gap-0 p-3">+ {addingProject ? (+ <>+ <p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">+ Add project+ </p>+ <input+ className="mb-2 w-full rounded-md border border-border bg-secondary px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:border-ring focus:outline-none"+ placeholder="/path/to/project"+ value={newCwd}+ onChange={(event) => setNewCwd(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") handleAddProject();+ if (event.key === "Escape") setAddingProject(false);+ }}+ />+ {isElectron && (+ <button+ type="button"+ className="mb-2 flex w-full items-center justify-center rounded-md border border-border px-2 py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60"+ onClick={() => void handlePickFolder()}+ disabled={isPickingFolder || isAddingProject}+ >+ {isPickingFolder ? "Picking folder..." : "Browse for folder"}+ </button>+ )}+ <div className="flex gap-2">+ <button+ type="button"+ className="flex-1 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90"+ onClick={handleAddProject}+ disabled={isAddingProject}+ >+ {isAddingProject ? "Adding..." : "Add"}+ </button>+ <button+ type="button"+ className="flex-1 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground/80 transition-colors duration-150 hover:bg-secondary"+ onClick={() => setAddingProject(false)}+ >+ Cancel+ </button>+ </div>+ </>+ ) : (<buttontype="button"className="flex w-full items-center justify-center gap-1 rounded-md border border-dashed border-border py-2 text-xs text-muted-foreground/70 transition-colors duration-150 hover:border-ring hover:text-muted-foreground"diff --cc packages/contracts/src/git.tsindex 08a5f4739,7ac616aff..22d8ae9c6--- a/packages/contracts/src/git.ts+++ b/packages/contracts/src/git.ts@@@ -1,157 -1,163 +1,167 @@@- import { z } from "zod";-- // ── Existing branch/worktree Git API ─────────────────────────────────-- export const gitListBranchesInputSchema = z.object({- cwd: z.string().min(1),+ import { Schema } from "effect";+ import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas";++ const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;++ // Domain Types++ export const GitStackedAction = Schema.Literals(["commit", "commit_push", "commit_push_pr"]);+ export type GitStackedAction = typeof GitStackedAction.Type;+ export const GitCommitStepStatus = Schema.Literals(["created", "skipped_no_changes"]);+ export const GitPushStepStatus = Schema.Literals([+ "pushed",+ "skipped_not_requested",+ "skipped_up_to_date",+ ]);+ export const GitPrStepStatus = Schema.Literals([+ "created",+ "opened_existing",+ "skipped_not_requested",+ ]);++export const GitStatusPrState = Schema.Literals(["open", "closed", "merged"]);++export type GitStatusPrState = typeof GitStatusPrState.Type;++ export const GitBranch = Schema.Struct({+ name: TrimmedNonEmptyStringSchema,+ current: Schema.Boolean,+ isDefault: Schema.Boolean,+ worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),});+ export type GitBranch = typeof GitBranch.Type;- export const gitCreateWorktreeInputSchema = z.object({- cwd: z.string().min(1),- branch: z.string().min(1),- newBranch: z.string().min(1),- path: z.string().min(1).optional(),+ export const GitWorktree = Schema.Struct({+ path: TrimmedNonEmptyStringSchema,+ branch: TrimmedNonEmptyStringSchema,});+ export type GitWorktree = typeof GitWorktree.Type;- export const gitRemoveWorktreeInputSchema = z.object({- cwd: z.string().min(1),- path: z.string().min(1),- force: z.boolean().optional(),- });+ // RPC Inputs- export const gitCreateBranchInputSchema = z.object({- cwd: z.string().min(1),- branch: z.string().min(1),+ export const GitStatusInput = Schema.Struct({+ cwd: TrimmedNonEmptyStringSchema,});+ export type GitStatusInput = typeof GitStatusInput.Type;- export const gitCheckoutInputSchema = z.object({- cwd: z.string().min(1),- branch: z.string().min(1),+ export const GitPullInput = Schema.Struct({+ cwd: TrimmedNonEmptyStringSchema,});+ export type GitPullInput = typeof GitPullInput.Type;- export const gitInitInputSchema = z.object({- cwd: z.string().min(1),+ export const GitRunStackedActionInput = Schema.Struct({+ cwd: TrimmedNonEmptyStringSchema,+ action: GitStackedAction,+ commitMessage: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(10_000))),});+ export type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;- export const gitBranchSchema = z.object({- name: z.string().min(1),- current: z.boolean(),- isDefault: z.boolean(),- worktreePath: z.string().min(1).nullable(),+ export const GitListBranchesInput = Schema.Struct({+ cwd: TrimmedNonEmptyStringSchema,});+ export type GitListBranchesInput = typeof GitListBranchesInput.Type;- export const gitWorktreeSchema = z.object({- path: z.string().min(1),- branch: z.string().min(1),+ export const GitCreateWorktreeInput = Schema.Struct({+ cwd: TrimmedNonEmptyStringSchema,+ branch: TrimmedNonEmptyStringSchema,+ newBranch: TrimmedNonEmptyStringSchema,+ path: Schema.NullOr(TrimmedNonEmptyStringSchema),});+ export type GitCreateWorktreeInput = typeof GitCreateWorktreeInput.Type;- export type GitListBranchesInput = z.infer<typeof gitListBranchesInputSchema>;- export type GitBranch = z.infer<typeof gitBranchSchema>;- export type GitCreateWorktreeInput = z.infer<typeof gitCreateWorktreeInputSchema>;- export type GitWorktree = z.infer<typeof gitWorktreeSchema>;- export type GitRemoveWorktreeInput = z.infer<typeof gitRemoveWorktreeInputSchema>;- export type GitCreateBranchInput = z.infer<typeof gitCreateBranchInputSchema>;- export type GitCheckoutInput = z.infer<typeof gitCheckoutInputSchema>;- export type GitInitInput = z.infer<typeof gitInitInputSchema>;-- export interface GitListBranchesResult {- branches: GitBranch[];- isRepo: boolean;- }-- export interface GitCreateWorktreeResult {- worktree: GitWorktree;- }+ export const GitRemoveWorktreeInput = Schema.Struct({+ cwd: TrimmedNonEmptyStringSchema,+ path: TrimmedNonEmptyStringSchema,+ force: Schema.optional(Schema.Boolean),+ });+ export type GitRemoveWorktreeInput = typeof GitRemoveWorktreeInput.Type;- // ── Stacked action Git API ───────────────────────────────────────────+ export const GitCreateBranchInput = Schema.Struct({+ cwd: TrimmedNonEmptyStringSchema,+ branch: TrimmedNonEmptyStringSchema,+ });+ export type GitCreateBranchInput = typeof GitCreateBranchInput.Type;- export const gitStatusInputSchema = z.object({- cwd: z.string().trim().min(1),+ export const GitCheckoutInput = Schema.Struct({+ cwd: TrimmedNonEmptyStringSchema,+ branch: TrimmedNonEmptyStringSchema,});+ export type GitCheckoutInput = typeof GitCheckoutInput.Type;- export const gitPullInputSchema = z.object({- cwd: z.string().trim().min(1),+ export const GitInitInput = Schema.Struct({+ cwd: TrimmedNonEmptyStringSchema,});+ export type GitInitInput = typeof GitInitInput.Type;- export const gitStatusPrStateSchema = z.enum(["open", "closed", "merged"]);+ // RPC Results- export const gitStatusPrSchema = z.object({- number: z.number().int().positive(),- title: z.string().min(1),- url: z.string().url(),- baseBranch: z.string().min(1),- headBranch: z.string().min(1),- state: gitStatusPrStateSchema,++export const GitStatusPr = Schema.Struct({++ number: PositiveInt,++ title: TrimmedNonEmptyStringSchema,++ url: Schema.String,++ baseBranch: TrimmedNonEmptyStringSchema,++ headBranch: TrimmedNonEmptyStringSchema,++ state: GitStatusPrState,+});-- export const gitStatusResultSchema = z.object({- branch: z.string().min(1).nullable(),- hasWorkingTreeChanges: z.boolean(),- workingTree: z.object({- files: z.array(- z.object({- path: z.string().min(1),- insertions: z.number().int().nonnegative(),- deletions: z.number().int().nonnegative(),++export type GitStatusPr = typeof GitStatusPr.Type;+++ export const GitStatusResult = Schema.Struct({+ branch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),+ hasWorkingTreeChanges: Schema.Boolean,+ workingTree: Schema.Struct({+ files: Schema.Array(+ Schema.Struct({+ path: TrimmedNonEmptyStringSchema,+ insertions: NonNegativeInt,+ deletions: NonNegativeInt,}),),- insertions: z.number().int().nonnegative(),- deletions: z.number().int().nonnegative(),+ insertions: NonNegativeInt,+ deletions: NonNegativeInt,}),- hasUpstream: z.boolean(),- aheadCount: z.number().int().nonnegative(),- behindCount: z.number().int().nonnegative(),- pr: gitStatusPrSchema.nullable(),+ hasUpstream: Schema.Boolean,+ aheadCount: NonNegativeInt,+ behindCount: NonNegativeInt,- openPr: Schema.NullOr(- Schema.Struct({- number: PositiveInt,- title: TrimmedNonEmptyStringSchema,- url: Schema.String,- baseBranch: TrimmedNonEmptyStringSchema,- headBranch: TrimmedNonEmptyStringSchema,- }),- ),++ pr: Schema.NullOr(GitStatusPr),});+ export type GitStatusResult = typeof GitStatusResult.Type;- export const gitStackedActionSchema = z.enum(["commit", "commit_push", "commit_push_pr"]);-- const gitCommitStepStatusSchema = z.enum(["created", "skipped_no_changes"]);- const gitPushStepStatusSchema = z.enum(["pushed", "skipped_not_requested", "skipped_up_to_date"]);- const gitPrStepStatusSchema = z.enum(["created", "opened_existing", "skipped_not_requested"]);-- export const gitRunStackedActionInputSchema = z.object({- cwd: z.string().trim().min(1),- action: gitStackedActionSchema,- commitMessage: z.string().trim().min(1).max(10_000).optional(),+ export const GitListBranchesResult = Schema.Struct({+ branches: Schema.Array(GitBranch),+ isRepo: Schema.Boolean,});+ export type GitListBranchesResult = typeof GitListBranchesResult.Type;- export const gitRunStackedActionResultSchema = z.object({- action: gitStackedActionSchema,- commit: z.object({- status: gitCommitStepStatusSchema,- commitSha: z.string().min(1).optional(),- subject: z.string().min(1).optional(),+ export const GitCreateWorktreeResult = Schema.Struct({+ worktree: GitWorktree,+ });+ export type GitCreateWorktreeResult = typeof GitCreateWorktreeResult.Type;++ export const GitRunStackedActionResult = Schema.Struct({+ action: GitStackedAction,+ commit: Schema.Struct({+ status: GitCommitStepStatus,+ commitSha: Schema.optional(TrimmedNonEmptyStringSchema),+ subject: Schema.optional(TrimmedNonEmptyStringSchema),}),- push: z.object({- status: gitPushStepStatusSchema,- branch: z.string().min(1).optional(),- upstreamBranch: z.string().min(1).optional(),- setUpstream: z.boolean().optional(),+ push: Schema.Struct({+ status: GitPushStepStatus,+ branch: Schema.optional(TrimmedNonEmptyStringSchema),+ upstreamBranch: Schema.optional(TrimmedNonEmptyStringSchema),+ setUpstream: Schema.optional(Schema.Boolean),}),- pr: z.object({- status: gitPrStepStatusSchema,- url: z.string().url().optional(),- number: z.number().int().positive().optional(),- baseBranch: z.string().min(1).optional(),- headBranch: z.string().min(1).optional(),- title: z.string().min(1).optional(),+ pr: Schema.Struct({+ status: GitPrStepStatus,+ url: Schema.optional(Schema.String),+ number: Schema.optional(PositiveInt),+ baseBranch: Schema.optional(TrimmedNonEmptyStringSchema),+ headBranch: Schema.optional(TrimmedNonEmptyStringSchema),+ title: Schema.optional(TrimmedNonEmptyStringSchema),}),});+ export type GitRunStackedActionResult = typeof GitRunStackedActionResult.Type;- export type GitStatusInput = z.input<typeof gitStatusInputSchema>;- export type GitPullInput = z.input<typeof gitPullInputSchema>;- export type GitStatusPrState = z.infer<typeof gitStatusPrStateSchema>;- export type GitStatusPr = z.infer<typeof gitStatusPrSchema>;- export type GitStatusResult = z.infer<typeof gitStatusResultSchema>;- export type GitStackedAction = z.infer<typeof gitStackedActionSchema>;- export type GitRunStackedActionInput = z.input<typeof gitRunStackedActionInputSchema>;- export type GitRunStackedActionResult = z.infer<typeof gitRunStackedActionResultSchema>;-- export const gitPullResultSchema = z.object({- status: z.enum(["pulled", "skipped_up_to_date"]),- branch: z.string().min(1),- upstreamBranch: z.string().min(1).optional(),+ export const GitPullResult = Schema.Struct({+ status: Schema.Literals(["pulled", "skipped_up_to_date"]),+ branch: TrimmedNonEmptyStringSchema,+ upstreamBranch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),});-- export type GitPullResult = z.infer<typeof gitPullResultSchema>;+ export type GitPullResult = typeof GitPullResult.Type;