dsh-asuta-worktree-control 0.0.0-stage → 0.1.2

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/git.js ADDED
@@ -0,0 +1,1011 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { promisify, stripVTControlCharacters } from 'node:util'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { AsyncLocalStorage } from 'node:async_hooks'
5
+ import { copyFile, lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises'
6
+ import { tmpdir } from 'node:os'
7
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'
8
+ import ignore from 'ignore'
9
+ import { parse as parseToml } from 'smol-toml'
10
+
11
+ const execute = promisify(execFile)
12
+ const COMMAND_CONTEXT = new AsyncLocalStorage()
13
+ const SETUP_RUNNER = new AsyncLocalStorage()
14
+ const LIMIT = 8 * 1024 * 1024
15
+ const MAX_SNAPSHOT_BYTES = 512 * 1024 * 1024
16
+ const LOCKS = new Map()
17
+ const GIT_ENV_KEYS = [
18
+ 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',
19
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT',
20
+ 'GIT_CEILING_DIRECTORIES', 'GIT_PREFIX', 'GIT_SHALLOW_FILE', 'GIT_GRAFT_FILE', 'GIT_REPLACE_REF_BASE', 'GIT_ATTR_SOURCE',
21
+ ]
22
+
23
+ function envForGit(extra = {}) {
24
+ const allowed = process.platform === 'win32'
25
+ ? ['PATH', 'PATHEXT', 'SYSTEMROOT', 'WINDIR', 'COMSPEC', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'TEMP', 'TMP', 'SSH_AUTH_SOCK']
26
+ : ['PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL', 'TERM', 'SSH_AUTH_SOCK']
27
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => allowed.some(name => name.toLowerCase() === key.toLowerCase())))
28
+ Object.assign(env, { GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', ...extra })
29
+ for (const key of GIT_ENV_KEYS) if (!(key in extra)) delete env[key]
30
+ return env
31
+ }
32
+
33
+ export async function git(cwd, args, options = {}) {
34
+ const runtime = COMMAND_CONTEXT.getStore()
35
+ if (runtime) return runManagedCommand(runtime, cwd, ['git', '--no-pager', '-c', 'core.quotepath=false', '-c', 'core.fsmonitor=false', ...args], options)
36
+ const { stdout } = await execute('git', ['--no-pager', '-c', 'core.quotepath=false', '-c', 'core.fsmonitor=false', ...args], {
37
+ cwd, windowsHide: true, encoding: 'utf8', timeout: options.timeout ?? 30000,
38
+ maxBuffer: options.maxBuffer ?? LIMIT, env: envForGit(options.env),
39
+ })
40
+ return stdout
41
+ }
42
+
43
+ async function runManagedCommand(runtime, cwd, argv, options = {}) {
44
+ const timeoutMs = options.timeout ?? 30000
45
+ const controller = new AbortController()
46
+ const timeout = setTimeout(() => controller.abort(new Error('工作树命令超时。')), timeoutMs)
47
+ const signal = runtime.signal ? AbortSignal.any([runtime.signal, controller.signal]) : controller.signal
48
+ let child
49
+ try {
50
+ signal.throwIfAborted()
51
+ const command = [await runtime.ctx.subprocess.resolveExecutable(argv[0], undefined, signal), ...argv.slice(1)]
52
+ const wrapped = runtime.policy.mode === 'danger-full-access' ? command : (await runtime.ctx.sandbox.confine(command, { ...runtime.policy, mode: runtime.policy.mode }, signal)).argv
53
+ child = runtime.ctx.subprocess.spawn({
54
+ argv: wrapped, cwd, env: envForGit(options.env), signal,
55
+ graceMs: 3000,
56
+ stdio: { stdin: 'ignore', stdout: { maxBytes: options.maxBuffer ?? LIMIT }, stderr: { maxBytes: options.maxBuffer ?? LIMIT } },
57
+ })
58
+ const outcome = await child.done
59
+ const captured = child.collected
60
+ const stdout = captured.stdout.readFrom(0)
61
+ const stderr = captured.stderr.readFrom(0)
62
+ const allowed = options.allowedExitCodes ?? [0]
63
+ if (outcome.exitCode === null || !allowed.includes(outcome.exitCode)) {
64
+ const detail = stderr.text.trim() || stdout.text.trim()
65
+ throw new Error(argv[0] + ' command failed (' + (outcome.signal ?? outcome.exitCode) + '): ' + detail.slice(-4000))
66
+ }
67
+ if (stdout.lossy || stderr.lossy) throw new Error('工作树命令输出超过大小上限。')
68
+ return stdout.text
69
+ } finally {
70
+ clearTimeout(timeout)
71
+ if (child) { child.terminate(); await child.waitForExit() }
72
+ }
73
+ }
74
+
75
+ export function withCommandContext(ctx, session, operation, signal) {
76
+ const policy = ctx.sandboxPolicy.resolve({ session })
77
+ return COMMAND_CONTEXT.run({ ctx, session, policy, signal }, operation)
78
+ }
79
+
80
+ // The UI adapter supplies a visible terminal without changing Git operations.
81
+ export function withSetupRunner(runner, operation) {
82
+ return SETUP_RUNNER.run(runner, operation)
83
+ }
84
+
85
+ async function runManagedTerminal(runtime, cwd, argv, options) {
86
+ const controller = new AbortController()
87
+ const signal = AbortSignal.any([runtime.signal, options.signal, controller.signal].filter(Boolean))
88
+ const timer = options.timeout ? setTimeout(() => controller.abort(new Error('环境命令超时。')), options.timeout) : null
89
+ let child, output = '', drain
90
+ const stop = () => { void child?.terminate().catch(() => {}) }
91
+ try {
92
+ signal.throwIfAborted()
93
+ const command = [await runtime.ctx.subprocess.resolveExecutable(argv[0], undefined, signal), ...argv.slice(1)]
94
+ const wrapped = runtime.policy.mode === 'danger-full-access' ? command : (await runtime.ctx.sandbox.confine(command, runtime.policy, signal)).argv
95
+ child = await runtime.ctx.subprocess.spawnTerminal({ argv: wrapped, cwd, env: envForGit(options.env),
96
+ cols: 100, rows: 28, terminalType: 'xterm-256color', shellActivity: false, graceMs: 3000, signal })
97
+ signal.addEventListener('abort', stop, { once: true })
98
+ if (signal.aborted) stop()
99
+ options.onTerminal?.(child)
100
+ drain = (async () => {
101
+ const decoder = new TextDecoder()
102
+ for await (const chunk of child.output) {
103
+ const text = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true })
104
+ output = (output + text).slice(-16000)
105
+ options.onOutput?.(text)
106
+ }
107
+ const tail = decoder.decode()
108
+ if (tail) { output = (output + tail).slice(-16000); options.onOutput?.(tail) }
109
+ })()
110
+ // Observe both promises immediately; stream failures must also stop the process.
111
+ const [outcome] = await Promise.all([child.done, drain])
112
+ signal.throwIfAborted()
113
+ if (outcome.exitCode !== 0) throw new Error('命令退出:' + (outcome.signal ?? outcome.exitCode) + '\n' + output.slice(-4000))
114
+ return output
115
+ } finally {
116
+ clearTimeout(timer)
117
+ signal.removeEventListener('abort', stop)
118
+ if (child) await child.terminate()
119
+ await drain?.catch(() => {})
120
+ }
121
+ }
122
+
123
+ const keyPath = value => process.platform === 'win32' ? resolve(value).toLowerCase() : resolve(value)
124
+ const samePath = (a, b) => keyPath(a) === keyPath(b)
125
+ const splitNul = value => value.split('\0').filter(Boolean)
126
+
127
+ export async function withRepoLock(key, operation) {
128
+ const lockKey = keyPath(key)
129
+ const previous = LOCKS.get(lockKey) ?? Promise.resolve()
130
+ let release
131
+ const current = new Promise(resolveLock => { release = resolveLock })
132
+ LOCKS.set(lockKey, current)
133
+ await previous
134
+ try { return await operation() } finally {
135
+ release()
136
+ if (LOCKS.get(lockKey) === current) LOCKS.delete(lockKey)
137
+ }
138
+ }
139
+
140
+ export async function repository(cwd) {
141
+ const root = resolve((await git(cwd, ['rev-parse', '--show-toplevel'])).trim())
142
+ const commonDir = resolve(root, (await git(root, ['rev-parse', '--git-common-dir'])).trim())
143
+ const canonicalRoot = await realpath(root)
144
+ const canonicalCommon = await realpath(commonDir)
145
+ return { root: canonicalRoot, commonDir: canonicalCommon, stateDir: resolve(canonicalCommon, 'dsh-worktree-control') }
146
+ }
147
+
148
+ export async function listWorktrees(cwd) {
149
+ const info = await repository(cwd)
150
+ const raw = await git(info.root, ['worktree', 'list', '--porcelain', '-z'])
151
+ const rows = []
152
+ let row = {}
153
+ for (const field of raw.split('\0')) {
154
+ if (!field) {
155
+ if (row.path) rows.push(row)
156
+ row = {}
157
+ continue
158
+ }
159
+ const split = field.indexOf(' ')
160
+ const name = split < 0 ? field : field.slice(0, split)
161
+ const value = split < 0 ? '' : field.slice(split + 1)
162
+ if (name === 'worktree') row.path = resolve(value)
163
+ else if (name === 'HEAD') row.head = value
164
+ else if (name === 'branch') row.branch = value.replace(/^refs\/heads\//, '')
165
+ else if (name === 'detached') row.detached = true
166
+ else if (name === 'bare') row.bare = true
167
+ else if (name === 'locked') row.locked = value || true
168
+ else if (name === 'prunable') row.prunable = value || true
169
+ }
170
+ if (row.path) rows.push(row)
171
+ return { ...info, worktrees: rows }
172
+ }
173
+
174
+ function emptyState() { return { version: 1, retentionLimit: 15, worktreeRoot: '', worktrees: {}, archives: [], environments: [], defaultEnvironmentId: '', sessionEnvironments: {}, sessionSetupWarnings: {}, drafts: {} } }
175
+
176
+ async function loadState(info) {
177
+ const file = resolve(info.stateDir, 'state.json')
178
+ let value
179
+ try { value = JSON.parse(await readFile(file, 'utf8')) } catch (error) {
180
+ if (error.code === 'ENOENT') return emptyState()
181
+ throw new Error('工作树元数据无法读取;为避免覆盖数据,已停止操作。')
182
+ }
183
+ if (value?.version !== 1 || !value.worktrees || !Array.isArray(value.archives)) throw new Error('工作树元数据格式不受支持;已停止操作。')
184
+ return { ...emptyState(), ...value }
185
+ }
186
+
187
+ async function saveState(info, state) {
188
+ await mkdir(info.stateDir, { recursive: true })
189
+ const file = resolve(info.stateDir, 'state.json')
190
+ const temp = resolve(info.stateDir, 'state-' + randomUUID() + '.tmp')
191
+ await writeFile(temp, JSON.stringify(state, null, 2) + '\n', { flag: 'wx' })
192
+ await rename(temp, file)
193
+ }
194
+
195
+ async function refs(cwd) {
196
+ const raw = await git(cwd, ['for-each-ref', '--format=%(refname:short)', 'refs/heads', 'refs/remotes'])
197
+ return [...new Set(raw.trim().split(/\r?\n/).filter(Boolean).filter(value => !value.endsWith('/HEAD')))]
198
+ }
199
+
200
+ function safeBranch(value) {
201
+ if (!value) return ''
202
+ if (value.length > 180 || value.startsWith('-') || value.includes('\\') || value.includes(':') || value.split('/').some(part => !part || part === '.' || part === '..') || !/^[\w./-]+$/.test(value)) throw new Error('分支名只允许字母、数字、点、下划线、连字符和斜杠,且不能包含路径跳转。')
203
+ return value
204
+ }
205
+
206
+ function safeRelative(value) {
207
+ if (!value || value.includes('\0') || isAbsolute(value) || value.includes('\\') || value.includes(':') || value.split('/').some(part => !part || part === '.' || part === '..' || part.toLowerCase() === '.git')) throw new Error('文件路径必须是仓库内的相对路径。')
208
+ return value
209
+ }
210
+
211
+ function inside(parent, child) {
212
+ const part = relative(parent, child)
213
+ return part === '' || (part !== '..' && !part.startsWith('..' + sep) && !isAbsolute(part))
214
+ }
215
+
216
+ function freshName() {
217
+ const now = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z')
218
+ return 'worktree-' + now + '-' + randomUUID().slice(0, 6)
219
+ }
220
+
221
+ function addSession(record, sessionId) {
222
+ const ids = new Set(record.sessionIds ?? [])
223
+ if (sessionId && /^[\w-]{1,128}$/.test(sessionId)) ids.add(sessionId)
224
+ return [...ids]
225
+ }
226
+
227
+ function isSnapshotSafe(rawStatus) {
228
+ if (/(?:^|\0)160000 [0-9a-f]+ \d+\t/.test(rawStatus)) throw new Error('此工作树包含子模块;为避免产生不完整快照,暂不能归档。')
229
+ }
230
+
231
+ async function includedPaths(root) {
232
+ const file = resolve(root, '.worktreeinclude')
233
+ const source = await readFile(file, 'utf8').catch(error => error.code === 'ENOENT' ? '' : Promise.reject(error))
234
+ const matcher = ignore().add(source).add('AGENTS.override.md')
235
+ const ignored = splitNul(await git(root, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z']))
236
+ return ignored.filter(path => !path.startsWith('.agents/worktrees/') && matcher.ignores(path))
237
+ }
238
+
239
+ async function collectFiles(root, requested, maxBytes = MAX_SNAPSHOT_BYTES) {
240
+ const files = []
241
+ let total = 0
242
+ async function visit(path) {
243
+ const target = resolve(root, path)
244
+ if (!inside(root, target)) throw new Error('工作树路径越界。')
245
+ await assertSafeParents(root, path)
246
+ const info = await lstat(target).catch(error => error.code === 'ENOENT' ? null : Promise.reject(error))
247
+ if (!info) return
248
+ if (info.isSymbolicLink()) throw new Error('所选本地配置包含符号链接;为避免越界读取,已停止复制。')
249
+ if (info.isDirectory()) {
250
+ for (const entry of await readdir(target)) await visit(path + '/' + entry)
251
+ } else if (info.isFile()) {
252
+ total += info.size
253
+ if (total > maxBytes) throw new Error('本地文件总量超过安全上限。')
254
+ files.push({ path, target, size: info.size })
255
+ } else throw new Error('所选路径包含非普通文件。')
256
+ }
257
+ for (const path of requested) await visit(safeRelative(path))
258
+ return files
259
+ }
260
+
261
+ async function copyIncluded(sourceRoot, destination) {
262
+ const requested = await includedPaths(sourceRoot)
263
+ const files = await collectFiles(sourceRoot, requested)
264
+ for (const file of files) {
265
+ const target = resolve(destination, file.path)
266
+ if (!inside(destination, target)) throw new Error('本地配置目标路径越界。')
267
+ await assertSafeParents(destination, file.path)
268
+ if (await lstat(target).catch(error => error.code === 'ENOENT' ? null : Promise.reject(error))) continue
269
+ await mkdir(dirname(target), { recursive: true })
270
+ await copyFile(file.target, target)
271
+ }
272
+ return files.map(file => file.path)
273
+ }
274
+
275
+ async function assertSafeParents(root, path) {
276
+ const parts = safeRelative(path).split('/')
277
+ let current = root
278
+ for (const part of parts.slice(0, -1)) {
279
+ current = resolve(current, part)
280
+ const stat = await lstat(current).catch(error => error.code === 'ENOENT' ? null : Promise.reject(error))
281
+ if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error('文件父路径包含链接或不是目录:' + path)
282
+ }
283
+ }
284
+
285
+ async function ensureWorktreePool(root, pool, destination) {
286
+ const runtime = COMMAND_CONTEXT.getStore()
287
+ if (runtime && runtime.policy.mode !== 'danger-full-access' && !inside(runtime.policy.workspaceRoot, destination)) throw new Error('目标目录超出当前对话可写范围,请先调整权限或使用项目内的工作树目录。')
288
+ if (inside(root, destination)) await assertSafeParents(root, relative(root, destination).split(sep).join('/'))
289
+ const exists = await lstat(pool).catch(error => error.code === 'ENOENT' ? null : Promise.reject(error))
290
+ if (!exists) {
291
+ await mkdir(dirname(pool), { recursive: true })
292
+ await mkdir(pool)
293
+ await writeFile(resolve(pool, '.gitignore'), '*\n', { flag: 'wx' })
294
+ return
295
+ }
296
+ if (!exists.isDirectory() || exists.isSymbolicLink()) throw new Error('工作树容器路径不是普通目录。')
297
+ if (!inside(root, destination)) return
298
+ const relativeTarget = relative(root, destination).split(sep).join('/')
299
+ try { await git(root, ['check-ignore', '--quiet', '--no-index', '--', relativeTarget]) }
300
+ catch { throw new Error('已有 .agents/worktrees 目录尚未被 Git 忽略。请先在其中配置 .gitignore,再创建工作树。') }
301
+ }
302
+
303
+ async function captureDirtyState(root) {
304
+ const staged = await git(root, ['diff', '--cached', '--binary', '--full-index', 'HEAD', '--'])
305
+ const unstaged = await git(root, ['diff', '--binary', '--full-index', '--'])
306
+ const names = splitNul(await git(root, ['ls-files', '--others', '--exclude-standard', '-z']))
307
+ const files = await collectFiles(root, names)
308
+ return { staged, unstaged, files }
309
+ }
310
+
311
+ async function applyPatch(root, patch, label) {
312
+ if (!patch) return
313
+ const file = resolve(tmpdir(), 'dsh-worktree-' + randomUUID() + '.patch')
314
+ await writeFile(file, patch, { flag: 'wx' })
315
+ try { await git(root, ['apply', '--binary', file], { timeout: 60000 }) }
316
+ catch (error) { throw new Error('无法带入' + label + '改动,源工作树保持原样;新工作树创建失败:' + error.message) }
317
+ finally { await rm(file, { force: true }) }
318
+ }
319
+
320
+ function activeMap(trees, state) {
321
+ const paths = new Map(trees.map(tree => [keyPath(tree.path), tree]))
322
+ return Object.entries(state.worktrees).filter(([path, record]) => paths.has(keyPath(path))).map(([path, record]) => ({ ...record, ...paths.get(keyPath(path)), managed: true }))
323
+ }
324
+
325
+ export async function overview(cwd, sessionId, options = {}) {
326
+ const info = await listWorktrees(cwd)
327
+ const state = await loadState(info)
328
+ if (options.retentionLimit !== undefined) {
329
+ state.retentionLimit = normalizeRetention(options.retentionLimit)
330
+ await saveState(info, state)
331
+ }
332
+ const currentPath = resolve(cwd)
333
+ const currentRoot = (await git(currentPath, ['rev-parse', '--show-toplevel']).catch(() => currentPath)).trim()
334
+ const rows = activeMap(info.worktrees, state).map(tree => ({ ...tree, managed: true, current: samePath(tree.path, currentRoot), pinned: Boolean(tree.pinned) }))
335
+ const primary = info.worktrees.find(tree => !tree.bare)
336
+ for (const tree of info.worktrees.filter(tree => !tree.bare)) if (!rows.some(row => samePath(row.path, tree.path))) rows.unshift({
337
+ ...tree, managed: false, primary: tree === primary, pinned: false, sessionIds: [], current: samePath(tree.path, currentRoot),
338
+ })
339
+ return {
340
+ repositoryRoot: info.root,
341
+ primaryRoot: info.worktrees.find(tree => !tree.bare)?.path ?? info.root,
342
+ currentPath,
343
+ currentRoot,
344
+ branches: await refs(info.root),
345
+ retentionLimit: state.retentionLimit,
346
+ worktreeRoot: state.worktreeRoot || resolve(primary?.path ?? info.root, '.agents', 'worktrees'),
347
+ worktrees: rows,
348
+ archives: state.archives.filter(item => !item.restoredAt && !item.deletedAt).sort((a, b) => b.archivedAt.localeCompare(a.archivedAt)),
349
+ sessionId,
350
+ }
351
+ }
352
+
353
+ function normalizeRetention(value) {
354
+ const result = Number(value)
355
+ if (!Number.isSafeInteger(result) || result < 0 || result > 200) throw new Error('保留数量必须是 0 到 200 的整数;0 表示不自动清理。')
356
+ return result
357
+ }
358
+
359
+ export async function setPinned(cwd, path, pinned) {
360
+ const info = await listWorktrees(cwd)
361
+ return withRepoLock(info.commonDir, async () => {
362
+ const state = await loadState(info)
363
+ const record = state.worktrees[resolve(path)]
364
+ if (!record) throw new Error('只能固定由工作树控制插件创建的工作树。')
365
+ record.pinned = Boolean(pinned)
366
+ await saveState(info, state)
367
+ return { path: record.path, pinned: record.pinned }
368
+ })
369
+ }
370
+
371
+ export async function configure(cwd, values = {}) {
372
+ const info = await repository(cwd)
373
+ return withRepoLock(info.commonDir, async () => {
374
+ const state = await loadState(info)
375
+ if (values.retentionLimit !== undefined) state.retentionLimit = normalizeRetention(values.retentionLimit)
376
+ if (values.worktreeRoot !== undefined) {
377
+ if (typeof values.worktreeRoot !== 'string' || !isAbsolute(values.worktreeRoot)) throw new Error('工作树根目录必须是绝对路径。')
378
+ const target = resolve(values.worktreeRoot)
379
+ if (inside(info.commonDir, target)) throw new Error('工作树根目录不能放在 Git 元数据目录内。')
380
+ state.worktreeRoot = target
381
+ }
382
+ await saveState(info, state)
383
+ return overview(cwd)
384
+ })
385
+ }
386
+
387
+ export async function createWorktree(cwd, options = {}) {
388
+ const info = await listWorktrees(cwd)
389
+ return withRepoLock(info.commonDir, async () => {
390
+ const state = await loadState(info)
391
+ const baseRef = options.baseRef || 'HEAD'
392
+ const knownRefs = await refs(info.root)
393
+ if (baseRef !== 'HEAD' && !knownRefs.includes(baseRef)) throw new Error('请选择仓库中存在的分支或远端分支。')
394
+ const baseCommit = (await git(info.root, ['rev-parse', '--verify', '--end-of-options', baseRef + '^{commit}'])).trim()
395
+ const branch = safeBranch(options.branch ?? '')
396
+ if (branch) await git(info.root, ['check-ref-format', '--branch', branch])
397
+ if (branch && (await git(info.root, ['show-ref', '--verify', '--quiet', 'refs/heads/' + branch]).then(() => true).catch(() => false))) throw new Error('本地分支已存在:' + branch)
398
+ const name = safeBranch(options.name || (branch ? branch.replaceAll('/', '--') : freshName()))
399
+ const primaryRoot = info.worktrees.find(tree => !tree.bare)?.path ?? info.root
400
+ const pool = state.worktreeRoot || resolve(primaryRoot, '.agents', 'worktrees')
401
+ const destination = resolve(pool, ...name.split('/'))
402
+ if (!inside(pool, destination) || samePath(destination, primaryRoot)) throw new Error('工作树目标目录无效。')
403
+ if (await lstat(destination).catch(error => error.code === 'ENOENT' ? null : Promise.reject(error))) throw new Error('工作树目录已存在:' + destination)
404
+
405
+ const source = resolve(cwd)
406
+ const changes = options.includeChanges ? await captureDirtyState(source) : { staged: '', unstaged: '', files: [] }
407
+ await ensureWorktreePool(primaryRoot, pool, destination)
408
+ await mkdir(dirname(destination), { recursive: true })
409
+ const addArgs = branch ? ['worktree', 'add', '-b', branch, '--', destination, baseCommit] : ['worktree', 'add', '--detach', '--', destination, baseCommit]
410
+ await git(info.root, addArgs, { timeout: 120000 })
411
+ const tree = { path: destination, branch, head: baseCommit, createdAt: new Date().toISOString(), lastUsedAt: new Date().toISOString(), pinned: false, sessionIds: options.sessionId ? [options.sessionId] : [], includedFiles: [] }
412
+ state.worktrees[destination] = tree
413
+ try {
414
+ await saveState(info, state)
415
+ if (changes.staged) {
416
+ const patchFile = resolve(tmpdir(), 'dsh-worktree-staged-' + randomUUID() + '.patch')
417
+ await writeFile(patchFile, changes.staged, { flag: 'wx' })
418
+ try { await git(destination, ['apply', '--3way', '--binary', '--index', patchFile], { timeout: 60000 }) }
419
+ finally { await rm(patchFile, { force: true }) }
420
+ }
421
+ await applyPatch(destination, changes.unstaged, '未暂存')
422
+ for (const file of changes.files) {
423
+ const target = resolve(destination, file.path)
424
+ if (!inside(destination, target)) throw new Error('未跟踪文件路径越界。')
425
+ await assertSafeParents(destination, file.path)
426
+ if (await lstat(target).catch(error => error.code === 'ENOENT' ? null : Promise.reject(error))) throw new Error('目标分支存在同名文件:' + file.path)
427
+ await mkdir(dirname(target), { recursive: true })
428
+ await copyFile(file.target, target)
429
+ }
430
+ const included = await copyIncluded(source, destination)
431
+ tree.includedFiles = included
432
+ if (options.retentionLimit !== undefined) state.retentionLimit = normalizeRetention(options.retentionLimit)
433
+ await saveState(info, state)
434
+ const setupScript = options.setupScript ?? (options.runSetup ? await readSetupScript(destination) : '')
435
+ let setupOutput = '', setupWarning = ''
436
+ if (setupScript) {
437
+ try { setupOutput = await runSetup(destination, setupScript) }
438
+ catch (error) { setupWarning = '工作树已创建,但环境初始化失败:' + error.message }
439
+ }
440
+ const warnings = await prune(info, state, { ...options, currentPath: destination })
441
+ if (setupWarning) warnings.push(setupWarning)
442
+ return { tree, setupOutput, warnings }
443
+ } catch (error) {
444
+ throw new Error('工作树已创建,但初始化未完成;原工作树内容未改动。新目录:' + destination + '。' + error.message, { cause: error })
445
+ }
446
+ })
447
+ }
448
+
449
+ export async function switchWorktree(cwd, target, sessionId) {
450
+ const info = await listWorktrees(cwd)
451
+ return withRepoLock(info.commonDir, async () => {
452
+ const normalized = resolve(target)
453
+ const tree = info.worktrees.find(item => samePath(item.path, normalized))
454
+ if (!tree || tree.prunable) throw new Error('目标不是当前仓库中可用的工作树。')
455
+ const state = await loadState(info)
456
+ const record = state.worktrees[tree.path]
457
+ if (record) {
458
+ record.lastUsedAt = new Date().toISOString()
459
+ record.sessionIds = addSession(record, sessionId)
460
+ await saveState(info, state)
461
+ }
462
+ return tree.path
463
+ })
464
+ }
465
+
466
+ /** Resolve/register a conversation in an existing managed tree; never create or switch trees. */
467
+ export async function worktreeSession(cwd, sessionId) {
468
+ // Ordinary non-Git conversations need no membership. Errors reading a real
469
+ // repository's state must still propagate, so conversion can be retried.
470
+ if (!cwd || !await git(cwd, ['rev-parse', '--is-inside-work-tree']).then(value => value.trim() === 'true').catch(() => false)) return
471
+ const info = await repository(cwd)
472
+ return withRepoLock(info.commonDir, async () => {
473
+ const current = await listWorktrees(cwd)
474
+ const tree = current.worktrees.find(item => samePath(item.path, current.root) && !item.prunable)
475
+ const primary = current.worktrees.find(item => !item.bare)
476
+ if (!tree || !primary || samePath(tree.path, primary.path)) return
477
+ const state = await loadState(current)
478
+ const record = state.worktrees[tree.path]
479
+ if (!record) return
480
+ if (sessionId !== undefined && !record.sessionIds?.includes(sessionId)) {
481
+ if (!/^[\w-]{1,128}$/.test(sessionId)) throw new Error('会话 ID 无效。')
482
+ record.sessionIds = addSession(record, sessionId)
483
+ await saveState(current, state)
484
+ }
485
+ return { projectPath: primary.path, worktreePath: tree.path }
486
+ })
487
+ }
488
+
489
+ export async function createBranch(cwd, branch) {
490
+ const info = await repository(cwd)
491
+ branch = safeBranch(branch)
492
+ if (!branch) throw new Error('请输入新分支名称。')
493
+ await git(info.root, ['check-ref-format', '--branch', branch])
494
+ await git(info.root, ['switch', '-c', branch])
495
+ return { branch }
496
+ }
497
+
498
+ // Copy the complete change relative to the common ancestor without changing
499
+ // either branch reference or deleting anything from the source checkout.
500
+ export async function handoffWorktree(cwd, target, sessionId) {
501
+ const info = await listWorktrees(cwd)
502
+ return withRepoLock(info.commonDir, async () => {
503
+ const destination = info.worktrees.find(tree => samePath(tree.path, target) && !tree.bare && !tree.prunable)
504
+ if (!destination) throw new Error('请选择当前仓库中可用的目标工作树。')
505
+ if (samePath(info.root, destination.path)) return { path: info.root }
506
+ if (await git(info.root, ['ls-files', '-u', '-z'])) throw new Error('源工作树存在未解决冲突,无法交接。')
507
+ isSnapshotSafe(await git(info.root, ['ls-files', '--stage', '-z']))
508
+ await collectFiles(info.root, splitNul(await git(info.root, ['ls-files', '--others', '--exclude-standard', '-z'])))
509
+ const state = await loadState(info)
510
+ await mkdir(info.stateDir, { recursive: true })
511
+ const indexPath = resolve(info.stateDir, 'handoff-index-' + randomUUID())
512
+ const patchFile = resolve(info.stateDir, 'handoff-' + randomUUID() + '.patch')
513
+ const head = (await git(info.root, ['rev-parse', 'HEAD'])).trim()
514
+ const targetHead = (await git(destination.path, ['rev-parse', 'HEAD'])).trim()
515
+ try {
516
+ const env = { GIT_INDEX_FILE: indexPath }
517
+ await git(info.root, ['read-tree', head], { env })
518
+ await git(info.root, ['add', '-A', '--', '.'], { env })
519
+ const tree = (await git(info.root, ['write-tree'], { env })).trim()
520
+ // Repeated handoffs to a checkout already containing the result need no writes.
521
+ await git(destination.path, ['read-tree', targetHead], { env })
522
+ await git(destination.path, ['add', '-A', '--', '.'], { env })
523
+ const targetTree = (await git(destination.path, ['write-tree'], { env })).trim()
524
+ if (targetTree !== tree) {
525
+ if (await git(destination.path, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])) throw new Error('目标工作树有未提交改动。请先提交或保存后再交接;源工作树保持不变。')
526
+ const base = (await git(info.root, ['merge-base', head, targetHead])).trim()
527
+ const patch = await git(info.root, ['diff', '--binary', '--full-index', '--no-ext-diff', '--no-textconv', base, tree, '--'])
528
+ if (patch) {
529
+ await writeFile(patchFile, patch, { flag: 'wx' })
530
+ await git(destination.path, ['read-tree', targetHead], { env })
531
+ try { await git(destination.path, ['apply', '--cached', '--3way', '--binary', patchFile], { env }) }
532
+ catch { throw new Error('交接改动与目标分支冲突;两边的文件均未更改。请先解决分支差异。') }
533
+ // Git validates applicability again against the real index before writing.
534
+ await git(destination.path, ['apply', '--3way', '--index', '--binary', patchFile])
535
+ }
536
+ }
537
+ const record = state.worktrees[destination.path]
538
+ if (record) { record.lastUsedAt = new Date().toISOString(); record.sessionIds = addSession(record, sessionId) }
539
+ await saveState(info, state)
540
+ return { path: destination.path, warnings: ['源工作树保留原样。目标分支不变,带入的成果作为暂存改动等待提交。'] }
541
+ } finally { await rm(indexPath, { force: true }); await rm(patchFile, { force: true }) }
542
+ })
543
+ }
544
+
545
+ async function snapshotWorktree(info, state, tree, options = {}) {
546
+ const root = resolve(tree.path)
547
+ const indexed = await git(root, ['ls-files', '--stage', '-z'])
548
+ isSnapshotSafe(indexed)
549
+ if (await git(root, ['ls-files', '-u', '-z'])) throw new Error('此工作树存在未解决的合并冲突,暂不能归档。')
550
+ const head = (await git(root, ['rev-parse', '--verify', 'HEAD'])).trim()
551
+ const id = randomUUID()
552
+ const indexPath = resolve(info.stateDir, 'index-' + id)
553
+ await mkdir(info.stateDir, { recursive: true })
554
+ try {
555
+ const env = { GIT_INDEX_FILE: indexPath }
556
+ await git(root, ['read-tree', head], { env })
557
+ await git(root, ['add', '-A', '--', '.'], { env, timeout: 120000 })
558
+ const forced = await collectFiles(root, await includedPaths(root))
559
+ if (forced.length) await git(root, ['add', '-f', '--', ...forced.map(file => ':(literal)' + file.path)], { env, timeout: 120000 })
560
+ const snapshotTree = (await git(root, ['write-tree'], { env })).trim()
561
+ const commit = (await git(root, ['commit-tree', snapshotTree, '-p', head, '-m', 'DSH 工作树归档 ' + id])).trim()
562
+ const ref = 'refs/dsh-worktree-control/archive/' + id
563
+ await git(root, ['update-ref', ref, commit])
564
+ const includedFiles = forced.map(file => file.path)
565
+ const record = {
566
+ id, path: root, branch: tree.branch || '', head, snapshotCommit: commit, snapshotRef: ref,
567
+ archivedAt: new Date().toISOString(), sessionIds: addSession(tree, options.sessionId), includedFiles,
568
+ }
569
+ state.archives.push(record)
570
+ await saveState(info, state)
571
+ try { await git(info.root, ['worktree', 'remove', '--force', '--', root], { timeout: 120000 }) }
572
+ catch (error) {
573
+ record.removeError = error.message
574
+ await saveState(info, state)
575
+ throw new Error('快照已保存,但移除工作树失败;可以稍后重试清理。快照编号:' + id)
576
+ }
577
+ delete state.worktrees[root]
578
+ await saveState(info, state)
579
+ return record
580
+ } finally { await rm(indexPath, { force: true }) }
581
+ }
582
+
583
+ async function treeBusy(record, isAgentActive) {
584
+ if (!isAgentActive) return false
585
+ if (await isAgentActive(undefined, record.path)) return true
586
+ for (const sessionId of record.sessionIds ?? []) if (await isAgentActive(sessionId, record.path)) return true
587
+ return false
588
+ }
589
+
590
+ async function prune(info, state, options = {}) {
591
+ const limit = state.retentionLimit
592
+ if (!limit) return []
593
+ const trees = activeMap((await listWorktrees(info.root)).worktrees, state)
594
+ const warnings = []
595
+ while (trees.length > limit) {
596
+ const candidates = trees.filter(tree => !tree.pinned && !samePath(tree.path, options.currentPath || '')).sort((a, b) => (a.lastUsedAt || a.createdAt || '').localeCompare(b.lastUsedAt || b.createdAt || ''))
597
+ let selected
598
+ for (const candidate of candidates) if (options.isAgentActive && !(await treeBusy(candidate, options.isAgentActive))) { selected = candidate; break }
599
+ if (!selected) { warnings.push('已达到保留上限,但其余工作树均已固定、正在使用或无法判断是否空闲;未自动删除。'); break }
600
+ try { await snapshotWorktree(info, state, selected, {}) }
601
+ catch (error) { warnings.push('自动归档 ' + selected.path + ' 失败:' + error.message); break }
602
+ trees.splice(trees.findIndex(tree => samePath(tree.path, selected.path)), 1)
603
+ }
604
+ return warnings
605
+ }
606
+
607
+ export async function archiveWorktree(cwd, path, options = {}) {
608
+ const info = await listWorktrees(cwd)
609
+ return withRepoLock(info.commonDir, async () => {
610
+ const state = await loadState(info)
611
+ const normalized = resolve(path)
612
+ const tree = info.worktrees.find(item => samePath(item.path, normalized))
613
+ if (!tree || !state.worktrees[tree.path]) throw new Error('只能归档由工作树控制插件创建的工作树。')
614
+ if (samePath(tree.path, options.currentPath || '')) throw new Error('请先把当前对话切换到其他目录,再归档这棵工作树。')
615
+ if (state.worktrees[tree.path].pinned) throw new Error('此工作树已固定;取消固定后才能归档。')
616
+ if (await treeBusy(state.worktrees[tree.path], options.isAgentActive)) throw new Error('此工作树正被另一个活动对话使用,暂不能归档。')
617
+ return snapshotWorktree(info, state, { ...state.worktrees[tree.path], ...tree }, options)
618
+ })
619
+ }
620
+
621
+ export async function restoreArchive(cwd, id, options = {}) {
622
+ const info = await listWorktrees(cwd)
623
+ return withRepoLock(info.commonDir, async () => {
624
+ const state = await loadState(info)
625
+ const archive = state.archives.find(item => item.id === id && !item.restoredAt && !item.deletedAt)
626
+ if (!archive) throw new Error('找不到可恢复的快照。')
627
+ const destination = resolve(archive.path)
628
+ const runtime = COMMAND_CONTEXT.getStore()
629
+ if (runtime && runtime.policy.mode !== 'danger-full-access' && !inside(runtime.policy.workspaceRoot, destination)) throw new Error('恢复目录超出当前对话可写范围,请先调整权限。')
630
+ if (await lstat(destination).catch(error => error.code === 'ENOENT' ? null : Promise.reject(error))) throw new Error('原工作树路径已被占用,请先移走该目录:' + destination)
631
+ const commit = (await git(info.root, ['rev-parse', '--verify', '--end-of-options', archive.snapshotRef + '^{commit}'])).trim()
632
+ await mkdir(dirname(destination), { recursive: true })
633
+ await git(info.root, ['worktree', 'add', '--detach', '--', destination, commit], { timeout: 120000 })
634
+ try {
635
+ await git(destination, ['reset', '--soft', archive.head])
636
+ // Ignored configuration belongs on disk, never in the next user commit.
637
+ if (archive.includedFiles?.length) await git(destination, ['rm', '--cached', '--quiet', '--', ...archive.includedFiles.map(path => ':(literal)' + path)])
638
+ archive.restoredAt = new Date().toISOString()
639
+ state.worktrees[destination] = {
640
+ path: destination, branch: '', head: archive.head, createdAt: archive.archivedAt,
641
+ lastUsedAt: archive.restoredAt, pinned: false, sessionIds: addSession(archive, options.sessionId), restoredFrom: id,
642
+ includedFiles: archive.includedFiles ?? [],
643
+ }
644
+ await saveState(info, state)
645
+ return state.worktrees[destination]
646
+ } catch (error) {
647
+ throw new Error('工作树已恢复,但恢复文件状态时失败;目录保留在 ' + destination + '。' + error.message, { cause: error })
648
+ }
649
+ })
650
+ }
651
+
652
+ export async function deleteArchive(cwd, id) {
653
+ const info = await listWorktrees(cwd)
654
+ return withRepoLock(info.commonDir, async () => {
655
+ const state = await loadState(info)
656
+ const archive = state.archives.find(item => item.id === id && !item.restoredAt && !item.deletedAt)
657
+ if (!archive) throw new Error('找不到可删除的快照。')
658
+ await git(info.root, ['update-ref', '-d', archive.snapshotRef])
659
+ archive.deletedAt = new Date().toISOString()
660
+ await saveState(info, state)
661
+ return { id }
662
+ })
663
+ }
664
+
665
+ export async function inspect(cwd) {
666
+ const info = await listWorktrees(cwd)
667
+ const root = info.root
668
+ const raw = await git(root, ['diff', '--no-ext-diff', '--no-textconv', '--no-renames', '--numstat', '-z', 'HEAD', '--'])
669
+ const stagedNames = splitNul(await git(root, ['diff', '--cached', '--no-renames', '--name-only', '-z', 'HEAD', '--']))
670
+ const unstagedNames = splitNul(await git(root, ['diff', '--no-renames', '--name-only', '-z', '--']))
671
+ const trackedNames = [...new Set([...stagedNames, ...unstagedNames])]
672
+ const untracked = splitNul(await git(root, ['ls-files', '--others', '--exclude-standard', '-z']))
673
+ const files = []
674
+ for (const path of [...new Set([...trackedNames, ...untracked])]) {
675
+ let patch = ''
676
+ if (untracked.includes(path)) {
677
+ const target = resolve(root, path)
678
+ if (!inside(root, target)) continue
679
+ const file = await lstat(target).catch(error => error.code === 'ENOENT' ? null : Promise.reject(error))
680
+ if (!file || !file.isFile() || file.isSymbolicLink() || file.size > LIMIT) continue
681
+ const content = await readFile(target)
682
+ if (content.includes(0)) continue
683
+ const lines = content.toString('utf8').split('\n')
684
+ if (lines.at(-1) === '') lines.pop()
685
+ patch = ['diff --git a/' + path + ' b/' + path, 'new file mode 100644', '--- /dev/null', '+++ b/' + path, '@@ -0,0 +1,' + lines.length + ' @@', ...lines.map(line => '+' + line)].join('\n') + '\n'
686
+ } else patch = await git(root, ['diff', '--no-ext-diff', '--no-textconv', '--no-renames', '--unified=3', 'HEAD', '--', ':(literal)' + path])
687
+ files.push({ path, patch, untracked: untracked.includes(path), staged: stagedNames.includes(path), unstaged: unstagedNames.includes(path) })
688
+ }
689
+ return { root, branch: info.worktrees.find(tree => samePath(tree.path, root))?.branch ?? '', files, numstat: raw }
690
+ }
691
+
692
+ async function validatePaths(cwd, paths) {
693
+ if (!Array.isArray(paths) || !paths.length || paths.length > 200) throw new Error('请至少选择一个文件。')
694
+ const status = await git(cwd, ['status', '--porcelain=v1', '--no-renames', '-z', '--untracked-files=all'])
695
+ const allowed = new Set()
696
+ const fields = splitNul(status)
697
+ for (const field of fields) {
698
+ const path = field.length > 3 ? field.slice(3) : ''
699
+ if (path) allowed.add(path)
700
+ }
701
+ for (const path of paths) if (typeof path !== 'string' || !allowed.has(safeRelative(path))) throw new Error('文件状态已变化,请刷新后重试。')
702
+ return paths
703
+ }
704
+
705
+ export async function stage(cwd, paths, staged = true) {
706
+ const info = await listWorktrees(cwd)
707
+ const selected = await validatePaths(info.root, paths)
708
+ const literal = selected.map(path => ':(literal)' + path)
709
+ await git(info.root, staged ? ['add', '--', ...literal] : ['restore', '--staged', '--', ...literal])
710
+ return inspect(info.root)
711
+ }
712
+
713
+ export async function discard(cwd, paths) {
714
+ const info = await listWorktrees(cwd)
715
+ const selected = await validatePaths(info.root, paths)
716
+ const status = await git(info.root, ['status', '--porcelain=v1', '--no-renames', '-z', '--untracked-files=all'])
717
+ const untracked = new Set(splitNul(status).filter(field => field.startsWith('?? ')).map(field => field.slice(3)))
718
+ for (const path of selected) {
719
+ const target = resolve(info.root, path)
720
+ if (!inside(info.root, target)) throw new Error('文件路径越界。')
721
+ const infoStat = await lstat(target).catch(error => error.code === 'ENOENT' ? null : Promise.reject(error))
722
+ if (infoStat?.isSymbolicLink()) throw new Error('为避免删除符号链接目标,未删除该文件。')
723
+ if (untracked.has(path)) {
724
+ if (infoStat?.isFile()) await rm(target)
725
+ continue
726
+ }
727
+ const pathspec = ':(literal)' + path
728
+ const inHead = Boolean(await git(info.root, ['ls-tree', '-z', 'HEAD', '--', pathspec]))
729
+ if (inHead) await git(info.root, ['restore', '--source=HEAD', '--staged', '--worktree', '--', pathspec])
730
+ else {
731
+ await git(info.root, ['rm', '--cached', '--force', '--', pathspec]).catch(() => {})
732
+ if (infoStat?.isFile()) await rm(target)
733
+ }
734
+ }
735
+ return inspect(info.root)
736
+ }
737
+
738
+ export async function commit(cwd, message) {
739
+ if (typeof message !== 'string' || !message.trim() || message.length > 500) throw new Error('请输入 1 到 500 个字符的提交说明。')
740
+ const info = await listWorktrees(cwd)
741
+ const staged = await git(info.root, ['diff', '--cached', '--quiet', 'HEAD', '--']).then(() => false).catch(() => true)
742
+ if (!staged) throw new Error('暂存区没有改动。')
743
+ await git(info.root, ['commit', '-m', message.trim()], { timeout: 120000 })
744
+ return { head: (await git(info.root, ['rev-parse', '--short', 'HEAD'])).trim() }
745
+ }
746
+
747
+ export async function push(cwd) {
748
+ const info = await listWorktrees(cwd)
749
+ const branch = info.worktrees.find(tree => samePath(tree.path, info.root))?.branch
750
+ if (!branch) throw new Error('当前为 detached HEAD;先创建并切换到分支后再推送。')
751
+ const upstream = (await git(info.root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}']).catch(() => '')).trim()
752
+ if (upstream) await git(info.root, ['push'], { timeout: 120000 })
753
+ else await git(info.root, ['push', '--set-upstream', 'origin', branch], { timeout: 120000 })
754
+ return { branch }
755
+ }
756
+
757
+ export async function readSetupScript(root) {
758
+ return (await readEnvironment(root)).setup
759
+ }
760
+
761
+ export async function readEnvironment(root) {
762
+ const file = resolve(root, '.codex', 'environments', 'environment.toml')
763
+ const content = await readFile(file, 'utf8').catch(error => error.code === 'ENOENT' ? '' : Promise.reject(error))
764
+ if (!content) return { setup: '', actions: [] }
765
+ const config = parseToml(content)
766
+ const platform = process.platform === 'win32' ? 'windows' : process.platform === 'darwin' ? 'macos' : 'linux'
767
+ const setup = config.setup?.[platform]?.script ?? config.setup?.script ?? ''
768
+ if (typeof setup !== 'string' || setup.length > 16000) throw new Error('environment.toml 中的 setup.script 无效。')
769
+ const actions = (Array.isArray(config.actions) ? config.actions : []).map((item, id) => ({ id, name: item.name, command: item.command }))
770
+ .filter(item => typeof item.name === 'string' && typeof item.command === 'string' && item.command.trim() && item.command.length <= 16000)
771
+ return { setup, actions }
772
+ }
773
+
774
+ function validateEnvironment(profile) {
775
+ const name = String(profile?.name ?? '').trim()
776
+ const setup = String(profile?.setup ?? '')
777
+ if (!name || name.length > 80 || setup.length > 16000) throw new Error('环境名称或初始化脚本无效。')
778
+ if (!Array.isArray(profile.actions)) throw new Error('环境操作格式无效。')
779
+ const actions = []
780
+ profile.actions.forEach((item, actionIndex) => {
781
+ const name = String(item?.name ?? '').trim(), command = String(item?.command ?? '').trim()
782
+ if (!name && !command) return
783
+ const field = !name || name.length > 80 ? 'name' : !command || command.length > 16000 ? 'command' : null
784
+ if (field) {
785
+ const reason = field === 'name' ? !name ? '请填写操作名称。' : '操作名称不能超过 80 个字符。'
786
+ : !command ? '请填写操作命令。' : '操作命令不能超过 16000 个字符。'
787
+ throw Object.assign(new Error('第 ' + (actionIndex + 1) + ' 项操作:' + reason), { validation: { actionIndex, field } })
788
+ }
789
+ actions.push({ name, command })
790
+ })
791
+ if (actions.length > 30) throw new Error('环境操作不能超过 30 项。')
792
+ return { name, setup, actions }
793
+ }
794
+
795
+ export async function environmentCatalog(cwd, sessionId) {
796
+ const info = await repository(cwd)
797
+ const state = await loadState(info)
798
+ const native = await readEnvironment(info.root)
799
+ const profiles = [...(state.environments ?? [])]
800
+ if (native.setup || native.actions.length) profiles.unshift({ id: 'project', name: '项目配置 (.codex)', ...native, imported: true })
801
+ return { profiles, defaultId: state.defaultEnvironmentId || '', selectedId: state.drafts?.[sessionId]?.environmentId ?? state.sessionEnvironments?.[sessionId] ?? state.defaultEnvironmentId ?? '', draft: state.drafts?.[sessionId] ?? null, setupWarning: state.sessionSetupWarnings?.[sessionId] || state.drafts?.[sessionId]?.setupWarning || '' }
802
+ }
803
+
804
+ export async function clearSetupWarning(cwd, sessionId) {
805
+ const info = await repository(cwd)
806
+ return withRepoLock(info.commonDir, async () => {
807
+ const state = await loadState(info)
808
+ if (!state.sessionSetupWarnings?.[sessionId]) return
809
+ delete state.sessionSetupWarnings[sessionId]
810
+ await saveState(info, state)
811
+ })
812
+ }
813
+
814
+ export async function saveEnvironment(cwd, input) {
815
+ const info = await repository(cwd)
816
+ return withRepoLock(info.commonDir, async () => {
817
+ const state = await loadState(info)
818
+ const value = validateEnvironment(input)
819
+ const id = input.id && input.id !== 'project' ? String(input.id) : randomUUID()
820
+ const index = (state.environments ?? []).findIndex(item => item.id === id)
821
+ if (input.id && input.id !== 'project' && index < 0) throw new Error('环境配置不存在。')
822
+ if (index < 0) state.environments.push({ id, ...value })
823
+ else state.environments[index] = { id, ...value }
824
+ await saveState(info, state)
825
+ return { id }
826
+ })
827
+ }
828
+
829
+ export async function deleteEnvironment(cwd, id) {
830
+ const info = await repository(cwd)
831
+ return withRepoLock(info.commonDir, async () => {
832
+ const state = await loadState(info)
833
+ if (id === 'project' || !(state.environments ?? []).some(item => item.id === id)) throw new Error('环境配置不存在或不可删除。')
834
+ state.environments = state.environments.filter(item => item.id !== id)
835
+ if (state.defaultEnvironmentId === id) state.defaultEnvironmentId = ''
836
+ for (const [sessionId, selected] of Object.entries(state.sessionEnvironments ?? {})) if (selected === id) state.sessionEnvironments[sessionId] = ''
837
+ for (const draft of Object.values(state.drafts ?? {})) if (draft.environmentId === id) draft.environmentId = ''
838
+ await saveState(info, state)
839
+ return { id }
840
+ })
841
+ }
842
+
843
+ export async function selectEnvironment(cwd, sessionId, id, kind = 'session', draft = {}) {
844
+ const info = await repository(cwd)
845
+ return withRepoLock(info.commonDir, async () => {
846
+ const state = await loadState(info)
847
+ const native = await readEnvironment(info.root)
848
+ if (id && !(state.environments ?? []).some(item => item.id === id) && !(id === 'project' && (native.setup || native.actions.length))) throw new Error('所选环境不存在。')
849
+ if (kind === 'default') state.defaultEnvironmentId = id
850
+ else if (kind === 'draft') {
851
+ if (typeof draft.create !== 'boolean' || typeof draft.baseRef !== 'string' || draft.baseRef.length > 200) throw new Error('新对话设置无效。')
852
+ state.drafts[sessionId] = { create: draft.create, baseRef: draft.baseRef, environmentId: id }
853
+ } else if (kind === 'session') state.sessionEnvironments[sessionId] = id
854
+ else throw new Error('环境选择类型无效。')
855
+ await saveState(info, state)
856
+ return { id }
857
+ })
858
+ }
859
+
860
+ export async function consumeDraft(cwd, sessionId, agent, ctx, signal) {
861
+ const info = await repository(cwd)
862
+ const state = await loadState(info)
863
+ const draft = state.drafts?.[sessionId]
864
+ if (!draft && Object.hasOwn(state.sessionEnvironments ?? {}, sessionId)) return
865
+ if (!draft && !state.defaultEnvironmentId) return
866
+ const id = draft?.environmentId ?? state.defaultEnvironmentId ?? ''
867
+ const native = await readEnvironment(info.root)
868
+ const selected = id === 'project' ? native : state.environments?.find(item => item.id === id)
869
+ if (id && !selected) throw new Error('新对话选择的环境已被删除,请重新选择。')
870
+ if (draft?.create) {
871
+ if (ctx.sandboxPolicy.resolve({ session: agent.session }).mode === 'read-only') throw new Error('当前对话处于只读模式,无法创建工作树。')
872
+ let path = draft.createdPath
873
+ if (!path) {
874
+ const result = await createWorktree(cwd, { baseRef: draft.baseRef || 'HEAD', sessionId, setupScript: selected?.setup || '', currentPath: cwd })
875
+ path = result.tree.path
876
+ await withRepoLock(info.commonDir, async () => {
877
+ const latest = await loadState(info)
878
+ if (latest.drafts?.[sessionId]) {
879
+ latest.drafts[sessionId].createdPath = path
880
+ await saveState(info, latest)
881
+ }
882
+ })
883
+ const setupFailure = result.warnings?.find(warning => warning.startsWith('工作树已创建,但环境初始化失败'))
884
+ for (const warning of result.warnings ?? []) ctx.logger.warn('worktree-control: ' + warning)
885
+ if (setupFailure) {
886
+ await withRepoLock(info.commonDir, async () => {
887
+ const latest = await loadState(info)
888
+ if (latest.drafts?.[sessionId]) {
889
+ latest.drafts[sessionId].setupWarning = setupFailure
890
+ await saveState(info, latest)
891
+ }
892
+ })
893
+ }
894
+ }
895
+ await ctx.workingDirectory.set(agent, path, signal)
896
+ }
897
+ await withRepoLock(info.commonDir, async () => {
898
+ const latest = await loadState(info)
899
+ if (latest.drafts?.[sessionId]?.setupWarning) latest.sessionSetupWarnings[sessionId] = latest.drafts[sessionId].setupWarning
900
+ if (latest.drafts?.[sessionId]) delete latest.drafts[sessionId]
901
+ latest.sessionEnvironments[sessionId] = id
902
+ await saveState(info, latest)
903
+ })
904
+ }
905
+
906
+ // PowerShell 5.1 does not turn native nonzero exits into terminating errors.
907
+ // Resolve each command at its normal invocation site, then check native exits
908
+ // only for statements that actually invoked a native program. Never clear the
909
+ // user's LASTEXITCODE, and leave restricted data blocks untouched.
910
+ const POWERSHELL_SCRIPT_RUNNER = String.raw`
911
+ $ErrorActionPreference = 'Continue'
912
+ $PSDefaultParameterValues['*:ErrorAction'] = 'Stop'
913
+ $ProgressPreference = 'SilentlyContinue'
914
+ function Resolve-DshEnvironmentCommand {
915
+ param($Command, [hashtable]$State)
916
+ if ($Command -is [scriptblock]) { return $Command }
917
+ $resolved = if ($Command -is [System.Management.Automation.CommandInfo]) { $Command } else {
918
+ $ExecutionContext.InvokeCommand.GetCommand([string]$Command, [System.Management.Automation.CommandTypes]::All)
919
+ }
920
+ if ($null -eq $resolved) { throw ('Command not found: ' + $Command) }
921
+ $actual = $resolved
922
+ while ($actual -is [System.Management.Automation.AliasInfo]) { $actual = $actual.ResolvedCommand }
923
+ if ($actual -is [System.Management.Automation.ApplicationInfo]) { $State.Native = $true }
924
+ return $resolved
925
+ }
926
+ function Test-DshGuardedStatement($node) {
927
+ return ($node -is [System.Management.Automation.Language.PipelineAst] -or
928
+ $node -is [System.Management.Automation.Language.AssignmentStatementAst]) -and
929
+ ($node.Parent -is [System.Management.Automation.Language.StatementBlockAst] -or
930
+ $node.Parent -is [System.Management.Automation.Language.NamedBlockAst])
931
+ }
932
+ try {
933
+ $scriptText = $env:DSH_WORKTREE_SCRIPT
934
+ Remove-Item Env:DSH_WORKTREE_SCRIPT
935
+ $tokens = $null; $parseErrors = $null
936
+ $ast = [System.Management.Automation.Language.Parser]::ParseInput($scriptText, [ref]$tokens, [ref]$parseErrors)
937
+ if ($parseErrors.Count) { throw ($parseErrors | Out-String) }
938
+ $edits = [System.Collections.Generic.List[object]]::new()
939
+ $statementIndex = 0
940
+ foreach ($node in $ast.FindAll({ param($n) Test-DshGuardedStatement $n }, $true)) {
941
+ $restricted = $false
942
+ for ($parent = $node.Parent; $null -ne $parent; $parent = $parent.Parent) {
943
+ if ($parent -is [System.Management.Automation.Language.DataStatementAst]) { $restricted = $true; break }
944
+ }
945
+ if ($restricted) { continue }
946
+ $stateName = '$__dshCommandState' + $statementIndex++
947
+ $commands = @($node.FindAll({ param($n) $n -is [System.Management.Automation.Language.CommandAst] }, $true) | Where-Object {
948
+ $owner = $_.Parent
949
+ while ($null -ne $owner -and -not (Test-DshGuardedStatement $owner)) { $owner = $owner.Parent }
950
+ [object]::ReferenceEquals($owner, $node)
951
+ })
952
+ if (-not $commands.Count) {
953
+ $edits.Add(@{ Offset = $node.Extent.EndOffset; Order = 3; Text = ('; if (-not $?) { throw "Expression failed at line ' + $node.Extent.StartLineNumber + '." }') })
954
+ continue
955
+ }
956
+ $edits.Add(@{ Offset = $node.Extent.StartOffset; Order = 0; Text = ($stateName + ' = @{ Native = $false }; ') })
957
+ foreach ($command in $commands) {
958
+ $head = $command.CommandElements[0]
959
+ $invoke = if ($command.InvocationOperator -eq 'Unknown') { '& ' } else { '' }
960
+ $edits.Add(@{ Offset = $head.Extent.StartOffset; Order = 1; Text = ($invoke + '(Resolve-DshEnvironmentCommand -Command ') })
961
+ $edits.Add(@{ Offset = $head.Extent.EndOffset; Order = 2; Text = (' -State ' + $stateName + ')') })
962
+ }
963
+ $check = '; if ((' + $stateName + '.Native -and $LASTEXITCODE -ne 0) -or (-not ' + $stateName + '.Native -and -not $?)) { throw ("Command failed at line ' + $node.Extent.StartLineNumber + ' (exit code " + $LASTEXITCODE + ").") }'
964
+ $edits.Add(@{ Offset = $node.Extent.EndOffset; Order = 3; Text = $check })
965
+ }
966
+ foreach ($edit in ($edits | Sort-Object -Property @{ Expression = { $_.Offset }; Descending = $true }, @{ Expression = { $_.Order }; Descending = $true })) {
967
+ $scriptText = $scriptText.Insert($edit.Offset, $edit.Text)
968
+ }
969
+ . ([scriptblock]::Create($scriptText))
970
+ exit 0
971
+ } catch {
972
+ [Console]::Error.WriteLine($_.ToString())
973
+ exit 1
974
+ }
975
+ `
976
+
977
+ export async function runSetup(cwd, script, options = {}) {
978
+ if (typeof script !== 'string' || !script.trim() || script.length > 16000) throw new Error('初始化命令为空或过长。')
979
+ const runtime = COMMAND_CONTEXT.getStore()
980
+ const runner = SETUP_RUNNER.getStore()
981
+ if (runner) return runner(cwd, script, next => COMMAND_CONTEXT.run(runtime, () => SETUP_RUNNER.run(null, () => runSetup(cwd, script, next))), runtime?.signal)
982
+ const command = process.platform === 'win32' ? 'powershell.exe' : '/bin/sh'
983
+ const args = process.platform === 'win32'
984
+ ? ['-NoProfile', '-NonInteractive', '-OutputFormat', 'Text', '-EncodedCommand', Buffer.from(POWERSHELL_SCRIPT_RUNNER, 'utf16le').toString('base64')]
985
+ : ['-e', '-lc', script]
986
+ // Keep script text out of shell quoting and the Windows argv size limit.
987
+ const extraEnv = process.platform === 'win32' ? { DSH_WORKTREE_SCRIPT: script } : {}
988
+ try {
989
+ if (runtime && options.terminal) return await runManagedTerminal(runtime, cwd, [command, ...args], { ...options, env: extraEnv })
990
+ if (runtime) {
991
+ return (await runManagedCommand(runtime, cwd, [command, ...args], { env: extraEnv, timeout: 10 * 60 * 1000, maxBuffer: 4 * 1024 * 1024 })).slice(-16000)
992
+ }
993
+ const env = envForGit(extraEnv)
994
+ const { stdout, stderr } = await execute(command, args, { cwd, env, windowsHide: true, timeout: 10 * 60 * 1000, maxBuffer: 4 * 1024 * 1024, encoding: 'utf8' })
995
+ return (stdout + stderr).slice(-16000)
996
+ } catch (error) {
997
+ throw new Error('环境命令执行失败,已停止后续执行:' + stripVTControlCharacters(String(error.stderr || error.message)).slice(-4000))
998
+ }
999
+ }
1000
+
1001
+ export async function openPullRequest(cwd) {
1002
+ const info = await listWorktrees(cwd)
1003
+ const branch = info.worktrees.find(tree => samePath(tree.path, info.root))?.branch
1004
+ if (!branch) throw new Error('当前为 detached HEAD,无法创建 PR。')
1005
+ const runtime = COMMAND_CONTEXT.getStore()
1006
+ if (runtime) return { output: (await runManagedCommand(runtime, info.root, ['gh', 'pr', 'create', '--web'], { timeout: 120000, maxBuffer: 1024 * 1024 })).slice(-8000) }
1007
+ const { stdout, stderr } = await execute('gh', ['pr', 'create', '--web'], { cwd: info.root, windowsHide: true, timeout: 120000, maxBuffer: 1024 * 1024, env: envForGit() })
1008
+ return { output: (stdout + stderr).slice(-8000) }
1009
+ }
1010
+
1011
+ export { normalizeRetention, samePath }