dsh-agent-team-playbook 1.23.1 → 1.24.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.
Files changed (2) hide show
  1. package/bin/cli.mjs +235 -147
  2. package/package.json +1 -1
package/bin/cli.mjs CHANGED
@@ -18,7 +18,7 @@
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, readdir, rename, rm, rmdir } 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'
@@ -55,6 +55,8 @@ function parseArgs(argv) {
55
55
  yes: false,
56
56
  inlineCore: false,
57
57
  backupExisting: false,
58
+ renameCore: undefined,
59
+ renameDocs: undefined,
58
60
  }
59
61
  for (let i = 0; i < argv.length; i += 1) {
60
62
  const a = argv[i]
@@ -66,6 +68,8 @@ function parseArgs(argv) {
66
68
  else if (a === '--yes' || a === '-y') opts.yes = true
67
69
  else if (a === '--inline-core') opts.inlineCore = true
68
70
  else if (a === '--backup-existing') opts.backupExisting = true
71
+ else if (a === '--rename-core') opts.renameCore = argv[(i += 1)]
72
+ else if (a === '--rename-docs') opts.renameDocs = argv[(i += 1)]
69
73
  else if (a === '--help' || a === '-h') opts.help = true
70
74
  else if (a === 'init') continue
71
75
  else {
@@ -91,6 +95,8 @@ ${C.bold('选项')}
91
95
  --yes, -y 非交互确认(--global 追加区块用)
92
96
  --dry-run 只显示计划,不写任何文件
93
97
  --backup-existing 冲突时把已有项改名为 *<后缀>,再装我们的(不询问)
98
+ --rename-core <名> 非交互:把我们的核心装成这个名字(如 AGENTS.team.md),引用同步改写
99
+ --rename-docs <名> 非交互:把我们的分册目录装成这个名字(如 docs-playbook),引用同步改写
94
100
  --force, -f 冲突时全部覆盖(不询问)
95
101
  --skip-conflicts 冲突时全部跳过(不询问)
96
102
  -h, --help 显示本帮助
@@ -315,131 +321,137 @@ async function main() {
315
321
  process.exit(1)
316
322
  }
317
323
 
318
- // ── 1. 组装安装计划 ───────────────────────────────────────────────
319
- const files = [{ rel: ROOT_FILE, group: ROOT_FILE }]
324
+ // ── 1. 组装安装单元:核心与分册是一个整体,必须同进同退 ─────────────
320
325
  const docRels = await walk(ROOT_DIR)
321
326
  if (docRels.length === 0) {
322
327
  console.error(C.red(`✗ 包内缺少分册:${path.join(SOURCE_ROOT, ROOT_DIR)} 为空或不存在`))
323
328
  process.exit(1)
324
329
  }
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)
330
+ const UNITS = [
331
+ { key: ROOT_FILE, kind: 'file', files: [ROOT_FILE] },
332
+ { key: ROOT_DIR, kind: 'dir', files: docRels },
333
+ ]
334
+
335
+ // ── 2. 冲突检测(按单元归并) ──────────────────────────────────────
336
+ const conflicts = new Map()
337
+ for (const u of UNITS) {
338
+ for (const rel of u.files) {
339
+ const c = await inspectConflict(path.join(opts.dir, rel))
340
+ if (c === null) continue
341
+ if (!conflicts.has(u.key)) conflicts.set(u.key, { kind: u.kind, targets: new Set(), files: [], reasons: new Set() })
342
+ const entry = conflicts.get(u.key)
343
+ entry.targets.add(c.target)
344
+ entry.files.push(rel)
345
+ entry.reasons.add(c.reason)
346
+ }
338
347
  }
339
348
 
340
- if (groups.size === 0) {
341
- console.log(C.green('✓ 目标目录没有同名内容,可直接安装。'))
349
+ if (conflicts.size === 0) {
350
+ console.log(C.green('✓ 目标目录没有同名内容,直接安装(核心 + 分册一起)。'))
342
351
  } 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} 个文件`)
352
+ console.log(C.yellow('⚠ 检测到冲突(核心与分册必须一起装,所以下面整体决策):'))
353
+ for (const [key, info] of conflicts) {
354
+ console.log(` · ${C.bold(key)} —— ${[...info.reasons].join(';')},涉及 ${info.files.length} 个文件`)
346
355
  for (const target of info.targets) console.log(C.dim(` 已有:${path.relative(opts.dir, target)}`))
347
356
  }
348
357
  }
349
358
 
350
- // ── 3. 逐组决定 ──────────────────────────────────────────────────
351
- const renames = []
352
- const skipped = new Set()
353
- const overwrite = new Set()
354
- /** 被改名的"已有文件/目录":{from, to}。安装后原路径归我们使用。 */
355
- const existingRenames = []
359
+ // ── 3. 决策(只有"整体"的选项,不存在装一半) ──────────────────────
360
+ const renames = [] // 我们这侧的改名(会同步改写引用)
361
+ const existingRenames = [] // 已有项改名备份
356
362
  const defaultSuffix = `.bak-${new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)}`
357
-
363
+ let install = true
358
364
  const interactive = stdin.isTTY && stdout.isTTY
359
365
 
360
- if (groups.size > 0) {
366
+ const backupAll = (suffix) => {
367
+ for (const [, info] of conflicts) {
368
+ for (const target of info.targets) {
369
+ existingRenames.push({ from: target, to: uniqueBackupPath(target, suffix) })
370
+ }
371
+ }
372
+ }
373
+
374
+ // 非交互显式改名:只要每个冲突单元都被覆盖,就不再提问
375
+ if (opts.renameCore !== undefined) {
376
+ if (!/^[^/\\]+$/.test(opts.renameCore)) { console.error(C.red('✗ --rename-core 不能含路径分隔符')); process.exit(1) }
377
+ if (opts.renameCore === ROOT_FILE) { console.error(C.red(`✗ --rename-core 不能与原名相同`)); process.exit(1) }
378
+ if (existsSync(path.join(opts.dir, opts.renameCore))) {
379
+ console.error(C.red(`✗ --rename-core 目标已存在:${opts.renameCore}`)); process.exit(1)
380
+ }
381
+ renames.push({ from: ROOT_FILE, to: opts.renameCore })
382
+ }
383
+ if (opts.renameDocs !== undefined) {
384
+ if (!/^[^/\\]+$/.test(opts.renameDocs)) { console.error(C.red('✗ --rename-docs 不能含路径分隔符')); process.exit(1) }
385
+ if (opts.renameDocs === ROOT_DIR) { console.error(C.red(`✗ --rename-docs 不能与原名相同`)); process.exit(1) }
386
+ if (existsSync(path.join(opts.dir, opts.renameDocs))) {
387
+ console.error(C.red(`✗ --rename-docs 目标已存在:${opts.renameDocs}`)); process.exit(1)
388
+ }
389
+ renames.push({ from: `${ROOT_DIR}/`, to: `${opts.renameDocs}/` })
390
+ }
391
+ const unresolved = [...conflicts.keys()].filter(
392
+ (k) => !renames.some((r) => (k === ROOT_FILE ? r.from === ROOT_FILE : r.from === `${ROOT_DIR}/`)),
393
+ )
394
+ // 显式改名时提示一下(用户可能以为必须冲突才会改名)
395
+ for (const r of renames) {
396
+ if (r.from === ROOT_FILE && !conflicts.has(ROOT_FILE)) console.log(C.dim(` --rename-core:核心将装成 ${r.to}(原路径未冲突,仍按你的要求改名)`))
397
+ if (r.from === `${ROOT_DIR}/` && !conflicts.has(ROOT_DIR)) console.log(C.dim(` --rename-docs:分册将装到 ${r.to}/(原路径未冲突,仍按你的要求改名)`))
398
+ }
399
+ if (conflicts.size > 0 && unresolved.length === 0) {
400
+ console.log(C.dim(` 已按 --rename-* 处理全部冲突:${renames.map((r) => `${r.from} → ${r.to}`).join(',')}`))
401
+ }
402
+
403
+ if (unresolved.length > 0) {
361
404
  if (opts.force) {
362
- for (const g of groups.keys()) overwrite.add(g)
363
- console.log(C.dim(' --force:全部覆盖'))
405
+ console.log(C.dim(' --force:覆盖已有内容'))
364
406
  } else if (opts.skipConflicts) {
365
- for (const g of groups.keys()) skipped.add(g)
366
- console.log(C.dim(' --skip-conflicts:全部跳过'))
407
+ install = false
408
+ console.log(C.dim(' --skip-conflicts:整体跳过(不会只装一半)'))
367
409
  } 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}`))
