skill-family-studio 0.2.1 → 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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "platformId": "codex",
3
3
  "familyId": "skill-family-studio",
4
- "version": "0.2.1",
4
+ "version": "0.2.2",
5
5
  "logicalMappings": [
6
6
  {
7
7
  "logicalName": "skill-family-studio",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "platformId": "claude",
3
3
  "familyId": "skill-family-studio",
4
- "version": "0.2.1",
4
+ "version": "0.2.2",
5
5
  "logicalMappings": [
6
6
  {
7
7
  "logicalName": "skill-family-studio",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skill-family-studio",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "单端口统一承载 artifact-graph 宽屏制品图谱审阅与 Foundation 运行态监控的本地离线研发控制台。",
5
5
  "author": {
6
6
  "name": "广州市风荷科技有限公司"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skill-family-studio",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "单端口统一承载 artifact-graph 宽屏制品图谱审阅与 Foundation 运行态监控的本地离线研发控制台。",
5
5
  "author": {
6
6
  "name": "广州市风荷科技有限公司"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skill-family-studio",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "单端口统一承载 artifact-graph 宽屏制品图谱审阅与 Foundation 运行态监控的本地离线研发控制台。",
5
5
  "author": {
6
6
  "name": "广州市风荷科技有限公司"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skill-family-studio",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "单端口统一承载 artifact-graph 宽屏制品图谱审阅与 Foundation 运行态监控的本地离线研发控制台。",
5
5
  "author": {
6
6
  "name": "广州市风荷科技有限公司"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skill-family-studio",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "单端口统一承载 artifact-graph 宽屏制品图谱审阅与 Foundation 运行态监控的本地离线研发控制台。",
5
5
  "author": {
6
6
  "name": "广州市风荷科技有限公司"
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.2
4
+
5
+ - 升级对齐 `artifact-graph@1.2.3`(细粒度提示词与 `SKILL.md`/`references/**` 非代码资产 SHA-256 锁)与 `skill-family-execution-driver@0.2.1`(厂商中立受管多宿主 CLI 采集驱动与 `./replay-driver` 导出)。
6
+ - 正式纳入公开包映射并导出 `./blueprint-canvas`(零 `innerHTML` 受限枚举多会话编排蓝图画布、实时反自审与外部副作用 HITL 门禁支配检查及 `blueprintRef` 规范化 SHA-256 摘要生成)。
7
+
3
8
  ## 0.2.1
4
9
 
5
10
  - 单端口统一承载三业务主页签(审阅与对齐、制品图谱、运行监控)与按需「📖 手册」,提供零配置单仓与声明式多仓发现。
package/README.md CHANGED
@@ -28,6 +28,7 @@ npm install -g skill-family-studio
28
28
  2. **全站实体第一身份与统一表头 `ⓘ` 口径**:无论是高阶对齐表、子仓绑定、审阅目录、运行计划还是智能体编队,均将中文标题与正文第一句自然摘要放于首位,编号与文件路径退居辅助位置;高频列表头以单一 `ⓘ` 集中阐释列规则与状态字典,行内仅真正异常与漂移告警保留诊断 `ⓘ`。
29
29
  3. **折叠目录树、现代长文排版与草稿不丢失**:逐篇审阅左侧提供「① 用户故事 → ② 生命周期讲解 → ③ 需求总纲 → ④ 场景剧本 → ⑤ 领域模型与架构设计 → 附:机器数据契约 (.json/.yaml · 自动跳过)」手风琴折叠目录树,支持关键词穿透搜索;正文顶部呈现 Hero 摘要卡、GitHub Callout 与用户故事卡片;Archify 业务逻辑图通过 `&embed=1` 纯净内嵌,未提交批注与备注草稿自动暂存(「📝 草稿」)并支持 5 秒撤销,零侵入保存在 `.skill-family-studio/reviews.json`。
30
30
  4. **双栏主从运行监控(活跃 + 历史计划树 & 多宿主编队)**:「🌳 任务推进树」左侧聚合活跃运行计划与近期进行中/已完成历史计划、右侧展开多级树与进度条;「🛰️ 智能体会话编队」左侧以宿主过滤芯片和摘要卡片直选 Antigravity / Claude / Codex / 沙箱编队,右侧联动渲染网络拓扑、协作泳道与 Markdown 事件简报;「🩺 异常排障」实时汇报运行时排他写锁、事件哈希链与子进程看门狗。
31
+ 5. **全周期协同矩阵与受限枚举编排蓝图画布(`./blueprint-canvas`)**:「🧭 全周期协同」视图基于 `artifact-graph@1.2.3`(支持细粒度提示词与非代码资产锁)与 `skill-family-execution-driver@0.2.1` 实时核验三环泳道与里程碑机器探针,并内置受限枚举多会话编排蓝图编辑器,实时执行图连通性、独立复核防自审与外部副作用人工门禁(HITL)支配检查,一键导出规范化 `blueprintRef` SHA-256 摘要。
31
32
 
32
33
  ## 环境要求
33
34
 
package/VERSION CHANGED
@@ -1 +1 @@
1
- 0.2.1
1
+ 0.2.2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skill-family-studio",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "private": false,
5
5
  "description": "单端口统一承载 artifact-graph 宽屏制品图谱审阅与 Foundation 运行态监控的本地离线研发控制台。",
6
6
  "author": "广州市风荷科技有限公司",
@@ -16,7 +16,8 @@
16
16
  ".": "./src/index.mjs",
17
17
  "./cli": "./bin/skill-family-studio.mjs",
18
18
  "./layout": "./src/graph-layout.mjs",
19
- "./review-state": "./src/review-state.mjs"
19
+ "./review-state": "./src/review-state.mjs",
20
+ "./blueprint-canvas": "./src/ui/blueprint-canvas.mjs"
20
21
  },
21
22
  "files": [
22
23
  "bin",
@@ -39,8 +40,9 @@
39
40
  "NOTICE"
40
41
  ],
41
42
  "dependencies": {
42
- "artifact-graph": "1.2.2",
43
+ "artifact-graph": "1.2.3",
43
44
  "skill-family-contracts": "0.39.2",
45
+ "skill-family-execution-driver": "0.2.1",
44
46
  "skill-family-harness-node": "0.39.2",
45
47
  "skill-family-engineering-kit": "0.39.2",
46
48
  "yaml": "2.9.0"
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "skill-family-studio",
3
3
  "displayName": "Skill Family Studio",
4
- "version": "0.2.1",
4
+ "version": "0.2.2",
5
5
  "description": "单端口统一承载 artifact-graph 宽屏制品图谱审阅与 Foundation 运行态监控的本地离线研发控制台。",
6
6
  "author": "广州市风荷科技有限公司",
7
7
  "repository": "https://github.com/ifoohoo/skill-family-studio"
@@ -1226,7 +1226,41 @@ async function evaluateRoadmapMilestones(rawRoadmap, ctx) {
1226
1226
  'packages/skill-family-test/src/tool-mock-replay.mjs',
1227
1227
  'src/tool-mock-replay.mjs',
1228
1228
  ]) : [];
1229
- if (bpHits.length > 0 && replayHits.length > 0) {
1229
+ let bpSemanticReady = false;
1230
+ if (studioRepo?.live?.realPath && bpHits.length > 0) {
1231
+ const studioPrefix = studioRepo.publicName ? `${studioRepo.publicName}/` : `${studioRepo.name}/`;
1232
+ const bpRel = bpHits[0].startsWith(studioPrefix)
1233
+ ? bpHits[0].slice(studioPrefix.length)
1234
+ : bpHits[0].startsWith(`${studioRepo.name}/`)
1235
+ ? bpHits[0].slice(studioRepo.name.length + 1)
1236
+ : bpHits[0];
1237
+ const bpSrc = await readTextContainedSafe(studioRepo.live.realPath, bpRel);
1238
+ bpSemanticReady = Boolean(
1239
+ bpSrc &&
1240
+ !/\.\s*innerHTML\b/.test(bpSrc) &&
1241
+ bpSrc.includes('BLUEPRINT_ENUMS') &&
1242
+ /export\s+function\s+validateBlueprintCanvasDraft\b/.test(bpSrc) &&
1243
+ /export\s+function\s+computeBlueprintDigestSync\b/.test(bpSrc) &&
1244
+ /export\s+function\s+renderBlueprintCanvasSubView\b/.test(bpSrc),
1245
+ );
1246
+ }
1247
+ let replaySemanticReady = false;
1248
+ if (sftRepo?.live?.realPath && replayHits.length > 0) {
1249
+ const sftPrefix = sftRepo.publicName ? `${sftRepo.publicName}/` : `${sftRepo.name}/`;
1250
+ const replayRel = replayHits[0].startsWith(sftPrefix)
1251
+ ? replayHits[0].slice(sftPrefix.length)
1252
+ : replayHits[0].startsWith(`${sftRepo.name}/`)
1253
+ ? replayHits[0].slice(sftRepo.name.length + 1)
1254
+ : replayHits[0];
1255
+ const replaySrc = await readTextContainedSafe(sftRepo.live.realPath, replayRel);
1256
+ replaySemanticReady = Boolean(
1257
+ replaySrc &&
1258
+ /export\s+function\s+sealToolMockFixture\b/.test(replaySrc) &&
1259
+ /export\s+function\s+verifyToolMockFixtureSeal\b/.test(replaySrc) &&
1260
+ /export\s+function\s+verifyToolReplayRun\b/.test(replaySrc),
1261
+ );
1262
+ }
1263
+ if (bpSemanticReady && replaySemanticReady) {
1230
1264
  status = 'passed';
1231
1265
  badgeLabel = '✅ 已达成';
1232
1266
  badgeTone = 'emerald';
@@ -1235,8 +1269,8 @@ async function evaluateRoadmapMilestones(rawRoadmap, ctx) {
1235
1269
  badgeLabel = '🔵 部分落盘';
1236
1270
  badgeTone = 'indigo';
1237
1271
  }
1238
- liveDetail = `编排蓝图画布:${bpHits[0] || '待 Wave 4D 按实战摩擦建设'} · sft 工具替身回放:${replayHits[0] || '待 Wave 4D 建设'}`;
1239
- probeSource = 'skill-family-studio/blueprint-canvas.mjs + skill-family-test/tool-mock-replay.mjs 探针';
1272
+ liveDetail = `编排蓝图画布:${bpSemanticReady ? bpHits[0] : (bpHits[0] ? `${bpHits[0]} (语义探针未齐)` : '待建设')} · sft 工具替身回放:${replaySemanticReady ? replayHits[0] : (replayHits[0] ? `${replayHits[0]} (导出未齐)` : '待建设')}`;
1273
+ probeSource = 'skill-family-studio/blueprint-canvas.mjs + skill-family-test/tool-mock-replay.mjs 内容语义探针';
1240
1274
  } else if (ms.probeCheck === 'skill_eval_scorecard_engine') {
1241
1275
  const evalRepo = lookupProbedRepo(probedByKey, 'skill-family-eval')
1242
1276
  || lookupProbedRepo(probedByKey, 'skill-eval')
package/src/server.mjs CHANGED
@@ -817,6 +817,7 @@ export async function createStudioServer({
817
817
  '/assets/fleet-ui.mjs': { file: join(UI_DIR, 'fleet-ui.mjs'), type: MIME_TYPES['.mjs'] },
818
818
  '/assets/stb-ui.mjs': { file: join(UI_DIR, 'stb-ui.mjs'), type: MIME_TYPES['.mjs'] },
819
819
  '/assets/lifecycle-ui.mjs': { file: join(UI_DIR, 'lifecycle-ui.mjs'), type: MIME_TYPES['.mjs'] },
820
+ '/assets/blueprint-canvas.mjs': { file: join(UI_DIR, 'blueprint-canvas.mjs'), type: MIME_TYPES['.mjs'] },
820
821
  '/graph-layout.mjs': { file: join(PKG_SRC_DIR, 'graph-layout.mjs'), type: MIME_TYPES['.mjs'] },
821
822
  '/assets/graph-layout.mjs': { file: join(PKG_SRC_DIR, 'graph-layout.mjs'), type: MIME_TYPES['.mjs'] },
822
823
  };
@@ -455,7 +455,7 @@ export function buildSandboxFleetSample(nowIso = new Date().toISOString()) {
455
455
  role: 'coordinator',
456
456
  roleShort: '主控',
457
457
  hueIndex: 0,
458
- model: 'gemini-4-xhigh',
458
+ model: 'flagship-reasoning',
459
459
  status: 'running',
460
460
  startedAt: iso(0),
461
461
  updatedAt: iso(595),
@@ -475,7 +475,7 @@ export function buildSandboxFleetSample(nowIso = new Date().toISOString()) {
475
475
  role: 'subagent',
476
476
  roleShort: '架构',
477
477
  hueIndex: 1,
478
- model: 'gemini-4-high',
478
+ model: 'balanced-coding',
479
479
  status: 'completed',
480
480
  startedAt: iso(25),
481
481
  updatedAt: iso(260),
@@ -495,7 +495,7 @@ export function buildSandboxFleetSample(nowIso = new Date().toISOString()) {
495
495
  role: 'subagent',
496
496
  roleShort: '前端',
497
497
  hueIndex: 2,
498
- model: 'gemini-4-high',
498
+ model: 'balanced-coding',
499
499
  status: 'running',
500
500
  startedAt: iso(35),
501
501
  updatedAt: iso(590),
@@ -515,7 +515,7 @@ export function buildSandboxFleetSample(nowIso = new Date().toISOString()) {
515
515
  role: 'subagent',
516
516
  roleShort: '文档',
517
517
  hueIndex: 3,
518
- model: 'gemini-4-high',
518
+ model: 'balanced-coding',
519
519
  status: 'completed',
520
520
  startedAt: iso(50),
521
521
  updatedAt: iso(310),
@@ -535,7 +535,7 @@ export function buildSandboxFleetSample(nowIso = new Date().toISOString()) {
535
535
  role: 'subagent',
536
536
  roleShort: '核验',
537
537
  hueIndex: 4,
538
- model: 'gemini-4-high',
538
+ model: 'balanced-coding',
539
539
  status: 'completed',
540
540
  startedAt: iso(330),
541
541
  updatedAt: iso(520),
@@ -555,7 +555,7 @@ export function buildSandboxFleetSample(nowIso = new Date().toISOString()) {
555
555
  role: 'reviewer',
556
556
  roleShort: '审阅',
557
557
  hueIndex: 5,
558
- model: 'gemini-4-xhigh',
558
+ model: 'flagship-reasoning',
559
559
  status: 'completed',
560
560
  startedAt: iso(525),
561
561
  updatedAt: iso(585),
@@ -2,9 +2,10 @@
2
2
 
3
3
  import { execFile } from 'node:child_process';
4
4
  import { randomBytes } from 'node:crypto';
5
- import { existsSync } from 'node:fs';
5
+ import { existsSync, lstatSync, readdirSync } from 'node:fs';
6
6
  import { copyFile, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
7
- import { tmpdir } from 'node:os';
7
+ import { createRequire } from 'node:module';
8
+ import { homedir, tmpdir } from 'node:os';
8
9
  import path from 'node:path';
9
10
  import { fileURLToPath, pathToFileURL } from 'node:url';
10
11
  import { promisify } from 'node:util';
@@ -199,26 +200,105 @@ export function summarizeStbEntry(id, sourceLabel, bundle, report, conclusion) {
199
200
  };
200
201
  }
201
202
 
202
- function resolveWorkspaceDriverPaths(root) {
203
- const candidates = [
204
- path.resolve(root),
205
- path.resolve(root, 'skill-family-studio-workspace'),
206
- WORKSPACE_CANDIDATE_ROOT,
203
+ const localRequire = createRequire(import.meta.url);
204
+ const IS_SOURCE_CHECKOUT = path.basename(path.dirname(STUDIO_PKG_ROOT)) === 'packages'
205
+ && !STUDIO_PKG_ROOT.split(path.sep).includes('node_modules');
206
+
207
+ function isRegularNonSymlinkFile(candidatePath) {
208
+ try {
209
+ const st = lstatSync(candidatePath);
210
+ return st.isFile() && !st.isSymbolicLink();
211
+ } catch {
212
+ return false;
213
+ }
214
+ }
215
+
216
+ function isNonSymlinkDir(candidatePath) {
217
+ try {
218
+ const st = lstatSync(candidatePath);
219
+ return st.isDirectory() && !st.isSymbolicLink();
220
+ } catch {
221
+ return false;
222
+ }
223
+ }
224
+
225
+ function discoverSfaEvaluationTool() {
226
+ const envTool = typeof process.env.SFA_EVALUATION_TOOL_PATH === 'string'
227
+ ? process.env.SFA_EVALUATION_TOOL_PATH.trim()
228
+ : '';
229
+ if (envTool) {
230
+ const resolvedEnv = path.resolve(envTool);
231
+ if (isRegularNonSymlinkFile(resolvedEnv)) return resolvedEnv;
232
+ }
233
+
234
+ const relativeProbes = [
235
+ 'scripts/evaluation_tool.py',
236
+ 'platforms/claude-code/skill/scripts/evaluation_tool.py',
237
+ 'platforms/codex/skill/scripts/evaluation_tool.py',
238
+ 'packages/skill-failure-auditor/plugin-src/core/scripts/evaluation_tool.py',
207
239
  ];
208
- for (const base of candidates) {
209
- const driverEntry = path.join(base, 'packages/execution-driver/src/index.mjs');
210
- const fixturesDir = path.join(base, 'packages/execution-driver/fixtures');
211
- if (existsSync(driverEntry)) {
212
- const parentEco = path.resolve(base, '..');
213
- const sfaTool = path.join(
214
- parentEco,
215
- 'skill-failure-auditor-workspace/packages/skill-failure-auditor/plugin-src/core/scripts/evaluation_tool.py',
216
- );
240
+
241
+ const home = homedir();
242
+ for (const installedBase of [
243
+ path.join(home, '.agents/skills/skill-failure-auditor'),
244
+ path.join(home, '.claude/skills/skill-failure-auditor'),
245
+ ]) {
246
+ if (!isNonSymlinkDir(installedBase)) continue;
247
+ for (const rel of relativeProbes) {
248
+ const hit = path.join(installedBase, rel);
249
+ if (isRegularNonSymlinkFile(hit)) return hit;
250
+ }
251
+ }
252
+
253
+ if (IS_SOURCE_CHECKOUT) {
254
+ const checkoutParent = path.resolve(WORKSPACE_CANDIDATE_ROOT, '..');
255
+ if (isNonSymlinkDir(checkoutParent)) {
256
+ try {
257
+ for (const ent of readdirSync(checkoutParent, { withFileTypes: true })) {
258
+ if (!ent.isDirectory() || ent.isSymbolicLink() || ent.name.startsWith('.')) continue;
259
+ if (!ent.name.includes('skill-failure-auditor')) continue;
260
+ const childBase = path.join(checkoutParent, ent.name);
261
+ if (!isNonSymlinkDir(childBase)) continue;
262
+ for (const rel of relativeProbes) {
263
+ const hit = path.join(childBase, rel);
264
+ if (isRegularNonSymlinkFile(hit)) return hit;
265
+ }
266
+ }
267
+ } catch {
268
+ // ignore unreadable parent dir
269
+ }
270
+ }
271
+ }
272
+ return null;
273
+ }
274
+
275
+ export function resolveWorkspaceDriverPaths(_root) {
276
+ const sfaTool = discoverSfaEvaluationTool();
277
+ try {
278
+ const resolvedEntry = localRequire.resolve('skill-family-execution-driver');
279
+ if (resolvedEntry && isRegularNonSymlinkFile(resolvedEntry)) {
280
+ const pkgDir = path.resolve(path.dirname(resolvedEntry), '..');
281
+ const fixturesDir = path.join(pkgDir, 'fixtures');
282
+ return {
283
+ available: true,
284
+ driverEntry: resolvedEntry,
285
+ fixturesDir: isNonSymlinkDir(fixturesDir) ? fixturesDir : null,
286
+ sfaTool,
287
+ };
288
+ }
289
+ } catch {
290
+ // fallback to local source checkout layout when running uninstalled tests
291
+ }
292
+
293
+ if (IS_SOURCE_CHECKOUT) {
294
+ const driverEntry = path.join(WORKSPACE_CANDIDATE_ROOT, 'packages/execution-driver/src/index.mjs');
295
+ const fixturesDir = path.join(WORKSPACE_CANDIDATE_ROOT, 'packages/execution-driver/fixtures');
296
+ if (isRegularNonSymlinkFile(driverEntry)) {
217
297
  return {
218
298
  available: true,
219
299
  driverEntry,
220
- fixturesDir,
221
- sfaTool: existsSync(sfaTool) ? sfaTool : null,
300
+ fixturesDir: isNonSymlinkDir(fixturesDir) ? fixturesDir : null,
301
+ sfaTool,
222
302
  };
223
303
  }
224
304
  }
@@ -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
+ }
@@ -1,5 +1,6 @@
1
1
  // @feature STU004
2
2
  // @feature STU005
3
+ import { renderBlueprintCanvasSubView } from './blueprint-canvas.mjs';
3
4
 
4
5
  const ROLE_LABELS = Object.freeze({
5
6
  lead: { label: '主导', tone: 'indigo' },
@@ -1155,6 +1156,7 @@ export function mountLifecyclePanel(host, {
1155
1156
  ['contracts', '② 契约流与架构体检'],
1156
1157
  ['catalog', '③ 全谱系能力与采用现状'],
1157
1158
  ['roadmap', '④ 迁移路线与架构裁决(现状 → 理想态)'],
1159
+ ['blueprint', '⑤ 编排蓝图画布 (M2-1)'],
1158
1160
  ]) {
1159
1161
  const b = mk('button', svLabel, `st-btn${state.lcSubView === svKey ? ' is-active' : ''}`);
1160
1162
  b.type = 'button';
@@ -1181,6 +1183,8 @@ export function mountLifecyclePanel(host, {
1181
1183
  subMount.append(renderCatalogSubView(doc, data, state, callbacks));
1182
1184
  } else if (state.lcSubView === 'roadmap') {
1183
1185
  subMount.append(renderRoadmapSubView(doc, data, state, callbacks));
1186
+ } else if (state.lcSubView === 'blueprint') {
1187
+ subMount.append(renderBlueprintCanvasSubView(doc, state, callbacks));
1184
1188
  } else {
1185
1189
  subMount.append(renderMatrixSubView(doc, data, state, callbacks));
1186
1190
  }