dsh-ai-collab 0.4.4 → 0.5.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/index.js CHANGED
@@ -9,13 +9,21 @@
9
9
  * 2) 'tools' 是否就是 ctx.tools 的注入名(当前按官方示例 inject = ['tools'])。
10
10
  * 插件异常会影响 Host 启动,所以首次安装请用 --patch 隔离验证,见 README。
11
11
  */
12
- import { existsSync, mkdirSync, appendFileSync, readFileSync, writeFileSync, readdirSync, renameSync, statSync, rmSync } from 'node:fs'
12
+ import { existsSync, mkdirSync, appendFileSync, readFileSync, readdirSync, renameSync, statSync, rmSync, writeFileSync } from 'node:fs'
13
13
  import { join, dirname } from 'node:path'
14
14
  import { fileURLToPath, pathToFileURL } from 'node:url'
15
15
  import { homedir } from 'node:os'
16
16
  import { spawn } from 'node:child_process'
17
17
  import { normalizeConfig } from './lib/config.js'
18
18
  import { writeTasks } from './lib/tasks.js'
19
+ import { writeFileAtomic, readText, backupFile } from './lib/atomic.js'
20
+ import { withLock } from './lib/lock.js'
21
+ import {
22
+ addGlobalModule, auditProject, listProject, loadGlobal, loadProject, migrateGlobal,
23
+ normaliseRegistry, projectDir, projectRegistryPath, projectRulesDir, removeGlobalModule,
24
+ renderGlobalFile, renderProjectSection, setGlobalEnabled, ID_RE,
25
+ } from './lib/disciplines.js'
26
+ import { buildHandoff, inheritPrompt, writeSessionBoot } from './lib/handoff.js'
19
27
 
20
28
  export const name = 'ai-collab'
21
29
  // Only `tools` is required. `workingDirectory` is used when present