410
+ backupAll(defaultSuffix)
411
+ console.log(C.dim(` --backup-existing:已有冲突项改名为 *${defaultSuffix} 后安装`))
376
412
  } else if (!interactive) {
377
- console.error(C.red('\n✗ 非交互环境下检测到冲突,已中止(不会静默覆盖)。'))
378
- console.error(' 可选:--force 全部覆盖|--skip-conflicts 全部跳过|--backup-existing 备份已有项后安装|或手动指定 --dir。')
413
+ console.error(C.red('\n✗ 非交互环境下检测到冲突,已中止(不会静默覆盖,也不会只装一半)。'))
414
+ console.error(' 可选:--force 覆盖|--skip-conflicts 跳过(整体不装)|--backup-existing 备份已有项后安装。')
379
415
  process.exit(1)
380
416
  } else {
381
417
  const rl = createInterface({ input: stdin, output: stdout })
382
- let overwriteRest = false
383
418
  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
- )
419
+ const answer = (
420
+ await rl.question(
421
+ `\n${C.bold('怎么处理?')} ${C.bold('[o]')} 覆盖已有 ${C.bold('[e]')} 改名已有 ${C.bold('[r]')} 改名我们的 ${C.bold('[s]')} 跳过(整体不装) ${C.bold('[q]')} 中止 > `,
395
422
  )
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
423
+ )
424
+ .trim()
425
+ .toLowerCase()
426
+
427
+ if (answer === 'o') {
428
+ // 覆盖
429
+ } else if (answer === 'e') {
430
+ const suffix = (await rl.question(` 给已有项加的后缀(默认 ${defaultSuffix})> `)).trim() || defaultSuffix
431
+ if (!/^[.A-Za-z0-9_-]+$/.test(suffix)) {
432
+ console.error(C.red(' 后缀只能含字母数字点下划线横线,已中止。'))
433
+ process.exit(1)
434
+ }
435
+ backupAll(suffix)
436
+ } else if (answer === 'r') {
437
+ // 只对我们这侧改名:逐个冲突单元问
438
+ for (const key of conflicts.keys()) {
439
+ const suggestion = key === ROOT_DIR ? 'docs-playbook' : 'AGENTS.team.md'
440
+ const raw = (await rl.question(` ${key} 的新名字(默认 ${suggestion})> `)).trim() || suggestion
427
441
  const clean = raw.replace(/[/\\]/g, '-')
428
- if (clean === path.basename(g) || clean === '') {
429
- console.log(C.yellow(' 名字未变化,按跳过处理。'))
430
- skipped.add(g)
431
- continue
442
+ if (clean === path.basename(key) || clean === '') {
443
+ console.error(C.red(' 名字未变化,已中止。'))
444
+ process.exit(1)
432
445
  }
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)
446
+ if (key === ROOT_DIR) renames.push({ from: `${key}/`, to: `${clean}/` })
447
+ else renames.push({ from: key, to: clean })
448
+ console.log(C.dim(` → ${key} 将安装为 ${clean},文档内引用同步改写`))
442
449
  }
450
+ } else if (answer === 's') {
451
+ install = false
452
+ } else {
453
+ console.log('已中止,未写入任何文件。')
454
+ process.exit(1)
443
455
  }
