flow-comet 1.5.0 → 1.6.0

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.
@@ -12,7 +12,8 @@
12
12
  // E. 自定义协议(--protocol/env 加载、自定义节点声明机制与出口、内置特化校验不误触发)
13
13
  // F. 自动初始化(缺失提示/跳过记忆/新鲜静默/生成协作全链路)
14
14
  // G. 分支模式(init 建分支/归档入口分支校验/一致性失配警告)
15
- // H. verify 与归档(验证命令真实执行 + 超时配置/完整归档流程/归档路径声明标记查找)
15
+ // H. verify 与归档(验证命令真实执行 + 超时配置/完整归档流程/归档路径声明标记查找/
16
+ // 受控重入真实命令链路:授权门禁·转移·审计·备份指纹·幂等·轮次上限·手工回滚)
16
17
  // I. 异常路径(损坏状态/缺工件出口/非法参数/状态字段类型非法)
17
18
  // J. 文档一致性(双语健康检查/公开产物零代号检查——调用仓库本地工具)
18
19
  // K. 安装器与平台(版本标识/多平台安装与平台化路径/codex hook JSON 契约/平台选择链/
@@ -35,6 +36,7 @@
35
36
  // 仅 node 内置模块(child_process/fs/os/path);无网络。
36
37
 
37
38
  import { execFileSync, spawnSync } from 'child_process';
39
+ import { createHash } from 'crypto';
38
40
  import fs from 'fs';
39
41
  import os from 'os';
40
42
  import path from 'path';
@@ -160,6 +162,11 @@ function readStateFile(root) {
160
162
  return JSON.parse(fs.readFileSync(path.join(root, '.flow-comet', 'flow-comet-state.json'), 'utf8'));
161
163
  }
162
164
 
165
+ // 读取 state 原始字节(「字节零改写」断言用——不解析,直接逐字节比较)
166
+ function readStateBytes(root) {
167
+ return fs.readFileSync(path.join(root, '.flow-comet', 'flow-comet-state.json'));
168
+ }
169
+
163
170
  // git 工具:临时目录内初始化仓库(含初始 commit——unborn HEAD 下 init 不会建分支)
164
171
  function gitInit(root) {
165
172
  execFileSync('git', ['init', '-q'], { cwd: root, stdio: 'ignore' });
@@ -423,16 +430,21 @@ const DISTRIBUTION_MARKERS = {
423
430
  copy: 'distribution:not-applicable@copy',
424
431
  };
425
432
 
433
+ // K14 安装副本侧「不适用」说明:K14 分支与契约夹具共用同一字面量来源(防两处文案漂移)。
434
+ const K14_COPY_DETAIL = '桥接 loader 版本戳重装断言仅权威源侧可判';
435
+
426
436
  // 运行器侧标记契约校验(分发面项):标记必须显式在场且与结构化环境判据推出的期望值一致。
427
437
  // 缺标记 = 该项走了静默跳过(「未验证 ≠ 通过」,与显式「不适用」是两回事)→ 失败;
428
438
  // 标记与环境不符 = 环境判据写反(副本侧假红 / 权威源侧静默漏检)→ 失败。
429
- function assertDistributionOutcome(itemName, marker) {
439
+ // ctx 是可注入接缝(默认按真实环境判据解析):使两侧错配与非法 marker 的失败路径能由夹具
440
+ // 合成 ctx 真实驱动(否则这些分支没有调用者,判定被改宽也没有断言能拦住)。
441
+ function assertDistributionOutcome(itemName, marker, ctx = resolvePackageContext()) {
430
442
  const legal = Object.values(DISTRIBUTION_MARKERS);
431
443
  if (!legal.includes(marker)) {
432
444
  throw new Error('分发面结果标记缺席或非法(应回传 ' + legal.join(' 或 ') + ',实际 ' + JSON.stringify(marker)
433
445
  + ')——禁止静默跳过');
434
446
  }
435
- const expected = DISTRIBUTION_MARKERS[resolvePackageContext().kind];
447
+ const expected = DISTRIBUTION_MARKERS[ctx.kind];
436
448
  if (marker !== expected) {
437
449
  throw new Error('分发面结果标记与环境判据不符:本环境应 ' + expected + ',实际 ' + marker
438
450
  + '(判定写反会让该侧静默漏检或假红)');
@@ -440,6 +452,57 @@ function assertDistributionOutcome(itemName, marker) {
440
452
  console.log('OUTCOME: ' + itemName + ' → ' + marker);
441
453
  }
442
454
 
455
+ // copy 形态「不适用」回传:文案与机器可读结果标记同源产出(文案是「非静默跳过」的证据)。
456
+ // 返回 { message, marker } 供 early-return 分支直接消费,也使夹具无需捕获 stdout 即可逐字驱动断言。
457
+ // 非 copy ctx 必须 fail-closed——不允许把 source 形态的 marker 与「不适用」文案拼在一起。
458
+ function copyDistributionOutcome(ctx, detail) {
459
+ if (!ctx || ctx.kind !== 'copy' || typeof ctx.reason !== 'string' || ctx.reason.trim() === '') {
460
+ throw new Error('copy 回传契约要求 kind=copy 且含非空 reason,实际 ' + JSON.stringify(ctx));
461
+ }
462
+ return {
463
+ message: ' 不适用(安装副本侧:' + ctx.reason + ')——' + detail + ',本项计通过',
464
+ marker: DISTRIBUTION_MARKERS[ctx.kind],
465
+ };
466
+ }
467
+
468
+ // 分发面回传契约夹具(环境无关;K14 在副本 early-return 之前调用,故两侧都会真跑):
469
+ // ① 三类失败路径负例必须 throw——copy ctx + source marker / source ctx + copy marker /
470
+ // undefined 或非法 marker(缺可注入 ctx 接缝时这些路径没有任何调用者);
471
+ // ② 接缝正例:两侧 marker 与 ctx 匹配时必须通过;
472
+ // ③ copy 形态真实判据 + helper 文案/marker 同源产出。
473
+ function assertDistributionOutcomeContract(scratch) {
474
+ const expectThrow = (fn, label) => {
475
+ let threw = null;
476
+ try { fn(); } catch (e) { threw = e; }
477
+ if (!threw) throw new Error('分发面回传契约失配(' + label + '):失败路径应抛错而未抛错');
478
+ };
479
+ // ① 失败路径负例先驱动:接缝缺失时先在此以「应抛错而未抛错」暴露,不被后续环境相关失败掩盖
480
+ expectThrow(() => assertDistributionOutcome('分发面契约夹具:copy ctx + source marker', DISTRIBUTION_MARKERS.source, { kind: 'copy', reason: '夹具' }), 'copy ctx + source marker');
481
+ expectThrow(() => assertDistributionOutcome('分发面契约夹具:source ctx + copy marker', DISTRIBUTION_MARKERS.copy, { kind: 'source' }), 'source ctx + copy marker');
482
+ expectThrow(() => assertDistributionOutcome('分发面契约夹具:undefined marker', undefined, { kind: 'copy', reason: '夹具' }), 'undefined marker');
483
+ expectThrow(() => assertDistributionOutcome('分发面契约夹具:非法 marker', 'distribution:unknown', { kind: 'copy', reason: '夹具' }), '非法 marker');
484
+ // ② 接缝正例
485
+ assertDistributionOutcome('分发面契约夹具:copy 正例', DISTRIBUTION_MARKERS.copy, { kind: 'copy', reason: '夹具' });
486
+ assertDistributionOutcome('分发面契约夹具:source 正例', DISTRIBUTION_MARKERS.source, { kind: 'source' });
487
+ // ③ copy 形态真实判据 + helper 文案/marker 同源
488
+ const copyCtx = resolvePackageContext(path.join(scratch, 'k14-copy-probe'));
489
+ if (copyCtx.kind !== 'copy' || typeof copyCtx.reason !== 'string' || copyCtx.reason.trim() === '') {
490
+ throw new Error('分发面回传契约夹具 copy 判据失配: ' + JSON.stringify(copyCtx));
491
+ }
492
+ const copyOutcome = copyDistributionOutcome(copyCtx, K14_COPY_DETAIL);
493
+ if (copyOutcome.marker !== DISTRIBUTION_MARKERS.copy) {
494
+ throw new Error('分发面回传契约 copy marker 失配: ' + JSON.stringify(copyOutcome.marker));
495
+ }
496
+ if (!copyOutcome.message.includes('不适用(安装副本侧:' + copyCtx.reason + ')')
497
+ || !copyOutcome.message.includes(K14_COPY_DETAIL)
498
+ || !copyOutcome.message.includes('本项计通过')) {
499
+ throw new Error('分发面回传契约 copy 文案失配: ' + JSON.stringify(copyOutcome.message));
500
+ }
501
+ // ④ helper 非 copy ctx 必须 fail-closed(不得把 source marker 伪装成「不适用」)
502
+ expectThrow(() => copyDistributionOutcome({ kind: 'source' }, 'x'), 'copy helper 非 copy ctx');
503
+ console.log(' 分发面回传契约: copy 文案/marker + 两侧正例 + 三类失败路径负例 ✓');
504
+ }
505
+
443
506
  // 跑 `npm pack --dry-run --json`(只读,不产出 tarball)并解析出产物相对路径清单。
444
507
  // 命令以字符串形态经 shell 执行(与 workflow-guard verify 命令执行同形态):Windows 上 npm 是
445
508
  // npm.cmd(CreateProcess 不解析 .cmd 后缀,且 Node 对 .cmd/.bat 直接 spawn 属 EINVAL)——
@@ -569,6 +632,68 @@ function assertInitTokenContract(installer, cwd) {
569
632
  throw new Error('变形/重复词元 `' + bad + '` 的 stderr 应含「未知参数」,实际:\n' + res.stderr);
570
633
  }
571
634
  }
635
+ // ⑤ 版本查询:`--version` / `-v` 退 0 且输出本工具的版本标识(同一个解析来源,不另设常量)。
636
+ // 断言做成**状态无关**,因为「版本面已 bump、tag 尚未打」是发布准备的常态:此时随包标记
637
+ // 领先于 git describe(标记 = 待发版本,describe = 旧 tag + 提交数)。两条合法来源:
638
+ // ① 随包分发的权威源标记(包形态 / 发布后命中);② 当前 tag 的开发态后缀 `<tag>-N-g<hash>`。
639
+ // 等值断言会在发布准备期误红——那不是缺陷,是顺序(先改版本面、后打 tag)。
640
+ const versionShape = /^\d+\.\d+\.\d+(-[0-9A-Za-z][0-9A-Za-z.-]*)?$/;
641
+ const installedVersion = fs.readFileSync(path.join(__dirname, '..', 'INSTALLED_VERSION'), 'utf8').trim();
642
+ let headTag = '';
643
+ try {
644
+ const repoRoot = path.resolve(__dirname, '..', '..', '..', '..');
645
+ headTag = execFileSync('git', ['describe', '--tags', '--abbrev=0'], { cwd: repoRoot, encoding: 'utf8', timeout: 30000 }).trim().replace(/^v/, '');
646
+ } catch { /* 无 git 或无 tag:只按随包标记比对 */ }
647
+ for (const flag of ['--version', '-v']) {
648
+ const res = runInstaller([flag]);
649
+ if (res.status !== 0) {
650
+ throw new Error('`' + flag + '` 应退 0(版本查询不是错误),实际 ' + res.status + '\n' + res.stderr);
651
+ }
652
+ const printed = res.stdout.trim();
653
+ if (!versionShape.test(printed)) {
654
+ throw new Error('`' + flag + '` 的输出不是版本标识形态: ' + JSON.stringify(printed));
655
+ }
656
+ // 等值、或**以「版本 + `-`」为界**的开发态后缀——不能裸用前缀匹配:`1.5.10` 会被
657
+ // `startsWith('1.5.1')` 收下,把「族外的更长版本号」误判为一致(实测:注入 1.5.10 时
658
+ // 裸前缀谓词全绿通过)。边界字符取 `-`,正合 git describe 的后缀形态 `<tag>-N-g<hash>`。
659
+ const matchesMarker = printed === installedVersion || printed.startsWith(installedVersion + '-');
660
+ const matchesHeadTag = headTag !== '' && (printed === headTag || printed.startsWith(headTag + '-'));
661
+ if (!matchesMarker && !matchesHeadTag) {
662
+ throw new Error('`' + flag + '` 的输出与「随包标记 / 当前 tag」都不一致(标记=' + installedVersion + ' tag=' + headTag + '): ' + JSON.stringify(printed));
663
+ }
664
+ }
665
+ console.log(' 版本查询: `--version` / `-v` 退 0 且输出为版本标识形态(标记=' + installedVersion + ' / 当前 tag=' + headTag + ')✓');
666
+ // ⑥ 零参数裸调用不得安装到当前目录(本轮修正):无参数 = 没说要做什么,
667
+ // 应当在当前目录留下零产物并给出用法与非零退出码。修复前它会做一次完整安装
668
+ // (.claude/ + flow-kit/ + 改写 .gitignore)→ 误敲即在当前目录铺开一套环境。
669
+ const emptyDir = fs.mkdtempSync(path.join(os.tmpdir(), 'no-action-'));
670
+ try {
671
+ seedForeignFlowKit(emptyDir); // 预置同名非上游目录:走「已跳过」路径,零网络接触
672
+ const bareRun = spawnSync(process.execPath, [installer], { cwd: emptyDir, encoding: 'utf8', timeout: 60000 });
673
+ const status = bareRun.status ?? 1;
674
+ const stderr = String(bareRun.stderr || '');
675
+ if (status === 0) {
676
+ throw new Error('零参数裸调用不得退 0(它做了/声称做了一次安装);实际退 0\n' + String(bareRun.stdout || '').slice(-300));
677
+ }
678
+ if (!stderr.includes('用法')) {
679
+ throw new Error('零参数裸调用的 stderr 应给出用法,实际:\n' + stderr);
680
+ }
681
+ // 用法必须**整段**在 stderr:只断言「stderr 含用法」会漏掉「部分行仍写 stdout」的实现
682
+ // (首行在 stderr 即满足该断言,其余行可能被劈到 stdout——实测出现过)。故此处两侧同判:
683
+ // stderr 末尾行在场,且 stdout 为空。
684
+ if (!/--version 打印版本标识/.test(stderr)) {
685
+ throw new Error('用法末行不在 stderr(用法输出被劈到 stdout):stderr 实际:\n' + stderr);
686
+ }
687
+ if (String(bareRun.stdout || '').trim() !== '') {
688
+ throw new Error('零参数裸调用的 stdout 应为空(用法整段走 stderr),实际:\n' + String(bareRun.stdout));
689
+ }
690
+ if (fs.existsSync(path.join(emptyDir, '.claude'))) {
691
+ throw new Error('零参数裸调用不得在当前目录留下安装产物(.claude/ 被创建)');
692
+ }
693
+ console.log(' 零参数裸调用: 非零退出 + 用法整段在 stderr + stdout 空 + 当前目录零产物 ✓');
694
+ } finally {
695
+ fs.rmSync(emptyDir, { recursive: true, force: true });
696
+ }
572
697
  console.log(' init 词元: `init --help` 退 0 且含 fcomet init / 裸形态行为不变 / 变形·重复词元 4 例退 1 且报未知参数 ✓');
573
698
  }
574
699
 
@@ -592,6 +717,35 @@ function stampBridgeLoader(sourceLoader, version) {
592
717
  return replaced;
593
718
  }
594
719
 
720
+ // 安装副本载体的 bridge-check 版本比较断言:dev 态载体(INSTALLED_VERSION = <发布>-<N>-g<hash>)
721
+ // 与同基础版本 loader 判健康,基础版本失配仍 FAIL。以副本自身脚本运行——bridge-check 读取脚本
722
+ // 同包 INSTALLED_VERSION,与真实安装载体同构(权威源检出路径固定为发布标记,无法构造 dev 态)。
723
+ function assertInstalledCopyBridgeVersionSemantics(target, dshHome, srcVersion) {
724
+ const installedSkillRoot = path.join(target, '.dsh', 'skills', 'flow-comet');
725
+ const installedVersionPath = path.join(installedSkillRoot, 'INSTALLED_VERSION');
726
+ const runBridgeCheck = () => {
727
+ const res = spawnSync(process.execPath, [path.join(installedSkillRoot, 'scripts', 'workflow-state.mjs'), 'bridge-check'], {
728
+ cwd: target, encoding: 'utf8', timeout: 60000, env: { ...process.env, DSH_HOME: dshHome },
729
+ });
730
+ return { status: res.status ?? 1, output: String(res.stdout || '') + String(res.stderr || '') };
731
+ };
732
+ const devVersion = srcVersion + '-11-g93d96c0';
733
+ fs.writeFileSync(installedVersionPath, devVersion + '\n', 'utf8');
734
+ const devHealthy = runBridgeCheck();
735
+ assertExit(devHealthy, 0);
736
+ assertOut(devHealthy, '[OK] 版本一致性: loader BRIDGE_VERSION=' + srcVersion + ' ~= 项目 INSTALLED_VERSION=' + devVersion);
737
+ assertOut(devHealthy, '(dev 态后缀归一后基础版本 ' + srcVersion + ' 一致)');
738
+ assertOut(devHealthy, 'bridge-check: 健康(全部检查通过)——exit 0');
739
+ const [major] = srcVersion.split('.').map((p) => parseInt(p, 10));
740
+ const otherBase = (major + 9) + '.0.0';
741
+ const otherVersion = otherBase + '-3-gabcdef0';
742
+ fs.writeFileSync(installedVersionPath, otherVersion + '\n', 'utf8');
743
+ const baseMismatch = runBridgeCheck();
744
+ assertExit(baseMismatch, 1);
745
+ assertOut(baseMismatch, '[FAIL] 版本偏斜: loader BRIDGE_VERSION=' + srcVersion + ' != 项目 INSTALLED_VERSION=' + otherVersion + '(归一基础版本: loader=' + srcVersion + ' / installed=' + otherBase + ')——两值如上');
746
+ assertOut(baseMismatch, 'bridge-check: 失配 1 项——exit 1');
747
+ }
748
+
595
749
  // 预置目标项目 flow-kit/ 为同名非上游目录(安装器走「非上游克隆,已跳过」路径——
596
750
  // 网络零接触;与安装器冒烟同手法)
597
751
  function seedForeignFlowKit(root) {
@@ -687,6 +841,123 @@ function execSummaryFixture(taskId) {
687
841
  ].join('\n');
688
842
  }
689
843
 
844
+ // ---------- Fix 批次真实命令链路夹具(A21~A23 共用) ----------
845
+
846
+ // 串行任务块(字段齐备:可过 task-parsing 解析与 guard 结构校验)
847
+ function serialTaskBlock(id, status) {
848
+ return '<task id="' + id + '" parallel="false" status="' + status + '">' +
849
+ '<action>实现 ' + id + '</action><write_files>src/' + id.toLowerCase() + '.mjs</write_files>' +
850
+ '<verify>node --check src/' + id.toLowerCase() + '.mjs</verify></task>';
851
+ }
852
+
853
+ // Fix 批次任务集:既有任务 T01 done +「Fix 任务」段追加修复任务(追加纪律与节点技能一致)
854
+ function fixBatchTaskText(fixStatus) {
855
+ return '# TASK\n\n## 任务清单\n\n' + serialTaskBlock('T01', 'done') +
856
+ '\n\n## Fix 任务(来自 REVIEW / INTEGRATION)\n\n' + serialTaskBlock('T-FIX-01', fixStatus) + '\n';
857
+ }
858
+
859
+ // 并行 Fix 任务集(无依赖 → 可委托):既有任务 T01 done + parallel 修复任务(状态由参数指定)。
860
+ function fixBatchParallelTaskText(fixStatus) {
861
+ return '# TASK\n\n## 任务清单\n\n' + serialTaskBlock('T01', 'done') +
862
+ '\n\n## Fix 任务(来自 REVIEW / INTEGRATION)\n\n'
863
+ + '<task id="P-FIX-01" parallel="true" status="' + fixStatus + '">'
864
+ + '<action>实现 P-FIX-01</action><write_files>src/p-fix-01.mjs</write_files>'
865
+ + '<verify>node --check src/p-fix-01.mjs</verify></task>\n';
866
+ }
867
+
868
+ // 两波修复任务集(多波次真实 Fix 链路夹具):既有任务 T01 done + Fix 段内两个修复任务,
869
+ // 两个修复任务的状态由入参分别指定——第一波收口后追加第二波,任务集签名随之发散。
870
+ function fixBatchTwoFixTaskText(fixStatus1, fixStatus2) {
871
+ return '# TASK\n\n## 任务清单\n\n' + serialTaskBlock('T01', 'done') +
872
+ '\n\n## Fix 任务(来自 REVIEW / INTEGRATION)\n\n' +
873
+ serialTaskBlock('T-FIX-01', fixStatus1) + '\n' + serialTaskBlock('T-FIX-02', fixStatus2) + '\n';
874
+ }
875
+
876
+ // 审查文档:disposed=false 时发现条目缺处置标记(钉住 review 出口的真实校验与恢复)
877
+ function fixBatchReviewDoc(disposed) {
878
+ const finding = disposed
879
+ ? '- **状态机路径未闭环** —— 已追加修复任务并回修。[已修]'
880
+ : '- **状态机路径未闭环** —— 已追加修复任务,处置标记待补。';
881
+ return '# REVIEW\n\n## 发现\n\n### Critical\n\n- 无\n\n### Major\n\n' + finding +
882
+ '\n\n### Minor\n\n- 无\n\n## 结论\n\nFix 批次在 execute 生命周期内完成后回源节点重新跑出口。\n';
883
+ }
884
+
885
+ // done-but-unclosed 回放夹具(L-070 事故形态):history 最新 exit-applied execute 记录的任务集
886
+ // 签名仍是追加修复任务之前的占位值(与当前「既有任务 + 追加修复任务」任务集签名必然不等)——
887
+ // 机器信号 =「修复任务已 done,但本批 execute 出口从未重新通过」。判据只比较是否相等,占位常量
888
+ // 与哈希实现解耦;旧 state 无该字段 → 渐进放行。
889
+ const STALE_TASK_SET_SIGNATURE = '0'.repeat(64);
890
+ function fixBatchHistoryWithStaleExecuteExit() {
891
+ return [{ event: 'exit-applied', node: 'execute', at: '2026-09-20T00:00:00.000Z', taskSetSignature: STALE_TASK_SET_SIGNATURE }];
892
+ }
893
+
894
+ // Fix 批次夹具写入:state + TASK + 既有任务 SUMMARY + REVIEW.md(verify 源另备 TEST/UAT)。
895
+ // kind='review'(审查驻留,execute 已首次完成)/ 'verify'(验证驻留,review 已完成);
896
+ // newChange=false 时 state 不带新 change 标记(旧 change 渐进形态)。
897
+ function writeFixBatchFixture(dir, { kind, fixStatus, newChange = true, parallelFix = false }) {
898
+ const completed = kind === 'verify'
899
+ ? ['open', 'design', 'plan', 'execute', 'subagent-execute', 'review']
900
+ : ['open', 'design', 'plan', 'execute', 'subagent-execute'];
901
+ const state = {
902
+ activeChange: CHANGE_ID,
903
+ currentNode: kind,
904
+ completedNodes: completed,
905
+ enteredNodes: [...completed, kind],
906
+ evidence: {
907
+ execute: { summary: 'first pass executed' },
908
+ review: kind === 'review' ? { summary: 'review in progress' } : { summary: 'review complete' },
909
+ },
910
+ verifyFailures: 0,
911
+ executionMode: 'subagent',
912
+ directOverride: false,
913
+ };
914
+ if (kind === 'verify') state.evidence.verify = { summary: 'verify in progress' };
915
+ if (newChange) state.newChange = true;
916
+ writeState(dir, state);
917
+ // 前置节点产物齐备(open/design/plan)——共享路由在任务特判前先过前置产物门控
918
+ writeIntakeArtifacts(dir);
919
+ writeFile(dir, '.specs/' + CHANGE_ID + '/DESIGN.md',
920
+ '# DESIGN\n\n- **Change ID**: ' + CHANGE_ID + '\n\n## 0. 技术栈选定\n\nNode.js(ESM)\n\n## 决策清单\n\n- [ ] 循环路由\n');
921
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md',
922
+ parallelFix ? fixBatchParallelTaskText(fixStatus) : fixBatchTaskText(fixStatus));
923
+ writeFile(dir, '.specs/' + CHANGE_ID + '/T01-SUMMARY.md', execSummaryFixture('T01'));
924
+ writeFile(dir, '.specs/' + CHANGE_ID + '/REVIEW.md', fixBatchReviewDoc(true));
925
+ if (kind === 'verify') {
926
+ // 真实验证命令:落盘副作用文件——出口是否执行验证命令以文件系统事实判定(不只看退出码)
927
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TEST.md',
928
+ '# TEST\n\n## 验证命令\n\n```\nnode -e "require(\'fs\').writeFileSync(\'verify-gate-ran.txt\', \'GATE-RAN\')"\n```\n');
929
+ writeFile(dir, '.specs/' + CHANGE_ID + '/UAT.md', '# UAT\n\n## 验收\n\n- 通过\n');
930
+ }
931
+ }
932
+
933
+ // 完成修复任务的后半段:标记 done + 逐任务 SUMMARY + 重载 execute 声明 + record execute。
934
+ // record 的新 change 前置门要求本节点加载声明;takeover 豁免回传显式落库,供出口校验读取。
935
+ function completeFixTaskAndRecord(dir, env) {
936
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', fixBatchTaskText('done'));
937
+ writeFile(dir, '.specs/' + CHANGE_ID + '/T-FIX-01-SUMMARY.md', execSummaryFixture('T-FIX-01'));
938
+ assertExit(runState(['skill-load', 'execute', 'flow-comet-execute', '--prompt', 'flow-kit/prompts/4-dev.md'], dir, env), 0);
939
+ const rec = runState(['record', 'execute', '{"summary":"fix batch executed","parallelTakeoverApproved":true}'], dir, env);
940
+ assertExit(rec, 0);
941
+ assertOut(rec, 'EVIDENCE: execute');
942
+ const st = readStateFile(dir);
943
+ if (st.evidence?.execute?.summary !== 'fix batch executed') {
944
+ throw new Error('record execute 未刷新证据: ' + JSON.stringify(st.evidence?.execute));
945
+ }
946
+ }
947
+
948
+ // 节点行断言(行锚定):防「关键词作为子串出现在其它行」的弱断言
949
+ function assertNodeLine(res, nodeId) {
950
+ if (!new RegExp('^NODE: ' + nodeId + '$', 'm').test(res.output)) {
951
+ throw new Error('输出缺少行 NODE: ' + nodeId + '(exit ' + res.status + ')\n实际输出:\n' + res.output);
952
+ }
953
+ }
954
+
955
+ function assertNotNodeLine(res, nodeId) {
956
+ if (new RegExp('^NODE: ' + nodeId + '$', 'm').test(res.output)) {
957
+ throw new Error('输出不应包含行 NODE: ' + nodeId + '(exit ' + res.status + ')\n实际输出:\n' + res.output);
958
+ }
959
+ }
960
+
690
961
  // 混排多波 TASK:双并行开路 → 串行衔接(依赖双并行)→ 收尾并行(依赖串行衔接)。
