dsh-agent-team-playbook 1.24.0 → 1.27.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,8 +103,15 @@ 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` | 覆盖同名内容后安装(先暂存原件,失败自动回滚) |
108
+ | `/atp apply 1=覆盖 2=备份 3=改名:x` | 对 install 列出的冲突**逐项决定**(覆盖 / 备份你的文件 / 我们这侧改名并同步引用) |
106
109
  | `/atp help` | 用法 |
107
110
 
111
+ **Web / 桌面端还会多一个设置面板**(设置 → 协作规程):显示当前工作区是否已安装、有无同名冲突,并可一键复制建议的处理命令。面板**只读**,不改你任何文件;真正的写入仍走 `/atp install` / `/atp apply`(可见、可审计)。
112
+
113
+ > dsh-go 手机原生界面不加载浏览器半身,因此没有这个面板——在那边用命令即可。
114
+
108
115
  插件**不写任何文件**、也**不挂 skill**——skill 的目录摘要会常驻占用上下文(约 300 tokens/轮),而分册本来就不会自动进上下文,用命令按需取更划算。
109
116
 
110
117
  ### ② 装成"常驻上下文"(会写文件,核心价值)
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, rm, rmdir } 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`,
@@ -116,70 +113,9 @@ ${C.bold('行为')}
116
113
  `)
117
114
  }
118
115
 
119
- /** 递归列出源目录下所有文件,返回相对 SOURCE_ROOT 的 posix 路径。 */
120
- async function walk(relDir) {
121
- const abs = path.join(SOURCE_ROOT, relDir)
122
- const out = []
123
- let entries
124
- try {
125
- entries = await readdir(abs, { withFileTypes: true })
126
- } catch {
127
- return out
128
- }
129
- for (const entry of entries) {
130
- const rel = path.posix.join(relDir, entry.name)
131
- if (entry.isDirectory()) out.push(...(await walk(rel)))
132
- else if (entry.isFile()) out.push(rel)
133
- }
134
- return out.sort()
135
- }
136
116
 
137
- /**
138
- * 目标路径的冲突详情。`target` 是"改已有文件名"时要动的那个路径:
139
- * - 同名文件已存在 → 改名该文件
140
- * - 同名位置是目录 → 改名该目录(风险高,调用处需提示)
141
- * - 上级是文件导致建不了目录 → 改名那个上级文件
142
- */
143
- async function inspectConflict(destAbs) {
144
- if (existsSync(destAbs)) {
145
- const s = await stat(destAbs)
146
- return s.isDirectory()
147
- ? { reason: '同名位置已是目录', kind: 'dir', target: destAbs }
148
- : { reason: '文件已存在', kind: 'file', target: destAbs }
149
- }
150
- let p = path.dirname(destAbs)
151
- while (p && p !== path.dirname(p)) {
152
- if (existsSync(p)) {
153
- const s = await stat(p)
154
- if (!s.isDirectory()) return { reason: `上级 ${path.basename(p)} 是文件,无法创建目录`, kind: 'parent-file', target: p }
155
- break
156
- }
157
- p = path.dirname(p)
158
- }
159
- return null
160
- }
161
117
 
162
- /** 生成不冲突的备份路径。 */
163
- function uniqueBackupPath(target, suffix) {
164
- let to = `${target}${suffix}`
165
- let i = 1
166
- while (existsSync(to)) to = `${target}${suffix}-${i++}`
167
- return to
168
- }
169
118
 
170
- /** 把引用改写应用到文本内容:先改目录前缀,再改根文件名。 */
171
- function rewriteReferences(text, renames) {
172
- let out = text
173
- for (const { from, to } of renames) {
174
- if (from === 'AGENTS.md') {
175
- // 仅替换独立出现的文件名(前后不是路径分隔或字母数字)
176
- out = out.replace(/(^|[^/\w.-])AGENTS\.md(?![.\w-])/g, (_m, pre) => `${pre}${to}`)
177
- } else {
178
- out = out.split(from).join(to)
179
- }
180
- }
181
- return out
182
- }
183
119
 
184
120
  /** 受管区块标记:重复执行时原地更新,绝不碰区块外内容。 */
185
121
  const BLOCK_START = '<!-- agent-team-playbook:start -->'
@@ -229,7 +165,7 @@ async function runGlobalMode(opts) {
229
165
  const coreText = await readFile(path.join(SOURCE_ROOT, 'AGENTS.md'), 'utf8')
230
166
  const block = managedBlock(destDir, opts.inlineCore, coreText)
231
167
 
232
- const rels = [ROOT_FILE, ...(await walk(ROOT_DIR))]
168
+ const rels = [CORE_FILE, ...(await listFiles(SOURCE_ROOT, DOCS_DIR))]
233
169
  console.log(C.bold('全局安装计划'))
234
170
  console.log(C.dim(` 区块模式:${opts.inlineCore ? '内联核心全文(每轮真常驻)' : '指针(默认,agent 需先读一次文件)'}`))
235
171
  console.log(` 复制 ${rels.length} 个文件 → ${destDir}`)
@@ -308,9 +244,7 @@ async function main() {
308
244
  console.error(C.red(`✗ 找不到包内 playbook 目录:${SOURCE_ROOT}`))
309
245
  process.exit(1)
310
246
  }
311
- if (opts.global) {
312
- return runGlobalMode(opts)
313
- }
247
+ if (opts.global) return runGlobalMode(opts)
314
248
 
315
249
  if (!existsSync(opts.dir)) {
316
250
  console.error(C.red(`✗ 目标目录不存在:${opts.dir}`))
@@ -320,86 +254,73 @@ async function main() {
320
254
  console.error(C.red(`✗ --dir 不是目录:${opts.dir}`))
321
255
  process.exit(1)
322
256
  }
323
-
324
- // ── 1. 组装安装单元:核心与分册是一个整体,必须同进同退 ─────────────
325
- const docRels = await walk(ROOT_DIR)
326
- if (docRels.length === 0) {
327
- 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)} 为空或不存在`))
328
259
  process.exit(1)
