dsh-agent-team-playbook 1.24.0 → 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 +2 -0
- package/bin/cli.mjs +77 -264
- package/lib/index.js +143 -68
- package/lib/install.js +252 -0
- package/package.json +1 -1
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
|
|
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 = [
|
|
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,72 @@ async function main() {
|
|
|
320
254
|
console.error(C.red(`✗ --dir 不是目录:${opts.dir}`))
|
|
321
255
|
process.exit(1)
|
|
322
256
|
}
|
|
323
|
-
|
|
324
|
-
|
|
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
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
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.
|
|
273
|
+
if (conflicts.length === 0) {
|
|
350
274
|
console.log(C.green('✓ 目标目录没有同名内容,直接安装(核心 + 分册一起)。'))
|
|
351
275
|
} else {
|
|
352
276
|
console.log(C.yellow('⚠ 检测到冲突(核心与分册必须一起装,所以下面整体决策):'))
|
|
353
|
-
for (const [
|
|
354
|
-
console.log(` · ${C.bold(
|
|
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
|
-
// ──
|
|
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 = 'overwrite'
|
|
287
|
+
let backupSuffix
|
|
363
288
|
let install = true
|
|
364
289
|
const interactive = stdin.isTTY && stdout.isTTY
|
|
365
290
|
|
|
366
|
-
|
|
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
|
-
// 非交互显式改名:只要每个冲突单元都被覆盖,就不再提问
|
|
291
|
+
// 非交互显式改名
|
|
375
292
|
if (opts.renameCore !== undefined) {
|
|
376
|
-
if (!/^[^/\\]+$/.test(opts.renameCore)
|
|
377
|
-
|
|
293
|
+
if (!/^[^/\\]+$/.test(opts.renameCore) || opts.renameCore === CORE_FILE) {
|
|
294
|
+
console.error(C.red('✗ --rename-core 非法(不能含路径分隔符,也不能与原名相同)'))
|
|
295
|
+
process.exit(1)
|
|
296
|
+
}
|
|
378
297
|
if (existsSync(path.join(opts.dir, opts.renameCore))) {
|
|
379
|
-
console.error(C.red(`✗ --rename-core 目标已存在:${opts.renameCore}`))
|
|
298
|
+
console.error(C.red(`✗ --rename-core 目标已存在:${opts.renameCore}`))
|
|
299
|
+
process.exit(1)
|
|
380
300
|
}
|
|
381
|
-
renames.push({ from:
|
|
301
|
+
renames.push({ from: CORE_FILE, to: opts.renameCore })
|
|
382
302
|
}
|
|
383
303
|
if (opts.renameDocs !== undefined) {
|
|
384
|
-
if (!/^[^/\\]+$/.test(opts.renameDocs)
|
|
385
|
-
|
|
304
|
+
if (!/^[^/\\]+$/.test(opts.renameDocs) || opts.renameDocs === DOCS_DIR) {
|
|
305
|
+
console.error(C.red('✗ --rename-docs 非法(不能含路径分隔符,也不能与原名相同)'))
|
|
306
|
+
process.exit(1)
|
|
307
|
+
}
|
|
386
308
|
if (existsSync(path.join(opts.dir, opts.renameDocs))) {
|
|
387
|
-
console.error(C.red(`✗ --rename-docs 目标已存在:${opts.renameDocs}`))
|
|
309
|
+
console.error(C.red(`✗ --rename-docs 目标已存在:${opts.renameDocs}`))
|
|
310
|
+
process.exit(1)
|
|
388
311
|
}
|
|
389
|
-
renames.push({ from: `${
|
|
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}/(原路径未冲突,仍按你的要求改名)`))
|
|
312
|
+
renames.push({ from: `${DOCS_DIR}/`, to: `${opts.renameDocs}/` })
|
|
398
313
|
}
|
|
399
|
-
if (
|
|
400
|
-
console.log(C.dim(`
|
|
314
|
+
if (renames.length > 0) {
|
|
315
|
+
console.log(C.dim(` 按 --rename-* 处理:${renames.map((r) => `${r.from} → ${r.to}`).join(',')}`))
|
|
401
316
|
}
|
|
402
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
|
+
|
|
403
323
|
if (unresolved.length > 0) {
|
|
404
324
|
if (opts.force) {
|
|
405
325
|
console.log(C.dim(' --force:覆盖已有内容'))
|
|
@@ -407,7 +327,8 @@ async function main() {
|
|
|
407
327
|
install = false
|
|
408
328
|
console.log(C.dim(' --skip-conflicts:整体跳过(不会只装一半)'))
|
|
409
329
|
} else if (opts.backupExisting) {
|
|
410
|
-
|
|
330
|
+
onConflict = 'backup'
|
|
331
|
+
backupSuffix = defaultSuffix
|
|
411
332
|
console.log(C.dim(` --backup-existing:已有冲突项改名为 *${defaultSuffix} 后安装`))
|
|
412
333
|
} else if (!interactive) {
|
|
413
334
|
console.error(C.red('\n✗ 非交互环境下检测到冲突,已中止(不会静默覆盖,也不会只装一半)。'))
|
|
@@ -432,20 +353,20 @@ async function main() {
|
|
|
432
353
|
console.error(C.red(' 后缀只能含字母数字点下划线横线,已中止。'))
|
|
433
354
|
process.exit(1)
|
|
434
355
|
}
|
|
435
|
-
|
|
356
|
+
onConflict = 'backup'
|
|
357
|
+
backupSuffix = suffix
|
|
436
358
|
} else if (answer === 'r') {
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
const
|
|
440
|
-
const raw = (await rl.question(` ${key} 的新名字(默认 ${suggestion})> `)).trim() || suggestion
|
|
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
|
|
441
362
|
const clean = raw.replace(/[/\\]/g, '-')
|
|
442
|
-
if (clean === path.basename(
|
|
363
|
+
if (clean === path.basename(unit) || clean === '') {
|
|
443
364
|
console.error(C.red(' 名字未变化,已中止。'))
|
|
444
365
|
process.exit(1)
|
|
445
366
|
}
|
|
446
|
-
if (
|
|
447
|
-
else renames.push({ from:
|
|
448
|
-
console.log(C.dim(` → ${
|
|
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},文档内引用同步改写`))
|
|
449
370
|
}
|
|
450
371
|
} else if (answer === 's') {
|
|
451
372
|
install = false
|
|
@@ -464,146 +385,38 @@ async function main() {
|
|
|
464
385
|
return
|
|
465
386
|
}
|
|
466
387
|
|
|
467
|
-
// ──
|
|
468
|
-
const
|
|
469
|
-
|
|
470
|
-
|
|
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
|
-
}
|
|
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})` : ''}`))
|
|
492
392
|
|
|
493
393
|
if (opts.dryRun) {
|
|
494
394
|
console.log(C.dim('\n(dry-run 结束,未写入任何文件)'))
|
|
495
395
|
return
|
|
496
396
|
}
|
|
497
397
|
|
|
498
|
-
// ──
|
|
499
|
-
const
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
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
|
-
}
|
|
398
|
+
// ── 4. 原子安装(暂存 → 提交 → 失败回滚) ────────────────────────
|
|
399
|
+
const result = await installAtomic({
|
|
400
|
+
sourceRoot: SOURCE_ROOT,
|
|
401
|
+
targetDir: opts.dir,
|
|
402
|
+
onConflict,
|
|
403
|
+
renames,
|
|
404
|
+
backupSuffix,
|
|
405
|
+
})
|
|
526
406
|
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
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('核心与分册没有同时落地')
|
|
407
|
+
if (!result.ok) {
|
|
408
|
+
if (result.code === 'conflict') {
|
|
409
|
+
console.error(C.red(`\n✗ 失败:${result.message}`))
|
|
410
|
+
process.exit(1)
|
|
596
411
|
}
|
|
597
|
-
|
|
598
|
-
console.error(C.red(`\n✗ 安装失败,正在回滚:${error.message}`))
|
|
599
|
-
await rollback()
|
|
600
|
-
console.error(C.red(' 已回滚到安装前状态,未留下半成品。'))
|
|
412
|
+
console.error(C.red(`\n✗ 安装失败,已回滚到安装前状态:${result.message}`))
|
|
601
413
|
process.exit(1)
|
|
602
414
|
}
|
|
603
415
|
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
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(',')}`))
|
|
419
|
+
}
|
|
607
420
|
console.log(C.dim(' 提示:若项目已有自己的协作规则,建议把它们合并进新的 AGENTS.md,而不是两份并存。'))
|
|
608
421
|
}
|
|
609
422
|
|
package/lib/index.js
CHANGED
|
@@ -1,61 +1,68 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* dsh-agent-team-playbook — DSH 命令插件(Host 半身)
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* /atp
|
|
6
|
-
* /atp core
|
|
7
|
-
* /atp paths
|
|
8
|
-
* /atp
|
|
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
|
|
11
|
-
* 用
|
|
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
|
-
/**
|
|
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
|
|
40
|
-
' paths
|
|
41
|
-
'
|
|
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
|
-
'
|
|
43
|
+
'多智能体协作规程(agent-team-playbook)',
|
|
47
44
|
'',
|
|
48
|
-
'
|
|
45
|
+
'档位:快速 15–30 分钟(单点可逆、自审)|标准 半天(S0–S6、源码级+短测)|严格 1–2 天/子任务(全流程+红队+双重审计)',
|
|
49
46
|
'',
|
|
50
|
-
'
|
|
47
|
+
'动手前:验收标准可判真假?档位定了吗?方案过四问了吗——可行性 / 合理性 / 完整性 / 优越性?',
|
|
51
48
|
'',
|
|
52
|
-
'
|
|
49
|
+
'修复型任务:先调查根因再改,不允许「没复现就动手」。',
|
|
53
50
|
'',
|
|
54
|
-
'
|
|
51
|
+
'完成 = 实现 + 自检 + 证据;审计要全面系统并追到根因,别只修表象。',
|
|
55
52
|
'',
|
|
56
|
-
'
|
|
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 = [
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
}
|
|
79
|
-
|
|
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(''
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
111
|
+
/* 服务不可用 → 返回 null,由调用方拒绝 */
|
|
90
112
|
}
|
|
113
|
+
return null
|
|
91
114
|
}
|
|
92
115
|
|
|
93
|
-
/**
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
return
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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${
|
|
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.
|
|
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",
|