@sshirkit/dsh-orchestrator 0.9.1 → 1.0.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.
@@ -0,0 +1,687 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { randomUUID } from 'node:crypto'
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+
6
+ export const WORKTREE_POOL_DIRNAME = '.dsh-orchestrator'
7
+ export const WORKTREE_POOL_SUBDIR = 'worktrees'
8
+ export const WORKTREE_BRANCH_PREFIX = 'dsh-wt/'
9
+ export const WORKTREE_STATES = Object.freeze([
10
+ 'active', 'ready_for_review', 'merged', 'discarded', 'merge_conflict', 'cleanup_failed',
11
+ ])
12
+
13
+ const PROTECTED_STATES = new Set(['active', 'ready_for_review', 'merge_conflict'])
14
+ const CLOSED_STATES = new Set(['merged', 'discarded'])
15
+ const WINDOWS = process.platform === 'win32'
16
+ const fold = (filename) => WINDOWS ? filename.toLowerCase() : filename
17
+ const pathKey = (filename) => fold(path.resolve(filename))
18
+ const posix = (filename) => filename.split(path.sep).join('/')
19
+ const missing = (error) => error.code === 'ENOENT' || error.code === 'ENOTDIR'
20
+ const line = (text) => text.replace(/\r?\n$/, '')
21
+ const failure = (code, message, fields = {}) => ({ ok: false, code, message, ...fields })
22
+ const errorText = (error) => String(error.stderr || error.message).trim()
23
+ const isId = (value) => typeof value === 'string' && value.length > 0
24
+ const textOrNull = (value) => typeof value === 'string' ? value : null
25
+ const timeOrNull = (value) => Number.isFinite(value) ? value : null
26
+
27
+ export function isWorktreeLockedRecord(record) {
28
+ return Boolean(record?.locked) || record?.state === 'merged' || record?.state === 'discarded' ||
29
+ Boolean(record?.mergeCommit) || Boolean(record?.cleaned)
30
+ }
31
+
32
+ function childIdsOf(record) {
33
+ const ids = Array.isArray(record.childIds) ? record.childIds : []
34
+ return [...new Set([record.childId, ...ids].filter(isId))]
35
+ }
36
+
37
+ function copyAuditSummary(value) {
38
+ try {
39
+ return JSON.parse(JSON.stringify(value ?? null))
40
+ } catch {
41
+ return null
42
+ }
43
+ }
44
+
45
+ function persistedRecord(record) {
46
+ return {
47
+ id: record.id, parentId: textOrNull(record.parentId), childId: textOrNull(record.childId),
48
+ childIds: childIdsOf(record), batchId: textOrNull(record.batchId),
49
+ itemIndex: Number.isSafeInteger(record.itemIndex) ? record.itemIndex : null,
50
+ repoRoot: textOrNull(record.repoRoot), sourceCwd: textOrNull(record.sourceCwd),
51
+ subPath: textOrNull(record.subPath), worktreePath: textOrNull(record.worktreePath),
52
+ execCwd: textOrNull(record.execCwd), branch: textOrNull(record.branch),
53
+ baseBranch: textOrNull(record.baseBranch), baseCommit: textOrNull(record.baseCommit),
54
+ label: textOrNull(record.label), state: record.state, mergeCommit: textOrNull(record.mergeCommit),
55
+ cleaned: record.cleaned === true, locked: isWorktreeLockedRecord(record),
56
+ createdAt: timeOrNull(record.createdAt), updatedAt: timeOrNull(record.updatedAt),
57
+ auditSummary: copyAuditSummary(record.auditSummary),
58
+ }
59
+ }
60
+
61
+ // A restored record may be a pathless tombstone. Never use an unverified shape as a Git target.
62
+ function isManagedCheckout(record) {
63
+ const { id, repoRoot, worktreePath, branch, baseCommit } = record
64
+ return /^wt-[a-z0-9_-]{1,8}$/.test(id) && branch === `${WORKTREE_BRANCH_PREFIX}${id}` &&
65
+ isId(repoRoot) && path.isAbsolute(repoRoot) && isId(worktreePath) && path.isAbsolute(worktreePath) &&
66
+ pathKey(worktreePath) === pathKey(path.join(poolPaths(repoRoot).pool, id)) &&
67
+ typeof baseCommit === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(baseCommit)
68
+ }
69
+
70
+ function git(cwd, args, readOnly = false) {
71
+ return execFileSync('git', readOnly ? ['--no-optional-locks', ...args] : args, {
72
+ cwd,
73
+ encoding: 'utf8',
74
+ windowsHide: true,
75
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' },
76
+ maxBuffer: 16 * 1024 * 1024,
77
+ timeout: 30000,
78
+ stdio: ['ignore', 'pipe', 'pipe'],
79
+ })
80
+ }
81
+
82
+ const query = (cwd, ...args) => git(cwd, args, true)
83
+
84
+ function optionalQuery(cwd, args, expectedStatus) {
85
+ try {
86
+ return line(query(cwd, ...args))
87
+ } catch (error) {
88
+ if (error.status === expectedStatus) return null
89
+ throw error
90
+ }
91
+ }
92
+
93
+ function isInside(root, filename) {
94
+ const relative = path.relative(fold(root), fold(filename))
95
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)
96
+ }
97
+
98
+ function lstat(filename) {
99
+ try {
100
+ return fs.lstatSync(filename)
101
+ } catch (error) {
102
+ if (missing(error)) return null
103
+ throw error
104
+ }
105
+ }
106
+
107
+ // Resolve a prospective path through every existing ancestor, including junctions.
108
+ function prospectiveRealpath(filename) {
109
+ if (lstat(filename)) return fs.realpathSync.native(filename)
110
+ const parent = path.dirname(filename)
111
+ if (parent === filename) return fs.realpathSync.native(filename)
112
+ return path.join(prospectiveRealpath(parent), path.basename(filename))
113
+ }
114
+
115
+ export function probeGitRepo(cwd) {
116
+ const unavailable = {
117
+ isGit: false, repoRoot: null, gitCommonDir: null, headCommit: null, headBranch: null,
118
+ subPath: '', reason: 'not-git-repo',
119
+ }
120
+ if (typeof cwd !== 'string' || !cwd.trim()) return unavailable
121
+ let repoRoot
122
+ let realCwd
123
+ try {
124
+ realCwd = fs.realpathSync.native(path.resolve(cwd))
125
+ repoRoot = fs.realpathSync.native(line(query(realCwd, 'rev-parse', '--show-toplevel')))
126
+ } catch (error) {
127
+ if (missing(error) || error.status === 128) return unavailable
128
+ throw error
129
+ }
130
+ const common = line(query(repoRoot, 'rev-parse', '--path-format=absolute', '--git-common-dir'))
131
+ const gitCommonDir = fs.realpathSync.native(path.resolve(repoRoot, common))
132
+ const headCommit = optionalQuery(repoRoot, ['rev-parse', '--verify', '--quiet', 'HEAD'], 1)
133
+ const headBranch = optionalQuery(repoRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD'], 1)
134
+ return {
135
+ isGit: true, repoRoot, gitCommonDir, headCommit, headBranch,
136
+ subPath: posix(path.relative(repoRoot, realCwd)), reason: headCommit ? null : 'unborn-head',
137
+ }
138
+ }
139
+
140
+ function poolPaths(repoRoot) {
141
+ const owner = path.join(repoRoot, WORKTREE_POOL_DIRNAME)
142
+ return { owner, pool: path.join(owner, WORKTREE_POOL_SUBDIR) }
143
+ }
144
+
145
+ function assertDirectory(filename) {
146
+ const stats = lstat(filename)
147
+ if (stats && (!stats.isDirectory() || stats.isSymbolicLink())) {
148
+ throw new Error(`工作树池路径不是普通目录:${filename}`)
149
+ }
150
+ return stats
151
+ }
152
+
153
+ export function ensurePoolIgnore(repoRoot) {
154
+ const { owner, pool } = poolPaths(repoRoot)
155
+ assertDirectory(owner)
156
+ assertDirectory(pool)
157
+ fs.mkdirSync(pool, { recursive: true })
158
+ const filename = path.join(owner, '.gitignore')
159
+ const stats = lstat(filename)
160
+ if (stats && !stats.isFile()) throw new Error(`池忽略文件不是普通文件:${filename}`)
161
+ const previous = stats ? fs.readFileSync(filename, 'utf8') : ''
162
+ // Put the catch-all last so existing negation rules cannot expose the pool.
163
+ if (!/(?:^|\n)\*\n$/.test(previous)) {
164
+ const separator = previous.length > 0 && !previous.endsWith('\n') ? '\n' : ''
165
+ fs.appendFileSync(filename, `${separator}*\n`)
166
+ }
167
+ return pool
168
+ }
169
+
170
+ function status(cwd) {
171
+ const records = query(cwd, 'status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=all', '--ignore-submodules=none')
172
+ const stagedFiles = []
173
+ const unstagedFiles = []
174
+ const untrackedFiles = []
175
+ const dirtyFiles = []
176
+ for (const row of records.split('\0')) {
177
+ if (!row) continue
178
+ const filename = row.slice(3)
179
+ dirtyFiles.push(filename)
180
+ if (row.startsWith('??')) untrackedFiles.push(filename)
181
+ else {
182
+ if (row[0] !== ' ') stagedFiles.push(filename)
183
+ if (row[1] !== ' ') unstagedFiles.push(filename)
184
+ }
185
+ }
186
+ return { stagedFiles, unstagedFiles, untrackedFiles, dirtyFiles, dirty: dirtyFiles.length > 0 }
187
+ }
188
+
189
+ function commitsOf(text) {
190
+ return line(text).split('\n').filter(Boolean).map((row) => {
191
+ const [hash, shortHash, ...subject] = row.split('\x1f')
192
+ return { hash, shortHash, subject: subject.join('\x1f') }
193
+ })
194
+ }
195
+
196
+ function gitWorktrees(repoRoot) {
197
+ const entries = []
198
+ let entry
199
+ for (const row of query(repoRoot, 'worktree', 'list', '--porcelain', '-z').split('\0')) {
200
+ const at = row.indexOf(' ')
201
+ const name = at < 0 ? row : row.slice(0, at)
202
+ const value = at < 0 ? '' : row.slice(at + 1)
203
+ if (name === 'worktree') {
204
+ entry = { path: path.resolve(value), branch: null, prunable: false }
205
+ entries.push(entry)
206
+ } else if (entry && name === 'branch') entry.branch = value.replace(/^refs\/heads\//, '')
207
+ else if (entry && name === 'prunable') entry.prunable = true
208
+ }
209
+ return entries
210
+ }
211
+
212
+ function branchExists(repoRoot, branch) {
213
+ return optionalQuery(repoRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], 1) !== null
214
+ }
215
+
216
+ function hasNewCommits(cwd, baseCommit, tip = 'HEAD') {
217
+ return Number(line(query(cwd, 'rev-list', '--count', `${baseCommit}..${tip}`))) > 0
218
+ }
219
+
220
+ function isAncestor(cwd, ancestor, descendant) {
221
+ return optionalQuery(cwd, ['merge-base', '--is-ancestor', ancestor, descendant], 1) !== null
222
+ }
223
+
224
+ function identityArgs(cwd) {
225
+ const defaults = { 'user.name': 'DSH Orchestrator', 'user.email': 'dsh-orchestrator@localhost' }
226
+ return Object.entries(defaults).flatMap(([key, value]) =>
227
+ optionalQuery(cwd, ['config', '--get', key], 1) ? [] : ['-c', `${key}=${value}`])
228
+ }
229
+
230
+ function removeWorktree(record, force = false) {
231
+ const { repoRoot, worktreePath } = record
232
+ const entry = gitWorktrees(repoRoot).find((row) => pathKey(row.path) === pathKey(worktreePath))
233
+ if (!entry && !lstat(worktreePath)) return
234
+ if (!entry || (entry.branch && entry.branch !== record.branch)) {
235
+ throw new Error('工作树登记缺失或已换用其他分支,拒绝删除目录。')
236
+ }
237
+ const directory = worktreeDirectory(record)
238
+ if (directory) assertCheckout(record)
239
+ const args = ['worktree', 'remove', ...(force ? ['--force'] : []), '--', worktreePath]
240
+ for (let attempt = 0; ; attempt += 1) {
241
+ try {
242
+ git(repoRoot, args)
243
+ return
244
+ } catch (error) {
245
+ if (!WINDOWS || attempt >= 3 || !/permission denied|access is denied|directory not empty|failed to (delete|remove)|resource busy/i.test(errorText(error))) {
246
+ throw error
247
+ }
248
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50 * (attempt + 1))
249
+ }
250
+ }
251
+ }
252
+
253
+ function sourceOperationInProgress(repoRoot) {
254
+ const gitDir = line(query(repoRoot, 'rev-parse', '--absolute-git-dir'))
255
+ return ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'rebase-apply', 'rebase-merge', 'sequencer']
256
+ .some((marker) => lstat(path.join(gitDir, marker)))
257
+ }
258
+
259
+ function worktreeDirectory({ repoRoot, worktreePath }) {
260
+ const { owner, pool } = poolPaths(repoRoot)
261
+ assertDirectory(owner)
262
+ assertDirectory(pool)
263
+ return assertDirectory(worktreePath)
264
+ }
265
+
266
+ function assertCheckout({ repoRoot, worktreePath }) {
267
+ const reported = line(query(worktreePath, 'rev-parse', '--show-toplevel'))
268
+ const common = line(query(worktreePath, 'rev-parse', '--path-format=absolute', '--git-common-dir'))
269
+ const expected = line(query(repoRoot, 'rev-parse', '--path-format=absolute', '--git-common-dir'))
270
+ if (pathKey(fs.realpathSync.native(reported)) !== pathKey(fs.realpathSync.native(worktreePath)) ||
271
+ pathKey(fs.realpathSync.native(common)) !== pathKey(fs.realpathSync.native(expected))) {
272
+ throw new Error('目录不再是原工作树根目录。')
273
+ }
274
+ }
275
+
276
+ export function createWorktreeManager({ now = () => Date.now(), newId = randomUUID } = {}) {
277
+ const records = new Map()
278
+ const children = new Map()
279
+ const childHistory = new Map()
280
+ const get = (id) => records.get(id) ?? null
281
+ const getByChild = (childId) => get(children.get(childId))
282
+ const getByWorktreeOrChild = (idOrChildId) => get(idOrChildId) ?? get(childHistory.get(idOrChildId))
283
+ const notFound = () => failure('worktree-not-found', '未找到工作树记录。')
284
+ const unsafeCheckout = (worktree) => failure('worktree-invalid-record', '工作树登记不符合受管目录或分支约束。', { worktree })
285
+ const save = (record) => {
286
+ const { childIds, locked, ...fields } = record
287
+ const snapshot = { ...fields, conflictFiles: Object.freeze([...record.conflictFiles]) }
288
+ // Keep the enumerable shape of legacy manager receipts; exportRecords owns the persistence shape.
289
+ Object.defineProperties(snapshot, {
290
+ childIds: { value: Object.freeze(childIdsOf({ childId: record.childId, childIds })) },
291
+ locked: { value: isWorktreeLockedRecord({ ...fields, locked }) },
292
+ })
293
+ const frozen = Object.freeze(snapshot)
294
+ records.set(frozen.id, frozen)
295
+ for (const childId of frozen.childIds) childHistory.set(childId, frozen.id)
296
+ return frozen
297
+ }
298
+ const update = (record, changes) => save({
299
+ ...record, childIds: record.childIds, locked: record.locked, ...changes, updatedAt: now(),
300
+ })
301
+
302
+ function exportRecords() {
303
+ return [...records.values()].map(persistedRecord)
304
+ }
305
+
306
+ function hydrateRecords(rows, { replace = false } = {}) {
307
+ let restored = 0
308
+ let skipped = 0
309
+ if (!Array.isArray(rows)) return { restored, skipped }
310
+ if (replace) clear()
311
+ for (const row of rows) {
312
+ if (!isId(row?.id) || !WORKTREE_STATES.includes(row.state) ||
313
+ (row.updatedAt != null && !Number.isFinite(row.updatedAt))) {
314
+ skipped += 1
315
+ continue
316
+ }
317
+ const updatedAt = timeOrNull(row.updatedAt) ?? timeOrNull(row.createdAt) ?? 0
318
+ const previous = get(row.id)
319
+ const childIds = [...new Set([...childIdsOf(row), ...(previous?.childIds ?? [])])]
320
+ if ((previous && previous.updatedAt > updatedAt) || childIds.some((childId) =>
321
+ childHistory.has(childId) && childHistory.get(childId) !== row.id)) {
322
+ skipped += 1
323
+ continue
324
+ }
325
+ const record = save({
326
+ ...persistedRecord({
327
+ ...row, childIds, updatedAt, locked: isWorktreeLockedRecord(row) || isWorktreeLockedRecord(previous),
328
+ mergeCommit: row.mergeCommit || previous?.mergeCommit,
329
+ cleaned: row.cleaned || previous?.cleaned,
330
+ }),
331
+ settledAt: timeOrNull(row.settledAt), closedAt: timeOrNull(row.closedAt),
332
+ conflictFiles: Array.isArray(row.conflictFiles) ? row.conflictFiles.filter(isId) : [],
333
+ error: textOrNull(row.error),
334
+ })
335
+ for (const childId of record.childIds) children.set(childId, record.id)
336
+ restored += 1
337
+ }
338
+ return { restored, skipped }
339
+ }
340
+ const cleanFailure = (record, error, fields) => {
341
+ const detail = errorText(error)
342
+ return failure('worktree-cleanup-failed', detail, {
343
+ ...fields, worktree: update(record, { state: 'cleanup_failed', error: detail }),
344
+ })
345
+ }
346
+
347
+ function create({ sourceCwd, workspaceRoot = null, label = null, parentId = null,
348
+ childId = null, batchId = null, itemIndex = null }) {
349
+ try {
350
+ const probe = probeGitRepo(sourceCwd)
351
+ if (!probe.isGit) return failure('not-git-repo', '源目录不在 Git 工作树内。')
352
+ if (!probe.headCommit) return failure('unborn-head', '源仓库没有可检出的提交。')
353
+ const { repoRoot, gitCommonDir, headCommit: baseCommit, headBranch: baseBranch, subPath } = probe
354
+ const suffix = String(newId()).replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 8).toLowerCase()
355
+ const id = `wt-${suffix}`
356
+ const branch = `${WORKTREE_BRANCH_PREFIX}${id}`
357
+ const worktreePath = path.join(poolPaths(repoRoot).pool, id)
358
+ if (workspaceRoot !== null) {
359
+ let allowed = false
360
+ try {
361
+ const root = fs.realpathSync.native(path.resolve(workspaceRoot))
362
+ allowed = isInside(root, prospectiveRealpath(worktreePath)) && isInside(root, gitCommonDir)
363
+ } catch {
364
+ // A containment boundary that cannot be resolved is not safe to use.
365
+ }
366
+ if (!allowed) return failure('worktree-outside-workspace', '工作树或共享 Git 目录超出工作区边界。', {
367
+ worktreePath, gitCommonDir, workspaceRoot,
368
+ })
369
+ }
370
+ if (!suffix || records.has(id) || lstat(worktreePath) || branchExists(repoRoot, branch)) {
371
+ return failure('worktree-id-conflict', '工作树 ID 无效或已存在。')
372
+ }
373
+ if (childId !== null && childHistory.has(childId)) return failure('worktree-child-conflict', '子代理已绑定工作树。')
374
+ ensurePoolIgnore(repoRoot)
375
+ git(repoRoot, ['worktree', 'add', '-b', branch, worktreePath, baseCommit])
376
+ const candidate = path.join(worktreePath, subPath)
377
+ const execCwd = lstat(candidate)?.isDirectory() &&
378
+ isInside(fs.realpathSync.native(worktreePath), fs.realpathSync.native(candidate)) ? candidate : worktreePath
379
+ const time = now()
380
+ const worktree = save({
381
+ id, parentId, childId, batchId, itemIndex, label, repoRoot, sourceCwd: path.resolve(sourceCwd),
382
+ subPath, worktreePath, execCwd, branch, baseCommit, baseBranch, state: 'active',
383
+ createdAt: time, updatedAt: time, settledAt: null, closedAt: null, auditSummary: null,
384
+ mergeCommit: null, conflictFiles: [], error: null,
385
+ })
386
+ if (childId !== null) children.set(childId, id)
387
+ return { ok: true, worktree }
388
+ } catch (error) {
389
+ return failure('worktree-create-failed', errorText(error))
390
+ }
391
+ }
392
+
393
+ function bindChild(worktreeId, childId) {
394
+ const record = get(worktreeId)
395
+ if (!record || !isId(childId) ||
396
+ (childHistory.has(childId) && childHistory.get(childId) !== worktreeId)) return null
397
+ children.set(childId, worktreeId)
398
+ if (record.childIds.includes(childId)) return record
399
+ return update(record, { childIds: [...record.childIds, childId] })
400
+ }
401
+
402
+ function rebindChild(id, childId) {
403
+ const record = get(id)
404
+ if (!record || (childId != null && (!isId(childId) ||
405
+ (childHistory.has(childId) && childHistory.get(childId) !== id)))) return null
406
+ children.delete(record.childId)
407
+ if (childId != null) children.set(childId, id)
408
+ return update(record, { childId: childId ?? null })
409
+ }
410
+
411
+ function getChildWorktreeMap() {
412
+ return new Map(childHistory)
413
+ }
414
+
415
+ function list({ parentId = null, state = null, includeClosed = true } = {}) {
416
+ return [...records.values()].filter((row) => (parentId === null || row.parentId === parentId) &&
417
+ (state === null || state === row.state) && (includeClosed || !CLOSED_STATES.has(row.state)))
418
+ .sort((left, right) => right.createdAt - left.createdAt)
419
+ }
420
+
421
+ function isChildLocked(childId) {
422
+ const record = get(childHistory.get(childId))
423
+ if (!record) return { locked: false }
424
+ const { id: worktreeId, state, worktreePath } = record
425
+ const locked = isWorktreeLockedRecord(record) || !worktreePath || !fs.existsSync(worktreePath)
426
+ return locked ? { locked, reason: '工作树已合回、关闭或目录已移除。', worktreeId, state }
427
+ : { locked, worktreeId, state }
428
+ }
429
+
430
+ function reopenForRetry(id) {
431
+ const record = get(id)
432
+ if (!record || isWorktreeLockedRecord(record) ||
433
+ !['ready_for_review', 'merge_conflict'].includes(record.state)) return record
434
+ return update(record, { state: 'active', conflictFiles: [], error: null })
435
+ }
436
+
437
+ function markReadyForReview(id, auditSummary = null) {
438
+ const record = get(id)
439
+ if (!record || isWorktreeLockedRecord(record) ||
440
+ !['active', 'ready_for_review'].includes(record.state)) return record
441
+ return update(record, { state: 'ready_for_review', settledAt: now(), auditSummary })
442
+ }
443
+
444
+ function inspect(idOrChildId, { maxDiffChars = 16000, maxCommits = 30 } = {}) {
445
+ const worktree = getByWorktreeOrChild(idOrChildId)
446
+ if (!worktree) return notFound()
447
+ if (!isManagedCheckout(worktree)) return unsafeCheckout(worktree)
448
+ const { worktreePath, baseCommit } = worktree
449
+ try {
450
+ if (!worktreeDirectory(worktree)) {
451
+ return { ok: true, worktree, exists: false, headCommit: null, aheadCount: 0, commits: [],
452
+ diffStat: '', diffPatch: '', diffTruncated: false, stagedFiles: [], unstagedFiles: [],
453
+ untrackedFiles: [], dirty: false }
454
+ }
455
+ assertCheckout(worktree)
456
+ const range = `${baseCommit}..HEAD`
457
+ const commitLimit = Number.isFinite(maxCommits) ? Math.max(0, Math.floor(maxCommits)) : 30
458
+ const diffLimit = Number.isFinite(maxDiffChars) ? Math.max(0, Math.floor(maxDiffChars)) : 16000
459
+ const current = status(worktreePath)
460
+ const diffArgs = ['diff', '--no-ext-diff', '--no-textconv']
461
+ const patch = query(worktreePath, ...diffArgs, baseCommit, '--')
462
+ return {
463
+ ok: true, worktree, exists: true,
464
+ headCommit: line(query(worktreePath, 'rev-parse', 'HEAD')),
465
+ aheadCount: Number(line(query(worktreePath, 'rev-list', '--count', range))),
466
+ commits: commitsOf(query(worktreePath, 'log', '--format=%H%x1f%h%x1f%s', `--max-count=${commitLimit}`, range)),
467
+ diffStat: query(worktreePath, ...diffArgs, '--stat', baseCommit, '--'),
468
+ diffPatch: patch.slice(0, diffLimit), diffTruncated: patch.length > diffLimit,
469
+ stagedFiles: current.stagedFiles, unstagedFiles: current.unstagedFiles,
470
+ untrackedFiles: current.untrackedFiles, dirty: current.dirty,
471
+ }
472
+ } catch (error) {
473
+ return failure('worktree-inspect-failed', errorText(error), { worktree })
474
+ }
475
+ }
476
+
477
+ function merge(idOrChildId, { strategy = 'merge', commitMessage = null,
478
+ autoStageDirty = false, deleteAfterMerge = true } = {}) {
479
+ let worktree = getByWorktreeOrChild(idOrChildId)
480
+ if (!worktree) return notFound()
481
+ if (!['merge', 'squash', 'ff-only'].includes(strategy)) return failure('worktree-invalid-strategy', '未知合并策略。')
482
+ if (worktree.state === 'active') return failure('worktree-active', '活跃工作树尚不能合并。', { worktree })
483
+ if (worktree.mergeCommit !== null) {
484
+ const needsCleanup = worktree.state !== 'discarded' && worktree.cleaned === false
485
+ const message = '工作树已合回,不要重复合并。' + (needsCleanup
486
+ ? '请调用 worktree_manage(action: "discard", force: true) 清理残留目录或分支。' : '')
487
+ return failure('worktree-already-closed', message, { worktree, mergeCommit: worktree.mergeCommit })
488
+ }
489
+ if (isWorktreeLockedRecord(worktree)) {
490
+ return failure('worktree-already-closed', '工作树已关闭。', { worktree })
491
+ }
492
+ if (!isManagedCheckout(worktree)) return unsafeCheckout(worktree)
493
+ const { repoRoot, worktreePath, branch, baseCommit } = worktree
494
+ const message = commitMessage ?? `Merge worktree ${branch}`
495
+ let autoCommitted = false
496
+ try {
497
+ if (!worktreeDirectory(worktree)) return failure('worktree-missing', '待合并的工作树目录不存在。', { worktree })
498
+ assertCheckout(worktree)
499
+ const checkedOut = optionalQuery(worktreePath, ['symbolic-ref', '--quiet', '--short', 'HEAD'], 1)
500
+ if (checkedOut !== branch) return failure('worktree-branch-changed', '工作树不再检出原隔离分支。', { worktree })
501
+ const dirtyFiles = status(worktreePath).dirtyFiles
502
+ if (dirtyFiles.length && !autoStageDirty) {
503
+ return failure('worktree-dirty', '工作树仍有未提交改动。', { dirtyFiles, worktree })
504
+ }
505
+ if (!dirtyFiles.length && !hasNewCommits(worktreePath, baseCommit)) {
506
+ return { ok: true, noop: true, merged: false, autoCommitted, worktree }
507
+ }
508
+ // Check the source before auto-committing too: a refusal should not mutate either checkout.
509
+ const sourceDirty = status(repoRoot).dirtyFiles
510
+ if (sourceDirty.length) return failure('source-repo-dirty', '源仓库有未提交改动。', { dirtyFiles: sourceDirty, worktree })
511
+ if (sourceOperationInProgress(repoRoot)) {
512
+ return failure('source-repo-busy', '源仓库已有未完成的 Git 操作。', { worktree })
513
+ }
514
+ if (dirtyFiles.length) {
515
+ git(worktreePath, ['add', '-A'])
516
+ git(worktreePath, [...identityArgs(worktreePath), 'commit', '-m', message])
517
+ autoCommitted = true
518
+ const remaining = status(worktreePath).dirtyFiles
519
+ if (remaining.length) {
520
+ return failure('worktree-dirty', '自动提交后仍有未提交改动。', { dirtyFiles: remaining, autoCommitted, worktree })
521
+ }
522
+ }
523
+ const latestSourceDirty = status(repoRoot).dirtyFiles
524
+ if (latestSourceDirty.length) return failure('source-repo-dirty', '源仓库有未提交改动。', {
525
+ dirtyFiles: latestSourceDirty, autoCommitted, worktree,
526
+ })
527
+ if (sourceOperationInProgress(repoRoot)) {
528
+ return failure('source-repo-busy', '源仓库已有未完成的 Git 操作。', { autoCommitted, worktree })
529
+ }
530
+ let squashStaged = false
531
+ try {
532
+ if (strategy === 'squash') {
533
+ git(repoRoot, ['merge', '--squash', branch])
534
+ squashStaged = true
535
+ if (status(repoRoot).stagedFiles.length) git(repoRoot, [...identityArgs(repoRoot), 'commit', '-m', message])
536
+ } else if (strategy === 'ff-only') {
537
+ git(repoRoot, ['merge', '--ff-only', branch])
538
+ } else {
539
+ git(repoRoot, [...identityArgs(repoRoot), 'merge', '--no-ff', branch, '-m', message])
540
+ }
541
+ } catch (error) {
542
+ const conflictFiles = [...new Set(query(repoRoot, 'diff', '--name-only', '--diff-filter=U', '-z').split('\0').filter(Boolean))]
543
+ const detail = errorText(error)
544
+ let rollbackError = null
545
+ try {
546
+ if (strategy === 'squash' && (squashStaged || conflictFiles.length)) git(repoRoot, ['reset', '--merge'])
547
+ else if (strategy !== 'squash' && sourceOperationInProgress(repoRoot)) git(repoRoot, ['merge', '--abort'])
548
+ } catch (rollback) {
549
+ rollbackError = errorText(rollback)
550
+ }
551
+ if (conflictFiles.length) worktree = update(worktree, { state: 'merge_conflict', conflictFiles, error: detail })
552
+ return failure(conflictFiles.length ? 'merge-conflict' : 'worktree-merge-failed',
553
+ rollbackError ? `${detail}\n源仓回退失败:${rollbackError}` : detail,
554
+ { conflictFiles, worktreePath, branch, worktree, autoCommitted, ...(rollbackError && { rollbackError }) })
555
+ }
556
+ const mergeCommit = line(query(repoRoot, 'rev-parse', 'HEAD'))
557
+ worktree = update(worktree, { mergeCommit, cleaned: false, conflictFiles: [], error: null })
558
+ if (deleteAfterMerge) {
559
+ try {
560
+ removeWorktree(worktree)
561
+ if (branchExists(repoRoot, branch)) git(repoRoot, ['branch', '-d', '--', branch])
562
+ } catch (error) {
563
+ return cleanFailure(worktree, error, { merged: true, cleaned: false, mergeCommit, autoCommitted })
564
+ }
565
+ }
566
+ worktree = update(worktree, { state: 'merged', cleaned: deleteAfterMerge, closedAt: now() })
567
+ return { ok: true, merged: true, cleaned: deleteAfterMerge, mergeCommit, autoCommitted, worktree }
568
+ } catch (error) {
569
+ return failure('worktree-merge-failed', errorText(error), { worktree, autoCommitted })
570
+ }
571
+ }
572
+
573
+ function discard(idOrChildId, { force = false } = {}) {
574
+ const worktree = getByWorktreeOrChild(idOrChildId)
575
+ if (!worktree) return notFound()
576
+ if (worktree.state === 'discarded') return { ok: true, discarded: true, worktree }
577
+ if (worktree.state === 'active' && !force) return failure('worktree-active', '活跃工作树必须显式强制丢弃。', { worktree })
578
+ if (!isManagedCheckout(worktree)) return unsafeCheckout(worktree)
579
+ const { repoRoot, worktreePath, branch, baseCommit, mergeCommit } = worktree
580
+ try {
581
+ const directory = worktreeDirectory(worktree)
582
+ if (directory) {
583
+ assertCheckout(worktree)
584
+ if (!force) {
585
+ const { dirtyFiles } = status(worktreePath)
586
+ if (dirtyFiles.length) return failure('worktree-dirty', '工作树仍有未提交改动。', { dirtyFiles, worktree })
587
+ }
588
+ }
589
+ if (!force && !mergeCommit) {
590
+ // Check the actual worktree tip as well as the original branch before any deletion.
591
+ const refs = [...(branchExists(repoRoot, branch) ? [branch] : [])]
592
+ if (directory) refs.push(line(query(worktreePath, 'rev-parse', 'HEAD')))
593
+ if (refs.some((ref) => hasNewCommits(repoRoot, baseCommit, ref) && !isAncestor(repoRoot, ref, 'HEAD'))) {
594
+ return failure('worktree-unmerged', '工作树仍有未合并提交,必须显式强制丢弃。', { worktree })
595
+ }
596
+ }
597
+ removeWorktree(worktree, force)
598
+ if (branchExists(repoRoot, branch)) git(repoRoot, ['branch', '-D', '--', branch])
599
+ return { ok: true, discarded: true, worktree: update(worktree, {
600
+ state: 'discarded', closedAt: now(), error: null, ...(mergeCommit !== null && { cleaned: true }),
601
+ }) }
602
+ } catch (error) {
603
+ return cleanFailure(worktree, error, { discarded: false })
604
+ }
605
+ }
606
+
607
+ function prune({ repoRoot, dryRun = false } = {}) {
608
+ try {
609
+ const probe = probeGitRepo(repoRoot)
610
+ if (!probe.isGit) return failure('not-git-repo', '清理目录不在 Git 工作树内。')
611
+ repoRoot = probe.repoRoot
612
+ const { owner, pool } = poolPaths(repoRoot)
613
+ assertDirectory(owner)
614
+ const poolExists = assertDirectory(pool)
615
+ const protectedPaths = new Set(list().filter((row) => PROTECTED_STATES.has(row.state) && isManagedCheckout(row))
616
+ .map((row) => pathKey(row.worktreePath)))
617
+ const entries = gitWorktrees(repoRoot)
618
+ const registered = new Map(entries.map((entry) => [pathKey(entry.path), entry]))
619
+ const inPool = (filename) => pathKey(path.dirname(filename)) === pathKey(pool)
620
+ const eligible = (filename) => inPool(filename) && !protectedPaths.has(pathKey(filename))
621
+ const missingWorktrees = entries.filter((entry) => entry.prunable && eligible(entry.path) && !lstat(entry.path))
622
+ const loose = (poolExists ? fs.readdirSync(pool, { withFileTypes: true }) : [])
623
+ .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
624
+ .map((entry) => path.join(pool, entry.name))
625
+ .filter((filename) => eligible(filename) && !registered.has(pathKey(filename)))
626
+ const orphans = [...loose, ...missingWorktrees.map((entry) => entry.path)].sort()
627
+ const result = { ok: true, dryRun, repoRoot, orphans, prunedWorktrees: [], prunedBranches: [], errors: [] }
628
+ if (dryRun) return result
629
+ const note = (filename, error) => result.errors.push({ path: filename, message: errorText(error) })
630
+ const branchCandidates = new Set()
631
+ // `git worktree prune` is repository-wide; never let it touch unrelated or protected entries.
632
+ const allowedPrunable = new Set(missingWorktrees.map((entry) => pathKey(entry.path)))
633
+ if (!entries.some((entry) => entry.prunable && !allowedPrunable.has(pathKey(entry.path)))) {
634
+ try {
635
+ git(repoRoot, ['worktree', 'prune'])
636
+ const remaining = new Set(gitWorktrees(repoRoot).map((entry) => pathKey(entry.path)))
637
+ for (const entry of missingWorktrees) {
638
+ if (remaining.has(pathKey(entry.path))) continue
639
+ result.prunedWorktrees.push(entry.path)
640
+ if (entry.branch) branchCandidates.add(entry.branch)
641
+ }
642
+ } catch (error) {
643
+ note(pool, error)
644
+ }
645
+ } else if (missingWorktrees.length) {
646
+ note(pool, new Error('Git 清理会影响池外或受保护的登记项,已跳过。'))
647
+ }
648
+ for (const filename of loose) {
649
+ try {
650
+ if (!assertDirectory(filename)) continue
651
+ // An independently owned checkout is not a disposable orphan.
652
+ if (lstat(path.join(filename, '.git'))) throw new Error('目录含 Git 元数据,拒绝自动清理。')
653
+ if (gitWorktrees(repoRoot).some((row) => pathKey(row.path) === pathKey(filename))) continue
654
+ fs.rmSync(filename, { recursive: true, force: false })
655
+ result.prunedWorktrees.push(filename)
656
+ branchCandidates.add(`${WORKTREE_BRANCH_PREFIX}${path.basename(filename)}`)
657
+ } catch (error) {
658
+ note(filename, error)
659
+ }
660
+ }
661
+ for (const branch of branchCandidates) {
662
+ if (!branch.startsWith(WORKTREE_BRANCH_PREFIX)) continue
663
+ try {
664
+ if (branchExists(repoRoot, branch) && !gitWorktrees(repoRoot).some((row) => row.branch === branch)) {
665
+ git(repoRoot, ['branch', '-D', '--', branch])
666
+ result.prunedBranches.push(branch)
667
+ }
668
+ } catch (error) {
669
+ note(branch, error)
670
+ }
671
+ }
672
+ return result
673
+ } catch (error) {
674
+ return failure('worktree-prune-failed', errorText(error))
675
+ }
676
+ }
677
+
678
+ function clear() {
679
+ records.clear()
680
+ children.clear()
681
+ childHistory.clear()
682
+ }
683
+
684
+ return { create, rebindChild, bindChild, get, getByChild, getByWorktreeOrChild, list, isChildLocked,
685
+ getChildWorktreeMap, exportRecords, hydrateRecords, markReadyForReview, reopenForRetry,
686
+ inspect, merge, discard, prune, clear }
687
+ }