329
260
  }
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
- }
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
347
271
  }
348
272
 
349
- if (conflicts.size === 0) {
273
+ if (conflicts.length === 0) {
350
274
  console.log(C.green('✓ 目标目录没有同名内容,直接安装(核心 + 分册一起)。'))
351
275
  } else {
352
276
  console.log(C.yellow('⚠ 检测到冲突(核心与分册必须一起装,所以下面整体决策):'))
353
- for (const [key, info] of conflicts) {
354
- console.log(` · ${C.bold(key)} —— ${[...info.reasons].join(';')},涉及 ${info.files.length} 个文件`)
277
+ for (const [unit, info] of byUnit) {
278
+ console.log(` · ${C.bold(unit)} —— ${[...info.reasons].join(';')},涉及 ${info.count} 个文件`)
355
279
  for (const target of info.targets) console.log(C.dim(` 已有:${path.relative(opts.dir, target)}`))
356
280
  }
357
281
  }
358
282
 
359
- // ── 3. 决策(只有"整体"的选项,不存在装一半) ──────────────────────
360
- const renames = [] // 我们这侧的改名(会同步改写引用)
361
- const existingRenames = [] // 已有项改名备份
283
+ // ── 2. 决策 ────────────────────────────────────────────────────────
284
+ const renames = []
362
285
  const defaultSuffix = `.bak-${new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)}`
286
+ let onConflict = 'proceed'
287
+ let backupAllConflicts = false
288
+ let backupSuffix
363
289
  let install = true
364
290
  const interactive = stdin.isTTY && stdout.isTTY
365
291
 
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
- // 非交互显式改名:只要每个冲突单元都被覆盖,就不再提问
292
+ // 非交互显式改名
375
293
  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) }