444
456
  } finally {
445
457
  rl.close()
@@ -447,76 +459,152 @@ async function main() {
447
459
  }
448
460
  }
449
461
 
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) })
462
+ if (!install) {
463
+ console.log(C.yellow('\n已跳过:核心与分册都没有安装(不产生半成品)。'))
464
+ return
460
465
  }
461
466
 
462
- if (plan.length === 0) {
463
- console.log(C.yellow('\n没有需要写入的文件(全部跳过)。'))
464
- return
467
+ // ── 4. 生成最终计划(改名会同步改写引用) ──────────────────────────
468
+ const plan = []
469
+ for (const u of UNITS) {
470
+ for (const rel of u.files) {
471
+ let finalRel = rel
472
+ for (const r of renames) {
473
+ if (r.from === ROOT_FILE) {
474
+ if (finalRel === ROOT_FILE) finalRel = r.to
475
+ } else if (finalRel.startsWith(r.from)) {
476
+ finalRel = r.to + finalRel.slice(r.from.length)
477
+ }
478
+ }
479
+ plan.push({ srcRel: rel, finalRel })
480
+ }
465
481
  }
466
482
 
467
- // ── 5. 预览 / 写入 ───────────────────────────────────────────────
468
483
  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
- }
484
+ console.log(`\n${C.bold('安装计划')}${opts.dryRun ? C.dim('(--dry-run,不会写入)') : ''} —— 共 ${plan.length} 个文件,整体生效`)
485
+ for (const item of plan.slice(0, 3)) console.log(` ${C.dim('新增')} ${item.finalRel}`)
486
+ if (plan.length > 6) console.log(C.dim(` …… 中间 ${plan.length - 6} 个文件省略……`))
487
+ for (const item of plan.slice(-3)) console.log(` ${C.dim('新增')} ${item.finalRel}`)
488
+ if (refRenames.length > 0) console.log(C.dim(`引用同步改写:${refRenames.map((r) => `${r.from} → ${r.to}`).join(',')}`))
477
489
  if (existingRenames.length > 0) {
478
490
  console.log(C.dim(`已有项改名:${existingRenames.map((r) => `${path.relative(opts.dir, r.from)} → ${path.relative(opts.dir, r.to)}`).join(',')}`))
479
491
  }
