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
@@ -0,0 +1,279 @@
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/types/contracts.ts —— 契约类型层(jiufeng-ts-phase12 · Phase 1 · coder)
19
+ //
20
+ // type-only:本文件只含 type/interface 声明,零值导出、零运行期产物(编译产物为空模块)。
21
+ // 消费方式:
22
+ // - Phase 2 的 5 个模块(schema/schema-v3/machine-rules/gates/wave-plan)转 .ts 后
23
+ // `import type { ... } from '../types/contracts.js'`(import type 编译期擦除);
24
+ // - JS 侧 JSDoc 纯类型引用:`/** @type {import('../types/contracts.js').Batch} */`
25
+ // (JSDoc 类型注解编译期擦除,零运行时 require——JS 文件本身不得 import 本文件)。
26
+ //
27
+ // 单一事实源:字面量联合(MemberState/BatchPhase/SettleState)与 lib/schema.js 常量
28
+ // MEMBER_STATES/BATCH_PHASES/SETTLE_STATES 逐值一致。Phase 1 自包含定义(schema.js
29
+ // 尚为 JS、无类型导出,`import type { ... } from '../schema.js'` 不可行);Phase 2
30
+ // schema.js→schema.ts 转换后按设计 §1.1/§2 改为从 '../schema.js' re-export 派生类型
31
+ // (两处字面量结构等价,切换零风险)。派生方向单向:schema(常量+派生) → contracts(通用形状)
32
+ // → 消费 .ts;类型层 import 全部擦除,无运行期循环依赖风险。
33
+
34
+ // ── §1 甲:枚举字面量联合(与 lib/schema.js 常量逐值一致)──
35
+
36
+ /** 成员状态:pending/running/review 迁移中态 + merged/failed/skipped/conflict 终态 + idle 恢复态(8 值) */
37
+ export type MemberState =
38
+ | 'pending'
39
+ | 'running'
40
+ | 'review'
41
+ | 'merged'
42
+ | 'failed'
43
+ | 'skipped'
44
+ | 'conflict'
45
+ | 'idle';
46
+
47
+ /** 批次阶段:planning/running/paused 非终态 + aborted/complete 终态(5 值) */
48
+ export type BatchPhase = 'planning' | 'running' | 'paused' | 'aborted' | 'complete';
49
+
50
+ /** 结算终态三值(isMemberTerminal 判定 = SETTLE_STATES.includes(s) || s === 'conflict') */
51
+ export type SettleState = 'merged' | 'failed' | 'skipped';
52
+
53
+ // ── §1 乙:迁移表(通用 Record 形态;schema.ts 常量以 satisfies 绑定防漂移)──
54
+
55
+ /** 成员迁移表:from 态 → 合法 to 态列表(只读;运行期只复制后写,不原地改常量) */
56
+ export type TransitionTable = Record<MemberState, readonly MemberState[]>;
57
+
58
+ /** 批次阶段迁移表(同 TransitionTable 语义) */
59
+ export type BatchTransitionTable = Record<BatchPhase, readonly BatchPhase[]>;
60
+
61
+ // ── §1 丙:WavePlanTask(输入/持久双形态)──
62
+
63
+ /** 任务分层:plan(规划)/ exec(执行)/ audit(验收)——Tier3 三层门禁 */
64
+ export type Layer = 'plan' | 'exec' | 'audit';
65
+
66
+ /** 条件子句:产物根内相对路径存在性(normalizeCondition 归一后的对象形态) */
67
+ export interface ConditionClause {
68
+ path: string;
69
+ exists: true;
70
+ }
71
+
72
+ /** 建批输入条件:对象数组(主形态)或字符串简写数组;null/缺省 = 恒满足 */
73
+ export type ConditionInput = ConditionClause[] | string[] | null | undefined;
74
+
75
+ /** 输入形态:wave_plan 建批工具 tasks 入参(id 必填,其余可选) */
76
+ export interface WavePlanTaskInput {
77
+ id: string;
78
+ cmd?: string;
79
+ deps?: string[];
80
+ model?: string;
81
+ tools?: string[];
82
+ layer?: Layer;
83
+ role?: string;
84
+ skills?: string[];
85
+ consume?: string[];
86
+ produce?: string[];
87
+ outputs?: string[];
88
+ condition?: ConditionInput;
89
+ checkpoint?: { steps: number };
90
+ resume?: boolean;
91
+ targets?: string[]; // O2:批次产物根外绝对路径目标文件
92
+ targetsMarker?: string | null;
93
+ }
94
+
95
+ /** 持久形态:buildWavePlan 规范化产物(gates.ts / validateWavePlan / findTask 消费面) */
96
+ export interface WavePlanTask {
97
+ id: string;
98
+ cmd: string; // assembleCmd 产物,恒 string(缺省 '')
99
+ deps: string[]; // 缺省 []
100
+ model: string | null; // 缺省 null
101
+ tools: string[] | null; // 缺省 null
102
+ layer: Layer | null; // 缺省 null(generic 任务)
103
+ role: string | null; // 归一化小写规范名;非法角色保留原值(GATE_ROLE_INVALID 告警)
104
+ skills: string[] | null; // 缺省 null(装配补全或显式声明后为数组)
105
+ consume: string[] | null; // 缺省 null
106
+ produce: string[] | null; // 缺省 null
107
+ outputs: string[] | null; // 缺省 null
108
+ condition: ConditionClause[] | null; // normalizeCondition 产物:统一对象数组;null = 恒满足
109
+ checkpoint: { steps: number } | null; // normalizeResumeContract 产物
110
+ resume: boolean; // 缺省 false
111
+ targets: string[] | null; // 缺省 null(绝对路径数组)
112
+ targetsMarker: string | null; // 缺省 null
113
+ }
114
+
115
+ /** 单 wave 层:wave 序号 + 该层任务列表(topoWaves 分层产物) */
116
+ export interface Wave {
117
+ wave: number;
118
+ tasks: WavePlanTask[];
119
+ }
120
+
121
+ /** buildWavePlan 返回值(建批产物文档) */
122
+ export interface WavePlanDoc {
123
+ schema: number; // SCHEMA_VERSION = 1
124
+ batchId: string;
125
+ team: string; // 'generic' 兜底
126
+ wavePlan: Wave[];
127
+ concurrency: number; // 正整数兜底 5
128
+ warnings: Array<{
129
+ code: string;
130
+ task?: string;
131
+ layer?: string;
132
+ role?: string;
133
+ missing?: string;
134
+ message: string;
135
+ }>;
136
+ }
137
+
138
+ // ── §1 丁:Batch / Lane / BatchEvent ──
139
+
140
+ /** 环防护记账状态(C4 mailbox;batch JSON 唯一事实源,v3 字段) */
141
+ export interface ChainsState {
142
+ chains: Record<string, { edges: Record<string, number>; said: Record<string, string> }>;
143
+ order: string[];
144
+ }
145
+
146
+ /** 断点进度(laneProgress 值形态;status 与成员态对齐,不新增成员态) */
147
+ export interface LaneProgress {
148
+ step: number;
149
+ total: number;
150
+ status: 'running' | 'review';
151
+ updatedAt: string; // ISO
152
+ }
153
+
154
+ /** 断点进度表:laneId → 进度(批次级可选字段;缺省 undefined = 无断点记录) */
155
+ export type LaneProgressMap = Record<string, LaneProgress>;
156
+
157
+ /** 批次对象(v3:store.js createBatch 运行时形态 + schema-v3.js migrateV2toV3 兜底字段) */
158
+ export interface Batch {
159
+ schema: 3; // BATCH_SCHEMA_V3
160
+ sessionId: string;
161
+ batchId: string;
162
+ phase: BatchPhase;
163
+ concurrency: number;
164
+ team: string;
165
+ wavePlan: Wave[]; // 注意:是 Wave 数组(buildWavePlan 产物 .wavePlan 字段)
166
+ lanes: Record<string, MemberState>; // laneId → 成员态(建批全 'pending')
167
+ chains: ChainsState; // v3 字段(chainsDefaults 兜底)
168
+ archived: boolean; // v3 字段(false 缺省;complete 归档后置 true)
169
+ laneProgress?: LaneProgressMap; // v3 可选字段;非法形态经 migrateV2toV3 归一为 undefined(不写字段)
170
+ events: BatchEvent[];
171
+ createdAt: string; // ISO
172
+ updatedAt: string; // ISO
173
+ }
174
+
175
+ /** Lane 视图类型(lanes 记录 + laneProgress 指针的投影;工具/面板消费) */
176
+ export interface Lane {
177
+ id: string;
178
+ state: MemberState;
179
+ progress?: LaneProgress;
180
+ }
181
+
182
+ /** 事件基座:ts + type 必备(store.js newEvent 工厂 = { ts, type, ...fields }) */
183
+ export interface BatchEventBase {
184
+ ts: string;
185
+ type: string;
186
+ }
187
+
188
+ /**
189
+ * 批次事件判别联合:按 lib/state/event-types.js EVT_* 常量值登记 + 兜底分支。
190
+ * 判别字段 type 与 EVT 常量值绑定(常量仍为运行期事实源;gates.ts 内
191
+ * `e.type === EVT.EVT_MEMBER_SETTLED` 与字面量比较两写法并存均可收窄)。
192
+ * 尾部兜底分支保证未知/未来事件不报错(R-01 扩面事件:lane.stalled /
193
+ * lane.over-budget / budget.rejected / worktree.* / gate.role_* /
194
+ * archive.done / system.restored 等——ts+type 必备,其余字段 unknown 可读)。
195
+ */
196
+ export type BatchEvent = BatchEventBase & (
197
+ | { type: 'batch.created'; batchId: string; sessionId: string } // EVT_BATCH_CREATED
198
+ | { type: 'batch.phase'; from: BatchPhase; to: BatchPhase; reason?: string } // EVT_BATCH_PHASE
199
+ | { type: 'batch.failed-escalate'; lane: string; count: number } // EVT_BATCH_FAILED_ESCALATE
200
+ | { type: 'member.settled'; lane: string; from: MemberState; to: MemberState; note: string | null } // EVT_MEMBER_SETTLED
201
+ | { type: 'lane.skipped'; lane: string; from: MemberState; note: string } // EVT_LANE_SKIPPED
202
+ | { type: 'lane.needhuman'; lane: string; path: string | null } // EVT_LANE_NEEDHUMAN
203
+ | { type: 'lane.recycled'; lane: string; from: string; reason: string; note: string | null } // EVT_LANE_RECYCLED
204
+ | { type: 'human.decision'; lane: string; note: string | null } // EVT_HUMAN_DECISION
205
+ | { type: 'asset.claimed'; lane: string | null; source: string; target: string } // EVT_ASSET_CLAIMED
206
+ | { type: 'gate.entry.missing'; lane: string; missing: string[] } // EVT_GATE_ENTRY_MISSING
207
+ | { type: 'gate.exit.missing'; lane: string; code: string; detail: unknown } // EVT_GATE_EXIT_MISSING
208
+ | { type: 'gate.passed'; lane: string; gate: string } // EVT_GATE_PASSED
209
+ | { type: 'gate.target_blocked'; lane: string; code: string; missing: string[]; unchanged: string[] } // EVT_GATE_TARGET_BLOCKED
210
+ | { type: 'gate.target.passed'; lane: string; mode: string; targets: string[] } // EVT_GATE_TARGET_PASSED
211
+ | { type: 'gate.exit_blocked'; lane: string; code: string; command: string | null; exitCode: number | null; detail: string | null; escalation: boolean } // EVT_GATE_EXIT_BLOCKED
212
+ | { type: 'gate.exit'; lane: string; commands: string[]; results: unknown[]; outputTruncated: boolean } // EVT_GATE_EXIT
213
+ | { type: 'gate.needhuman_blocked'; lane: string; code: string; path: string | null } // EVT_GATE_NEEDHUMAN_BLOCKED
214
+ | { type: 'gate.complete_blocked'; code: string; pending?: string[] } // EVT_GATE_COMPLETE_BLOCKED
215
+ | { type: 'archive.failed'; reason: string } // EVT_ARCHIVE_FAILED
216
+ | { type: 'system.recovered'; batchId: string; sessionId: string; recoveredLanes: string[]; detail: unknown[] } // EVT_SYSTEM_RECOVERED
217
+ // 兜底:R-01 扩面事件(lane.stalled / lane.over-budget / budget.rejected /
218
+ // worktree.created|checkpoint|merged|merge.conflict|merge.resolved /
219
+ // gate.role_missing / gate.role_invalid / archive.done / system.restored 等)
220
+ // 与未来新增事件——ts+type 必备,其余字段保持 unknown 可读
221
+ | { type: string; [k: string]: unknown }
222
+ );
223
+
224
+ // ── §1 戊:GateResult 判别联合(gates.js 全部返回点;核心形态 + 载荷可选字段)──
225
+
226
+ /** 门禁失败错误码全量枚举(按层后缀/门禁族;不设通配符,保持穷尽性收益) */
227
+ export type GateErrorCode =
228
+ // entry(consume 前置)
229
+ | 'GATE_ENTRY_MISSING'
230
+ // plan 契约
231
+ | 'GATE_PLAN_CONTRACT'
232
+ // exit(按层后缀)
233
+ | 'GATE_EXIT_MISSING_EXEC' | 'GATE_EXIT_MISSING_AUDIT'
234
+ // needHuman 人工闸
235
+ | 'GATE_NEEDHUMAN_PENDING'
236
+ // 命令 gate(V1)——GATE_EXIT_* 全族
237
+ | 'GATE_EXIT_NO_COMMAND' | 'GATE_EXIT_FORBIDDEN' | 'GATE_EXIT_TIMEOUT'
238
+ | 'GATE_EXIT_SPAWN_FAIL' | 'GATE_EXIT_NONZERO'
239
+ // targets 门禁(O2)
240
+ | 'GATE_TARGET_MISSING' | 'GATE_TARGET_UNCHANGED'
241
+ // complete 门禁
242
+ | 'GATE_COMPLETE_NO_AUDIT' | 'GATE_EXIT_PENDING_AUDIT'
243
+ | 'GATE_COMPLETE_AUDIT_FAILED' | 'GATE_COMPLETE_EXEC_PENDING';
244
+
245
+ /** 门禁通过:ok: true + 各门禁可选载荷 */
246
+ export interface GateOk {
247
+ ok: true;
248
+ // 载荷(各门禁可选携带):
249
+ declared?: boolean; // needHuman / command / targets 门禁的声明探测结果
250
+ commands?: string[]; // command gate:已执行命令(保序)
251
+ results?: Array<{ command: string; exitCode: number | null; durationMs: number }>;
252
+ outputTruncated?: boolean;
253
+ path?: string | null;
254
+ mode?: 'mtime' | 'marker'; // targets 门禁判定模式
255
+ targets?: string[]; // targets 门禁声明清单
256
+ missing?: []; unchanged?: []; // ok 分支恒空数组(与 fail 分支对称,便于调用方统一读取)
257
+ }
258
+
259
+ /** 门禁失败:ok: false + code + 载荷(按门禁族可选携带) */
260
+ export interface GateFail {
261
+ ok: false;
262
+ code: GateErrorCode;
263
+ missing?: string[]; // entry / targets / exit missing
264
+ problems?: string[]; // plan 契约问题清单
265
+ pending?: string[]; // complete 门禁 pending lane 清单
266
+ command?: string | null; // command gate
267
+ exitCode?: number | null;
268
+ detail?: string | null;
269
+ declared?: boolean;
270
+ path?: string | null;
271
+ needHumanEscalation?: boolean; // command gate 失败 + 产物声明 needHuman → 转人工闸
272
+ mode?: 'mtime' | 'marker';
273
+ targets?: string[];
274
+ unchanged?: string[];
275
+ message?: string; // needHuman 门禁提示语
276
+ }
277
+
278
+ /** 门禁结果判别联合:`if (g.ok)` 分支后即可访问 fail/ok 专属载荷字段 */
279
+ export type GateResult = GateOk | GateFail;
@@ -0,0 +1,249 @@
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
+ // verify/evidence.js —— post-execute 捕获 + 内容寻址 blob(C3 成熟模式:dsh-verification CapturedEvidence)
19
+ // 订阅宿主 tools/post-execute(cordis waterfall,pass-through 不断链),从真实 ToolExecutionResult 派生证据;
20
+ // 内容寻址存储(key=contentHash,tmp+rename 原子写,读校验损坏 fail closed,>256KB 截断标记),同内容去重;
21
+ // 控制面工具不产证据。纯逻辑 + 文件 blob(root/verify/blobs + root/verify/ledger-<session>.jsonl,引擎状态根)。
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import { canonicalizeArgs, stableHash } from './selector.js';
25
+ import { SESSION_RE } from '../state/constants.js'; // P1-07 单点(原 :29 定义迁出)
26
+
27
+ // 256KB 截断阈值(对齐 dsh-verification evidence-store 超限截断语义)
28
+ export const MAX_BLOB_BYTES = 256 * 1024;
29
+
30
+ // 控制面工具名单:治理/协调/宿主控制面工具不产证据(结果非领域产出,含本批后续挂载工具)
31
+ export const CONTROL_PLANE_TOOLS = new Set([
32
+ // 蟛蜞治理 core 11 + mailbox 3
33
+ 'wave_plan', 'batch_phase', 'batch_status', 'artifact_types', 'assign_check', 'asset_claim',
34
+ 'gate_status', 'lane_claim', 'lane_release', 'member_settle', 'member_status',
35
+ 'mailbox_send', 'mailbox_read', 'mailbox_ack',
36
+ // 本批后续能力(watch/worktree/budget/trajectory 装配后同样控制面)
37
+ 'lane_heartbeat', 'lane_worktree_create', 'lane_worktree_merge', 'lane_checkpoint',
38
+ // 宿主控制/会话面
39
+ 'ask_user_question', 'describe_image', 'read_image', 'todo_write', 'list_agents',
40
+ 'send_message', 'interrupt_agent', 'job_list', 'job_output', 'job_kill',
41
+ 'memory_save', 'memory_search', 'memory_list', 'memory_update', 'memory_delete', 'memory_archive', 'memory_forget',
42
+ ]);
43
+
44
+ // 证据分类表:工具 → 证据类别(4 类;未映射工具不产证据,保守兜底)
45
+ const KIND_BY_TOOL = {
46
+ // 命令输出:执行型工具的 stdout/结果文本
47
+ pwsh: 'command_output', bash: 'command_output', run_code: 'command_output',
48
+ ssh_exec: 'command_output', ssh_cluster: 'command_output',
49
+ // 文件存在:目录/文件探测结果
50
+ glob: 'file_exists',
51
+ // 带定位引用:read/grep 行号定位文本
52
+ read: 'quote_with_location', grep: 'quote_with_location',
53
+ // 文件差异:写/编辑产生的变更证据
54
+ write: 'file_diff', edit: 'file_diff',
55
+ };
56
+
57
+ export function classifyEvidence(exec) {
58
+ if (!exec || typeof exec.name !== 'string' || !exec.name.length) return null;
59
+ if (CONTROL_PLANE_TOOLS.has(exec.name)) return null;
60
+ return KIND_BY_TOOL[exec.name] ?? null;
61
+ }
62
+
63
+ // 从 ToolExecutionResult 提取展示文本(content 块兼容 string/array/object;失败/空 → '')
64
+ export function extractResultText(result) {
65
+ if (!result) return '';
66
+ const c = result.content;
67
+ if (typeof c === 'string') return c;
68
+ if (Array.isArray(c)) {
69
+ return c.map((b) => {
70
+ if (b === null || b === undefined) return '';
71
+ if (typeof b === 'string') return b;
72
+ if (typeof b === 'object' && typeof b.text === 'string') return b.text;
73
+ return '';
74
+ }).join('\n');
75
+ }
76
+ if (c === undefined || c === null) return '';
77
+ try { return JSON.stringify(c); } catch { return String(c); }
78
+ }
79
+
80
+ // 派生证据(纯函数):控制面/未知工具 → null;其余 → 结构化证据(含 selectorKey 供审计侧全等匹配)
81
+ export function deriveEvidence(exec, result) {
82
+ const kind = classifyEvidence(exec);
83
+ if (!kind) return null;
84
+ const args = exec && exec.arguments && typeof exec.arguments === 'object' ? exec.arguments : {};
85
+ const failed = Boolean(result && result.isError === true);
86
+ return {
87
+ kind,
88
+ tool: exec.name,
89
+ callId: exec.callId ?? null,
90
+ // 与 freezeSelector.argsHash 同源计算(stableHash({tool, canonicalArgs})),审计侧按此匹配 AC
91
+ selectorKey: stableHash({ tool: exec.name, args: canonicalizeArgs(args) }),
92
+ ts: new Date().toISOString(),
93
+ ok: !failed,
94
+ error: failed ? String(result?.error?.message ?? result?.error ?? 'tool error') : null,
95
+ summary: extractResultText(result).slice(0, 512),
96
+ };
97
+ }
98
+
99
+ // ---- 内容寻址 blob 存储(引擎状态根 root/verify/blobs/) ----
100
+ function blobDirOf(root) { return path.join(root, 'verify', 'blobs'); }
101
+ function blobPathOf(root, key) { return path.join(blobDirOf(root), key + '.json'); }
102
+
103
+ // 内容哈希:只对证据的规范字段求值(不含 blobKey 元数据),读校验与写校验共用同一函数
104
+ export function evidenceKey(evidence) {
105
+ return stableHash({
106
+ kind: evidence.kind,
107
+ tool: evidence.tool,
108
+ selectorKey: evidence.selectorKey,
109
+ ok: evidence.ok,
110
+ summary: evidence.summary ?? null,
111
+ });
112
+ }
113
+
114
+ // 原子写 + 写后读校验(损坏 fail closed:删除损坏文件并抛错,不留半成品)
115
+ function writeBlobAtomic(root, key, payload) {
116
+ fs.mkdirSync(blobDirOf(root), { recursive: true });
117
+ const file = blobPathOf(root, key);
118
+ const tmp = file + '.' + process.pid + '.tmp';
119
+ fs.writeFileSync(tmp, payload, 'utf8');
120
+ try {
121
+ const written = JSON.parse(fs.readFileSync(tmp, 'utf8'));
122
+ // truncated 记录只保留截断摘要,内容哈希必然不等于原始 key → 仅校验 key 字段;
123
+ // 完整记录才做内容哈希核对(写后读校验,fail closed)
124
+ if (written.key !== key) throw new Error('write verify failed: key mismatch');
125
+ if (written.truncated !== true && evidenceKey(written) !== key) throw new Error('write verify failed: content hash mismatch');
126
+ fs.renameSync(tmp, file);
127
+ } catch (e) {
128
+ try { fs.unlinkSync(tmp); } catch {}
129
+ throw new Error('blob write failed (fail closed): ' + key + ' — ' + String(e?.message ?? e));
130
+ }
131
+ return key;
132
+ }
133
+
134
+ // 内容寻址写入:key=contentHash;同内容去重(已存在直接返回既有 key,不重写);>256KB 截断标记
135
+ export function storeBlob(root, evidence) {
136
+ if (!evidence || typeof evidence.kind !== 'string') throw new Error('storeBlob: invalid evidence');
137
+ const key = evidenceKey(evidence);
138
+ const file = blobPathOf(root, key);
139
+ if (fs.existsSync(file)) return key; // 去重:同内容只存一份,blobKey 稳定
140
+ const payload = JSON.stringify({ key, ...evidence }, null, 2);
141
+ if (Buffer.byteLength(payload, 'utf8') > MAX_BLOB_BYTES) {
142
+ const truncated = {
143
+ key, truncated: true, kind: evidence.kind, tool: evidence.tool,
144
+ selectorKey: evidence.selectorKey, ok: evidence.ok,
145
+ summary: (evidence.summary ?? '').slice(0, 2000),
146
+ note: 'evidence truncated at ' + MAX_BLOB_BYTES + ' bytes',
147
+ };
148
+ writeBlobAtomic(root, key, JSON.stringify(truncated, null, 2));
149
+ return key;
150
+ }
151
+ writeBlobAtomic(root, key, payload);
152
+ return key;
153
+ }
154
+
155
+ // 读校验:损坏 fail closed(key 不匹配 / 内容哈希不匹配 / 不可解析 → 抛错,绝不以损坏内容裁决)
156
+ export function readBlob(root, key) {
157
+ if (typeof key !== 'string' || !key.length) throw new Error('readBlob: key required');
158
+ const file = blobPathOf(root, key);
159
+ if (!fs.existsSync(file)) throw new Error('blob not found: ' + key);
160
+ let data;
161
+ try { data = JSON.parse(fs.readFileSync(file, 'utf8')); }
162
+ catch { throw new Error('blob corrupted (unparseable): ' + key); }
163
+ if (data.key !== key) throw new Error('blob corrupted (key mismatch): ' + key);
164
+ if (data.truncated !== true && evidenceKey(data) !== key) {
165
+ throw new Error('blob corrupted (content hash mismatch): ' + key);
166
+ }
167
+ return data;
168
+ }
169
+
170
+ // ---- 每会话捕获台账(jsonl 追加写;审计 lane 按会话/selectorKey 消费) ----
171
+ function ledgerFileOf(root, sessionId) {
172
+ if (!SESSION_RE.test(String(sessionId))) throw new Error('invalid sessionId: ' + sessionId);
173
+ return path.join(root, 'verify', 'ledger-' + sessionId + '.jsonl');
174
+ }
175
+
176
+ export function appendLedger(root, sessionId, entry) {
177
+ const file = ledgerFileOf(root, sessionId);
178
+ fs.mkdirSync(path.dirname(file), { recursive: true });
179
+ fs.appendFileSync(file, JSON.stringify(entry) + '\n', 'utf8');
180
+ }
181
+
182
+ // 读取台账:可按 selectorKey / tool 过滤;损坏行跳过(台账尽力而为,blob 仍可单查)
183
+ export function readLedger(root, sessionId, { selectorKey, tool } = {}) {
184
+ const file = ledgerFileOf(root, sessionId);
185
+ if (!fs.existsSync(file)) return [];
186
+ const out = [];
187
+ for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
188
+ if (!line.trim()) continue;
189
+ try {
190
+ const e = JSON.parse(line);
191
+ if (selectorKey && e.selectorKey !== selectorKey) continue;
192
+ if (tool && e.tool !== tool) continue;
193
+ out.push(e);
194
+ } catch { /* 跳过损坏行 */ }
195
+ }
196
+ return out;
197
+ }
198
+
199
+ // ---- 证据绑定注册表(audit lane 侧:按 AC 冻结 selector 匹配台账 → bindEvidence → 供裁决) ----
200
+ export function createEvidenceRegistry() {
201
+ const bindings = new Map(); // acId -> [{ selectorRef, blobKey }]
202
+
203
+ return {
204
+ // 捕获 → 绑定:同一 AC 同 blobKey 幂等(去重)
205
+ bindEvidence(acId, selectorRef, blobKey) {
206
+ if (typeof acId !== 'string' || !acId.length) throw new Error('bindEvidence: acId required');
207
+ if (typeof selectorRef !== 'string' || !selectorRef.length) throw new Error('bindEvidence: selectorRef required');
208
+ if (typeof blobKey !== 'string' || !blobKey.length) throw new Error('bindEvidence: blobKey required');
209
+ const list = bindings.get(acId) ?? [];
210
+ if (!list.some((b) => b.blobKey === blobKey && b.selectorRef === selectorRef)) {
211
+ list.push({ selectorRef, blobKey });
212
+ }
213
+ bindings.set(acId, list);
214
+ return { acId, selectorRef, blobKey, bound: true };
215
+ },
216
+ bindingsFor(acId) { return bindings.get(acId) ?? []; },
217
+ all() { return [...bindings.entries()].map(([acId, list]) => ({ acId, evidence: list })); },
218
+ size() { return bindings.size; },
219
+ clear() { bindings.clear(); },
220
+ };
221
+ }
222
+
223
+ // ---- post-execute 捕获安装(enabled 缺省关,V5:enabled=false 零运行时开销) ----
224
+ // 订阅宿主 tools/post-execute waterfall:观察派生证据 → 落 blob + 台账;pass-through 不断链(return next())。
225
+ // 捕获失败只记录不抛(观察者不得破坏工具执行链)。
226
+ export function installEvidenceCapture(ctx, opts = {}) {
227
+ const { root, enabled = false, onCaptured } = opts;
228
+ if (enabled !== true || !root || typeof ctx?.on !== 'function') {
229
+ return { dispose: () => {}, count: () => 0, installed: false };
230
+ }
231
+ let captured = 0;
232
+ const listener = (exec, result, next) => {
233
+ try {
234
+ const evidence = deriveEvidence(exec, result);
235
+ if (evidence) {
236
+ const blobKey = storeBlob(root, evidence);
237
+ const sessionId = exec?.agent?.session?.id ?? 'cli';
238
+ appendLedger(root, sessionId, { blobKey, ...evidence });
239
+ captured++;
240
+ if (typeof onCaptured === 'function') onCaptured({ blobKey, ...evidence });
241
+ }
242
+ } catch (e) {
243
+ ctx.logger?.warn?.('[verify] evidence capture failed: ' + String(e?.message ?? e));
244
+ }
245
+ return next(); // pass-through:不断链(下游决策原样透传)
246
+ };
247
+ const dispose = ctx.on('tools/post-execute', listener);
248
+ return { dispose, count: () => captured, installed: true };
249
+ }