294
+ if (!/^[^/\\]+$/.test(opts.renameCore) || opts.renameCore === CORE_FILE) {
295
+ console.error(C.red('✗ --rename-core 非法(不能含路径分隔符,也不能与原名相同)'))
296
+ process.exit(1)
297
+ }
378
298
  if (existsSync(path.join(opts.dir, opts.renameCore))) {
379
- console.error(C.red(`✗ --rename-core 目标已存在:${opts.renameCore}`)); process.exit(1)
299
+ console.error(C.red(`✗ --rename-core 目标已存在:${opts.renameCore}`))
300
+ process.exit(1)
380
301
  }
381
- renames.push({ from: ROOT_FILE, to: opts.renameCore })
302
+ renames.push({ from: CORE_FILE, to: opts.renameCore })
382
303
  }
383
304
  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) }
305
+ if (!/^[^/\\]+$/.test(opts.renameDocs) || opts.renameDocs === DOCS_DIR) {
306
+ console.error(C.red('✗ --rename-docs 非法(不能含路径分隔符,也不能与原名相同)'))
307
+ process.exit(1)
308
+ }
386
309
  if (existsSync(path.join(opts.dir, opts.renameDocs))) {
387
- console.error(C.red(`✗ --rename-docs 目标已存在:${opts.renameDocs}`)); process.exit(1)
310
+ console.error(C.red(`✗ --rename-docs 目标已存在:${opts.renameDocs}`))
311
+ process.exit(1)
388
312
  }
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}/(原路径未冲突,仍按你的要求改名)`))
313
+ renames.push({ from: `${DOCS_DIR}/`, to: `${opts.renameDocs}/` })
398
314
  }
399
- if (conflicts.size > 0 && unresolved.length === 0) {
400
- console.log(C.dim(` 已按 --rename-* 处理全部冲突:${renames.map((r) => `${r.from} → ${r.to}`).join(',')}`))
315
+ if (renames.length > 0) {
316
+ console.log(C.dim(` 按 --rename-* 处理:${renames.map((r) => `${r.from} → ${r.to}`).join(',')}`))
401
317
  }
402
318
 
319
+ // 未被改名覆盖的冲突才需要决策
320
+ const unresolved = conflicts.filter(
321
+ (c) => !renames.some((r) => (c.unit === CORE_FILE ? r.from === CORE_FILE : r.from === `${DOCS_DIR}/`)),
322
+ )
323
+
403
324
  if (unresolved.length > 0) {
404
325
  if (opts.force) {
405
326
  console.log(C.dim(' --force:覆盖已有内容'))
@@ -407,7 +328,8 @@ async function main() {
407
328
  install = false
408
329
  console.log(C.dim(' --skip-conflicts:整体跳过(不会只装一半)'))
409
330
  } else if (opts.backupExisting) {
410
- backupAll(defaultSuffix)
331
+ backupAllConflicts = true
332
+ backupSuffix = defaultSuffix
411
333
  console.log(C.dim(` --backup-existing:已有冲突项改名为 *${defaultSuffix} 后安装`))
412
334
  } else if (!interactive) {
413
335
  console.error(C.red('\n✗ 非交互环境下检测到冲突,已中止(不会静默覆盖,也不会只装一半)。'))
@@ -432,20 +354,20 @@ async function main() {
432
354
  console.error(C.red(' 后缀只能含字母数字点下划线横线,已中止。'))
433
355
  process.exit(1)
434
356
  }
435
- backupAll(suffix)
357
+ backupAllConflicts = true
358
+ backupSuffix = suffix
436
359
  } 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
360
+ for (const unit of new Set(unresolved.map((c) => c.unit))) {
361
+ const suggestion = unit === DOCS_DIR ? 'docs-playbook' : 'AGENTS.team.md'
362
+ const raw = (await rl.question(` ${unit} 的新名字(默认 ${suggestion})> `)).trim() || suggestion
441
363
  const clean = raw.replace(/[/\\]/g, '-')
442
- if (clean === path.basename(key) || clean === '') {
364
+ if (clean === path.basename(unit) || clean === '') {
443
365
  console.error(C.red(' 名字未变化,已中止。'))
444
366
  process.exit(1)
445
367
  }
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},文档内引用同步改写`))
368
+ if (unit === DOCS_DIR) renames.push({ from: `${unit}/`, to: `${clean}/` })
369
+ else renames.push({ from: unit, to: clean })
370
+ console.log(C.dim(` → ${unit} 将安装为 ${clean},文档内引用同步改写`))
449
371
  }
