dsh-ai-collab 0.4.4 → 0.6.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/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
+ }
@@ -0,0 +1,187 @@
1
+ /**
2
+ * 跨项目仪表盘渲染:读取父目录下各项目 status.json + log.jsonl 行数,
3
+ * 生成 `board.md` 同级目录的 `dashboard.html`(自包含单文件,同 TASKS.html 风格)。
4
+ */
5
+ import { existsSync, mkdirSync, readdirSync } from 'node:fs'
6
+ import { join, dirname } from 'node:path'
7
+ import { readText, writeFileAtomic } from './atomic.js'
8
+
9
+ // ---------------------------------------------------------------- helpers
10
+
11
+ export function readdirSafe(dir) {
12
+ try { return readdirSync(dir) } catch { return [] }
13
+ }
14
+
15
+ function htmlEsc(s) {
16
+ return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
17
+ }
18
+
19
+ function readJsonFile(path) {
20
+ try { return JSON.parse(readText(path)) } catch { return null }
21
+ }
22
+
23
+ /** 读 `<root>/.ai/log.jsonl` 非空行数。 */
24
+ function logLineCount(root) {
25
+ try {
26
+ const raw = readText(join(root, '.ai', 'log.jsonl'))
27
+ return raw.split('\n').filter((l) => l.trim().length > 0).length
28
+ } catch { return 0 }
29
+ }
30
+
31
+ function phaseLabel(phase) {
32
+ const map = { init: '初始化', build: '构建', feature: '特性开发', 'attitude-validation': '姿态验证',
33
+ diagnosis: '诊断', maintain: '维护', deliver: '交付' }
34
+ return map[phase] || phase || '—'
35
+ }
36
+
37
+ // ---------------------------------------------------------------- scan
38
+
39
+ export function scanProjects(parent) {
40
+ const rows = []
41
+ for (const entry of readdirSafe(parent)) {
42
+ if (entry.startsWith('.') || entry.startsWith('_')) continue
43
+ const st = readJsonFile(join(parent, entry, '.ai', 'status.json'))
44
+ if (!st) continue
45
+ rows.push({
46
+ project: st.project || entry,
47
+ dir: entry,
48
+ phase: st.phase || '',
49
+ focus: st.focus || '',
50
+ blockers: st.blockers || [],
51
+ next: st.next || [],
52
+ updated_at: st.updated_at || '',
53
+ logCount: logLineCount(join(parent, entry)),
54
+ })
55
+ }
56
+ return rows.sort((a, b) => String(b.updated_at).localeCompare(String(a.updated_at)))
57
+ }
58
+
59
+ // ---------------------------------------------------------------- render: dashboard.html
60
+
61
+ export function renderDashboard(rows, parent, now) {
62
+ const dir = htmlEsc(parent)
63
+ const totalProjects = rows.length
64
+ const totalRecords = rows.reduce((s, r) => s + r.logCount, 0)
65
+ const blocking = rows.filter((r) => r.blockers.length > 0)
66
+ const maxLog = Math.max(1, ...rows.map((r) => r.logCount))
67
+
68
+ let tableHtml = ''
69
+ for (const r of rows) {
70
+ const hasBlock = r.blockers.length > 0
71
+ const blockText = hasBlock ? r.blockers.map((b) => htmlEsc(b)).join('; ') : '—'
72
+ const trClass = hasBlock ? ' style="background:#fff5f5"' : ''
73
+ tableHtml += `<tr${trClass}>
74
+ <td>${hasBlock ? '<span class="badge blocked">阻塞</span>' : ''}</td>
75
+ <td><strong>${htmlEsc(r.project)}</strong></td>
76
+ <td>${phaseLabel(r.phase)}</td>
77
+ <td>${htmlEsc(r.focus)}</td>
78
+ <td>${blockText}</td>
79
+ <td><a href="${htmlEsc(r.dir)}/TASKS.html" title="任务清单">${r.logCount} 条</a></td>
80
+ <td class="muted">${htmlEsc(r.updated_at)}</td>
81
+ </tr>`
82
+ }
83
+
84
+ let barHtml = ''
85
+ for (const r of rows) {
86
+ const pct = Math.round((r.logCount / maxLog) * 100)
87
+ const color = r.logCount >= 40 ? '#198754' : r.logCount >= 20 ? '#0d6efd' : '#6c757d'
88
+ barHtml += `<div class="bar-row">
89
+ <span class="bar-label">${htmlEsc(r.project)}</span>
90
+ <span class="bar-track"><span class="bar-fill" style="width:${pct}%;background:${color}"></span></span>
91
+ <span class="bar-count">${r.logCount}</span>
92
+ </div>`
93
+ }
94
+
95
+ let blockHtml = ''
96
+ if (blocking.length > 0) {
97
+ blockHtml = '<section class="blocking"><h2>🚨 当前阻塞</h2><ul>'
98
+ for (const r of blocking) {
99
+ for (const b of r.blockers) {
100
+ blockHtml += `<li><strong>${htmlEsc(r.project)}</strong>:${htmlEsc(b)}</li>`
101
+ }
102
+ }
103
+ blockHtml += '</ul></section>'
104
+ }
105
+
106
+ return `<!DOCTYPE html>
107
+ <html lang="zh-CN">
108
+ <head>
109
+ <meta charset="UTF-8">
110
+ <meta name="viewport" content="width=device-width,initial-scale=1.0">
111
+ <title>跨项目仪表盘</title>
112
+ <style>
113
+ :root { --bg:#f8f9fa; --card:#fff; --text:#212529; --muted:#6c757d; --border:#dee2e6; font-family:system-ui,-apple-system,sans-serif; }
114
+ body { background:var(--bg); color:var(--text); margin:0; padding:16px; }
115
+ .container { max-width:1100px; margin:0 auto; }
116
+ header { background:var(--card); border:1px solid var(--border); border-radius:8px; padding:16px 24px; margin-bottom:16px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:8px; }
117
+ header h1 { margin:0; font-size:20px; }
118
+ header .stats { display:flex; gap:16px; }
119
+ header .stat { text-align:center; }
120
+ header .stat .num { font-size:22px; font-weight:700; }
121
+ header .stat .label { font-size:11px; color:var(--muted); }
122
+ section { background:var(--card); border:1px solid var(--border); border-radius:8px; padding:16px 24px; margin-bottom:16px; }
123
+ section h2 { margin:0 0 12px; font-size:16px; }
124
+ section.blocking { border-color:#dc3545; }
125
+ section.blocking ul { margin:0; padding-left:20px; color:#dc3545; }
126
+ section.blocking li { margin-bottom:4px; }
127
+ section.blocking strong { color:var(--text); }
128
+ table { width:100%; border-collapse:collapse; font-size:13px; }
129
+ th, td { text-align:left; padding:6px 8px; border-bottom:1px solid var(--border); vertical-align:top; }
130
+ th { background:#f1f3f5; font-weight:600; white-space:nowrap; }
131
+ tr:hover { background:#f8f9fa; }
132
+ .muted { color:var(--muted); font-size:12px; }
133
+ .badge { display:inline-block; padding:2px 6px; border-radius:3px; font-size:11px; font-weight:600; }
134
+ .badge.blocked { background:#dc3545; color:#fff; }
135
+ a { color:#0d6efd; text-decoration:none; }
136
+ a:hover { text-decoration:underline; }
137
+ .bar-row { display:flex; align-items:center; gap:8px; margin-bottom:6px; font-size:13px; }
138
+ .bar-label { min-width:80px; text-align:right; font-weight:500; }
139
+ .bar-track { flex:1; height:18px; background:#e9ecef; border-radius:4px; overflow:hidden; }
140
+ .bar-fill { height:100%; border-radius:4px; transition:width .3s; }
141
+ .bar-count { min-width:30px; font-variant-numeric:tabular-nums; color:var(--muted); }
142
+ footer { text-align:center; color:var(--muted); font-size:12px; padding:12px; }
143
+ </style>
144
+ </head>
145
+ <body>
146
+ <div class="container">
147
+ <header>
148
+ <div><h1>📊 跨项目仪表盘</h1><div class="muted">扫描:${dir} · 共 ${totalProjects} 个项目 · ${now}</div></div>
149
+ <div class="stats">
150
+ <div class="stat"><div class="num">${totalProjects}</div><div class="label">项目</div></div>
151
+ <div class="stat"><div class="num">${totalRecords}</div><div class="label">记录</div></div>
152
+ <div class="stat"><div class="num" style="color:#dc3545">${blocking.length}</div><div class="label">阻塞</div></div>
153
+ </div>
154
+ </header>
155
+ ${blockHtml}
156
+ <section><h2>记录趋势</h2>${barHtml}</section>
157
+ <section><h2>项目总览</h2>
158
+ <table>
159
+ <tr><th></th><th>项目</th><th>阶段</th><th>焦点</th><th>阻塞</th><th>记录</th><th class="muted">最后更新</th></tr>
160
+ ${tableHtml}
161
+ </table>
162
+ </section>
163
+ <footer>自动生成 · 来源各项目 .ai/status.json + .ai/log.jsonl · 勿手动编辑</footer>
164
+ </div>
165
+ </body>
166
+ </html>
167
+ `
168
+ }
169
+
170
+ // ---------------------------------------------------------------- write
171
+
172
+ /**
173
+ * 读父目录 `board.md` 的位置来确定仪表盘输出路径。
174
+ * 目标:`<board.md 所在目录>\dashboard.html`。
175
+ * 当父目录没有 board.md 时返回 null。
176
+ */
177
+ export function writeDashboard(root) {
178
+ const parent = dirname(root)
179
+ const boardPath = join(parent, '.ai', 'board.md')
180
+ if (!existsSync(boardPath)) return null
181
+ const rows = scanProjects(parent)
182
+ const now = new Date().toISOString()
183
+ const outPath = join(parent, '.ai', 'dashboard.html')
184
+ mkdirSync(join(parent, '.ai'), { recursive: true })
185
+ writeFileAtomic(outPath, renderDashboard(rows, parent, now))
186
+ return { path: outPath, rows: rows.length, written: true }
187
+ }