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/docs/index.html CHANGED
@@ -484,7 +484,7 @@
484
484
  <svg class="logo" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8" fill="#0d6b5b"/><path d="M9 11h14M9 16h9M9 21h11" stroke="#8fe7d1" stroke-width="2.6" stroke-linecap="round"/></svg>
485
485
  <span>dsh-ai-collab</span>
486
486
  </a>
487
- <span class="ver">v0.4.4</span>
487
+ <span class="ver">v0.6.0</span>
488
488
  <nav class="top-nav" aria-label="页面导航">
489
489
  <a href="#problem">问题</a>
490
490
  <a href="#model">机制</a>
@@ -561,13 +561,14 @@
561
561
  <li><a href="#records"><span class="n">04</span>记录:本地留存与追溯</a></li>
562
562
  <li><a href="#zones"><span class="n">05</span>分区:模板与事实各管各的</a></li>
563
563
  <li><a href="#discipline"><span class="n">06</span>纪律:随会话加载</a></li>
564
- <li><a href="#start"><span class="n">07</span>上手:三条命令</a></li>
565
- <li><a href="#status"><span class="n">08</span>边界与发布状态</a></li>
566
- <li><a href="#summary"><span class="n">09</span>结语</a></li>
564
+ <li><a href="#handoff"><span class="n">07</span>交接:接棒提示词与并发</a></li>
565
+ <li><a href="#start"><span class="n">08</span>上手:三条命令</a></li>
566
+ <li><a href="#status"><span class="n">09</span>边界与发布状态</a></li>
567
+ <li><a href="#summary"><span class="n">10</span>结语</a></li>
567
568
  </ol>
568
569
  </nav>
569
570
  <div class="side-card">
570
- <div class="sc-row"><span class="pulse" aria-hidden="true"></span>已发布 · 0.4.4</div>
571
+ <div class="sc-row"><span class="pulse" aria-hidden="true"></span>已发布 · 0.6.0</div>
571
572
  <p>npm 已上架,社区市场已收录;脚手架当前支持 Windows。</p>
572
573
  <button class="print-btn" type="button" id="printBtn" onclick="window.print()">打印 / 保存为 PDF</button>
573
574
  </div>
@@ -845,7 +846,7 @@
845
846
  <section class="sec" id="discipline">
846
847
  <p class="kicker"><span class="bar" aria-hidden="true"></span>06 · 全局纪律</p>
847
848
  <h2>全局纪律,随每个会话加载</h2>
848
- <p class="lead">插件附带用户级纪律模板 <code>AGENTS.global.template.md</code>:复制到 <code>$DSH_HOME/AGENTS.md</code>(已有全局文件则合并),DSH 会在每个会话注入它——不依赖模型记性,也不依赖项目是否已经接入。它是可加载的:改一次文件,之后每个会话都带着同一套纪律开始。</p>
849
+ <p class="lead">纪律现在由插件管理,不再靠手抄。全局纪律驻留在 <code>$DSH_HOME/AGENTS.md</code>,DSH 在每个会话无条件注入;<code>ai_discipline global-migrate</code> 把它拆成 8 个可独立开关的模块(<code>g0.md</code>…<code>g7.md</code>),之后 <code>global-disable g7</code> 这样一条调用就能让某节纪律从提示词里真正消失。</p>
849
850
 
850
851
  <div class="loadmap" aria-label="纪律加载链路">
851
852
  <div><span class="lm-k">01 · 安装</span><b>$DSH_HOME/AGENTS.md</b><span>跨项目纪律,一份文件</span></div>
@@ -856,6 +857,7 @@
856
857
 
857
858
  <div class="callout">
858
859
  <p><strong>全局文件只放跨项目纪律,没有任何项目事实。</strong>项目事实留在 <code>&lt;项目根&gt;/AGENTS.md</code>。编辑全局文件对下一次请求立即生效,无需重启;插件代码升级才需要重启 DSH。</p>
860
+ <p><strong>能做什么、不能做什么:</strong>可以全局停用某一节纪律,也可以给单个项目追加更严的规则;但<strong>不能只对某个项目卸载全局纪律</strong>——DSH 注入全局文件是无条件的,项目级只能「加」不能「减」。</p>
859
861
  </div>
860
862
 
861
863
  <div class="rules">
@@ -905,14 +907,72 @@
905
907
  </div>
906
908
 
907
909
  <div class="code-wrap">
