feat(git): extend source control with worktrees, stashes, conflicts and identities

- Create a worktree from a new or existing branch
- Integrate a worktree branch into a target branch by merge commit or cherry-pick, with continue/abort on conflicts
- Delete a worktree with keep, delete-local, or delete-local-and-remote branch options, using safe branch deletion for unmerged branches
- Add a stash tab (list, push, apply, pop, drop) shared across a repository and its worktrees
- Rename and delete branches, optionally deleting the remote branch and updating scheduled base branches
- Detect in-progress merge, rebase, cherry-pick and revert operations and hand conflicts to an agent session
- Generate commit messages from staged changes with the default model
- Add a default git identity and saved per-repository identities written to git config
- Unify git error mapping behind a typed error and one route helper; consolidate git mutations and cache invalidation
- Update repository docs
This commit is contained in:
Chris Scott committed 2026-10-03 21:59:00 -04:00
1 parent 52b6147ed3
commit 53238a6324
89 files changed
+7704 -793

No files matched your search

+8 -3
View File
@@ -1,5 +1,8 @@
import type { GitCredential } from '@opencode-manager/shared'
import { githubFetch } from './github'
import { logger } from './logger'
const GITHUB_USER_INFO_TIMEOUT_MS = 10_000
export function isGitHubHttpsUrl(repoUrl: string): boolean {
const url = normalizeGitCredentialUrl(repoUrl)
@@ -210,9 +213,10 @@ export function createGitIdentityEnv(identity: GitIdentity): Record<string, stri
export async function fetchGitHubUserInfo(token: string): Promise<GitHubUserInfo | null> {
try {
const signal = AbortSignal.timeout(GITHUB_USER_INFO_TIMEOUT_MS)
const [userResponse, emailsResponse] = await Promise.all([
githubFetch('https://api.github.com/user', { token, apiVersion: '2022-11-28' }),
githubFetch('https://api.github.com/user/emails', { token, apiVersion: '2022-11-28' }),
githubFetch('https://api.github.com/user', { token, apiVersion: '2022-11-28', signal }),
githubFetch('https://api.github.com/user/emails', { token, apiVersion: '2022-11-28', signal }),
])
if (!userResponse.ok) return null
@@ -236,7 +240,8 @@ export async function fetchGitHubUserInfo(token: string): Promise<GitHubUserInfo
email,
login: data.login
}
} catch {
} catch (error) {
logger.warn(`Failed to fetch GitHub user info, falling back to the manual git identity: ${error instanceof Error ? error.message : String(error)}`)
return null
}
}
+85 -3
View File
@@ -12,9 +12,15 @@ export function isNoUpstreamError(error: Error): boolean {
return patterns.some(pattern => pattern.test(error.message))
}
export function parseBranchNameFromError(error: Error): string | null {
const match = error.message.match(/The current branch (.+) has no upstream branch/i)
return match?.[1]?.trim() ?? null
export class GitOperationError extends Error {
constructor(
readonly code: GitErrorCode,
message?: string,
readonly details?: Record<string, unknown>
) {
super(message)
this.name = 'GitOperationError'
}
}
export interface GitErrorInfo {
@@ -22,6 +28,7 @@ export interface GitErrorInfo {
summary: string
detail: string
statusCode: number
details?: Record<string, unknown>
}
interface ErrorPattern {
@@ -154,6 +161,34 @@ const ERROR_PATTERNS: ErrorPattern[] = [
/reference.*not found/i,
],
},
{
code: 'BRANCH_CHECKED_OUT',
summary: 'This branch is currently checked out and cannot be deleted.',
statusCode: 409,
patterns: [
/cannot delete branch .*checked out/i,
],
},
{
code: 'BRANCH_IN_OTHER_WORKTREE',
summary: 'This branch is checked out in another worktree and cannot be modified here.',
statusCode: 409,
patterns: [],
},
{
code: 'BRANCH_NOT_MERGED',
summary: 'This branch has unmerged commits. Merge it or delete it with force.',
statusCode: 409,
patterns: [
/is not fully merged/i,
],
},
{
code: 'STASH_CHANGED',
summary: 'The stash list changed. Refresh and try again.',
statusCode: 409,
patterns: [],
},
{
code: 'UNCOMMITTED_CHANGES',
summary: 'You have uncommitted changes. Commit or stash them first.',
@@ -164,6 +199,42 @@ const ERROR_PATTERNS: ErrorPattern[] = [
/would lose uncommitted changes/i,
],
},
{
code: 'NO_OPERATION_IN_PROGRESS',
summary: 'No merge, rebase, cherry-pick, or revert is in progress.',
statusCode: 409,
patterns: [],
},
{
code: 'INTEGRATE_DETACHED_HEAD',
summary: 'Cannot integrate from a detached HEAD',
statusCode: 400,
patterns: [],
},
{
code: 'INTEGRATE_INTO_SELF',
summary: 'Cannot integrate a branch into itself',
statusCode: 400,
patterns: [],
},
{
code: 'INTEGRATE_TARGET_NOT_CHECKED_OUT',
summary: 'Target branch is not checked out in any worktree',
statusCode: 409,
patterns: [],
},
{
code: 'INTEGRATE_TARGET_NOT_MANAGED',
summary: 'Target checkout is not a managed repository',
statusCode: 409,
patterns: [],
},
{
code: 'INTEGRATE_NOTHING_TO_INTEGRATE',
summary: 'Nothing to integrate',
statusCode: 400,
patterns: [],
},
]
function stripCommandFailedPrefix(message: string): string {
@@ -194,6 +265,17 @@ export function parseGitError(error: unknown): GitErrorInfo {
const message = stripCommandFailedPrefix(rawMessage)
const cleanedMessage = cleanGitProgressLines(message)
if (error instanceof GitOperationError) {
const entry = ERROR_PATTERNS.find((errorPattern) => errorPattern.code === error.code)
return {
code: error.code,
summary: entry?.summary ?? 'A git operation failed.',
detail: cleanedMessage || message,
statusCode: entry?.statusCode ?? 500,
...(error.details ? { details: error.details } : {}),
}
}
for (const errorPattern of ERROR_PATTERNS) {
for (const pattern of errorPattern.patterns) {
if (pattern.test(message) || pattern.test(cleanedMessage)) {
+2 -1
View File
@@ -4,6 +4,7 @@ interface GithubRequestOptions {
token?: string
apiVersion?: string
accept?: string
signal?: AbortSignal
}
export function githubFetch(
@@ -17,7 +18,7 @@ export function githubFetch(
}
if (options.token) headers.Authorization = `Bearer ${options.token}`
if (options.apiVersion) headers['X-GitHub-Api-Version'] = options.apiVersion
return fetchFn(url, { headers })
return fetchFn(url, { headers, signal: options.signal })
}
export async function githubFetchJson<T = unknown>(
+18 -1
View File
@@ -7,6 +7,7 @@ interface ExecuteCommandOptions {
env?: Record<string, string>
ignoreExitCode?: boolean
timeout?: number
maxOutputChars?: number
}
export async function executeCommand(
@@ -50,6 +51,7 @@ export async function executeCommand(
let stdout = ''
let stderr = ''
let isResolved = false
let outputCapped = false
const timeoutId = options.timeout ? setTimeout(() => {
if (!isResolved) {
@@ -60,7 +62,14 @@ export async function executeCommand(
}, options.timeout) : undefined
proc.stdout?.on('data', (data: Buffer) => {
if (outputCapped) return
stdout += data.toString()
if (options.maxOutputChars !== undefined && stdout.length > options.maxOutputChars) {
outputCapped = true
stdout = stdout.slice(0, options.maxOutputChars)
proc.kill('SIGKILL')
}
})
proc.stderr?.on('data', (data: Buffer) => {
@@ -88,7 +97,15 @@ export async function executeCommand(
const exitCode = code === null ? 1 : code
const failureDetail = terminatedBySignal ? `signal ${signal}` : `code ${code}`
if (options.ignoreExitCode) {
if (outputCapped) {
resolve(options.ignoreExitCode
? {
exitCode,
stdout,
stderr: terminatedBySignal ? `${stderr}Command terminated by signal ${signal}` : stderr,
}
: stdout)
} else if (options.ignoreExitCode) {
resolve({
exitCode,
stdout,
+34
View File
@@ -3,6 +3,7 @@ import type { ContentfulStatusCode } from 'hono/utils/http-status'
import { ClientError, openCodeErrorStatus } from '@opencode-manager/shared/opencode'
import { isOAuthErrorCode } from '@opencode-manager/shared/schemas'
import { getErrorMessage } from './error-utils'
import { parseGitError } from './git-errors'
import { logger } from './logger'
export function parseId(value: string | undefined, label?: string, ErrorClass?: new (message: string, status: number) => Error): number {
@@ -43,6 +44,39 @@ export function handleServiceError(
return c.json({ error: getErrorMessage(error) }, 500)
}
export function respondWithGitError(c: Context, error: unknown, logMessage: string) {
logger.error(logMessage, error)
const gitError = parseGitError(error)
return c.json(
{
error: gitError.summary,
detail: gitError.detail,
code: gitError.code,
...(gitError.details ? { details: gitError.details } : {}),
},
gitError.statusCode as ContentfulStatusCode
)
}
interface JsonBodySchema<T> {
safeParse(data: unknown): { success: true; data: T } | { success: false; error: { issues: Array<{ message?: string }> } }
}
export async function parseJsonBody<T>(c: Context, schema: JsonBodySchema<T>): Promise<T | Response> {
let body: unknown
try {
body = await c.req.json()
} catch {
return c.json({ error: 'Invalid JSON' }, 400)
}
const parsed = schema.safeParse(body)
if (!parsed.success) {
return c.json({ error: parsed.error.issues[0]?.message || 'Invalid request' }, 400)
}
return parsed.data
}
export function handleOpenCodeError(c: Context, error: unknown, fallback: string) {
if (error instanceof Error) {
const tag = (error as { _tag?: unknown })._tag