mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(walkthrough): plan-then-explain generation with selectable diff sources
This commit is contained in:
1 parent
aeea96b466
commit
88b3543dc1
35 files changed
+2583
-609
No files matched your search
@@ -244,7 +244,8 @@ const terminalService = new TerminalService(
|
||||
new CredentialProvider(db),
|
||||
() => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()),
|
||||
)
|
||||
const projectConfigService = new ProjectConfigService(db, createGitService(gitAuthService), gitAuthService)
|
||||
const gitService = createGitService(gitAuthService)
|
||||
const projectConfigService = new ProjectConfigService(db, gitService, gitAuthService)
|
||||
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager)
|
||||
scheduleService.setWorktreeRemovedHandler(async (directory) => {
|
||||
@@ -272,7 +273,7 @@ const sessionGoalService = new SessionGoalService(db, openCodeClient, sessionSet
|
||||
sessionGoalService.loadOpenGoals()
|
||||
|
||||
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService)
|
||||
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService)
|
||||
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService, gitService)
|
||||
|
||||
sseAggregator.onEvent((directory, event) => {
|
||||
sessionPermissionModeService.handleEvent(directory, event).catch((err) => {
|
||||
|
||||
@@ -19,7 +19,8 @@ export function createChangeWalkthroughRoutes(service: ChangeWalkthroughService)
|
||||
}
|
||||
|
||||
try {
|
||||
const state = await service.getState(c.req.param('sessionId'), source)
|
||||
const hunksFor = c.req.query('hunksFor')
|
||||
const state = await service.getState(c.req.param('sessionId'), source, hunksFor)
|
||||
return c.json(state)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to read change walkthrough', ServiceError)
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
fileExists,
|
||||
ensureDirectoryExists,
|
||||
} from './file-operations'
|
||||
import { ASSISTANT_NOTIFICATION_LIMITS, OpenCodeConfigSchema, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_NOTIFICATION_LIMITS, AssistantSettingsPatchSchema, OpenCodeConfigSchema, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@opencode-manager/shared/schemas'
|
||||
import { MANAGER_COLOR_THEME_ID, OPENCODE_THEMES } from '@opencode-manager/shared/themes'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME } from '@opencode-manager/shared/utils'
|
||||
import { getAssistantModePath, getReposPath } from '@opencode-manager/shared/config/env'
|
||||
@@ -581,6 +581,23 @@ Sending is rate limited to **10 notifications per minute**. Beyond that the tool
|
||||
`
|
||||
}
|
||||
|
||||
type AssistantSettingsKey = keyof typeof AssistantSettingsPatchSchema.shape
|
||||
|
||||
const ASSISTANT_SETTINGS_KEY_NOTES: Partial<Record<AssistantSettingsKey, string>> = {
|
||||
tts: 'Non-secret TTS preferences (`enabled`, `provider`, `autoPlay`, `voice`, `model`, `speed`). TTS must already be configured in the UI (the endpoint returns 400 otherwise).',
|
||||
stt: 'Non-secret STT preferences (`enabled`, `provider`, `model`, `language`). STT must already be configured in the UI (the endpoint returns 400 otherwise).',
|
||||
}
|
||||
|
||||
function buildAllowedSettingsKeysList(): string {
|
||||
const keys = Object.keys(AssistantSettingsPatchSchema.shape) as AssistantSettingsKey[]
|
||||
return keys
|
||||
.map((key) => {
|
||||
const note = ASSISTANT_SETTINGS_KEY_NOTES[key]
|
||||
return note === undefined ? `- \`${key}\`` : `- \`${key}\` — ${note}`
|
||||
})
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
export function buildSettingsSkill(): string {
|
||||
return `---
|
||||
name: manager-settings
|
||||
@@ -660,13 +677,7 @@ Update a subset of safe user preferences.
|
||||
|
||||
**Allowed Keys:**
|
||||
The following preference keys can be modified:
|
||||
- \`theme\`, \`colorTheme\`, \`mode\`, \`defaultModel\`, \`defaultAgent\`
|
||||
- \`autoScroll\`, \`expandDiffs\`, \`expandToolCalls\`, \`showReasoning\`
|
||||
- \`simpleChatMode\`, \`leaderKey\`, \`directShortcuts\`
|
||||
- \`keyboardShortcuts\`, \`customCommands\`, \`notifications\`
|
||||
- \`repoOrder\`, \`repoSortMode\`
|
||||
- \`tts\` — Non-secret TTS preferences (\`enabled\`, \`provider\`, \`autoPlay\`, \`voice\`, \`model\`, \`speed\`). TTS must already be configured in the UI (the endpoint returns 400 otherwise).
|
||||
- \`stt\` — Non-secret STT preferences (\`enabled\`, \`provider\`, \`model\`, \`language\`). STT must already be configured in the UI (the endpoint returns 400 otherwise).
|
||||
${buildAllowedSettingsKeysList()}
|
||||
|
||||
**DO NOT attempt to set:**
|
||||
- \`gitCredentials\` - Git credentials must be managed via the full UI
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -738,6 +738,26 @@ export class GitService {
|
||||
)
|
||||
}
|
||||
|
||||
async fetchRemoteRef(
|
||||
repo: { id?: number; repoUrl?: string; fullPath: string },
|
||||
remote: string,
|
||||
refspec: string,
|
||||
database: Database,
|
||||
timeoutMs?: number,
|
||||
): Promise<void> {
|
||||
await this.withRemoteAuth(
|
||||
repo,
|
||||
async (env) => {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'fetch', '--no-tags', remote, refspec], {
|
||||
env,
|
||||
silent: true,
|
||||
timeout: timeoutMs,
|
||||
})
|
||||
},
|
||||
{ database, silent: true }
|
||||
)
|
||||
}
|
||||
|
||||
async pull(repoId: number, database: Database): Promise<string> {
|
||||
const repo = getRepoById(database, repoId)
|
||||
if (!repo) {
|
||||
|
||||
@@ -1019,6 +1019,18 @@ export async function resolveDefaultBranch(repoPath: string, env: Record<string,
|
||||
.catch(() => 'main')
|
||||
}
|
||||
|
||||
export async function resolveBaseRef(repoPath: string, base: string, env: Record<string, string>): Promise<string | null> {
|
||||
for (const candidate of [`refs/remotes/origin/${base}`, `refs/heads/${base}`]) {
|
||||
try {
|
||||
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', candidate], { env, silent: true })
|
||||
return candidate.startsWith('refs/remotes/') ? `origin/${base}` : base
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export async function removeWorktree(
|
||||
baseRepoPath: string,
|
||||
worktreePath: string,
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { Repo } from '../types/repo'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
import { isSSHUrl } from '@opencode-manager/shared/utils'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { resolveDefaultBranch, createWorktreeSafely, listGitWorktrees, removeWorktree } from './repo'
|
||||
import { resolveDefaultBranch, resolveBaseRef, createWorktreeSafely, listGitWorktrees, removeWorktree } from './repo'
|
||||
import { logger } from '../utils/logger'
|
||||
import { canonicalPathSync, mkdirSyncSafe } from '../utils/fs-safe'
|
||||
import {
|
||||
@@ -95,7 +95,7 @@ export class ScheduleWorktreeManager {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'fetch', '--prune', 'origin'], { env }).catch(() => {})
|
||||
|
||||
const base = job.branch?.trim() || (await resolveDefaultBranch(repo.fullPath, env))
|
||||
const baseRef = await this.resolveBaseRef(repo.fullPath, base, env)
|
||||
const baseRef = await resolveBaseRef(repo.fullPath, base, env)
|
||||
if (!baseRef) {
|
||||
throw new Error(`Base branch "${base}" was not found in this repository. Choose an existing branch in the schedule settings.`)
|
||||
}
|
||||
@@ -319,24 +319,6 @@ export class ScheduleWorktreeManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a user-supplied base branch name to a verified git ref, preferring
|
||||
* the remote-tracking branch for freshness. Returns null when neither the
|
||||
* remote nor local ref exists, allowing the caller to fail with a clear error
|
||||
* instead of a cryptic git "not a valid object name" failure.
|
||||
*/
|
||||
private async resolveBaseRef(repoPath: string, base: string, env: Record<string, string>): Promise<string | null> {
|
||||
for (const candidate of [`refs/remotes/origin/${base}`, `refs/heads/${base}`]) {
|
||||
try {
|
||||
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', candidate], { env, silent: true })
|
||||
return candidate.startsWith('refs/remotes/') ? `origin/${base}` : base
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private async buildGitEnv(repo: Repo, sshSetup: boolean, silent: boolean): Promise<Record<string, string>> {
|
||||
const baseEnv = this.gitAuthService.getGitEnvironment(silent)
|
||||
const sshEnv = sshSetup ? this.gitAuthService.getSSHEnvironment() : {}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from 'zod'
|
||||
import { SessionGoalVerdictSchema, type SessionGoalVerdict } from '@opencode-manager/shared/schemas'
|
||||
import { extractFirstJsonObject } from '../utils/json-extract'
|
||||
import { parseFirstJsonObject } from '../utils/json-extract'
|
||||
import { truncateSessionReply } from './session-reply'
|
||||
|
||||
export const GOAL_AUDIT_REASON_MAX_CHARS = 500
|
||||
@@ -51,39 +52,23 @@ export function buildGoalContinuationPrompt({ objective, reason }: GoalContinuat
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
const goalVerdictSchema = z.object({
|
||||
verdict: SessionGoalVerdictSchema,
|
||||
reason: z.string(),
|
||||
})
|
||||
|
||||
export function parseGoalVerdict(text: string): GoalVerdict | null {
|
||||
const block = extractFirstJsonObject(text)
|
||||
if (!block) {
|
||||
const parsed = parseFirstJsonObject(text, goalVerdictSchema)
|
||||
if (!parsed) {
|
||||
return null
|
||||
}
|
||||
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(block)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
if (typeof parsed !== 'object' || parsed === null) {
|
||||
return null
|
||||
}
|
||||
|
||||
const candidate = parsed as { verdict?: unknown; reason?: unknown }
|
||||
const verdict = SessionGoalVerdictSchema.safeParse(candidate.verdict)
|
||||
if (!verdict.success) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (typeof candidate.reason !== 'string') {
|
||||
return null
|
||||
}
|
||||
|
||||
const reason = candidate.reason.trim()
|
||||
const reason = parsed.reason.trim()
|
||||
if (!reason) {
|
||||
return null
|
||||
}
|
||||
|
||||
return { verdict: verdict.data, reason: reason.slice(0, GOAL_AUDIT_REASON_MAX_CHARS) }
|
||||
return { verdict: parsed.verdict, reason: reason.slice(0, GOAL_AUDIT_REASON_MAX_CHARS) }
|
||||
}
|
||||
|
||||
function truncateReply(reply: string | null): string {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { copyFileSync, existsSync, mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import type { FileDiffInfo, SessionInfo } from '@opencode-manager/shared/opencode'
|
||||
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
|
||||
import { splitUnifiedDiffByFile } from '@opencode-manager/shared/utils'
|
||||
@@ -5,6 +8,7 @@ import { getErrorMessage } from '../utils/error-utils'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { ChangeWalkthroughError } from './change-walkthrough-error'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { resolveBaseRef, resolveDefaultBranch } from './repo'
|
||||
import { readSessionChanges } from './session-changes'
|
||||
|
||||
export interface ReadWalkthroughChangesOptions {
|
||||
@@ -16,14 +20,71 @@ export interface ReadWalkthroughChangesOptions {
|
||||
|
||||
type GitWalkthroughSource = Exclude<WalkthroughSource, { kind: 'session' }>
|
||||
|
||||
interface CommandResult {
|
||||
exitCode: number
|
||||
stdout: string
|
||||
stderr: string
|
||||
const GIT_DIFF_TIMEOUT_MS = 30_000
|
||||
const GIT_FETCH_TIMEOUT_MS = 60_000
|
||||
const GIT_DIFF_MAX_OUTPUT_CHARS = 5_000_000
|
||||
const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
|
||||
const DIFF_ARGS = ['--no-color', '--src-prefix=a/', '--dst-prefix=b/', '--no-ext-diff', '--no-textconv', '-U3']
|
||||
const PULL_REQUEST_REMOTE_PREFERENCE = ['upstream', 'origin']
|
||||
|
||||
type PullRequestSource = Extract<GitWalkthroughSource, { kind: 'pullRequest' }>
|
||||
|
||||
export interface PullRequestFetchPlan {
|
||||
remote: string
|
||||
refspec: string
|
||||
ref: string
|
||||
}
|
||||
|
||||
function commandResult(result: string | CommandResult): CommandResult {
|
||||
return typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
export type PullRequestFetchRunner = (
|
||||
remote: string,
|
||||
refspec: string,
|
||||
timeoutMs: number,
|
||||
) => Promise<void>
|
||||
|
||||
export function walkthroughPullRequestRef(number: number): string {
|
||||
return `refs/ocm-walkthrough/pr/${number}`
|
||||
}
|
||||
|
||||
export async function planPullRequestFetch(
|
||||
directory: string,
|
||||
source: PullRequestSource,
|
||||
gitEnv?: Record<string, string>,
|
||||
): Promise<PullRequestFetchPlan> {
|
||||
const remotes = (await tryGit(directory, ['remote'], gitEnv))?.split('\n').map((line) => line.trim()) ?? []
|
||||
const remote = PULL_REQUEST_REMOTE_PREFERENCE.find((candidate) => remotes.includes(candidate)) ?? 'origin'
|
||||
const ref = walkthroughPullRequestRef(source.number)
|
||||
return { remote, refspec: `+refs/pull/${source.number}/head:${ref}`, ref }
|
||||
}
|
||||
|
||||
export async function fetchPullRequestRef(
|
||||
directory: string,
|
||||
source: PullRequestSource,
|
||||
gitEnv: Record<string, string> | undefined,
|
||||
runFetch: PullRequestFetchRunner,
|
||||
): Promise<string> {
|
||||
const plan = await planPullRequestFetch(directory, source, gitEnv)
|
||||
await mapGitError(
|
||||
() => runFetch(plan.remote, plan.refspec, GIT_FETCH_TIMEOUT_MS),
|
||||
'Failed to fetch the pull request',
|
||||
)
|
||||
return plan.ref
|
||||
}
|
||||
|
||||
export async function deletePullRequestRef(
|
||||
directory: string,
|
||||
ref: string,
|
||||
gitEnv?: Record<string, string>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await executeCommand(['git', '-C', directory, 'update-ref', '-d', ref], {
|
||||
env: gitEnv,
|
||||
silent: true,
|
||||
ignoreExitCode: true,
|
||||
timeout: GIT_DIFF_TIMEOUT_MS,
|
||||
})
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
export async function readWalkthroughChanges({
|
||||
@@ -44,39 +105,41 @@ async function readGitChanges(
|
||||
gitEnv?: Record<string, string>,
|
||||
): Promise<FileDiffInfo[]> {
|
||||
await assertGitRepository(directory, gitEnv)
|
||||
const repoRoot = await resolveRepoRoot(directory, gitEnv)
|
||||
|
||||
switch (source.kind) {
|
||||
case 'uncommitted':
|
||||
return collectChanges(directory, await uncommittedRevision(directory, gitEnv), true, gitEnv)
|
||||
return collectChanges(repoRoot, await uncommittedRevision(repoRoot, gitEnv), true, gitEnv)
|
||||
case 'staged':
|
||||
return collectChanges(directory, ['--cached'], false, gitEnv)
|
||||
return collectChanges(repoRoot, ['--cached'], false, gitEnv)
|
||||
case 'unstaged':
|
||||
return collectChanges(directory, await unstagedRevision(directory, gitEnv), true, gitEnv)
|
||||
return collectChanges(repoRoot, [], true, gitEnv)
|
||||
case 'branch': {
|
||||
const base = await resolveBaseBranch(directory, source.base, gitEnv)
|
||||
return collectChanges(directory, [`${base}...HEAD`], false, gitEnv)
|
||||
const base = await resolveBase(repoRoot, source.base, gitEnv)
|
||||
return collectChanges(repoRoot, [`${base}...HEAD`], false, gitEnv)
|
||||
}
|
||||
case 'pullRequest': {
|
||||
const base = await resolveBaseBranch(directory, source.base, gitEnv)
|
||||
const ref = `refs/ocm-walkthrough/pr/${source.number}`
|
||||
try {
|
||||
await runGit(directory, ['fetch', '--no-tags', 'origin', `+refs/pull/${source.number}/head:${ref}`], gitEnv)
|
||||
} catch (error) {
|
||||
throw new ChangeWalkthroughError(getErrorMessage(error) || 'Failed to fetch the pull request', 502, {
|
||||
code: 'WALKTHROUGH_SOURCE_UNAVAILABLE',
|
||||
})
|
||||
}
|
||||
return collectChanges(directory, [`${base}...${ref}`], false, gitEnv)
|
||||
const base = await resolveBase(repoRoot, source.base, gitEnv)
|
||||
const ref = walkthroughPullRequestRef(source.number)
|
||||
return collectChanges(repoRoot, [`${base}...${ref}`], false, gitEnv)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function uncommittedRevision(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
|
||||
return (await headExists(directory, gitEnv)) ? ['HEAD'] : ['--cached']
|
||||
async function resolveBase(directory: string, base: string | undefined, gitEnv?: Record<string, string>): Promise<string> {
|
||||
const resolved = await resolveBaseRef(
|
||||
directory,
|
||||
base ?? await resolveDefaultBranch(directory, gitEnv ?? {}),
|
||||
gitEnv ?? {},
|
||||
)
|
||||
if (!resolved) {
|
||||
throw new ChangeWalkthroughError('No base branch found', 409, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
async function unstagedRevision(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
|
||||
return (await headExists(directory, gitEnv)) ? [] : ['--cached']
|
||||
async function uncommittedRevision(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
|
||||
return (await headExists(directory, gitEnv)) ? ['HEAD'] : [EMPTY_TREE]
|
||||
}
|
||||
|
||||
async function collectChanges(
|
||||
@@ -85,26 +148,60 @@ async function collectChanges(
|
||||
includeUntracked: boolean,
|
||||
gitEnv?: Record<string, string>,
|
||||
): Promise<FileDiffInfo[]> {
|
||||
const tracked = await runGit(directory, ['diff', '--no-color', '--no-ext-diff', '-U3', ...revisionArgs], gitEnv)
|
||||
const tracked = await runDiff(directory, revisionArgs, gitEnv)
|
||||
if (!includeUntracked) {
|
||||
return splitUnifiedDiffByFile(tracked)
|
||||
}
|
||||
const untracked = await readUntrackedDiffs(directory, gitEnv)
|
||||
return splitUnifiedDiffByFile([tracked, ...untracked].join(''))
|
||||
const untracked = await readUntrackedDiff(directory, gitEnv)
|
||||
return splitUnifiedDiffByFile(`${tracked}${untracked}`)
|
||||
}
|
||||
|
||||
async function readUntrackedDiffs(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
|
||||
const output = await runGit(directory, ['ls-files', '--others', '--exclude-standard', '-z'], gitEnv)
|
||||
const paths = output.split('\0').filter((entry) => entry.length > 0).sort()
|
||||
const diffs: string[] = []
|
||||
for (const filePath of paths) {
|
||||
const result = commandResult(await executeCommand(
|
||||
['git', '-C', directory, 'diff', '--no-color', '--no-index', '--', '/dev/null', filePath],
|
||||
{ env: gitEnv, silent: true, ignoreExitCode: true },
|
||||
))
|
||||
diffs.push(result.stdout)
|
||||
async function readUntrackedDiff(directory: string, gitEnv?: Record<string, string>): Promise<string> {
|
||||
const untracked = await runGit(directory, ['ls-files', '--others', '--exclude-standard', '-z'], gitEnv)
|
||||
if (untracked.length === 0) {
|
||||
return ''
|
||||
}
|
||||
return diffs
|
||||
|
||||
const tempDir = mkdtempSync(path.join(tmpdir(), 'ocm-walkthrough-index-'))
|
||||
const tempIndex = path.join(tempDir, 'index')
|
||||
const env = { ...gitEnv, GIT_INDEX_FILE: tempIndex }
|
||||
|
||||
try {
|
||||
const indexPath = (await tryGit(directory, ['rev-parse', '--git-path', 'index'], gitEnv))?.trim()
|
||||
if (indexPath) {
|
||||
const realIndex = path.resolve(directory, indexPath)
|
||||
if (existsSync(realIndex)) {
|
||||
copyFileSync(realIndex, tempIndex)
|
||||
}
|
||||
}
|
||||
await runGit(directory, ['add', '-N', '-A'], env)
|
||||
return await runDiff(directory, ['--diff-filter=A', '--no-renames'], env)
|
||||
} finally {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
async function runDiff(directory: string, revisionArgs: string[], gitEnv?: Record<string, string>): Promise<string> {
|
||||
const result = await mapGitError(
|
||||
() => executeCommand(
|
||||
['git', '-C', directory, 'diff', ...DIFF_ARGS, ...revisionArgs],
|
||||
{
|
||||
env: gitEnv,
|
||||
silent: true,
|
||||
ignoreExitCode: true,
|
||||
timeout: GIT_DIFF_TIMEOUT_MS,
|
||||
maxOutputChars: GIT_DIFF_MAX_OUTPUT_CHARS,
|
||||
},
|
||||
),
|
||||
'git diff failed',
|
||||
)
|
||||
if (result.truncated) {
|
||||
throw new ChangeWalkthroughError('The diff is too large to display', 413, { code: 'WALKTHROUGH_DIFF_TOO_LARGE' })
|
||||
}
|
||||
if (result.exitCode !== 0) {
|
||||
throw new ChangeWalkthroughError(result.stderr.trim() || 'git diff failed', 502, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
|
||||
}
|
||||
return result.stdout
|
||||
}
|
||||
|
||||
async function assertGitRepository(directory: string, gitEnv?: Record<string, string>): Promise<void> {
|
||||
@@ -119,47 +216,52 @@ async function assertGitRepository(directory: string, gitEnv?: Record<string, st
|
||||
}
|
||||
}
|
||||
|
||||
async function headExists(directory: string, gitEnv?: Record<string, string>): Promise<boolean> {
|
||||
const result = commandResult(await executeCommand(
|
||||
['git', '-C', directory, 'rev-parse', '--verify', '--quiet', 'HEAD'],
|
||||
{ env: gitEnv, silent: true, ignoreExitCode: true },
|
||||
))
|
||||
return result.exitCode === 0
|
||||
async function resolveRepoRoot(directory: string, gitEnv?: Record<string, string>): Promise<string> {
|
||||
const root = await tryGit(directory, ['rev-parse', '--show-toplevel'], gitEnv)
|
||||
return root ? root.trim() : directory
|
||||
}
|
||||
|
||||
async function resolveBaseBranch(
|
||||
directory: string,
|
||||
base: string | undefined,
|
||||
gitEnv?: Record<string, string>,
|
||||
): Promise<string> {
|
||||
if (base) {
|
||||
return base
|
||||
}
|
||||
|
||||
const originHead = await tryGit(directory, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], gitEnv)
|
||||
if (originHead) {
|
||||
return originHead.trim()
|
||||
}
|
||||
|
||||
for (const candidate of ['main', 'master']) {
|
||||
const resolved = await tryGit(directory, ['rev-parse', '--verify', '--quiet', candidate], gitEnv)
|
||||
if (resolved) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
|
||||
throw new ChangeWalkthroughError('No base branch found', 409, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
|
||||
async function headExists(directory: string, gitEnv?: Record<string, string>): Promise<boolean> {
|
||||
return (await tryGit(directory, ['rev-parse', '--verify', '--quiet', 'HEAD'], gitEnv)) !== null
|
||||
}
|
||||
|
||||
async function tryGit(directory: string, args: string[], gitEnv?: Record<string, string>): Promise<string | null> {
|
||||
const result = commandResult(await executeCommand(['git', '-C', directory, ...args], {
|
||||
const result = await executeCommand(['git', '-C', directory, ...args], {
|
||||
env: gitEnv,
|
||||
silent: true,
|
||||
ignoreExitCode: true,
|
||||
}))
|
||||
timeout: GIT_DIFF_TIMEOUT_MS,
|
||||
maxOutputChars: GIT_DIFF_MAX_OUTPUT_CHARS,
|
||||
})
|
||||
return result.exitCode === 0 ? result.stdout : null
|
||||
}
|
||||
|
||||
async function runGit(directory: string, args: string[], gitEnv?: Record<string, string>): Promise<string> {
|
||||
return executeCommand(['git', '-C', directory, ...args], { env: gitEnv, silent: true })
|
||||
async function runGit(
|
||||
directory: string,
|
||||
args: string[],
|
||||
gitEnv?: Record<string, string>,
|
||||
timeout = GIT_DIFF_TIMEOUT_MS,
|
||||
fallback = 'Git command failed',
|
||||
): Promise<string> {
|
||||
return mapGitError(
|
||||
() => executeCommand(['git', '-C', directory, ...args], {
|
||||
env: gitEnv,
|
||||
silent: true,
|
||||
timeout,
|
||||
maxOutputChars: GIT_DIFF_MAX_OUTPUT_CHARS,
|
||||
}),
|
||||
fallback,
|
||||
)
|
||||
}
|
||||
|
||||
async function mapGitError<T>(run: () => Promise<T>, fallback: string): Promise<T> {
|
||||
try {
|
||||
return await run()
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error)
|
||||
if (message.includes('timed out')) {
|
||||
throw new ChangeWalkthroughError('git timed out', 504, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
|
||||
}
|
||||
throw new ChangeWalkthroughError(message || fallback, 502, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
|
||||
}
|
||||
}
|
||||
@@ -21,3 +21,47 @@ export async function mapWithConcurrency<T, R>(
|
||||
await Promise.all(Array.from({ length: workerCount }, () => worker()))
|
||||
return results
|
||||
}
|
||||
|
||||
export interface Limiter {
|
||||
readonly activeCount: number
|
||||
run<T>(task: () => Promise<T>): Promise<T>
|
||||
}
|
||||
|
||||
export function createLimiter(limit: number): Limiter {
|
||||
const max = Math.max(1, limit)
|
||||
let active = 0
|
||||
const waiters: Array<() => void> = []
|
||||
|
||||
const acquire = (): Promise<void> => {
|
||||
if (active < max) {
|
||||
active += 1
|
||||
return Promise.resolve()
|
||||
}
|
||||
return new Promise<void>((resolve) => {
|
||||
waiters.push(resolve)
|
||||
})
|
||||
}
|
||||
|
||||
const release = (): void => {
|
||||
const next = waiters.shift()
|
||||
if (next) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
active -= 1
|
||||
}
|
||||
|
||||
return {
|
||||
get activeCount(): number {
|
||||
return active
|
||||
},
|
||||
async run<T>(task: () => Promise<T>): Promise<T> {
|
||||
await acquire()
|
||||
try {
|
||||
return await task()
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ZodType } from 'zod'
|
||||
|
||||
export function extractFirstJsonObject(text: string): string | null {
|
||||
const start = text.indexOf('{')
|
||||
if (start === -1) {
|
||||
@@ -39,3 +41,24 @@ export function extractFirstJsonObject(text: string): string | null {
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function parseFirstJsonObject<T>(text: string, schema: ZodType<T>): T | null {
|
||||
const extracted = extractFirstJsonObject(text)
|
||||
if (!extracted) {
|
||||
return null
|
||||
}
|
||||
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(extracted)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
const parsed = schema.safeParse(raw)
|
||||
if (!parsed.success) {
|
||||
return null
|
||||
}
|
||||
|
||||
return parsed.data
|
||||
}
|
||||
@@ -10,23 +10,24 @@ interface ExecuteCommandOptions {
|
||||
maxOutputChars?: number
|
||||
}
|
||||
|
||||
export async function executeCommand(
|
||||
export interface ExecuteCommandResult {
|
||||
exitCode: number
|
||||
stdout: string
|
||||
stderr: string
|
||||
truncated?: boolean
|
||||
}
|
||||
|
||||
type ExecuteCommandReturn<O> = O extends { ignoreExitCode: true } ? ExecuteCommandResult : string
|
||||
|
||||
export async function executeCommand<O extends ExecuteCommandOptions = ExecuteCommandOptions>(
|
||||
args: string[],
|
||||
cwdOrOptions?: string | ExecuteCommandOptions
|
||||
): Promise<string>
|
||||
export async function executeCommand(
|
||||
args: string[],
|
||||
cwdOrOptions: string | (ExecuteCommandOptions & { ignoreExitCode: true })
|
||||
): Promise<string | { exitCode: number; stdout: string; stderr: string }>
|
||||
export async function executeCommand(
|
||||
args: string[],
|
||||
cwdOrOptions?: string | ExecuteCommandOptions
|
||||
): Promise<string | { exitCode: number; stdout: string; stderr: string }> {
|
||||
cwdOrOptions?: string | O
|
||||
): Promise<ExecuteCommandReturn<O>> {
|
||||
const options: ExecuteCommandOptions = typeof cwdOrOptions === 'string'
|
||||
? { cwd: cwdOrOptions }
|
||||
: cwdOrOptions || {}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
return new Promise<string | ExecuteCommandResult>((resolve, reject) => {
|
||||
const [command, ...cmdArgs] = args
|
||||
|
||||
const effectiveEnv = { ...process.env, ...options.env }
|
||||
@@ -103,6 +104,7 @@ export async function executeCommand(
|
||||
exitCode,
|
||||
stdout,
|
||||
stderr: terminatedBySignal ? `${stderr}Command terminated by signal ${signal}` : stderr,
|
||||
truncated: true,
|
||||
}
|
||||
: stdout)
|
||||
} else if (options.ignoreExitCode) {
|
||||
@@ -121,5 +123,5 @@ export async function executeCommand(
|
||||
reject(error)
|
||||
}
|
||||
})
|
||||
})
|
||||
}) as Promise<ExecuteCommandReturn<O>>
|
||||
}
|
||||
Reference in new issue
Block a user