dsh-punky-swarm 0.3.6

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.
Files changed (101) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/LICENSE +661 -0
  3. package/README.en.md +281 -0
  4. package/README.md +281 -0
  5. package/cordis.patch.yml +59 -0
  6. package/lib/acps/certs.js +310 -0
  7. package/lib/acps/discovery-client.js +283 -0
  8. package/lib/acps/registry-client.js +527 -0
  9. package/lib/acps/server.js +302 -0
  10. package/lib/aip/agent-descriptor.js +170 -0
  11. package/lib/aip/identity.js +469 -0
  12. package/lib/aip/tool-descriptor.js +93 -0
  13. package/lib/api.js +266 -0
  14. package/lib/artifact-types.js +48 -0
  15. package/lib/assembly/audit-blind-review.js +170 -0
  16. package/lib/assembly/schema.js +253 -0
  17. package/lib/assembly.js +41 -0
  18. package/lib/assets.js +103 -0
  19. package/lib/bridge/trajectory.js +202 -0
  20. package/lib/client.js +704 -0
  21. package/lib/comms/acps-bridge.js +219 -0
  22. package/lib/comms/aip-format.js +141 -0
  23. package/lib/comms/budget.js +124 -0
  24. package/lib/comms/mailbox.js +221 -0
  25. package/lib/comms/topic-runtime.js +76 -0
  26. package/lib/comms/topic.js +115 -0
  27. package/lib/discovery/filter.js +199 -0
  28. package/lib/discovery/schema.js +157 -0
  29. package/lib/discovery/service.js +251 -0
  30. package/lib/hot/config-watch.js +252 -0
  31. package/lib/index.js +433 -0
  32. package/lib/lock.js +69 -0
  33. package/lib/panel/batch-detail.js +163 -0
  34. package/lib/panel/batch-list.js +84 -0
  35. package/lib/panel/locales.js +93 -0
  36. package/lib/panel/main.js +270 -0
  37. package/lib/panel/stream.js +348 -0
  38. package/lib/panel/theme.js +103 -0
  39. package/lib/panel/widgets.js +63 -0
  40. package/lib/schema.d.ts +192 -0
  41. package/lib/schema.js +259 -0
  42. package/lib/schema.ts +398 -0
  43. package/lib/state/archive.js +174 -0
  44. package/lib/state/command-exec.js +148 -0
  45. package/lib/state/constants.js +37 -0
  46. package/lib/state/corrupt-registry.js +103 -0
  47. package/lib/state/event-types.js +65 -0
  48. package/lib/state/gates.d.ts +226 -0
  49. package/lib/state/gates.js +428 -0
  50. package/lib/state/gates.ts +348 -0
  51. package/lib/state/machine-rules.d.ts +14 -0
  52. package/lib/state/machine-rules.js +76 -0
  53. package/lib/state/machine-rules.ts +88 -0
  54. package/lib/state/machine.js +68 -0
  55. package/lib/state/resume.js +201 -0
  56. package/lib/state/schema-v3.d.ts +10 -0
  57. package/lib/state/schema-v3.js +57 -0
  58. package/lib/state/schema-v3.ts +80 -0
  59. package/lib/state/store.js +607 -0
  60. package/lib/state/task-utils.js +40 -0
  61. package/lib/tools/core.js +323 -0
  62. package/lib/tools/git-utils.js +44 -0
  63. package/lib/tools/lane-tools.js +455 -0
  64. package/lib/tools/log-tools.js +173 -0
  65. package/lib/tools/mailbox-tools.js +121 -0
  66. package/lib/tools/merge-agent.js +127 -0
  67. package/lib/tools/register.js +85 -0
  68. package/lib/tools/shared.js +32 -0
  69. package/lib/types/contracts.d.ts +277 -0
  70. package/lib/types/contracts.js +17 -0
  71. package/lib/types/contracts.ts +279 -0
  72. package/lib/verify/evidence.js +249 -0
  73. package/lib/verify/gate.js +161 -0
  74. package/lib/verify/mount.js +48 -0
  75. package/lib/verify/selector.js +101 -0
  76. package/lib/watch/lane-heartbeat.js +333 -0
  77. package/lib/wave-plan.d.ts +48 -0
  78. package/lib/wave-plan.js +473 -0
  79. package/lib/wave-plan.ts +465 -0
  80. package/package.json +71 -0
  81. package/presets/jiufeng/NOTICE +5 -0
  82. package/presets/jiufeng/agent.cordis.yml +275 -0
  83. package/presets/jiufeng/preset.yml +3 -0
  84. package/skills/jiufeng-team/SKILL.md +214 -0
  85. package/skills/jiufeng-team/references/constitution.md +62 -0
  86. package/skills/jiufeng-team/references/roles/coder.md +17 -0
  87. package/skills/jiufeng-team/references/roles/coordinator.md +13 -0
  88. package/skills/jiufeng-team/references/roles/designer.md +14 -0
  89. package/skills/jiufeng-team/references/roles/doc-manager.md +13 -0
  90. package/skills/jiufeng-team/references/roles/manager.md +22 -0
  91. package/skills/jiufeng-team/references/roles/reviewer.md +19 -0
  92. package/skills/jiufeng-team/references/roles/supervisor.md +13 -0
  93. package/skills/jiufeng-team/references/roles/tester.md +13 -0
  94. package/skills/jiufeng-team/references/templates/call-chain-matrix-template.md +121 -0
  95. package/skills/jiufeng-team/references/templates/endpoint-behavior-template.md +60 -0
  96. package/skills/jiufeng-team/references/templates/gap-list.json +33 -0
  97. package/skills/jiufeng-team/references/templates/leader-decision-pack.md +92 -0
  98. package/skills/jiufeng-team/references/templates/plan-template.md +61 -0
  99. package/skills/jiufeng-team/references/templates/success-pattern-seeds.md +126 -0
  100. package/skills/jiufeng-team/references/workflow.md +98 -0
  101. package/skills/jiufeng-team/scripts/check-v3-density.mjs +98 -0
