dsh-agent-team-playbook 1.23.1 → 1.25.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/README.md CHANGED
@@ -103,6 +103,8 @@ dsh plugin --profile web add dsh-agent-team-playbook
103
103
  | `/atp` | 规程摘要(档位、四问、收尾三问)+ 安装方式 |
104
104
  | `/atp core` | 输出核心全文,读完即在本轮按它协作 |
105
105
  | `/atp paths` | 各分册的绝对路径,按需查阅 |
106
+ | `/atp install` | 把 playbook **原子安装进当前工作区**(有同名内容则拒绝,不覆盖) |
107
+ | `/atp install force` | 覆盖同名内容后安装(先暂存原件,失败自动回滚) |
106
108
  | `/atp help` | 用法 |
107
109
 
108
110
  插件**不写任何文件**、也**不挂 skill**——skill 的目录摘要会常驻占用上下文(约 300 tokens/轮),而分册本来就不会自动进上下文,用命令按需取更划算。
package/bin/cli.mjs CHANGED
@@ -18,10 +18,11 @@
18
18
  import { createInterface } from 'node:readline/promises'
19
19
  import os from 'node:os'
20
20
  import { stdin, stdout } from 'node:process'
21
- import { readFile, writeFile, mkdir, stat, readdir, rename } from 'node:fs/promises'
21
+ import { readFile, writeFile, mkdir, stat } from 'node:fs/promises'
22
22
  import { existsSync } from 'node:fs'
23
23
  import path from 'node:path'
24
24
  import { fileURLToPath } from 'node:url'
25
+ import { installAtomic, scan, listFiles, CORE_FILE, DOCS_DIR } from '../lib/install.js'
25
26
 
26
27
  const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
27
28
 
@@ -32,10 +33,6 @@ process.stdout.on('error', (err) => {
32
33
  })
33
34
  const SOURCE_ROOT = path.join(PACKAGE_ROOT, 'playbook')
34
35
 
