dsh-git-bugfix 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/git.js ADDED
@@ -0,0 +1,728 @@
1
+ /**
2
+ * Git plumbing for the defect fixer.
3
+ *
4
+ * Every command is local-only: this module never fetches, pulls, pushes, or
5
+ * contacts a remote, and it never rewrites the repository's configuration.
6
+ * Fixes live on local `bugfix/*` branches in dedicated worktrees; applying one
7
+ * to the user's branch is a local `git cherry-pick` that stops on conflicts so
8
+ * the human can resolve them.
9
+ */
10
+
11
+ import { execFile } from 'node:child_process'
12
+ import { readFile } from 'node:fs/promises'
13
+ import path from 'node:path'
14
+
15
+ /** Environment every git command starts from: no prompts, no ambient locks. */
16
+ const BASE_ENV = {
17
+ GIT_TERMINAL_PROMPT: '0',
18
+ GIT_OPTIONAL_LOCKS: '0',
19
+ LC_ALL: 'C.UTF-8',
20
+ LANG: 'C.UTF-8',
21
+ }
22
+
23
+ /** Git subcommands that touch remotes and are globally forbidden. */
24
+ const FORBIDDEN_GIT_SUBCOMMANDS = new Set(['push', 'fetch', 'pull'])
25
+
26
+ /**
27
+ * Extract the git subcommand from an argument list (skipping leading `-c k=v` or `-C dir` flags).
28
+ * @param {string[]} args - git arguments.
29
+ * @returns {string} the subcommand, or empty string.
30
+ */
31
+ function gitSubcommand(args) {
32
+ for (let index = 0; index < args.length; index += 1) {
33
+ const arg = args[index]
34
+ if (arg === '-c' || arg === '-C' || arg === '--git-dir' || arg === '--work-tree') {
35
+ index += 1
36
+ continue
37
+ }
38
+ if (arg.startsWith('-')) continue
39
+ return arg
40
+ }
41
+ return ''
42
+ }
43
+
44
+ /**
45
+ * Run one git command without a shell.
46
+ * @param {object} options - invocation facts.
47
+ * @param {string} options.cwd - directory to run in.
48
+ * @param {string[]} options.args - git arguments.
49
+ * @param {AbortSignal} [options.signal] - caller cancellation.
50
+ * @param {number} [options.timeoutMs] - hard deadline.
51
+ * @param {number} [options.maxBuffer] - stdout/stderr retention cap.
52
+ * @returns {Promise<{ code: number, stdout: string, stderr: string, timedOut: boolean }>}
53
+ * the command result; non-zero exits resolve instead of throwing.
54
+ */
55
+ export function git({ cwd, args, signal, timeoutMs = 120000, maxBuffer = 32 * 1024 * 1024 }) {
56
+ const subcommand = gitSubcommand(args)
57
+ if (FORBIDDEN_GIT_SUBCOMMANDS.has(subcommand)) {
58
+ return Promise.reject(new Error(`全局禁止执行 git ${subcommand},仅允许本地提交`))
59
+ }
60
+ return new Promise((resolve, reject) => {
61
+ execFile('git', args, {
62
+ cwd,
63
+ env: { ...process.env, ...BASE_ENV },
64
+ timeout: timeoutMs,
65
+ maxBuffer,
66
+ windowsHide: true,
67
+ signal,
68
+ }, (error, stdout, stderr) => {
69
+ if (error !== null && error !== undefined && typeof error.code !== 'number') {
70
+ // Spawn failures (git missing, cwd gone) are infrastructure faults.
71
+ if (error.killed === true && error.signal !== undefined && error.signal !== null) {
72
+ resolve({ code: 124, stdout: stdout ?? '', stderr: stderr ?? '', timedOut: true })
73
+ return
74
+ }
75
+ reject(error)
76
+ return
77
+ }
78
+ resolve({
79
+ code: typeof error?.code === 'number' ? error.code : 0,
80
+ stdout: stdout ?? '',
81
+ stderr: stderr ?? '',
82
+ timedOut: error?.killed === true,
83
+ })
84
+ })
85
+ })
86
+ }
87
+
88
+ /**
89
+ * Locate the Git repository that owns a directory.
90
+ * @param {string} cwd - a directory, usually the Session working directory.
91
+ * @param {AbortSignal} [signal] - caller cancellation.
92
+ * @returns {Promise<null | { root: string, gitDir: string, branch: string, detached: boolean, head: string, headShort: string }>}
93
+ * repository facts, or null when the directory is not inside a work tree.
94
+ */
95
+ export async function resolveRepo(cwd, signal) {
96
+ const resolved = path.resolve(cwd)
97
+ const top = await git({ cwd: resolved, args: ['rev-parse', '--show-toplevel'], signal, timeoutMs: 20000 })
98
+ if (top.code !== 0) return null
99
+ const root = path.resolve(top.stdout.trim())
100
+ const [head, branch] = await Promise.all([
101
+ git({ cwd: root, args: ['rev-parse', 'HEAD'], signal, timeoutMs: 20000 }),
102
+ git({ cwd: root, args: ['symbolic-ref', '--short', '-q', 'HEAD'], signal, timeoutMs: 20000 }),
103
+ ])
104
+ if (head.code !== 0) {
105
+ return { root, gitDir: root, branch: '', detached: true, head: '', headShort: '' }
106
+ }
107
+ const sha = head.stdout.trim()
108
+ const branchName = branch.code === 0 ? branch.stdout.trim() : ''
109
+ const common = await git({ cwd: root, args: ['rev-parse', '--path-format=absolute', '--git-common-dir'], signal, timeoutMs: 20000 })
110
+ return {
111
+ root,
112
+ gitDir: common.code === 0 ? path.resolve(common.stdout.trim()) : root,
113
+ branch: branchName,
114
+ detached: branchName === '',
115
+ head: sha,
116
+ headShort: sha.slice(0, 8),
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Make sure the repository's local exclude file hides the plugin's working
122
+ * directory, so the user's `git status` stays clean without touching a tracked
123
+ * `.gitignore` (which would affect the remote).
124
+ * @param {{ root: string, gitDir: string }} repo - repository facts.
125
+ * @returns {Promise<void>} after the exclude entry exists.
126
+ */
127
+ export async function ensureLocalExclude(repo) {
128
+ const excludePath = path.join(repo.gitDir, 'info', 'exclude')
129
+ const marker = '/.dsh-git-bugfix/'
130
+ let current = ''
131
+ try {
132
+ current = await readFile(excludePath, 'utf8')
133
+ } catch {
134
+ current = ''
135
+ }
136
+ if (current.split(/\r?\n/).some(line => line.trim() === marker)) return
137
+ const { mkdir, writeFile } = await import('node:fs/promises')
138
+ await mkdir(path.dirname(excludePath), { recursive: true })
139
+ const separator = current === '' || current.endsWith('\n') ? '' : '\n'
140
+ await writeFile(excludePath, `${current}${separator}# dsh-git-bugfix isolated worktrees\n${marker}\n`, 'utf8')
141
+ }
142
+
143
+ /**
144
+ * Read the worktree list of a repository.
145
+ * @param {string} root - repository root.
146
+ * @param {AbortSignal} [signal] - caller cancellation.
147
+ * @returns {Promise<Array<{ path: string, branch: string, head: string, prunable: boolean }>>} worktrees.
148
+ */
149
+ export async function listWorktrees(root, signal) {
150
+ const result = await git({ cwd: root, args: ['worktree', 'list', '--porcelain'], signal, timeoutMs: 30000 })
151
+ if (result.code !== 0) return []
152
+ const entries = []
153
+ let current = undefined
154
+ for (const line of result.stdout.split(/\r?\n/)) {
155
+ if (line.startsWith('worktree ')) current = { path: path.resolve(line.slice('worktree '.length)), branch: '', head: '', prunable: false }
156
+ else if (current === undefined) continue
157
+ else if (line.startsWith('HEAD ')) current.head = line.slice(5).trim()
158
+ else if (line.startsWith('branch ')) current.branch = line.slice(7).replace(/^refs\/heads\//, '').trim()
159
+ else if (line.startsWith('prunable')) current.prunable = true
160
+ else if (line === '') {
161
+ entries.push(current)
162
+ current = undefined
163
+ }
164
+ }
165
+ if (current !== undefined) entries.push(current)
166
+ return entries
167
+ }
168
+
169
+ /**
170
+ * Create a worktree on a new local branch, preserving existing branches.
171
+ * @param {object} options - creation facts.
172
+ * @param {string} options.root - repository root.
173
+ * @param {string} options.worktreePath - absolute path for the checkout.
174
+ * @param {string} options.branch - new local branch to create.
175
+ * @param {string} options.baseSha - commit the branch starts from.
176
+ * @param {AbortSignal} [options.signal] - caller cancellation.
177
+ * @returns {Promise<{ ok: boolean, message: string }>} the outcome.
178
+ */
179
+ export async function createWorktree({ root, worktreePath, branch, baseSha, signal }) {
180
+ const existing = await listWorktrees(root, signal)
181
+ const sameBranch = existing.find(entry => entry.branch === branch && entry.path !== path.resolve(root))
182
+ if (sameBranch !== undefined) return { ok: false, message: `分支 ${branch} 已在工作区中使用` }
183
+ const branchCheck = await git({ cwd: root, args: ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], signal, timeoutMs: 20000 })
184
+ if (branchCheck.code === 0) {
185
+ return { ok: false, message: `分支 ${branch} 已存在` }
186
+ }
187
+ const result = await git({
188
+ cwd: root,
189
+ args: ['worktree', 'add', '-b', branch, worktreePath, baseSha],
190
+ signal,
191
+ timeoutMs: 10 * 60 * 1000,
192
+ })
193
+ if (result.code !== 0) return { ok: false, message: result.stderr.trim() || result.stdout.trim() || '创建 worktree 失败' }
194
+ return { ok: true, message: '' }
195
+ }
196
+
197
+ /**
198
+ * Remove a worktree checkout and prune stale records.
199
+ * @param {string} root - repository root.
200
+ * @param {string} worktreePath - absolute worktree path.
201
+ * @param {AbortSignal} [signal] - caller cancellation.
202
+ * @returns {Promise<void>} after the attempt.
203
+ */
204
+ export async function removeWorktree(root, worktreePath, signal) {
205
+ const result = await git({ cwd: root, args: ['worktree', 'remove', '--force', worktreePath], signal, timeoutMs: 120000 })
206
+ if (result.code !== 0) {
207
+ const { rm } = await import('node:fs/promises')
208
+ await rm(worktreePath, { recursive: true, force: true }).catch(() => {})
209
+ await git({ cwd: root, args: ['worktree', 'prune'], signal, timeoutMs: 60000 })
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Delete a local branch, ignoring a missing branch.
215
+ * @param {string} root - repository root.
216
+ * @param {string} branch - branch name.
217
+ * @param {AbortSignal} [signal] - caller cancellation.
218
+ * @returns {Promise<void>} after the attempt.
219
+ */
220
+ export async function deleteBranch(root, branch, signal) {
221
+ await git({ cwd: root, args: ['branch', '-D', branch], signal, timeoutMs: 30000 })
222
+ }
223
+
224
+ /**
225
+ * List the repository's local branches.
226
+ * @param {string} root - repository root.
227
+ * @param {AbortSignal} [signal] - caller cancellation.
228
+ * @returns {Promise<Array<{ name: string, headShort: string, committedAt: number }>>} local branches.
229
+ */
230
+ export async function listLocalBranches(root, signal) {
231
+ const result = await git({
232
+ cwd: root,
233
+ args: ['for-each-ref', '--format=%(refname:short)%00%(objectname:short)%00%(committerdate:unix)', 'refs/heads'],
234
+ signal,
235
+ timeoutMs: 30000,
236
+ })
237
+ if (result.code !== 0) return []
238
+ const branches = []
239
+ for (const line of result.stdout.split(/\r?\n/)) {
240
+ if (line === '') continue
241
+ const [name, headShort, seconds] = line.split('\u0000')
242
+ if (name === undefined || name === '') continue
243
+ branches.push({
244
+ name,
245
+ headShort: headShort ?? '',
246
+ committedAt: Number(seconds) > 0 ? Number(seconds) * 1000 : 0,
247
+ })
248
+ }
249
+ return branches.sort((left, right) => right.committedAt - left.committedAt || left.name.localeCompare(right.name, 'en'))
250
+ }
251
+
252
+ /**
253
+ * Resolve one local branch's current commit.
254
+ * @param {string} root - repository root.
255
+ * @param {string} branch - branch name.
256
+ * @param {AbortSignal} [signal] - caller cancellation.
257
+ * @returns {Promise<{ sha: string, short: string } | null>} the head commit, or null when the branch is missing.
258
+ */
259
+ export async function branchHead(root, branch, signal) {
260
+ const result = await git({ cwd: root, args: ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], signal, timeoutMs: 20000 })
261
+ if (result.code !== 0) return null
262
+ const sha = result.stdout.trim()
263
+ if (sha === '') return null
264
+ return { sha, short: sha.slice(0, 8) }
265
+ }
266
+
267
+ /**
268
+ * Check out an existing local branch in a new worktree (only when no other
269
+ * worktree currently holds it).
270
+ * @param {object} options - creation facts.
271
+ * @param {string} options.root - repository root.
272
+ * @param {string} options.worktreePath - absolute checkout path.
273
+ * @param {string} options.branch - existing local branch to check out.
274
+ * @param {AbortSignal} [options.signal] - caller cancellation.
275
+ * @returns {Promise<{ ok: boolean, message: string }>} outcome.
276
+ */
277
+ export async function createApplyWorktree({ root, worktreePath, branch, signal }) {
278
+ const result = await git({
279
+ cwd: root,
280
+ args: ['worktree', 'add', worktreePath, branch],
281
+ signal,
282
+ timeoutMs: 10 * 60 * 1000,
283
+ })
284
+ if (result.code !== 0) return { ok: false, message: result.stderr.trim() || result.stdout.trim() || '创建应用 worktree 失败' }
285
+ return { ok: true, message: '' }
286
+ }
287
+
288
+ /**
289
+ * Apply one fix commit onto the current local branch of a worktree with
290
+ * `git cherry-pick`, stopping on conflicts.
291
+ * @param {string} cwd - the worktree whose branch receives the fix.
292
+ * @param {string} sha - fix commit.
293
+ * @param {AbortSignal} [signal] - caller cancellation.
294
+ * @returns {Promise<{ ok: boolean, conflict: string[], message: string }>} outcome.
295
+ */
296
+ export async function cherryPick(cwd, sha, signal) {
297
+ const result = await git({ cwd, args: ['cherry-pick', '--no-edit', sha], signal, timeoutMs: 10 * 60 * 1000 })
298
+ if (result.code === 0) return { ok: true, conflict: [], message: '' }
299
+ const conflict = await conflictedFiles(cwd, signal)
300
+ const message = (result.stderr.trim() || result.stdout.trim() || 'git cherry-pick 失败')
301
+ .split(/\r?\n/).slice(0, 12).join('\n')
302
+ return { ok: false, conflict, message }
303
+ }
304
+
305
+ /**
306
+ * Continue an in-progress cherry-pick in one worktree.
307
+ * @param {string} cwd - worktree directory.
308
+ * @param {AbortSignal} [signal] - caller cancellation.
309
+ * @returns {Promise<{ ok: boolean, skipped?: boolean, message: string }>} outcome.
310
+ */
311
+ export async function continueCherryPickIn(cwd, signal) {
312
+ const result = await git({
313
+ cwd,
314
+ args: ['-c', 'user.name=DSH Git Bugfix', '-c', 'user.email=dsh-git-bugfix@localhost', 'commit', '--no-edit'],
315
+ signal,
316
+ timeoutMs: 10 * 60 * 1000,
317
+ })
318
+ if (result.code === 0) return { ok: true, message: '' }
319
+ const combined = `${result.stderr}\n${result.stdout}`
320
+ if (/previous cherry-pick is now empty|nothing to commit, working tree clean/i.test(combined)) {
321
+ const skipped = await git({ cwd, args: ['cherry-pick', '--skip'], signal, timeoutMs: 120000 })
322
+ if (skipped.code === 0) return { ok: true, skipped: true, message: '' }
323
+ return { ok: false, message: (skipped.stderr.trim() || skipped.stdout.trim() || '继续合并失败').split(/\r?\n/).slice(0, 12).join('\n') }
324
+ }
325
+ return { ok: false, message: (result.stderr.trim() || result.stdout.trim() || '继续合并失败').split(/\r?\n/).slice(0, 12).join('\n') }
326
+ }
327
+
328
+ /**
329
+ * Abort an in-progress cherry-pick in one worktree.
330
+ * @param {string} cwd - worktree directory.
331
+ * @param {AbortSignal} [signal] - caller cancellation.
332
+ * @returns {Promise<{ ok: boolean, message: string }>} outcome.
333
+ */
334
+ export async function abortCherryPickIn(cwd, signal) {
335
+ const result = await git({ cwd, args: ['cherry-pick', '--abort'], signal, timeoutMs: 120000 })
336
+ if (result.code === 0) return { ok: true, message: '' }
337
+ return { ok: false, message: result.stderr.trim() || '中止合并失败' }
338
+ }
339
+
340
+ /**
341
+ * Merge one local branch into the current branch of a worktree with
342
+ * `git merge --no-ff`, keeping the branch's commits and creating one merge
343
+ * commit. Stops on conflicts in the standard merge state.
344
+ * @param {string} cwd - worktree whose branch receives the merge.
345
+ * @param {string} branch - branch to merge in.
346
+ * @param {AbortSignal} [signal] - caller cancellation.
347
+ * @returns {Promise<{ ok: boolean, conflict: string[], message: string }>} outcome.
348
+ */
349
+ export async function mergeBranch(cwd, branch, signal) {
350
+ const result = await git({ cwd, args: ['merge', '--no-ff', '--no-edit', branch], signal, timeoutMs: 10 * 60 * 1000 })
351
+ if (result.code === 0) return { ok: true, conflict: [], message: '' }
352
+ const conflict = await conflictedFiles(cwd, signal)
353
+ const message = (result.stderr.trim() || result.stdout.trim() || 'git merge 失败')
354
+ .split(/\r?\n/).slice(0, 12).join('\n')
355
+ return { ok: false, conflict, message }
356
+ }
357
+
358
+ /**
359
+ * Continue an in-progress merge in one worktree.
360
+ * @param {string} cwd - worktree directory.
361
+ * @param {AbortSignal} [signal] - caller cancellation.
362
+ * @returns {Promise<{ ok: boolean, message: string }>} outcome.
363
+ */
364
+ export async function continueMergeIn(cwd, signal) {
365
+ const result = await git({
366
+ cwd,
367
+ args: ['-c', 'user.name=DSH Git Bugfix', '-c', 'user.email=dsh-git-bugfix@localhost', 'commit', '--no-edit'],
368
+ signal,
369
+ timeoutMs: 10 * 60 * 1000,
370
+ })
371
+ if (result.code === 0) return { ok: true, message: '' }
372
+ return { ok: false, message: (result.stderr.trim() || result.stdout.trim() || '继续合并失败').split(/\r?\n/).slice(0, 12).join('\n') }
373
+ }
374
+
375
+ /**
376
+ * Abort an in-progress merge in one worktree.
377
+ * @param {string} cwd - worktree directory.
378
+ * @param {AbortSignal} [signal] - caller cancellation.
379
+ * @returns {Promise<{ ok: boolean, message: string }>} outcome.
380
+ */
381
+ export async function abortMergeIn(cwd, signal) {
382
+ const result = await git({ cwd, args: ['merge', '--abort'], signal, timeoutMs: 120000 })
383
+ if (result.code === 0) return { ok: true, message: '' }
384
+ return { ok: false, message: result.stderr.trim() || '中止合并失败' }
385
+ }
386
+
387
+ /**
388
+ * Read working-tree status of a worktree.
389
+ * @param {string} cwd - worktree path.
390
+ * @param {AbortSignal} [signal] - caller cancellation.
391
+ * @returns {Promise<{ clean: boolean, entries: Array<{ status: string, path: string }> }>} status facts.
392
+ */
393
+ export async function worktreeStatus(cwd, signal) {
394
+ const result = await git({ cwd, args: ['status', '--porcelain=v1', '-z', '--untracked-files=all'], signal, timeoutMs: 60000 })
395
+ if (result.code !== 0) throw new Error(result.stderr.trim() || '无法读取 Git 工作区状态')
396
+ const entries = []
397
+ const parts = result.stdout.split('\u0000')
398
+ for (let index = 0; index < parts.length; index += 1) {
399
+ const part = parts[index]
400
+ if (part.length < 4) continue
401
+ const status = part.slice(0, 2)
402
+ const file = part.slice(3)
403
+ entries.push({ status, path: file })
404
+ // A rename entry is followed by its source path.
405
+ if (status.includes('R') || status.includes('C')) index += 1
406
+ }
407
+ return { clean: entries.length === 0, entries }
408
+ }
409
+
410
+ /**
411
+ * Count lines of a file for untracked-file statistics.
412
+ * @param {string} file - absolute file path.
413
+ * @returns {Promise<number>} line count, or 0 for unreadable files.
414
+ */
415
+ async function countLines(file) {
416
+ try {
417
+ const text = await readFile(file, 'utf8')
418
+ if (text === '') return 0
419
+ return text.split(/\r?\n/).length - (text.endsWith('\n') ? 1 : 0)
420
+ } catch {
421
+ return 0
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Summarize a fix's changed files with line counts.
427
+ * @param {string} cwd - worktree path.
428
+ * @param {string} baseSha - commit the worktree started from.
429
+ * @param {AbortSignal} [signal] - caller cancellation.
430
+ * @returns {Promise<Array<{ path: string, display: string, added: number, deleted: number, binary: boolean, untracked: boolean }>>}
431
+ * changed files; `path` is relative to the worktree.
432
+ */
433
+ export async function changedFiles(cwd, baseSha, signal) {
434
+ const tracked = await git({ cwd, args: ['diff', '--numstat', '-z', '--no-renames', baseSha, '--'], signal, timeoutMs: 120000 })
435
+ const files = new Map()
436
+ if (tracked.code === 0) {
437
+ for (const line of tracked.stdout.split('\u0000')) {
438
+ if (line === '') continue
439
+ const [addedText, deletedText, ...rest] = line.split('\t')
440
+ const display = rest.join('\t')
441
+ if (display === '') continue
442
+ const binary = addedText === '-' || deletedText === '-'
443
+ files.set(display, {
444
+ path: display,
445
+ display,
446
+ added: binary ? 0 : Number(addedText) || 0,
447
+ deleted: binary ? 0 : Number(deletedText) || 0,
448
+ binary,
449
+ untracked: false,
450
+ })
451
+ }
452
+ }
453
+ const status = await worktreeStatus(cwd, signal)
454
+ for (const entry of status.entries) {
455
+ if (files.has(entry.path)) continue
456
+ if (!entry.status.includes('?') && !entry.status.includes('A')) continue
457
+ const lines = await countLines(path.join(cwd, entry.path))
458
+ files.set(entry.path, {
459
+ path: entry.path,
460
+ display: entry.path,
461
+ added: lines,
462
+ deleted: 0,
463
+ binary: false,
464
+ untracked: true,
465
+ })
466
+ }
467
+ return [...files.values()].sort((left, right) => left.display.localeCompare(right.display))
468
+ }
469
+
470
+ /**
471
+ * Parse a unified diff into hunks for browser rendering.
472
+ * @param {string} patch - unified diff text for one file.
473
+ * @returns {Array<{ oldStart: number, oldLines: number, newStart: number, newLines: number, lines: string[] }>} hunks.
474
+ */
475
+ function parseHunks(patch) {
476
+ const hunks = []
477
+ let current = undefined
478
+ for (const line of patch.split(/\r?\n/)) {
479
+ const header = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line)
480
+ if (header !== null) {
481
+ current = {
482
+ oldStart: Number(header[1]),
483
+ oldLines: header[2] === undefined ? 1 : Number(header[2]),
484
+ newStart: Number(header[3]),
485
+ newLines: header[4] === undefined ? 1 : Number(header[4]),
486
+ lines: [],
487
+ }
488
+ hunks.push(current)
489
+ continue
490
+ }
491
+ if (current !== undefined && (line.startsWith(' ') || line.startsWith('+') || line.startsWith('-') || line.startsWith('\\'))) {
492
+ current.lines.push(line)
493
+ }
494
+ }
495
+ return hunks
496
+ }
497
+
498
+ /**
499
+ * Read one file's comparison between the worktree base and its fix commit.
500
+ * @param {string} cwd - worktree path.
501
+ * @param {string} baseSha - base commit.
502
+ * @param {string} headSha - fix commit (or worktree HEAD).
503
+ * @param {string} file - worktree-relative path.
504
+ * @param {AbortSignal} [signal] - caller cancellation.
505
+ * @returns {Promise<{ kind: 'text', path: string, added: number, deleted: number, hunks: Array<object> } | { kind: 'binary', path: string } | { kind: 'missing', path: string }>}
506
+ * the comparison.
507
+ */
508
+ export async function fileDiff(cwd, baseSha, headSha, file, signal) {
509
+ const range = headSha !== '' ? [baseSha, headSha] : [baseSha]
510
+ const stat = await git({
511
+ cwd,
512
+ args: ['diff', '--numstat', '--no-renames', ...range, '--', file],
513
+ signal,
514
+ timeoutMs: 60000,
515
+ })
516
+ const statLine = stat.stdout.split(/\r?\n/).find(line => line !== '') ?? ''
517
+ const [addedText, deletedText] = statLine.split('\t')
518
+ if (addedText === '-' || deletedText === '-') return { kind: 'binary', path: file }
519
+ const patch = await git({
520
+ cwd,
521
+ args: ['diff', '--no-color', '--no-ext-diff', '--no-textconv', '--unified=3', ...range, '--', file],
522
+ signal,
523
+ timeoutMs: 120000,
524
+ maxBuffer: 8 * 1024 * 1024,
525
+ })
526
+ if (patch.code !== 0) return { kind: 'missing', path: file }
527
+ const hunks = parseHunks(patch.stdout)
528
+ if (hunks.length === 0 && patch.stdout.trim() === '') {
529
+ if (headSha === '') {
530
+ const untracked = await git({
531
+ cwd,
532
+ args: ['ls-files', '--others', '--exclude-standard', '-z', '--', file],
533
+ signal,
534
+ timeoutMs: 20000,
535
+ })
536
+ if (untracked.code === 0 && untracked.stdout.split('\u0000').includes(file)) {
537
+ try {
538
+ const bytes = await readFile(path.join(cwd, file))
539
+ if (bytes.includes(0)) return { kind: 'binary', path: file }
540
+ const text = bytes.toString('utf8')
541
+ const rawLines = text === '' ? [] : text.split(/\r?\n/)
542
+ if (text.endsWith('\n') && rawLines[rawLines.length - 1] === '') rawLines.pop()
543
+ return {
544
+ kind: 'text',
545
+ path: file,
546
+ added: rawLines.length,
547
+ deleted: 0,
548
+ hunks: rawLines.length === 0
549
+ ? []
550
+ : [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: rawLines.length, lines: rawLines.map(line => `+${line}`) }],
551
+ }
552
+ } catch {
553
+ return { kind: 'missing', path: file }
554
+ }
555
+ }
556
+ }
557
+ return { kind: 'missing', path: file }
558
+ }
559
+ return {
560
+ kind: 'text',
561
+ path: file,
562
+ added: Number(addedText) || 0,
563
+ deleted: Number(deletedText) || 0,
564
+ hunks,
565
+ }
566
+ }
567
+
568
+ /**
569
+ * Commit everything a fix agent changed inside its worktree.
570
+ * @param {string} cwd - worktree path.
571
+ * @param {string} message - commit message.
572
+ * @param {AbortSignal} [signal] - caller cancellation.
573
+ * @returns {Promise<{ ok: boolean, sha: string, message: string }>} outcome.
574
+ */
575
+ export async function commitAll(cwd, message, signal) {
576
+ const add = await git({ cwd, args: ['add', '-A', '--', '.'], signal, timeoutMs: 120000 })
577
+ if (add.code !== 0) return { ok: false, sha: '', message: add.stderr.trim() || 'git add 失败' }
578
+ const commit = await git({ cwd, args: ['commit', '-m', message], signal, timeoutMs: 120000 })
579
+ if (commit.code === 0) {
580
+ const head = await git({ cwd, args: ['rev-parse', 'HEAD'], signal, timeoutMs: 20000 })
581
+ return { ok: true, sha: head.stdout.trim(), message: '' }
582
+ }
583
+ // A fresh clone may carry no committer identity; use a local fallback that
584
+ // never touches the repository configuration.
585
+ const fallback = await git({
586
+ cwd,
587
+ args: ['-c', 'user.name=DSH Git Bugfix', '-c', 'user.email=dsh-git-bugfix@localhost', 'commit', '-m', message],
588
+ signal,
589
+ timeoutMs: 120000,
590
+ })
591
+ if (fallback.code !== 0) return { ok: false, sha: '', message: commit.stderr.trim() || fallback.stderr.trim() || 'git commit 失败' }
592
+ const head = await git({ cwd, args: ['rev-parse', 'HEAD'], signal, timeoutMs: 20000 })
593
+ return { ok: true, sha: head.stdout.trim(), message: '' }
594
+ }
595
+
596
+ /**
597
+ * Read an in-progress operation that a merge (cherry-pick) would collide with.
598
+ * @param {string} root - repository root.
599
+ * @param {AbortSignal} [signal] - caller cancellation.
600
+ * @returns {Promise<'' | 'cherry-pick' | 'merge' | 'revert' | 'rebase'>} the pending operation.
601
+ */
602
+ export async function pendingOperation(root, signal) {
603
+ for (const [kind, ref] of [['cherry-pick', 'CHERRY_PICK_HEAD'], ['merge', 'MERGE_HEAD'], ['revert', 'REVERT_HEAD'], ['rebase', 'rebase-merge']]) {
604
+ const result = await git({ cwd: root, args: ['rev-parse', '--verify', '--quiet', ref], signal, timeoutMs: 20000 })
605
+ if (result.code === 0) return kind
606
+ }
607
+ return ''
608
+ }
609
+
610
+ /**
611
+ * Stage specific resolved files in a worktree.
612
+ * @param {string} cwd - worktree directory.
613
+ * @param {string[]} files - worktree-relative paths.
614
+ * @param {AbortSignal} [signal] - caller cancellation.
615
+ * @returns {Promise<{ ok: boolean, message: string }>} outcome.
616
+ */
617
+ export async function stageFiles(cwd, files, signal) {
618
+ if (!Array.isArray(files) || files.length === 0) return { ok: true, message: '' }
619
+ const result = await git({ cwd, args: ['add', '--', ...files], signal, timeoutMs: 60000 })
620
+ if (result.code === 0) return { ok: true, message: '' }
621
+ return { ok: false, message: result.stderr.trim() || 'git add 失败' }
622
+ }
623
+
624
+ /**
625
+ * Read the current HEAD commit SHA of a worktree.
626
+ * @param {string} cwd - worktree directory.
627
+ * @param {AbortSignal} [signal] - caller cancellation.
628
+ * @returns {Promise<string>} full 40-char SHA, or empty string.
629
+ */
630
+ export async function headSha(cwd, signal) {
631
+ const result = await git({ cwd, args: ['rev-parse', 'HEAD'], signal, timeoutMs: 20000 })
632
+ return result.code === 0 ? result.stdout.trim() : ''
633
+ }
634
+
635
+ /**
636
+ * Reset a clean worktree back by one commit (used when withdrawing the tip commit).
637
+ * @param {string} cwd - worktree directory.
638
+ * @param {AbortSignal} [signal] - caller cancellation.
639
+ * @returns {Promise<{ ok: boolean, message: string }>} outcome.
640
+ */
641
+ export async function resetBackOne(cwd, signal) {
642
+ const result = await git({ cwd, args: ['reset', '--hard', 'HEAD~1'], signal, timeoutMs: 60000 })
643
+ if (result.code === 0) return { ok: true, message: '' }
644
+ return { ok: false, message: result.stderr.trim() || 'git reset 失败' }
645
+ }
646
+
647
+ /**
648
+ * Revert one commit in a clean worktree; aborts automatically on conflicts so
649
+ * the branch stays clean.
650
+ * @param {string} cwd - worktree directory.
651
+ * @param {string} sha - commit SHA to revert.
652
+ * @param {AbortSignal} [signal] - caller cancellation.
653
+ * @returns {Promise<{ ok: boolean, message: string }>} outcome.
654
+ */
655
+ export async function revertCommit(cwd, sha, signal) {
656
+ const result = await git({
657
+ cwd,
658
+ args: ['-c', 'user.name=DSH Git Bugfix', '-c', 'user.email=dsh-git-bugfix@localhost', 'revert', '--no-edit', sha],
659
+ signal,
660
+ timeoutMs: 120000,
661
+ })
662
+ if (result.code === 0) return { ok: true, message: '' }
663
+ await git({ cwd, args: ['revert', '--abort'], signal, timeoutMs: 30000 }).catch(() => {})
664
+ return { ok: false, message: (result.stderr.trim() || result.stdout.trim() || 'git revert 失败').split(/\r?\n/).slice(0, 8).join('\n') }
665
+ }
666
+
667
+ /**
668
+ * List unmerged paths in the repository.
669
+ * @param {string} root - repository root.
670
+ * @param {AbortSignal} [signal] - caller cancellation.
671
+ * @returns {Promise<string[]>} conflicted paths.
672
+ */
673
+ export async function conflictedFiles(root, signal) {
674
+ const result = await git({ cwd: root, args: ['diff', '--name-only', '--diff-filter=U', '-z'], signal, timeoutMs: 60000 })
675
+ if (result.code !== 0) return []
676
+ return result.stdout.split('\u0000').filter(item => item !== '')
677
+ }
678
+
679
+ /**
680
+ * Apply one fix commit onto the current local branch with `git cherry-pick`.
681
+ * The command is local-only and stops on conflicts, leaving the repository in
682
+ * the standard cherry-pick state for the human to resolve.
683
+ * @param {string} root - repository root.
684
+ * @param {string} sha - fix commit.
685
+ * @param {AbortSignal} [signal] - caller cancellation.
686
+ * @returns {Promise<{ ok: boolean, conflict: string[], message: string }>} outcome.
687
+ */
688
+ export function applyFixCommit(root, sha, signal) {
689
+ return cherryPick(root, sha, signal)
690
+ }
691
+
692
+ /**
693
+ * Continue an in-progress cherry-pick after the human resolved conflicts.
694
+ * @param {string} root - repository root.
695
+ * @param {AbortSignal} [signal] - caller cancellation.
696
+ * @returns {Promise<{ ok: boolean, message: string }>} outcome.
697
+ */
698
+ export function continueCherryPick(root, signal) {
699
+ return continueCherryPickIn(root, signal)
700
+ }
701
+
702
+ /**
703
+ * Abort an in-progress cherry-pick.
704
+ * @param {string} root - repository root.
705
+ * @param {AbortSignal} [signal] - caller cancellation.
706
+ * @returns {Promise<{ ok: boolean, message: string }>} outcome.
707
+ */
708
+ export function abortCherryPick(root, signal) {
709
+ return abortCherryPickIn(root, signal)
710
+ }
711
+
712
+ /**
713
+ * Read the current branch and whether the working tree is clean.
714
+ * @param {string} root - repository root.
715
+ * @param {AbortSignal} [signal] - caller cancellation.
716
+ * @returns {Promise<{ branch: string, detached: boolean, clean: boolean }>} branch facts.
717
+ */
718
+ export async function branchState(root, signal) {
719
+ const [branch, status] = await Promise.all([
720
+ git({ cwd: root, args: ['symbolic-ref', '--short', '-q', 'HEAD'], signal, timeoutMs: 20000 }),
721
+ worktreeStatus(root, signal),
722
+ ])
723
+ return {
724
+ branch: branch.code === 0 ? branch.stdout.trim() : '',
725
+ detached: branch.code !== 0,
726
+ clean: status.clean,
727
+ }
728
+ }