480
492
 
481
493
  if (opts.dryRun) {
482
- console.log(C.dim('\n(dry-run 结束)'))
494
+ console.log(C.dim('\n(dry-run 结束,未写入任何文件)'))
483
495
  return
484
496
  }
485
497
 
486
- // ── 5.5 先腾出原路径(改名已有项),再写我们的 ────────────────────
487
- for (const r of existingRenames) {
488
- try {
498
+ // ── 5. 暂存 → 提交 → 失败回滚(保证要么全有、要么全无) ─────────────
499
+ const stageRoot = path.join(opts.dir, `.atp-stage-${process.pid}-${Date.now()}`)
500
+ const stashRoot = path.join(stageRoot, '.rollback')
501
+ const committed = []
502
+ const madeDirs = []
503
+ const doneBackups = []
504
+ const stashed = [] // 被覆盖的原件:安装失败时还原
505
+
506
+ const cleanupStage = async () => {
507
+ await rm(stageRoot, { recursive: true, force: true }).catch(() => {})
508
+ }
509
+
510
+ const rollback = async () => {
511
+ for (const f of committed.reverse()) {
512
+ await rm(f, { force: true, recursive: true }).catch(() => {})
513
+ }
514
+ for (const s of stashed.reverse()) {
515
+ await mkdir(path.dirname(s.from), { recursive: true }).catch(() => {})
516
+ await rename(s.to, s.from).catch(() => {})
517
+ }
518
+ for (const r of doneBackups.reverse()) {
519
+ await rename(r.to, r.from).catch(() => {})
520
+ }
521
+ for (const d of madeDirs.reverse()) {
522
+ await rmdir(d).catch(() => {})
523
+ }
524
+ await cleanupStage()
525
+ }
526
+
527
+ try {
528
+ // 5.1 全部写进暂存目录(此时用户目录还没被改动)
529
+ for (const item of plan) {
530
+ const dest = path.join(stageRoot, item.finalRel)
531
+ await mkdir(path.dirname(dest), { recursive: true })
532
+ const srcAbs = path.join(SOURCE_ROOT, item.srcRel)
533
+ const isText = /\.(md|svg|txt|yml|yaml|json)$/i.test(item.srcRel)
534
+ if (isText && refRenames.length > 0) {
535
+ await writeFile(dest, rewriteReferences(await readFile(srcAbs, 'utf8'), refRenames), 'utf8')
536
+ } else {
537
+ await writeFile(dest, await readFile(srcAbs))
538
+ }
539
+ }
540
+
541
+ // 5.2 备份"已有项"(改名腾出原路径)
542
+ for (const r of existingRenames) {
489
543
  await mkdir(path.dirname(r.to), { recursive: true })
490
544
  await rename(r.from, r.to)
491
- } catch (error) {
492
- console.error(C.red(`✗ 改名失败:${r.from} → ${r.to}(${error.message})。后续文件未写入。`))
493
- process.exit(1)
545
+ doneBackups.push(r)
494
546
  }
495
- }
496
547
 
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
548
+ // 5.3 覆盖前先"暂存"原件:这样即使后面失败,也能原样还原,不会丢用户数据
549
+ const planDestSet = new Set(plan.map((i) => path.join(opts.dir, i.finalRel)))
550
+ for (const [, info] of conflicts) {
551
+ for (const target of info.targets) {
552
+ if (!existsSync(target)) continue // 已被 [e] 备份走
553
+ if (!planDestSet.has(target)) continue // 我们改了自己的名字,没占用这个路径 → 不动用户文件
554
+ const rel = path.relative(opts.dir, target)
555
+ const to = path.join(stashRoot, rel)
556
+ await mkdir(path.dirname(to), { recursive: true })
557
+ await rename(target, to)
558
+ stashed.push({ from: target, to })
559
+ }
504
560
  }
505
- await mkdir(path.dirname(destAbs), { recursive: true })
506
561
 
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))
562
+ // 5.4 提交:逐个 rename 到最终位置
563
+ for (const item of plan) {
564
+ const dest = path.join(opts.dir, item.finalRel)
565
+ if (!dest.startsWith(opts.dir + path.sep)) throw new Error(`拒绝写入目标目录之外:${dest}`)
566
+ let dir = path.dirname(dest)
567
+ const missingDirs = []
568
+ while (!existsSync(dir)) {
569
+ missingDirs.unshift(dir)
570
+ const parent = path.dirname(dir)
571
+ if (parent === dir) break
572
+ dir = parent
573
+ }
574
+ for (const d of missingDirs) {
575
+ await mkdir(d)
576
+ madeDirs.push(d)
577
+ }
578
+ await rename(path.join(stageRoot, item.finalRel), dest)
579
+ committed.push(dest)
580
+ // 仅测试用故障注入:验证"中途失败也能完整回滚"
581
+ const failAfter = Number(process.env.ATP_FAIL_AFTER_COMMITS ?? 0)
582
+ if (failAfter > 0 && committed.length === failAfter) {
583
+ throw new Error(`injected failure after ${failAfter} commits (ATP_FAIL_AFTER_COMMITS)`)
584
+ }
513
585
  }