450
372
  } else if (answer === 's') {
451
373
  install = false
@@ -464,146 +386,39 @@ async function main() {
464
386
  return
465
387
  }
466
388
 
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
- }
481
- }
482
-
483
- const refRenames = renames.map(({ from, to }) => ({ from, to }))
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(',')}`))
489
- if (existingRenames.length > 0) {
490
- console.log(C.dim(`已有项改名:${existingRenames.map((r) => `${path.relative(opts.dir, r.from)} → ${path.relative(opts.dir, r.to)}`).join(',')}`))
491
- }
389
+ // ── 3. 预览 ────────────────────────────────────────────────────────
390
+ const preview = renames.length > 0 ? `(改名:${renames.map((r) => `${r.from} → ${r.to}`).join(',')})` : ''
391
+ console.log(`\n${C.bold('安装计划')}${opts.dryRun ? C.dim('(--dry-run,不会写入)') : ''}${C.dim(preview)}`)
392
+ console.log(C.dim(` ${CORE_FILE} + ${DOCS_DIR}/ 作为整体一起安装;冲突策略:${onConflict}${backupSuffix ? `(后缀 ${backupSuffix})` : ''}`))
492
393
 
493
394
  if (opts.dryRun) {
494
395
  console.log(C.dim('\n(dry-run 结束,未写入任何文件)'))
495
396
  return
496
397
  }
497
398
 
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
- }
399
+ // ── 4. 原子安装(暂存 → 提交 → 失败回滚) ────────────────────────
400
+ const result = await installAtomic({
401
+ sourceRoot: SOURCE_ROOT,
402
+ targetDir: opts.dir,
403
+ onConflict,
404
+ renames,
405
+ backupTargets: backupAllConflicts ? conflicts.map((c) => c.target) : [],
406
+ backupSuffix,
407
+ })
526
408
 
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) {
543
- await mkdir(path.dirname(r.to), { recursive: true })
544
- await rename(r.from, r.to)
545
- doneBackups.push(r)
546
- }
547
-
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
- }
560
- }
561
-
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
- }
585
- }
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('核心与分册没有同时落地')
409
+ if (!result.ok) {
410
+ if (result.code === 'conflict') {
411
+ console.error(C.red(`\n✗ 失败:${result.message}`))
412
+ process.exit(1)
596
413
  }
597
- } catch (error) {
598
- console.error(C.red(`\n✗ 安装失败,正在回滚:${error.message}`))
599
- await rollback()
600
- console.error(C.red(' 已回滚到安装前状态,未留下半成品。'))
414
+ console.error(C.red(`\n✗ 安装失败,已回滚到安装前状态:${result.message}`))
601
415
  process.exit(1)
602
416
  }
603
417
 
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(',')}`))
418
+ console.log(C.green(`\n✓ 完成:${result.installed.length} 个文件已原子安装到 ${opts.dir}`))
419
+ if (result.backups.length > 0) {
420
+ console.log(C.yellow(` 你的原文件已保留为:${result.backups.map((b) => path.relative(opts.dir, b.to)).join(',')}`))
421
+ }
607
422
  console.log(C.dim(' 提示:若项目已有自己的协作规则,建议把它们合并进新的 AGENTS.md,而不是两份并存。'))
608
423
  }
609
424
 