691
962
  // 各任务 status 由入参映射(任务 id → 'pending'|'done')控制;status 变更不影响任务集签名
692
963
  // (签名仅保留 id/parallel 与块内容,剥离 status 类属性)。串行衔接置于两并行波之间——
@@ -723,6 +994,56 @@ function driveThroughDesign(dir) {
723
994
  assertExit(runGuard(['exit', 'design', '--apply'], dir), 0);
724
995
  }
725
996
 
997
+ // ---------- 受控重入真实命令链路夹具(H5~H8 共用) ----------
998
+
999
+ // archive 已 entry 形态的完成集(built-in 协议:open → verify 全部完成;archive 已进入未出口)
1000
+ const ARCHIVE_ENTRY_COMPLETED_NODES = ['open', 'design', 'plan', 'execute', 'subagent-execute', 'review', 'verify'];
1001
+ // 前驱交集结果:目标 verify 的前驱 = 上述完成集去掉 verify 自身(按协议顺序)
1002
+ const REENTRY_VERIFY_PREDECESSORS = ['open', 'design', 'plan', 'execute', 'subagent-execute', 'review'];
1003
+
1004
+ // 重入前夹具:临时 runRoot 内 init → archive 已 entry 形态(前序节点全部完成、activeChange 在场、
1005
+ // status=running、.specs/<id>/ 未移动、TASK.md 在场)。协议由 runState/runGuard 显式注入
1006
+ // FLOW_COMET_PROTOCOL(L-079:门禁不得静默跳过)。
1007
+ function seedArchiveEntryState(root, changeId = CHANGE_ID) {
1008
+ assertExit(runState(['init', changeId, '--init-skip'], root), 0);
1009
+ assertExit(runState(['skill-load', 'archive', 'flow-comet-integration', '--prompt', 'flow-kit/prompts/7-integration.md'], root), 0);
1010
+ writeFile(root, '.specs/' + changeId + '/TASK.md',
1011
+ '# TASK\n\n<task id="T01" parallel="false" status="done"><action>初版实现</action>' +
1012
+ '<write_files>src/t01.mjs</write_files><verify>node --check src/t01.mjs</verify><done>落地</done></task>\n');
1013
+ const st = readStateFile(root);
1014
+ st.currentNode = 'archive';
1015
+ st.completedNodes = ARCHIVE_ENTRY_COMPLETED_NODES.slice();
1016
+ st.status = 'running';
1017
+ st.enteredNodes = ARCHIVE_ENTRY_COMPLETED_NODES.concat('archive');
1018
+ writeState(root, st);
1019
+ assertExit(runState(['record', 'archive', '{"summary":"archived"}'], root), 0);
1020
+ assertExit(runGuard(['entry', 'archive'], root), 0);
1021
+ }
1022
+
1023
+ // 备份目录/文件读取(.specs/<id>/.reentry-backups/)
1024
+ function reentryBackupDir(root, changeId = CHANGE_ID) {
1025
+ return path.join(root, '.specs', changeId, '.reentry-backups');
1026
+ }
1027
+
1028
+ function reentryBackupFiles(root, changeId = CHANGE_ID) {
1029
+ return fs.existsSync(reentryBackupDir(root, changeId)) ? fs.readdirSync(reentryBackupDir(root, changeId)) : [];
1030
+ }
1031
+
1032
+ // reentry-applied 事件过滤(state.history 追加记录)
1033
+ function reentryEventsOf(state) {
1034
+ return (state.history || []).filter((e) => e && e.event === 'reentry-applied');
1035
+ }
1036
+
1037
+ // 事件 backup 字段 → 实际文件路径(相对 runRoot 的路径或仅文件名两种写法都接受)
1038
+ function resolveReentryBackupPath(root, changeId, event) {
1039
+ if (!event || typeof event.backup !== 'string' || event.backup.trim() === '') return null;
1040
+ const raw = event.backup;
1041
+ const candidates = path.isAbsolute(raw)
1042
+ ? [raw]
1043
+ : [path.resolve(root, raw), path.join(reentryBackupDir(root, changeId), path.basename(raw))];
1044
+ return candidates.find((p) => fs.existsSync(p)) || null;
1045
+ }
1046
+
726
1047
  // ---------- 系统测试项(A~L 十二类) ----------
727
1048
 