@@ -183,22 +191,28 @@ function appendRecord(root, input) {
183
191
  const errors = recordErrors(rec, 0)
184
192
  if (errors.length > 0) throw new Error(`记录校验失败,未写入: ${errors.join('; ')}`)
185
193
 
186
- mkdirSync(aiDir(root), { recursive: true })
187
- appendFileSync(logPath(root), JSON.stringify(rec) + '\n', 'utf8')
188
-
189
- const st = readJson(statusPath(root))
190
- if (st) {
191
- st.last_log_ts = rec.ts
192
- st.last_log_id = rec.id
193
- st.updated_at = nowIso()
194
- if (rec.next) st.next = [rec.next]
195
- if (rec.status === 'blocked' || rec.status === 'failed') {
196
- const list = Array.isArray(st.blockers) ? st.blockers : []
197
- st.blockers = [...new Set([rec.issue, ...list].filter(Boolean))]
194
+ // One writer at a time per project: append + status read-modify-write must be
195
+ // a unit, otherwise two sessions overwrite each other's status fields.
196
+ const lockPath = join(aiDir(root), '.log.lock')
197
+ return withLock(lockPath, () => {
198
+ mkdirSync(aiDir(root), { recursive: true })
199
+ appendFileSync(logPath(root), JSON.stringify(rec) + '\n', 'utf8')
200
+
201
+ const st = readJson(statusPath(root))
202
+ if (st) {
203
+ st.rev = Number.isInteger(st.rev) ? st.rev + 1 : 1
204
+ st.last_log_ts = rec.ts
205
+ st.last_log_id = rec.id
206
+ st.updated_at = nowIso()
207
+ if (rec.next) st.next = [rec.next]
208
+ if (rec.status === 'blocked' || rec.status === 'failed') {
209
+ const list = Array.isArray(st.blockers) ? st.blockers : []
210
+ st.blockers = [...new Set([rec.issue, ...list].filter(Boolean))]
211
+ }
212
+ writeFileAtomic(statusPath(root), JSON.stringify(st, null, 2) + '\n')
198
213
  }
199
- try { writeFileSync(statusPath(root), JSON.stringify(st, null, 2) + '\n', 'utf8') } catch { /* 状态刷新失败不影响日志 */ }
200
- }
201
- return rec
214
+ return rec
215
+ })
202
216
  }
203
217
 
204
218
  function spawnEnsure(root, config, extraArgs = []) {
@@ -268,7 +282,7 @@ function maybeRefreshBoard(root) {
268
282
  function refreshTasks(root) {
269
283
  try {
270
284
  if (!existsSync(join(root, '.ai', 'tasks-enabled'))) return
271
- const { written, count } = writeTasks(root, nowIso())
285
+ const { written, count } = withLock(join(root, '.ai', '.tasks.lock'), () => writeTasks(root, nowIso()))
272
286
  if (!written) return
273
287
  if (count === 0) appendLog('ai-collab-tasks.log', `root=${root} count=0`)
274
288
  } catch (error) {
@@ -276,6 +290,19 @@ function refreshTasks(root) {
276
290
  }
277
291
  }
278
292
 
293
+ /**
294
+ * Rebuild `.ai\SESSION_BOOT.md` after every record. It is derived data
295
+ * (status + last N records), so a stale boot file is worse than a small write.
296
+ */
297
+ function refreshSessionBoot(root) {
298
+ try {
299
+ if (!existsSync(join(root, '.ai'))) return
300
+ writeSessionBoot(root, { maxTail: 10 })
301
+ } catch (error) {
302
+ appendLog('ai-collab-handoff.log', `root=${root} throw ${error?.message || error}`)
303
+ }
304
+ }
305
+
279
306
  // ---------------------------------------------------------------- plugin
280
307
 
281
308
  export function apply(ctx, config = {}) {
@@ -311,6 +338,11 @@ export function apply(ctx, config = {}) {
311
338
  const result = spawnEnsure(root, opts)
312
339
  if (result.done) {
313
340
  const finished = await result.done
341
+ if (finished.ok) {
342
+ try { writeSessionBoot(root, { maxTail: opts.maxTail }) } catch (error) {
343
+ appendLog('ai-collab-handoff.log', `autoInit root=${root} throw ${error?.message || error}`)
344
+ }
345
+ }
314
346
  ctx.logger?.info?.('ai-collab autoInit', { root, ok: finished.ok, parsed: parseEnsureOutput(finished.out) })
315
347
  }
316
348
  } catch (error) {
@@ -387,6 +419,19 @@ function registerTools(ctx, opts, defineTool, spec) {
387
419
  // DSH 契约:output.render 必须返回内容块数组;schema 用值 schema DSL 的 json 节点
388
420
  const output = { schema: { type: 'json' }, render: (args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }] }
389
421
 
422
+ /** Re-render AGENTS.md §8 (and the boot file) after a discipline change. */
423
+ const resyncProject = async (root) => {
424
+ if (!SCAFFOLD_SUPPORTED) return { started: false, reason: `unsupported-platform: ${process.platform}` }
425
+ const handle = spawnEnsure(root, opts, ['-Force'])
426
+ if (!handle.started) return { started: false, reason: handle.reason }
427
+ const finished = await handle.done
428
+ let boot = null
429
+ try { boot = writeSessionBoot(root, { maxTail: opts.maxTail }) } catch (error) {
430
+ boot = { ok: false, error: String(error?.message || error) }
431
+ }
432
+ return { started: true, exit: finished.code ?? null, ok: finished.ok === true, result: parseEnsureOutput(finished.out), boot }
433
+ }
434
+
390
435
  registered.push('ai_status')
391
436
  ctx.tools.register(defineTool({
392
437
  name: 'ai_status',
@@ -426,6 +471,7 @@ function registerTools(ctx, opts, defineTool, spec) {
426
471
  const r = await rootOf(exec)
427
472
  const rec = appendRecord(r, args)
428
473
  refreshTasks(r)
474
+ refreshSessionBoot(r)
429
475
  maybeRefreshBoard(r)
430
476
  return rec
431
477
  }
@@ -455,6 +501,11 @@ function registerTools(ctx, opts, defineTool, spec) {
455
501
  }
456
502
  })
457
503
  if (!readJson(statusPath(r))) errors.push('status.json 缺失或不可解析')
504
+ try {
505
+ for (const drift of auditProject(r, readText(join(r, 'AGENTS.md')))) errors.push(`§8 漂移: ${drift}`)
506
+ } catch (error) {
507
+ errors.push(`§8 审计失败: ${error?.message || error}`)
508
+ }
458
509
  return { root: r, records: readLines(logPath(r)).length, errors }
459
510
  }
460
511
  }))
@@ -512,6 +563,140 @@ function registerTools(ctx, opts, defineTool, spec) {
512
563
  }
513
564
  if (finished.err) payload.stderr = finished.err.slice(0, 500)
514
565
  if (finished.error) payload.error = finished.error
566
+ if (finished.ok) {
567
+ try { payload.boot = writeSessionBoot(target, { maxTail: opts.maxTail }) } catch (error) {
568
+ payload.boot = { ok: false, error: String(error?.message || error) }
569
+ }
570
+ }
571
+ return payload
572
+ }
573
+ }))
574
+
575
+ registered.push('ai_discipline')
576
+ ctx.tools.register(defineTool({
577
+ name: 'ai_discipline',
578
+ description: '纪律清单:列出/新增/启用/停用/删除项目纪律(渲染进 AGENTS.md §8),或管理全局纪律模块(重写 $DSH_HOME\\AGENTS.md,自动备份)。',
579
+ parameters: {
580
+ action: {
581
+ type: 'string', required: true,
582
+ enum: [
583
+ 'list', 'add', 'enable', 'disable', 'remove',
584
+ 'global-list', 'global-migrate', 'global-add', 'global-enable', 'global-disable', 'global-remove',
585
+ ],
586
+ description: '项目动作直接改 .ai\\disciplines\\ 并重渲染 §8;global-* 动作改 $DSH_HOME\\disciplines\\ 并重写全局 AGENTS.md。',
587
+ },
588
+ id: { type: 'string', description: '纪律 id(2–41 位小写字母/数字/连字符)' },
589
+ title: { type: 'string', description: 'add / global-add 的标题' },
590
+ body: { type: 'string', description: 'add / global-add 的规则正文(Markdown)' },
591
+ priority: { type: 'number', description: '排序权重,越小越靠前' },
592
+ force: { type: 'boolean', description: 'global-migrate 时重建已存在的模块(先备份)' },
593
+ root: { type: 'string', description: '目标工作区,缺省为会话 cwd' },
594
+ },
595
+ output,
596
+ async execute(args, exec) {
597
+ const action = String(args?.action || '')
598
+ const r = args?.root ? String(args.root) : await rootOf(exec)
599
+ const id = String(args?.id || '').trim()
600
+
601
+ if (action === 'list') {
602
+ let counts = null
603
+ try { counts = renderProjectSection(r).counts } catch { /* 注册表不可读时只返回原始列表 */ }
604
+ return { root: r, ...listProject(r), counts }
605
+ }
606
+
607
+ // ---------- project rules ----------
608
+ if (['add', 'enable', 'disable', 'remove'].includes(action)) {
609
+ const registry = normaliseRegistry(readJson(projectRegistryPath(r)) ?? {}, 'project')
610
+ const rules = registry.rules
611
+ let target = null
612
+ if (action === 'add') {
613
+ if (!ID_RE.test(id)) throw new Error('id 必须为 2–41 位小写字母/数字/连字符')
614
+ if (!String(args?.title ?? '').trim()) throw new Error('add 需要 title')
615
+ if (!String(args?.body ?? '').trim()) throw new Error('add 需要 body')
616
+ if (rules.some((x) => x.id === id)) throw new Error(`项目纪律已存在: ${id}`)
617
+ mkdirSync(projectRulesDir(r), { recursive: true })
618
+ writeFileAtomic(join(projectRulesDir(r), `${id}.md`), `${String(args.body).trim()}\n`)
619
+ target = {
620
+ id, title: String(args.title).trim(), enabled: true,
621
+ priority: Number.isFinite(Number(args?.priority)) ? Number(args.priority) : rules.length * 10,
622
+ file: `${id}.md`, description: '',
623
+ }
624
+ rules.push(target)
625
+ } else {
626
+ target = rules.find((x) => x.id === id)
627
+ if (!target) throw new Error(`项目纪律不存在: ${id}`)
628
+ if (action === 'remove') {
629
+ const src = join(projectRulesDir(r), target.file)
630
+ if (existsSync(src)) {
631
+ const destDir = join(projectDir(r), '_archive')
632
+ mkdirSync(destDir, { recursive: true })
633
+ renameSync(src, join(destDir, `${id}.${Date.now()}.md`))
634
+ }
635
+ registry.rules = rules.filter((x) => x.id !== id)
636
+ } else {
637
+ target.enabled = action === 'enable'
638
+ }
639
+ }
640
+ writeFileAtomic(projectRegistryPath(r), `${JSON.stringify(registry, null, 2)}\n`)
641
+ const sync = await resyncProject(r)
642
+ return { ok: true, action, id, rule: target, sync }
643
+ }
644
+
645
+ // ---------- global modules ----------
646
+ if (action === 'global-list') {
647
+ const state = loadGlobal()
648
+ return {
649
+ root: r,
650
+ home: state.dir,
651
+ agents: state.agentsPath,
652
+ generated: state.generated,
653
+ modules: (state.modules.length ? state.modules : state.fallback).map((m) => ({ id: m.id, title: m.title, enabled: m.enabled, file: m.file, priority: m.priority, hash: m.hash })),
654
+ }
655
+ }
656
+ if (action === 'global-migrate') {
657
+ return { ok: true, ...migrateGlobal({ force: args?.force === true }) }
658
+ }
659
+ if (action === 'global-add') {
660
+ const module = addGlobalModule({ id, title: args?.title, body: args?.body, priority: args?.priority })
661
+ return { ok: true, module, render: renderGlobalFile() }
662
+ }
663
+ if (action === 'global-enable' || action === 'global-disable') {
664
+ const module = setGlobalEnabled(id, action === 'global-enable')
665
+ return { ok: true, module: { id: module.id, title: module.title, enabled: module.enabled }, render: renderGlobalFile() }
666
+ }
667
+ if (action === 'global-remove') {
668
+ const removed = removeGlobalModule({ id })
669
+ return { ok: true, removed: { id: removed.id, title: removed.title }, render: renderGlobalFile() }
670
+ }
671
+ throw new Error(`未知 action: ${action}`)
672
+ }
673
+ }))
674
+
675
+ registered.push('ai_handoff')
676
+ ctx.tools.register(defineTool({
677
+ name: 'ai_handoff',
678
+ description: '跨会话交接:生成/读取 .ai/SESSION_BOOT.md(接棒提示词,含必读顺序、当前状态、最近记录、纪律清单与继承摘要要求)。',
679
+ parameters: {
680
+ action: { type: 'string', enum: ['read', 'write', 'inherit'], description: 'read 只返回内容;write 重新生成;inherit 生成并返回给新会话的提示语' },
681
+ maxTail: { type: 'number', description: '摘录最近多少条记录(默认 10,最大 50)' },
682
+ root: { type: 'string', description: '目标工作区,缺省为会话 cwd' },
683
+ },
684
+ output,
685
+ async execute(args, exec) {
686
+ const r = args?.root ? String(args.root) : await rootOf(exec)
687
+ const action = String(args?.action || 'read')
688
+ const maxTail = Number.isFinite(Number(args?.maxTail)) ? Number(args.maxTail) : opts.maxTail
689
+ let boot = null
690
+ if (action !== 'read') boot = writeSessionBoot(r, { maxTail })
691
+ const packet = buildHandoff(r, { maxTail })
692
+ const payload = { action, root: r, boot, packet }
693
+ if (action === 'read' || action === 'inherit') {
694
+ const bootPath = join(r, '.ai', 'SESSION_BOOT.md')
695
+ // read 必须返回可用的接棒提示词:文件缺失时先生成一次
696
+ if (!existsSync(bootPath)) boot = writeSessionBoot(r, { maxTail })
697
+ payload.content = readText(bootPath)
698
+ }
699
+ if (action === 'inherit') payload.prompt = inheritPrompt(r)
515
700
  return payload
516
701
  }
517
702
  }))