package/client.js ADDED
@@ -0,0 +1,167 @@
1
+ /**
2
+ * dsh-agent-team-playbook — 浏览器半身(Step 1:只读面板)
3
+ *
4
+ * 形态照抄官方内置插件(如 @deepseek-ai/dsh-client-ui-open-in-app):
5
+ * 手写 window.__ModuleLoader__.load({ id, factory }),无构建步骤,
6
+ * require 由 shell 提供(react / primitives / slots …)。
7
+ *
8
+ * 本步只做**只读**面板:
9
+ * · 显示当前工作区是否已安装、有无同名冲突
10
+ * · 冲突项可一键复制建议命令(真正的写入仍由用户执行 /atp apply,可见可审计)
11
+ * 不做任何写操作,也不直接调用命令。
12
+ */
13
+ window.__ModuleLoader__.load({
14
+ id: 'dsh-agent-team-playbook',
15
+ factory: (require) => {
16
+ const module = { exports: {} }
17
+ const exports = module.exports
18
+
19
+ const React = require('react')
20
+ const primitives = require('@deepseek-ai/dsh-client-ui-primitives')
21
+
22
+ const h = React.createElement
23
+ const { useCallback, useEffect, useMemo, useState } = React
24
+
25
+ const NAME = 'dsh-agent-team-playbook'
26
+ const API = '/api/agent-team-playbook/status'
27
+ const Button = primitives?.Button
28
+
29
+ /** 读一次状态;cwd 为空时只验证连通性。 */
30
+ async function fetchStatus(cwd) {
31
+ const url = cwd ? `${API}?cwd=${encodeURIComponent(cwd)}` : API
32
+ const res = await fetch(url, { credentials: 'same-origin', headers: { accept: 'application/json' } })
33
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
34
+ return res.json()
35
+ }
36
+
37
+ /** 取"当前正在看的会话"的 cwd(客户端 sessions 快照里就有)。 */
38
+ function currentCwd(ctx) {
39
+ try {
40
+ const rows = ctx?.sessions?.list?.getSnapshot?.()?.byId ?? {}
41
+ const list = Object.values(rows)
42
+ const active = list.find((row) => (row?.retainedBy?.mainView ?? 0) > 0) ?? list.find((row) => typeof row?.cwd === 'string')
43
+ return typeof active?.cwd === 'string' ? active.cwd : undefined
44
+ } catch {
45
+ return undefined
46
+ }
47
+ }
48
+
49
+ /** 一行小字 + 值。 */
50
+ function Row({ label, children }) {
51
+ return h(
52
+ 'div',
53
+ { style: { display: 'flex', gap: 8, alignItems: 'baseline', margin: '2px 0' } },
54
+ h('span', { style: { opacity: 0.65, minWidth: 72 } }, label),
55
+ h('span', null, children),
56
+ )
57
+ }
58
+
59
+ function LinkButton({ onClick, children }) {
60
+ if (typeof Button === 'function') return h(Button, { onClick, variant: 'secondary' }, children)
61
+ return h('button', { type: 'button', onClick }, children)
62
+ }
63
+
64
+ function Panel() {
65
+ const [state, setState] = useState({ phase: 'loading' })
66
+ const [copied, setCopied] = useState('')
67
+
68
+ const refresh = useCallback(async () => {
69
+ setState({ phase: 'loading' })
70
+ try {
71
+ const cwd = currentCwd(Panel.ctx)
72
+ const data = await fetchStatus(cwd)
73
+ setState({ phase: 'ready', data, cwd })
74
+ } catch (error) {
75
+ setState({ phase: 'error', message: String(error?.message ?? error) })
76
+ }
77
+ }, [])
78
+
79
+ useEffect(() => {
80
+ void refresh()
81
+ }, [refresh])
82
+
83
+ const conflicts = state.phase === 'ready' ? state.data?.conflicts ?? [] : []
84
+
85
+ const suggestion = useMemo(() => {
86
+ if (conflicts.length === 0) return ''
87
+ return `/atp apply ${conflicts.map((_, i) => `${i + 1}=覆盖`).join(' ')}`
88
+ }, [conflicts])
89
+
90
+ const copy = useCallback(async (text) => {
91
+ try {
92
+ await navigator.clipboard.writeText(text)
93
+ setCopied(text)
94
+ setTimeout(() => setCopied(''), 1500)
95
+ } catch {
96
+ setCopied('')
97
+ }
98
+ }, [])
99
+
100
+ const children = []
101
+ children.push(h('div', { key: 'title', style: { fontWeight: 600, marginBottom: 4 } }, '多智能体协作规程(agent-team-playbook)'))
102
+
103
+ if (state.phase === 'loading') {
104
+ children.push(h(Row, { key: 'loading', label: '状态' }, '检测中…'))
105
+ } else if (state.phase === 'error') {
106
+ children.push(h(Row, { key: 'err', label: '状态' }, `无法连接:${state.message}`))
107
+ } else {
108
+ const d = state.data ?? {}
109
+ children.push(h(Row, { key: 'conn', label: '接口' }, d.connected ? '已连通' : '未连通'))
110
+ children.push(h(Row, { key: 'cwd', label: '工作区' }, d.cwd ?? '(未取到当前会话目录)'))
111
+ children.push(
112
+ h(Row, { key: 'inst', label: '安装状态' }, d.installed ? '已安装(AGENTS.md + docs/ 都在)' : '未安装'),
113
+ )
114
+ if (conflicts.length > 0) {
115
+ children.push(
116
+ h('div', { key: 'conf', style: { marginTop: 8, marginBottom: 4, color: 'var(--dsh-warning, #b8862b)' } },
117
+ `检测到 ${conflicts.length} 处同名内容(不会被自动覆盖):`),
118
+ )
119
+ conflicts.forEach((c, i) => {
120
+ children.push(
121
+ h('div', { key: `c${i}`, style: { paddingLeft: 12, margin: '2px 0' } },
122
+ `${i + 1}. ${c.rel} — ${c.reason}`),
123
+ )
124
+ })
125
+ children.push(
126
+ h('div', { key: 'sug', style: { marginTop: 8 } },
127
+ h('div', { style: { opacity: 0.65, marginBottom: 4 } }, '逐项决定后执行(可改 覆盖→备份 / 改名:新名):'),
128
+ h('code', { style: { display: 'block', padding: 6, borderRadius: 6, background: 'rgba(127,127,127,0.12)' } }, suggestion),
129
+ h('div', { style: { marginTop: 6 } },
130
+ h(LinkButton, { onClick: () => void copy(suggestion) }, copied === suggestion ? '已复制 ✓' : '复制命令')),
131
+ ),
132
+ )
133
+ } else if (d.installed) {
134
+ children.push(h('div', { key: 'ok', style: { marginTop: 8, opacity: 0.8 } }, '没有同名冲突。'))
135
+ }
136
+ }
137
+
138
+ children.push(
139
+ h('div', { key: 'actions', style: { marginTop: 10, display: 'flex', gap: 8 } },
140
+ h(LinkButton, { onClick: () => void refresh() }, '重新检测'),
141
+ h(LinkButton, { onClick: () => void copy('/atp install') }, copied === '/atp install' ? '已复制 ✓' : '复制 /atp install')),
142
+ )
143
+
144
+ children.push(
145
+ h('div', { key: 'hint', style: { marginTop: 10, opacity: 0.6, fontSize: 12 } },
146
+ '面板只读:不会修改你的文件。安装/覆盖/改名仍通过 /atp install 与 /atp apply 执行(可见、可审计)。'),
147
+ )
148
+
149
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 2 } }, children)
150
+ }
151
+
152
+ function apply(ctx) {
153
+ Panel.ctx = ctx
154
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
155
+ name: 'settings.section',
156
+ id: 'agent-team-playbook',
157
+ order: 36,
158
+ label: () => '协作规程',
159
+ }, () => h(Panel, null)))
160
+ }
161
+
162
+ exports.apply = apply
163
+ exports.inject = ['slots', 'sessions']
164
+ exports.name = NAME
165
+ return module.exports
166
+ },
167
+ })