728
1049
  const TEST_ITEMS = [
@@ -1066,12 +1387,14 @@ const TEST_ITEMS = [
1066
1387
  };
1067
1388
  const markDone = (statusMap) => writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', multiWaveTaskContent(statusMap));
1068
1389
  // 单趟驱动:record → entry → exit --apply,断言 NODE 行路由到期望节点(可观测性不变式)
1390
+ let lastPassResult = null;
1069
1391
  const drivePass = (node, expectNext, label) => {
1070
1392
  assertExit(runState(['record', node, '{"summary":"' + label + '"}'], dir), 0);
1071
1393
  assertExit(runGuard(['entry', node], dir), 0);
1072
1394
  const res = runGuard(['exit', node, '--apply'], dir);
1073
1395
  assertExit(res, 0);
1074
1396
  assertOut(res, 'ALL CHECKS PASSED');
1397
+ lastPassResult = res;
1075
1398
  const m = res.output.match(/^NODE: ([a-z-]+)\s*$/m);
1076
1399
  if (!m) throw new Error('exit ' + node + '(' + label + ')输出缺 NODE 行:\n' + res.output);
1077
1400
  if (m[1] !== expectNext) {
@@ -1085,6 +1408,39 @@ const TEST_ITEMS = [
1085
1408
  completeTasks(['P01', 'P02']);
1086
1409
  drivePass('subagent-execute', 'execute', 'parallel-wave-1');
1087
1410
 
1411
+ // 归属门禁事故回放(真实命令链路):波 1 收口后工作归属在 execute(尚有串行衔接待办),
1412
+ // 此刻对未消化的并行 pending 任务发起委托 → 新 change BLOCK(state 字节零改写、不落请求)。
1413
+ // P03 依赖未满足:恢复指引以 workflow-state next 实际输出为准(next 按串行消化输出
1414
+ // execute),不得固定指向 entry subagent-execute;随后原链路照跑(串行衔接完成后并行收尾正常委托)。
1415
+ const ownershipEnv = { FLOW_COMET_PROTOCOL: path.join(dir, 'reference', 'workflow-protocol.json') };
1416
+ const ownershipStatePath = path.join(dir, '.flow-comet', 'flow-comet-state.json');
1417
+ const ownershipBytesBefore = fs.readFileSync(ownershipStatePath, 'utf8');
1418
+ const wrongNodeRequest = runHandoff(['request', 'P03', 'P03 委托', '--write-files', 'src/p03.mjs'], dir, ownershipEnv);
1419
+ assertExit(wrongNodeRequest, 1);
1420
+ assertOut(wrongNodeRequest, 'BLOCKED');
1421
+ assertOut(wrongNodeRequest, '当前不可委托');
1422
+ assertOut(wrongNodeRequest, '依赖未满足');
1423
+ assertOut(wrongNodeRequest, '未完成: S01');
1424
+ assertOut(wrongNodeRequest, '原始 currentNode=execute');
1425
+ assertOut(wrongNodeRequest, 'workflow-state next');
1426
+ assertOut(wrongNodeRequest, '若输出 execute 表示依赖未满足');
1427
+ assertOut(wrongNodeRequest, '待任务变为可委托');
1428
+ // 反锚:不得固定指引 next 不会输出的节点(按该指引进入会被 currentNode 门禁拦成死路)
1429
+ assertNotOut(wrongNodeRequest, 'entry subagent-execute');
1430
+ assertNotOut(wrongNodeRequest, 'HANDOFF REQUEST');
1431
+ if (fs.readFileSync(ownershipStatePath, 'utf8') !== ownershipBytesBefore) {
1432
+ throw new Error('归属门禁 BLOCK 不得改写 state 字节(含 handoffRequests)');
1433
+ }
1434
+ const ownershipState = readStateFile(dir);
1435
+ if (ownershipState.evidence?.['subagent-execute']?.handoffRequests?.P03) {
1436
+ throw new Error('归属门禁 BLOCK 不得落 handoffRequests: '
1437
+ + JSON.stringify(ownershipState.evidence?.['subagent-execute']?.handoffRequests));
1438
+ }
1439
+ // 指引与 next 实际输出一致:依赖未满足 → next 输出 execute(串行消化),无 entry 死路
1440
+ const routeAfterBlock = runState(['next'], dir, ownershipEnv);
1441
+ assertExit(routeAfterBlock, 0);
1442
+ assertNodeLine(routeAfterBlock, 'execute');
1443
+
1088
1444
  // 趟 2 · execute:先消化本趟全部串行 pending(串行衔接,标 done 并委托留证)——
1089
1445
  // 确认无串行残留后才 exit → 收尾并行依赖满足 → 再次进入委托节点
1090
1446
  // (旧引擎单趟限制下此处不再路由回——本断言即多趟语义回归锚)
@@ -1095,13 +1451,31 @@ const TEST_ITEMS = [
1095
1451
  // 趟 3 · subagent-execute:收尾并行委托完成 → 全部 done → 出口照常门控进 review(循环终止语义不变)
1096
1452
  markDone({ P01: 'done', P02: 'done', S01: 'done', P03: 'done' });
1097
1453
  completeTasks(['P03']);
1454
+ // 收口前基线(只读):出口 NODE 与完成节点集合之外零改写,收尾前后仅审计行文本变化
1455
+ const pass3Before = readStateFile(dir);
1098
1456
  drivePass('subagent-execute', 'review', 'parallel-wave-2');
1457
+ const pass3 = lastPassResult;
1458
+ // 正常多趟收尾:无 Fix 结构标记且历史签名全等 → 中性 RETURN,不得出现 FIX-BATCH 锚
1459
+ assertOut(pass3, 'RETURN: 回源节点 review(subagent-execute 出口已完成;正常多趟收尾,非 Fix 回修)');
1460
+ assertNotOut(pass3, 'FIX-BATCH');
1461
+ assertNodeLine(pass3, 'review');
1462
+ const pass3After = readStateFile(dir);
1463
+ if (JSON.stringify(pass3After.completedNodes) !== JSON.stringify(pass3Before.completedNodes)) {
1464
+ throw new Error('正常多趟收尾不得改写完成节点集合(审计行分类零副作用): 收口前 '
1465
+ + JSON.stringify(pass3Before.completedNodes) + ' 收口后 ' + JSON.stringify(pass3After.completedNodes));
1466
+ }
1467
+ if (pass3After.currentNode !== 'review' || pass3After.completedNodes.includes('review')) {
1468
+ throw new Error('正常多趟收尾应停在未完成的 review: ' + JSON.stringify(pass3After));
1469
+ }
1470
+ const pass3PostNext = runState(['next'], dir);
1471
+ assertExit(pass3PostNext, 0);
1472
+ assertNodeLine(pass3PostNext, 'review');
1099
1473
 
1100
1474
  const st = readStateFile(dir);
1101
1475
  if (st.currentNode !== 'review') {
1102
1476
  throw new Error('全部任务 done 后应停在 review 门控前: ' + JSON.stringify(st.currentNode));
1103
1477
  }
1104
- console.log(' 多趟路由:subagent-execute→execute→subagent-execute→review 三趟两交替 ✓');
1478
+ console.log(' 多趟路由:subagent-execute→execute→subagent-execute→review 三趟两交替 + 归属门禁 BLOCK 后原链路续跑 ✓');
1105
1479
  },
1106
1480
  },
1107
1481
 
@@ -1561,6 +1935,634 @@ const TEST_ITEMS = [
1561
1935
  },
1562
1936
  },
1563
1937
 
1938
+ {
1939
+ // review 源 Fix 闭环(真实命令链路):execute 已首次完成、review 驻留 +「Fix 任务」段追加
1940
+ // pending 修复任务 → 直接 exit review --apply 被拦(旧绕过路径会静默跳过 execute 生命周期);
1941
+ // next 受控归位 execute 并写盘 → 完成修复任务后 record/exit execute --apply 回源 review →
1942
+ // review 出口门禁真实执行(发现条目缺处置标记仍 BLOCKED,补齐后通过)并推进 verify。
1943
+ // 修复前 next 停在 review(无 NODE: execute / 无归位审计行)→ 本项应失败(RED 锚)。
1944
+ name: 'A21 review 源 Fix 闭环:next 归位 execute → 出口回源 review → 审查出口真实执行(真实命令)',
1945
+ run: (dir) => {
1946
+ const env = { FLOW_COMET_PROTOCOL: path.join(dir, 'reference', 'workflow-protocol.json') };
1947
+ writeFixBatchFixture(dir, { kind: 'review', fixStatus: 'pending' });
1948
+
1949
+ // ① 旧绕过路径:Fix 任务仍 pending 时直接 exit review --apply → 新 change BLOCKED + 恢复指引
1950
+ const bypass = runGuard(['exit', 'review', '--apply'], dir, env);
1951
+ assertExit(bypass, 1);
1952
+ assertOut(bypass, 'BLOCKED: 存在未归位/未跑出口的 Fix 批次');
1953
+ assertOut(bypass, 'Fix 批次');
1954
+ assertOut(bypass, 'entry execute');
1955
+ assertOut(bypass, 'workflow-state.mjs next');
1956
+ assertNotOut(bypass, 'ALL CHECKS PASSED');
1957
+ let st = readStateFile(dir);
1958
+ if (st.currentNode !== 'review' || st.completedNodes.includes('review')) {
1959
+ throw new Error('越界 BLOCK 不得改写 state: ' + JSON.stringify({ currentNode: st.currentNode, completedNodes: st.completedNodes }));
1960
+ }
1961
+
1962
+ // 首轮计数与 verify 失败计数互相独立:先记一次 verify 失败,归位不得改动其计数。
1963
+ assertExit(runState(['verify-fail'], dir, env), 0);
1964
+ // ② next 受控归位 execute:显式审计行 + 真实写盘(不得停在源节点)
1965
+ const nxt = runState(['next'], dir, env);
1966
+ assertExit(nxt, 0);
1967
+ assertOut(nxt, 'FIX-BATCH: 归位 execute(源节点 review)(第 1/3 轮)');
1968
+ assertNodeLine(nxt, 'execute');
1969
+ assertNotNodeLine(nxt, 'review');
1970
+ st = readStateFile(dir);
1971
+ if (st.currentNode !== 'execute') {
1972
+ throw new Error('归位后 currentNode 应为 execute,实际 ' + JSON.stringify(st.currentNode));
1973
+ }
1974
+ if (st.completedNodes.includes('review')) {
1975
+ throw new Error('归位不得把源节点标完成: ' + JSON.stringify(st.completedNodes));
1976
+ }
1977
+ if (!st.evidence?.review) {
1978
+ throw new Error('归位不得清掉源节点证据: ' + JSON.stringify(st.evidence));
1979
+ }
1980
+ if (st.fixRoundsByChange?.ch !== 1) {
1981
+ throw new Error('首轮受控归位应计数 1: ' + JSON.stringify(st.fixRoundsByChange));
1982
+ }
1983
+ if (st.verifyFailuresByChange?.ch !== 1) {
1984
+ throw new Error('Fix 轮次计数不得改写 verify 失败计数: ' + JSON.stringify(st.verifyFailuresByChange));
1985
+ }
1986
+
1987
+ // ③ 完成修复任务(标 done + 逐任务 SUMMARY + 重载声明 + record execute)
1988
+ completeFixTaskAndRecord(dir, env);
1989
+
1990
+ // 收口前基线(只读):出口前后完成节点集合不变,目的地仍为未完成的 review
1991
+ const a21Before = readStateFile(dir);
1992
+ // ④ exit execute --apply 跑四类出口后回源 review(REVIEW.md 在场也不得按产物跳 verify)
1993
+ const ex = runGuard(['exit', 'execute', '--apply'], dir, env);
1994
+ assertExit(ex, 0);
1995
+ assertOut(ex, 'ALL CHECKS PASSED');
1996
+ assertOut(ex, 'FIX-BATCH: 回源节点 review(execute 出口已完成)');
1997
+ assertNodeLine(ex, 'review');
1998
+ assertNotNodeLine(ex, 'verify');
1999
+ assertNotOut(ex, 'RETURN: 回源节点');
2000
+ assertNotOut(ex, '未分类');
2001
+ st = readStateFile(dir);
2002
+ if (st.currentNode !== 'review' || st.completedNodes.includes('review')) {
2003
+ throw new Error('回源后应停在未完成的 review: ' + JSON.stringify({ currentNode: st.currentNode, completedNodes: st.completedNodes }));
2004
+ }
2005
+ if (JSON.stringify(st.completedNodes) !== JSON.stringify(a21Before.completedNodes)) {
2006
+ throw new Error('Fix 回源收尾不得改写完成节点集合(仅审计行分类变化): 收口前 '
2007
+ + JSON.stringify(a21Before.completedNodes) + ' 收口后 ' + JSON.stringify(st.completedNodes));
2008
+ }
2009
+ const a21PostNext = runState(['next'], dir, env);
2010
+ assertExit(a21PostNext, 0);
2011
+ assertNodeLine(a21PostNext, 'review');
2012
+
2013
+ // ⑤ 回源 review 出口门禁真实执行:缺处置标记 → BLOCKED;补齐后同出口通过并推进 verify
2014
+ assertExit(runState(['skill-load', 'review', 'flow-comet-review', '--prompt', 'flow-kit/prompts/6-review.md'], dir, env), 0);
2015
+ assertExit(runGuard(['entry', 'review'], dir, env), 0);
2016
+ writeFile(dir, '.specs/' + CHANGE_ID + '/REVIEW.md', fixBatchReviewDoc(false));
2017
+ const gate = runGuard(['exit', 'review', '--apply'], dir, env);
2018
+ assertExit(gate, 1);
2019
+ assertOut(gate, 'BLOCKED');
2020
+ assertOut(gate, '处置');
2021
+ assertNotOut(gate, 'ALL CHECKS PASSED');
2022
+ st = readStateFile(dir);
2023
+ if (st.currentNode !== 'review' || st.completedNodes.includes('review')) {
2024
+ throw new Error('审查出口 BLOCK 不得改写 state: ' + JSON.stringify({ currentNode: st.currentNode, completedNodes: st.completedNodes }));
2025
+ }
2026
+ writeFile(dir, '.specs/' + CHANGE_ID + '/REVIEW.md', fixBatchReviewDoc(true));
2027
+ const pass = runGuard(['exit', 'review', '--apply'], dir, env);
2028
+ assertExit(pass, 0);
2029
+ assertOut(pass, 'ALL CHECKS PASSED');
2030
+ assertNodeLine(pass, 'verify');
2031
+ st = readStateFile(dir);
2032
+ if (st.currentNode !== 'verify' || !st.completedNodes.includes('review')) {
2033
+ throw new Error('审查出口通过后应推进 verify: ' + JSON.stringify({ currentNode: st.currentNode, completedNodes: st.completedNodes }));
2034
+ }
2035
+ if (st.fixRoundsByChange?.ch !== 1) {
2036
+ throw new Error('审查出口通过不得清零 Fix 轮次计数: ' + JSON.stringify(st.fixRoundsByChange));
2037
+ }
2038
+ if (st.verifyFailuresByChange?.ch !== 1) {
2039
+ throw new Error('审查出口不得改写 verify 失败计数: ' + JSON.stringify(st.verifyFailuresByChange));
2040
+ }
2041
+ },
2042
+ },
2043
+ {
2044
+ // verify 源 Fix 回程(真实命令链路):review 已完成、verify 驻留 + pending 修复任务;
2045
+ // TEST/UAT 已在场(正常产物推导会跳过未出口的 verify 去 archive)→ 修复前 next 停在 verify /
2046
+ // 产物推导会跳过 verify;修复后 next 归位 execute,exit execute --apply 回源 verify 并真实跑
2047
+ // verify 出口(验证命令落盘副作用文件 + 推进 archive)。
2048
+ name: 'A22 verify 源 Fix 回程:回 verify 而非跳过 archive + verify 出口真实执行(真实命令)',
2049
+ run: (dir) => {
2050
+ const env = { FLOW_COMET_PROTOCOL: path.join(dir, 'reference', 'workflow-protocol.json') };
2051
+ const gateMarker = path.join(dir, 'verify-gate-ran.txt');
2052
+ writeFixBatchFixture(dir, { kind: 'verify', fixStatus: 'pending' });
2053
+
2054
+ // ① 旧绕过路径:pending 修复任务时直接 exit verify --apply → BLOCKED,且验证命令未被执行
2055
+ const bypass = runGuard(['exit', 'verify', '--apply'], dir, env);
2056
+ assertExit(bypass, 1);
2057
+ assertOut(bypass, 'BLOCKED: 存在未归位/未跑出口的 Fix 批次');
2058
+ assertOut(bypass, 'entry execute');
2059
+ assertNotOut(bypass, 'ALL CHECKS PASSED');
2060
+ if (fs.existsSync(gateMarker)) throw new Error('越界 BLOCK 不得执行 verify 验证命令');
2061
+ let st = readStateFile(dir);
2062
+ if (st.currentNode !== 'verify' || st.completedNodes.includes('verify')) {
2063
+ throw new Error('越界 BLOCK 不得改写 state: ' + JSON.stringify({ currentNode: st.currentNode, completedNodes: st.completedNodes }));
2064
+ }
2065
+
2066
+ // ② next 受控归位 execute(源节点 verify)
2067
+ const nxt = runState(['next'], dir, env);
2068
+ assertExit(nxt, 0);
2069
+ assertOut(nxt, 'FIX-BATCH: 归位 execute(源节点 verify)');
2070
+ assertNodeLine(nxt, 'execute');
2071
+ assertNotNodeLine(nxt, 'verify');
2072
+ st = readStateFile(dir);
2073
+ if (st.currentNode !== 'execute') {
2074
+ throw new Error('归位后 currentNode 应为 execute,实际 ' + JSON.stringify(st.currentNode));
2075
+ }
2076
+
2077
+ // ③ 完成修复任务并 record execute
2078
+ completeFixTaskAndRecord(dir, env);
2079
+
2080
+ // 收口前基线(只读):出口前后完成节点集合不变,目的地仍为未完成的 verify
2081
+ const a22Before = readStateFile(dir);
2082
+ // ④ exit execute --apply:不按产物跳过 verify → 回源 verify(不是 archive)
2083
+ const ex = runGuard(['exit', 'execute', '--apply'], dir, env);
2084
+ assertExit(ex, 0);
2085
+ assertOut(ex, 'ALL CHECKS PASSED');
2086
+ assertOut(ex, 'FIX-BATCH: 回源节点 verify(execute 出口已完成)');
2087
+ assertNodeLine(ex, 'verify');
2088
+ assertNotNodeLine(ex, 'archive');
2089
+ assertNotOut(ex, 'RETURN: 回源节点');
2090
+ assertNotOut(ex, '未分类');
2091
+ st = readStateFile(dir);
2092
+ if (st.currentNode !== 'verify' || st.completedNodes.includes('verify')) {
2093
+ throw new Error('回源后应停在未完成的 verify: ' + JSON.stringify({ currentNode: st.currentNode, completedNodes: st.completedNodes }));
2094
+ }
2095
+ if (JSON.stringify(st.completedNodes) !== JSON.stringify(a22Before.completedNodes)) {
2096
+ throw new Error('Fix 回源收尾不得改写完成节点集合(仅审计行分类变化): 收口前 '
2097
+ + JSON.stringify(a22Before.completedNodes) + ' 收口后 ' + JSON.stringify(st.completedNodes));
2098
+ }
2099
+ const a22PostNext = runState(['next'], dir, env);
2100
+ assertExit(a22PostNext, 0);
2101
+ assertNodeLine(a22PostNext, 'verify');
2102
+
2103
+ // ⑤ 回源 verify 出口真实执行:验证命令落盘 + 推进 archive
2104
+ assertExit(runState(['skill-load', 'verify', 'flow-comet-verify', '--prompt', 'flow-kit/prompts/7-integration.md'], dir, env), 0);
2105
+ assertExit(runGuard(['entry', 'verify'], dir, env), 0);
2106
+ const vf = runGuard(['exit', 'verify', '--apply'], dir, env);
2107
+ assertExit(vf, 0);
2108
+ assertOut(vf, 'ALL CHECKS PASSED');
2109
+ assertNodeLine(vf, 'archive');
2110
+ if (!fs.existsSync(gateMarker) || fs.readFileSync(gateMarker, 'utf8') !== 'GATE-RAN') {
2111
+ throw new Error('verify 出口未真实执行 TEST.md 验证命令(副作用文件缺失/内容不符)');
2112
+ }
2113
+ st = readStateFile(dir);
2114
+ if (st.currentNode !== 'archive' || !st.completedNodes.includes('verify')) {
2115
+ throw new Error('验证出口通过后应推进 archive: ' + JSON.stringify({ currentNode: st.currentNode, completedNodes: st.completedNodes }));
2116
+ }
2117
+ },
2118
+ },
2119
+ {
2120
+ // 越界拦截 + done-but-unclosed 回放 + 旧 change 兼容(真实命令链路):
2121
+ // ① 新 change review/pending → BLOCKED + state 不变;
2122
+ // ② L-070 事故回放——Fix 任务全 done 但 history 最新 exit execute 签名仍是追加前值
2123
+ // (从未重跑 execute 出口)→ 同出口 BLOCKED + state 字节零改写(修复前被错误断言为通过);
2124
+ // ③ 正对照——按指引 entry execute + exit execute --apply 真闭合后,review 出口通过;
2125
+ // ④⑤ verify 源 pending / done-but-unclosed 同样 BLOCKED 且验证命令不执行,⑥ 闭合后通过;
2126
+ // ⑦⑧⑨ 旧 change(无 new change 标记)同形态渐进 WARN 放行、next 归位可达、验证出口真实执行。
2127
+ name: 'A23 Fix 越界拦截与旧 change 渐进:源节点直接 exit BLOCK(新)/WARN(旧)不卡死(真实命令)',
2128
+ run: (dir) => {
2129
+ const env = { FLOW_COMET_PROTOCOL: path.join(dir, 'reference', 'workflow-protocol.json') };
2130
+ const gateMarker = path.join(dir, 'verify-gate-ran.txt');
2131
+ const statePath = path.join(dir, '.flow-comet', 'flow-comet-state.json');
2132
+
2133
+ // ① 新 change review 源 + pending:直接 exit review --apply → BLOCKED + 恢复指引 + state 不变
2134
+ writeFixBatchFixture(dir, { kind: 'review', fixStatus: 'pending' });
2135
+ const rBlock = runGuard(['exit', 'review', '--apply'], dir, env);
2136
+ assertExit(rBlock, 1);
2137
+ assertOut(rBlock, 'BLOCKED: 存在未归位/未跑出口的 Fix 批次');
2138
+ assertOut(rBlock, '未跑出口');
2139
+ assertOut(rBlock, '恢复');
2140
+ assertOut(rBlock, 'entry execute');
2141
+ assertOut(rBlock, 'workflow-state.mjs next');
2142
+ assertNotOut(rBlock, 'ALL CHECKS PASSED');
2143
+ let st = readStateFile(dir);
2144
+ if (st.currentNode !== 'review' || st.completedNodes.includes('review')) {
2145
+ throw new Error('review 源越界 BLOCK 不得改写 state: ' + JSON.stringify({ currentNode: st.currentNode, completedNodes: st.completedNodes }));
2146
+ }
2147
+
2148
+ // ② L-070 事故回放形态:Fix 任务已全 done,但 history 最新 exit execute 记录的是追加前签名
2149
+ //(done 后从未再跑 execute 出口)→ 修复前静默放行,修复后必须 BLOCKED + state 字节零改写
2150
+ writeFixBatchFixture(dir, { kind: 'review', fixStatus: 'done' });
2151
+ writeFile(dir, '.specs/' + CHANGE_ID + '/T-FIX-01-SUMMARY.md', execSummaryFixture('T-FIX-01'));
2152
+ const doneUnclosed = readStateFile(dir);
2153
+ doneUnclosed.history = fixBatchHistoryWithStaleExecuteExit();
2154
+ writeState(dir, doneUnclosed);
2155
+ const doneBytes = fs.readFileSync(statePath, 'utf8');
2156
+ const rDoneBlock = runGuard(['exit', 'review', '--apply'], dir, env);
2157
+ assertExit(rDoneBlock, 1);
2158
+ assertOut(rDoneBlock, 'BLOCKED: 存在未归位/未跑出口的 Fix 批次');
2159
+ assertOut(rDoneBlock, 'entry execute');
2160
+ assertOut(rDoneBlock, 'workflow-state.mjs next');
2161
+ assertNotOut(rDoneBlock, 'ALL CHECKS PASSED');
2162
+ if (fs.readFileSync(statePath, 'utf8') !== doneBytes) {
2163
+ throw new Error('done-but-unclosed 越界 BLOCK 不得改写 state 字节');
2164
+ }
2165
+
2166
+ // ③ 正对照:同夹具按指引真闭合(entry execute → 完成声明/record → exit execute --apply 写当前
2167
+ // 签名并回源 review)→ 再 exit review --apply 通过(拦截只针对未闭合态,不误伤正常路径)
2168
+ assertExit(runGuard(['entry', 'execute'], dir, env), 0);
2169
+ completeFixTaskAndRecord(dir, env);
2170
+ const rClosedExit = runGuard(['exit', 'execute', '--apply'], dir, env);
2171
+ assertExit(rClosedExit, 0);
2172
+ assertOut(rClosedExit, 'FIX-BATCH: 回源节点 review(execute 出口已完成)');
2173
+ assertNotOut(rClosedExit, 'RETURN: 回源节点');
2174
+ assertNodeLine(rClosedExit, 'review');
2175
+ assertExit(runState(['skill-load', 'review', 'flow-comet-review', '--prompt', 'flow-kit/prompts/6-review.md'], dir, env), 0);
2176
+ assertExit(runGuard(['entry', 'review'], dir, env), 0);
2177
+ const rReviewPass = runGuard(['exit', 'review', '--apply'], dir, env);
2178
+ assertExit(rReviewPass, 0);
2179
+ assertOut(rReviewPass, 'ALL CHECKS PASSED');
2180
+ assertNotOut(rReviewPass, 'BLOCKED');
2181
+ assertNodeLine(rReviewPass, 'verify');
2182
+
2183
+ // ③b 并行 Fix 任务(可委托 parallel pending)+ review 源(真实命令链路):
2184
+ // 直接 exit review BLOCKED;next 归位 subagent-execute;完成委托后第二趟
2185
+ // exit subagent-execute --apply 回源 review;源节点出口真实执行并推进 verify。
2186
+ writeFixBatchFixture(dir, { kind: 'review', fixStatus: 'pending', parallelFix: true });
2187
+ const pBypass = runGuard(['exit', 'review', '--apply'], dir, env);
2188
+ assertExit(pBypass, 1);
2189
+ assertOut(pBypass, 'BLOCKED: 存在未归位/未跑出口的 Fix 批次');
2190
+ assertNotOut(pBypass, 'ALL CHECKS PASSED');
2191
+ let pSt = readStateFile(dir);
2192
+ if (pSt.currentNode !== 'review' || pSt.completedNodes.includes('review')) {
2193
+ throw new Error('并行越界 BLOCK 不得改写 state: ' + JSON.stringify({ currentNode: pSt.currentNode, completedNodes: pSt.completedNodes }));
2194
+ }
2195
+ const pNext = runState(['next'], dir, env);
2196
+ assertExit(pNext, 0);
2197
+ assertOut(pNext, 'FIX-BATCH: 归位 subagent-execute(源节点 review)');
2198
+ assertNodeLine(pNext, 'subagent-execute');
2199
+ assertNotNodeLine(pNext, 'execute');
2200
+ pSt = readStateFile(dir);
2201
+ if (pSt.currentNode !== 'subagent-execute') {
2202
+ throw new Error('并行回退归位后 currentNode 应为 subagent-execute,实际 ' + JSON.stringify(pSt.currentNode));
2203
+ }
2204
+ // 完成并行修复任务:标记 done + 摘要 + 真实 handoff request/result + skill-load/record。
2205
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', fixBatchParallelTaskText('done'));
2206
+ writeFile(dir, '.specs/' + CHANGE_ID + '/P-FIX-01-SUMMARY.md', execSummaryFixture('P-FIX-01'));
2207
+ // 委托前先加载节点技能声明(新 change 两层加载模型:request 命令要求标记在位)。
2208
+ assertExit(runState(['skill-load', 'subagent-execute', 'flow-comet-dev', '--prompt', 'flow-kit/prompts/4-dev.md'], dir, env), 0);
2209
+ for (const taskId of ['T01', 'P-FIX-01']) {
2210
+ assertExit(runHandoff(['request', taskId, taskId + ' 委托', '--write-files', 'src/' + taskId.toLowerCase() + '.mjs'], dir), 0);
2211
+ assertExit(runHandoff(['result', taskId, fullContract('abcd1234abcd1234abcd1234abcd1234abcd1234', taskId)], dir), 0);
2212
+ }
2213
+ assertExit(runState(['record', 'subagent-execute', '{"summary":"parallel fix delegated and collected"}'], dir, env), 0);
2214
+ const pExit = runGuard(['exit', 'subagent-execute', '--apply'], dir, env);
2215
+ assertExit(pExit, 0);
2216
+ assertOut(pExit, 'ALL CHECKS PASSED');
2217
+ assertOut(pExit, 'FIX-BATCH: 回源节点 review(subagent-execute 出口已完成)');
2218
+ assertNotOut(pExit, 'RETURN: 回源节点');
2219
+ assertNodeLine(pExit, 'review');
2220
+ pSt = readStateFile(dir);
2221
+ if (pSt.currentNode !== 'review') {
2222
+ throw new Error('并行修复第二趟出口应回源 review,实际 ' + JSON.stringify(pSt.currentNode));
2223
+ }
2224
+ assertExit(runState(['skill-load', 'review', 'flow-comet-review', '--prompt', 'flow-kit/prompts/6-review.md'], dir, env), 0);
2225
+ assertExit(runGuard(['entry', 'review'], dir, env), 0);
2226
+ const pReviewPass = runGuard(['exit', 'review', '--apply'], dir, env);
2227
+ assertExit(pReviewPass, 0);
2228
+ assertOut(pReviewPass, 'ALL CHECKS PASSED');
2229
+ assertNodeLine(pReviewPass, 'verify');
2230
+ // ④ 新 change verify 源 + pending:直接 exit verify --apply → BLOCKED,验证命令未执行
2231
+ fs.rmSync(gateMarker, { force: true });
2232
+ writeFixBatchFixture(dir, { kind: 'verify', fixStatus: 'pending' });
2233
+ const vBlock = runGuard(['exit', 'verify', '--apply'], dir, env);
2234
+ assertExit(vBlock, 1);
2235
+ assertOut(vBlock, 'BLOCKED: 存在未归位/未跑出口的 Fix 批次');
2236
+ assertOut(vBlock, 'entry execute');
2237
+ assertNotOut(vBlock, 'ALL CHECKS PASSED');
2238
+ if (fs.existsSync(gateMarker)) throw new Error('越界 BLOCK 不得执行 verify 验证命令');
2239
+ st = readStateFile(dir);
2240
+ if (st.currentNode !== 'verify' || st.completedNodes.includes('verify')) {
2241
+ throw new Error('verify 源越界 BLOCK 不得改写 state: ' + JSON.stringify({ currentNode: st.currentNode, completedNodes: st.completedNodes }));
2242
+ }
2243
+
2244
+ // ⑤ verify 源 done-but-unclosed 回放(独立复核实跑形态):review 已完成 + TEST/UAT 在场
2245
+ //(原路径会跳过 verify 去 archive)+ 全 done + 最新 execute exit 签名过时 → BLOCKED,验证命令
2246
+ // 不执行、state 字节零改写;⑥ 按指引闭合后 exit verify 真实执行验证命令并推进 archive
2247
+ writeFixBatchFixture(dir, { kind: 'verify', fixStatus: 'done' });
2248
+ writeFile(dir, '.specs/' + CHANGE_ID + '/T-FIX-01-SUMMARY.md', execSummaryFixture('T-FIX-01'));
2249
+ const verifyDoneUnclosed = readStateFile(dir);
2250
+ verifyDoneUnclosed.history = fixBatchHistoryWithStaleExecuteExit();
2251
+ writeState(dir, verifyDoneUnclosed);
2252
+ const verifyDoneBytes = fs.readFileSync(statePath, 'utf8');
2253
+ const vDoneBlock = runGuard(['exit', 'verify', '--apply'], dir, env);
2254
+ assertExit(vDoneBlock, 1);
2255
+ assertOut(vDoneBlock, 'BLOCKED: 存在未归位/未跑出口的 Fix 批次');
2256
+ assertOut(vDoneBlock, 'entry execute');
2257
+ assertNotOut(vDoneBlock, 'ALL CHECKS PASSED');
2258
+ if (fs.existsSync(gateMarker)) throw new Error('done-but-unclosed 越界 BLOCK 不得执行 verify 验证命令');
2259
+ if (fs.readFileSync(statePath, 'utf8') !== verifyDoneBytes) {
2260
+ throw new Error('verify done-but-unclosed 越界 BLOCK 不得改写 state 字节');
2261
+ }
2262
+ assertExit(runGuard(['entry', 'execute'], dir, env), 0);
2263
+ completeFixTaskAndRecord(dir, env);
2264
+ const vClosedExit = runGuard(['exit', 'execute', '--apply'], dir, env);
2265
+ assertExit(vClosedExit, 0);
2266
+ assertOut(vClosedExit, 'FIX-BATCH: 回源节点 verify(execute 出口已完成)');
2267
+ assertNotOut(vClosedExit, 'RETURN: 回源节点');
2268
+ assertNodeLine(vClosedExit, 'verify');
2269
+ assertExit(runState(['skill-load', 'verify', 'flow-comet-verify', '--prompt', 'flow-kit/prompts/7-integration.md'], dir, env), 0);
2270
+ assertExit(runGuard(['entry', 'verify'], dir, env), 0);
2271
+ const vPass = runGuard(['exit', 'verify', '--apply'], dir, env);
2272
+ assertExit(vPass, 0);
2273
+ assertOut(vPass, 'ALL CHECKS PASSED');
2274
+ assertNodeLine(vPass, 'archive');
2275
+ if (!fs.existsSync(gateMarker) || fs.readFileSync(gateMarker, 'utf8') !== 'GATE-RAN') {
2276
+ throw new Error('闭合后 verify 出口未真实执行 TEST.md 验证命令(副作用文件缺失/内容不符)');
2277
+ }
2278
+
2279
+ // ⑦ 旧 change review 源 + pending:直接 exit review --apply → FIX-BATCH WARN 渐进放行(不 BLOCK、不死结)
2280
+ writeFixBatchFixture(dir, { kind: 'review', fixStatus: 'pending', newChange: false });
2281
+ const oldExit = runGuard(['exit', 'review', '--apply'], dir, env);
2282
+ assertExit(oldExit, 0);
2283
+ assertOut(oldExit, 'FIX-BATCH WARN');
2284
+ assertNotOut(oldExit, 'BLOCKED');
2285
+ assertOut(oldExit, 'ALL CHECKS PASSED');
2286
+ assertNodeLine(oldExit, 'execute'); // pending 修复任务使路由继续回 execute(流程未卡死)
2287
+ st = readStateFile(dir);
2288
+ if (st.currentNode !== 'execute') {
2289
+ throw new Error('旧 change 渐进放行后 currentNode 应为 execute,实际 ' + JSON.stringify(st.currentNode));
2290
+ }
2291
+
2292
+ // ⑧ 旧 change next 入口:pending 修复 + 源节点驻留 → 不新增 BLOCK,归位 execute 可继续
2293
+ writeFixBatchFixture(dir, { kind: 'review', fixStatus: 'pending', newChange: false });
2294
+ const oldNext = runState(['next'], dir, env);
2295
+ assertExit(oldNext, 0);
2296
+ assertNotOut(oldNext, 'BLOCKED');
2297
+ assertOut(oldNext, 'FIX-BATCH: 归位 execute(源节点 review)');
2298
+ assertNodeLine(oldNext, 'execute');
2299
+ st = readStateFile(dir);
2300
+ if (st.currentNode !== 'execute') {
2301
+ throw new Error('旧 change next 归位后 currentNode 应为 execute,实际 ' + JSON.stringify(st.currentNode));
2302
+ }
2303
+
2304
+ // ⑨ 旧 change verify 源 + pending:直接 exit verify --apply → WARN 渐进且验证出口真实执行、不卡死
2305
+ fs.rmSync(gateMarker, { force: true });
2306
+ writeFixBatchFixture(dir, { kind: 'verify', fixStatus: 'pending', newChange: false });
2307
+ const oldVerify = runGuard(['exit', 'verify', '--apply'], dir, env);
2308
+ assertExit(oldVerify, 0);
2309
+ assertOut(oldVerify, 'FIX-BATCH WARN');
2310
+ assertNotOut(oldVerify, 'BLOCKED');
2311
+ assertOut(oldVerify, 'ALL CHECKS PASSED');
2312
+ assertNodeLine(oldVerify, 'execute'); // pending 修复任务使路由继续回 execute
2313
+ if (!fs.existsSync(gateMarker) || fs.readFileSync(gateMarker, 'utf8') !== 'GATE-RAN') {
2314
+ throw new Error('旧 change verify 出口未真实执行 TEST.md 验证命令(渐进不等于跳过门禁)');
2315
+ }
2316
+
2317
+ // ⑩ 多波次真实 Fix:第一波收口后追加第二波;第三趟收口时历史最新签名已等于当前签名、
2318
+ // 更早签名仍发散——全量签名扫描不得被最新签名覆盖,仍须保留 FIX-BATCH 锚。
2319
+ writeFixBatchFixture(dir, { kind: 'review', fixStatus: 'pending' });
2320
+ assertExit(runState(['next'], dir, env), 0); // 受控归位 execute
2321
+ completeFixTaskAndRecord(dir, env); // 第一波:单修复任务 done + 声明/record
2322
+ const wave1 = runGuard(['exit', 'execute', '--apply'], dir, env);
2323
+ assertExit(wave1, 0);
2324
+ assertOut(wave1, 'FIX-BATCH: 回源节点 review(execute 出口已完成)');
2325
+ assertNotOut(wave1, 'RETURN: 回源节点');
2326
+ // 第二波:追加第二个修复任务(任务集签名发散)→ 归位 → 两任务完成后收口
2327
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', fixBatchTwoFixTaskText('pending', 'pending'));
2328
+ const wave2Next = runState(['next'], dir, env);
2329
+ assertExit(wave2Next, 0);
2330
+ assertOut(wave2Next, 'FIX-BATCH: 归位 execute(源节点 review)');
2331
+ assertNodeLine(wave2Next, 'execute');
2332
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', fixBatchTwoFixTaskText('done', 'done'));
2333
+ writeFile(dir, '.specs/' + CHANGE_ID + '/T-FIX-01-SUMMARY.md', execSummaryFixture('T-FIX-01'));
2334
+ writeFile(dir, '.specs/' + CHANGE_ID + '/T-FIX-02-SUMMARY.md', execSummaryFixture('T-FIX-02'));
2335
+ assertExit(runState(['skill-load', 'execute', 'flow-comet-execute', '--prompt', 'flow-kit/prompts/4-dev.md'], dir, env), 0);
2336
+ assertExit(runState(['record', 'execute', '{"summary":"fix wave two executed","parallelTakeoverApproved":true}'], dir, env), 0);
2337
+ const wave2 = runGuard(['exit', 'execute', '--apply'], dir, env);
2338
+ assertExit(wave2, 0);
2339
+ assertOut(wave2, 'FIX-BATCH: 回源节点 review(execute 出口已完成)');
2340
+ assertNotOut(wave2, 'RETURN: 回源节点');
2341
+ // 第三趟(把工作归属置回 execute 后直达真实出口,不改任务集):历史最新签名已==当前签名、
2342
+ // 更早签名仍发散——全量签名扫描不得被最新签名覆盖,仍须保留 FIX-BATCH 锚。
2343
+ const stWave3 = readStateFile(dir);
2344
+ stWave3.currentNode = 'execute';
2345
+ writeState(dir, stWave3);
2346
+ const wave3 = runGuard(['exit', 'execute', '--apply'], dir, env);
2347
+ assertExit(wave3, 0);
2348
+ assertOut(wave3, 'FIX-BATCH: 回源节点 review(execute 出口已完成)');
2349
+ assertNotOut(wave3, 'RETURN: 回源节点');
2350
+ const waveState = readStateFile(dir);
2351
+ const waveExits = (waveState.history || []).filter((event) =>
2352
+ event && event.event === 'exit-applied' && (event.node === 'execute' || event.node === 'subagent-execute'));
2353
+ if (waveExits.length < 3) {
2354
+ throw new Error('多波次收口应留下至少三条 execute 家族出口事件: ' + JSON.stringify(waveExits));
2355
+ }
2356
+ const latestSignature = waveExits[waveExits.length - 1].taskSetSignature;
2357
+ if (latestSignature !== waveExits[waveExits.length - 2].taskSetSignature) {
2358
+ throw new Error('第三趟收口后最新签名应已等于当前任务集签名(夹具前提)');
2359
+ }
2360
+ if (latestSignature === waveExits[0].taskSetSignature) {
2361
+ throw new Error('多波次任务集签名应已发散(夹具前提): ' + latestSignature);
2362
+ }
2363
+
2364
+ // ⑪ 源未 entry 的真实 Fix:分类只认历史签名/Fix 结构标记,不依赖 enteredNodes → 仍 FIX-BATCH
2365
+ writeFixBatchFixture(dir, { kind: 'review', fixStatus: 'pending' });
2366
+ const noEntryState = readStateFile(dir);
2367
+ noEntryState.enteredNodes = (noEntryState.enteredNodes || []).filter((nodeId) => nodeId !== 'review');
2368
+ writeState(dir, noEntryState);
2369
+ const noEntryNext = runState(['next'], dir, env);
2370
+ assertExit(noEntryNext, 0);
2371
+ assertOut(noEntryNext, 'FIX-BATCH: 归位 execute(源节点 review)');
2372
+ completeFixTaskAndRecord(dir, env);
2373
+ const noEntryExit = runGuard(['exit', 'execute', '--apply'], dir, env);
2374
+ assertExit(noEntryExit, 0);
2375
+ assertOut(noEntryExit, 'FIX-BATCH: 回源节点 review(execute 出口已完成)');
2376
+ assertNotOut(noEntryExit, 'RETURN: 回源节点');
2377
+ assertNodeLine(noEntryExit, 'review');
2378
+
2379
+ // ⑫ 旧态证据不足:无签名历史、无 Fix 标记 → 中性未分类 RETURN,不 BLOCK、不冒充 Fix、不卡死
2380
+ writeIntakeArtifacts(dir);
2381
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md',
2382
+ '# TASK\n\n## 任务清单\n\n' + serialTaskBlock('T01', 'done') + '\n');
2383
+ writeFile(dir, '.specs/' + CHANGE_ID + '/T01-SUMMARY.md', execSummaryFixture('T01'));
2384
+ writeState(dir, {
2385
+ activeChange: CHANGE_ID,
2386
+ currentNode: 'execute',
2387
+ completedNodes: ['open', 'design', 'plan', 'execute', 'subagent-execute'],
2388
+ enteredNodes: ['open', 'design', 'plan', 'execute', 'subagent-execute', 'review'],
2389
+ evidence: { execute: { summary: 'first pass executed' }, review: { summary: 'review reopened' } },
2390
+ verifyFailures: 0,
2391
+ executionMode: 'subagent',
2392
+ directOverride: false,
2393
+ });
2394
+ assertExit(runState(['skill-load', 'execute', 'flow-comet-execute', '--prompt', 'flow-kit/prompts/4-dev.md'], dir, env), 0);
2395
+ assertExit(runState(['record', 'execute', '{"summary":"legacy state closure","parallelTakeoverApproved":true}'], dir, env), 0);
2396
+ const legacyExit = runGuard(['exit', 'execute', '--apply'], dir, env);
2397
+ assertExit(legacyExit, 0);
2398
+ assertOut(legacyExit, 'RETURN: 回源节点 review(execute 出口已完成;旧 state 缺闭合/修复证据,未分类)');
2399
+ assertNotOut(legacyExit, 'FIX-BATCH');
2400
+ assertNotOut(legacyExit, 'BLOCKED');
2401
+ assertNodeLine(legacyExit, 'review');
2402
+ const legacyState = readStateFile(dir);
2403
+ if (legacyState.currentNode !== 'review') {
2404
+ throw new Error('旧态未分类回程应停在 review: ' + JSON.stringify(legacyState.currentNode));
2405
+ }
2406
+
2407
+ // ⑬ 受控归位轮次真实链路(review 源):第 1~3 轮输出「第 n/3 轮」并递增计数;第 4 轮新
2408
+ // change BLOCK(state 字节零改写、currentNode 保持 review);用户显式授权(嵌套证据)
2409
+ // 后放行;verify 失败计数与轮次计数各自独立;旧 change 第 4 轮渐进 WARN 放行。
2410
+ const fixRoundsText = (statuses) => '# TASK\n\n## 任务清单\n\n' + serialTaskBlock('T01', 'done')
2411
+ + '\n\n## Fix 任务(来自 REVIEW / INTEGRATION)\n\n'
2412
+ + statuses.map((s, i) => serialTaskBlock('T-FIX-0' + (i + 1), s)).join('\n') + '\n';
2413
+ const doneStatuses = (n) => Array.from({ length: n }, () => 'done');
2414
+ const assertRoundCounters = (round, label) => {
2415
+ const s = readStateFile(dir);
2416
+ if (s.fixRoundsByChange?.ch !== round) {
2417
+ throw new Error(label + ' 受控归位轮次应为 ' + round + ': ' + JSON.stringify(s.fixRoundsByChange));
2418
+ }
2419
+ if (s.verifyFailuresByChange?.ch !== 2) {
2420
+ throw new Error(label + ' 不得改写 verify 失败计数(应保持 2): ' + JSON.stringify(s.verifyFailuresByChange));
2421
+ }
2422
+ };
2423
+ const completeFixRound = (n) => {
2424
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', fixRoundsText(doneStatuses(n)));
2425
+ for (let i = 1; i <= n; i++) {
2426
+ writeFile(dir, '.specs/' + CHANGE_ID + '/T-FIX-0' + i + '-SUMMARY.md', execSummaryFixture('T-FIX-0' + i));
2427
+ }
2428
+ assertExit(runState(['skill-load', 'execute', 'flow-comet-execute', '--prompt', 'flow-kit/prompts/4-dev.md'], dir, env), 0);
2429
+ // entry 记录 taskHash:签名值必须带算法版本前缀(新链路 vN 前缀形态)
2430
+ assertExit(runGuard(['entry', 'execute'], dir, env), 0);
2431
+ const stHash = readStateFile(dir);
2432
+ if (!/^v1:[0-9a-f]{64}$/.test(String(stHash.taskHash))) {
2433
+ throw new Error('execute entry 应写入带算法版本前缀的任务集签名: ' + JSON.stringify(stHash.taskHash));
2434
+ }
2435
+ assertExit(runState(['record', 'execute', '{"summary":"fix round ' + n + ' executed","parallelTakeoverApproved":true}'], dir, env), 0);
2436
+ const closed = runGuard(['exit', 'execute', '--apply'], dir, env);
2437
+ assertExit(closed, 0);
2438
+ assertOut(closed, 'FIX-BATCH: 回源节点 review(execute 出口已完成)');
2439
+ const stEvent = readStateFile(dir);
2440
+ const lastExit = [...(stEvent.history || [])].reverse()
2441
+ .find((e) => e.event === 'exit-applied' && e.node === 'execute');
2442
+ if (!lastExit || lastExit.signatureAlgo !== 'v1' || !/^v1:[0-9a-f]{64}$/.test(String(lastExit.taskSetSignature))) {
2443
+ throw new Error('execute 出口事件应携带算法版本元数据(signatureAlgo + vN 前缀签名): ' + JSON.stringify(lastExit));
2444
+ }
2445
+ if (stEvent.currentNode !== 'review') {
2446
+ throw new Error('第 ' + n + ' 轮收口应回到未完成的 review: ' + JSON.stringify(stEvent.currentNode));
2447
+ }
2448
+ };
2449
+
2450
+ writeFixBatchFixture(dir, { kind: 'review', fixStatus: 'pending' });
2451
+ // verify 失败计数先落到 2——后续 4 轮归位都不得触碰该值
2452
+ assertExit(runState(['verify-fail'], dir, env), 0);
2453
+ const vfTwo = runState(['verify-fail'], dir, env);
2454
+ assertExit(vfTwo, 0);
2455
+ assertOut(vfTwo, 'VERIFY-FAIL: 2/3');
2456
+ for (let round = 1; round <= 3; round++) {
2457
+ const rollback = runState(['next'], dir, env);
2458
+ assertExit(rollback, 0);
2459
+ assertOut(rollback, 'FIX-BATCH: 归位 execute(源节点 review)');
2460
+ assertOut(rollback, '(第 ' + round + '/3 轮)');
2461
+ assertRoundCounters(round, '第 ' + round + ' 轮');
2462
+ completeFixRound(round);
2463
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', fixRoundsText([...doneStatuses(round), 'pending']));
2464
+ }
2465
+ // 第 4 轮:新 change BLOCK;state 字节零改写、currentNode 保持 review、轮次仍为 3
2466
+ const round4Bytes = fs.readFileSync(statePath, 'utf8');
2467
+ const round4Block = runState(['next'], dir, env);
2468
+ assertExit(round4Block, 1);
2469
+ assertOut(round4Block, 'BLOCKED');
2470
+ assertOut(round4Block, '第 4 轮需用户决策');
2471
+ assertOut(round4Block, '继续修');
2472
+ assertOut(round4Block, '停止');
2473
+ assertOut(round4Block, 'fixRoundOverride');
2474
+ if (fs.readFileSync(statePath, 'utf8') !== round4Bytes) {
2475
+ throw new Error('第 4 轮 BLOCK 不得改写 state 字节(currentNode/计数均不得变化)');
2476
+ }
2477
+ let round4State = readStateFile(dir);
2478
+ if (round4State.currentNode !== 'review') {
2479
+ throw new Error('第 4 轮 BLOCK 不得改写 currentNode: ' + JSON.stringify(round4State.currentNode));
2480
+ }
2481
+ assertRoundCounters(3, '第 4 轮 BLOCK 后');
2482
+ // F5 真实链路:不完整授权(仅 round,缺 at/source)按未授权 fail-closed——仍 BLOCK 且
2483
+ // state 字节零改写;随后补全完整三元组才放行(BLOCK → 非法形态仍 BLOCK → 完整授权 → 放行)。
2484
+ round4State.evidence.review = {
2485
+ ...(round4State.evidence.review || {}),
2486
+ fixRoundOverride: { round: 4 },
2487
+ };
2488
+ writeState(dir, round4State);
2489
+ const incompleteBytes = fs.readFileSync(statePath, 'utf8');
2490
+ const round4Incomplete = runState(['next'], dir, env);
2491
+ assertExit(round4Incomplete, 1);
2492
+ assertOut(round4Incomplete, 'BLOCKED');
2493
+ assertNotOut(round4Incomplete, '(第 4/3 轮)');
2494
+ if (fs.readFileSync(statePath, 'utf8') !== incompleteBytes) {
2495
+ throw new Error('F5 缺 at/source 的不完整授权必须 fail-closed:state 字节零改写');
2496
+ }
2497
+ assertRoundCounters(3, 'F5 不完整授权 BLOCK 后');
2498
+ if (readStateFile(dir).currentNode !== 'review') {
2499
+ throw new Error('F5 不完整授权不得改写 currentNode(应保持 review)');
2500
+ }
2501
+ // 用户显式授权:嵌套 evidence 补全 round/at/source 三元组 → 同一入口放行第 4 轮
2502
+ round4State = readStateFile(dir);
2503
+ round4State.evidence.review = {
2504
+ ...(round4State.evidence.review || {}),
2505
+ fixRoundOverride: { round: 4, at: new Date().toISOString(), source: 'user' },
2506
+ };
2507
+ writeState(dir, round4State);
2508
+ const round4Authorized = runState(['next'], dir, env);
2509
+ assertExit(round4Authorized, 0);
2510
+ assertOut(round4Authorized, 'FIX-BATCH: 归位 execute(源节点 review)(第 4/3 轮)');
2511
+ round4State = readStateFile(dir);
2512
+ if (round4State.currentNode !== 'execute' || round4State.fixRoundsByChange?.ch !== 4) {
2513
+ throw new Error('授权后应放行第 4 轮并计数到 4: '
2514
+ + JSON.stringify({ currentNode: round4State.currentNode, rounds: round4State.fixRoundsByChange }));
2515
+ }
2516
+ completeFixRound(4);
2517
+ // 轮次计数不影响 verify 预算:同一 change 继续失败到 3/3 仍可用,第 4 次才超限
2518
+ const vfThree = runState(['verify-fail'], dir, env);
2519
+ assertExit(vfThree, 0);
2520
+ assertOut(vfThree, 'VERIFY-FAIL: 3/3');
2521
+ const vfFour = runState(['verify-fail'], dir, env);
2522
+ assertExit(vfFour, 1);
2523
+ assertOut(vfFour, '超限');
2524
+ if (readStateFile(dir).fixRoundsByChange?.ch !== 4) {
2525
+ throw new Error('verify 失败累计不得改写 Fix 轮次计数: ' + JSON.stringify(readStateFile(dir).fixRoundsByChange));
2526
+ }
2527
+ // 旧 change 第 4 轮渐进:WARN 后照常归位(不 BLOCK、不卡死)
2528
+ writeFixBatchFixture(dir, { kind: 'review', fixStatus: 'pending', newChange: false });
2529
+ const oldRoundState = readStateFile(dir);
2530
+ oldRoundState.fixRoundsByChange = { ch: 3 };
2531
+ writeState(dir, oldRoundState);
2532
+ const oldRound4 = runState(['next'], dir, env);
2533
+ assertExit(oldRound4, 0);
2534
+ assertOut(oldRound4, 'FIX-BATCH WARN');
2535
+ assertOut(oldRound4, '(第 4/3 轮)');
2536
+ assertNotOut(oldRound4, 'BLOCKED');
2537
+ const oldRoundAfter = readStateFile(dir);
2538
+ if (oldRoundAfter.currentNode !== 'execute' || oldRoundAfter.fixRoundsByChange?.ch !== 4) {
2539
+ throw new Error('旧 change 第 4 轮应渐进归位并计数: '
2540
+ + JSON.stringify({ currentNode: oldRoundAfter.currentNode, rounds: oldRoundAfter.fixRoundsByChange }));
2541
+ }
2542
+
2543
+ // ⑭ 签名算法版本可判别(真实命令链路):跨版本(v2 事件 vs 当前 v1)不做同版本比对——
2544
+ // 不得把正常回程误判为未闭合 Fix;同版本 legacy 裸 hex 按既有语义参与(②⑤ 已锚)。
2545
+ writeFixBatchFixture(dir, { kind: 'review', fixStatus: 'done' });
2546
+ writeFile(dir, '.specs/' + CHANGE_ID + '/T-FIX-01-SUMMARY.md', execSummaryFixture('T-FIX-01'));
2547
+ const versionSkewState = readStateFile(dir);
2548
+ versionSkewState.history = [{
2549
+ event: 'exit-applied', node: 'execute', change: CHANGE_ID, at: '2026-09-20T00:00:00.000Z',
2550
+ taskSetSignature: 'v2:' + '0'.repeat(64), signatureAlgo: 'v2',
2551
+ }];
2552
+ writeState(dir, versionSkewState);
2553
+ // 清掉本项先前 verify 子场景遗留的 TEST/UAT,使回程路由确定为 verify(夹具前提)
2554
+ fs.rmSync(path.join(dir, '.specs', CHANGE_ID, 'TEST.md'), { force: true });
2555
+ fs.rmSync(path.join(dir, '.specs', CHANGE_ID, 'UAT.md'), { force: true });
2556
+ assertExit(runState(['skill-load', 'review', 'flow-comet-review', '--prompt', 'flow-kit/prompts/6-review.md'], dir, env), 0);
2557
+ assertExit(runGuard(['entry', 'review'], dir, env), 0);
2558
+ const skewExit = runGuard(['exit', 'review', '--apply'], dir, env);
2559
+ assertExit(skewExit, 0);
2560
+ assertOut(skewExit, 'ALL CHECKS PASSED');
2561
+ assertNotOut(skewExit, 'BLOCKED: 存在未归位/未跑出口的 Fix 批次');
2562
+ assertNodeLine(skewExit, 'verify');
2563
+
2564
+ },
2565
+ },
1564
2566
  // ---------- B. 声明机制(skill-load / record / exit 校验) ----------
1565
2567
 
1566
2568
  {
@@ -1756,6 +2758,7 @@ const TEST_ITEMS = [
1756
2758
  name: 'C1 handoff:请求/结果/状态全链路(含提交校验)',
1757
2759
  run: (dir) => {
1758
2760
  gitInit(dir);
2761
+ writeFile(dir, '.gitignore', '.specs/\n');
1759
2762
  writeState(dir, baseState('execute'));
1760
2763
  writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md',
1761
2764
  '# TASK\n\n<task id="T01" status="done" parallel="true">\n <action>实现 T01</action>\n <write_files>src/t1.mjs</write_files>\n <verify>node --check src/t1.mjs</verify>\n</task>\n');
@@ -1862,6 +2865,11 @@ const TEST_ITEMS = [
1862
2865
  execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'chore: rogue zero'], { cwd: dir });
1863
2866
  const rogueHash = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim();
1864
2867
  assertExit(runHandoff(['request', 'T05b', 'T05b 委托', '--write-files', 'src/t2.mjs'], dir), 0);
2868
+ const stAbuseReq = readStateFile(dir);
2869
+ if (stAbuseReq.evidence['subagent-execute'].handoffRequests['T05b'].noCommit === true) {
2870
+ throw new Error('tracked write_files 的 request 不应记录 noCommit(无资格声称不得被资格判定放行)');
2871
+ }
2872
+ const abuseBytes = fs.readFileSync(path.join(dir, '.flow-comet', 'flow-comet-state.json'), 'utf8');
1865
2873
  const resAbuse = runHandoff(['result', 'T05b', JSON.stringify({
1866
2874
  status: 'DONE', taskId: 'T05b', noCommit: true, commitHash: rogueHash,
1867
2875
  changedFiles: ['src/rogue-zero.mjs'],
@@ -1872,6 +2880,9 @@ const TEST_ITEMS = [
1872
2880
  assertExit(resAbuse, 1);
1873
2881
  assertOut(resAbuse, '超出 writeFiles 范围');
1874
2882
  assertOut(resAbuse, '零提交');
2883
+ if (fs.readFileSync(path.join(dir, '.flow-comet', 'flow-comet-state.json'), 'utf8') !== abuseBytes) {
2884
+ throw new Error('零提交越权 BLOCK 不得改写 state 字节');
2885
+ }
1875
2886
  // ⑧ 段感知精确匹配:allowed=[src/foo] 不匹配提交 src/foobar.mjs(前缀匹配会放行,
1876
2887
  // 精确匹配判越界——修复前前缀匹配误放行,此处应 RED)
1877
2888
  writeFile(dir, 'src/foobar.mjs', 'export const x = 1;\n');
@@ -1922,6 +2933,367 @@ const TEST_ITEMS = [
1922
2933
  })], dir);
1923
2934
  assertExit(resGlob, 0);
1924
2935
  assertNotOut(resGlob, '超出 writeFiles 范围');
2936
+
2937
+ // ⑫ 零提交正例(真实 request/result 链路):临时 git 仓内 .specs/ 被 gitignore,
2938
+ // TASK 的 write_files 全为字面 .specs/... 路径 → request 记 noCommit:true + 审计行;
2939
+ // result 回传无 commitHash 的零提交契约 → 无 HANDOFF ERROR、exit 0、记录写入成功。
2940
+ const f6StatePath = path.join(dir, '.flow-comet', 'flow-comet-state.json');
2941
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md',
2942
+ '# TASK\n\n<task id="T12" status="pending"><action>账本同步</action>'
2943
+ + '<write_files>.specs/' + CHANGE_ID + '/T12-SUMMARY.md</write_files>'
2944
+ + '<verify>echo ok</verify></task>\n');
2945
+ const stIgnored = readStateFile(dir);
2946
+ stIgnored.newChange = true;
2947
+ writeState(dir, stIgnored);
2948
+ const reqIgnored = runHandoff(['request', 'T12'], dir, { FLOW_COMET_PROTOCOL: '' });
2949
+ assertExit(reqIgnored, 0);
2950
+ assertOut(reqIgnored, 'HANDOFF REQUEST: T12');
2951
+ // 协议不可读边界(真实链路):runHandoff 不默认注入协议(独立于 runGuard/runState),
2952
+ // 此处显式清空协议环境变量以固定「临时 runRoot 无可用协议」形态——归属门禁必须输出
2953
+ // 可见 WARN(原因 + 本次未执行归属校验)后放行,不得静默 skip,且零提交资格等既有
2954
+ // 请求行为不变。
2955
+ assertOut(reqIgnored, 'WARN:');
2956
+ assertOut(reqIgnored, '协议不可读');
2957
+ assertOut(reqIgnored, '本次未执行归属校验');
2958
+ assertOut(reqIgnored, 'HANDOFF 零提交资格: T12');
2959
+ const stIgnoredReq = readStateFile(dir);
2960
+ if (stIgnoredReq.evidence['subagent-execute'].handoffRequests['T12'].noCommit !== true) {
2961
+ throw new Error('字面 gitignored write_files 的 request 应记录 noCommit:true: '
2962
+ + JSON.stringify(stIgnoredReq.evidence['subagent-execute'].handoffRequests['T12']));
2963
+ }
2964
+ const ignoredBytes = fs.readFileSync(f6StatePath, 'utf8');
2965
+ const resIgnored = runHandoff(['result', 'T12', JSON.stringify({
2966
+ status: 'DONE', taskId: 'T12', noCommit: true,
2967
+ completedChecks: ['required-skill:subagent-execute.flow-comet-dev'],
2968
+ redEvidence: { command: 'echo ok' },
2969
+ greenEvidence: { command: 'echo ok', output: 'ok' },
2970
+ })], dir);
2971
+ assertExit(resIgnored, 0);
2972
+ assertOut(resIgnored, 'HANDOFF RESULT: T12');
2973
+ assertOut(resIgnored, 'HANDOFF 零提交: T12');
2974
+ assertNotOut(resIgnored, 'HANDOFF ERROR');
2975
+ assertNotOut(resIgnored, 'BLOCKED');
2976
+ const stIgnoredResult = readStateFile(dir);
2977
+ const ignoredRecord = stIgnoredResult.evidence['subagent-execute'].handoffResult['T12'];
2978
+ if (!ignoredRecord || ignoredRecord.result?.noCommit !== true || ignoredRecord.result.commitHash !== undefined) {
2979
+ throw new Error('零提交 result 应写入无 commitHash 的契约: ' + JSON.stringify(ignoredRecord));
2980
+ }
2981
+ if (fs.readFileSync(f6StatePath, 'utf8') === ignoredBytes) {
2982
+ throw new Error('零提交 result 应真实写入 state');
2983
+ }
2984
+
2985
+ // ⑬ 零提交负例:无资格形态(glob / .. 越界 / 非 git 仓 / tracked 文件)→ request 不记 noCommit
2986
+ const assertNoCommitNotRecorded = (root, taskId, label) => {
2987
+ const requestState = readStateFile(root);
2988
+ const requestRecord = requestState.evidence?.['subagent-execute']?.handoffRequests?.[taskId];
2989
+ if (!requestRecord || requestRecord.noCommit === true) {
2990
+ throw new Error(label + ' 的 request 不应记录 noCommit: ' + JSON.stringify(requestRecord));
2991
+ }
2992
+ };
2993
+ const reqGlob = runHandoff(['request', 'T13', '--write-files', '.specs/' + CHANGE_ID + '/*.md'], dir);
2994
+ assertExit(reqGlob, 0);
2995
+ assertNotOut(reqGlob, 'HANDOFF 零提交资格');
2996
+ assertNoCommitNotRecorded(dir, 'T13', 'glob write_files');
2997
+ const reqDotDot = runHandoff(['request', 'T14', '--write-files', '../evil.mjs'], dir);
2998
+ assertExit(reqDotDot, 0);
2999
+ assertNotOut(reqDotDot, 'HANDOFF 零提交资格');
3000
+ assertNoCommitNotRecorded(dir, 'T14', '.. 越界 write_files');
3001
+ writeFile(dir, 'src/tracked-zero.mjs', 'export const tracked = 1;\n');
3002
+ execFileSync('git', ['add', 'src/tracked-zero.mjs'], { cwd: dir });
3003
+ execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'chore: tracked zero'], { cwd: dir });
3004
+ const reqTracked = runHandoff(['request', 'T15', '--write-files', 'src/tracked-zero.mjs'], dir);
3005
+ assertExit(reqTracked, 0);
3006
+ assertNotOut(reqTracked, 'HANDOFF 零提交资格');
3007
+ assertNoCommitNotRecorded(dir, 'T15', 'tracked write_files');
3008
+ const nonGitRoot = makeTmp();
3009
+ try {
3010
+ writeState(nonGitRoot, {
3011
+ activeChange: CHANGE_ID,
3012
+ currentNode: 'review',
3013
+ completedNodes: [],
3014
+ evidence: {},
3015
+ verifyFailures: 0,
3016
+ executionMode: 'subagent',
3017
+ directOverride: false,
3018
+ newChange: true,
3019
+ });
3020
+ const reqNonGit = runHandoff(['request', 'T16', '--write-files', '.specs/' + CHANGE_ID + '/x.md'], nonGitRoot,
3021
+ { GIT_CEILING_DIRECTORIES: os.tmpdir() });
3022
+ assertExit(reqNonGit, 0);
3023
+ assertNotOut(reqNonGit, 'HANDOFF 零提交资格');
3024
+ assertNoCommitNotRecorded(nonGitRoot, 'T16', '非 git 仓 write_files');
3025
+ } finally {
3026
+ fs.rmSync(nonGitRoot, { recursive: true, force: true });
3027
+ }
3028
+
3029
+ // ⑭ 归属门禁事故回放与恢复(真实命令链路):stale currentNode=execute(并行任务未消化、
3030
+ // execute 已在完成集合内)→ request BLOCK(state 字节零改写、不落 handoffRequests,
3031
+ // 指引 next/entry)→ next 校正 state.currentNode → entry 正确节点 → request/result 成功。
3032
+ const ownershipEnv = { FLOW_COMET_PROTOCOL: path.join(dir, 'reference', 'workflow-protocol.json') };
3033
+ writeState(dir, {
3034
+ activeChange: CHANGE_ID,
3035
+ currentNode: 'execute',
3036
+ completedNodes: ['open', 'design', 'plan', 'execute', 'subagent-execute'],
3037
+ enteredNodes: ['open', 'design', 'plan', 'execute', 'subagent-execute'],
3038
+ evidence: { execute: { summary: 'previous pass executed' }, 'subagent-execute': { summary: 'previous wave collected' } },
3039
+ verifyFailures: 0,
3040
+ executionMode: 'subagent',
3041
+ directOverride: false,
3042
+ newChange: true,
3043
+ });
3044
+ writeIntakeArtifacts(dir);
3045
+ writeFile(dir, '.specs/' + CHANGE_ID + '/DESIGN.md',
3046
+ '# DESIGN\n\n- **Change ID**: ' + CHANGE_ID + '\n\n## 0. 技术栈选定\n\nNode.js(ESM)\n\n## 决策清单\n\n- [ ] 循环路由\n');
3047
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md',
3048
+ '# TASK\n\n<task id="P02" parallel="true" status="pending">\n <action>实现 P02</action>\n <write_files>src/p02.mjs</write_files>\n <verify>node --check src/p02.mjs</verify>\n</task>\n');
3049
+ writeFile(dir, 'src/p02.mjs', 'export const p02 = 2;\n');
3050
+ execFileSync('git', ['add', 'src/p02.mjs'], { cwd: dir });
3051
+ execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'feat: p02'], { cwd: dir });
3052
+ const p02Hash = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim();
3053
+ assertExit(runState(['skill-load', 'execute', 'flow-comet-dev', '--prompt', 'flow-kit/prompts/4-dev.md'], dir), 0);
3054
+ const ownershipStatePath = path.join(dir, '.flow-comet', 'flow-comet-state.json');
3055
+ const ownershipBytes = fs.readFileSync(ownershipStatePath, 'utf8');
3056
+ const wrongNode = runHandoff(['request', 'P02', 'P02 委托', '--write-files', 'src/p02.mjs'], dir, ownershipEnv);
3057
+ assertExit(wrongNode, 1);
3058
+ assertOut(wrongNode, 'BLOCKED');
3059
+ assertOut(wrongNode, '应归属节点 subagent-execute');
3060
+ assertOut(wrongNode, '原始 currentNode=execute');
3061
+ assertOut(wrongNode, 'workflow-state next');
3062
+ assertOut(wrongNode, 'entry subagent-execute');
3063
+ assertNotOut(wrongNode, 'HANDOFF REQUEST');
3064
+ if (fs.readFileSync(ownershipStatePath, 'utf8') !== ownershipBytes) {
3065
+ throw new Error('归属门禁 BLOCK 不得改写 state 字节(含 handoffRequests)');
3066
+ }
3067
+ if (readStateFile(dir).evidence?.['subagent-execute']?.handoffRequests?.P02) {
3068
+ throw new Error('归属门禁 BLOCK 不得落 handoffRequests');
3069
+ }
3070
+ const correction = runState(['next'], dir);
3071
+ assertExit(correction, 0);
3072
+ assertNodeLine(correction, 'subagent-execute');
3073
+ if (readStateFile(dir).currentNode !== 'subagent-execute') {
3074
+ throw new Error('next 未按路由校正 state.currentNode: ' + JSON.stringify(readStateFile(dir).currentNode));
3075
+ }
3076
+ assertExit(runState(['skill-load', 'subagent-execute', 'flow-comet-dev', '--prompt', 'flow-kit/prompts/4-dev.md'], dir), 0);
3077
+ assertExit(runGuard(['entry', 'subagent-execute'], dir), 0);
3078
+ const correctedRequest = runHandoff(['request', 'P02', 'P02 委托', '--write-files', 'src/p02.mjs'], dir, ownershipEnv);
3079
+ assertExit(correctedRequest, 0);
3080
+ assertOut(correctedRequest, 'HANDOFF REQUEST: P02');
3081
+ const correctedResult = runHandoff(['result', 'P02', JSON.stringify({
3082
+ status: 'DONE', taskId: 'P02', commitHash: p02Hash,
3083
+ changedFiles: ['src/p02.mjs'],
3084
+ completedChecks: ['required-skill:subagent-execute.flow-comet-dev'],
3085
+ redEvidence: { command: 'node --check src/p02.mjs' },
3086
+ greenEvidence: { command: 'node --check src/p02.mjs', output: 'ok' },
3087
+ })], dir);
3088
+ assertExit(correctedResult, 0);
3089
+ assertOut(correctedResult, 'HANDOFF RESULT: P02');
3090
+ assertNotOut(correctedResult, 'HANDOFF ERROR');
3091
+
3092
+ // ⑭b 依赖未满足的并行 pending 委派(真实命令链路):request BLOCK 且指引与 next 实际
3093
+ // 输出一致(next 输出 execute)→ 按输出进入 execute 消化串行依赖 → 依赖满足后
3094
+ // next 输出 subagent-execute → entry 后 request 成功(无 entry 死路)。
3095
+ const unmetTaskContent = (s04Status) =>
3096
+ '# TASK\n\n<task id="S04" parallel="false" status="' + s04Status + '"><action>实现 S04</action>'
3097
+ + '<write_files>src/s04.mjs</write_files><verify>node --check src/s04.mjs</verify></task>\n'
3098
+ + '<task id="P05" parallel="true" status="pending"><action>实现 P05</action>'
3099
+ + '<write_files>src/p05.mjs</write_files><verify>node --check src/p05.mjs</verify>'
3100
+ + '<depends_on>S04</depends_on></task>\n';
3101
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', unmetTaskContent('pending'));
3102
+ const unmetBytesBefore = fs.readFileSync(ownershipStatePath, 'utf8');
3103
+ const unmetRequest = runHandoff(['request', 'P05', 'P05 委托(依赖未满足)', '--write-files', 'src/p05.mjs'], dir, ownershipEnv);
3104
+ assertExit(unmetRequest, 1);
3105
+ assertOut(unmetRequest, 'BLOCKED');
3106
+ assertOut(unmetRequest, '当前不可委托');
3107
+ assertOut(unmetRequest, '依赖未满足');
3108
+ assertOut(unmetRequest, '未完成: S04');
3109
+ assertOut(unmetRequest, 'workflow-state next');
3110
+ assertOut(unmetRequest, '若输出 execute 表示依赖未满足');
3111
+ assertOut(unmetRequest, '待任务变为可委托');
3112
+ assertNotOut(unmetRequest, 'entry subagent-execute');
3113
+ assertNotOut(unmetRequest, 'HANDOFF REQUEST');
3114
+ if (fs.readFileSync(ownershipStatePath, 'utf8') !== unmetBytesBefore) {
3115
+ throw new Error('依赖未满足 BLOCK 不得改写 state 字节(含 handoffRequests)');
3116
+ }
3117
+ if (readStateFile(dir).evidence?.['subagent-execute']?.handoffRequests?.P05) {
3118
+ throw new Error('依赖未满足 BLOCK 不得落 handoffRequests');
3119
+ }
3120
+ // 按 next 实际输出进入 execute 消化串行依赖(指引条件分支与真实路由一致)
3121
+ const unmetNext = runState(['next'], dir);
3122
+ assertExit(unmetNext, 0);
3123
+ assertNodeLine(unmetNext, 'execute');
3124
+ if (readStateFile(dir).currentNode !== 'execute') {
3125
+ throw new Error('依赖未满足时 next 应把工作归属校正到 execute: ' + JSON.stringify(readStateFile(dir).currentNode));
3126
+ }
3127
+ // 串行依赖消化完成(execute 生命周期闭合:completedNodes/evidence 推进)
3128
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', unmetTaskContent('done'));
3129
+ const afterSerialState = readStateFile(dir);
3130
+ afterSerialState.completedNodes = [...new Set([...(afterSerialState.completedNodes || []), 'execute'])];
3131
+ afterSerialState.evidence = { ...(afterSerialState.evidence || {}), execute: { summary: 'serial dependency digested' } };
3132
+ writeState(dir, afterSerialState);
3133
+ const delegableNext = runState(['next'], dir);
3134
+ assertExit(delegableNext, 0);
3135
+ assertNodeLine(delegableNext, 'subagent-execute');
3136
+ if (readStateFile(dir).currentNode !== 'subagent-execute') {
3137
+ throw new Error('依赖满足后 next 应把工作归属推到 subagent-execute');
3138
+ }
3139
+ assertExit(runGuard(['entry', 'subagent-execute'], dir), 0);
3140
+ const recoveredRequest = runHandoff(['request', 'P05', 'P05 委托(依赖已满足)', '--write-files', 'src/p05.mjs'], dir, ownershipEnv);
3141
+ assertExit(recoveredRequest, 0);
3142
+ assertOut(recoveredRequest, 'HANDOFF REQUEST: P05');
3143
+
3144
+ // ⑮ result 重验零提交资格(真实命令链路):合法零提交 result 无 HANDOFF ERROR;
3145
+ // request 后修改 .gitignore(路径不再被忽略)→ 新 change BLOCK(request 证据 noCommit
3146
+ // 置 false、不落 result);修正 .gitignore 后重新 request/result 恢复通过。
3147
+ writeFile(dir, '.gitignore', '.specs/\n');
3148
+ const writeM13Task = (taskId, files) => writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md',
3149
+ '# TASK\n\n<task id="' + taskId + '" status="done">\n <action>交付 ' + taskId + '</action>\n'
3150
+ + ' <write_files>' + files + '</write_files>\n <verify>echo ok</verify>\n</task>\n');
3151
+ const zeroCommitContract = (taskId) => JSON.stringify({
3152
+ status: 'DONE', taskId: taskId, noCommit: true,
3153
+ completedChecks: ['required-skill:subagent-execute.flow-comet-dev'],
3154
+ redEvidence: { command: 'echo ok' },
3155
+ greenEvidence: { command: 'echo ok', output: 'ok' },
3156
+ });
3157
+ // F6 撤销审计断言(真实链路):noCommit=false + 非空、可被 Date 解析的 revokedAt +
3158
+ // 与失败类别对应的 revokeReason;三种真实失败形态分别断言类别(过期资格 / tracked / 逃逸)。
3159
+ const assertRevokeAudit = (record, expectedReason, label) => {
3160
+ if (!record || record.noCommit !== false) {
3161
+ throw new Error(label + ' 应撤销 noCommit=false: ' + JSON.stringify(record));
3162
+ }
3163
+ if (typeof record.revokedAt !== 'string' || record.revokedAt.trim() === '' || Number.isNaN(Date.parse(record.revokedAt))) {
3164
+ throw new Error(label + ' 应记录非空且可被 Date 解析的 revokedAt: ' + JSON.stringify(record));
3165
+ }
3166
+ if (record.revokeReason !== expectedReason) {
3167
+ throw new Error(label + ' 应记录 revokeReason=' + expectedReason + ': ' + JSON.stringify(record.revokeReason));
3168
+ }
3169
+ };
3170
+ writeM13Task('Z01', '.specs/' + CHANGE_ID + '/Z01-SUMMARY.md');
3171
+ const z01Request = runHandoff(['request', 'Z01'], dir, ownershipEnv);
3172
+ assertExit(z01Request, 0);
3173
+ assertOut(z01Request, 'HANDOFF 零提交资格: Z01');
3174
+ if (readStateFile(dir).evidence['subagent-execute'].handoffRequests.Z01.noCommit !== true) {
3175
+ throw new Error('request 应记录字面 gitignored 路径的零提交资格');
3176
+ }
3177
+ const z01Result = runHandoff(['result', 'Z01', zeroCommitContract('Z01')], dir);
3178
+ assertExit(z01Result, 0);
3179
+ assertOut(z01Result, 'HANDOFF RESULT: Z01');
3180
+ assertOut(z01Result, 'HANDOFF 零提交: Z01');
3181
+ assertNotOut(z01Result, 'HANDOFF ERROR');
3182
+ assertNotOut(z01Result, 'BLOCKED');
3183
+
3184
+ writeM13Task('Z02', '.specs/' + CHANGE_ID + '/Z02.md');
3185
+ const z02Request = runHandoff(['request', 'Z02'], dir, ownershipEnv);
3186
+ assertExit(z02Request, 0);
3187
+ assertOut(z02Request, 'HANDOFF 零提交资格: Z02');
3188
+ writeFile(dir, '.gitignore', 'node_modules/\n');
3189
+ const z02Blocked = runHandoff(['result', 'Z02', zeroCommitContract('Z02')], dir);
3190
+ assertExit(z02Blocked, 1);
3191
+ assertOut(z02Blocked, 'HANDOFF ERROR');
3192
+ assertOut(z02Blocked, '零提交资格 result 重验失败');
3193
+ assertNotOut(z02Blocked, 'HANDOFF RESULT');
3194
+ let m13State = readStateFile(dir);
3195
+ if (m13State.evidence['subagent-execute'].handoffRequests.Z02.noCommit !== false) {
3196
+ throw new Error('重验失败应把 request evidence 的 noCommit 置 false: '
3197
+ + JSON.stringify(m13State.evidence['subagent-execute'].handoffRequests.Z02));
3198
+ }
3199
+ assertRevokeAudit(m13State.evidence['subagent-execute'].handoffRequests.Z02,
3200
+ 'stale-eligibility', 'Z02 忽略规则变化重验');
3201
+ assertOut(z02Blocked, 'revokeReason=stale-eligibility');
3202
+ if (m13State.evidence['subagent-execute'].handoffResult?.Z02) {
3203
+ throw new Error('新 change 重验失败不得落 result');
3204
+ }
3205
+ writeFile(dir, '.gitignore', '.specs/\n');
3206
+ const z02Recover = runHandoff(['request', 'Z02'], dir, ownershipEnv);
3207
+ assertExit(z02Recover, 0);
3208
+ assertOut(z02Recover, 'HANDOFF 零提交资格: Z02');
3209
+ const z02RecoverResult = runHandoff(['result', 'Z02', zeroCommitContract('Z02')], dir);
3210
+ assertExit(z02RecoverResult, 0);
3211
+ assertNotOut(z02RecoverResult, 'HANDOFF ERROR');
3212
+
3213
+ // ⑯ request 后路径变为 tracked → result 重验失败 → 新 change BLOCK(资格撤销留痕)
3214
+ writeM13Task('Z03', '.specs/' + CHANGE_ID + '/Z03.md');
3215
+ writeFile(dir, '.specs/' + CHANGE_ID + '/Z03.md', 'tracked-after-request\n');
3216
+ const z03Request = runHandoff(['request', 'Z03'], dir, ownershipEnv);
3217
+ assertExit(z03Request, 0);
3218
+ assertOut(z03Request, 'HANDOFF 零提交资格: Z03');
3219
+ execFileSync('git', ['add', '-f', '.specs/' + CHANGE_ID + '/Z03.md'], { cwd: dir });
3220
+ execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'chore: z03 tracked'], { cwd: dir });
3221
+ const z03Blocked = runHandoff(['result', 'Z03', zeroCommitContract('Z03')], dir);
3222
+ assertExit(z03Blocked, 1);
3223
+ assertOut(z03Blocked, 'HANDOFF ERROR');
3224
+ assertOut(z03Blocked, '重验失败');
3225
+ if (readStateFile(dir).evidence['subagent-execute'].handoffRequests.Z03.noCommit !== false) {
3226
+ throw new Error('tracked 形态应撤销零提交资格');
3227
+ }
3228
+ const z03Revoked = readStateFile(dir).evidence['subagent-execute'].handoffRequests.Z03;
3229
+ assertRevokeAudit(z03Revoked, 'became-tracked', 'Z03 路径变 tracked 重验');
3230
+ assertOut(z03Blocked, 'revokeReason=became-tracked');
3231
+
3232
+ // ⑰ symlink/junction 逃逸:request 时路径尚未存在 → 记资格;result 前落 junction 指向 runRoot
3233
+ // 外 → 重验拒绝(fail-closed);request 时即存在 junction → 资格直接不成立(越权负例)。
3234
+ const escapeTarget = fs.mkdtempSync(path.join(os.tmpdir(), 'flow-comet-system-escape-'));
3235
+ const removeEscapeLink = (link) => {
3236
+ try { fs.unlinkSync(link); } catch { try { fs.rmdirSync(link); } catch { /* 已清理 */ } }
3237
+ };
3238
+ const z04Link = path.join(dir, '.specs', CHANGE_ID, 'z04-link');
3239
+ const z05Link = path.join(dir, '.specs', CHANGE_ID, 'z05-link');
3240
+ try {
3241
+ writeM13Task('Z04', '.specs/' + CHANGE_ID + '/z04-link');
3242
+ const z04Request = runHandoff(['request', 'Z04'], dir, ownershipEnv);
3243
+ assertExit(z04Request, 0);
3244
+ assertOut(z04Request, 'HANDOFF 零提交资格: Z04');
3245
+ fs.symlinkSync(escapeTarget, z04Link, process.platform === 'win32' ? 'junction' : 'dir');
3246
+ const z04Blocked = runHandoff(['result', 'Z04', zeroCommitContract('Z04')], dir);
3247
+ assertExit(z04Blocked, 1);
3248
+ assertOut(z04Blocked, 'HANDOFF ERROR');
3249
+ assertOut(z04Blocked, '重验失败');
3250
+ if (readStateFile(dir).evidence['subagent-execute'].handoffRequests.Z04.noCommit !== false) {
3251
+ throw new Error('symlink/junction 逃逸应撤销零提交资格');
3252
+ }
3253
+ assertRevokeAudit(readStateFile(dir).evidence['subagent-execute'].handoffRequests.Z04,
3254
+ 'symlink-junction-escape', 'Z04 symlink/junction 逃逸重验');
3255
+ assertOut(z04Blocked, 'revokeReason=symlink-junction-escape');
3256
+ writeM13Task('Z05', '.specs/' + CHANGE_ID + '/z05-link');
3257
+ fs.symlinkSync(escapeTarget, z05Link, process.platform === 'win32' ? 'junction' : 'dir');
3258
+ const z05Request = runHandoff(['request', 'Z05'], dir, ownershipEnv);
3259
+ assertExit(z05Request, 0);
3260
+ assertOut(z05Request, 'HANDOFF REQUEST: Z05');
3261
+ assertNotOut(z05Request, 'HANDOFF 零提交资格');
3262
+ if (readStateFile(dir).evidence['subagent-execute'].handoffRequests.Z05.noCommit === true) {
3263
+ throw new Error('request 时已存在的 symlink/junction 不得被判定零提交资格');
3264
+ }
3265
+ removeEscapeLink(z05Link);
3266
+ } finally {
3267
+ removeEscapeLink(z04Link);
3268
+ removeEscapeLink(z05Link);
3269
+ fs.rmSync(escapeTarget, { recursive: true, force: true });
3270
+ }
3271
+
3272
+ // ⑱ state 协议绑定(真实命令链路):init --protocol 自定义协议(无 execute /
3273
+ // subagent-execute 节点)→ state.protocolPath 持久化 → handoff request 按该协议
3274
+ // 判定(无对应 enabled 委托节点 → 跳过归属校验、不 BLOCK)。env 指向内置协议,
3275
+ // 协议来源未持久化时会误判串行 pending 归属 execute → BLOCK(修复前 RED)。
3276
+ const boundChange = 'bound-proto-real';
3277
+ const boundProtocol = JSON.parse(fs.readFileSync(path.join(dir, 'reference', 'workflow-protocol.json'), 'utf8'));
3278
+ boundProtocol.nodes = boundProtocol.nodes.filter((n) => n.id !== 'execute' && n.id !== 'subagent-execute');
3279
+ writeFile(dir, 'reference/protocol-bound.json', JSON.stringify(boundProtocol, null, 2) + '\n');
3280
+ assertExit(runState(['init', boundChange, '--init-skip', '--protocol', 'reference/protocol-bound.json'], dir), 0);
3281
+ writeFile(dir, '.specs/' + boundChange + '/TASK.md',
3282
+ '# TASK\n\n<task id="R01" parallel="false" status="pending"><action>实现 R01</action>'
3283
+ + '<write_files>src/r01.mjs</write_files><verify>node --check src/r01.mjs</verify></task>\n');
3284
+ const boundRequest = runHandoff(['request', 'R01', 'bound protocol serial'], dir, ownershipEnv);
3285
+ assertExit(boundRequest, 0);
3286
+ assertOut(boundRequest, 'HANDOFF REQUEST: R01');
3287
+ assertNotOut(boundRequest, 'BLOCKED');
3288
+ assertNotOut(boundRequest, '本次未执行归属校验');
3289
+ const boundState = readStateFile(dir);
3290
+ if (boundState.protocolPath !== 'reference/protocol-bound.json') {
3291
+ throw new Error('init --protocol 应把解析后的协议路径持久化为项目根相对形态,实际: '
3292
+ + JSON.stringify(boundState.protocolPath));
3293
+ }
3294
+ if (!boundState.evidence?.['subagent-execute']?.handoffRequests?.R01) {
3295
+ throw new Error('state 绑定协议下的 request 应照常落库');
3296
+ }
1925
3297
  },