package/lib/index.js ADDED
@@ -0,0 +1,433 @@
1
+ /*
2
+ Copyright (C) 2025-2026 Punky
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Affero General Public License as
6
+ published by the Free Software Foundation, either version 3 of the
7
+ License, or (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Affero General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Affero General Public License
15
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ // dsh-punky-swarm 插件入口:蟛蜞模式集群治理引擎(leader-member 治理)
19
+ // v2:批次绑定 session(root/sessions/<sessionId>/...);存量 root/batches 自动迁移到 legacy
20
+ import { join } from 'node:path';
21
+ import { homedir } from 'node:os';
22
+ import { mkdirSync, existsSync, readdirSync } from 'node:fs';
23
+ import { createStore } from './state/store.js';
24
+ import { createTools } from './tools/register.js';
25
+ import { createApi } from './api.js';
26
+ import { syncAssets } from './assets.js';
27
+ import { createTrajectoryBridge, isTrajectoryEnabled } from './bridge/trajectory.js';
28
+ import { createLaneHeartbeat } from './watch/lane-heartbeat.js';
29
+ import { resolveWatchConfig, resolveDiscoveryConfig, resolveAcpsDiscoveryConfig, resolveAcpsConfig } from './schema.js';
30
+ import { validateCapabilities, readCapability } from './assembly/schema.js';
31
+ import { createDiscoveryService } from './discovery/service.js';
32
+ import { createAcpsDiscoveryClient } from './acps/discovery-client.js';
33
+ import { buildAgentDescriptors } from './aip/agent-descriptor.js';
34
+ import { engineVersion } from './aip/tool-descriptor.js';
35
+ import { DEFAULT_ASSEMBLY } from './assembly.js';
36
+ import { mountVerify } from './verify/mount.js';
37
+ import { mountBridge, createEndpointRpcHandler } from './comms/acps-bridge.js';
38
+ import { createRegistryClient, resolveRegistryConfig } from './acps/registry-client.js';
39
+ import { createAcpsServer } from './acps/server.js';
40
+ import * as mailbox from './comms/mailbox.js';
41
+ // R1 热更新运行时(lib/hot/config-watch.js,新建):<root>/config/runtime.json watch → deepMerge 快照 → config.changed 广播
42
+ import { createConfigWatcher, CONFIG_CHANGED_EVENT } from './hot/config-watch.js';
43
+ // R2 topic 运行时(lib/comms/topic-runtime.js,新建):装配面 start/stop(与 trajectory 桥同形)+ 状态事件发布接线
44
+ import { createTopicRuntime } from './comms/topic-runtime.js';
45
+ // M1 闭合(panel-verify §3 修复指引):R3 SSE hub(lib/panel/stream.js)由装配层创建注入 api.js(deps.panelStream),
46
+ // topic.enabled 时经 hub.attachTopic('swarm.') 订阅低延迟触发源(subscribeTopicPrefix → parseTopicIds → notifyAll)
47
+ import { createStreamHub } from './panel/stream.js';
48
+ // P1-02 接线:启动恢复经 resume 模块(恢复 running/review 而非一律 idle;config.resume.enabled 缺省关 →
49
+ // 内部原样委托 store.recoverBatches(),零行为变化)
50
+ import { recoverBatches as resumeRecoverBatches, resolveResumeConfig } from './state/resume.js';
51
+
52
+ export const name = 'dsh-punky-swarm';
53
+ export const inject = ['tools', 'webServer'];
54
+
55
+ // 恢复语义:每个进程只执行一次(无论插件按进程级还是会话级挂载)
56
+ let recoveredThisProcess = false;
57
+
58
+ export const apply = (ctx, config = {}) => {
59
+ const rawRoot = config.root ?? '~/.dsh/jiufeng';
60
+ const root = rawRoot.startsWith('~') ? join(homedir(), rawRoot.slice(1)) : rawRoot;
61
+ mkdirSync(root, { recursive: true });
62
+ // 启动日志:引擎产物根(诊断可见性——worker/Leader 产物落盘契约的权威路径)
63
+ ctx.logger?.info?.('[dsh-punky-swarm] engine root: ' + root + ';产物根 = <root>/sessions/<sessionId>/artifacts/<batchId>/');
64
+
65
+ // 配置校验兜底:仅 warn 不炸宿主——validateCapabilities 仅对显式
66
+ // enabled 的非法组合报错;禁用能力零校验零 warn;空/缺省 config → errors=[] → 零 warn
67
+ for (const err of validateCapabilities(config).errors) {
68
+ ctx.logger?.warn?.('[dsh-punky-swarm] config: ' + err);
69
+ }
70
+
71
+ // R2 topic 发布钩子容器:store 状态事件 → topic 运行时(装配点写入 emit;默认关零路径)
72
+ const topicSink = { emit: null };
73
+ const store = createStore(root, {
74
+ // R2 topic 发布钩子(store 状态事件 → topic 运行时):topic 默认关 → emit=null → 零行为变化;
75
+ // enabled 时装配点注入 emitTopic 发布(setMember/setPhase 调用点埋点,appendEvent 闭包不可外部 wrap)
76
+ onStateChange: (ev) => { try { topicSink.emit?.(ev); } catch { /* 隔离:topic 发布失败不阻断状态机 */ } },
77
+ });
78
+
79
+ // P2-04:GATE_ENABLED=false 逃生阀启动级留痕——gates.js checkCommandGate/checkTargetsGate 命中逃生阀时
80
+ // 内部静默返回零感知({ ok:true, declared:false },行为语义不变),装配侧在此检测并落启动级 warn,
81
+ // 保证「门禁被禁用」状态可查(审计/排障经启动日志即可见,无需翻 gates.js 源码)。
82
+ if (String(process.env.GATE_ENABLED).toLowerCase() === 'false') {
83
+ ctx.logger?.warn?.('[dsh-punky-swarm] GATE_ENABLED=false: 命令门禁/targets 门禁整体放行(应急逃生阀,零感知语义),禁用状态已留痕于启动日志');
84
+ }
85
+
86
+ // mailbox 周期 sweep 定时器(④,config.mailbox.sweepIntervalMs>0 时挂载;默认 0=关,零隐式行为)——提升到 apply 作用域供 disposer 清理
87
+ let sweepTimer = null;
88
+
89
+ // 存量迁移:root/batches/*.json -> sessions/legacy/batches/(仅一次,幂等)
90
+ if (!recoveredThisProcess) {
91
+ try {
92
+ const moved = store.migrateLegacy();
93
+ if (moved) ctx.logger?.info?.('[dsh-punky-swarm] migrated ' + moved + ' legacy batch(es) to sessions/legacy');
94
+ } catch (e) {
95
+ ctx.logger?.warn?.('[dsh-punky-swarm] legacy migration failed: ' + String(e));
96
+ }
97
+ // 资产同步:预设(~/.dsh/.agent-presets/jiufeng)与技能(~/.agents/skills/jiufeng-team),幂等,参照 dsh-liangshen
98
+ try {
99
+ for (const r of syncAssets()) {
100
+ if (r.status === 'synced') ctx.logger?.info?.('[dsh-punky-swarm] asset synced: ' + r.asset);
101
+ else if (r.status === 'failed') ctx.logger?.warn?.('[dsh-punky-swarm] asset sync failed: ' + r.asset + ': ' + r.error);
102
+ }
103
+ } catch (e) {
104
+ ctx.logger?.warn?.('[dsh-punky-swarm] asset sync failed: ' + String(e));
105
+ }
106
+ }
107
+
108
+ // 启动恢复:in-flight 成员 -> idle + system.recovered(每个进程仅一次,跨全部 session)
109
+ // P1-02 接线:改调 resume.recoverBatches(store, { restoreRunning: resumeCfg.enabled })——
110
+ // config.resume.enabled 缺省关 → 内部委托 store.recoverBatches()(原路径零行为变化);
111
+ // 开启 → restoreBatches()(running/review 原地保留 + system.restored 事件)。返回数组形态
112
+ // .length/.corrupt 兼容既有日志消费。
113
+ if (!recoveredThisProcess) {
114
+ recoveredThisProcess = true;
115
+ try {
116
+ const resumeCfg = resolveResumeConfig(config);
117
+ const r = resumeRecoverBatches(store, { restoreRunning: resumeCfg.enabled });
118
+ if (r.length) ctx.logger?.info?.('[dsh-punky-swarm] recovered batches: ' + r.join(', '));
119
+ // 恢复容错汇总(v2-node-robustness ②):损坏批次被隔离(corrupt-batches.json + 跳过),不阻断其余恢复
120
+ if (Array.isArray(r.corrupt) && r.corrupt.length) {
121
+ ctx.logger?.warn?.('[dsh-punky-swarm] isolated ' + r.corrupt.length + ' corrupt batch(es): ' + r.corrupt.join(', ') + '(人工修复/删除后 clearCorruptMark)');
122
+ }
123
+ } catch (e) {
124
+ ctx.logger?.warn?.('[dsh-punky-swarm] recovery failed: ' + String(e));
125
+ }
126
+
127
+ // mailbox 启动清扫(④,D-006/sweepOnStart 默认 true):recoverBatches 之后逐批次 mailbox 根 sweep 一次——
128
+ // 清 ack 超 TTL 消息+标记 / 损坏消息 quarantine / 孤儿 .acked(默认 TTL 7d、quarantine 30d)。
129
+ // 失败仅 warn 不阻塞启动;幂等可重入(sweep 无状态全量扫描)。
130
+ const mailCfg = config?.mailbox ?? {};
131
+ const sweepAllMailboxes = () => {
132
+ const agg = { scanned: 0, removed: 0, quarantined: 0, failed: 0 };
133
+ const mbBase = join(root, 'sessions');
134
+ if (existsSync(mbBase)) {
135
+ for (const sid of readdirSync(mbBase)) {
136
+ const mbRoot = join(mbBase, sid, 'mailbox');
137
+ if (!existsSync(mbRoot)) continue;
138
+ for (const bid of readdirSync(mbRoot)) {
139
+ try {
140
+ const r = mailbox.sweep(join(mbRoot, bid));
141
+ agg.scanned += r.scanned; agg.removed += r.removed; agg.quarantined += r.quarantined; agg.failed += r.failed;
142
+ } catch { agg.failed++; }
143
+ }
144
+ }
145
+ }
146
+ return agg;
147
+ };
148
+ if (mailCfg.sweepOnStart !== false) {
149
+ try {
150
+ const agg = sweepAllMailboxes();
151
+ if (agg.scanned || agg.removed || agg.quarantined || agg.failed) {
152
+ ctx.logger?.info?.('[dsh-punky-swarm] mailbox sweep on start: scanned=' + agg.scanned
153
+ + ' removed=' + agg.removed + ' quarantined=' + agg.quarantined + ' failed=' + agg.failed);
154
+ }
155
+ } catch (e) {
156
+ ctx.logger?.warn?.('[dsh-punky-swarm] mailbox sweep on start failed: ' + String(e));
157
+ }
158
+ }
159
+ // 周期 sweep(默认 0=关,C-6 零隐式行为):显式配置 sweepIntervalMs>0 才挂 setInterval(unref + dispose 清理)
160
+ const sweepIntervalMs = Number(mailCfg.sweepIntervalMs) || 0;
161
+ if (sweepIntervalMs > 0) {
162
+ sweepTimer = setInterval(() => {
163
+ try {
164
+ const agg = sweepAllMailboxes();
165
+ if (agg.removed || agg.quarantined || agg.failed) {
166
+ ctx.logger?.info?.('[dsh-punky-swarm] mailbox sweep (periodic): scanned=' + agg.scanned
167
+ + ' removed=' + agg.removed + ' quarantined=' + agg.quarantined + ' failed=' + agg.failed);
168
+ }
169
+ } catch (e) {
170
+ ctx.logger?.warn?.('[dsh-punky-swarm] mailbox sweep failed: ' + String(e));
171
+ }
172
+ }, sweepIntervalMs);
173
+ if (typeof sweepTimer.unref === 'function') sweepTimer.unref();
174
+ if (ctx.effect) {
175
+ ctx.effect(() => () => { clearInterval(sweepTimer); sweepTimer = null; }, 'dsh-punky-swarm: mailbox sweep');
176
+ }
177
+ ctx.logger?.info?.('[dsh-punky-swarm] mailbox periodic sweep mounted (interval ' + sweepIntervalMs + 'ms)');
178
+ }
179
+ }
180
+
181
+ // config 贯通:apply 的 config(cordis.patch.yml -> 插件 config)传入 createTools,
182
+ // tools.js guard 经 config?.escalation.execTools 覆盖执行型工具名单(可选,缺省 EXEC_TOOLS)
183
+ // enabled=true 时 register() 生成 catalog(14 工具 6 属性快照),传给 createApi 挂 /tools 端点
184
+ // watch 心跳引擎(lane 过期检测):enabled 默认关——开启时才创建引擎并挂 watchdog 定时器
185
+ const watchCfg = resolveWatchConfig(config);
186
+ let heartbeat = null;
187
+ if (watchCfg.enabled) {
188
+ heartbeat = createLaneHeartbeat({ store, mailbox, config, root });
189
+ }
190
+ const tools = createTools(ctx, { store, root, config, heartbeat });
191
+ tools.register();
192
+
193
+ // watchdog 挂载:setInterval(scanIntervalMinutes) 调 heartbeat.tick() 扫描全部 running lane。
194
+ // enabled 缺省/false 不挂——零运行时开销;ctx.effect(宿主可用时)与 apply 返回的 disposer 双保险清理(幂等)
195
+ let watchTimer = null;
196
+ if (watchCfg.enabled && heartbeat) {
197
+ const scanMs = Math.max(1000, Math.round(watchCfg.scanIntervalMinutes * 60_000));
198
+ watchTimer = setInterval(() => {
199
+ try { heartbeat.tick(); } catch (e) { ctx.logger?.warn?.('[dsh-punky-swarm] heartbeat tick failed: ' + String(e)); }
200
+ }, scanMs);
201
+ if (typeof watchTimer.unref === 'function') watchTimer.unref();
202
+ if (ctx.effect) {
203
+ ctx.effect(() => () => { clearInterval(watchTimer); watchTimer = null; heartbeat?.dispose(); }, 'dsh-punky-swarm: watch heartbeat');
204
+ }
205
+ ctx.logger?.info?.('[dsh-punky-swarm] watch capability enabled: lane heartbeat watchdog mounted (scan ' + scanMs + 'ms)');
206
+ }
207
+
208
+ // 只读治理 API(工作台用);agentCatalog:ACS 描述目录(aip.enabled 门控,register 后非空)
209
+ // aipFormat 随装配导出给 api.js 只读端点(mailbox/batch 响应附 ACPs 投影;纯函数不改存储)
210
+ // M1:panelStream hub 由装配层创建并注入 deps.panelStream(api.js:44 注入面复用),dispose 归本层
211
+ // (api.js:45 仅自建者 push disposer——注入时不重复 dispose);topicAttachUn 保存 attachTopic 退订句柄
212
+ let apiDispose = null;
213
+ let panelStream = null;
214
+ let topicAttachUn = null;
215
+ if (ctx.webServer) {
216
+ // 发现服务(ADP):capabilities.discovery.enabled(默认开)时装配——
217
+ // 消费 tool-descriptor catalog(tools.catalog,aip.enabled 时非空)+ agent-descriptor 目录(DEFAULT_ASSEMBLY 派生)
218
+ const discoveryCfg = resolveDiscoveryConfig(config);
219
+ let discovery = null;
220
+ if (discoveryCfg.enabled) {
221
+ const agentDescriptors = buildAgentDescriptors(DEFAULT_ASSEMBLY, { version: engineVersion() });
222
+ discovery = createDiscoveryService({ catalog: tools.catalog, agentDescriptors, config: discoveryCfg });
223
+ ctx.logger?.info?.('[dsh-punky-swarm] discovery capability enabled: POST /discover + /.well-known/aip mounted (' + discovery.stats().entries + ' entries)');
224
+ }
225
+
226
+ // 外部 ADP 发现客户端(acps.discovery,默认关——显式开启):
227
+ // 装配在 webServer 域(与本地 discovery service 同域,scope=local/both 依赖其实例);
228
+ // enabled=false 不创建实例,零运行时路径(无网络/定时器)。消费方:经 api 上下文 acpsDiscovery 取用
229
+ // mini-ADSP 仅预留签名(createMiniAdsp),endpoint 就绪前不实现。
230
+ const acpsDiscoveryCfg = resolveAcpsDiscoveryConfig(config);
231
+ let acpsDiscoveryClient = null;
232
+ if (acpsDiscoveryCfg.enabled) {
233
+ acpsDiscoveryClient = createAcpsDiscoveryClient({
234
+ baseUrl: acpsDiscoveryCfg.baseUrl,
235
+ timeout: acpsDiscoveryCfg.timeout,
236
+ limit: acpsDiscoveryCfg.limit,
237
+ scope: acpsDiscoveryCfg.scope,
238
+ localService: discovery,
239
+ });
240
+ ctx.logger?.info?.('[dsh-punky-swarm] acps discovery client enabled: scope=' + acpsDiscoveryCfg.scope
241
+ + ' baseUrl=' + (acpsDiscoveryCfg.baseUrl || '(unset)') + ' (external ADP /discover)');
242
+ }
243
+
244
+ // M1 闭合(panel-verify §3 修复指引 2):SSE hub 装配层创建注入——先建 hub 再传 deps.panelStream,
245
+ // dispose 归属本层(api.js:45 自建者 dispose;注入时 api.js 不 push disposer)。
246
+ // hub 随 webServer 挂载(ADR-4 无独立配置键);topic.enabled 时经 attachTopic('swarm.') 接线触发源①
247
+ panelStream = createStreamHub({ root, logger: ctx.logger });
248
+ apiDispose = createApi(ctx, { store, root, catalog: tools.catalog, agentCatalog: tools.agentCatalog, aipFormat: tools.aipFormat, discovery, acpsDiscovery: acpsDiscoveryClient, panelStream }).dispose;
249
+
250
+ // M1 闭合(panel-verify §3 修复指引):R3 SSE hub 装配层创建注入(上方 createStreamHub + deps.panelStream),
251
+ // topic.enabled 时经 attachTopic('swarm.') 订阅低延迟触发源①(下方 topic 运行时装配分支与 R1 热更新③对称接线);
252
+ // topic 关闭时 hub 仍装配(fs.watch ② + 心跳 ③ 双通道不变),attachTopic 零调用零路径。
253
+ }
254
+
255
+ // 诊断桥接(trajectory):订阅 trajectory 异常 → sessionId→lane 映射 → notify(默认 notify-only)。
256
+ // enabled 默认关:enabled=false 时桥接不创建不挂载——零运行时开销,行为与既有版本一致。
257
+ // 生命周期:start() 挂订阅/轮询;stop() 退订/清定时器(经 apply 返回的 dispose 释放,进程重启后桥接随插件重建、映射从批次事件幂等恢复)
258
+ let trajectory = isTrajectoryEnabled(config) ? createTrajectoryBridge(ctx, { store, config, mailbox }) : null;
259
+ if (trajectory) {
260
+ const st = trajectory.start();
261
+ if (st.subscribed) {
262
+ ctx.logger?.info?.('[dsh-punky-swarm] trajectory bridge subscribed (autoFail=' + (config?.capabilities?.trajectory?.autoFail === true) + ')');
263
+ }
264
+ }
265
+
266
+ // R2 topic 运行时装配(默认关——readCapability 缺省合并 {enabled:false};显式 capabilities.topic.enabled:true 开启):
267
+ // enabled 时创建运行时(start/stop 与 trajectory 桥同形)+ 接线状态事件发布(store.setMember/setPhase 调用点埋点);
268
+ // 关闭时零挂载零路径(与 acps/bridge config 短路同构)。trajectory 桥 broadcast 直走不变,topic.enabled 时仅镜像(并存不替换)。
269
+ // R1 热更新(config.changed)可实时启停本运行时(L1 消费点,见下方 applyConfigChange ③)。
270
+ let topicRuntime = null;
271
+ if (readCapability(config, 'topic')?.enabled) {
272
+ topicRuntime = createTopicRuntime(ctx, { root, logger: ctx.logger });
273
+ topicRuntime.start();
274
+ topicSink.emit = (ev) => { try { topicRuntime.publishStateChange(ev); } catch { /* 隔离 */ } };
275
+ // M1 闭合:hub 触发源①接线(attachTopic('swarm.'),幂等——已接线不重复订阅)——
276
+ // 订阅后 store.setMember/setPhase 状态事件(swarm.member.settled / swarm.batch.phase)经 hub 路由推送 SSE
277
+ if (panelStream && !topicAttachUn) topicAttachUn = panelStream.attachTopic('swarm.');
278
+ ctx.logger?.info?.('[dsh-punky-swarm] topic capability enabled: topic runtime started (swarm.<type>.<sid>.<bid>)');
279
+ }
280
+
281
+ // 内部 ACPs 桥接(config.acps.bridge,默认关):enabled=false 时 mountBridge 短路返回 null——
282
+ // 不实例化、零运行时路径(config 短路);outbound=mailbox→ACPs 投影/投递,inbound 默认关:
283
+ // 外部写 mailbox 需显式 acps.bridge.inbound=true。/rpc 监听与对外投递由 endpoint 侧承担。
284
+ const bridge = mountBridge(config, { root, mailbox, logger: ctx.logger });
285
+ if (bridge) {
286
+ ctx.logger?.info?.('[dsh-punky-swarm] acps.bridge enabled: in-process bridge mounted (inbound='
287
+ + (config?.acps?.bridge?.inbound === true) + ')');
288
+ }
289
+
290
+ // 半自动注册客户端(config.acps.registry):默认关——enabled=true 且
291
+ // registry.url 配置时创建 RegistryClient 实例(能力装配,不自动发起注册——V3 人工审核不自动化
292
+ // 跳过,注册动作由用户经脚本/工具显式触发:login→upsert→submit→人工审批→requestEab)。
293
+ // enabled=false / 缺 url 时短路:不建实例、零网络、零运行时路径。
294
+ const registryCfg = resolveRegistryConfig(config);
295
+ const registryClient = registryCfg.enabled ? createRegistryClient(registryCfg) : null;
296
+ if (registryCfg.enabled && !registryClient) {
297
+ ctx.logger?.warn?.('[dsh-punky-swarm] acps.registry: ' + (registryCfg.reason ?? 'unable to create client'));
298
+ } else if (registryClient) {
299
+ ctx.logger?.info?.('[dsh-punky-swarm] acps.registry enabled: semi-automatic registration client ready ('
300
+ + registryCfg.apiBaseUrl + ')');
301
+ }
302
+
303
+ // ACPs 对外 mTLS 服务端点:acps.enabled && acps.endpoint.enabled 双真才装配——
304
+ // 默认双关 = 零加载零监听零定时器(config 短路,关闭时无运行时路径)。
305
+ // 证书缺失/不可用 → 启动告警并保持禁用,不阻塞主进程。
306
+ // 与既有端点零冲突:对外独立 9443 监听 + /acps/* 前缀,/api/dsh-punky-swarm/* 与 /.well-known/aip 一字不动。
307
+ const acpsCfg = resolveAcpsConfig(config);
308
+ let acpsEndpoint = null;
309
+ if (acpsCfg.enabled && acpsCfg.endpoint?.enabled) {
310
+ try {
311
+ const endpointCfg = {
312
+ ...acpsCfg,
313
+ endpoint: {
314
+ ...acpsCfg.endpoint,
315
+ certDir: acpsCfg.endpoint.certDir ?? join(root, 'acps', 'certs'), // 默认数据目录(引擎根内)
316
+ },
317
+ };
318
+ // /acps/rpc → bridge inbound 接线——endpoint 收到 TaskCommand 交 bridge.handleInbound
319
+ // (经 mailbox 公共接口原子写 inbox;inbound 门控保持:bridge.inbound=false → INBOUND_DISABLED 拒绝,
320
+ // /rpc 回 TaskResult rejected 不落 mailbox)。bridge 未装配(enabled=false)时回独立 accepted(向后兼容)。
321
+ const rpcHandler = bridge ? createEndpointRpcHandler(bridge, { logger: ctx.logger }) : undefined;
322
+ acpsEndpoint = createAcpsServer({ config: endpointCfg, logger: ctx.logger, rpcHandler });
323
+ if (acpsEndpoint.error) {
324
+ ctx.logger?.warn?.('[dsh-punky-swarm] ' + acpsEndpoint.error + '(acps endpoint 保持禁用)');
325
+ acpsEndpoint = null;
326
+ } else {
327
+ acpsEndpoint.listen().then((addr) => {
328
+ ctx.logger?.info?.('[dsh-punky-swarm] acps endpoint enabled: mTLS listener https://' + addr.address + ':' + addr.port
329
+ + ' (TLSv1.3 + CERT_REQUIRED, devInsecure=' + endpointCfg.endpoint.devInsecure + ')');
330
+ }).catch((e) => {
331
+ ctx.logger?.warn?.('[dsh-punky-swarm] acps endpoint listen failed: ' + String(e) + '(保持禁用)');
332
+ acpsEndpoint = null;
333
+ });
334
+ }
335
+ } catch (e) {
336
+ ctx.logger?.warn?.('[dsh-punky-swarm] acps endpoint disabled: ' + String(e.message));
337
+ acpsEndpoint = null;
338
+ }
339
+ }
340
+
341
+ // verify 引擎级捕获(verify-report 集成注意项 1 接线):capabilities.verify.enabled 门控挂
342
+ // installEvidenceCapture(tools/post-execute 证据捕获,blob + ledger 落 <root>/verify/)。enabled=false(默认)
343
+ // 不挂 hook、零运行时开销;ctx.on 缺失静默降级。createCompletionGate 与 audit lane DI 消费路径一字不动(gate.js 零改动)。
344
+ let verifyMount = mountVerify(ctx, { root, config });
345
+ if (verifyMount.installed) {
346
+ ctx.logger?.info?.('[dsh-punky-swarm] verify capability enabled: post-execute evidence capture mounted');
347
+ }
348
+
349
+ // ── R1 热更新装配(L1 消费点就地启停,叠加非替换)──
350
+ // 触发源:<root>/config/runtime.json(fs.watch + 防抖 300ms + 原子读重试)→ deepMerge 快照 → config.changed 广播
351
+ // 生效语义:只影响被覆盖键的后续读取;不写静态文件、不改变 cordis.patch.yml 读取结果(D2);
352
+ // 缺省 {} → 快照 = 静态 config 原样(零行为变化);判定语义双套保留、热更新只做值传播(设计 §3.1.5 裁决)
353
+ // 生效范围(L1,设计 §3.1.4):trajectory 桥 start/stop、watch watchdog 启停、topic 运行时启停、verify 挂载(可选)
354
+ // 对外能力(acps/bridge/acps.discovery/identity)不纳入热切(设计 §3.1.5 附带裁决)
355
+ let hotConfig = null;
356
+ const applyConfigChange = (change) => {
357
+ const next = change.config;
358
+ // ① watch watchdog:enabled 翻转 → 启/停(heartbeat.dispose + timer 句柄,幂等)
359
+ const wc = resolveWatchConfig(next);
360
+ if (wc.enabled && !heartbeat) {
361
+ heartbeat = createLaneHeartbeat({ store, mailbox, config: next, root });
362
+ const scanMs = Math.max(1000, Math.round(wc.scanIntervalMinutes * 60_000));
363
+ watchTimer = setInterval(() => {
364
+ try { heartbeat.tick(); } catch (e) { ctx.logger?.warn?.('[dsh-punky-swarm] heartbeat tick failed: ' + String(e)); }
365
+ }, scanMs);
366
+ if (typeof watchTimer.unref === 'function') watchTimer.unref();
367
+ ctx.logger?.info?.('[dsh-punky-swarm] hot config: watch watchdog started (scan ' + scanMs + 'ms)');
368
+ } else if (!wc.enabled && heartbeat) {
369
+ if (watchTimer) { clearInterval(watchTimer); watchTimer = null; }
370
+ heartbeat.dispose(); heartbeat = null;
371
+ ctx.logger?.info?.('[dsh-punky-swarm] hot config: watch watchdog stopped');
372
+ }
373
+ // ② trajectory 桥:enabled 翻转 → stop + 以新快照重建(映射经批次事件幂等恢复)
374
+ const trajOn = isTrajectoryEnabled(next);
375
+ if (trajOn && !trajectory) {
376
+ trajectory = createTrajectoryBridge(ctx, { store, config: next, mailbox });
377
+ const st = trajectory.start();
378
+ if (st.subscribed) ctx.logger?.info?.('[dsh-punky-swarm] hot config: trajectory bridge started');
379
+ } else if (!trajOn && trajectory) {
380
+ trajectory.stop(); trajectory = null;
381
+ ctx.logger?.info?.('[dsh-punky-swarm] hot config: trajectory bridge stopped');
382
+ }
383
+ // ③ topic 运行时:readCapability 缺省关 → enabled 翻转 → 启/停(状态事件发布钩子随动 + M1 hub attachTopic 对称退订)
384
+ const topicCfg = readCapability(next, 'topic');
385
+ if (topicCfg?.enabled && !topicRuntime) {
386
+ topicRuntime = createTopicRuntime(ctx, { root, logger: ctx.logger });
387
+ topicRuntime.start();
388
+ topicSink.emit = (ev) => { try { topicRuntime.publishStateChange(ev); } catch { /* 隔离 */ } };
389
+ if (panelStream && !topicAttachUn) topicAttachUn = panelStream.attachTopic('swarm.');
390
+ ctx.logger?.info?.('[dsh-punky-swarm] hot config: topic runtime started');
391
+ } else if (!topicCfg?.enabled && topicRuntime) {
392
+ topicRuntime.stop(); topicRuntime = null;
393
+ topicSink.emit = null;
394
+ if (topicAttachUn) { topicAttachUn(); topicAttachUn = null; }
395
+ ctx.logger?.info?.('[dsh-punky-swarm] hot config: topic runtime stopped');
396
+ }
397
+ // ④ verify 挂载(可选 L1):enabled 翻转 → dispose + 以新快照重挂(inert 与 installed 双态幂等)
398
+ const vc = resolveVerifyConfig(next);
399
+ if (vc.enabled !== verifyMount.installed) {
400
+ verifyMount.dispose?.();
401
+ verifyMount = mountVerify(ctx, { root, config: next });
402
+ ctx.logger?.info?.('[dsh-punky-swarm] hot config: verify capture ' + (vc.enabled ? 'mounted' : 'unmounted'));
403
+ }
404
+ };
405
+ hotConfig = createConfigWatcher({
406
+ root, config,
407
+ onChange: (change) => {
408
+ // ① 进程内广播(cordis 总线事件,宿主可用时;exec-b hub/未来订阅方经 ctx.on 订阅)
409
+ try { ctx.emit?.(CONFIG_CHANGED_EVENT, change); } catch { /* 宿主事件缺失静默 */ }
410
+ // ② topic 镜像(R1→R2 可选,设计 §3.4):topic.enabled 时同步 emitTopic('swarm.config.changed'),仅进程内分发
411
+ if (topicRuntime) { try { topicRuntime.publishConfigChanged(change); } catch { /* 隔离 */ } }
412
+ // ③ L1 消费点就地启停
413
+ applyConfigChange(change);
414
+ },
415
+ logger: ctx.logger,
416
+ });
417
+ hotConfig.start();
418
+
419
+ return () => {
420
+ hotConfig?.dispose();
421
+ if (watchTimer) { clearInterval(watchTimer); watchTimer = null; }
422
+ if (sweepTimer) { clearInterval(sweepTimer); sweepTimer = null; }
423
+ heartbeat?.dispose();
424
+ apiDispose?.();
425
+ trajectory?.stop();
426
+ topicRuntime?.stop();
427
+ // M1:attachTopic 退订 + hub dispose(装配层创建者负责,api.js 注入时不重复 dispose)
428
+ if (topicAttachUn) { topicAttachUn(); topicAttachUn = null; }
429
+ if (panelStream) { panelStream.dispose(); panelStream = null; }
430
+ verifyMount?.dispose();
431
+ if (acpsEndpoint) { acpsEndpoint.close().catch(() => {}); acpsEndpoint = null; }
432
+ };
433
+ };
package/lib/lock.js ADDED
@@ -0,0 +1,69 @@
1
+ /*
2
+ Copyright (C) 2025-2026 Punky
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Affero General Public License as
6
+ published by the Free Software Foundation, either version 3 of the
7
+ License, or (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Affero General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Affero General Public License
15
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ // O_EXCL 单写者锁(最小可行):原子创建锁文件,冲突先拒绝(wait/force 可选)
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { randomUUID } from 'node:crypto';
22
+
23
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
24
+
25
+ export async function acquire(lockPath, { waitMs = 0, pollMs = 50, force = false } = {}) {
26
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
27
+ const token = randomUUID();
28
+ const deadline = Date.now() + Math.max(0, waitMs);
29
+ for (;;) {
30
+ try {
31
+ const fd = fs.openSync(lockPath, 'wx');
32
+ fs.writeSync(fd, JSON.stringify({ token, ts: Date.now(), pid: process.pid }));
33
+ fs.closeSync(fd);
34
+ return { ok: true, token, lockPath };
35
+ } catch (e) {
36
+ if (e.code !== 'EEXIST') throw e;
37
+ if (force) {
38
+ try { fs.unlinkSync(lockPath); } catch {}
39
+ continue;
40
+ }
41
+ if (Date.now() >= deadline) {
42
+ return { ok: false, conflict: true, lockPath };
43
+ }
44
+ await sleep(Math.max(10, pollMs));
45
+ }
46
+ }
47
+ }
48
+
49
+ export function release(lockPath, token) {
50
+ try {
51
+ const raw = fs.readFileSync(lockPath, 'utf8');
52
+ const cur = JSON.parse(raw);
53
+ // 仅当持有者 token 匹配时释放(防 force 接管后误释放)
54
+ if (token && cur.token !== token) return { ok: false, reason: 'token-mismatch' };
55
+ fs.unlinkSync(lockPath);
56
+ return { ok: true };
57
+ } catch (e) {
58
+ if (e.code === 'ENOENT') return { ok: true };
59
+ throw e;
60
+ }
61
+ }
62
+
63
+ export function isLocked(lockPath) {
64
+ return fs.existsSync(lockPath);
65
+ }
66
+
67
+ export function lockFileName(batchId) {
68
+ return path.join('.locks', batchId + '.lock');
69
+ }