package/install.ps1 CHANGED
@@ -54,7 +54,39 @@ function ConvertFrom-JsonEscapes([string]$Text) {
54
54
  function Write-Utf8([string]$Path, [string]$Text) {
55
55
  $dir = Split-Path -Parent $Path
56
56
  if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
57
- [System.IO.File]::WriteAllText($Path, ($Text -replace "`r`n", "`n"), $Utf8NoBom)
57
+ $normalized = $Text -replace "`r`n", "`n"
58
+ $tmp = Join-Path $dir ('.' + [System.IO.Path]::GetFileName($Path) + '.tmp-' + [guid]::NewGuid().ToString('N'))
59
+ [System.IO.File]::WriteAllText($tmp, $normalized, $Utf8NoBom)
60
+ for ($i = 0; $i -lt 8; $i++) {
61
+ try {
62
+ if (Test-Path -LiteralPath $Path) {
63
+ [System.IO.File]::Replace($tmp, $Path, [NullString]::Value)
64
+ } else {
65
+ [System.IO.File]::Move($tmp, $Path)
66
+ }
67
+ return
68
+ } catch {
69
+ if ($i -eq 7) {
70
+ Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue
71
+ throw
72
+ }
73
+ Start-Sleep -Milliseconds (30 * ($i + 1))
74
+ }
75
+ }
76
+ }
77
+
78
+ # AGENTS.md 变更前留一份可回滚快照(最多 10 份,位于 .ai\backups\)
79
+ function Backup-Agents([string]$Path) {
80
+ try {
81
+ if (-not (Test-Path -LiteralPath $Path)) { return }
82
+ $backupDir = Join-Path (Join-Path (Split-Path -Parent $Path) '.ai') 'backups'
83
+ New-Item -ItemType Directory -Force -Path $backupDir | Out-Null
84
+ $stamp = (Get-Date).ToString('yyyyMMdd-HHmmss-fff')
85
+ Copy-Item -LiteralPath $Path -Destination (Join-Path $backupDir ("AGENTS.{0}.md" -f $stamp)) -Force
86
+ Get-ChildItem -LiteralPath $backupDir -Filter 'AGENTS.*.md' -File |
87
+ Sort-Object LastWriteTime -Descending | Select-Object -Skip 10 |
88
+ Remove-Item -Force -ErrorAction SilentlyContinue
89
+ } catch { }
58
90
  }
59
91
 
60
92
  # 整理成 2 空格缩进、无多余空格的 JSON
@@ -187,7 +219,68 @@ else {
187
219
  Step '保留: .ai\status.json(已存在)'
188
220
  }
189
221
 
222
+ # 读取纪律注册表,生成 AGENTS.md §8 的清单表与内联规则块。
223
+ # 全局模块:$DSH_HOME\disciplines\(只列表,正文已在全局 AGENTS.md);
224
+ # 项目规则:<root>\.ai\disciplines\rules\(启用才内联,停用只列表)。
225
+ function Get-DisciplineSection([string]$Root) {
226
+ $dshHome = $env:DSH_HOME
227
+ if ([string]::IsNullOrWhiteSpace($dshHome)) { $dshHome = Join-Path $HOME '.dsh' }
228
+ $table = New-Object System.Collections.ArrayList
229
+ [void]$table.Add('| 编号 | 范围 | 纪律 | 状态 | 来源 |')
230
+ [void]$table.Add('|---|---|---|---|---|')
231
+ $rules = New-Object System.Collections.ArrayList
232
+ $count = 0
233
+
234
+ $globalReg = Join-Path $dshHome 'disciplines\disciplines.json'
235
+ if (Test-Path -LiteralPath $globalReg) {
236
+ try { $g = (Read-Utf8 $globalReg) | ConvertFrom-Json } catch { $g = $null }
237
+ foreach ($m in @($g.modules)) {
238
+ if (-not $m -or [string]::IsNullOrWhiteSpace([string]$m.id)) { continue }
239
+ $id = [string]$m.id
240
+ $disp = 'G' + ($id -replace '^g', '')
241
+ $title = ([string]$m.title) -replace '\|', '\|'
242
+ $state = if ($m.enabled -ne $false) { '启用' } else { '停用' }
243
+ $src = if ($m.file) { '$DSH_HOME\disciplines\' + (([string]$m.file) -replace '/', '\') } else { '$DSH_HOME\AGENTS.md' }
244
+ [void]$table.Add(('| {0} | 全局 | {1} | {2} | `{3}` |' -f $disp, $title, $state, $src))
245
+ $count++
246
+ }
247
+ }
248
+
249
+ $projReg = Join-Path $Root '.ai\disciplines\disciplines.json'
250
+ $projRules = Join-Path $Root '.ai\disciplines\rules'
251
+ if (Test-Path -LiteralPath $projReg) {
252
+ try { $p = (Read-Utf8 $projReg) | ConvertFrom-Json } catch { $p = $null }
253
+ foreach ($r in @($p.rules)) {
254
+ if (-not $r -or [string]::IsNullOrWhiteSpace([string]$r.id)) { continue }
255
+ $id = [string]$r.id
256
+ $disp = 'P-' + ($id -replace '^p-', '')
257
+ $title = ([string]$r.title) -replace '\|', '\|'
258
+ $enabled = ($r.enabled -ne $false)
259
+ $state = if ($enabled) { '启用' } else { '停用' }
260
+ $file = if ($r.file) { [string]$r.file } else { "$id.md" }
261
+ $src = '.ai\disciplines\rules\' + ($file -replace '/', '\')
262
+ [void]$table.Add(('| {0} | 项目 | {1} | {2} | `{3}` |' -f $disp, $title, $state, $src))
263
+ if ($enabled) {
264
+ $bodyPath = Join-Path $projRules $file
265
+ if (Test-Path -LiteralPath $bodyPath) {
266
+ $body = (Read-Utf8 $bodyPath).Trim()
267
+ $body = [regex]::Replace($body, '(?s)^#{1,3}\s+.*?\r?\n\r?\n', '')
268
+ [void]$rules.Add(("<!-- dsh-ai-collab:discipline:{0}:start -->`n### {1} · {2}`n`n{3}`n<!-- dsh-ai-collab:discipline:{0}:end -->" -f $id, $disp, $title, $body))
269
+ }
270
+ }
271
+ $count++
272
+ }
273
+ }
274
+
275
+ if ($count -eq 0) { [void]$table.Add('| — | — | (暂无纪律清单) | — | — |') }
276
+ if ($rules.Count -eq 0) { [void]$rules.Add('(暂无启用的项目纪律)') }
277
+ return @{ Table = ($table -join "`n"); Rules = ($rules -join "`n`n") }
278
+ }
279
+
190
280
  # ---------- 2. AGENTS.md ----------
281
+ $discipline = Get-DisciplineSection $ProjectRoot
282
+ $map['DISCIPLINE_TABLE'] = $discipline.Table
283
+ $map['DISCIPLINE_RULES'] = $discipline.Rules
191
284
  $agentsPath = Join-Path $ProjectRoot 'AGENTS.md'
192
285
  $tplAgents = Read-Utf8 (Join-Path $here 'AGENTS.template.md')
193
286
  foreach ($k in $map.Keys) { $tplAgents = $tplAgents.Replace('{{' + $k + '}}', $map[$k]) }
@@ -227,8 +320,9 @@ if (-not $agentsExists) {
227
320
  Step '写入: AGENTS.md'
228
321
  }
229
322
  elseif ($ResetAgents) {
323
+ Backup-Agents $agentsPath
230
324
  Write-Utf8 $agentsPath $tplAgents
231
- Step '写入: AGENTS.md(-ResetAgents:丢弃旧内容,仅按模板重建)'
325
+ Step '写入: AGENTS.md(-ResetAgents:丢弃旧内容,仅按模板重建;旧文件已备份到 .ai\backups\)'
232
326
  }
233
327
  elseif ($agentsGenerated) {
234
328
  # 只替换 generated 区,user 区与其它内容原样保留
@@ -237,8 +331,14 @@ elseif ($agentsGenerated) {
237
331
  $merged = $currentAgents.Substring(0, $oldSpan.Start) +
238
332
  $tplAgents.Substring($newSpan.Start, $newSpan.End - $newSpan.Start) +
239
333
  $currentAgents.Substring($oldSpan.End)
240
- Write-Utf8 $agentsPath $merged
241
- Step '更新: AGENTS.md(仅替换自动区,项目自维护区原样保留)'
334
+ if ($merged -ne $currentAgents) {
335
+ Backup-Agents $agentsPath
336
+ Write-Utf8 $agentsPath $merged
337
+ Step '更新: AGENTS.md(仅替换自动区,项目自维护区原样保留)'
338
+ }
339
+ else {
340
+ Step '保留: AGENTS.md(内容未变化)'
341
+ }
242
342
  }
243
343
  elseif ($ForceAgents) {
244
344
  # 旧格式/手工文件:保留全部旧内容,放进 user 区,绝不删除
@@ -248,8 +348,9 @@ elseif ($ForceAgents) {
248
348
  $composed = $generated + "`n`n" + $uStart + "`n" +
249
349
  "<!-- 以下为原 AGENTS.md 内容,由 -ForceAgents 原样迁入,未做删改 -->`n`n" +
250
350
  $preserved + "`n" + $uEnd + "`n"
351
+ Backup-Agents $agentsPath
251
352
  Write-Utf8 $agentsPath $composed
252
- Step '写入: AGENTS.md(-ForceAgents:自动区重建,旧内容整体迁入项目自维护区)'
353
+ Step '写入: AGENTS.md(-ForceAgents:自动区重建,旧内容整体迁入项目自维护区;旧文件已备份)'
253
354
  }
254
355
  else {
255
356
  $response = Join-Path (Join-Path $ProjectRoot '.ai') 'AGENTS.generated.md'
package/lib/atomic.js ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Atomic file writes and timestamped backups.
3
+ *
4
+ * Why: the plugin updates `status.json`, `TASKS.md`, `AGENTS.md` and the global
5
+ * discipline file while other sessions/tools may read them. A plain
6
+ * `writeFileSync` truncates first, so a reader can observe a half-written file;
7
+ * a crash mid-write loses the previous content. Write to a sibling temp file,
8
+ * fsync it, then rename over the target: readers see either the old or the new
9
+ * file, never a partial one.
10
+ */
11
+ import {
12
+ closeSync, copyFileSync, existsSync, fsyncSync, mkdirSync, openSync,
13
+ readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync,
14
+ } from 'node:fs'
15
+ import { basename, dirname, join } from 'node:path'
16
+
17
+ /** Synchronous sleep that does not need timers (works inside a lock loop). */
18
+ export function sleepSync(ms) {
19
+ if (ms > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
20
+ }
21
+
22
+ /**
23
+ * Replace `path` atomically with `data`.
24
+ * Rename is retried a few times because Windows antivirus/indexers can hold a
25
+ * short-lived handle on the target (`EPERM`/`EBUSY`).
26
+ */
27
+ export function writeFileAtomic(path, data, { encoding = 'utf8', retries = 6 } = {}) {
28
+ const dir = dirname(path)
29
+ mkdirSync(dir, { recursive: true })
30
+ const tmp = join(dir, `.${basename(path)}.${process.pid}.${Date.now().toString(36)}.tmp`)
31
+ let fd
32
+ try {
33
+ fd = openSync(tmp, 'w')
34
+ writeFileSync(fd, data, typeof data === 'string' ? encoding : undefined)
35
+ try { fsyncSync(fd) } catch { /* fsync is best effort */ }
36
+ closeSync(fd)
37
+ fd = undefined
38
+ for (let attempt = 0; ; attempt += 1) {
39
+ try {
40
+ renameSync(tmp, path)
41
+ return path
42
+ } catch (error) {
43
+ if (attempt >= retries || !['EPERM', 'EBUSY', 'EACCES'].includes(error.code)) throw error
44
+ sleepSync(40 * (attempt + 1))
45
+ }
46
+ }
47
+ } catch (error) {
48
+ try { if (fd !== undefined) closeSync(fd) } catch { /* already closed */ }
49
+ try { rmSync(tmp, { force: true }) } catch { /* nothing to clean */ }
50
+ throw error
51
+ }
52
+ }
53
+
54
+ /** Timestamp safe for filenames: 20261123-152000-123. */
55
+ export function fileStamp(date = new Date()) {
56
+ const p = (n, w = 2) => String(n).padStart(w, '0')
57
+ return `${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}-` +
58
+ `${p(date.getHours())}${p(date.getMinutes())}${p(date.getSeconds())}-${p(date.getMilliseconds(), 3)}`
59
+ }
60
+
61
+ /**
62
+ * Copy `path` into `backupDir` with a timestamp, then prune oldest copies.
63
+ * Returns the backup path, or null when the source does not exist.
64
+ */
65
+ export function backupFile(path, backupDir, { prefix = '', keep = 10 } = {}) {
66
+ if (!existsSync(path)) return null
67
+ mkdirSync(backupDir, { recursive: true })
68
+ const backup = join(backupDir, `${prefix || basename(path)}.${fileStamp()}.bak`)
69
+ copyFileSync(path, backup)
70
+ try {
71
+ const entries = readdirSync(backupDir)
72
+ .filter((name) => name.startsWith(`${prefix || basename(path)}.`) && name.endsWith('.bak'))
73
+ .map((name) => ({ name, time: statSync(join(backupDir, name)).mtimeMs }))
74
+ .sort((a, b) => b.time - a.time)
75
+ for (const stale of entries.slice(keep)) rmSync(join(backupDir, stale.name), { force: true })
76
+ } catch { /* pruning is best effort */ }
77
+ return backup
78
+ }
79
+
80
+ /** Read a UTF-8 file, returning '' when missing. */
81
+ export function readText(path) {
82
+ try { return readFileSync(path, 'utf8') } catch { return '' }
83
+ }