1926
3298
  },
1927
3299
 
@@ -2464,6 +3836,298 @@ const TEST_ITEMS = [
2464
3836
  },
2465
3837
  },
2466
3838
 
3839
+ // ---------- H5~H8: archive 源受控重入真实命令链路 ----------
3840
+
3841
+ {
3842
+ name: 'H5 受控重入:未授权调用 fail-closed 且 state 字节零改写',
3843
+ run: (dir) => {
3844
+ seedArchiveEntryState(dir);
3845
+ const before = readStateBytes(dir);
3846
+ // ② 未授权(缺 --authorized-by)→ 非零退出 + 授权形态指引 + 零改写
3847
+ const noAuth = runState(['reenter', 'verify', '--reason', '归档后发现缺陷'], dir);
3848
+ assertExit(noAuth, 1);
3849
+ assertOut(noAuth, 'reenter');
3850
+ assertOut(noAuth, 'authorized-by');
3851
+ if (!readStateBytes(dir).equals(before)) throw new Error('未授权调用改写了 state 字节');
3852
+ if (reentryBackupFiles(dir).length !== 0) {
3853
+ throw new Error('未授权调用产生了备份: ' + JSON.stringify(reentryBackupFiles(dir)));
3854
+ }
3855
+ // ② 授权源为纯空白 → 同样 fail-closed 且零改写
3856
+ const blankAuth = runState(['reenter', 'verify', '--authorized-by', ' ', '--reason', 'x'], dir);
3857
+ assertExit(blankAuth, 1);
3858
+ if (!readStateBytes(dir).equals(before)) throw new Error('空白授权源调用改写了 state 字节');
3859
+ const st = readStateFile(dir);
3860
+ if (st.currentNode !== 'archive') throw new Error('未授权调用改写了 currentNode: ' + JSON.stringify(st.currentNode));
3861
+ if (reentryEventsOf(st).length !== 0) throw new Error('未授权调用写入了 reentry-applied 事件');
3862
+ },
3863
+ },
3864
+
3865
+ {
3866
+ name: 'H6 受控重入:完整授权链路(转移+嵌套证据+审计事件+备份指纹+审计行)',
3867
+ run: (dir) => {
3868
+ seedArchiveEntryState(dir);
3869
+ const beforeState = readStateFile(dir);
3870
+ const res = runState(['reenter', 'verify', '--authorized-by', '用户裁决', '--reason', '归档后发现验证缺口'], dir);
3871
+ assertExit(res, 0);
3872
+ const st = readStateFile(dir);
3873
+ // ③ 转移语义:currentNode = 目标、completedNodes = 前驱交集、status = running
3874
+ if (st.currentNode !== 'verify') throw new Error('重入后 currentNode 应为 verify: ' + JSON.stringify(st.currentNode));
3875
+ if (JSON.stringify(st.completedNodes) !== JSON.stringify(REENTRY_VERIFY_PREDECESSORS)) {
3876
+ throw new Error('重入后 completedNodes 应为 verify 前驱交集 ' + JSON.stringify(REENTRY_VERIFY_PREDECESSORS)
3877
+ + ',实际 ' + JSON.stringify(st.completedNodes));
3878
+ }
3879
+ if (st.status !== 'running') throw new Error('重入后 status 应为 running: ' + JSON.stringify(st.status));
3880
+ // ③ 授权嵌套记录(evidence.<目标节点>.reentryAuthorization)
3881
+ const auth = st.evidence && st.evidence.verify ? st.evidence.verify.reentryAuthorization : null;
3882
+ if (!auth || typeof auth !== 'object') {
3883
+ throw new Error('缺 evidence.verify.reentryAuthorization: ' + JSON.stringify(st.evidence));
3884
+ }
3885
+ if (auth.round !== 1 || auth.target !== 'verify' || auth.source !== '用户裁决') {
3886
+ throw new Error('授权记录形态不符: ' + JSON.stringify(auth));
3887
+ }
3888
+ if (typeof auth.at !== 'string' || auth.at.trim() === '') throw new Error('授权记录缺 at: ' + JSON.stringify(auth));
3889
+ // ③ 审计事件——change 必填(轮次按 change 隔离)
3890
+ const events = reentryEventsOf(st);
3891
+ if (events.length !== 1) throw new Error('应恰一条 reentry-applied 事件: ' + JSON.stringify(events));
3892
+ const ev = events[0];
3893
+ if (ev.from !== 'archive' || ev.to !== 'verify' || ev.round !== 1 || ev.change !== CHANGE_ID) {
3894
+ throw new Error('reentry-applied 事件字段不符: ' + JSON.stringify(ev));
3895
+ }
3896
+ if (!ev.authorization || ev.authorization.source !== '用户裁决' || ev.authorization.round !== 1) {
3897
+ throw new Error('事件 authorization 不符: ' + JSON.stringify(ev.authorization));
3898
+ }
3899
+ if (typeof ev.at !== 'string' || ev.at.trim() === '') throw new Error('事件缺 at: ' + JSON.stringify(ev));
3900
+ // ③ 备份在场 + 指纹与文件 sha256 一致 + 全量快照语义(AC-9)
3901
+ const backupPath = resolveReentryBackupPath(dir, CHANGE_ID, ev);
3902
+ if (!backupPath) throw new Error('事件 backup 指向的备份文件不在场: ' + JSON.stringify(ev.backup));
3903
+ if (!/-pre-verify\.json$/.test(backupPath)) {
3904
+ throw new Error('备份命名应为 <UTC ISO>-pre-<target>.json: ' + backupPath);
3905
+ }
3906
+ const backupBytes = fs.readFileSync(backupPath);
3907
+ const backupState = JSON.parse(backupBytes.toString('utf8'));
3908
+ if (backupState.currentNode !== beforeState.currentNode || backupState.status !== beforeState.status
3909
+ || JSON.stringify(backupState.completedNodes) !== JSON.stringify(beforeState.completedNodes)) {
3910
+ throw new Error('备份应为重入前 state 全量快照: ' + JSON.stringify(backupState));
3911
+ }
3912
+ if (reentryEventsOf(backupState).length !== 0) throw new Error('备份不应含本次重入事件');
3913
+ const fingerprint = createHash('sha256').update(backupBytes).digest('hex');
3914
+ const recorded = String(ev.fingerprint || '').toLowerCase().replace(/^sha256:/, '');
3915
+ if (recorded !== fingerprint) {
3916
+ throw new Error('事件指纹与备份文件 sha256 不一致: ' + JSON.stringify(ev.fingerprint) + ' vs ' + fingerprint);
3917
+ }
3918
+ // ④ 审计行:REENTRY 前缀 + 来源 archive + 目标 + 轮次 n/3 + 备份路径
3919
+ assertOut(res, 'REENTRY');
3920
+ assertOut(res, 'archive');
3921
+ assertOut(res, 'verify');
3922
+ assertOut(res, '1/3');
3923
+ assertOut(res, path.basename(backupPath));
3924
+ const backups = reentryBackupFiles(dir);
3925
+ if (backups.length !== 1) throw new Error('成功重入应恰一份备份: ' + JSON.stringify(backups));
3926
+ },
3927
+ },
3928
+
3929
+ {
3930
+ name: 'H7 受控重入:幂等重放零改写与按备份手工回滚可执行',
3931
+ run: (dir) => {
3932
+ seedArchiveEntryState(dir);
3933
+ const first = runState(['reenter', 'verify', '--authorized-by', '用户裁决', '--reason', '首次重入'], dir);
3934
+ assertExit(first, 0);
3935
+ const afterFirst = readStateBytes(dir);
3936
+ const ev = reentryEventsOf(readStateFile(dir))[0];
3937
+ const backupPath = resolveReentryBackupPath(dir, CHANGE_ID, ev);
3938
+ if (!backupPath) throw new Error('首次重入后缺备份文件: ' + JSON.stringify(ev));
3939
+ // ⑤ 幂等重放:同目标再调用 → 空操作(state 字节零改写、不新增备份/事件)
3940
+ const replay = runState(['reenter', 'verify', '--authorized-by', '用户裁决', '--reason', '重复调用'], dir);
3941
+ assertExit(replay, 0);
3942
+ if (!readStateBytes(dir).equals(afterFirst)) throw new Error('幂等重放改写了 state 字节');
3943
+ if (reentryEventsOf(readStateFile(dir)).length !== 1) throw new Error('幂等重放重复写入 reentry-applied 事件');
3944
+ if (reentryBackupFiles(dir).length !== 1) {
3945
+ throw new Error('幂等重放新增了备份: ' + JSON.stringify(reentryBackupFiles(dir)));
3946
+ }
3947
+ // ⑦ 手工回滚(AC-9):按备份文件覆盖 → status 可读且语义回到重入前
3948
+ const backupBytes = fs.readFileSync(backupPath);
3949
+ fs.writeFileSync(path.join(dir, '.flow-comet', 'flow-comet-state.json'), backupBytes);
3950
+ const status = runState(['status'], dir);
3951
+ assertExit(status, 0);
3952
+ assertOut(status, '"stateCurrentNode": "archive"');
3953
+ assertOut(status, '"change": "' + CHANGE_ID + '"');
3954
+ const restored = readStateFile(dir);
3955
+ if (restored.currentNode !== 'archive') throw new Error('回滚后 currentNode 未回到 archive: ' + JSON.stringify(restored.currentNode));
3956
+ if (JSON.stringify(restored.completedNodes) !== JSON.stringify(ARCHIVE_ENTRY_COMPLETED_NODES)) {
3957
+ throw new Error('回滚后 completedNodes 未回到重入前形态: ' + JSON.stringify(restored.completedNodes));
3958
+ }
3959
+ if (reentryEventsOf(restored).length !== 0) throw new Error('回滚后不应残留本次 reentry-applied 事件');
3960
+ },
3961
+ },
3962
+
3963
+ {
3964
+ name: 'H8 受控重入:上限 BLOCK、显式授权续轮与重入后闭环组合链路(真实命令)',
3965
+ run: (dir) => {
3966
+ const env = { FLOW_COMET_PROTOCOL: path.join(dir, 'reference', 'workflow-protocol.json') };
3967
+ const gateMarker = path.join(dir, 'verify-gate-ran.txt');
3968
+ seedArchiveEntryState(dir);
3969
+ // 真实链路跑满 3 轮:每轮成功后把归属重置回 archive 已 entry 形态(模拟流程再次归档进入),
3970
+ // history 事件保留——轮次按 change 从事件派生
3971
+ for (let round = 1; round <= 3; round += 1) {
3972
+ const res = runState(['reenter', 'verify', '--authorized-by', '用户裁决', '--reason', '第 ' + round + ' 轮'], dir);
3973
+ assertExit(res, 0);
3974
+ if (reentryEventsOf(readStateFile(dir)).length !== round) {
3975
+ throw new Error('第 ' + round + ' 轮后 reentry-applied 事件数应为 ' + round);
3976
+ }
3977
+ const st = readStateFile(dir);
3978
+ st.currentNode = 'archive';
3979
+ st.completedNodes = ARCHIVE_ENTRY_COMPLETED_NODES.slice();
3980
+ st.status = 'running';
3981
+ writeState(dir, st);
3982
+ }
3983
+ if (reentryBackupFiles(dir).length !== 3) {
3984
+ throw new Error('三轮应产生三份备份: ' + JSON.stringify(reentryBackupFiles(dir)));
3985
+ }
3986
+ const beforeFourth = readStateBytes(dir);
3987
+ // ⑥ 第 4 次 → BLOCK + 人工裁决指引(继续 / 停止)+ state 字节零改写
3988
+ const fourth = runState(['reenter', 'execute', '--authorized-by', '用户裁决', '--reason', '第 4 轮'], dir);
3989
+ assertExit(fourth, 1);
3990
+ assertOut(fourth, 'BLOCK');
3991
+ assertOut(fourth, '继续');
3992
+ assertOut(fourth, '停止');
3993
+ if (!readStateBytes(dir).equals(beforeFourth)) throw new Error('超上限调用改写了 state 字节');
3994
+ if (reentryEventsOf(readStateFile(dir)).length !== 3) throw new Error('超上限调用写入了 reentry-applied 事件');
3995
+ if (reentryBackupFiles(dir).length !== 3) {
3996
+ throw new Error('超上限调用新增了备份: ' + JSON.stringify(reentryBackupFiles(dir)));
3997
+ }
3998
+ // ⑦ 上限判定先于空操作短路:同目标形态 + 3 条本 change 事件 → 仍 BLOCK 零改写
3999
+ {
4000
+ const capped = readStateFile(dir);
4001
+ capped.currentNode = 'verify';
4002
+ capped.completedNodes = REENTRY_VERIFY_PREDECESSORS.slice();
4003
+ writeState(dir, capped);
4004
+ const cappedBytes = readStateBytes(dir);
4005
+ const sameTarget = runState(['reenter', 'verify', '--authorized-by', '用户裁决', '--reason', '超限同目标重放'], dir);
4006
+ assertExit(sameTarget, 1);
4007
+ assertOut(sameTarget, 'BLOCK');
4008
+ assertOut(sameTarget, '继续');
4009
+ assertNotOut(sameTarget, '空操作');
4010
+ if (!readStateBytes(dir).equals(cappedBytes)) throw new Error('超限同目标形态改写了 state 字节');
4011
+ if (reentryEventsOf(readStateFile(dir)).length !== 3) throw new Error('超限同目标形态写入了 reentry-applied 事件');
4012
+ const reset = readStateFile(dir);
4013
+ reset.currentNode = 'archive';
4014
+ reset.completedNodes = ARCHIVE_ENTRY_COMPLETED_NODES.slice();
4015
+ reset.status = 'running';
4016
+ writeState(dir, reset);
4017
+ }
4018
+ // ⑧ 续轮授权不足(授权轮次 < 已用 + 1)→ BLOCK 零改写:上限裁决点不可被残缺授权绕过
4019
+ {
4020
+ const insufficientBytes = readStateBytes(dir);
4021
+ const insufficient = runState(['reenter', 'verify', '--authorized-by', '用户授权', '--reason', '轮次不足', '--continue-round', '3'], dir);
4022
+ assertExit(insufficient, 1);
4023
+ assertOut(insufficient, 'BLOCK');
4024
+ if (!readStateBytes(dir).equals(insufficientBytes)) throw new Error('续轮授权轮次不足改写了 state 字节');
4025
+ }
4026
+ // ⑨ 上限后的显式授权续轮(AC-7 后半句)→ 放行并计第 4 轮:审计事件 / 嵌套授权留痕带续轮
4027
+ // 标记与原因,备份链新增一份
4028
+ const continued = runState(['reenter', 'verify', '--authorized-by', '用户授权续轮', '--reason', '第 4 轮显式授权续轮', '--continue-round', '4'], dir);
4029
+ assertExit(continued, 0);
4030
+ assertOut(continued, 'REENTRY');
4031
+ assertOut(continued, '续轮');
4032
+ assertOut(continued, '4');
4033
+ const continuedState = readStateFile(dir);
4034
+ if (continuedState.currentNode !== 'verify') {
4035
+ throw new Error('续轮放行后 currentNode 应为 verify: ' + JSON.stringify(continuedState.currentNode));
4036
+ }
4037
+ const continuedEvents = reentryEventsOf(continuedState);
4038
+ const continuedEvent = continuedEvents[continuedEvents.length - 1];
4039
+ if (!continuedEvent || continuedEvent.round !== 4 || continuedEvent.change !== CHANGE_ID
4040
+ || continuedEvent.continuationAuthorized !== true
4041
+ || continuedEvent.reason !== '第 4 轮显式授权续轮') {
4042
+ throw new Error('续轮审计事件字段不符(round=4 / change / 续轮标记 / reason): ' + JSON.stringify(continuedEvent));
4043
+ }
4044
+ if (continuedState.evidence?.verify?.reentryAuthorization?.continuationAuthorized !== true) {
4045
+ throw new Error('续轮授权留痕缺失: ' + JSON.stringify(continuedState.evidence?.verify));
4046
+ }
4047
+ if (reentryBackupFiles(dir).length !== 4) {
4048
+ throw new Error('续轮放行应新增一份备份(共 4 份): ' + JSON.stringify(reentryBackupFiles(dir)));
4049
+ }
4050
+ // ⑩ 组合真实链路(AC-8):续轮后的 verify 驻留态 → 追加 pending 修复任务 → 受控归位
4051
+ // execute → 执行家族四类出口真实执行 → 回源 verify 出口真实执行(验证命令副作用)→ archive
4052
+ writeIntakeArtifacts(dir);
4053
+ writeFile(dir, '.specs/' + CHANGE_ID + '/DESIGN.md',
4054
+ '# DESIGN\n\n- **Change ID**: ' + CHANGE_ID + '\n\n## 0. 技术栈选定\n\nNode.js(ESM)\n\n## 决策清单\n\n- [ ] 循环路由\n');
4055
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', fixBatchTaskText('pending'));
4056
+ writeFile(dir, '.specs/' + CHANGE_ID + '/T01-SUMMARY.md', execSummaryFixture('T01'));
4057
+ // 源节点前序产物齐备:REVIEW.md 在场(已处置)——否则回源 verify 出口后的产物推导会把
4058
+ // 下一跳判回 review(产物即真相),组合链路的终点断言无法到达 archive。
4059
+ writeFile(dir, '.specs/' + CHANGE_ID + '/REVIEW.md', fixBatchReviewDoc(true));
4060
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TEST.md',
4061
+ '# TEST\n\n## 验证命令\n\n```\nnode -e "require(\'fs\').writeFileSync(\'verify-gate-ran.txt\', \'GATE-RAN\')"\n```\n');
4062
+ writeFile(dir, '.specs/' + CHANGE_ID + '/UAT.md', '# UAT\n\n## 验收\n\n- 通过\n');
4063
+ // 受控归位:next 检出 pending 修复任务 → FIX-BATCH 归位 execute(真实写盘)
4064
+ const reposition = runState(['next'], dir, env);
4065
+ assertExit(reposition, 0);
4066
+ assertOut(reposition, 'FIX-BATCH: 归位 execute(源节点 verify)');
4067
+ assertNodeLine(reposition, 'execute');
4068
+ let chainState = readStateFile(dir);
4069
+ if (chainState.currentNode !== 'execute') {
4070
+ throw new Error('受控归位后 currentNode 应为 execute: ' + JSON.stringify(chainState.currentNode));
4071
+ }
4072
+ if (chainState.completedNodes.includes('verify')) {
4073
+ throw new Error('受控归位不得把源节点标完成: ' + JSON.stringify(chainState.completedNodes));
4074
+ }
4075
+ // 完成修复任务(标 done + 逐任务 SUMMARY + 重载声明 + record execute)
4076
+ completeFixTaskAndRecord(dir, env);
4077
+ // execute 家族四类出口真实跑通:全任务 done / 逐任务 SUMMARY / 六段自查与自检方法 / 任务集签名
4078
+ const execExit = runGuard(['exit', 'execute', '--apply'], dir, env);
4079
+ assertExit(execExit, 0);
4080
+ assertOut(execExit, 'ALL CHECKS PASSED');
4081
+ assertOut(execExit, 'FIX-BATCH: 回源节点 verify(execute 出口已完成)');
4082
+ assertNodeLine(execExit, 'verify');
4083
+ assertNotNodeLine(execExit, 'archive');
4084
+ chainState = readStateFile(dir);
4085
+ if (chainState.currentNode !== 'verify' || chainState.completedNodes.includes('verify')) {
4086
+ throw new Error('回源后应停在未完成的 verify: ' + JSON.stringify({ node: chainState.currentNode, completed: chainState.completedNodes }));
4087
+ }
4088
+ if (!fs.existsSync(path.join(dir, '.specs', CHANGE_ID, 'T01-SUMMARY.md'))
4089
+ || !fs.existsSync(path.join(dir, '.specs', CHANGE_ID, 'T-FIX-01-SUMMARY.md'))) {
4090
+ throw new Error('逐任务 SUMMARY 必须在场(execute 家族出口之一)');
4091
+ }
4092
+ for (const summaryName of ['T01-SUMMARY.md', 'T-FIX-01-SUMMARY.md']) {
4093
+ const summaryText = fs.readFileSync(path.join(dir, '.specs', CHANGE_ID, summaryName), 'utf8');
4094
+ if (!/##\s*6 维自查/.test(summaryText) || !/##\s*自检方法/.test(summaryText)) {
4095
+ throw new Error(summaryName + ' 缺六维自查 / 自检方法段(execute 家族出口之一)');
4096
+ }
4097
+ }
4098
+ const execEvent = (chainState.history || [])
4099
+ .filter((e) => e.event === 'exit-applied' && e.node === 'execute')
4100
+ .pop();
4101
+ if (!execEvent || !/^v1:[0-9a-f]{64}$/.test(String(execEvent.taskSetSignature || ''))) {
4102
+ throw new Error('execute 家族出口必须记录任务集签名(出口之一): ' + JSON.stringify(execEvent));
4103
+ }
4104
+ if (!chainState.evidence?.execute?.summary) {
4105
+ throw new Error('execute 出口证据缺失: ' + JSON.stringify(chainState.evidence?.execute));
4106
+ }
4107
+ // 源节点(verify)出口真实重跑:验证命令落盘副作用 + 推进 archive
4108
+ assertExit(runState(['skill-load', 'verify', 'flow-comet-verify', '--prompt', 'flow-kit/prompts/7-integration.md'], dir, env), 0);
4109
+ assertExit(runState(['record', 'verify', '{"summary":"回源复验完成"}'], dir, env), 0);
4110
+ assertExit(runGuard(['entry', 'verify'], dir, env), 0);
4111
+ const verifyExit = runGuard(['exit', 'verify', '--apply'], dir, env);
4112
+ assertExit(verifyExit, 0);
4113
+ assertOut(verifyExit, 'ALL CHECKS PASSED');
4114
+ assertNodeLine(verifyExit, 'archive');
4115
+ if (!fs.existsSync(gateMarker) || fs.readFileSync(gateMarker, 'utf8') !== 'GATE-RAN') {
4116
+ throw new Error('回源 verify 出口未真实执行 TEST.md 验证命令(副作用文件缺失/内容不符)');
4117
+ }
4118
+ const finalState = readStateFile(dir);
4119
+ if (finalState.currentNode !== 'archive' || !finalState.completedNodes.includes('verify')) {
4120
+ throw new Error('组合链路终点应为 archive 且 verify 已完成: ' + JSON.stringify({ node: finalState.currentNode, completed: finalState.completedNodes }));
4121
+ }
4122
+ if (reentryEventsOf(finalState).length !== 4) {
4123
+ throw new Error('组合链路不得丢失重入审计事件(应为 4 条): ' + reentryEventsOf(finalState).length);
4124
+ }
4125
+ if (reentryBackupFiles(dir).length !== 4) {
4126
+ throw new Error('组合链路不得新增 / 丢失备份(应为 4 份): ' + JSON.stringify(reentryBackupFiles(dir)));
4127
+ }
4128
+ },
4129
+ },
4130
+
2467
4131
  // ---------- I. 异常路径 ----------
