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/lib/plan.js ADDED
@@ -0,0 +1,334 @@
1
+ /**
2
+ * `ai_plan` data layer: `.ai/plan.json` (structured plan/checklist/risks)
3
+ * and its rendered outputs `.ai/PLAN.md` and `TASKS.md` (three-section).
4
+ *
5
+ * plan.json 写入走原子写 + 项目级锁(与 appendRecord 同级保护)。
6
+ * TASKS.md / TASKS.html / PLAN.md 是渲染产物,不手改。
7
+ */
8
+ import { existsSync, mkdirSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { writeFileAtomic, readText } from './atomic.js'
11
+ import { withLock } from './lock.js'
12
+
13
+ // ---------------------------------------------------------------- schema
14
+
15
+ export const PLAN_STATUSES = ['todo', 'in_progress', 'done', 'blocked']
16
+ export const CHECKLIST_STATUSES = ['open', 'done', 'na']
17
+ export const RISK_PROBABILITIES = ['高', '中', '低']
18
+ export const RISK_IMPACTS = ['高', '中', '低']
19
+ export const RISK_STRATEGIES = ['规避', '减轻', '接受', '转移']
20
+ export const RISK_STATUSES = ['active', 'resolved', 'expired']
21
+
22
+ /** 新建空 plan 的默认值。 */
23
+ export function emptyPlan() {
24
+ return {
25
+ schema_version: 1,
26
+ updated_at: '',
27
+ plan: [],
28
+ checklist: [],
29
+ risks: [],
30
+ }
31
+ }
32
+
33
+ // ---------------------------------------------------------------- paths
34
+
35
+ function planPath(root) { return join(root, '.ai', 'plan.json') }
36
+ function planMdPath(root) { return join(root, '.ai', 'PLAN.md') }
37
+ function tasksMdPath(root) { return join(root, 'TASKS.md') }
38
+
39
+ /** 需要锁保护的动作统一走这里。 */
40
+ function planLockPath(root) { return join(root, '.ai', '.plan.lock') }
41
+
42
+ // ---------------------------------------------------------------- read / write
43
+
44
+ export function readPlan(root) {
45
+ try {
46
+ const raw = readText(planPath(root))
47
+ const obj = JSON.parse(raw)
48
+ if (!obj || typeof obj !== 'object') return emptyPlan()
49
+ const p = emptyPlan()
50
+ if (Array.isArray(obj.plan)) p.plan = obj.plan
51
+ if (Array.isArray(obj.checklist)) p.checklist = obj.checklist
52
+ if (Array.isArray(obj.risks)) p.risks = obj.risks
53
+ if (typeof obj.schema_version === 'number') p.schema_version = obj.schema_version
54
+ if (typeof obj.updated_at === 'string') p.updated_at = obj.updated_at
55
+ return p
56
+ } catch {
57
+ return emptyPlan()
58
+ }
59
+ }
60
+
61
+ export function writePlan(root, plan, now) {
62
+ mkdirSync(join(root, '.ai'), { recursive: true })
63
+ const payload = { ...plan, updated_at: now || new Date().toISOString() }
64
+ return withLock(planLockPath(root), () => {
65
+ writeFileAtomic(planPath(root), JSON.stringify(payload, null, 2) + '\n')
66
+ writeFileAtomic(planMdPath(root), renderPlanMarkdown(payload))
67
+ return payload
68
+ })
69
+ }
70
+
71
+ // ---------------------------------------------------------------- setters
72
+
73
+ /** 用一组项覆盖 plan/checklist/risks 中的一块。 */
74
+ export function setBlock(root, key, items, now) {
75
+ const plan = readPlan(root)
76
+ if (!['plan', 'checklist', 'risks'].includes(key)) throw new Error(`未知块: ${key}`)
77
+ if (!Array.isArray(items)) throw new Error(`${key} 必须为数组`)
78
+ plan[key] = items
79
+ return writePlan(root, plan, now)
80
+ }
81
+
82
+ /** 勾选清单项。返回更新后的 plan 与该项。 */
83
+ export function doneChecklistItem(root, id, now) {
84
+ const plan = readPlan(root)
85
+ const target = plan.checklist.find((c) => c.id === id)
86
+ if (!target) throw new Error(`清单项不存在: ${id}`)
87
+ target.status = 'done'
88
+ return { plan: writePlan(root, plan, now), item: target }
89
+ }
90
+
91
+ /** 收集当前 active 风险标题(用于联动 status.json.blockers)。 */
92
+ export function activeRiskTitles(plan) {
93
+ return (plan.risks || [])
94
+ .filter((r) => r.status === 'active')
95
+ .map((r) => r.risk)
96
+ }
97
+
98
+ // ---------------------------------------------------------------- render: PLAN.md
99
+
100
+ function cell(value) {
101
+ return String(value ?? '').replace(/\|/g, '\\|').replace(/\n/g, ' ')
102
+ }
103
+
104
+ function statusLabel(status) {
105
+ const map = { todo: '待办', in_progress: '进行中', done: '完成', blocked: '阻塞',
106
+ open: '待办', na: '不适用', active: '活跃', resolved: '已解决', expired: '已失效' }
107
+ return map[status] || status
108
+ }
109
+
110
+ export function renderPlanMarkdown(plan) {
111
+ const lines = [
112
+ '# 执行计划与清单',
113
+ '',
114
+ `> 自动生成:来源 \`.ai\\plan.json\`。最后更新 ${plan.updated_at || '—'}`,
115
+ '> 用工具 `ai_plan` 管理,不要手动编辑本文件。',
116
+ '',
117
+ ]
118
+
119
+ if ((plan.plan || []).length > 0) {
120
+ lines.push('## 执行计划', '')
121
+ lines.push('| # | 步骤 | 验收标准 | 状态 | 负责人 | 截止 |')
122
+ lines.push('|---|---|---|---|---|---|')
123
+ for (const p of plan.plan) {
124
+ lines.push(`| ${cell(p.id)} | ${cell(p.step)} | ${cell(p.acceptance)} | ${statusLabel(p.status)} | ${cell(p.owner)} | ${cell(p.due)} |`)
125
+ }
126
+ lines.push('')
127
+ }
128
+
129
+ if ((plan.checklist || []).length > 0) {
130
+ lines.push('## 检查清单', '')
131
+ lines.push('| # | 项 | 状态 | 关联记录 |')
132
+ lines.push('|---|---|---|---|')
133
+ for (const c of plan.checklist) {
134
+ lines.push(`| ${cell(c.id)} | ${cell(c.item)} | ${statusLabel(c.status)} | ${cell(c.link)} |`)
135
+ }
136
+ lines.push('')
137
+ }
138
+
139
+ if ((plan.risks || []).length > 0) {
140
+ lines.push('## 风险与应对', '')
141
+ lines.push('| 风险 | 概率 | 影响 | 策略 | 状态 |')
142
+ lines.push('|---|---|---|---|---|')
143
+ for (const r of plan.risks) {
144
+ lines.push(`| ${cell(r.risk)} | ${cell(r.probability)} | ${cell(r.impact)} | ${cell(r.strategy)} | ${statusLabel(r.status)} |`)
145
+ }
146
+ lines.push('')
147
+ }
148
+
149
+ return lines.join('\n')
150
+ }
151
+
152
+ // ---------------------------------------------------------------- render: TASKS.md (three-section)
153
+
154
+ export function renderTasksMarkdown(root, records, plan, now) {
155
+ const lines = [
156
+ '# 任务记录清单',
157
+ '',
158
+ `> 自动生成:来自 \`.ai\\log.jsonl\`,共 ${records.length} 条;按时间倒序。最后更新 ${now}`,
159
+ '> 只读清单:要新增记录请用 `.ai\\llm.cmd add` 或工具 `ai_log`,不要直接编辑本文件。',
160
+ '',
161
+ ]
162
+
163
+ // --- plan sections ---
164
+ if (plan && plan.plan.length > 0) {
165
+ lines.push('## 执行计划(来源:`.ai\\plan.json`)', '')
166
+ lines.push('| # | 步骤 | 验收标准 | 状态 | 负责人 | 截止 |')
167
+ lines.push('|---|---|---|---|---|---|')
168
+ for (const p of plan.plan) {
169
+ lines.push(`| ${cell(p.id)} | ${cell(p.step)} | ${cell(p.acceptance)} | ${statusLabel(p.status)} | ${cell(p.owner)} | ${cell(p.due)} |`)
170
+ }
171
+ lines.push('')
172
+ }
173
+
174
+ if (plan && plan.checklist.length > 0) {
175
+ lines.push('## 检查清单(来源:`.ai\\plan.json`)', '')
176
+ lines.push('| # | 项 | 状态 | 关联记录 |')
177
+ lines.push('|---|---|---|---|')
178
+ for (const c of plan.checklist) {
179
+ lines.push(`| ${cell(c.id)} | ${cell(c.item)} | ${statusLabel(c.status)} | ${cell(c.link)} |`)
180
+ }
181
+ lines.push('')
182
+ }
183
+
184
+ if (plan && plan.risks.length > 0) {
185
+ lines.push('## 风险与应对(来源:`.ai\\plan.json`)', '')
186
+ lines.push('| 风险 | 概率 | 影响 | 策略 | 状态 |')
187
+ lines.push('|---|---|---|---|---|')
188
+ for (const r of plan.risks) {
189
+ lines.push(`| ${cell(r.risk)} | ${cell(r.probability)} | ${cell(r.impact)} | ${cell(r.strategy)} | ${statusLabel(r.status)} |`)
190
+ }
191
+ lines.push('')
192
+ }
193
+
194
+ // --- log records ---
195
+ lines.push('## 工作日志(来源:`.ai\\log.jsonl`,只读)', '')
196
+ lines.push('| 时间 | 类型 | 状态 | 摘要 | 记录 id |')
197
+ lines.push('|---|---|---|---|---|')
198
+ const rows = records.map((r) => ({
199
+ ts: String(r.ts ?? ''),
200
+ action: String(r.action ?? ''),
201
+ status: String(r.status ?? ''),
202
+ summary: cell(r.summary),
203
+ id: String(r.id ?? ''),
204
+ }))
205
+ for (let i = rows.length - 1; i >= 0; i -= 1) {
206
+ const r = rows[i]
207
+ lines.push(`| ${r.ts} | ${r.action} | ${r.status} | ${r.summary} | \`${r.id}\` |`)
208
+ }
209
+ if (rows.length === 0) lines.push('| (暂无记录) | | | | |')
210
+ lines.push('')
211
+
212
+ return lines.join('\n')
213
+ }
214
+
215
+ // ---------------------------------------------------------------- render: TASKS.html (dashboard-style)
216
+
217
+ function htmlEsc(s) {
218
+ return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
219
+ }
220
+
221
+ function riskColor(p, i) {
222
+ // 高/高 → 红;高/中 或 中/高 → 橙;中/中 → 黄;其余 → 灰
223
+ if (p === '高' && i === '高') return '#dc3545'
224
+ if ((p === '高' && i === '中') || (p === '中' && i === '高')) return '#fd7e14'
225
+ if (p === '中' && i === '中') return '#ffc107'
226
+ return '#6c757d'
227
+ }
228
+
229
+ function statusBadge(status) {
230
+ const colors = { todo: '#6c757d', in_progress: '#0d6efd', done: '#198754', blocked: '#dc3545',
231
+ open: '#6c757d', na: '#adb5bd', active: '#dc3545', resolved: '#198754', expired: '#adb5bd' }
232
+ return `<span style="background:${colors[status] || '#6c757d'};color:#fff;padding:2px 8px;border-radius:4px;font-size:12px">${htmlEsc(statusLabel(status))}</span>`
233
+ }
234
+
235
+ export function renderTasksHtml(root, records, plan, now, projectName) {
236
+ const name = htmlEsc(projectName || root.split(/[/\\]/).filter(Boolean).pop() || '')
237
+ const recordRows = records.map((r) => ({
238
+ ts: String(r.ts ?? ''),
239
+ action: String(r.action ?? ''),
240
+ status: String(r.status ?? ''),
241
+ summary: htmlEsc(r.summary),
242
+ id: htmlEsc(r.id ?? ''),
243
+ })).reverse()
244
+
245
+ let planHtml = ''
246
+ if (plan && plan.plan.length > 0) {
247
+ planHtml += '<section><h2>📋 执行计划</h2><table><tr><th>#</th><th>步骤</th><th>验收标准</th><th>状态</th><th>负责人</th><th>截止</th></tr>'
248
+ for (const p of plan.plan) {
249
+ planHtml += `<tr><td>${htmlEsc(p.id)}</td><td>${htmlEsc(p.step)}</td><td>${htmlEsc(p.acceptance)}</td><td>${statusBadge(p.status)}</td><td>${htmlEsc(p.owner)}</td><td>${htmlEsc(p.due)}</td></tr>`
250
+ }
251
+ planHtml += '</table></section>'
252
+ }
253
+
254
+ let checklistHtml = ''
255
+ if (plan && plan.checklist.length > 0) {
256
+ checklistHtml += '<section><h2>✅ 检查清单</h2><table><tr><th>#</th><th>项</th><th>状态</th><th>关联记录</th></tr>'
257
+ for (const c of plan.checklist) {
258
+ checklistHtml += `<tr><td>${htmlEsc(c.id)}</td><td>${htmlEsc(c.item)}</td><td>${statusBadge(c.status)}</td><td>${htmlEsc(c.link)}</td></tr>`
259
+ }
260
+ checklistHtml += '</table></section>'
261
+ }
262
+
263
+ let risksHtml = ''
264
+ if (plan && plan.risks.length > 0) {
265
+ risksHtml += '<section><h2>⚠️ 风险与应对</h2><table><tr><th>风险</th><th>概率</th><th>影响</th><th>策略</th><th>状态</th></tr>'
266
+ for (const r of plan.risks) {
267
+ const dot = `<span style="display:inline-block;width:12px;height:12px;border-radius:50%;background:${riskColor(r.probability, r.impact)};margin-right:4px"></span>`
268
+ risksHtml += `<tr><td>${dot}${htmlEsc(r.risk)}</td><td>${htmlEsc(r.probability)}</td><td>${htmlEsc(r.impact)}</td><td>${htmlEsc(r.strategy)}</td><td>${statusBadge(r.status)}</td></tr>`
269
+ }
270
+ risksHtml += '</table></section>'
271
+ }
272
+
273
+ let logHtml = ''
274
+ if (recordRows.length > 0) {
275
+ logHtml += '<section><h2>📜 工作日志</h2><table><tr><th>时间</th><th>类型</th><th>状态</th><th>摘要</th><th>记录 id</th></tr>'
276
+ for (const r of recordRows) {
277
+ logHtml += `<tr><td>${htmlEsc(r.ts)}</td><td>${htmlEsc(r.action)}</td><td>${statusBadge(r.status)}</td><td>${r.summary}</td><td><code>${r.id}</code></td></tr>`
278
+ }
279
+ logHtml += '</table></section>'
280
+ }
281
+
282
+ const hasPlan = plan && (plan.plan.length > 0 || plan.checklist.length > 0 || plan.risks.length > 0)
283
+
284
+ return `<!DOCTYPE html>
285
+ <html lang="zh-CN">
286
+ <head>
287
+ <meta charset="UTF-8">
288
+ <meta name="viewport" content="width=device-width,initial-scale=1.0">
289
+ <title>${name} · 任务清单</title>
290
+ <style>
291
+ :root { --bg:#f8f9fa; --card:#fff; --text:#212529; --muted:#6c757d; --border:#dee2e6; font-family:system-ui,-apple-system,sans-serif; }
292
+ body { background:var(--bg); color:var(--text); margin:0; padding:16px; }
293
+ .container { max-width:960px; margin:0 auto; }
294
+ header { background:var(--card); border:1px solid var(--border); border-radius:8px; padding:16px 24px; margin-bottom:16px; }
295
+ header h1 { margin:0 0 4px; font-size:20px; }
296
+ header .meta { color:var(--muted); font-size:13px; }
297
+ section { background:var(--card); border:1px solid var(--border); border-radius:8px; padding:16px 24px; margin-bottom:16px; }
298
+ section h2 { margin:0 0 12px; font-size:16px; }
299
+ table { width:100%; border-collapse:collapse; font-size:13px; }
300
+ th, td { text-align:left; padding:6px 8px; border-bottom:1px solid var(--border); vertical-align:top; }
301
+ th { background:#f1f3f5; font-weight:600; white-space:nowrap; }
302
+ tr:hover { background:#f8f9fa; }
303
+ .placeholder { color:var(--muted); font-style:italic; padding:12px 0; }
304
+ footer { text-align:center; color:var(--muted); font-size:12px; padding:12px; }
305
+ </style>
306
+ </head>
307
+ <body>
308
+ <div class="container">
309
+ <header>
310
+ <h1>${name} · 任务清单</h1>
311
+ <div class="meta">${hasPlan ? `计划更新: ${htmlEsc(plan.updated_at || '—')} · ` : ''}日志共 ${records.length} 条 · 生成: ${htmlEsc(now)}</div>
312
+ </header>
313
+ ${planHtml}${checklistHtml}${risksHtml}${logHtml}
314
+ ${records.length === 0 && !hasPlan ? '<div class="placeholder">暂无记录与计划。</div>' : ''}
315
+ <footer>自动生成 · 来源 .ai/log.jsonl + .ai/plan.json · 勿手动编辑</footer>
316
+ </div>
317
+ </body>
318
+ </html>
319
+ `
320
+ }
321
+
322
+ // ---------------------------------------------------------------- write all renders
323
+
324
+ /** 一次写 TASKS.md + TASKS.html + PLAN.md(在锁内)。 */
325
+ export function writeAllRenders(root, records, now, projectName) {
326
+ mkdirSync(join(root, '.ai'), { recursive: true })
327
+ const plan = readPlan(root)
328
+ return withLock(planLockPath(root), () => {
329
+ writeFileAtomic(tasksMdPath(root), renderTasksMarkdown(root, records, plan, now))
330
+ writeFileAtomic(join(root, 'TASKS.html'), renderTasksHtml(root, records, plan, now, projectName))
331
+ writeFileAtomic(planMdPath(root), renderPlanMarkdown(plan))
332
+ return { plan, tasksMd: tasksMdPath(root), tasksHtml: join(root, 'TASKS.html'), planMd: planMdPath(root) }
333
+ })
334
+ }
package/lib/tasks.js CHANGED
@@ -1,13 +1,13 @@
1
1
  /**
2
- * Pure task-list renderer for the `.ai/` collaboration layer.
2
+ * Task-list renderer: reads `.ai/log.jsonl`, writes three-section `TASKS.md`
3
+ * + `TASKS.html` (dashboard-style) + `.ai/PLAN.md` (from .ai/plan.json).
3
4
  *
4
- * Why this exists: the plugin used to refresh `TASKS.md` by spawning the
5
- * workspace's own `.ai/llm.ps1`. That executed code from the repository being
6
- * worked on, which is a supply-chain risk. Rendering happens here instead:
7
- * no PowerShell, no workspace-provided script, identical output format.
5
+ * Plan-aware rendering is delegated to `lib/plan.js`; this module keeps the
6
+ * record parsing and provides `writeTasks` for index.js.
8
7
  */
9
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'
8
+ import { existsSync, readFileSync, mkdirSync } from 'node:fs'
10
9
  import { join } from 'node:path'
10
+ import { writeAllRenders } from './plan.js'
11
11
 
12
12
  /** Parse JSONL text into records, skipping blank or malformed lines. */
13
13
  export function parseRecords(text) {
@@ -24,17 +24,32 @@ export function parseRecords(text) {
24
24
  return out
25
25
  }
26
26
 
27
- function cell(value) {
28
- return String(value ?? '').replace(/\|/g, '\\|')
27
+ /**
28
+ * Write `<root>/TASKS.md` + `<root>/TASKS.html` + `.ai/PLAN.md`.
29
+ *
30
+ * When `.ai/plan.json` exists the TASKS files include plan/checklist/risks
31
+ * sections before the log table; otherwise they fall back to a log-only view.
32
+ *
33
+ * Returns `{ written, count, tasksMd, tasksHtml, planMd }`;
34
+ * never throws by design (caller logs).
35
+ */
36
+ export function writeTasks(root, now, projectName) {
37
+ const logFile = join(root, '.ai', 'log.jsonl')
38
+ const outFile = join(root, 'TASKS.md')
39
+ if (!existsSync(logFile)) return { written: false, count: 0, path: outFile }
40
+ const records = parseRecords(readFileSync(logFile, 'utf8'))
41
+ mkdirSync(join(root, '.ai'), { recursive: true })
42
+ const result = writeAllRenders(root, records, now, projectName)
43
+ return { written: true, count: records.length, ...result }
29
44
  }
30
45
 
31
- /** Render the exact `TASKS.md` body used by `.ai\llm.cmd tasks`. */
46
+ // Keep the old `renderTasks` export for test compatibility (deprecated).
32
47
  export function renderTasks(records, now) {
33
48
  const rows = records.map((r) => ({
34
49
  ts: String(r.ts ?? ''),
35
50
  action: String(r.action ?? ''),
36
51
  status: String(r.status ?? ''),
37
- summary: cell(r.summary),
52
+ summary: String(r.summary ?? '').replace(/\|/g, '\\|').replace(/\n/g, ' '),
38
53
  id: String(r.id ?? ''),
39
54
  }))
40
55
  const lines = [
@@ -52,18 +67,4 @@ export function renderTasks(records, now) {
52
67
  }
53
68
  if (rows.length === 0) lines.push('| (暂无记录) | | | | |')
54
69
  return `${lines.join('\n')}\n`
55
- }
56
-
57
- /**
58
- * Write `<root>/TASKS.md` from `<root>/.ai/log.jsonl`.
59
- * Returns `{ written, count, path }`; never throws by design (caller logs).
60
- */
61
- export function writeTasks(root, now) {
62
- const logFile = join(root, '.ai', 'log.jsonl')
63
- const outFile = join(root, 'TASKS.md')
64
- if (!existsSync(logFile)) return { written: false, count: 0, path: outFile }
65
- const records = parseRecords(readFileSync(logFile, 'utf8'))
66
- mkdirSync(join(root, '.ai'), { recursive: true })
67
- writeFileSync(outFile, renderTasks(records, now), 'utf8')
68
- return { written: true, count: records.length, path: outFile }
69
- }
70
+ }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "dsh-ai-collab",
3
- "version": "0.4.4",
3
+ "version": "0.6.0",
4
4
  "os": [
5
5
  "win32"
6
6
  ],
7
- "description": "DeepSeek Harness bundle: AI collaboration layer (status/log/check tools + workspace scaffold) built around AGENTS.md and .ai/",
7
+ "description": "DeepSeek Harness bundle: AI collaboration layer (status/log/check/plan tools, disciplines, handoff, workspace scaffold) built around AGENTS.md and .ai/",
8
8
  "type": "module",
9
9
  "main": "./index.js",
10
10
  "exports": {
@@ -63,7 +63,7 @@
63
63
  "dsh": ">=0.2.1"
64
64
  },
65
65
  "scripts": {
66
- "check": "node --check index.js && node --check lib/config.js && node --check lib/tasks.js",
67
- "test": "node --test test/smoke.test.mjs test/lib.test.mjs test/preservation.test.mjs"
66
+ "check": "node --check index.js && node --check lib/config.js && node --check lib/tasks.js && node --check lib/atomic.js && node --check lib/lock.js && node --check lib/disciplines.js && node --check lib/handoff.js && node --check lib/plan.js && node --check lib/dashboard.js",
67
+ "test": "node --test test/smoke.test.mjs test/lib.test.mjs test/preservation.test.mjs test/discipline.test.mjs test/plan.test.mjs"
68
68
  }
69
69
  }
@@ -82,6 +82,40 @@ $ErrorActionPreference = 'Stop'
82
82
 
83
83
  $Utf8NoBom = New-Object System.Text.UTF8Encoding($false)
84
84
 
85
+ # 并发保护:写临时文件再替换,避免读者看到半截 JSON/Markdown。
86
+ function Write-TextAtomic([string]$Path, [string]$Text) {
87
+ $dir = Split-Path -Parent $Path
88
+ if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
89
+ $tmp = Join-Path $dir ('.' + [System.IO.Path]::GetFileName($Path) + '.' + [guid]::NewGuid().ToString('N') + '.tmp')
90
+ [System.IO.File]::WriteAllText($tmp, $Text, $Utf8NoBom)
91
+ if (-not (Test-Path -LiteralPath $Path)) { Move-Item -LiteralPath $tmp -Destination $Path -Force; return }
92
+ for ($i = 0; $i -lt 8; $i++) {
93
+ try { [System.IO.File]::Replace($tmp, $Path, [NullString]::Value); return }
94
+ catch [System.IO.IOException] { Start-Sleep -Milliseconds (30 * ($i + 1)) }
95
+ }
96
+ Move-Item -LiteralPath $tmp -Destination $Path -Force
97
+ }
98
+
99
+ # 跨进程互斥:CreateNew 是原子的;超时抛错,由调用方决定是否继续。
100
+ function Enter-ProjectLock([string]$Path, [int]$TimeoutMs = 15000) {
101
+ $sw = [Diagnostics.Stopwatch]::StartNew()
102
+ while ($true) {
103
+ try {
104
+ $fs = [System.IO.File]::Open($Path, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
105
+ try {
106
+ $bytes = [Text.Encoding]::UTF8.GetBytes(("pid={0} ts={1}" -f $PID, (Get-Date).ToString('o')))
107
+ $fs.Write($bytes, 0, $bytes.Length); $fs.Flush()
108
+ } finally { $fs.Dispose() }
109
+ return
110
+ }
111
+ catch [System.IO.IOException] {
112
+ if ($sw.ElapsedMilliseconds -gt $TimeoutMs) { throw "获取锁超时: $Path" }
113
+ Start-Sleep -Milliseconds 50
114
+ }
115
+ }
116
+ }
117
+ function Exit-ProjectLock([string]$Path) { Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue }
118
+
85
119
  $ActionEnum = @('task_start', 'task_done', 'fix', 'diagnosis', 'build', 'commit',
86
120
  'doc', 'review', 'rollback', 'correction', 'maintenance', 'handoff')
87
121
  $StatusEnum = @('ok', 'partial', 'blocked', 'todo', 'failed')
@@ -289,7 +323,7 @@ function Save-StatusObject([string]$ProjectRoot, $Object) {
289
323
  $pretty = ConvertTo-Json -InputObject $Object -Depth 8
290
324
  $pretty = ConvertFrom-JsonEscapes $pretty
291
325
  $pretty = Format-JsonPretty $pretty
292
- [System.IO.File]::WriteAllText($path, ($pretty -replace "`r`n", "`n") + "`n", $Utf8NoBom)
326
+ Write-TextAtomic $path (($pretty -replace "`r`n", "`n") + "`n")
293
327
  return $path
294
328
  }
295
329
 
@@ -487,9 +521,13 @@ function Invoke-Add {
487
521
  $logPath = Get-LogPath $ProjectRoot
488
522
  $dir = Split-Path -Parent $logPath
489
523
  if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
490
- [System.IO.File]::AppendAllText($logPath, $line + "`n", $Utf8NoBom)
491
-
492
- Update-StatusFromLog $ProjectRoot $ordered
524
+ $lockPath = Join-Path $dir '.log.lock'
525
+ [void](Enter-ProjectLock $lockPath)
526
+ try {
527
+ [System.IO.File]::AppendAllText($logPath, $line + "`n", $Utf8NoBom)
528
+ Update-StatusFromLog $ProjectRoot $ordered
529
+ }
530
+ finally { Exit-ProjectLock $lockPath }
493
531
 
494
532
  # 自动刷新跨项目看板(约定:项目父目录存在 .ai\board.md)。-NoBoard 可关闭。
495
533
  if (-not $NoBoard) {
@@ -675,7 +713,7 @@ Record work through `.ai\llm.cmd` (status / tail / add / check). Never rewrite t
675
713
  $content = $template.Replace('{{TITLE}}', $t.Title).Replace('{{TOOL}}', $t.Tool).Replace('{{ROOT}}', $ProjectRoot)
676
714
  $dest = Join-Path $entriesDir $t.Name
677
715
  if ((Test-Path -LiteralPath $dest) -and -not $Force) { continue }
678
- [System.IO.File]::WriteAllText($dest, ($content -replace "`r`n", "`n") + "`n", $Utf8NoBom)
716
+ Write-TextAtomic $dest (($content -replace "`r`n", "`n") + "`n")
679
717
  }
680
718
  Write-Info ("母版已更新: .ai\entries\({0} 个)" -f $targets.Count)
681
719
 
@@ -726,7 +764,10 @@ function Invoke-Tasks([string]$ProjectRoot) {
726
764
  if ($rows.Count -eq 0) { [void]$sb.AppendLine('| (暂无记录) | | | | |') }
727
765
 
728
766
  $out = Join-Path $ProjectRoot 'TASKS.md'
729
- [System.IO.File]::WriteAllText($out, $sb.ToString().Replace("`r`n", "`n"), $Utf8NoBom)
767
+ $lock = Join-Path $ProjectRoot '.ai\.tasks.lock'
768
+ [void](Enter-ProjectLock $lock)
769
+ try { Write-TextAtomic $out ($sb.ToString().Replace("`r`n", "`n")) }
770
+ finally { Exit-ProjectLock $lock }
730
771
  if (-not $Quiet) { Write-Info ("已生成任务清单: {0}({1} 条)" -f $out, $rows.Count) }
731
772
  }
732
773
  function Invoke-Archive([string]$ProjectRoot) {
@@ -769,12 +810,21 @@ function Invoke-Archive([string]$ProjectRoot) {
769
810
  $archiveFile = Join-Path $archiveDir ("log-{0}-{1}.jsonl" -f (Get-Date).Year, $quarter)
770
811
  $backupFile = Join-Path $archiveDir ("log-{0}-backup-{1}.jsonl" -f (Get-Date).ToString('yyyyMMdd-HHmmss'), $quarter)
771
812
 
772
- Copy-Item -LiteralPath $logPath -Destination $backupFile -Force
773
- foreach ($line in $archived) { [System.IO.File]::AppendAllText($archiveFile, $line + "`n", $Utf8NoBom) }
813
+ $lockPath = Join-Path (Join-Path $ProjectRoot '.ai') '.log.lock'
814
+ [void](Enter-ProjectLock $lockPath)
815
+ try {
816
+ # 归档基于之前读取的行;若期间有并发追加,宁可中止也不能丢记录。
817
+ $currentCount = @([System.IO.File]::ReadAllLines($logPath, [Text.Encoding]::UTF8) | Where-Object { $_.Trim() }).Count
818
+ if ($currentCount -ne $lines.Count) { throw '归档期间日志有新增记录,已中止;请重试' }
774
819
 
775
- $keepText = ''
776
- if ($keep.Count -gt 0) { $keepText = ($keep -join "`n") + "`n" }
777
- [System.IO.File]::WriteAllText($logPath, $keepText, $Utf8NoBom)
820
+ Copy-Item -LiteralPath $logPath -Destination $backupFile -Force
821
+ foreach ($line in $archived) { [System.IO.File]::AppendAllText($archiveFile, $line + "`n", $Utf8NoBom) }
822
+
823
+ $keepText = ''
824
+ if ($keep.Count -gt 0) { $keepText = ($keep -join "`n") + "`n" }
825
+ Write-TextAtomic $logPath $keepText
826
+ }
827
+ finally { Exit-ProjectLock $lockPath }
778
828
 
779
829
  Write-Info ("已归档 {0} 条 → {1}" -f $archived.Count, $archiveFile)
780
830
  Write-Info ("整文件备份 → {0}" -f $backupFile)
@@ -869,7 +919,7 @@ function Invoke-Board([string]$ProjectRoot) {
869
919
 
870
920
  $outDir = Split-Path -Parent $Out
871
921
  if (-not (Test-Path -LiteralPath $outDir)) { New-Item -ItemType Directory -Force -Path $outDir | Out-Null }
872
- [System.IO.File]::WriteAllText($Out, $sb.ToString().Replace("`r`n", "`n"), $Utf8NoBom)
922
+ Write-TextAtomic $Out ($sb.ToString().Replace("`r`n", "`n"))
873
923
  Write-Info ("已生成看板: {0}({1} 个项目,{2} 个未接入)" -f $Out, $rows.Count, $unadopted.Count)
874
924
  }
875
925