514
- written += 1
586
+
587
+ // 5.5 校验:所有文件都在位,且核心与分册都不缺
588
+ const missingAfter = plan.filter((i) => !existsSync(path.join(opts.dir, i.finalRel)))
589
+ if (missingAfter.length > 0) {
590
+ throw new Error(`提交后缺少 ${missingAfter.length} 个文件:${missingAfter.map((i) => i.finalRel).join(', ')}`)
591
+ }
592
+ const coreRelFinal = plan.find((i) => i.srcRel === ROOT_FILE)?.finalRel
593
+ const docRelFinal = plan.find((i) => i.srcRel === `${ROOT_DIR}/workflow/rules/03-流水线.md`)?.finalRel
594
+ if (coreRelFinal === undefined || docRelFinal === undefined || !existsSync(path.join(opts.dir, coreRelFinal)) || !existsSync(path.join(opts.dir, docRelFinal))) {
595
+ throw new Error('核心与分册没有同时落地')
596
+ }
597
+ } catch (error) {
598
+ console.error(C.red(`\n✗ 安装失败,正在回滚:${error.message}`))
599
+ await rollback()
600
+ console.error(C.red(' 已回滚到安装前状态,未留下半成品。'))
601
+ process.exit(1)
515
602
  }
516
603
 
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 内容合并进去而不是替换。'))
604
+ await cleanupStage()
605
+ console.log(C.green(`\n✓ 完成:${plan.length} 个文件已原子安装到 ${opts.dir}`))
606
+ if (existingRenames.length > 0) console.log(C.yellow(` 你的原文件已保留为:${existingRenames.map((r) => path.relative(opts.dir, r.to)).join(',')}`))
607
+ console.log(C.dim(' 提示:若项目已有自己的协作规则,建议把它们合并进新的 AGENTS.md,而不是两份并存。'))
520
608
  }
521
609
 
522
610
  await main()
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.24.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",