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.
- package/CHANGELOG.md +120 -0
- package/LICENSE +661 -0
- package/README.en.md +281 -0
- package/README.md +281 -0
- package/cordis.patch.yml +59 -0
- package/lib/acps/certs.js +310 -0
- package/lib/acps/discovery-client.js +283 -0
- package/lib/acps/registry-client.js +527 -0
- package/lib/acps/server.js +302 -0
- package/lib/aip/agent-descriptor.js +170 -0
- package/lib/aip/identity.js +469 -0
- package/lib/aip/tool-descriptor.js +93 -0
- package/lib/api.js +266 -0
- package/lib/artifact-types.js +48 -0
- package/lib/assembly/audit-blind-review.js +170 -0
- package/lib/assembly/schema.js +253 -0
- package/lib/assembly.js +41 -0
- package/lib/assets.js +103 -0
- package/lib/bridge/trajectory.js +202 -0
- package/lib/client.js +704 -0
- package/lib/comms/acps-bridge.js +219 -0
- package/lib/comms/aip-format.js +141 -0
- package/lib/comms/budget.js +124 -0
- package/lib/comms/mailbox.js +221 -0
- package/lib/comms/topic-runtime.js +76 -0
- package/lib/comms/topic.js +115 -0
- package/lib/discovery/filter.js +199 -0
- package/lib/discovery/schema.js +157 -0
- package/lib/discovery/service.js +251 -0
- package/lib/hot/config-watch.js +252 -0
- package/lib/index.js +433 -0
- package/lib/lock.js +69 -0
- package/lib/panel/batch-detail.js +163 -0
- package/lib/panel/batch-list.js +84 -0
- package/lib/panel/locales.js +93 -0
- package/lib/panel/main.js +270 -0
- package/lib/panel/stream.js +348 -0
- package/lib/panel/theme.js +103 -0
- package/lib/panel/widgets.js +63 -0
- package/lib/schema.d.ts +192 -0
- package/lib/schema.js +259 -0
- package/lib/schema.ts +398 -0
- package/lib/state/archive.js +174 -0
- package/lib/state/command-exec.js +148 -0
- package/lib/state/constants.js +37 -0
- package/lib/state/corrupt-registry.js +103 -0
- package/lib/state/event-types.js +65 -0
- package/lib/state/gates.d.ts +226 -0
- package/lib/state/gates.js +428 -0
- package/lib/state/gates.ts +348 -0
- package/lib/state/machine-rules.d.ts +14 -0
- package/lib/state/machine-rules.js +76 -0
- package/lib/state/machine-rules.ts +88 -0
- package/lib/state/machine.js +68 -0
- package/lib/state/resume.js +201 -0
- package/lib/state/schema-v3.d.ts +10 -0
- package/lib/state/schema-v3.js +57 -0
- package/lib/state/schema-v3.ts +80 -0
- package/lib/state/store.js +607 -0
- package/lib/state/task-utils.js +40 -0
- package/lib/tools/core.js +323 -0
- package/lib/tools/git-utils.js +44 -0
- package/lib/tools/lane-tools.js +455 -0
- package/lib/tools/log-tools.js +173 -0
- package/lib/tools/mailbox-tools.js +121 -0
- package/lib/tools/merge-agent.js +127 -0
- package/lib/tools/register.js +85 -0
- package/lib/tools/shared.js +32 -0
- package/lib/types/contracts.d.ts +277 -0
- package/lib/types/contracts.js +17 -0
- package/lib/types/contracts.ts +279 -0
- package/lib/verify/evidence.js +249 -0
- package/lib/verify/gate.js +161 -0
- package/lib/verify/mount.js +48 -0
- package/lib/verify/selector.js +101 -0
- package/lib/watch/lane-heartbeat.js +333 -0
- package/lib/wave-plan.d.ts +48 -0
- package/lib/wave-plan.js +473 -0
- package/lib/wave-plan.ts +465 -0
- package/package.json +71 -0
- package/presets/jiufeng/NOTICE +5 -0
- package/presets/jiufeng/agent.cordis.yml +275 -0
- package/presets/jiufeng/preset.yml +3 -0
- package/skills/jiufeng-team/SKILL.md +214 -0
- package/skills/jiufeng-team/references/constitution.md +62 -0
- package/skills/jiufeng-team/references/roles/coder.md +17 -0
- package/skills/jiufeng-team/references/roles/coordinator.md +13 -0
- package/skills/jiufeng-team/references/roles/designer.md +14 -0
- package/skills/jiufeng-team/references/roles/doc-manager.md +13 -0
- package/skills/jiufeng-team/references/roles/manager.md +22 -0
- package/skills/jiufeng-team/references/roles/reviewer.md +19 -0
- package/skills/jiufeng-team/references/roles/supervisor.md +13 -0
- package/skills/jiufeng-team/references/roles/tester.md +13 -0
- package/skills/jiufeng-team/references/templates/call-chain-matrix-template.md +121 -0
- package/skills/jiufeng-team/references/templates/endpoint-behavior-template.md +60 -0
- package/skills/jiufeng-team/references/templates/gap-list.json +33 -0
- package/skills/jiufeng-team/references/templates/leader-decision-pack.md +92 -0
- package/skills/jiufeng-team/references/templates/plan-template.md +61 -0
- package/skills/jiufeng-team/references/templates/success-pattern-seeds.md +126 -0
- package/skills/jiufeng-team/references/workflow.md +98 -0
- package/skills/jiufeng-team/scripts/check-v3-density.mjs +98 -0
|
@@ -0,0 +1,221 @@
|
|
|
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
|
+
// 文件 mailbox:worker <-> supervisor 异步通信(原子写 + ack),不共享上下文
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { randomUUID } from 'node:crypto';
|
|
22
|
+
|
|
23
|
+
const LANE_RE = /^[a-zA-Z0-9._-]+$/;
|
|
24
|
+
|
|
25
|
+
export function sanitizeLane(lane) {
|
|
26
|
+
if (!lane || !LANE_RE.test(lane)) throw new Error('invalid lane: ' + String(lane));
|
|
27
|
+
return lane;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// box: { type: 'inbox' | 'outbox' | 'broadcast', lane?: string }
|
|
31
|
+
export function boxDir(root, box) {
|
|
32
|
+
if (box.type === 'inbox') return path.join(root, 'supervisor', 'inbox');
|
|
33
|
+
if (box.type === 'broadcast') return path.join(root, 'broadcast');
|
|
34
|
+
if (box.type === 'outbox') {
|
|
35
|
+
return path.join(root, sanitizeLane(box.lane), 'outbox');
|
|
36
|
+
}
|
|
37
|
+
throw new Error('unknown mailbox type: ' + String(box.type));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function ackDir(dir) {
|
|
41
|
+
return path.join(dir, '.acks');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// 损坏消息 quarantine 目录(④,D-005):<boxDir>/.quarantine/,保留现场供人工检视
|
|
45
|
+
export function quarantineDir(dir) {
|
|
46
|
+
return path.join(dir, '.quarantine');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const DEFAULT_SWEEP_TTL_MS = 7 * 24 * 60 * 60 * 1000; // ack 标记保留期(默认 7d)
|
|
50
|
+
const DEFAULT_QUARANTINE_TTL_MS = 30 * 24 * 60 * 60 * 1000; // quarantine 保留期(默认 30d)
|
|
51
|
+
|
|
52
|
+
// 发送:原子写消息文件,返回 ackId(文件名)
|
|
53
|
+
export function send(root, box, message, meta = null) {
|
|
54
|
+
const dir = boxDir(root, box);
|
|
55
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
56
|
+
fs.mkdirSync(ackDir(dir), { recursive: true });
|
|
57
|
+
const ackId = Date.now().toString(36) + '-' + randomUUID().slice(0, 8) + '.json';
|
|
58
|
+
const payload = {
|
|
59
|
+
ackId,
|
|
60
|
+
ts: new Date().toISOString(),
|
|
61
|
+
box,
|
|
62
|
+
message,
|
|
63
|
+
meta: meta ?? null,
|
|
64
|
+
};
|
|
65
|
+
const tmp = path.join(dir, '.' + ackId + '.tmp');
|
|
66
|
+
fs.writeFileSync(tmp, JSON.stringify(payload));
|
|
67
|
+
fs.renameSync(tmp, path.join(dir, ackId));
|
|
68
|
+
return { ok: true, ackId };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function readUnacked(root, box, { sinceTs = 0 } = {}) {
|
|
72
|
+
const dir = boxDir(root, box);
|
|
73
|
+
if (!fs.existsSync(dir)) return [];
|
|
74
|
+
const acked = new Set();
|
|
75
|
+
if (fs.existsSync(ackDir(dir))) {
|
|
76
|
+
for (const f of fs.readdirSync(ackDir(dir))) acked.add(f.replace(/\.acked$/, ''));
|
|
77
|
+
}
|
|
78
|
+
const items = [];
|
|
79
|
+
for (const f of fs.readdirSync(dir).sort()) {
|
|
80
|
+
if (f.startsWith('.') || acked.has(f)) continue;
|
|
81
|
+
try {
|
|
82
|
+
const p = path.join(dir, f);
|
|
83
|
+
const data = JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
84
|
+
const ts = Date.parse(data.ts ?? 0) || 0;
|
|
85
|
+
if (ts >= sinceTs) items.push(data);
|
|
86
|
+
} catch {
|
|
87
|
+
// 跳过损坏消息(不阻塞)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return items;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function ack(root, box, ackId, { pruneOnAck = true } = {}) {
|
|
94
|
+
const dir = boxDir(root, box);
|
|
95
|
+
if (!ackId || typeof ackId !== 'string' || ackId.includes('..')) throw new Error('invalid ackId');
|
|
96
|
+
fs.mkdirSync(ackDir(dir), { recursive: true });
|
|
97
|
+
fs.writeFileSync(path.join(ackDir(dir), ackId + '.acked'), JSON.stringify({ ackedAt: new Date().toISOString() }));
|
|
98
|
+
if (pruneOnAck) {
|
|
99
|
+
// ack 即删原消息文件(④,D-004,默认开;pruneOnAck:false 保留,保兼容):
|
|
100
|
+
// 删除失败仅记录不 throw——.acked 已写,readUnacked 仍跳过该消息(INV-6),残留交下次 sweep 按 TTL 清
|
|
101
|
+
try {
|
|
102
|
+
const msgFile = path.join(dir, ackId);
|
|
103
|
+
if (fs.existsSync(msgFile)) fs.unlinkSync(msgFile);
|
|
104
|
+
} catch { /* 保留现场,sweep 兜底 */ }
|
|
105
|
+
}
|
|
106
|
+
return { ok: true, ackId };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function isAcked(root, box, ackId) {
|
|
110
|
+
return fs.existsSync(path.join(ackDir(boxDir(root, box)), ackId + '.acked'));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ---- 滞留清理(④,T-CODE-4):ack 标记 TTL sweep + 损坏消息 quarantine + 孤儿 .acked 清理 ----
|
|
114
|
+
// sweep(root, { ttlMs=7d, quarantineTtlMs=30d, now }):遍历 root 下全部 box 目录(supervisor/inbox、
|
|
115
|
+
// broadcast、<lane>/outbox):
|
|
116
|
+
// - acked 且标记超 TTL → 删消息文件 + 删 .acked 标记(消息删除失败则标记保留,下轮 sweep 重试)
|
|
117
|
+
// - 损坏消息(JSON.parse 失败)→ 移 .quarantine/(保留现场);quarantine 内文件按 quarantineTtlMs 清
|
|
118
|
+
// - 孤儿 .acked(无对应消息文件)→ 按 TTL 删标记
|
|
119
|
+
// - 未 ack 未超期消息 → 不动(保守,D-005:仅记录不删)
|
|
120
|
+
// 幂等可重入(INV-7):无状态全量扫描;单文件失败 catch 跳过 + failed 计数,不中断。
|
|
121
|
+
// 返回 { scanned, removed, quarantined, failed };readUnacked/isAcked/send 语义零变化。
|
|
122
|
+
function boxDirs(root) {
|
|
123
|
+
const dirs = [];
|
|
124
|
+
if (!fs.existsSync(root)) return dirs;
|
|
125
|
+
const supervisor = path.join(root, 'supervisor', 'inbox');
|
|
126
|
+
if (fs.existsSync(supervisor)) dirs.push(supervisor);
|
|
127
|
+
const broadcast = path.join(root, 'broadcast');
|
|
128
|
+
if (fs.existsSync(broadcast)) dirs.push(broadcast);
|
|
129
|
+
for (const name of fs.readdirSync(root)) {
|
|
130
|
+
if (name.startsWith('.')) continue;
|
|
131
|
+
if (name === 'supervisor' || name === 'broadcast') continue;
|
|
132
|
+
const ob = path.join(root, name, 'outbox');
|
|
133
|
+
if (fs.existsSync(ob)) dirs.push(ob);
|
|
134
|
+
}
|
|
135
|
+
return dirs;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function sweepBoxDir(dir, stats, { ttlMs, quarantineTtlMs, now }) {
|
|
139
|
+
if (!fs.existsSync(dir)) return;
|
|
140
|
+
const acksPath = ackDir(dir);
|
|
141
|
+
const acked = new Map(); // ackId -> ackedAt(ms)(.acked 内容 ackedAt;损坏标记按 mtime 兜底)
|
|
142
|
+
if (fs.existsSync(acksPath)) {
|
|
143
|
+
for (const f of fs.readdirSync(acksPath)) {
|
|
144
|
+
if (!f.endsWith('.acked')) continue;
|
|
145
|
+
const ackId = f.slice(0, -6);
|
|
146
|
+
let ackedAt = null;
|
|
147
|
+
try {
|
|
148
|
+
const data = JSON.parse(fs.readFileSync(path.join(acksPath, f), 'utf8'));
|
|
149
|
+
ackedAt = Date.parse(data.ackedAt) || null;
|
|
150
|
+
} catch { /* 标记损坏 → mtime 兜底 */ }
|
|
151
|
+
if (!ackedAt) {
|
|
152
|
+
try { ackedAt = fs.statSync(path.join(acksPath, f)).mtimeMs; } catch { ackedAt = 0; }
|
|
153
|
+
}
|
|
154
|
+
acked.set(ackId, ackedAt);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
// 1) 消息文件:acked 且超 TTL → 删消息+删标记;损坏 → quarantine;未 ack 未超期 → 不动
|
|
158
|
+
for (const f of fs.readdirSync(dir).sort()) {
|
|
159
|
+
if (f.startsWith('.')) continue;
|
|
160
|
+
const p = path.join(dir, f);
|
|
161
|
+
let st;
|
|
162
|
+
try { st = fs.statSync(p); } catch { continue; }
|
|
163
|
+
if (!st.isFile()) continue;
|
|
164
|
+
stats.scanned++;
|
|
165
|
+
const ackedAt = acked.get(f);
|
|
166
|
+
if (ackedAt !== undefined) {
|
|
167
|
+
if (now - ackedAt >= ttlMs) {
|
|
168
|
+
try {
|
|
169
|
+
fs.unlinkSync(p);
|
|
170
|
+
stats.removed++;
|
|
171
|
+
// SHOULD-FIX-1:仅消息删除成功才删 .acked 标记(删除顺序不变:先消息后标记)。
|
|
172
|
+
// 消息 unlink 失败时标记保留——.acked 继续保护 readUnacked 不重复暴露已消费消息,
|
|
173
|
+
// 消息留待下轮 sweep 重试(与 ack() 路径『.acked 先写,删除失败 sweep 兜底』意图一致)。
|
|
174
|
+
try { fs.unlinkSync(path.join(acksPath, f + '.acked')); } catch { /* 标记可能已删 */ }
|
|
175
|
+
acked.delete(f);
|
|
176
|
+
} catch { stats.failed++; /* 消息删除失败:保留 .acked 标记,下轮 sweep 重试 */ }
|
|
177
|
+
}
|
|
178
|
+
// acked 未超期:消息与标记均保留(readUnacked 仍跳过)
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
// 未 ack:损坏消息 → quarantine(保留现场)
|
|
182
|
+
try {
|
|
183
|
+
JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
184
|
+
} catch {
|
|
185
|
+
try {
|
|
186
|
+
const q = quarantineDir(dir);
|
|
187
|
+
fs.mkdirSync(q, { recursive: true });
|
|
188
|
+
fs.renameSync(p, path.join(q, f));
|
|
189
|
+
stats.quarantined++;
|
|
190
|
+
} catch { stats.failed++; }
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
// 未 ack 未超期 → 不动(D-005:保守,仅记录)
|
|
194
|
+
}
|
|
195
|
+
// 2) 孤儿 .acked(无对应消息文件)→ 按 TTL 删标记
|
|
196
|
+
for (const [ackId, ackedAt] of acked) {
|
|
197
|
+
if (fs.existsSync(path.join(dir, ackId))) continue; // 有对应消息:acked 超 TTL 已在 1) 处理
|
|
198
|
+
if (now - ackedAt >= ttlMs) {
|
|
199
|
+
try { fs.unlinkSync(path.join(acksPath, ackId + '.acked')); stats.removed++; } catch { stats.failed++; }
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
// 3) quarantine TTL:q 内文件 mtime 超 quarantineTtlMs → 删
|
|
203
|
+
const q = quarantineDir(dir);
|
|
204
|
+
if (fs.existsSync(q)) {
|
|
205
|
+
for (const f of fs.readdirSync(q)) {
|
|
206
|
+
if (f.startsWith('.')) continue;
|
|
207
|
+
const p = path.join(q, f);
|
|
208
|
+
try {
|
|
209
|
+
if (now - fs.statSync(p).mtimeMs >= quarantineTtlMs) { fs.unlinkSync(p); stats.removed++; }
|
|
210
|
+
} catch { stats.failed++; }
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function sweep(root, { ttlMs = DEFAULT_SWEEP_TTL_MS, quarantineTtlMs = DEFAULT_QUARANTINE_TTL_MS, now = Date.now() } = {}) {
|
|
216
|
+
const stats = { scanned: 0, removed: 0, quarantined: 0, failed: 0 };
|
|
217
|
+
for (const dir of boxDirs(root)) {
|
|
218
|
+
try { sweepBoxDir(dir, stats, { ttlMs, quarantineTtlMs, now }); } catch { stats.failed++; }
|
|
219
|
+
}
|
|
220
|
+
return stats;
|
|
221
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
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
|
+
// lib/comms/topic-runtime.js —— R2 topic 运行时装配(index.js 装配点,生命周期与 trajectory 桥同形)
|
|
19
|
+
// 设计依据:exec/panel-design.md §3.2(装配面/接线面/命名/开关)+ §3.2.4(trajectory 桥并存不统一)
|
|
20
|
+
// - 开关:capabilities.topic.enabled(readCapability 缺省合并 {enabled:false},默认关);enabled 时装配面创建
|
|
21
|
+
// 运行时(start/stop 供 R1 热更新实时启停),关闭时零挂载零路径(与 acps/bridge config 短路同构)
|
|
22
|
+
// - 发布方(首批枚举,设计 §3.2.3):store.setMember/setPhase 调用点埋点(onStateChange → publishStateChange)
|
|
23
|
+
// - 命名:swarm.<eventType>.<sessionId>.<batchId>(点分倒置,前缀固定便于 readTopic 精确过滤与日志检索)
|
|
24
|
+
// - 落盘:emitTopic 的 ctx 携带 {root, sessionId, batchId} 才落 mailbox broadcast(topic.js 既有语义不变);
|
|
25
|
+
// publishConfigChanged(R1→R2 可选镜像)无 session 归属 → 仅进程内分发,不落 mailbox
|
|
26
|
+
// - topic.js 三函数签名零改动(本文件只做装配与接线,不透改底层模块)
|
|
27
|
+
import { subscribeTopic, emitTopic, readTopic } from './topic.js';
|
|
28
|
+
|
|
29
|
+
export function createTopicRuntime(ctx, { root, logger } = {}) {
|
|
30
|
+
let started = false;
|
|
31
|
+
const log = logger ?? ctx?.logger ?? null;
|
|
32
|
+
|
|
33
|
+
// topic 命名规范:swarm.<eventType>.<sessionId>.<batchId>
|
|
34
|
+
function topicOf(type, sessionId, batchId) {
|
|
35
|
+
return 'swarm.' + type + '.' + sessionId + '.' + batchId;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// 状态机事件发布(store 调用点埋点 → 本函数):
|
|
39
|
+
// ev = { type: 'member.settled' | 'batch.phase', sessionId, batchId, lane?, from, to, note? }
|
|
40
|
+
// 未 start / 载荷不齐 → 零发布(不落盘不抛错);异常由 emitTopic 内部隔离
|
|
41
|
+
function publishStateChange(ev) {
|
|
42
|
+
if (!started) return { published: false, reason: 'not-started' };
|
|
43
|
+
if (!ev || !ev.type || !ev.sessionId || !ev.batchId) {
|
|
44
|
+
return { published: false, reason: 'invalid-event' };
|
|
45
|
+
}
|
|
46
|
+
const topic = topicOf(ev.type, ev.sessionId, ev.batchId);
|
|
47
|
+
const payload = { ...ev, ts: new Date().toISOString() };
|
|
48
|
+
// ctx 携带 {root, sessionId, batchId} → 落 mailbox broadcast(topic.js 既有语义);root 缺省(测试)仅进程内分发
|
|
49
|
+
return emitTopic(topic, payload, { root, sessionId: ev.sessionId, batchId: ev.batchId });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// 配置变更镜像(R1→R2 可选,设计 §3.4):swarm.config.changed——无 session 归属 → 仅进程内分发
|
|
53
|
+
function publishConfigChanged(change) {
|
|
54
|
+
if (!started) return { published: false, reason: 'not-started' };
|
|
55
|
+
return emitTopic('swarm.config.changed', { ...change, ts: new Date().toISOString() }, { root });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function start() {
|
|
59
|
+
started = true;
|
|
60
|
+
log?.info?.('[dsh-punky-swarm] topic runtime started');
|
|
61
|
+
return { started: true };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function stop() {
|
|
65
|
+
started = false;
|
|
66
|
+
log?.info?.('[dsh-punky-swarm] topic runtime stopped');
|
|
67
|
+
return { stopped: true };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
start, stop,
|
|
72
|
+
publishStateChange, publishConfigChanged,
|
|
73
|
+
subscribeTopic, emitTopic, readTopic,
|
|
74
|
+
topicOf, isStarted: () => started,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
// 文件 topic:broadcast topic 订阅/分发
|
|
19
|
+
// 两路分发:① 进程内 handler 同步调用(异常隔离);② 可选落 mailbox broadcast box(复用 mailbox.send,ackId 原子写语义)
|
|
20
|
+
// 消费侧跨进程经 mailbox_read(box=broadcast) 读取,readTopic 提供按 topic/sinceTs 过滤的只读辅助
|
|
21
|
+
//
|
|
22
|
+
// 接线状态(exec-panel-b 批②,R3 SSE hub):
|
|
23
|
+
// - subscribeTopicPrefix(前缀订阅,R3 hub 订阅 `swarm.` 用,exec-b 新增,签名零改动);
|
|
24
|
+
// - 装配开关 capabilities.topic.enabled(CAPABILITY_REGISTRY 注册表默认关,显式开启才接线)仍归 exec-a 装配;
|
|
25
|
+
// - 消费点不得绕过 mailbox 公共接口(与既有广播语义同源:mailbox.send/readUnacked)。
|
|
26
|
+
import { join } from 'node:path';
|
|
27
|
+
import { send as mailboxSend, readUnacked } from './mailbox.js';
|
|
28
|
+
|
|
29
|
+
const registry = new Map(); // Map<topic, Set<handler>>
|
|
30
|
+
const prefixRegistry = new Map(); // Map<prefix, Set<handler>>(前缀订阅,emitTopic 按 startsWith 分发)
|
|
31
|
+
|
|
32
|
+
function assertTopic(topic) {
|
|
33
|
+
if (typeof topic !== 'string' || topic.length === 0) {
|
|
34
|
+
throw new Error('invalid topic: ' + String(topic));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function boxRoot(root, sessionId, batchId) {
|
|
39
|
+
return join(root, 'sessions', sessionId, 'mailbox', batchId);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function subscribeTopic(topic, handler) {
|
|
43
|
+
assertTopic(topic);
|
|
44
|
+
if (typeof handler !== 'function') throw new Error('invalid handler: ' + String(handler));
|
|
45
|
+
let set = registry.get(topic);
|
|
46
|
+
if (!set) { set = new Set(); registry.set(topic, set); }
|
|
47
|
+
set.add(handler); // 同 topic 同 handler 幂等
|
|
48
|
+
let unsubscribed = false;
|
|
49
|
+
return function unsubscribe() {
|
|
50
|
+
if (unsubscribed) return; // 幂等,重复调用 no-op
|
|
51
|
+
unsubscribed = true;
|
|
52
|
+
const s = registry.get(topic);
|
|
53
|
+
if (s) {
|
|
54
|
+
s.delete(handler);
|
|
55
|
+
if (s.size === 0) registry.delete(topic);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 前缀订阅(R3 SSE hub 订阅 `swarm.` 用,exec-panel-b 新增;签名与 subscribeTopic 同形,handler 收 (topic, payload))
|
|
61
|
+
// 语义:emitTopic(topic) 时,topic.startsWith(prefix) 的前缀订阅者全部收到(精确注册与前缀注册并存、互不影响)
|
|
62
|
+
export function subscribeTopicPrefix(prefix, handler) {
|
|
63
|
+
assertTopic(prefix); // 前缀不得为空(空前缀会匹配一切,禁止)
|
|
64
|
+
if (typeof handler !== 'function') throw new Error('invalid handler: ' + String(handler));
|
|
65
|
+
let set = prefixRegistry.get(prefix);
|
|
66
|
+
if (!set) { set = new Set(); prefixRegistry.set(prefix, set); }
|
|
67
|
+
set.add(handler); // 同 prefix 同 handler 幂等
|
|
68
|
+
let unsubscribed = false;
|
|
69
|
+
return function unsubscribe() {
|
|
70
|
+
if (unsubscribed) return; // 幂等,重复调用 no-op
|
|
71
|
+
unsubscribed = true;
|
|
72
|
+
const s = prefixRegistry.get(prefix);
|
|
73
|
+
if (s) {
|
|
74
|
+
s.delete(handler);
|
|
75
|
+
if (s.size === 0) prefixRegistry.delete(prefix);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function emitTopic(topic, payload, ctx = {}) {
|
|
81
|
+
assertTopic(topic);
|
|
82
|
+
// ① 进程内分发:同步调用,异常隔离(单 handler 抛错不影响其余、不向上传播)
|
|
83
|
+
let delivered = 0;
|
|
84
|
+
const handlers = registry.get(topic);
|
|
85
|
+
if (handlers) {
|
|
86
|
+
for (const h of [...handlers]) {
|
|
87
|
+
try { h(payload); delivered++; } catch { /* 隔离 */ }
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
// ①b 前缀分发(R3 SSE hub 订阅 `swarm.`):handler 收 (topic, payload),异常隔离
|
|
91
|
+
for (const [prefix, prefixHandlers] of prefixRegistry) {
|
|
92
|
+
if (!topic.startsWith(prefix)) continue;
|
|
93
|
+
for (const h of [...prefixHandlers]) {
|
|
94
|
+
try { h(topic, payload); delivered++; } catch { /* 隔离 */ }
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
// ② 可选落 mailbox broadcast box(root/sessionId/batchId 齐备才落盘)
|
|
98
|
+
let sent = 0;
|
|
99
|
+
let ackId = null;
|
|
100
|
+
const { root, sessionId, batchId } = ctx;
|
|
101
|
+
if (root && sessionId && batchId) {
|
|
102
|
+
const msg = { topic, payload, ts: new Date().toISOString() };
|
|
103
|
+
const res = mailboxSend(boxRoot(root, sessionId, batchId), { type: 'broadcast' }, msg);
|
|
104
|
+
sent = res.ok ? 1 : 0;
|
|
105
|
+
ackId = res.ackId ?? null;
|
|
106
|
+
}
|
|
107
|
+
return { delivered, sent, ackId };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function readTopic(root, { sessionId, batchId, topic, sinceTs = 0 } = {}) {
|
|
111
|
+
const items = readUnacked(boxRoot(root, sessionId, batchId), { type: 'broadcast' }, { sinceTs });
|
|
112
|
+
return items
|
|
113
|
+
.filter((it) => it.message?.topic === topic)
|
|
114
|
+
.map((it) => ({ ackId: it.ackId, topic: it.message.topic, payload: it.message.payload, ts: it.message.ts }));
|
|
115
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
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
|
+
// ADP 过滤条件引擎(DiscoveryFilter → 布尔):独立模块,核心无感知。
|
|
19
|
+
// 语义对齐 06-ACPs-spec-ADP §4.2.2:{ field, op, value } 条件数组 + groups 嵌套 + logic(and/or/not)。
|
|
20
|
+
// 数组字段:条件应用于每个元素,任意元素满足即匹配(FilterCondition.field 注释语义)。
|
|
21
|
+
// 运算符:35 个 FilterOperator 全集(eq/ne/exists/gt/gte/lt/lte/between/in/nin/contains/…/hasAllKeys)。
|
|
22
|
+
// 纯函数,零依赖。
|
|
23
|
+
|
|
24
|
+
import { FILTER_OPERATORS } from './schema.js';
|
|
25
|
+
|
|
26
|
+
// ── 字段路径解析:点号分隔;数组字段逐元素取值(任意元素满足即匹配)──
|
|
27
|
+
// 返回候选值数组(可能为空)。对对象路径逐级下钻,遇数组则展平。
|
|
28
|
+
export function resolveField(record, field) {
|
|
29
|
+
if (typeof field !== 'string' || field.length === 0) return [];
|
|
30
|
+
const segs = field.split('.').filter((s) => s.length > 0);
|
|
31
|
+
let current = [record];
|
|
32
|
+
for (const seg of segs) {
|
|
33
|
+
const next = [];
|
|
34
|
+
for (const node of current) {
|
|
35
|
+
if (node === null || node === undefined) continue;
|
|
36
|
+
if (Array.isArray(node)) {
|
|
37
|
+
// 数组字段:逐元素取 seg(如 skills.tags → 每个 skill 的 tags)
|
|
38
|
+
for (const item of node) {
|
|
39
|
+
if (item !== null && item !== undefined && typeof item === 'object' && seg in item) next.push(item[seg]);
|
|
40
|
+
}
|
|
41
|
+
} else if (typeof node === 'object' && seg in node) {
|
|
42
|
+
const v = node[seg];
|
|
43
|
+
if (Array.isArray(v)) {
|
|
44
|
+
for (const item of v) next.push(item);
|
|
45
|
+
} else {
|
|
46
|
+
next.push(v);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
current = next;
|
|
51
|
+
if (current.length === 0) break;
|
|
52
|
+
}
|
|
53
|
+
return current;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ── 单值 vs 运算符(大小写不敏感为默认,Cs 变体大小写敏感)──
|
|
57
|
+
function isCs(op) {
|
|
58
|
+
return typeof op === 'string' && op.endsWith('Cs');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function baseOp(op) {
|
|
62
|
+
return isCs(op) ? op.slice(0, -2) : op;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function norm(v, cs) {
|
|
66
|
+
return (typeof v === 'string' && !cs) ? v.toLowerCase() : v;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function compareValues(a, b) {
|
|
70
|
+
// 数值优先;否则字符串字典序(版本号场景)
|
|
71
|
+
if (typeof a === 'number' && typeof b === 'number') return a - b;
|
|
72
|
+
return String(a).localeCompare(String(b));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ── 数组语义:候选值数组上应用运算符,任意一个满足即匹配(hasAllKeys 除外:需全键)──
|
|
76
|
+
// op 对 value 的语义按参考实现 operators 表:
|
|
77
|
+
// eq/ne/gt/gte/lt/lte/between/in/nin/contains/notContains/startsWith/endsWith/exists 作用于候选值
|
|
78
|
+
// anyOf/allOf/noneOf/size* 作用于「数组字段的整体」(候选值为数组时)
|
|
79
|
+
// hasKey/hasNoKey/hasAnyKey/hasAllKeys 作用于「对象字段」(候选值为对象时)
|
|
80
|
+
export function matchOp(op, candidates, value) {
|
|
81
|
+
const cs = isCs(op);
|
|
82
|
+
const b = baseOp(op);
|
|
83
|
+
const vals = Array.isArray(candidates) ? candidates : [candidates];
|
|
84
|
+
|
|
85
|
+
switch (b) {
|
|
86
|
+
case 'eq':
|
|
87
|
+
return vals.some((v) => norm(v, cs) === norm(value, cs));
|
|
88
|
+
case 'ne':
|
|
89
|
+
return vals.every((v) => norm(v, cs) !== norm(value, cs));
|
|
90
|
+
case 'exists':
|
|
91
|
+
// value=true:字段存在且非空;value=false:字段不存在或为空
|
|
92
|
+
return value === true ? vals.length > 0 : vals.length === 0;
|
|
93
|
+
case 'gt':
|
|
94
|
+
return vals.some((v) => compareValues(v, value) > 0);
|
|
95
|
+
case 'gte':
|
|
96
|
+
return vals.some((v) => compareValues(v, value) >= 0);
|
|
97
|
+
case 'lt':
|
|
98
|
+
return vals.some((v) => compareValues(v, value) < 0);
|
|
99
|
+
case 'lte':
|
|
100
|
+
return vals.some((v) => compareValues(v, value) <= 0);
|
|
101
|
+
case 'between': {
|
|
102
|
+
const [lo, hi] = Array.isArray(value) ? value : [value, value];
|
|
103
|
+
return vals.some((v) => compareValues(v, lo) >= 0 && compareValues(v, hi) <= 0);
|
|
104
|
+
}
|
|
105
|
+
case 'in': {
|
|
106
|
+
const list = Array.isArray(value) ? value : [value];
|
|
107
|
+
return vals.some((v) => list.some((x) => norm(x, cs) === norm(v, cs)));
|
|
108
|
+
}
|
|
109
|
+
case 'nin': {
|
|
110
|
+
const list = Array.isArray(value) ? value : [value];
|
|
111
|
+
return vals.every((v) => !list.some((x) => norm(x, cs) === norm(v, cs)));
|
|
112
|
+
}
|
|
113
|
+
case 'contains':
|
|
114
|
+
return vals.some((v) => norm(String(v ?? ''), cs).includes(norm(String(value ?? ''), cs)));
|
|
115
|
+
case 'notContains':
|
|
116
|
+
return vals.every((v) => !norm(String(v ?? ''), cs).includes(norm(String(value ?? ''), cs)));
|
|
117
|
+
case 'startsWith':
|
|
118
|
+
return vals.some((v) => norm(String(v ?? ''), cs).startsWith(norm(String(value ?? ''), cs)));
|
|
119
|
+
case 'endsWith':
|
|
120
|
+
return vals.some((v) => norm(String(v ?? ''), cs).endsWith(norm(String(value ?? ''), cs)));
|
|
121
|
+
// ── 数组集合运算:候选值数组(可能是数组字段的整体)──
|
|
122
|
+
case 'anyOf': {
|
|
123
|
+
const list = Array.isArray(value) ? value : [value];
|
|
124
|
+
const flat = candidates.flat(Infinity);
|
|
125
|
+
return list.some((x) => flat.some((v) => norm(v, cs) === norm(x, cs)));
|
|
126
|
+
}
|
|
127
|
+
case 'allOf': {
|
|
128
|
+
const list = Array.isArray(value) ? value : [value];
|
|
129
|
+
const flat = candidates.flat(Infinity);
|
|
130
|
+
return list.every((x) => flat.some((v) => norm(v, cs) === norm(x, cs)));
|
|
131
|
+
}
|
|
132
|
+
case 'noneOf': {
|
|
133
|
+
const list = Array.isArray(value) ? value : [value];
|
|
134
|
+
const flat = candidates.flat(Infinity);
|
|
135
|
+
return list.every((x) => !flat.some((v) => norm(v, cs) === norm(x, cs)));
|
|
136
|
+
}
|
|
137
|
+
case 'size': {
|
|
138
|
+
const arr = candidates.find((v) => Array.isArray(v));
|
|
139
|
+
return (arr ?? []).length === Number(value);
|
|
140
|
+
}
|
|
141
|
+
case 'sizeGt':
|
|
142
|
+
case 'sizeGte':
|
|
143
|
+
case 'sizeLt':
|
|
144
|
+
case 'sizeLte': {
|
|
145
|
+
const arr = candidates.find((v) => Array.isArray(v));
|
|
146
|
+
const len = (arr ?? []).length;
|
|
147
|
+
const n = Number(value);
|
|
148
|
+
if (b === 'sizeGt') return len > n;
|
|
149
|
+
if (b === 'sizeGte') return len >= n;
|
|
150
|
+
if (b === 'sizeLt') return len < n;
|
|
151
|
+
return len <= n;
|
|
152
|
+
}
|
|
153
|
+
// ── Map/对象键检查 ──
|
|
154
|
+
case 'hasKey': {
|
|
155
|
+
const keys = Array.isArray(value) ? value : [value];
|
|
156
|
+
return vals.some((v) => v !== null && typeof v === 'object' && !Array.isArray(v) && keys.every((k) => k in v));
|
|
157
|
+
}
|
|
158
|
+
case 'hasNoKey': {
|
|
159
|
+
const keys = Array.isArray(value) ? value : [value];
|
|
160
|
+
return vals.every((v) => v === null || typeof v !== 'object' || Array.isArray(v) || keys.every((k) => !(k in v)));
|
|
161
|
+
}
|
|
162
|
+
case 'hasAnyKey': {
|
|
163
|
+
const keys = Array.isArray(value) ? value : [value];
|
|
164
|
+
return vals.some((v) => v !== null && typeof v === 'object' && !Array.isArray(v) && keys.some((k) => k in v));
|
|
165
|
+
}
|
|
166
|
+
case 'hasAllKeys': {
|
|
167
|
+
const keys = Array.isArray(value) ? value : [value];
|
|
168
|
+
return vals.some((v) => v !== null && typeof v === 'object' && !Array.isArray(v) && keys.every((k) => k in v));
|
|
169
|
+
}
|
|
170
|
+
default:
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ── 单条件求值 ──
|
|
176
|
+
export function matchCondition(record, condition) {
|
|
177
|
+
if (!condition || typeof condition !== 'object') return false;
|
|
178
|
+
if (typeof condition.field !== 'string' || !FILTER_OPERATORS.includes(condition.op)) return false;
|
|
179
|
+
const candidates = resolveField(record, condition.field);
|
|
180
|
+
return matchOp(condition.op, candidates, condition.value);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// ── DiscoveryFilter 递归求值(conditions + groups + logic and/or/not)──
|
|
184
|
+
export function evaluateFilter(record, filter) {
|
|
185
|
+
if (!filter || typeof filter !== 'object') return true; // 无 filter = 不约束
|
|
186
|
+
const logic = filter.logic ?? 'and';
|
|
187
|
+
const results = [];
|
|
188
|
+
|
|
189
|
+
if (Array.isArray(filter.conditions)) {
|
|
190
|
+
for (const c of filter.conditions) results.push(matchCondition(record, c));
|
|
191
|
+
}
|
|
192
|
+
if (Array.isArray(filter.groups)) {
|
|
193
|
+
for (const g of filter.groups) results.push(evaluateFilter(record, g));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (logic === 'or') return results.some(Boolean);
|
|
197
|
+
if (logic === 'not') return !results.every(Boolean);
|
|
198
|
+
return results.every(Boolean); // and(默认)
|
|
199
|
+
}
|