skill-family-studio 0.2.0 → 0.2.2

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.
@@ -0,0 +1,894 @@
1
+ // @feature STU004
2
+ // @feature STU005
3
+
4
+ /**
5
+ * Studio 多会话编排蓝图画布与契约受限编辑器(Wave 4D-3 / M2-1):
6
+ * 1. 全程采用标准 DOM createElement / textContent 构建(零 innerHTML);
7
+ * 2. 下拉选择框严格锁定 skill-family-contracts@0.39.2 OrchestrationBlueprint 枚举集,消除手工拼写摩擦;
8
+ * 3. 内置起步蓝图模板(分诊-校验-异构独立复核-HITL 门禁 / 只读合规扫描-单向结论);
9
+ * 4. 实时执行图连通性、独立复核防自审与外部副作用 HITL 门禁支配检查,并同步计算规范化 JSON SHA-256 摘要(blueprintRef)。
10
+ */
11
+
12
+ export const BLUEPRINT_ENUMS = Object.freeze({
13
+ executor: Object.freeze(['llm_session', 'deterministic_script', 'mcp_tool', 'human_task']),
14
+ role: Object.freeze(['coordinator', 'worker', 'reviewer', 'approver']),
15
+ decisionAuthority: Object.freeze(['none', 'recommend', 'final_veto']),
16
+ modelTier: Object.freeze([
17
+ 'flagship_reasoning',
18
+ 'balanced_coding',
19
+ 'fast_lightweight',
20
+ 'deterministic_no_llm',
21
+ ]),
22
+ sideEffectCeiling: Object.freeze(['read_only', 'workspace_write', 'external_side_effect']),
23
+ workspaceMode: Object.freeze(['inherit', 'share', 'branch', 'fresh_readonly']),
24
+ mergeBack: Object.freeze(['none', 'coordinator_merge', 'patch_submission']),
25
+ contextMode: Object.freeze(['fresh', 'forked', 'summary_handoff']),
26
+ toolKind: Object.freeze(['script', 'mcp', 'host_builtin']),
27
+ exitMeaning: Object.freeze(['success', 'retryable', 'fatal', 'needs_input']),
28
+ edgeKind: Object.freeze([
29
+ 'delegate_spawn',
30
+ 'sequential_handoff',
31
+ 'review_submission',
32
+ 'rework_feedback',
33
+ ]),
34
+ handoffContract: Object.freeze([
35
+ 'task-handoff-envelope',
36
+ 'continuation-package',
37
+ 'professional-conclusion',
38
+ 'artifact_bundle',
39
+ ]),
40
+ hitlPlacement: Object.freeze(['before_node', 'after_node', 'on_edge']),
41
+ hitlTimeout: Object.freeze(['block_and_wait', 'abort_run']),
42
+ });
43
+
44
+ const K256 = new Uint32Array([
45
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
46
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
47
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
48
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
49
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
50
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
51
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
52
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
53
+ ]);
54
+
55
+ function rotr(x, n) {
56
+ return (x >>> n) | (x << (32 - n));
57
+ }
58
+
59
+ export function computeSha256HexSync(text) {
60
+ const bytes = new TextEncoder().encode(String(text));
61
+ const bitLenHi = Math.floor((bytes.length * 8) / 0x100000000);
62
+ const bitLenLo = (bytes.length * 8) >>> 0;
63
+ const padLen = (((bytes.length + 9 + 63) >> 6) << 6);
64
+ const buf = new Uint8Array(padLen);
65
+ buf.set(bytes);
66
+ buf[bytes.length] = 0x80;
67
+ const dv = new DataView(buf.buffer);
68
+ dv.setUint32(padLen - 8, bitLenHi, false);
69
+ dv.setUint32(padLen - 4, bitLenLo, false);
70
+
71
+ const H = new Uint32Array([
72
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
73
+ 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
74
+ ]);
75
+ const W = new Uint32Array(64);
76
+
77
+ for (let offset = 0; offset < padLen; offset += 64) {
78
+ for (let i = 0; i < 16; i += 1) {
79
+ W[i] = dv.getUint32(offset + i * 4, false);
80
+ }
81
+ for (let i = 16; i < 64; i += 1) {
82
+ const s0 = rotr(W[i - 15], 7) ^ rotr(W[i - 15], 18) ^ (W[i - 15] >>> 3);
83
+ const s1 = rotr(W[i - 2], 17) ^ rotr(W[i - 2], 19) ^ (W[i - 2] >>> 10);
84
+ W[i] = (W[i - 16] + s0 + W[i - 7] + s1) >>> 0;
85
+ }
86
+ let [a, b, c, d, e, f, g, h] = H;
87
+ for (let i = 0; i < 64; i += 1) {
88
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
89
+ const ch = (e & f) ^ (~e & g);
90
+ const temp1 = (h + S1 + ch + K256[i] + W[i]) >>> 0;
91
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
92
+ const maj = (a & b) ^ (a & c) ^ (b & c);
93
+ const temp2 = (S0 + maj) >>> 0;
94
+ h = g;
95
+ g = f;
96
+ f = e;
97
+ e = (d + temp1) >>> 0;
98
+ d = c;
99
+ c = b;
100
+ b = a;
101
+ a = (temp1 + temp2) >>> 0;
102
+ }
103
+ H[0] = (H[0] + a) >>> 0;
104
+ H[1] = (H[1] + b) >>> 0;
105
+ H[2] = (H[2] + c) >>> 0;
106
+ H[3] = (H[3] + d) >>> 0;
107
+ H[4] = (H[4] + e) >>> 0;
108
+ H[5] = (H[5] + f) >>> 0;
109
+ H[6] = (H[6] + g) >>> 0;
110
+ H[7] = (H[7] + h) >>> 0;
111
+ }
112
+
113
+ return Array.from(H)
114
+ .map((v) => v.toString(16).padStart(8, '0'))
115
+ .join('');
116
+ }
117
+
118
+ function canonicalJson(val) {
119
+ if (val === undefined) {
120
+ throw new TypeError('OrchestrationBlueprint cannot serialize undefined values');
121
+ }
122
+ if (val === null || typeof val !== 'object') return JSON.stringify(val);
123
+ if (Array.isArray(val)) return `[${val.map(canonicalJson).join(',')}]`;
124
+ const keys = Object.keys(val).sort();
125
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(val[k])}`).join(',')}}`;
126
+ }
127
+
128
+ export function computeBlueprintDigestSync(blueprint) {
129
+ return computeSha256HexSync(canonicalJson(blueprint));
130
+ }
131
+
132
+ export const CANVAS_STARTER_PRESETS = Object.freeze({
133
+ 'triage-validate-review-hitl': () => ({
134
+ schemaVersion: 1,
135
+ kind: 'skill-family.orchestration-blueprint',
136
+ blueprintId: 'bp-domain-triage-validate-review-v1',
137
+ skillFamilyId: 'example-domain-family',
138
+ version: '0.1.0',
139
+ title: '分诊路由、受限工作区校验、异构独立复核与 HITL 门禁蓝图',
140
+ summary: '只读分诊协调器委派受限写集执行节点,经异构模型只读独立复核后,在 plan_approve_digest 门禁保护下执行外部受控落盘。',
141
+ entryNodeId: 'n-triage',
142
+ terminalNodeIds: ['n-reviewer', 'n-apply'],
143
+ toolContracts: [
144
+ {
145
+ toolId: 'tool-triage',
146
+ kind: 'script',
147
+ inputSchemaRef: null,
148
+ outputSchemaRef: null,
149
+ sideEffectClass: 'read_only',
150
+ deterministic: true,
151
+ timeoutPolicyRef: null,
152
+ exitSemantics: [
153
+ { code: 0, meaning: 'success' },
154
+ { code: 2, meaning: 'needs_input' },
155
+ ],
156
+ },
157
+ {
158
+ toolId: 'tool-validate',
159
+ kind: 'script',
160
+ inputSchemaRef: null,
161
+ outputSchemaRef: 'schemas/validation-report.schema.json',
162
+ sideEffectClass: 'workspace_write',
163
+ deterministic: true,
164
+ timeoutPolicyRef: null,
165
+ exitSemantics: [
166
+ { code: 0, meaning: 'success' },
167
+ { code: 1, meaning: 'fatal' },
168
+ { code: 2, meaning: 'needs_input' },
169
+ ],
170
+ },
171
+ {
172
+ toolId: 'tool-read-ref',
173
+ kind: 'host_builtin',
174
+ inputSchemaRef: null,
175
+ outputSchemaRef: null,
176
+ sideEffectClass: 'read_only',
177
+ deterministic: true,
178
+ timeoutPolicyRef: null,
179
+ exitSemantics: [{ code: 0, meaning: 'success' }],
180
+ },
181
+ {
182
+ toolId: 'tool-apply',
183
+ kind: 'script',
184
+ inputSchemaRef: null,
185
+ outputSchemaRef: 'schemas/apply-receipt.schema.json',
186
+ sideEffectClass: 'external_side_effect',
187
+ deterministic: true,
188
+ timeoutPolicyRef: null,
189
+ exitSemantics: [
190
+ { code: 0, meaning: 'success' },
191
+ { code: 2, meaning: 'needs_input' },
192
+ ],
193
+ },
194
+ ],
195
+ nodes: [
196
+ {
197
+ nodeId: 'n-triage',
198
+ executor: 'llm_session',
199
+ role: 'coordinator',
200
+ decisionAuthority: 'recommend',
201
+ title: '一句话需求分诊协调节点',
202
+ responsibility: '只读解析用户意图并拦截越界请求。',
203
+ modelTier: 'flagship_reasoning',
204
+ allowedHosts: ['deepseek-harness', 'claude-code', 'codex'],
205
+ sideEffectCeiling: 'read_only',
206
+ allowedWriteSet: [],
207
+ allowedTools: ['tool-triage', 'tool-read-ref'],
208
+ skillBindings: [],
209
+ isolation: { workspaceMode: 'fresh_readonly', mergeBack: 'none', contextMode: 'fresh' },
210
+ onFailure: { route: 'abort', maxRetries: 0 },
211
+ hostRequirements: { requiredCapabilities: ['subagent_spawn'] },
212
+ hostFallbackPolicy: [],
213
+ completionCriteria: [],
214
+ },
215
+ {
216
+ nodeId: 'n-worker',
217
+ executor: 'llm_session',
218
+ role: 'worker',
219
+ decisionAuthority: 'none',
220
+ title: '受限写集确定性校验节点',
221
+ responsibility: '在 work/** 写集内运行确定性校验脚本并产出结构化报告。',
222
+ modelTier: 'balanced_coding',
223
+ allowedHosts: ['deepseek-harness', 'claude-code', 'codex'],
224
+ sideEffectCeiling: 'workspace_write',
225
+ allowedWriteSet: ['work/**'],
226
+ allowedTools: ['tool-validate', 'tool-read-ref'],
227
+ skillBindings: [],
228
+ isolation: { workspaceMode: 'share', mergeBack: 'coordinator_merge', contextMode: 'fresh' },
229
+ onFailure: { route: 'n-triage', maxRetries: 1 },
230
+ hostRequirements: { requiredCapabilities: ['os_sandbox', 'fs_snapshot'] },
231
+ hostFallbackPolicy: [],
232
+ completionCriteria: [{ evidenceKey: 'ev-report' }],
233
+ },
234
+ {
235
+ nodeId: 'n-reviewer',
236
+ executor: 'llm_session',
237
+ role: 'reviewer',
238
+ decisionAuthority: 'final_veto',
239
+ title: '异构模型认知独立复核员',
240
+ responsibility: '在全新只读上下文与异构模型家族下核验业务语义与证据闭环。',
241
+ modelTier: 'flagship_reasoning',
242
+ allowedHosts: ['claude-code', 'codex'],
243
+ sideEffectCeiling: 'read_only',
244
+ allowedWriteSet: [],
245
+ allowedTools: ['tool-read-ref'],
246
+ skillBindings: [],
247
+ isolation: { workspaceMode: 'fresh_readonly', mergeBack: 'none', contextMode: 'fresh' },
248
+ independence: {
249
+ reviewsNodes: ['n-worker'],
250
+ requireFreshContext: true,
251
+ requireDistinctModelFamily: true,
252
+ forbidWriteTools: true,
253
+ },
254
+ onFailure: { route: 'n-triage', maxRetries: 0 },
255
+ hostRequirements: { requiredCapabilities: [] },
256
+ hostFallbackPolicy: [],
257
+ completionCriteria: [],
258
+ },
259
+ {
260
+ nodeId: 'n-apply',
261
+ executor: 'deterministic_script',
262
+ role: 'worker',
263
+ decisionAuthority: 'none',
264
+ title: '受控外部落盘节点',
265
+ responsibility: '经人工摘要审批放行后调用确定性脚本完成落盘。',
266
+ modelTier: 'deterministic_no_llm',
267
+ allowedHosts: ['deepseek-harness', 'claude-code', 'codex'],
268
+ sideEffectCeiling: 'external_side_effect',
269
+ allowedWriteSet: [],
270
+ allowedTools: ['tool-apply'],
271
+ skillBindings: [],
272
+ isolation: { workspaceMode: 'inherit', mergeBack: 'none', contextMode: 'fresh' },
273
+ onFailure: { route: 'n-triage', maxRetries: 0 },
274
+ hostRequirements: { requiredCapabilities: ['hitl_prompt'] },
275
+ hostFallbackPolicy: [],
276
+ completionCriteria: [],
277
+ },
278
+ ],
279
+ edges: [
280
+ {
281
+ edgeId: 'e-triage-worker',
282
+ fromNodeId: 'n-triage',
283
+ toNodeId: 'n-worker',
284
+ edgeKind: 'delegate_spawn',
285
+ condition: 'route == validate',
286
+ handoff: {
287
+ contract: 'task-handoff-envelope',
288
+ freeTextOnlyForbidden: true,
289
+ requiredUpstreamEvidence: [],
290
+ },
291
+ },
292
+ {
293
+ edgeId: 'e-worker-reviewer',
294
+ fromNodeId: 'n-worker',
295
+ toNodeId: 'n-reviewer',
296
+ edgeKind: 'review_submission',
297
+ condition: null,
298
+ handoff: {
299
+ contract: 'artifact_bundle',
300
+ freeTextOnlyForbidden: true,
301
+ requiredUpstreamEvidence: ['ev-report'],
302
+ },
303
+ },
304
+ {
305
+ edgeId: 'e-reviewer-apply',
306
+ fromNodeId: 'n-reviewer',
307
+ toNodeId: 'n-apply',
308
+ edgeKind: 'sequential_handoff',
309
+ condition: 'approved_and_apply_requested',
310
+ handoff: {
311
+ contract: 'professional-conclusion',
312
+ freeTextOnlyForbidden: true,
313
+ requiredUpstreamEvidence: ['ev-report'],
314
+ },
315
+ },
316
+ ],
317
+ expectedEvidence: [
318
+ {
319
+ evidenceKey: 'ev-report',
320
+ kind: 'artifact',
321
+ pathPattern: 'work/report.md',
322
+ schemaRef: 'schemas/validation-report.schema.json',
323
+ producedBy: 'n-worker',
324
+ verifiedBy: 'n-reviewer',
325
+ critical: true,
326
+ },
327
+ ],
328
+ hitlGates: [
329
+ {
330
+ gateId: 'gate-apply',
331
+ placement: 'before_node',
332
+ attachToNodeId: 'n-apply',
333
+ edgeId: null,
334
+ protocol: 'plan_approve_digest',
335
+ coversSideEffects: ['external_side_effect'],
336
+ approverRole: 'domain_owner',
337
+ triggerReason: '触发外部写入前必须经领域负责人摘要审批',
338
+ timeoutSeconds: 600,
339
+ onTimeout: 'block_and_wait',
340
+ onReject: { route: 'n-triage' },
341
+ },
342
+ ],
343
+ budgetAndSafetyPolicy: {
344
+ contextPolicy: {
345
+ warnRatioBp: 4000,
346
+ hardStopRatioBp: 8500,
347
+ onWarn: 'warn_and_handoff',
348
+ },
349
+ maxTotalTokens: 240000,
350
+ maxCostMicroUsd: 1200000,
351
+ maxWallClockSeconds: 900,
352
+ onBudgetExceeded: 'pause_for_hitl',
353
+ sandboxPolicy: {
354
+ requireOsSandbox: true,
355
+ networkAccess: 'none',
356
+ },
357
+ },
358
+ }),
359
+ 'deterministic-audit-gate': () => ({
360
+ schemaVersion: 1,
361
+ kind: 'skill-family.orchestration-blueprint',
362
+ blueprintId: 'tpl-readonly-audit-conclusion-v1',
363
+ skillFamilyId: 'example-audit-family',
364
+ version: '0.1.0',
365
+ title: '只读合规扫描与单向专业结论独立复核蓝图',
366
+ summary: '只读扫描目标工作区并将机器报告落入 .runs/**,经认知独立复核节点核验后签发单向 professional-conclusion。',
367
+ entryNodeId: 'n-scan',
368
+ terminalNodeIds: ['n-review'],
369
+ toolContracts: [
370
+ {
371
+ toolId: 'tool-scan',
372
+ kind: 'script',
373
+ inputSchemaRef: null,
374
+ outputSchemaRef: 'schemas/scan-report.schema.json',
375
+ sideEffectClass: 'workspace_write',
376
+ deterministic: true,
377
+ timeoutPolicyRef: null,
378
+ exitSemantics: [
379
+ { code: 0, meaning: 'success' },
380
+ { code: 1, meaning: 'fatal' },
381
+ ],
382
+ },
383
+ {
384
+ toolId: 'tool-read-report',
385
+ kind: 'host_builtin',
386
+ inputSchemaRef: null,
387
+ outputSchemaRef: null,
388
+ sideEffectClass: 'read_only',
389
+ deterministic: true,
390
+ timeoutPolicyRef: null,
391
+ exitSemantics: [{ code: 0, meaning: 'success' }],
392
+ },
393
+ ],
394
+ nodes: [
395
+ {
396
+ nodeId: 'n-scan',
397
+ executor: 'deterministic_script',
398
+ role: 'worker',
399
+ decisionAuthority: 'none',
400
+ title: '确定性静态扫描节点',
401
+ responsibility: '只读扫描受检目录并将结构化结果写入 .runs/**。',
402
+ modelTier: 'deterministic_no_llm',
403
+ allowedHosts: ['deepseek-harness', 'claude-code', 'codex'],
404
+ sideEffectCeiling: 'workspace_write',
405
+ allowedWriteSet: ['.runs/**'],
406
+ allowedTools: ['tool-scan'],
407
+ skillBindings: [],
408
+ isolation: { workspaceMode: 'share', mergeBack: 'coordinator_merge', contextMode: 'fresh' },
409
+ onFailure: { route: 'abort', maxRetries: 0 },
410
+ hostRequirements: { requiredCapabilities: ['os_sandbox'] },
411
+ hostFallbackPolicy: [],
412
+ completionCriteria: [{ evidenceKey: 'ev-conclusion' }],
413
+ },
414
+ {
415
+ nodeId: 'n-review',
416
+ executor: 'llm_session',
417
+ role: 'reviewer',
418
+ decisionAuthority: 'final_veto',
419
+ title: '单向结论认知独立复核节点',
420
+ responsibility: '核验扫描范围与哈希绑定完整性。',
421
+ modelTier: 'flagship_reasoning',
422
+ allowedHosts: ['claude-code', 'codex'],
423
+ sideEffectCeiling: 'read_only',
424
+ allowedWriteSet: [],
425
+ allowedTools: ['tool-read-report'],
426
+ skillBindings: [],
427
+ isolation: { workspaceMode: 'fresh_readonly', mergeBack: 'none', contextMode: 'fresh' },
428
+ independence: {
429
+ reviewsNodes: ['n-scan'],
430
+ requireFreshContext: true,
431
+ requireDistinctModelFamily: true,
432
+ forbidWriteTools: true,
433
+ },
434
+ onFailure: { route: 'abort', maxRetries: 0 },
435
+ hostRequirements: { requiredCapabilities: [] },
436
+ hostFallbackPolicy: [],
437
+ completionCriteria: [],
438
+ },
439
+ ],
440
+ edges: [
441
+ {
442
+ edgeId: 'e-scan-review',
443
+ fromNodeId: 'n-scan',
444
+ toNodeId: 'n-review',
445
+ edgeKind: 'review_submission',
446
+ condition: null,
447
+ handoff: {
448
+ contract: 'professional-conclusion',
449
+ freeTextOnlyForbidden: true,
450
+ requiredUpstreamEvidence: ['ev-conclusion'],
451
+ },
452
+ },
453
+ ],
454
+ expectedEvidence: [
455
+ {
456
+ evidenceKey: 'ev-conclusion',
457
+ kind: 'professional_conclusion',
458
+ pathPattern: '.runs/conclusion.json',
459
+ schemaRef: null,
460
+ producedBy: 'n-scan',
461
+ verifiedBy: 'n-review',
462
+ critical: true,
463
+ },
464
+ ],
465
+ hitlGates: [],
466
+ budgetAndSafetyPolicy: {
467
+ contextPolicy: {
468
+ warnRatioBp: 4000,
469
+ hardStopRatioBp: 8000,
470
+ onWarn: 'warn_and_handoff',
471
+ },
472
+ maxTotalTokens: 120000,
473
+ maxCostMicroUsd: 600000,
474
+ maxWallClockSeconds: 600,
475
+ onBudgetExceeded: 'abort',
476
+ sandboxPolicy: {
477
+ requireOsSandbox: true,
478
+ networkAccess: 'none',
479
+ },
480
+ },
481
+ }),
482
+ });
483
+
484
+ const SIDE_EFFECT_RANK = Object.freeze({
485
+ read_only: 0,
486
+ workspace_write: 1,
487
+ external_side_effect: 2,
488
+ });
489
+
490
+ export function validateBlueprintCanvasDraft(bp) {
491
+ const issues = [];
492
+ if (!bp || typeof bp !== 'object') {
493
+ return { valid: false, issues: ['蓝图根对象缺失'] };
494
+ }
495
+ const nodeMap = new Map((bp.nodes || []).map((n) => [n.nodeId, n]));
496
+ const toolMap = new Map((bp.toolContracts || []).map((t) => [t.toolId, t]));
497
+
498
+ if (!nodeMap.has(bp.entryNodeId)) {
499
+ issues.push(`入口节点 ${bp.entryNodeId} 不存在于 nodes 列表中`);
500
+ }
501
+ for (const termId of bp.terminalNodeIds || []) {
502
+ if (!nodeMap.has(termId)) {
503
+ issues.push(`终止节点 ${termId} 不存在于 nodes 列表中`);
504
+ }
505
+ }
506
+
507
+ const incomingEdgesByNode = new Map((bp.nodes || []).map((n) => [n.nodeId, []]));
508
+ const forwardAdj = new Map((bp.nodes || []).map((n) => [n.nodeId, []]));
509
+ for (const edge of bp.edges || []) {
510
+ if (!nodeMap.has(edge.fromNodeId) || !nodeMap.has(edge.toNodeId)) {
511
+ issues.push(`有向边 ${edge.edgeId} 引用了不存在的起止节点`);
512
+ continue;
513
+ }
514
+ if (edge.fromNodeId === edge.toNodeId) {
515
+ issues.push(`有向边 ${edge.edgeId} 不允许节点自环`);
516
+ }
517
+ incomingEdgesByNode.get(edge.toNodeId)?.push(edge);
518
+ if (edge.edgeKind !== 'rework_feedback') {
519
+ forwardAdj.get(edge.fromNodeId)?.push(edge.toNodeId);
520
+ }
521
+ }
522
+
523
+ // 主干有向无环(DAG)与入口可达性核验
524
+ if (nodeMap.has(bp.entryNodeId)) {
525
+ const reachable = new Set();
526
+ const queue = [bp.entryNodeId];
527
+ while (queue.length > 0) {
528
+ const cur = queue.shift();
529
+ if (reachable.has(cur)) continue;
530
+ reachable.add(cur);
531
+ for (const nxt of forwardAdj.get(cur) || []) {
532
+ if (!reachable.has(nxt)) queue.push(nxt);
533
+ }
534
+ }
535
+ for (const n of bp.nodes || []) {
536
+ if (!reachable.has(n.nodeId)) {
537
+ issues.push(`节点 ${n.nodeId} 无法从入口节点 ${bp.entryNodeId} 到达`);
538
+ }
539
+ }
540
+ }
541
+ const visitState = new Map();
542
+ const hasForwardCycle = (u) => {
543
+ visitState.set(u, 1);
544
+ for (const v of forwardAdj.get(u) || []) {
545
+ const st = visitState.get(v) || 0;
546
+ if (st === 1) return true;
547
+ if (st === 0 && hasForwardCycle(v)) return true;
548
+ }
549
+ visitState.set(u, 2);
550
+ return false;
551
+ };
552
+ for (const n of bp.nodes || []) {
553
+ if (!visitState.has(n.nodeId) && hasForwardCycle(n.nodeId)) {
554
+ issues.push('非返工边存在有向环路(违反主干 DAG 约束)');
555
+ break;
556
+ }
557
+ }
558
+
559
+ for (const node of bp.nodes || []) {
560
+ if (!BLUEPRINT_ENUMS.executor.includes(node.executor)) {
561
+ issues.push(`节点 ${node.nodeId} 的 executor="${String(node.executor)}" 不在受控枚举内`);
562
+ }
563
+ if (!BLUEPRINT_ENUMS.role.includes(node.role)) {
564
+ issues.push(`节点 ${node.nodeId} 的 role="${String(node.role)}" 不在受控枚举内`);
565
+ }
566
+ if (!BLUEPRINT_ENUMS.decisionAuthority.includes(node.decisionAuthority)) {
567
+ issues.push(`节点 ${node.nodeId} 的 decisionAuthority="${String(node.decisionAuthority)}" 不在受控枚举内`);
568
+ }
569
+ if (!BLUEPRINT_ENUMS.modelTier.includes(node.modelTier)) {
570
+ issues.push(`节点 ${node.nodeId} 的 modelTier="${String(node.modelTier)}" 不在受控枚举内`);
571
+ }
572
+ if (!BLUEPRINT_ENUMS.sideEffectCeiling.includes(node.sideEffectCeiling)) {
573
+ issues.push(`节点 ${node.nodeId} 的 sideEffectCeiling="${String(node.sideEffectCeiling)}" 不在受控枚举内`);
574
+ }
575
+ if (node.executor === 'deterministic_script' && node.modelTier !== 'deterministic_no_llm') {
576
+ issues.push(`节点 ${node.nodeId} 为 deterministic_script,modelTier 必须设为 deterministic_no_llm`);
577
+ }
578
+ if (node.executor !== 'deterministic_script' && node.modelTier === 'deterministic_no_llm') {
579
+ issues.push(`节点 ${node.nodeId} 为 ${node.executor},modelTier 不能设为 deterministic_no_llm(仅 deterministic_script 可用)`);
580
+ }
581
+ if (node.sideEffectCeiling === 'read_only' && (node.allowedWriteSet || []).length > 0) {
582
+ issues.push(`节点 ${node.nodeId} 副作用上限为 read_only,但 allowedWriteSet 非空`);
583
+ }
584
+ const nodeRank = SIDE_EFFECT_RANK[node.sideEffectCeiling] ?? -1;
585
+ for (const tid of node.allowedTools || []) {
586
+ const tc = toolMap.get(tid);
587
+ if (!tc) {
588
+ issues.push(`节点 ${node.nodeId} 引用了未声明的工具 ${tid}`);
589
+ } else {
590
+ const toolRank = SIDE_EFFECT_RANK[tc.sideEffectClass] ?? 99;
591
+ if (toolRank > nodeRank) {
592
+ issues.push(
593
+ `节点 ${node.nodeId} (${node.sideEffectCeiling}) 不能挂载更高副作用等级的工具 ${tid} (${tc.sideEffectClass})`,
594
+ );
595
+ }
596
+ }
597
+ }
598
+ if (node.role === 'reviewer') {
599
+ if (node.sideEffectCeiling !== 'read_only') {
600
+ issues.push(`复核节点 ${node.nodeId} 必须保持 read_only 副作用上限`);
601
+ }
602
+ const ind = node.independence;
603
+ const revTargets = Array.isArray(ind?.reviewsNodes) ? ind.reviewsNodes : [];
604
+ if (revTargets.length === 0) {
605
+ issues.push(`复核节点 ${node.nodeId} 必须声明非空 independence.reviewsNodes`);
606
+ }
607
+ for (const targetId of revTargets) {
608
+ const targetNode = nodeMap.get(targetId);
609
+ if (!targetNode) {
610
+ issues.push(`复核节点 ${node.nodeId} 的 reviewsNodes 引用了不存在节点 ${targetId}`);
611
+ } else if (targetId === node.nodeId || targetNode.role === 'reviewer') {
612
+ issues.push(`复核节点 ${node.nodeId} 严禁自审或互审复核节点 (${targetId})`);
613
+ }
614
+ }
615
+ if (
616
+ ind?.requireFreshContext !== true ||
617
+ ind?.requireDistinctModelFamily !== true ||
618
+ ind?.forbidWriteTools !== true
619
+ ) {
620
+ issues.push(
621
+ `复核节点 ${node.nodeId} 必须同时开启 requireFreshContext、requireDistinctModelFamily 与 forbidWriteTools 反自审保护`,
622
+ );
623
+ }
624
+ if (
625
+ node.isolation?.contextMode !== 'fresh' ||
626
+ node.isolation?.workspaceMode !== 'fresh_readonly'
627
+ ) {
628
+ issues.push(
629
+ `复核节点 ${node.nodeId} 的 isolation 必须设为 contextMode="fresh" 且 workspaceMode="fresh_readonly"`,
630
+ );
631
+ }
632
+ }
633
+ if (node.sideEffectCeiling === 'external_side_effect') {
634
+ const gates = (bp.hitlGates || []).filter(
635
+ (g) =>
636
+ g.protocol === 'plan_approve_digest' &&
637
+ Array.isArray(g.coversSideEffects) &&
638
+ g.coversSideEffects.includes('external_side_effect'),
639
+ );
640
+ const beforeNodeCovered = gates.some(
641
+ (g) => g.placement === 'before_node' && g.attachToNodeId === node.nodeId,
642
+ );
643
+ const inEdges = incomingEdgesByNode.get(node.nodeId) || [];
644
+ const allInEdgesCovered =
645
+ node.nodeId !== bp.entryNodeId &&
646
+ inEdges.length > 0 &&
647
+ inEdges.every((e) => gates.some((g) => g.placement === 'on_edge' && g.edgeId === e.edgeId));
648
+ if (!beforeNodeCovered && !allInEdgesCovered) {
649
+ issues.push(
650
+ `外部副作用节点 ${node.nodeId} 缺少前置 before_node 或覆盖全部入边的 plan_approve_digest 人工确认门禁 (BP-HITL-DOMINATOR)`,
651
+ );
652
+ }
653
+ }
654
+ }
655
+
656
+ return { valid: issues.length === 0, issues };
657
+ }
658
+
659
+ export function renderBlueprintCanvasSubView(doc, state, { onStateChange = () => {} } = {}) {
660
+ const mk = (tag, text, cls) => {
661
+ const el = doc.createElement(tag);
662
+ if (text !== undefined && text !== null) el.textContent = String(text);
663
+ if (cls) el.className = cls;
664
+ return el;
665
+ };
666
+ const badge = (text, tone = 'zinc') => mk('span', text, `st-badge st-badge-${tone}`);
667
+
668
+ if (!state.bpCanvasDraft) {
669
+ state.bpCanvasPreset = 'triage-validate-review-hitl';
670
+ state.bpCanvasDraft = CANVAS_STARTER_PRESETS['triage-validate-review-hitl']();
671
+ state.bpSelectedNodeId = state.bpCanvasDraft.nodes[0]?.nodeId || null;
672
+ }
673
+
674
+ const draft = state.bpCanvasDraft;
675
+ const check = validateBlueprintCanvasDraft(draft);
676
+ const digest = computeBlueprintDigestSync(draft);
677
+ const selectedNode =
678
+ draft.nodes.find((n) => n.nodeId === state.bpSelectedNodeId) || draft.nodes[0] || null;
679
+
680
+ const root = mk('div', null, 'st-lc-section-stack');
681
+ root.dataset.role = 'blueprint-canvas-view';
682
+
683
+ // 1. 顶部工具栏:预设模板加载 + 校验状态 + blueprintRef 摘要 + 一键导出 JSON
684
+ const toolbar = mk('div', null, 'st-card st-lc-matrix-toolbar');
685
+ const leftControls = mk('div', null, 'st-graph-controls');
686
+ leftControls.append(mk('strong', '起步蓝图预设:'));
687
+
688
+ const presetSelect = mk('select', null, 'st-input');
689
+ presetSelect.dataset.role = 'bp-preset-select';
690
+ for (const [presetId, presetLabel] of [
691
+ ['triage-validate-review-hitl', '四节点业务闭环(分诊 → 校验 → 异构独立复核 → HITL 落盘)'],
692
+ ['deterministic-audit-gate', '双节点只读合规审计(静态扫描 → 单向专业结论复核)'],
693
+ ]) {
694
+ const opt = mk('option', presetLabel);
695
+ opt.value = presetId;
696
+ opt.selected = state.bpCanvasPreset === presetId;
697
+ presetSelect.append(opt);
698
+ }
699
+ presetSelect.addEventListener('change', () => {
700
+ const nextPreset = presetSelect.value;
701
+ const factory = CANVAS_STARTER_PRESETS[nextPreset];
702
+ if (factory) {
703
+ state.bpCanvasPreset = nextPreset;
704
+ state.bpCanvasDraft = factory();
705
+ state.bpSelectedNodeId = state.bpCanvasDraft.nodes[0]?.nodeId || null;
706
+ onStateChange();
707
+ }
708
+ });
709
+ leftControls.append(presetSelect);
710
+
711
+ leftControls.append(
712
+ badge(
713
+ check.valid ? '✅ 编排拓扑与反自审/HITL 门禁通过' : `🔴 检出 ${check.issues.length} 项拓扑契约违规`,
714
+ check.valid ? 'emerald' : 'rose',
715
+ ),
716
+ badge(`blueprintRef: sha256:${digest.slice(0, 12)}…`, 'indigo'),
717
+ );
718
+
719
+ const rightControls = mk('div', null, 'st-graph-controls');
720
+ const toggleExportBtn = mk(
721
+ 'button',
722
+ state.bpShowExportJson ? '收起导出 JSON' : '📋 预览 / 导出标准蓝图 JSON',
723
+ 'st-btn st-btn-primary',
724
+ );
725
+ toggleExportBtn.type = 'button';
726
+ toggleExportBtn.dataset.action = 'toggle-bp-json';
727
+ toggleExportBtn.addEventListener('click', () => {
728
+ state.bpShowExportJson = !state.bpShowExportJson;
729
+ onStateChange();
730
+ });
731
+ rightControls.append(toggleExportBtn);
732
+ toolbar.append(leftControls, rightControls);
733
+ root.append(toolbar);
734
+
735
+ // 2. 违规告警条(如有)
736
+ if (!check.valid) {
737
+ const alertCard = mk('div', null, 'st-card st-guide-section');
738
+ alertCard.dataset.role = 'bp-validation-issues';
739
+ alertCard.append(mk('strong', '⚠️ 编排拓扑与安全门禁实时拦截项:'));
740
+ const ul = mk('ul', null, 'st-lc-cap-list');
741
+ for (const iss of check.issues) {
742
+ ul.append(mk('li', iss));
743
+ }
744
+ alertCard.append(ul);
745
+ root.append(alertCard);
746
+ }
747
+
748
+ // 3. 可视化有向拓扑流画布(节点卡片 + 交接边 + HITL 门禁徽章)
749
+ const canvasCard = mk('div', null, 'st-card st-guide-section');
750
+ const cHead = mk('div', null, 'st-repo-opt-head');
751
+ cHead.append(
752
+ mk('h3', `编排拓扑画布:${draft.title}`, 'st-lc-sec-title'),
753
+ badge(`${draft.nodes.length} 节点 · ${draft.edges.length} 交接边 · ${draft.hitlGates.length} 人工门禁`, 'purple'),
754
+ );
755
+ canvasCard.append(cHead, mk('p', draft.summary, 'st-muted-xs'));
756
+
757
+ const nodeFlowGrid = mk('div', null, 'st-lc-feedback-grid');
758
+ nodeFlowGrid.dataset.role = 'bp-node-grid';
759
+ for (const node of draft.nodes) {
760
+ const isSel = selectedNode && selectedNode.nodeId === node.nodeId;
761
+ const isEntry = draft.entryNodeId === node.nodeId;
762
+ const isTerm = (draft.terminalNodeIds || []).includes(node.nodeId);
763
+ const attachedGate = (draft.hitlGates || []).find((g) => g.attachToNodeId === node.nodeId);
764
+
765
+ const card = mk('div', null, `st-lc-feedback-card${isSel ? ' is-selected' : ''}`);
766
+ card.dataset.nodeId = node.nodeId;
767
+
768
+ const top = mk('div', null, 'st-lc-pill-row');
769
+ top.append(
770
+ mk('code', node.nodeId, 'st-inline-code'),
771
+ badge(node.role, node.role === 'reviewer' ? 'purple' : 'indigo'),
772
+ badge(node.sideEffectCeiling, node.sideEffectCeiling === 'external_side_effect' ? 'amber' : 'emerald'),
773
+ );
774
+ if (isEntry) top.append(badge('入口', 'indigo'));
775
+ if (isTerm) top.append(badge('终点', 'zinc'));
776
+ if (attachedGate) top.append(badge(`🛡️ HITL: ${attachedGate.gateId}`, 'amber'));
777
+
778
+ const selectBtn = mk('button', isSel ? '✓ 当前编辑中' : '编辑节点契约', 'st-btn st-btn-xs');
779
+ selectBtn.type = 'button';
780
+ selectBtn.dataset.selectNode = node.nodeId;
781
+ selectBtn.addEventListener('click', () => {
782
+ state.bpSelectedNodeId = node.nodeId;
783
+ onStateChange();
784
+ });
785
+
786
+ card.append(
787
+ top,
788
+ mk('strong', node.title),
789
+ mk('div', `执行器:${node.executor} · 模型档位:${node.modelTier}`, 'st-muted-xs'),
790
+ mk('div', node.responsibility, 'st-muted-xs'),
791
+ selectBtn,
792
+ );
793
+ nodeFlowGrid.append(card);
794
+ }
795
+ canvasCard.append(nodeFlowGrid);
796
+
797
+ // 交接边摘要列表
798
+ const edgeStrip = mk('div', null, 'st-lc-planes-section');
799
+ edgeStrip.append(mk('div', '结构化交接边(禁止纯自由文本口头交接)', 'st-lc-subhead'));
800
+ const edgeStack = mk('div', null, 'st-lc-flow-stack');
801
+ for (const edge of draft.edges) {
802
+ const row = mk('div', null, 'st-lc-pill-row');
803
+ row.append(
804
+ badge(edge.fromNodeId, 'indigo'),
805
+ mk('span', ` ──[${edge.edgeKind}]──▶ `, 'st-lc-flow-arrow'),
806
+ badge(edge.toNodeId, 'emerald'),
807
+ mk('code', edge.handoff.contract, 'st-inline-code'),
808
+ );
809
+ if ((edge.handoff.requiredUpstreamEvidence || []).length > 0) {
810
+ row.append(badge(`前置证据: ${edge.handoff.requiredUpstreamEvidence.join(', ')}`, 'amber'));
811
+ }
812
+ edgeStack.append(row);
813
+ }
814
+ edgeStrip.append(edgeStack);
815
+ canvasCard.append(edgeStrip);
816
+ root.append(canvasCard);
817
+
818
+ // 4. 受限枚举检查器(消除手工编写 JSON 枚举拼写错误)
819
+ if (selectedNode) {
820
+ const inspector = mk('div', null, 'st-card st-guide-section');
821
+ inspector.dataset.role = 'bp-node-inspector';
822
+ inspector.append(
823
+ mk('h3', `节点受限契约编辑器:${selectedNode.nodeId}`, 'st-lc-sec-title'),
824
+ mk('p', '所有关键契约字段均由 Contracts 1.23.0 权威枚举受限驱动,修改后实时重算拓扑合法性与 SHA-256 摘要:', 'st-muted-xs'),
825
+ );
826
+
827
+ const formRow = mk('div', null, 'st-lc-cap-filters');
828
+ const makeEnumField = (labelTxt, fieldKey, allowedValues, onUpdate) => {
829
+ const wrap = mk('label', null, 'st-graph-controls');
830
+ wrap.append(mk('span', `${labelTxt}:`, 'st-muted-xs'));
831
+ const sel = mk('select', null, 'st-input');
832
+ sel.dataset.field = fieldKey;
833
+ for (const v of allowedValues) {
834
+ const opt = mk('option', v);
835
+ opt.value = v;
836
+ opt.selected = selectedNode[fieldKey] === v;
837
+ sel.append(opt);
838
+ }
839
+ sel.addEventListener('change', () => {
840
+ onUpdate(sel.value);
841
+ onStateChange();
842
+ });
843
+ wrap.append(sel);
844
+ return wrap;
845
+ };
846
+
847
+ formRow.append(
848
+ makeEnumField('执行器 (executor)', 'executor', BLUEPRINT_ENUMS.executor, (val) => {
849
+ selectedNode.executor = val;
850
+ if (val === 'deterministic_script') {
851
+ selectedNode.modelTier = 'deterministic_no_llm';
852
+ } else if (selectedNode.modelTier === 'deterministic_no_llm') {
853
+ selectedNode.modelTier = 'balanced_coding';
854
+ }
855
+ }),
856
+ makeEnumField('角色 (role)', 'role', BLUEPRINT_ENUMS.role, (val) => {
857
+ selectedNode.role = val;
858
+ }),
859
+ makeEnumField('裁决权 (decisionAuthority)', 'decisionAuthority', BLUEPRINT_ENUMS.decisionAuthority, (val) => {
860
+ selectedNode.decisionAuthority = val;
861
+ }),
862
+ makeEnumField('模型档位 (modelTier)', 'modelTier', BLUEPRINT_ENUMS.modelTier, (val) => {
863
+ selectedNode.modelTier = val;
864
+ if (val === 'deterministic_no_llm') {
865
+ selectedNode.executor = 'deterministic_script';
866
+ } else if (selectedNode.executor === 'deterministic_script') {
867
+ selectedNode.executor = 'llm_session';
868
+ }
869
+ }),
870
+ makeEnumField('副作用上限 (sideEffectCeiling)', 'sideEffectCeiling', BLUEPRINT_ENUMS.sideEffectCeiling, (val) => {
871
+ selectedNode.sideEffectCeiling = val;
872
+ }),
873
+ );
874
+ inspector.append(formRow);
875
+ root.append(inspector);
876
+ }
877
+
878
+ // 5. 标准 OrchestrationBlueprint JSON 预览与复制区
879
+ if (state.bpShowExportJson) {
880
+ const exportCard = mk('div', null, 'st-card st-guide-section');
881
+ exportCard.dataset.role = 'bp-export-panel';
882
+ const expHead = mk('div', null, 'st-repo-opt-head');
883
+ expHead.append(
884
+ mk('strong', '可直接保存至 artifacts/design/<family>-orchestration-blueprint.json 的标准文档'),
885
+ mk('code', `blueprintRef.sha256 = ${digest}`, 'st-inline-code'),
886
+ );
887
+ const pre = mk('pre', `${JSON.stringify(draft, null, 2)}\n`, 'st-code-block');
888
+ pre.dataset.role = 'bp-export-json';
889
+ exportCard.append(expHead, pre);
890
+ root.append(exportCard);
891
+ }
892
+
893
+ return root;
894
+ }