2468
4132
 
2469
4133
  {
@@ -2606,7 +4270,33 @@ const TEST_ITEMS = [
2606
4270
  // 格式:发布版本号(1.3.1) / prerelease(1.5.0-rc.1 或 1.5.0-beta-1) / git describe 开发态(1.3.1-N-g<hash>) / unreleased(无 tag 兜底)
2607
4271
  const ok = /^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(-\d+-g[0-9a-f]+)?$/.test(installed) || installed === 'unreleased';
2608
4272
  if (!ok) throw new Error('版本标识格式异常: ' + installed);
4273
+ // 信任边界:安装器目录**不是仓库根**时(包被装在别人的仓库里——本地安装进项目即是此形态),
4274
+ // 不得采信 git describe:它会向上找到宿主仓库,把**宿主 tag** 当成流工具版本。
4275
+ // 该解析值是单一来源——`--version` 输出它,`init` 写进目标项目的版本标识也是它,
4276
+ // 故此处断言它即覆盖两条路径。修复前实测:输出宿主 tag(9.9.9),且 init 把它写进项目。
4277
+ const host = path.join(dir, 'trust-host');
4278
+ const pkg = path.join(host, 'node_modules', 'flow-comet');
4279
+ fs.mkdirSync(path.join(pkg, 'scripts'), { recursive: true });
4280
+ fs.mkdirSync(path.join(pkg, '.flow-comet', 'skills', 'flow-comet'), { recursive: true });
4281
+ fs.copyFileSync(installer, path.join(pkg, 'scripts', 'prepare-env.mjs'));
4282
+ fs.copyFileSync(srcVersionFile, path.join(pkg, '.flow-comet', 'skills', 'flow-comet', 'INSTALLED_VERSION'));
4283
+ execFileSync('git', ['init', '-q'], { cwd: host, stdio: 'ignore' });
4284
+ execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '--allow-empty', '-m', 'init'], { cwd: host, stdio: 'ignore' });
4285
+ execFileSync('git', ['tag', 'v9.9.9'], { cwd: host, stdio: 'ignore' });
4286
+ const nested = spawnSync(process.execPath, [path.join(pkg, 'scripts', 'prepare-env.mjs'), '--version'], { cwd: host, encoding: 'utf8', timeout: 60000 });
4287
+ const printed = String(nested.stdout || '').trim();
4288
+ if (nested.status !== 0) throw new Error('包内直跑 --version 应退 0,实际 ' + nested.status + '\n' + nested.stderr);
4289
+ if (printed === '9.9.9' || printed.startsWith('9.9.9')) {
4290
+ throw new Error('版本解析越过了信任边界:安装器目录不是仓库根,却采信了宿主仓库的 tag(输出 ' + printed + ')');
4291
+ }
4292
+ if (printed !== srcVersion) {
4293
+ throw new Error('越界情形应回退随包分发的权威源标识 ' + srcVersion + ',实际 ' + printed);
4294
+ }
4295
+ if (/fatal:/.test(String(nested.stderr || ''))) {
4296
+ throw new Error('版本解析不应把 git 的 fatal 输出漏给用户:\n' + nested.stderr);
4297
+ }
2609
4298
  console.log(' 版本标识 = ' + installed + '(git describe 或权威源兜底——多人协作精确检测)✓');