908
- <pre class="code powershell"><code><span class="c"># 首次:把模板复制到 DSH 用户目录(已有全局文件则合并,不要直接覆盖)</span>
909
- Copy-Item <span class="s">"&lt;包目录&gt;\AGENTS.global.template.md"</span> <span class="s">"$env:DSH_HOME\AGENTS.md"</span></code></pre>
910
+ <pre class="code powershell"><code><span class="c"># 首次:把已有的全局 AGENTS.md 拆成可开关的模块(先备份,原文逐字节保留)</span>
911
+ ai_discipline action:global-migrate
912
+
913
+ <span class="c"># 日常:全局模块开关,改完立即重渲染 $DSH_HOME/AGENTS.md</span>
914
+ ai_discipline action:global-list
915
+ ai_discipline action:global-disable id:g7
916
+ ai_discipline action:global-enable id:g7
917
+
918
+ <span class="c"># 项目级:只对这个项目追加更严的规则,正文会内联进 AGENTS.md §8</span>
919
+ ai_discipline action:add id:no-force-push title:<span class="s">"禁止强推主干"</span> `
920
+ body:<span class="s">"推送前先确认远端状态;禁止 git push --force 到 main。"</span>
921
+ ai_discipline action:disable id:no-force-push <span class="c"># 只保留表行,不再约束</span></code></pre>
922
+ </div>
923
+
924
+ <div class="callout">
925
+ <p><strong>§8 是自检点。</strong>项目 <code>AGENTS.md</code> 的 generated 区里有一张纪律清单:全局行 <code>G0…G7</code> 只做索引(正文在全局文件里),项目行 <code>P-*</code> 的正文按「启用」内联。规则文件是纯 Markdown,人和工具都能改;<code>ai_check</code> 会报告漂移——启用了却没内联、停用了却还内联、注册表读不出来。</p>
910
926
  </div>
911
927
  </section>
912
928
 
913
929
  <!-- 07 -->
930
+ <section class="sec" id="handoff">
931
+ <p class="kicker"><span class="bar" aria-hidden="true"></span>07 · 交接与并发</p>
932
+ <h2>新会话先读一份「接棒提示词」</h2>
933
+ <p class="lead">原始日志是事件流,不适合当成开场白。插件维护一份 <code>.ai/SESSION_BOOT.md</code>:当前状态、最近记录、纪律清单、必读顺序,以及「读完请输出继承摘要」的指令。<code>ai_log</code>、<code>ai_init</code> 与自动接入都会重写它,<code>ai_handoff</code> 负责读取、重建和生成可粘贴的继承提示。</p>
934
+
935
+ <div class="loadmap" aria-label="交接链路">
936
+ <div><span class="lm-k">01 · 读取</span><b>SESSION_BOOT.md</b><span>接棒提示词与必读顺序</span></div>
937
+ <div><span class="lm-k">02 · 加载</span><b>status.json + log.jsonl</b><span>状态快照与最近流水</span></div>
938
+ <div><span class="lm-k">03 · 汇报</span><b>继承摘要</b><span>5–8 行,事实全部来自文件</span></div>
939
+ <div><span class="lm-k">04 · 开干</span><b>本轮任务</b><span>接着已有进度,不重新摸一遍</span></div>
940
+ </div>
941
+
942
+ <div class="code-wrap">
943
+ <pre class="code powershell"><code><span class="c"># 新会话开场:读接棒提示词(文件缺失时先生成再返回原文)</span>
944
+ ai_handoff action:read
945
+
946
+ <span class="c"># 或者直接要一段可粘贴给新会话的继承指令</span>
947
+ ai_handoff action:inherit
948
+
949
+ <span class="c"># 收工写记录时会自动重建 SESSION_BOOT.md</span>
950
+ &amp; .ai\llm.cmd add -Tool deepseek-harness -Action fix -Status ok -Summary <span class="s">"…"</span></code></pre>
951
+ </div>
952
+
953
+ <h3 class="subhead">多会话同时写,不会写坏文件</h3>
954
+ <div class="table-wrap">
955
+ <table>
956
+ <thead><tr><th>风险</th><th>做法</th><th>结果</th></tr></thead>
957
+ <tbody>
958
+ <tr><td>两个会话同时写日志</td><td><code>.ai/.log.lock</code> 跨进程锁,append 与状态更新在同一临界区</td><td>12 个进程并发写入 → 12 条记录、id 全唯一、<code>rev=12</code></td></tr>
959
+ <tr><td>写到一半被读到</td><td>临时文件 + <code>fsync</code> + rename 原子替换(对占用/权限错误退避重试)</td><td>读者只会看到旧版或新版,没有半截文件</td></tr>
960
+ <tr><td><code>TASKS.md</code> 被并行覆盖</td><td><code>.ai/.tasks.lock</code> 内整份重渲染</td><td>清单始终与日志一致</td></tr>
961
+ <tr><td><code>AGENTS.md</code> 改坏</td><td>原子写 + 写前备份到 <code>.ai/backups/</code>(保留最近 10 份)</td><td>可回滚;<code>-ResetAgents</code> 也有备份</td></tr>
962
+ <tr><td>状态快照丢更新</td><td><code>status.json</code> 增加自增 <code>rev</code>,写入在锁内完成</td><td><code>rev</code> 可作为「有没有丢写」的快速判断</td></tr>
963
+ <tr><td>纪律与实际渲染不一致</td><td><code>ai_check</code> 审计 §8 漂移</td><td>启用未内联 / 停用仍内联 / 注册表损坏都会报错</td></tr>
964
+ </tbody>
965
+ </table>
966
+ </div>
967
+
968
+ <div class="callout">
969
+ <p><strong>边界要说清:</strong>这是插件与 <code>.ai/llm.cmd</code> 之间的<strong>协作锁</strong>,不是操作系统级保证。用编辑器或别的脚本直接改这些文件,仍然可以绕过锁;<code>initScript</code> 是可信配置,不要指向不可信代码。</p>
970
+ </div>
971
+ </section>
972
+
973
+ <!-- 08 -->
914
974
  <section class="sec" id="start">
915
- <p class="kicker"><span class="bar" aria-hidden="true"></span>07 · 快速开始</p>
975
+ <p class="kicker"><span class="bar" aria-hidden="true"></span>08 · 快速开始</p>
916
976
  <h2>三条命令,开始交接</h2>
917
977
  <p class="lead">安装一次,之后每个会话只重复三个动作:读状态、干活、写记录。</p>
918
978
 
@@ -942,7 +1002,7 @@ dsh plugin --profile &lt;profile&gt; add "&lt;包绝对路径&gt;"</code></pre>
942
1002
  autoInit: true</code></pre>
943
1003
  </div>
944
1004
  </div>
945
- <p class="note">安装后重启 DSH;profile 内所有会话都会出现 5 个工具。首次进入某个项目时,先调用 <code>ai_init</code>(或把 <code>autoInit</code> 设为 <code>true</code>)生成 <code>.ai/</code> 与 <code>AGENTS.md</code>,之后按下面的动作循环。若包只进了依赖、未进 <code>dsh.profile.bundles</code>,需要手动补一行。</p>
1005
+ <p class="note">安装后重启 DSH;profile 内所有会话都会出现 7 个工具。首次进入某个项目时,先调用 <code>ai_init</code>(或把 <code>autoInit</code> 设为 <code>true</code>)生成 <code>.ai/</code> 与 <code>AGENTS.md</code>,之后按下面的动作循环。若包只进了依赖、未进 <code>dsh.profile.bundles</code>,需要手动补一行。</p>
946
1006
 
947
1007
  <div class="code-wrap">
948
1008
  <pre class="code powershell"><code><span class="c"># 开工:同步并读状态(约 10 秒)</span>
@@ -956,12 +1016,14 @@ dsh plugin --profile &lt;profile&gt; add "&lt;包绝对路径&gt;"</code></pre>
956
1016
  &amp; .ai\llm.cmd check</code></pre>
957
1017
  </div>
958
1018
 
959
- <div class="tools-chips" aria-label="五个原生工具">
1019
+ <div class="tools-chips" aria-label="七个原生工具">
960
1020
  <div class="toolchip"><b>ai_status</b><span>读状态与最近记录</span></div>
961
1021
  <div class="toolchip"><b>ai_log</b><span>追加一条记录</span></div>
962
1022
  <div class="toolchip"><b>ai_check</b><span>校验日志与状态</span></div>
963
1023
  <div class="toolchip"><b>ai_board</b><span>跨项目只读看板</span></div>
964
1024
  <div class="toolchip"><b>ai_init</b><span>幂等接入工作区</span></div>
1025
+ <div class="toolchip"><b>ai_discipline</b><span>纪律清单与开关</span></div>
1026
+ <div class="toolchip"><b>ai_handoff</b><span>跨会话交接摘要</span></div>
965
1027
  </div>
966
1028
 
967
1029
  <h3 class="subhead">常用命令</h3>
@@ -994,17 +1056,17 @@ dsh plugin --profile &lt;profile&gt; add "&lt;包绝对路径&gt;"</code></pre>
994
1056
  </div>
995
1057
  </section>
996
1058
 
997
- <!-- 08 -->
1059
+ <!-- 09 -->
998
1060
  <section class="sec" id="status">
999
- <p class="kicker"><span class="bar" aria-hidden="true"></span>08 · 边界与状态</p>
1061
+ <p class="kicker"><span class="bar" aria-hidden="true"></span>09 · 边界与状态</p>
1000
1062
  <h2>已发布,边界清晰</h2>
1001
- <p class="lead">0.4.4 已上 npm 并被社区插件市场收录;脚手架目前仅支持 Windows,只读工具与任务渲染本身与平台无关。</p>
1063
+ <p class="lead">0.6.0 已上 npm 并被社区插件市场收录;新增执行计划、检查清单、风险应对与跨项目仪表盘;脚手架目前仅支持 Windows,只读工具与任务渲染本身与平台无关。</p>
1002
1064
 
1003
1065
  <div class="release">
1004
1066
  <div class="rel">
1005
1067
  <div class="rel-top"><span>npm</span><span class="badge-ok">已发布</span></div>
1006
- <b>dsh-ai-collab@0.4.4</b>
1007
- <span>2026-11-20 上架,可直接安装</span>
1068
+ <b>dsh-ai-collab@0.6.0</b>
1069
+ <span>2026-11-27 上架,可直接安装</span>
1008
1070
  </div>
1009
1071
  <div class="rel">
1010
1072
  <div class="rel-top"><span>GitHub</span><span class="badge-ok">已就绪</span></div>
@@ -1023,6 +1085,30 @@ dsh plugin --profile &lt;profile&gt; add "&lt;包绝对路径&gt;"</code></pre>
1023
1085
  </div>
1024
1086
  </div>
1025
1087
 
1088
+ <h3 class="subhead">0.6.0 更新摘要</h3>
1089
+ <div class="rules">
1090
+ <div class="rule">
1091
+ <span class="rule-n">新</span>
1092
+ <div><h3>执行计划与任务管理</h3><p>新工具 <code>ai_plan</code>(show / set / done)将目标、检查清单、风险写入 <code>.ai/plan.json</code>;活跃风险自动合并到 <code>status.json</code> → <code>blockers</code>,每次 <code>ai_status</code> 都能看到。</p></div>
1093
+ </div>
1094
+ <div class="rule">
1095
+ <span class="rule-n">新</span>
1096
+ <div><h3>TASKS.md 三段式 + 可视化仪表盘</h3><p><code>TASKS.md</code> 现在分「当前计划 → 检查清单 → 风险日志 → 工作记录」四区,并同步生成 <code>TASKS.html</code>(与 <code>dashboard.html</code> 同 CSS 风格,自动色彩标记)。</p></div>
1097
+ </div>
1098
+ <div class="rule">
1099
+ <span class="rule-n">新</span>
1100
+ <div><h3>跨项目仪表盘</h3><p><code>F:\MyProject\.ai\dashboard.html</code> 扫描所有兄弟项目状态,有活动阻塞器的项目高亮红色,并附最近记录数量趋势条;每次 <code>ai_log</code> 自动刷新。</p></div>
1101
+ </div>
1102
+ <div class="rule">
1103
+ <span class="rule-n">改</span>
1104
+ <div><h3>路径整理与归档子目录</h3><p>项目根精简为 <code>AGENTS.md</code> + <code>TASKS.md</code> + <code>dsh-ai-collab.html</code>;其余统一收进 <code>.ai/docs/</code> <code>.ai/scripts/</code> <code>.ai/dist/</code>;AGENTS.md §6 索引已同步。</p></div>
1105
+ </div>
1106
+ <div class="rule">
1107
+ <span class="rule-n">测</span>
1108
+ <div><h3>验证</h3><p>39 个测试全通过;14 个新增覆盖规划 I/O、检查清单切换、风险合并、Markdown 与 HTML 渲染、项目扫描与仪表盘生成。</p></div>
1109
+ </div>
1110
+ </div>
1111
+
1026
1112
  <h3 class="subhead">兼容性</h3>
1027
1113
  <div class="table-wrap">
1028
1114
  <table>
@@ -1042,16 +1128,18 @@ dsh plugin --profile &lt;profile&gt; add "&lt;包绝对路径&gt;"</code></pre>
1042
1128
  <li><span class="lm">2</span><span><strong>尚未导出 Config schema。</strong>配置在进程内归一化,非法值写入 <code>ai-collab-config.log</code>,不会静默沿用。</span></li>
1043
1129
  <li><span class="lm">3</span><span><strong>旧 AGENTS.md 被冻结。</strong>无分区标记的文件不会自动升级,需显式 <code>-ForceAgents</code> 或 <code>-ResetAgents</code>。</span></li>
1044
1130
  <li><span class="lm">4</span><span><strong>看板依赖目录布局。</strong>仅当兄弟项目共享父级 <code>.ai\board.md</code> 时生成跨项目看板。</span></li>
1045
- <li><span class="lm">5</span><span><strong>生效时机不同。</strong>插件代码改动需重启 DSH;全局 <code>AGENTS.md</code> 编辑对下一次请求立即生效。</span></li>
1131
+ <li><span class="lm">5</span><span><strong>生效时机不同。</strong>插件代码改动需重启 DSH;全局 <code>AGENTS.md</code> 编辑对下一次请求立即生效;项目 §8 纪律清单在下次 <code>ai-ensure</code> 渲染时刷新。</span></li>
1132
+ <li><span class="lm">6</span><span><strong>全局纪律只能整体开关。</strong>停用/启用会重渲染 <code>$DSH_HOME/AGENTS.md</code>,且必须先 <code>global-migrate</code>;不能只对某个项目停用某节全局纪律。</span></li>
1133
+ <li><span class="lm">7</span><span><strong>锁是协作式的。</strong>插件与 <code>.ai/llm.cmd</code> 遵守同一套锁协议;外部编辑器直接改文件仍可能绕过。单个项目日志建议不超过 2 MB 并及时 <code>archive</code>。</span></li>
1046
1134
  </ul>
1047
1135
 
1048
1136
  <p class="roadmap"><b>下一步:</b>跨平台 Node 脚手架 · 导出 Config schema。市场详情页:<a href="https://awesome-dsh-plugin.com/p/ZhuYw3927/dsh-ai-collab/" target="_blank" rel="noopener">awesome-dsh-plugin.com/p/ZhuYw3927/dsh-ai-collab</a></p>
1049
1137
  </section>
1050
1138
 
1051
- <!-- 09 -->
1139
+ <!-- 10 -->
1052
1140
  <section class="sec" id="summary">
1053
1141
  <div class="closing">
1054
- <p class="kicker"><span class="bar" aria-hidden="true"></span>09 · 结语</p>
1142
+ <p class="kicker"><span class="bar" aria-hidden="true"></span>10 · 结语</p>
1055
1143
  <h2>它不发明新的工作流,只是让「交底、记账、校验」留在仓库里。</h2>
1056
1144
  <p>于是工具可以换、会话可以断、维护者可以更替,而项目的进度与判断依据不会丢。这就是 dsh-ai-collab 的全部野心:把一次性的会话成本,变成可继承的项目资产。</p>
1057
1145
  <div class="closing-chips">
@@ -1065,7 +1153,7 @@ dsh plugin --profile &lt;profile&gt; add "&lt;包绝对路径&gt;"</code></pre>
1065
1153
 
1066
1154
  <footer class="site-footer">
1067
1155
  <div class="foot-inner">
1068
- <div>本文基于项目 <code>AGENTS.md</code>、<code>dsh-ai-collab.md</code>、插件 README 与发布记录整理 · 2026-11-20 · 对应版本 0.4.4</div>
1156
+ <div>本文基于项目 <code>AGENTS.md</code>、<code>dsh-ai-collab.md</code>、插件 README 与发布记录整理 · 2026-11-27 · 对应版本 0.6.0</div>
1069
1157
  <div class="foot-links">
1070
1158
  <a href="https://www.npmjs.com/package/dsh-ai-collab" target="_blank" rel="noopener">npm</a>
1071
1159
  <a href="https://github.com/ZhuYw3927/dsh-ai-collab" target="_blank" rel="noopener">GitHub</a>
package/index.js CHANGED
@@ -9,13 +9,23 @@
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'
13
- import { join, dirname } from 'node:path'
12
+ import { existsSync, mkdirSync, appendFileSync, readFileSync, readdirSync, renameSync, statSync, rmSync, writeFileSync } from 'node:fs'
13
+ import { join, dirname, basename } 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'
27
+ import { activeRiskTitles, doneChecklistItem, PLAN_STATUSES, CHECKLIST_STATUSES, readPlan, setBlock, writePlan } from './lib/plan.js'
28
+ import { writeDashboard } from './lib/dashboard.js'
19
29
 
20
30
  export const name = 'ai-collab'
21
31
  // Only `tools` is required. `workingDirectory` is used when present
@@ -183,22 +193,38 @@ function appendRecord(root, input) {
183
193
  const errors = recordErrors(rec, 0)
184
194
  if (errors.length > 0) throw new Error(`记录校验失败,未写入: ${errors.join('; ')}`)
185
195
 
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))]
196
+ // One writer at a time per project: append + status read-modify-write must be
197
+ // a unit, otherwise two sessions overwrite each other's status fields.
198
+ const lockPath = join(aiDir(root), '.log.lock')
199
+ return withLock(lockPath, () => {
200
+ mkdirSync(aiDir(root), { recursive: true })
201
+ appendFileSync(logPath(root), JSON.stringify(rec) + '\n', 'utf8')
202
+
203
+ const st = readJson(statusPath(root))
204
+ if (st) {
205
+ st.rev = Number.isInteger(st.rev) ? st.rev + 1 : 1
206
+ st.last_log_ts = rec.ts
207
+ st.last_log_id = rec.id
208
+ st.updated_at = nowIso()
209
+ if (rec.next) st.next = [rec.next]
210
+ if (rec.status === 'blocked' || rec.status === 'failed') {
211
+ const list = Array.isArray(st.blockers) ? st.blockers : []
212
+ st.blockers = [...new Set([rec.issue, ...list].filter(Boolean))]
213
+ }
214
+ // 将 plan.json 的 active 风险标题合并进 blockers(轻联动,去重)
215
+ try {
216
+ const titles = activeRiskTitles(readPlan(root))
217
+ if (titles.length > 0) {
218
+ const current = new Set((Array.isArray(st.blockers) ? st.blockers : []).filter((b) => !titles.includes(b)))
219
+ for (const t of titles) current.add(t)
220
+ const merged = [...current]
221
+ if (JSON.stringify(merged) !== JSON.stringify(st.blockers)) st.blockers = merged
222
+ }
223
+ } catch { /* plan.json 不可读时不阻塞状态更新 */ }
224
+ writeFileAtomic(statusPath(root), JSON.stringify(st, null, 2) + '\n')
198
225
  }
199
- try { writeFileSync(statusPath(root), JSON.stringify(st, null, 2) + '\n', 'utf8') } catch { /* 状态刷新失败不影响日志 */ }
200
- }
201
- return rec
226
+ return rec
227
+ })
202
228
  }
203
229
 
204
230
  function spawnEnsure(root, config, extraArgs = []) {
@@ -252,30 +278,49 @@ function recentlyRefreshed(root, key, windowMs) {
252
278
  return false
253
279
  }
254
280
 
255
- // 写日志后顺带刷新看板(仅当上级目录已有 .ai\board.md;走包内 ai-ensure,不执行工作区脚本)
281
+ // 写日志后顺带刷新看板 + 仪表盘(仅当上级目录已有 .ai\board.md;走包内 ai-ensure,不执行工作区脚本)
256
282
  function maybeRefreshBoard(root) {
257
283
  try {
258
284
  if (!existsSync(join(dirname(root), '.ai', 'board.md'))) return
259
285
  if (recentlyRefreshed(root, 'board', 3000)) return
260
286
  spawnEnsure(root, {}, ['-NoAgents'])
287
+ // 仪表盘与看板同频刷新(3s 节流,不阻塞记录写入)
288
+ try { writeDashboard(root) } catch (e) { appendLog('ai-collab-dashboard.log', `root=${root} throw ${e?.message || e}`) }
261
289
  } catch { /* 看板刷新失败不影响记录 */ }
262
290
  }
263
291
 
264
292
  /**
265
- * 写日志后刷新任务清单(仅当 .ai\tasks-enabled 存在)。
293
+ * 写日志后刷新任务清单(TASKS.md + TASKS.html + PLAN.md)。
294
+ * 首次触发时自动创建 .ai\tasks-enabled(不再需要手动开)。
266
295
  * 进程内渲染:不执行工作区自带的 .ai/llm.ps1,避免仓库脚本被插件执行。
267
296
  */
268
297
  function refreshTasks(root) {
269
298
  try {
270
- if (!existsSync(join(root, '.ai', 'tasks-enabled'))) return
271
- const { written, count } = writeTasks(root, nowIso())
272
- if (!written) return
273
- if (count === 0) appendLog('ai-collab-tasks.log', `root=${root} count=0`)
299
+ const marker = join(root, '.ai', 'tasks-enabled')
300
+ if (!existsSync(marker)) mkdirSync(marker, { recursive: true })
301
+ const st = readJson(statusPath(root))
302
+ const projectName = (st && st.project) || basename(root)
303
+ const result = withLock(join(root, '.ai', '.tasks.lock'), () => writeTasks(root, nowIso(), projectName))
304
+ if (!result.written) return
305
+ if (result.count === 0) appendLog('ai-collab-tasks.log', `root=${root} count=0`)
274
306
  } catch (error) {
275
307
  appendLog('ai-collab-tasks.log', `root=${root} throw ${error?.message || error}`)
276
308
  }
277
309
  }
278
310
 
311
+ /**
312
+ * Rebuild `.ai\SESSION_BOOT.md` after every record. It is derived data
313
+ * (status + last N records), so a stale boot file is worse than a small write.
314
+ */
315
+ function refreshSessionBoot(root) {
316
+ try {
317
+ if (!existsSync(join(root, '.ai'))) return
318
+ writeSessionBoot(root, { maxTail: 10 })
319
+ } catch (error) {
320
+ appendLog('ai-collab-handoff.log', `root=${root} throw ${error?.message || error}`)
321
+ }
322
+ }
323
+
279
324
  // ---------------------------------------------------------------- plugin
280
325
 
281
326
  export function apply(ctx, config = {}) {
@@ -311,6 +356,11 @@ export function apply(ctx, config = {}) {
311
356
  const result = spawnEnsure(root, opts)
312
357
  if (result.done) {
313
358
  const finished = await result.done
359
+ if (finished.ok) {
360
+ try { writeSessionBoot(root, { maxTail: opts.maxTail }) } catch (error) {
361
+ appendLog('ai-collab-handoff.log', `autoInit root=${root} throw ${error?.message || error}`)
362
+ }
363
+ }
314
364
  ctx.logger?.info?.('ai-collab autoInit', { root, ok: finished.ok, parsed: parseEnsureOutput(finished.out) })
315
365
  }
316
366
  } catch (error) {
@@ -387,6 +437,19 @@ function registerTools(ctx, opts, defineTool, spec) {
387
437
  // DSH 契约:output.render 必须返回内容块数组;schema 用值 schema DSL 的 json 节点
388
438
  const output = { schema: { type: 'json' }, render: (args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }] }
389
439
 
440
+ /** Re-render AGENTS.md §8 (and the boot file) after a discipline change. */
441
+ const resyncProject = async (root) => {
442
+ if (!SCAFFOLD_SUPPORTED) return { started: false, reason: `unsupported-platform: ${process.platform}` }
443
+ const handle = spawnEnsure(root, opts, ['-Force'])
444
+ if (!handle.started) return { started: false, reason: handle.reason }
445
+ const finished = await handle.done
446
+ let boot = null
447
+ try { boot = writeSessionBoot(root, { maxTail: opts.maxTail }) } catch (error) {
448
+ boot = { ok: false, error: String(error?.message || error) }
449
+ }
450
+ return { started: true, exit: finished.code ?? null, ok: finished.ok === true, result: parseEnsureOutput(finished.out), boot }
451
+ }
452
+
390
453
  registered.push('ai_status')
391
454
  ctx.tools.register(defineTool({
392
455
  name: 'ai_status',
@@ -426,6 +489,7 @@ function registerTools(ctx, opts, defineTool, spec) {
426
489
  const r = await rootOf(exec)
427
490
  const rec = appendRecord(r, args)
428
491
  refreshTasks(r)
492
+ refreshSessionBoot(r)
429
493
  maybeRefreshBoard(r)
430
494
  return rec
431
495
  }
@@ -455,6 +519,11 @@ function registerTools(ctx, opts, defineTool, spec) {
455
519
  }
456
520
  })
457
521
  if (!readJson(statusPath(r))) errors.push('status.json 缺失或不可解析')
522
+ try {
523
+ for (const drift of auditProject(r, readText(join(r, 'AGENTS.md')))) errors.push(`§8 漂移: ${drift}`)
524
+ } catch (error) {
525
+ errors.push(`§8 审计失败: ${error?.message || error}`)
526
+ }
458
527
  return { root: r, records: readLines(logPath(r)).length, errors }
459
528
  }
460
529
  }))
@@ -512,10 +581,193 @@ function registerTools(ctx, opts, defineTool, spec) {
512
581
  }
513
582
  if (finished.err) payload.stderr = finished.err.slice(0, 500)
514
583
  if (finished.error) payload.error = finished.error
584
+ if (finished.ok) {
585
+ try { payload.boot = writeSessionBoot(target, { maxTail: opts.maxTail }) } catch (error) {
586
+ payload.boot = { ok: false, error: String(error?.message || error) }
587
+ }
588
+ }
515
589
  return payload
516
590
  }
517
591
  }))
518
592
 
593
+ registered.push('ai_discipline')
594
+ ctx.tools.register(defineTool({
595
+ name: 'ai_discipline',
596
+ description: '纪律清单:列出/新增/启用/停用/删除项目纪律(渲染进 AGENTS.md §8),或管理全局纪律模块(重写 $DSH_HOME\\AGENTS.md,自动备份)。',
597
+ parameters: {
598
+ action: {
599
+ type: 'string', required: true,
600
+ enum: [
601
+ 'list', 'add', 'enable', 'disable', 'remove',
602
+ 'global-list', 'global-migrate', 'global-add', 'global-enable', 'global-disable', 'global-remove',
603
+ ],
604
+ description: '项目动作直接改 .ai\\disciplines\\ 并重渲染 §8;global-* 动作改 $DSH_HOME\\disciplines\\ 并重写全局 AGENTS.md。',
605
+ },
606
+ id: { type: 'string', description: '纪律 id(2–41 位小写字母/数字/连字符)' },
607
+ title: { type: 'string', description: 'add / global-add 的标题' },
608
+ body: { type: 'string', description: 'add / global-add 的规则正文(Markdown)' },
609
+ priority: { type: 'number', description: '排序权重,越小越靠前' },
610
+ force: { type: 'boolean', description: 'global-migrate 时重建已存在的模块(先备份)' },
611
+ root: { type: 'string', description: '目标工作区,缺省为会话 cwd' },
612
+ },
613
+ output,
614
+ async execute(args, exec) {
615
+ const action = String(args?.action || '')
616
+ const r = args?.root ? String(args.root) : await rootOf(exec)
617
+ const id = String(args?.id || '').trim()
618
+
619
+ if (action === 'list') {
620
+ let counts = null
621
+ try { counts = renderProjectSection(r).counts } catch { /* 注册表不可读时只返回原始列表 */ }
622
+ return { root: r, ...listProject(r), counts }
623
+ }
624
+
625
+ // ---------- project rules ----------
626
+ if (['add', 'enable', 'disable', 'remove'].includes(action)) {
627
+ const registry = normaliseRegistry(readJson(projectRegistryPath(r)) ?? {}, 'project')
628
+ const rules = registry.rules
629
+ let target = null
630
+ if (action === 'add') {
631
+ if (!ID_RE.test(id)) throw new Error('id 必须为 2–41 位小写字母/数字/连字符')
632
+ if (!String(args?.title ?? '').trim()) throw new Error('add 需要 title')
633
+ if (!String(args?.body ?? '').trim()) throw new Error('add 需要 body')
634
+ if (rules.some((x) => x.id === id)) throw new Error(`项目纪律已存在: ${id}`)
635
+ mkdirSync(projectRulesDir(r), { recursive: true })
636
+ writeFileAtomic(join(projectRulesDir(r), `${id}.md`), `${String(args.body).trim()}\n`)
637
+ target = {
638
+ id, title: String(args.title).trim(), enabled: true,
639
+ priority: Number.isFinite(Number(args?.priority)) ? Number(args.priority) : rules.length * 10,
640
+ file: `${id}.md`, description: '',
641
+ }
642
+ rules.push(target)
643
+ } else {
644
+ target = rules.find((x) => x.id === id)
645
+ if (!target) throw new Error(`项目纪律不存在: ${id}`)
646
+ if (action === 'remove') {
647
+ const src = join(projectRulesDir(r), target.file)
648
+ if (existsSync(src)) {
649
+ const destDir = join(projectDir(r), '_archive')
650
+ mkdirSync(destDir, { recursive: true })
651
+ renameSync(src, join(destDir, `${id}.${Date.now()}.md`))
652
+ }
653
+ registry.rules = rules.filter((x) => x.id !== id)
654
+ } else {
655
+ target.enabled = action === 'enable'
656
+ }
657
+ }
658
+ writeFileAtomic(projectRegistryPath(r), `${JSON.stringify(registry, null, 2)}\n`)
659
+ const sync = await resyncProject(r)
660
+ return { ok: true, action, id, rule: target, sync }
661
+ }
662
+
663
+ // ---------- global modules ----------
664
+ if (action === 'global-list') {
665
+ const state = loadGlobal()
666
+ return {
667
+ root: r,
668
+ home: state.dir,
669
+ agents: state.agentsPath,
670
+ generated: state.generated,
671
+ 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 })),
672
+ }
673
+ }
674
+ if (action === 'global-migrate') {
675
+ return { ok: true, ...migrateGlobal({ force: args?.force === true }) }
676
+ }
677
+ if (action === 'global-add') {
678
+ const module = addGlobalModule({ id, title: args?.title, body: args?.body, priority: args?.priority })
679
+ return { ok: true, module, render: renderGlobalFile() }
680
+ }
681
+ if (action === 'global-enable' || action === 'global-disable') {
682
+ const module = setGlobalEnabled(id, action === 'global-enable')
683
+ return { ok: true, module: { id: module.id, title: module.title, enabled: module.enabled }, render: renderGlobalFile() }
684
+ }
685
+ if (action === 'global-remove') {
686
+ const removed = removeGlobalModule({ id })
687
+ return { ok: true, removed: { id: removed.id, title: removed.title }, render: renderGlobalFile() }
688
+ }
689
+ throw new Error(`未知 action: ${action}`)
690
+ }
691
+ }))
692
+
693
+ registered.push('ai_handoff')
694
+ ctx.tools.register(defineTool({
695
+ name: 'ai_handoff',
696
+ description: '跨会话交接:生成/读取 .ai/SESSION_BOOT.md(接棒提示词,含必读顺序、当前状态、最近记录、纪律清单与继承摘要要求)。',
697
+ parameters: {
698
+ action: { type: 'string', enum: ['read', 'write', 'inherit'], description: 'read 只返回内容;write 重新生成;inherit 生成并返回给新会话的提示语' },
699
+ maxTail: { type: 'number', description: '摘录最近多少条记录(默认 10,最大 50)' },
700
+ root: { type: 'string', description: '目标工作区,缺省为会话 cwd' },
701
+ },
702
+ output,
703
+ async execute(args, exec) {
704
+ const r = args?.root ? String(args.root) : await rootOf(exec)
705
+ const action = String(args?.action || 'read')
706
+ const maxTail = Number.isFinite(Number(args?.maxTail)) ? Number(args.maxTail) : opts.maxTail
707
+ let boot = null
708
+ if (action !== 'read') boot = writeSessionBoot(r, { maxTail })
709
+ const packet = buildHandoff(r, { maxTail })
710
+ const payload = { action, root: r, boot, packet }
711
+ if (action === 'read' || action === 'inherit') {
712
+ const bootPath = join(r, '.ai', 'SESSION_BOOT.md')
713
+ // read 必须返回可用的接棒提示词:文件缺失时先生成一次
714
+ if (!existsSync(bootPath)) boot = writeSessionBoot(r, { maxTail })
715
+ payload.content = readText(bootPath)
716
+ }
717
+ if (action === 'inherit') payload.prompt = inheritPrompt(r)
718
+ return payload
719
+ }
720
+ }))
721
+
722
+ registered.push('ai_plan')
723
+ ctx.tools.register(defineTool({
724
+ name: 'ai_plan',
725
+ description: '管理执行计划、检查清单与风险应对:数据存 .ai\\plan.json,渲染产物 .ai\\PLAN.md + TASKS.md + TASKS.html。show / set <plan|checklist|risks> / done <checklist-id>。',
726
+ parameters: {
727
+ action: { type: 'string', required: true, enum: ['show', 'set', 'done'], description: 'show 返回当前计划;set 覆盖 plan/checklist/risks 其中一块(传 key+items);done 勾选一条清单项' },
728
+ key: { type: 'string', description: 'set 时必填:plan / checklist / risks' },
729
+ items: { type: 'array', items: { type: 'json' }, description: 'set 时的项数组(JSON 对象列表)' },
730
+ id: { type: 'string', description: 'done 时的清单项 id' },
731
+ root: { type: 'string', description: '目标工作区,缺省为会话 cwd' },
732
+ },
733
+ output,
734
+ async execute(args, exec) {
735
+ const r = args?.root ? String(args.root) : await rootOf(exec)
736
+ const action = String(args?.action || 'show')
737
+ const now = nowIso()
738
+
739
+ if (action === 'show') {
740
+ const plan = readPlan(r)
741
+ return { root: r, plan, hasPlan: plan.plan.length > 0 || plan.checklist.length > 0 || plan.risks.length > 0 }
742
+ }
743
+
744
+ if (action === 'set') {
745
+ const key = String(args?.key || '')
746
+ const items = Array.isArray(args?.items) ? args.items : []
747
+ const result = setBlock(r, key, items, now)
748
+ refreshTasks(r)
749
+ maybeRefreshBoard(r)
750
+ return { root: r, ok: true, key, count: (result[key] || []).length, updated_at: result.updated_at }
751
+ }
752
+
753
+ if (action === 'done') {
754
+ const id = String(args?.id || '')
755
+ const { plan, item } = doneChecklistItem(r, id, now)
756
+ const rec = appendRecord(r, {
757
+ tool: 'ai_plan', action: 'task_done', status: 'ok',
758
+ summary: `清单项完成: ${item.item}`,
759
+ tags: ['plan', 'checklist'],
760
+ })
761
+ refreshTasks(r)
762
+ refreshSessionBoot(r)
763
+ maybeRefreshBoard(r)
764
+ return { root: r, ok: true, id, item, record: rec.id, plan: { ...plan, plan: undefined, checklist: undefined, risks: undefined } }
765
+ }
766
+
767
+ throw new Error(`未知 action: ${action}`)
768
+ }
769
+ }))
770
+
519
771
  logToolRegistration(registered, spec)
520
772
  }
521
773