35
- /** 会被安装进用户项目的条目:playbook 本体(核心 + 分册)。 */
36
- const ROOT_FILE = 'AGENTS.md'
37
- const ROOT_DIR = 'docs'
38
-
39
36
  const C = {
40
37
  dim: (s) => `\x1b[2m${s}\x1b[0m`,
41
38
  bold: (s) => `\x1b[1m${s}\x1b[0m`,
@@ -55,6 +52,8 @@ function parseArgs(argv) {
55
52
  yes: false,
56
53
  inlineCore: false,
57
54
  backupExisting: false,
55
+ renameCore: undefined,
56
+ renameDocs: undefined,
58
57
  }
59
58
  for (let i = 0; i < argv.length; i += 1) {
60
59
  const a = argv[i]
@@ -66,6 +65,8 @@ function parseArgs(argv) {
66
65
  else if (a === '--yes' || a === '-y') opts.yes = true
67
66
  else if (a === '--inline-core') opts.inlineCore = true
68
67
  else if (a === '--backup-existing') opts.backupExisting = true
68
+ else if (a === '--rename-core') opts.renameCore = argv[(i += 1)]
69
+ else if (a === '--rename-docs') opts.renameDocs = argv[(i += 1)]
69
70
  else if (a === '--help' || a === '-h') opts.help = true
70
71
  else if (a === 'init') continue
71
72
  else {
@@ -91,6 +92,8 @@ ${C.bold('选项')}
91
92
  --yes, -y 非交互确认(--global 追加区块用)
92
93
  --dry-run 只显示计划,不写任何文件
93
94
  --backup-existing 冲突时把已有项改名为 *<后缀>,再装我们的(不询问)
95
+ --rename-core <名> 非交互:把我们的核心装成这个名字(如 AGENTS.team.md),引用同步改写
96
+ --rename-docs <名> 非交互:把我们的分册目录装成这个名字(如 docs-playbook),引用同步改写
94
97
  --force, -f 冲突时全部覆盖(不询问)
95
98
  --skip-conflicts 冲突时全部跳过(不询问)
96
99
  -h, --help 显示本帮助
@@ -110,70 +113,9 @@ ${C.bold('行为')}
110
113
  `)
111
114
  }
112
115
 
113
- /** 递归列出源目录下所有文件,返回相对 SOURCE_ROOT 的 posix 路径。 */
114
- async function walk(relDir) {
115
- const abs = path.join(SOURCE_ROOT, relDir)
116
- const out = []
117
- let entries
118
- try {
119
- entries = await readdir(abs, { withFileTypes: true })
120
- } catch {
121
- return out
122
- }
123
- for (const entry of entries) {
124
- const rel = path.posix.join(relDir, entry.name)
125
- if (entry.isDirectory()) out.push(...(await walk(rel)))
126
- else if (entry.isFile()) out.push(rel)
127
- }
128
- return out.sort()
129
- }
130
116
 
131
- /**
132
- * 目标路径的冲突详情。`target` 是"改已有文件名"时要动的那个路径:
133
- * - 同名文件已存在 → 改名该文件
134
- * - 同名位置是目录 → 改名该目录(风险高,调用处需提示)
135
- * - 上级是文件导致建不了目录 → 改名那个上级文件
136
- */
137
- async function inspectConflict(destAbs) {
138
- if (existsSync(destAbs)) {
139
- const s = await stat(destAbs)
140
- return s.isDirectory()
141
- ? { reason: '同名位置已是目录', kind: 'dir', target: destAbs }
142
- : { reason: '文件已存在', kind: 'file', target: destAbs }
143
- }
144
- let p = path.dirname(destAbs)
145
- while (p && p !== path.dirname(p)) {
146
- if (existsSync(p)) {
147
- const s = await stat(p)
148
- if (!s.isDirectory()) return { reason: `上级 ${path.basename(p)} 是文件,无法创建目录`, kind: 'parent-file', target: p }
149
- break
150
- }
151
- p = path.dirname(p)
152
- }
153
- return null
154
- }
155
117
 
156
- /** 生成不冲突的备份路径。 */
157
- function uniqueBackupPath(target, suffix) {
158
- let to = `${target}${suffix}`
159
- let i = 1
160
- while (existsSync(to)) to = `${target}${suffix}-${i++}`
161
- return to
162
- }
163
118
 
164
- /** 把引用改写应用到文本内容:先改目录前缀,再改根文件名。 */
165
- function rewriteReferences(text, renames) {
166
- let out = text
167
- for (const { from, to } of renames) {
168
- if (from === 'AGENTS.md') {
169
- // 仅替换独立出现的文件名(前后不是路径分隔或字母数字)
170
- out = out.replace(/(^|[^/\w.-])AGENTS\.md(?![.\w-])/g, (_m, pre) => `${pre}${to}`)
171
- } else {
172
- out = out.split(from).join(to)
173
- }
174
- }
175
- return out
176
- }
177
119
 
178
120
  /** 受管区块标记:重复执行时原地更新,绝不碰区块外内容。 */
179
121
  const BLOCK_START = '<!-- agent-team-playbook:start -->'
@@ -223,7 +165,7 @@ async function runGlobalMode(opts) {
223
165
  const coreText = await readFile(path.join(SOURCE_ROOT, 'AGENTS.md'), 'utf8')
224
166
  const block = managedBlock(destDir, opts.inlineCore, coreText)
225
167
 
226
- const rels = [ROOT_FILE, ...(await walk(ROOT_DIR))]
168
+ const rels = [CORE_FILE, ...(await listFiles(SOURCE_ROOT, DOCS_DIR))]
227
169
  console.log(C.bold('全局安装计划'))
228
170
  console.log(C.dim(` 区块模式:${opts.inlineCore ? '内联核心全文(每轮真常驻)' : '指针(默认,agent 需先读一次文件)'}`))
229
171
  console.log(` 复制 ${rels.length} 个文件 → ${destDir}`)
@@ -302,9 +244,7 @@ async function main() {
302
244
  console.error(C.red(`✗ 找不到包内 playbook 目录:${SOURCE_ROOT}`))
303
245
  process.exit(1)
304
246
  }
305
- if (opts.global) {
306
- return runGlobalMode(opts)
307
- }
247
+ if (opts.global) return runGlobalMode(opts)
308
248
 
309
249
  if (!existsSync(opts.dir)) {
310
250
  console.error(C.red(`✗ 目标目录不存在:${opts.dir}`))
@@ -314,132 +254,125 @@ async function main() {
314
254
  console.error(C.red(`✗ --dir 不是目录:${opts.dir}`))
315
255
  process.exit(1)
316
256
  }
317
-
318
- // ── 1. 组装安装计划 ───────────────────────────────────────────────
319
- const files = [{ rel: ROOT_FILE, group: ROOT_FILE }]
320
- const docRels = await walk(ROOT_DIR)
321
- if (docRels.length === 0) {
322
- console.error(C.red(`✗ 包内缺少分册:${path.join(SOURCE_ROOT, ROOT_DIR)} 为空或不存在`))
257
+ if ((await listFiles(SOURCE_ROOT, DOCS_DIR)).length === 0) {
258
+ console.error(C.red(`✗ 包内缺少分册:${path.join(SOURCE_ROOT, DOCS_DIR)} 为空或不存在`))
323
259
  process.exit(1)
324
260
  }
325
- for (const rel of docRels) files.push({ rel, group: ROOT_DIR })
326
-
327
- // ── 2. 检测冲突(按 group 归并,避免逐文件轰炸式提问) ──────────────
328
- const groups = new Map()
329
- for (const f of files) {
330
- const dest = path.join(opts.dir, f.rel)
331
- const c = await inspectConflict(dest)
332
- if (c === null) continue
333
- if (!groups.has(f.group)) groups.set(f.group, { reason: c.reason, kind: c.kind, targets: new Set(), files: [] })
334
- const g = groups.get(f.group)
335
- g.targets.add(c.target)
336
- g.kind = g.kind === 'dir' ? 'dir' : c.kind
337
- g.files.push(f.rel)
261
+
262
+ // ── 1. 扫描冲突(核心 + 分册是一个不可分单元) ────────────────────
263
+ const { conflicts } = await scan({ sourceRoot: SOURCE_ROOT, targetDir: opts.dir })
264
+ const byUnit = new Map()
265
+ for (const c of conflicts) {
266
+ if (!byUnit.has(c.unit)) byUnit.set(c.unit, { reasons: new Set(), targets: new Set(), count: 0 })
267
+ const e = byUnit.get(c.unit)
268
+ e.reasons.add(c.reason)
269
+ e.targets.add(c.target)
270
+ e.count += 1
338
271
  }
339
272
 
340
- if (groups.size === 0) {
341
- console.log(C.green('✓ 目标目录没有同名内容,可直接安装。'))
273
+ if (conflicts.length === 0) {
274
+ console.log(C.green('✓ 目标目录没有同名内容,直接安装(核心 + 分册一起)。'))
342
275
  } else {
343
- console.log(C.yellow(`⚠ 检测到 ${groups.size} 处冲突:`))
344
- for (const [g, info] of groups) {
345
- console.log(` · ${C.bold(g)} —— ${info.reason},影响 ${info.files.length} 个文件`)
276
+ console.log(C.yellow('⚠ 检测到冲突(核心与分册必须一起装,所以下面整体决策):'))
277
+ for (const [unit, info] of byUnit) {
278
+ console.log(` · ${C.bold(unit)} —— ${[...info.reasons].join(';')},涉及 ${info.count} 个文件`)
346
279
  for (const target of info.targets) console.log(C.dim(` 已有:${path.relative(opts.dir, target)}`))
347
280
  }
348
281
  }
349
282
 
350
- // ── 3. 逐组决定 ──────────────────────────────────────────────────
283
+ // ── 2. 决策 ────────────────────────────────────────────────────────
351
284
  const renames = []
352
- const skipped = new Set()
353
- const overwrite = new Set()
354
- /** 被改名的"已有文件/目录":{from, to}。安装后原路径归我们使用。 */
355
- const existingRenames = []
356
285
  const defaultSuffix = `.bak-${new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)}`
357
-
286
+ let onConflict = 'overwrite'
287
+ let backupSuffix
288
+ let install = true
358
289
  const interactive = stdin.isTTY && stdout.isTTY
359
290
 
360
- if (groups.size > 0) {
291
+ // 非交互显式改名
292
+ if (opts.renameCore !== undefined) {
293
+ if (!/^[^/\\]+$/.test(opts.renameCore) || opts.renameCore === CORE_FILE) {
294
+ console.error(C.red('✗ --rename-core 非法(不能含路径分隔符,也不能与原名相同)'))
295
+ process.exit(1)
296
+ }
297
+ if (existsSync(path.join(opts.dir, opts.renameCore))) {
298
+ console.error(C.red(`✗ --rename-core 目标已存在:${opts.renameCore}`))
299
+ process.exit(1)
300
+ }
301
+ renames.push({ from: CORE_FILE, to: opts.renameCore })
302
+ }
303
+ if (opts.renameDocs !== undefined) {
304
+ if (!/^[^/\\]+$/.test(opts.renameDocs) || opts.renameDocs === DOCS_DIR) {
305
+ console.error(C.red('✗ --rename-docs 非法(不能含路径分隔符,也不能与原名相同)'))
306
+ process.exit(1)
307
+ }
308
+ if (existsSync(path.join(opts.dir, opts.renameDocs))) {
309
+ console.error(C.red(`✗ --rename-docs 目标已存在:${opts.renameDocs}`))
310
+ process.exit(1)
311
+ }
312
+ renames.push({ from: `${DOCS_DIR}/`, to: `${opts.renameDocs}/` })
313
+ }
314
+ if (renames.length > 0) {
315
+ console.log(C.dim(` 按 --rename-* 处理:${renames.map((r) => `${r.from} → ${r.to}`).join(',')}`))
316
+ }
317
+
318
+ // 未被改名覆盖的冲突才需要决策
319
+ const unresolved = conflicts.filter(
320
+ (c) => !renames.some((r) => (c.unit === CORE_FILE ? r.from === CORE_FILE : r.from === `${DOCS_DIR}/`)),
321
+ )
322
+
323
+ if (unresolved.length > 0) {
361
324
  if (opts.force) {
362
- for (const g of groups.keys()) overwrite.add(g)
363
- console.log(C.dim(' --force:全部覆盖'))
325
+ console.log(C.dim(' --force:覆盖已有内容'))
364
326
  } else if (opts.skipConflicts) {
365
- for (const g of groups.keys()) skipped.add(g)
366
- console.log(C.dim(' --skip-conflicts:全部跳过'))
327
+ install = false
328
+ console.log(C.dim(' --skip-conflicts:整体跳过(不会只装一半)'))
367
329
  } else if (opts.backupExisting) {
368
- for (const [g, info] of groups) {
369
- for (const target of info.targets) {
370
- const to = uniqueBackupPath(target, defaultSuffix)
371
- existingRenames.push({ from: target, to, group: g })
372
- }
373
- overwrite.add(g)
374
- }
375
- console.log(C.dim(` --backup-existing:已有冲突项将改名为 *${defaultSuffix}`))
330
+ onConflict = 'backup'
331
+ backupSuffix = defaultSuffix
332
+ console.log(C.dim(` --backup-existing:已有冲突项改名为 *${defaultSuffix} 后安装`))
376
333
  } else if (!interactive) {
377
- console.error(C.red('\n✗ 非交互环境下检测到冲突,已中止(不会静默覆盖)。'))
378
- console.error(' 可选:--force 全部覆盖|--skip-conflicts 全部跳过|--backup-existing 备份已有项后安装|或手动指定 --dir。')
334
+ console.error(C.red('\n✗ 非交互环境下检测到冲突,已中止(不会静默覆盖,也不会只装一半)。'))
335
+ console.error(' 可选:--force 覆盖|--skip-conflicts 跳过(整体不装)|--backup-existing 备份已有项后安装。')
379
336
  process.exit(1)
380
337
  } else {
381
338
  const rl = createInterface({ input: stdin, output: stdout })
382
- let overwriteRest = false
383
339
  try {
384
- for (const g of groups.keys()) {
385
- if (overwriteRest) {
386
- overwrite.add(g)
387
- continue
388
- }
389
- const isDir = g === ROOT_DIR
390
- console.log(`\n${C.bold('冲突:')}${g}${isDir ? '(目录)' : ''}`)
391
- const answer = (
392
- await rl.question(
393
- ` ${C.bold('[o]')} 覆盖已有 ${C.bold('[e]')} 改名已有 ${C.bold('[r]')} 改名我们的 ${C.bold('[s]')} 跳过 ${C.bold('[a]')} 剩余全部覆盖 ${C.bold('[q]')} 中止 > `,
394
- )
340
+ const answer = (
341
+ await rl.question(
342
+ `\n${C.bold('怎么处理?')} ${C.bold('[o]')} 覆盖已有 ${C.bold('[e]')} 改名已有 ${C.bold('[r]')} 改名我们的 ${C.bold('[s]')} 跳过(整体不装) ${C.bold('[q]')} 中止 > `,
395
343
  )
396
- .trim()
397
- .toLowerCase()
398
-
399
- if (answer === 'o') overwrite.add(g)
400
- else if (answer === 'e') {
401
- const targets = [...groups.get(g).targets]
402
- const risky = groups.get(g).kind === 'dir'
403
- if (risky) {
404
- console.log(C.yellow(' ⚠ 同名位置是目录:改名后你项目里对它的引用会指向我们的版本,请自行确认。'))
405
- }
406
- const suffix = (await rl.question(` 给已有项加的后缀(默认 ${defaultSuffix})> `)).trim() || defaultSuffix
407
- if (!/^[.A-Za-z0-9_-]+$/.test(suffix)) {
408
- console.log(C.yellow(' 后缀只能含字母数字点下划线横线,按跳过处理。'))
409
- skipped.add(g)
410
- continue
411
- }
412
- for (const target of targets) {
413
- const to = uniqueBackupPath(target, suffix)
414
- existingRenames.push({ from: target, to, group: g })
415
- }
416
- overwrite.add(g)
417
- for (const r of existingRenames.filter((r) => r.group === g)) {
418
- console.log(C.dim(` → ${path.relative(opts.dir, r.from)} 改名为 ${path.relative(opts.dir, r.to)}`))
419
- }
420
- } else if (answer === 'a') {
421
- overwrite.add(g)
422
- overwriteRest = true
423
- } else if (answer === 's') skipped.add(g)
424
- else if (answer === 'r') {
425
- const suggestion = isDir ? 'docs-playbook' : 'AGENTS.team.md'
426
- const raw = (await rl.question(` 新名字(默认 ${suggestion})> `)).trim() || suggestion
344
+ )
345
+ .trim()
346
+ .toLowerCase()
347
+
348
+ if (answer === 'o') {
349
+ // 覆盖
350
+ } else if (answer === 'e') {
351
+ const suffix = (await rl.question(` 给已有项加的后缀(默认 ${defaultSuffix})> `)).trim() || defaultSuffix
352
+ if (!/^[.A-Za-z0-9_-]+$/.test(suffix)) {
353
+ console.error(C.red(' 后缀只能含字母数字点下划线横线,已中止。'))
354
+ process.exit(1)
355
+ }
356
+ onConflict = 'backup'
357
+ backupSuffix = suffix
358
+ } else if (answer === 'r') {
359
+ for (const unit of new Set(unresolved.map((c) => c.unit))) {
360
+ const suggestion = unit === DOCS_DIR ? 'docs-playbook' : 'AGENTS.team.md'
361
+ const raw = (await rl.question(` ${unit} 的新名字(默认 ${suggestion})> `)).trim() || suggestion
427
362
  const clean = raw.replace(/[/\\]/g, '-')
428
- if (clean === path.basename(g) || clean === '') {
429
- console.log(C.yellow(' 名字未变化,按跳过处理。'))
430
- skipped.add(g)
431
- continue
363
+ if (clean === path.basename(unit) || clean === '') {
364
+ console.error(C.red(' 名字未变化,已中止。'))
365
+ process.exit(1)
432
366
  }
433
- if (isDir) renames.push({ from: `${g}/`, to: `${clean}/`, group: g })
434
- else renames.push({ from: g, to: clean, group: g })
435
- console.log(C.dim(` → 将安装为 ${clean},并对文档内引用同步改写`))
436
- } else if (answer === 'q') {
437
- console.log('已中止,未写入任何文件。')
438
- process.exit(1)
439
- } else {
440
- console.log(C.yellow(' 未识别的选项,按跳过处理。'))
441
- skipped.add(g)
367
+ if (unit === DOCS_DIR) renames.push({ from: `${unit}/`, to: `${clean}/` })
368
+ else renames.push({ from: unit, to: clean })
369
+ console.log(C.dim(` → ${unit} 将安装为 ${clean},文档内引用同步改写`))
442
370
  }
371
+ } else if (answer === 's') {
372
+ install = false
373
+ } else {
374
+ console.log('已中止,未写入任何文件。')
375
+ process.exit(1)
443
376
  }
444
377
  } finally {
445
378
  rl.close()
@@ -447,76 +380,44 @@ async function main() {
447
380
  }
448
381
  }
449
382
 
450
- // ── 4. 生成最终写入计划 ──────────────────────────────────────────
451
- const plan = []
452
- for (const f of files) {
453
- if (skipped.has(f.group)) continue
454
- let rel = f.rel
455
- for (const r of renames) {
456
- if (r.group !== f.group) continue
457
- rel = r.from === 'AGENTS.md' ? (rel === 'AGENTS.md' ? r.to : rel) : rel.startsWith(r.from) ? r.to + rel.slice(r.from.length) : rel
458
- }
459
- plan.push({ ...f, finalRel: rel, overwrite: overwrite.has(f.group) })
460
- }
461
-
462
- if (plan.length === 0) {
463
- console.log(C.yellow('\n没有需要写入的文件(全部跳过)。'))
383
+ if (!install) {
384
+ console.log(C.yellow('\n已跳过:核心与分册都没有安装(不产生半成品)。'))
464
385
  return
465
386
  }
466
387
 
467
- // ── 5. 预览 / 写入 ───────────────────────────────────────────────
468
- const refRenames = renames.map(({ from, to }) => ({ from, to }))
469
- console.log(`\n${C.bold('安装计划')}${opts.dryRun ? C.dim('(--dry-run,不会写入)') : ''}`)
470
- for (const item of plan) {
471
- const tag = item.overwrite ? C.yellow('覆盖') : item.finalRel !== item.rel ? C.green('改名') : C.dim('新增')
472
- console.log(` ${tag} ${item.finalRel}`)
473
- }
474
- if (refRenames.length > 0) {
475
- console.log(C.dim(`\n引用同步改写:${refRenames.map((r) => `${r.from} → ${r.to}`).join(',')}`))
476
- }
477
- if (existingRenames.length > 0) {
478
- console.log(C.dim(`已有项改名:${existingRenames.map((r) => `${path.relative(opts.dir, r.from)} → ${path.relative(opts.dir, r.to)}`).join(',')}`))
479
- }
388
+ // ── 3. 预览 ────────────────────────────────────────────────────────
389
+ const preview = renames.length > 0 ? `(改名:${renames.map((r) => `${r.from} → ${r.to}`).join(',')})` : ''
390
+ console.log(`\n${C.bold('安装计划')}${opts.dryRun ? C.dim('(--dry-run,不会写入)') : ''}${C.dim(preview)}`)
391
+ console.log(C.dim(` ${CORE_FILE} + ${DOCS_DIR}/ 作为整体一起安装;冲突策略:${onConflict}${backupSuffix ? `(后缀 ${backupSuffix})` : ''}`))
480
392
 
481
393
  if (opts.dryRun) {
482
- console.log(C.dim('\n(dry-run 结束)'))
394
+ console.log(C.dim('\n(dry-run 结束,未写入任何文件)'))
483
395
  return
484
396
  }
485
397
 
486
- // ── 5.5 先腾出原路径(改名已有项),再写我们的 ────────────────────
487
- for (const r of existingRenames) {
488
- try {
489
- await mkdir(path.dirname(r.to), { recursive: true })
490
- await rename(r.from, r.to)
491
- } catch (error) {
492
- console.error(C.red(`✗ 改名失败:${r.from} → ${r.to}(${error.message})。后续文件未写入。`))
398
+ // ── 4. 原子安装(暂存 → 提交 → 失败回滚) ────────────────────────
399
+ const result = await installAtomic({
400
+ sourceRoot: SOURCE_ROOT,
401
+ targetDir: opts.dir,
402
+ onConflict,
403
+ renames,
404
+ backupSuffix,
405
+ })
406
+
407
+ if (!result.ok) {
408
+ if (result.code === 'conflict') {
409
+ console.error(C.red(`\n✗ 失败:${result.message}`))
493
410
  process.exit(1)
494
411
  }
412
+ console.error(C.red(`\n✗ 安装失败,已回滚到安装前状态:${result.message}`))
413
+ process.exit(1)
495
414
  }
496
415
 
497
- let written = 0
498
- for (const item of plan) {
499
- const srcAbs = path.join(SOURCE_ROOT, item.rel)
500
- const destAbs = path.join(opts.dir, item.finalRel)
501
- if (!destAbs.startsWith(opts.dir + path.sep) && destAbs !== opts.dir) {
502
- console.error(C.red(`✗ 拒绝写入目标目录之外的路径:${destAbs}`))
503
- continue
504
- }
505
- await mkdir(path.dirname(destAbs), { recursive: true })
506
-
507
- const isText = /\.(md|svg|txt|yml|yaml|json)$/i.test(item.rel)
508
- if (isText && refRenames.length > 0) {
509
- const text = await readFile(srcAbs, 'utf8')
510
- await writeFile(destAbs, rewriteReferences(text, refRenames), 'utf8')
511
- } else {
512
- await writeFile(destAbs, await readFile(srcAbs))
513
- }
514
- written += 1
416
+ console.log(C.green(`\n✓ 完成:${result.installed.length} 个文件已原子安装到 ${opts.dir}`))
417
+ if (result.backups.length > 0) {
418
+ console.log(C.yellow(` 你的原文件已保留为:${result.backups.map((b) => path.relative(opts.dir, b.to)).join(',')}`))
515
419
  }
516
-
517
- console.log(C.green(`\n✓ 完成:写入 ${written} 个文件到 ${opts.dir}`))
518
- if (skipped.size > 0) console.log(C.yellow(` 跳过 ${skipped.size} 组冲突:${[...skipped].join(', ')}`))
519
- console.log(C.dim(' 提示:若项目已有自己的 AGENTS.md 规则,建议把 playbook 内容合并进去而不是替换。'))
420
+ console.log(C.dim(' 提示:若项目已有自己的协作规则,建议把它们合并进新的 AGENTS.md,而不是两份并存。'))
520
421
  }
521
422
 
522
423
  await main()
package/lib/index.js CHANGED
@@ -1,61 +1,68 @@
1
1
  /**
2
2
  * dsh-agent-team-playbook — DSH 命令插件(Host 半身)
3
3
  *
4
- * 提供一个只读命令 `/atp`(agent-team-playbook 缩写),把多智能体协作规程带进对话:
5
- * /atp 摘要(档位、四问、收尾三问、如何装成常驻)
6
- * /atp core 核心全文(读完即在本轮遵循)
7
- * /atp paths 各分册的绝对路径
8
- * /atp help 用法
4
+ * 只读命令 `/atp`(agent-team-playbook 缩写):
5
+ * /atp 摘要(档位、四问、收尾三问、安装方式)
6
+ * /atp core 核心全文(读完即在本轮遵循)
7
+ * /atp paths 各分册的绝对路径
8
+ * /atp install 把 playbook 原子安装进当前工作区(已存在同名内容则拒绝)
9
+ * /atp install force 覆盖同名内容后安装(会先暂存,失败可回滚)
10
+ * /atp help 用法
9
11
  *
10
- * 命令名刻意取得短而少见:DSH 对重名命令是**硬报错**(plugin 加载失败),
11
- * 用 `agent-team` 这种通用词容易被其他插件或后续官方功能占用。
12
- *
13
- * 本插件**不写任何文件**。要让规程成为每个 agent 每轮的固定上下文,
14
- * 用 CLI 安装:`npx dsh-agent-team-playbook init`(项目级)或 `init --global`(全局)。
15
- *
16
- * 为什么不做成 skill:skill 的目录摘要会常驻占用上下文(约 300 tokens/轮),
17
- * 而分册本来就不会自动进上下文(只有被读取时才消耗),所以用命令按需取更划算。
12
+ * 命令名刻意取得短而少见:DSH 对重名命令是**硬报错**(插件加载失败),
13
+ * 用 agent-team 这种通用词容易被其他插件或后续官方功能占用。
18
14
  *
19
15
  * @module lib/index.js
20
16
  */
21
-
22
17
  import { readFileSync, existsSync, readdirSync } from 'node:fs'
23
18
  import path from 'node:path'
24
19
  import { fileURLToPath } from 'node:url'
20
+ import { installAtomic } from './install.js'
25
21
 
26
- /** 插件名(与 cordis.patch.yml 中的 name 对应)。 */
27
22
  export const name = 'dsh-agent-team-playbook'
28
23
 
29
- /** 只依赖命令注册表;缺失时插件不加载,不会拖累 composition。 */
24
+ /** 只硬依赖命令注册表;工作区目录服务可选,缺失时回退到进程 cwd。 */
30
25
  export const inject = ['commands']
31
26
 
32
27
  const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
33
28
  const PLAYBOOK_DIR = path.join(PACKAGE_ROOT, 'playbook')
34
29
 
35
30
  const USAGE = [
36
- '用法:/atp [core|paths|help]',
31
+ '用法:/atp [core|paths|install|help]',
37
32
  '',
38
- ' (无参数) 规程摘要与安装方式',
39
- ' core 输出核心全文(约 5k 字符),读完即在本轮按它协作',
40
- ' paths 各分册的绝对路径,便于按需查阅',
41
- ' help 显示本说明',
33
+ ' (无参数) 规程摘要与安装方式',
34
+ ' core 输出核心全文(约 5k 字符),读完即在本轮按它协作',
35
+ ' paths 各分册的绝对路径,便于按需查阅',
36
+ ' install 把 playbook 原子安装进当前工作区(有同名内容则拒绝,不覆盖)',
37
+ ' install force 覆盖同名内容后安装(先暂存原件,失败自动回滚)',
38
+ ' help 显示本说明',
42
39
  ].join('\n')
43
40
 
44
- /** 摘要:刻意短,够判断"该用哪一档、先做什么"即可。 */
41
+ /** 摘要:纯文本(客户端把命令结果按原样渲染,用 markdown 反而难看)。 */
45
42
  const SUMMARY = [
46
- '## 多智能体协作规程(agent-team-playbook)',
43
+ '多智能体协作规程(agent-team-playbook)',
47
44
  '',
48
- '**档位**:快速 15–30 分钟(单点可逆、自审)|标准 半天(S0–S6、源码级+短测)|严格 1–2 天/子任务(全流程+红队+双重审计)',
45
+ '档位:快速 15–30 分钟(单点可逆、自审)|标准 半天(S0–S6、源码级+短测)|严格 1–2 天/子任务(全流程+红队+双重审计)',
49
46
  '',
50
- '**动手前**:验收标准可判真假?档位定了吗?方案过四问了吗——可行性 / 合理性 / **完整性** / 优越性?',
47
+ '动手前:验收标准可判真假?档位定了吗?方案过四问了吗——可行性 / 合理性 / 完整性 / 优越性?',
51
48
  '',
52
- '**修复型任务**:先调查根因再改,不允许"没复现就动手"。',
49
+ '修复型任务:先调查根因再改,不允许「没复现就动手」。',
53
50
  '',
54
- '**完成** = 实现 + 自检 + **证据**;审计要全面系统并追到根因,别只修表象。',
51
+ '完成 = 实现 + 自检 + 证据;审计要全面系统并追到根因,别只修表象。',
55
52
  '',
56
- '**审计产出的问题**分高/中/低:高的本轮修,中低出轮,回流深度上限 1 层。',
53
+ '审计产出的问题分高/中/低:高的本轮修,中低出轮,回流深度上限 1 层。',
57
54
  '',
58
- '**收尾三问**:哪里最慢?哪里最痛?哪条规则该改?有效经验必须写「已固化到哪」。',
55
+ '收尾三问:哪里最慢?哪里最痛?哪条规则该改?有效经验必须写「已固化到哪」。',
56
+ ].join('\n')
57
+
58
+ const INSTALL_HINT = [
59
+ '—',
60
+ '让规程变成每轮的固定上下文(本命令只是按需调用):',
61
+ '',
62
+ ' /atp install 装进当前工作区(AGENTS.md + docs/)',
63
+ ' /atp install force 已有同名内容时覆盖(先暂存,可回滚)',
64
+ ' npx dsh-agent-team-playbook init --global 全局指针区块',
65
+ ' npx dsh-agent-team-playbook init --global --inline-core 全局内联核心全文',
59
66
  ].join('\n')
60
67
 
61
68
  function readPlaybook(rel) {
@@ -71,65 +78,133 @@ function readPlaybook(rel) {
71
78
  /** 列出分册路径(用于 /atp paths)。 */
72
79
  function renderPaths() {
73
80
  const rulesDir = path.join(PLAYBOOK_DIR, 'docs/workflow/rules')
74
- const lines = [`核心:\`${path.join(PLAYBOOK_DIR, 'AGENTS.md')}\``, '', '分册:']
75
- if (existsSync(rulesDir)) {
76
- const files = readdirSafe(rulesDir).filter((f) => f.endsWith('.md')).sort()
77
- for (const f of files) lines.push(` \`${path.join(rulesDir, f)}\``)
78
- } else {
79
- lines.push(' (未找到分册目录)')
81
+ const lines = [`核心:${path.join(PLAYBOOK_DIR, 'AGENTS.md')}`, '', '分册:']
82
+ let files = []
83
+ try {
84
+ files = readdirSync(rulesDir).filter((f) => f.endsWith('.md')).sort()
85
+ } catch {
86
+ files = []
80
87
  }
81
- lines.push('', `经验库:\`${path.join(PLAYBOOK_DIR, 'docs/workflow/practices')}\``)
88
+ if (files.length === 0) lines.push(' (未找到分册目录)')
89
+ for (const f of files) lines.push(` ${path.join(rulesDir, f)}`)
90
+ lines.push('', `经验库:${path.join(PLAYBOOK_DIR, 'docs/workflow/practices')}`)
82
91
  return lines.join('\n')
83
92
  }
84
93
 
85
- function readdirSafe(dir) {
94
+ /**
95
+ * 解析工作区目录。
96
+ *
97
+ * **刻意不回退到 process.cwd()**:宿主进程的 cwd 可能是应用目录或 $HOME,
98
+ * 拿它当安装目标会写到用户意料之外的地方。拿不到就明确拒绝,让用户改用 CLI 的 --dir。
99
+ *
100
+ * @returns {string | null}
101
+ */
102
+ function resolveWorkspace(ctx, invocation) {
86
103
  try {
87
- return readdirSync(dir)
104
+ const wd = typeof ctx.get === 'function' ? ctx.get('workingDirectory') : undefined
105
+ const session = invocation?.agent?.session
106
+ if (wd && typeof wd.get === 'function' && session !== undefined) {
107
+ const dir = wd.get(session)
108
+ if (typeof dir === 'string' && dir.length > 0) return path.resolve(dir)
109
+ }
88
110
  } catch {
89
- return []
111
+ /* 服务不可用 → 返回 null,由调用方拒绝 */
90
112
  }
113
+ return null
91
114
  }
92
115
 
93
- /**
94
- * 安装提示:让用户知道"摘要 ≠ 常驻"。
95
- */
96
- function renderInstallHint() {
97
- return [
98
- '---',
99
- '**让规程变成每轮的固定上下文**(本命令只是按需调用):',
100
- '',
101
- '```bash',
102
- 'npx dsh-agent-team-playbook init # 写 <项目>/AGENTS.md + docs/',
103
- 'npx dsh-agent-team-playbook init --global # 用户全局:受管区块(指针)',
104
- 'npx dsh-agent-team-playbook init --global --inline-core # 全局内联核心全文',
105
- '```',
106
- ].join('\n')
116
+ /** 明显不该被当作安装目标的位置(防误写)。 */
117
+ function isUnsafeTarget(dir) {
118
+ const dshHome = process.env.DSH_HOME || path.join(process.env.HOME ?? '', '.dsh')
119
+ const unsafe = [PACKAGE_ROOT, dshHome, process.env.HOME ?? ''].filter(Boolean).map((p) => path.resolve(p))
120
+ return unsafe.some((u) => dir === u)
121
+ }
122
+
123
+ async function handleInstall(ctx, rawInput, invocation) {
124
+ const force = /\bforce\b|\b--force\b/i.test(rawInput)
125
+ const targetDir = resolveWorkspace(ctx, invocation)
126
+
127
+ if (targetDir === null) {
128
+ return {
129
+ kind: 'error',
130
+ text: [
131
+ '无法确定当前工作区目录,已拒绝安装(避免写到你没预期的地方)。',
132
+ '',
133
+ '请改用命令行并显式指定目录:',
134
+ ' npx dsh-agent-team-playbook init --dir <你的项目路径>',
135
+ ].join('\n'),
136
+ }
137
+ }
138
+ if (isUnsafeTarget(targetDir)) {
139
+ return {
140
+ kind: 'error',
141
+ text: `拒绝安装到 ${targetDir}:这看起来是 DSH 主目录或插件自身目录。请先在项目里打开会话,或用 CLI 的 --dir。`,
142
+ }
143
+ }
144
+
145
+ const result = await installAtomic({
146
+ sourceRoot: PLAYBOOK_DIR,
147
+ targetDir,
148
+ onConflict: force ? 'overwrite' : 'error',
149
+ })
150
+
151
+ if (!result.ok) {
152
+ if (result.code === 'conflict') {
153
+ const list = result.conflicts
154
+ .slice(0, 6)
155
+ .map((c) => ` · ${path.relative(targetDir, c.target)}(${c.reason})`)
156
+ .join('\n')
157
+ return {
158
+ kind: 'error',
159
+ text: [
160
+ `未安装:${targetDir} 已存在同名内容。`,
161
+ list,
162
+ result.conflicts.length > 6 ? ` ……共 ${result.conflicts.length} 处` : '',
163
+ '',
164
+ '可选做法:',
165
+ ' /atp install force 覆盖(先暂存原件,失败自动回滚)',
166
+ ' 或用 CLI 交互式处理(可改名/备份):npx dsh-agent-team-playbook init',
167
+ ]
168
+ .filter((l) => l !== '')
169
+ .join('\n'),
170
+ }
171
+ }
172
+ return { kind: 'error', text: `安装失败并已回滚:${result.message}` }
173
+ }
174
+
175
+ const core = result.installed.find((f) => f.endsWith('AGENTS.md')) ?? 'AGENTS.md'
176
+ const docCount = result.installed.filter((f) => f.startsWith('docs/')).length
177
+ return {
178
+ kind: 'success',
179
+ text: [
180
+ `已安装到:${targetDir}`,
181
+ ` ${core} + docs/(${docCount} 个文件),核心与分册作为整体一起落地`,
182
+ '',
183
+ '工作区 AGENTS.md 会被 DSH 每轮自动注入,重载会话后生效。',
184
+ ].join('\n'),
185
+ }
107
186
  }
108
187
 
109
188
  /**
110
189
  * 命令处理器。
111
- * @returns {{kind: 'success'|'error', text: string}}
190
+ * @returns {Promise<{kind: 'success'|'error', text: string}>|{kind:'success'|'error', text:string}}
112
191
  */
113
- function handleCommand(invocation) {
192
+ function handleCommand(ctx, invocation) {
114
193
  const raw = String(invocation?.rawInput ?? '').trim()
115
194
  const sub = raw.toLowerCase()
116
195
 
117
196
  if (sub === '' || sub === 'summary') {
118
- return { kind: 'success', text: `${SUMMARY}\n\n${renderInstallHint()}` }
119
- }
120
- if (sub === 'help' || sub === '?') {
121
- return { kind: 'success', text: USAGE }
122
- }
123
- if (sub === 'paths') {
124
- return { kind: 'success', text: renderPaths() }
197
+ return { kind: 'success', text: `${SUMMARY}\n\n${INSTALL_HINT}` }
125
198
  }
199
+ if (sub === 'help' || sub === '?') return { kind: 'success', text: USAGE }
200
+ if (sub === 'paths') return { kind: 'success', text: renderPaths() }
126
201
  if (sub === 'core' || sub === 'full') {
127
202
  const core = readPlaybook('AGENTS.md')
128
- if (core === undefined) {
129
- return { kind: 'error', text: `未找到核心文件:${path.join(PLAYBOOK_DIR, 'AGENTS.md')}` }
130
- }
203
+ if (core === undefined) return { kind: 'error', text: `未找到核心文件:${path.join(PLAYBOOK_DIR, 'AGENTS.md')}` }
131
204
  return { kind: 'success', text: core }
132
205
  }
206
+ if (sub === 'install' || sub.startsWith('install ')) return handleInstall(ctx, raw, invocation)
207
+
133
208
  return { kind: 'error', text: `未知参数:${raw}\n\n${USAGE}` }
134
209
  }
135
210
 
@@ -141,9 +216,9 @@ export function apply(ctx) {
141
216
  ctx.commands.register({
142
217
  definitionId: 'dsh-agent-team-playbook',
143
218
  name: 'atp',
144
- description: '多智能体协作规程(agent-team-playbook):摘要 / 核心全文 / 分册路径(只读)',
145
- input: { hint: '[core|paths|help]' },
146
- handler: handleCommand,
219
+ description: '多智能体协作规程(agent-team-playbook):摘要 / 核心全文 / 分册路径 / 安装到工作区',
220
+ input: { hint: '[core|paths|install|help]' },
221
+ handler: (invocation) => handleCommand(ctx, invocation),
147
222
  })
148
223
  }
149
224
 
package/lib/install.js ADDED
@@ -0,0 +1,252 @@
1
+ /**
2
+ * 原子安装逻辑(CLI 与 /atp 命令共用)
3
+ *
4
+ * 设计约束:
5
+ * - **核心与分册是一个不可分单元**:要么都装,要么都不装
6
+ * - **暂存 → 提交 → 回滚**:提交前不动用户目录;任何一步失败完整还原
7
+ * - 覆盖前把原件暂存进 stage,成功才丢弃(否则可能丢用户数据)
8
+ *
9
+ * 本模块不打印、不读 TTY,只返回结构化结果,方便 CLI 与命令各自渲染。
10
+ *
11
+ * @module lib/install
12
+ */
13
+ import { readFile, writeFile, mkdir, stat, readdir, rename, rm, rmdir } from 'node:fs/promises'
14
+ import { existsSync } from 'node:fs'
15
+ import path from 'node:path'
16
+
17
+ /** 会被安装进用户项目的单元:核心文件 + 分册目录。 */
18
+ export const CORE_FILE = 'AGENTS.md'
19
+ export const DOCS_DIR = 'docs'
20
+
21
+ /** 内容是否属于需要改写引用的文本类型。 */
22
+ const TEXT_RE = /\.(md|svg|txt|yml|yaml|json)$/i
23
+
24
+ /** 递归列出目录下所有文件(相对 given 目录的 posix 路径)。 */
25
+ export async function listFiles(rootDir, relDir) {
26
+ const abs = path.join(rootDir, relDir)
27
+ const out = []
28
+ let entries
29
+ try {
30
+ entries = await readdir(abs, { withFileTypes: true })
31
+ } catch {
32
+ return out
33
+ }
34
+ for (const entry of entries) {
35
+ const rel = path.posix.join(relDir, entry.name)
36
+ if (entry.isDirectory()) out.push(...(await listFiles(rootDir, rel)))
37
+ else if (entry.isFile()) out.push(rel)
38
+ }
39
+ return out.sort()
40
+ }
41
+
42
+ /**
43
+ * 检测目标路径的冲突。`target` 是"改已有项"时要动的路径。
44
+ * @returns {Promise<null | {reason: string, kind: 'file'|'dir'|'parent-file', target: string}>}
45
+ */
46
+ export async function inspectConflict(destAbs) {
47
+ if (existsSync(destAbs)) {
48
+ const s = await stat(destAbs)
49
+ return s.isDirectory()
50
+ ? { reason: '同名位置已是目录', kind: 'dir', target: destAbs }
51
+ : { reason: '文件已存在', kind: 'file', target: destAbs }
52
+ }
53
+ let p = path.dirname(destAbs)
54
+ while (p && p !== path.dirname(p)) {
55
+ if (existsSync(p)) {
56
+ const s = await stat(p)
57
+ if (!s.isDirectory()) return { reason: `上级 ${path.basename(p)} 是文件,无法创建目录`, kind: 'parent-file', target: p }
58
+ break
59
+ }
60
+ p = path.dirname(p)
61
+ }
62
+ return null
63
+ }
64
+
65
+ /** 生成不冲突的备份路径。 */
66
+ export function uniqueBackupPath(target, suffix) {
67
+ let to = `${target}${suffix}`
68
+ let i = 1
69
+ while (existsSync(to)) to = `${target}${suffix}-${i++}`
70
+ return to
71
+ }
72
+
73
+ /** 把引用改写应用到文本:目录前缀改完再改根文件名。 */
74
+ export function rewriteReferences(text, renames) {
75
+ let out = text
76
+ for (const { from, to } of renames) {
77
+ if (from === CORE_FILE) {
78
+ out = out.replace(/(^|[^/\w.-])AGENTS\.md(?![.\w-])/g, (_m, pre) => `${pre}${to}`)
79
+ } else {
80
+ out = out.split(from).join(to)
81
+ }
82
+ }
83
+ return out
84
+ }
85
+
86
+ /**
87
+ * 扫描安装单元并返回冲突摘要。
88
+ * @param {{sourceRoot: string, targetDir: string}} args
89
+ */
90
+ export async function scan({ sourceRoot, targetDir }) {
91
+ const docRels = await listFiles(sourceRoot, DOCS_DIR)
92
+ const units = [
93
+ { key: CORE_FILE, kind: 'file', files: [CORE_FILE] },
94
+ { key: DOCS_DIR, kind: 'dir', files: docRels },
95
+ ]
96
+ const conflicts = []
97
+ for (const u of units) {
98
+ for (const rel of u.files) {
99
+ const c = await inspectConflict(path.join(targetDir, rel))
100
+ if (c !== null) conflicts.push({ unit: u.key, rel, ...c })
101
+ }
102
+ }
103
+ return { units, docRels, conflicts }
104
+ }
105
+
106
+ /**
107
+ * 原子安装。
108
+ *
109
+ * @param {object} args
110
+ * @param {string} args.sourceRoot 包内 playbook 目录
111
+ * @param {string} args.targetDir 目标工作区
112
+ * @param {'error'|'overwrite'|'backup'} args.onConflict 冲突策略
113
+ * @param {Array<{from: string, to: string}>} [args.renames] 我们这侧的改名(会改写引用)
114
+ * @param {string} [args.backupSuffix] onConflict==='backup' 时用的后缀
115
+ * @param {(phase: string, detail?: any) => void} [args.onProgress] 进度回调(可选)
116
+ * @returns {Promise<{ok: boolean, code?: 'conflict'|'failed', message?: string,
117
+ * installed: string[], backups: Array<{from:string,to:string}>,
118
+ * conflicts?: any[]}>}
119
+ */
120
+ export async function installAtomic({ sourceRoot, targetDir, onConflict, renames = [], backupSuffix, onProgress = () => {} }) {
121
+ const scanned = await scan({ sourceRoot, targetDir })
122
+ const { units, docRels, conflicts } = scanned
123
+
124
+ if (docRels.length === 0) {
125
+ return { ok: false, code: 'failed', message: `包内缺少分册:${path.join(sourceRoot, DOCS_DIR)}`, installed: [], backups: [] }
126
+ }
127
+
128
+ if (conflicts.length > 0) {
129
+ if (onConflict === 'error') {
130
+ return { ok: false, code: 'conflict', message: '目标已存在同名内容', conflicts, installed: [], backups: [] }
131
+ }
132
+ }
133
+
134
+ // 1. 计划
135
+ const plan = []
136
+ for (const u of units) {
137
+ for (const rel of u.files) {
138
+ let finalRel = rel
139
+ for (const r of renames) {
140
+ if (r.from === CORE_FILE) {
141
+ if (finalRel === CORE_FILE) finalRel = r.to
142
+ } else if (finalRel.startsWith(r.from)) {
143
+ finalRel = r.to + finalRel.slice(r.from.length)
144
+ }
145
+ }
146
+ plan.push({ srcRel: rel, finalRel })
147
+ }
148
+ }
149
+
150
+ // 2. 备份(改名已有项)
151
+ const backups = []
152
+ if (conflicts.length > 0 && onConflict === 'backup') {
153
+ if (!backupSuffix) throw new Error('onConflict=backup 需要 backupSuffix')
154
+ for (const c of conflicts) {
155
+ const to = uniqueBackupPath(c.target, backupSuffix)
156
+ await mkdir(path.dirname(to), { recursive: true })
157
+ await rename(c.target, to)
158
+ backups.push({ from: c.target, to })
159
+ }
160
+ }
161
+ onProgress('backups', backups)
162
+
163
+ // 3. 暂存 → 提交 → 失败回滚
164
+ const stageRoot = path.join(targetDir, `.atp-stage-${process.pid}-${Date.now()}`)
165
+ const stashRoot = path.join(stageRoot, '.rollback')
166
+ const committed = []
167
+ const madeDirs = []
168
+ const stashed = []
169
+
170
+ const cleanup = async () => {
171
+ await rm(stageRoot, { recursive: true, force: true }).catch(() => {})
172
+ }
173
+
174
+ const rollback = async () => {
175
+ for (const f of committed.reverse()) await rm(f, { recursive: true, force: true }).catch(() => {})
176
+ for (const s of stashed.reverse()) {
177
+ await mkdir(path.dirname(s.from), { recursive: true }).catch(() => {})
178
+ await rename(s.to, s.from).catch(() => {})
179
+ }
180
+ for (const b of backups.reverse()) await rename(b.to, b.from).catch(() => {})
181
+ for (const d of madeDirs.reverse()) await rmdir(d).catch(() => {})
182
+ await cleanup()
183
+ }
184
+
185
+ try {
186
+ // 3.1 全量写进暂存(用户目录此时未被改动)
187
+ for (const item of plan) {
188
+ const dest = path.join(stageRoot, item.finalRel)
189
+ await mkdir(path.dirname(dest), { recursive: true })
190
+ const srcAbs = path.join(sourceRoot, item.srcRel)
191
+ if (TEXT_RE.test(item.srcRel) && renames.length > 0) {
192
+ await writeFile(dest, rewriteReferences(await readFile(srcAbs, 'utf8'), renames), 'utf8')
193
+ } else {
194
+ await writeFile(dest, await readFile(srcAbs))
195
+ }
196
+ }
197
+ onProgress('staged', plan.length)
198
+
199
+ // 3.2 提交前把"我们真要占用但还存在"的原件挪进 stash
200
+ const destSet = new Set(plan.map((i) => path.join(targetDir, i.finalRel)))
201
+ for (const c of conflicts) {
202
+ const target = c.target
203
+ if (!existsSync(target)) continue // 已被备份走
204
+ if (!destSet.has(target)) continue // 我们改了自己的名字,没占用它
205
+ const rel = path.relative(targetDir, target)
206
+ const to = path.join(stashRoot, rel)
207
+ await mkdir(path.dirname(to), { recursive: true })
208
+ await rename(target, to)
209
+ stashed.push({ from: target, to })
210
+ }
211
+
212
+ // 3.3 提交
213
+ for (const item of plan) {
214
+ const dest = path.join(targetDir, item.finalRel)
215
+ if (!dest.startsWith(targetDir + path.sep)) throw new Error(`拒绝写入目标目录之外:${dest}`)
216
+ const missing = []
217
+ let dir = path.dirname(dest)
218
+ while (!existsSync(dir)) {
219
+ missing.unshift(dir)
220
+ const parent = path.dirname(dir)
221
+ if (parent === dir) break
222
+ dir = parent
223
+ }
224
+ for (const d of missing) {
225
+ await mkdir(d)
226
+ madeDirs.push(d)
227
+ }
228
+ await rename(path.join(stageRoot, item.finalRel), dest)
229
+ committed.push(dest)
230
+ // 仅测试用故障注入:验证"中途失败也能完整回滚"
231
+ const failAfter = Number(process.env.ATP_FAIL_AFTER_COMMITS ?? 0)
232
+ if (failAfter > 0 && committed.length === failAfter) {
233
+ throw new Error(`injected failure after ${failAfter} commits`)
234
+ }
235
+ }
236
+
237
+ // 3.4 校验:全部落地,且核心与分册都在
238
+ const missingAfter = plan.filter((i) => !existsSync(path.join(targetDir, i.finalRel)))
239
+ if (missingAfter.length > 0) throw new Error(`提交后缺少 ${missingAfter.length} 个文件`)
240
+ const coreFinal = plan.find((i) => i.srcRel === CORE_FILE)?.finalRel
241
+ const sampleDoc = plan.find((i) => i.srcRel.startsWith(`${DOCS_DIR}/workflow/rules/`))?.finalRel
242
+ if (!coreFinal || !sampleDoc || !existsSync(path.join(targetDir, coreFinal)) || !existsSync(path.join(targetDir, sampleDoc))) {
243
+ throw new Error('核心与分册没有同时落地')
244
+ }
245
+ } catch (error) {
246
+ await rollback()
247
+ return { ok: false, code: 'failed', message: error.message, installed: [], backups: [] }
248
+ }
249
+
250
+ await cleanup()
251
+ return { ok: true, installed: plan.map((i) => i.finalRel), backups }
252
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-agent-team-playbook",
3
- "version": "1.23.1",
3
+ "version": "1.25.0",
4
4
  "description": "DeepSeek Harness plugin that brings an executable multi-agent collaboration workflow (charter, triage tiers, six-stage pipeline, audit gates, experience library): a read-only /agent-team command plus a collision-aware installer for the documents.",
5
5
  "type": "module",
6
6
  "license": "MIT",