4299
+ console.log(' 信任边界: 包装在他人仓库内 → 取随包标识 ' + srcVersion + '(不采信宿主 tag)✓');
2610
4300
  },
2611
4301
  },
2612
4302
 
@@ -2655,6 +4345,14 @@ const TEST_ITEMS = [
2655
4345
  const agents = fs.readFileSync(agentsFile, 'utf8');
2656
4346
  if (!agents.includes('Managed by flow-comet')) throw new Error('AGENTS.md 无托管标记');
2657
4347
  if (!agents.includes('flow-comet Orchestration')) throw new Error('AGENTS.md 未内联 orchestration 内容');
4348
+ // ④b 分发词面锁:orchestration 是**每个项目自动加载**的文本(CC 走 .claude/rules/、Codex/dsh 走
4349
+ // AGENTS.md 托管区,三者同源),其用词必须与工具当下的自称一致——不得残留 Comet 时代词汇
4350
+ // (本仓早已移除 bundles/ 双目录、权威源路径也从 bundle-drafts/ 迁走),也不得把**只有两行的
4351
+ // 兼容别名壳**列进脚本清单(它不是任何流程的入口,列出来只会让读者去找错文件)。
4352
+ for (const banned of ['Bundle', 'control plane']) {
4353
+ if (agents.includes(banned)) throw new Error('内联的 orchestration 含 Comet 时代词汇(' + banned + ')——分发文本须与工具当下的自称一致');
4354
+ }
4355
+ if (agents.includes('comet-plan.mjs')) throw new Error('内联的 orchestration 仍列兼容别名壳 comet-plan.mjs(它不是流程入口)');
2658
4356
  // ⑤ 纯 codex 平台不生成 .claude/
2659
4357
  if (fs.existsSync(path.join(target, '.claude'))) throw new Error('codex 平台不应生成 .claude/');
2660
4358
  // ⑥ 版本标识随技能包分发(平台化路径)
@@ -3664,9 +5362,19 @@ const TEST_ITEMS = [
3664
5362
  // 覆盖后磁盘为源新戳、同源重装收敛、purge 清除重建后路径回归。
3665
5363
  {
3666
5364
  name: 'K14 桥接 loader:版本戳重装断言(升级/降级方向与覆盖后新戳)',
5365
+ distributionSurface: true,
3667
5366
  run: (dir) => {
3668
5367
  const repoRoot = path.resolve(__dirname, '..', '..', '..', '..');
3669
- if (!fs.existsSync(path.join(repoRoot, '.flow-comet', 'skills', 'flow-comet'))) return; // 安装副本无权威源
5368
+ const pkgCtx = resolvePackageContext();
5369
+ // 分发面回传契约夹具先跑(环境无关):在副本 early-return 之前由夹具驱动断言——
5370
+ // copy 文案/marker 与三类失败路径负例在权威源与安装副本两侧都真跑,不依赖「装到副本才验证」。
5371
+ assertDistributionOutcomeContract(dir);
5372
+ const marker = DISTRIBUTION_MARKERS[pkgCtx.kind];
5373
+ if (pkgCtx.kind === 'copy') {
5374
+ const outcome = copyDistributionOutcome(pkgCtx, K14_COPY_DETAIL);
5375
+ console.log(outcome.message);
5376
+ return outcome.marker;
5377
+ }
3670
5378
  const installer = path.join(repoRoot, 'scripts', 'prepare-env.mjs');
3671
5379
  const loader = path.join(repoRoot, 'scripts', 'dsh-bridge.mjs');
3672
5380
  if (!fs.existsSync(loader)) throw new Error('缺少 scripts/dsh-bridge.mjs');
@@ -3717,7 +5425,12 @@ const TEST_ITEMS = [
3717
5425
  if (!fs.readFileSync(pluginPath, 'utf8').includes('// BRIDGE_VERSION: ' + srcVersion)) {
3718
5426
  throw new Error('降级重装后已装 loader 应为源戳');
3719
5427
  }
5428
+ // ③④ 安装副本载体版本比较语义(dev 态同基础健康 / 基础失配仍 FAIL)——助手单点实现
5429
+ assertInstalledCopyBridgeVersionSemantics(target, dshHome, srcVersion);
3720
5430
  console.log(' 版本戳重装断言:升级/降级方向措辞与覆盖后新戳 ✓');
5431
+ console.log(' dev 态载体版本比较:同基础健康 + 基础失配仍 FAIL ✓');
5432
+ console.log(' source 形态:既有断言全跑 → ' + marker + '(copy 文案/marker 与失败路径负例已由分发面回传契约夹具断言)✓');
5433
+ return marker;
3721
5434
  },
3722
5435
  },
3723
5436