flow-comet 1.6.2 → 1.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
  2. package/.flow-comet/skills/flow-comet/SKILL.md +64 -46
  3. package/.flow-comet/skills/flow-comet/reference/KNOWN-ISSUES-template.md +1 -1
  4. package/.flow-comet/skills/flow-comet/reference/commit-discipline.md +32 -0
  5. package/.flow-comet/skills/flow-comet/reference/dirty-worktree.md +1 -1
  6. package/.flow-comet/skills/flow-comet/{GUIDANCE.md → reference/entry-detail.md} +18 -28
  7. package/.flow-comet/skills/flow-comet/reference/fix-loop.md +57 -0
  8. package/.flow-comet/skills/flow-comet/reference/platform-facts.md +58 -0
  9. package/.flow-comet/skills/flow-comet/reference/replan.md +23 -0
  10. package/.flow-comet/skills/flow-comet/scripts/comet-check.mjs +5 -4
  11. package/.flow-comet/skills/flow-comet/scripts/comet-hook-guard.mjs +260 -17
  12. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +2714 -161
  13. package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +51 -4
  14. package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +13 -0
  15. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +877 -10
  16. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +52 -4
  17. package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +111 -4
  18. package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +108 -2
  19. package/.flow-comet/skills/flow-comet-archive/SKILL.md +10 -19
  20. package/.flow-comet/skills/flow-comet-change/SKILL.md +2 -3
  21. package/.flow-comet/skills/flow-comet-compose/SKILL.md +1 -1
  22. package/.flow-comet/skills/flow-comet-design/SKILL.md +6 -6
  23. package/.flow-comet/skills/flow-comet-execute/SKILL.md +58 -16
  24. package/.flow-comet/skills/flow-comet-integration/SKILL.md +8 -5
  25. package/.flow-comet/skills/flow-comet-open/SKILL.md +5 -1
  26. package/.flow-comet/skills/flow-comet-plan/GUIDANCE.md +1 -1
  27. package/.flow-comet/skills/flow-comet-plan/SKILL.md +8 -8
  28. package/.flow-comet/skills/flow-comet-review/SKILL.md +9 -12
  29. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +59 -16
  30. package/.flow-comet/skills/flow-comet-task/SKILL.md +3 -2
  31. package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +3 -3
  32. package/.flow-comet/skills/flow-comet-verify/SKILL.md +8 -17
  33. package/README.md +4 -4
  34. package/package.json +1 -1
  35. package/scripts/dsh-bridge.mjs +59 -26
  36. package/scripts/prepare-env.mjs +165 -1
  37. package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +0 -116
  38. package/.flow-comet/skills/flow-comet/reference/composition-report.md +0 -65
  39. package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +0 -184
  40. package/.flow-comet/skills/flow-comet/reference/resolved-skills.json +0 -661
  41. package/.flow-comet/skills/flow-comet/reference/skill-review.md +0 -13
  42. package/.flow-comet/skills/flow-comet/reference/subagents/script-author.md +0 -7
  43. package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +0 -70
@@ -22,6 +22,7 @@
22
22
  // purge 语义/描述符驱动/dsh 平台断言/loader 版本戳重装断言/hook 注入形态无关断言与旧条目幂等升级/
23
23
  // 旧布局状态迁移后状态可读与流程可继续/契约核对 CLI 参数化目录解析与缺省回退回归锚/
24
24
  // 分发面包体边界·可发布性清单与 bin 双入口(权威源真跑·副本回传显式「不适用」结果标记)
25
+ // ·安装器升级路径清理(权威源已删除或改名的生成物不得残留·反向探针 + 幂等)
25
26
  // 与 init 词元红线)
26
27
  // L. 执行遗漏防护(entry 进入证据/空退出豁免/空仓库提示)
27
28
  //
@@ -600,6 +601,42 @@ function assertPackageBoundary(root) {
600
601
  console.log(' 包体边界: ' + files.length + ' 文件,技能树 ' + skillsOnDisk.length + ' 文件逐文件在场,私有面零命中 ✓');
601
602
  }
602
603
 
604
+ // ③b workflow contract 检查(`comet-check.mjs`):包内**必含面清单**的自动锚。它此前全仓无任何
605
+ // CI/套件调用——清单漂移没有红灯(本批移出两个参考文件时只能靠手工同步清单)。判据两层:
606
+ // ① 真实执行权威源的该脚本 → exit 0 且输出 `workflow-contract-ok`(清单与真实树一致);
607
+ // ② 反向构造(同一判据驱动):把技能树复制到临时载体、删掉清单里的一个必含文件 → 该脚本必须
608
+ // exit ≠ 0 且报 `Missing required workflow contract files`(清单是真在查,不是恒真输出)。
609
+ function assertWorkflowContractCheck(scratch) {
610
+ const checker = path.join(__dirname, 'comet-check.mjs');
611
+ if (!fs.existsSync(checker)) throw new Error('缺少 comet-check.mjs: ' + checker);
612
+ const runChecker = (script) => {
613
+ const res = spawnSync(process.execPath, [script], { cwd: path.dirname(script), encoding: 'utf8', timeout: 60000 });
614
+ return { status: res.status ?? 1, output: String(res.stdout || '') + String(res.stderr || '') };
615
+ };
616
+ const real = runChecker(checker);
617
+ if (real.status !== 0 || !real.output.includes('workflow-contract-ok')) {
618
+ throw new Error('comet-check.mjs 未通过(包内必含面清单与真实树漂移)\n退出码 ' + real.status
619
+ + '\n输出:\n' + real.output);
620
+ }
621
+ // 反向构造:临时载体上一份技能树副本,删掉清单中的一个必含文件 ⇒ 必失败。
622
+ const carrier = path.join(scratch, 'contract-carrier');
623
+ fs.mkdirSync(carrier, { recursive: true });
624
+ fs.cpSync(path.join(__dirname, '..', '..'), path.join(carrier, 'skills'), { recursive: true });
625
+ const copiedChecker = path.join(carrier, 'skills', 'flow-comet', 'scripts', 'comet-check.mjs');
626
+ const removedRel = path.join('skills', 'flow-comet', 'reference', 'decision-points.md');
627
+ const removedAbs = path.join(carrier, removedRel);
628
+ if (!fs.existsSync(removedAbs)) {
629
+ throw new Error('反向构造前提不成立:清单必含文件不在副本内 ' + removedRel);
630
+ }
631
+ fs.rmSync(removedAbs);
632
+ const broken = runChecker(copiedChecker);
633
+ if (broken.status === 0 || !broken.output.includes('Missing required workflow contract files')) {
634
+ throw new Error('comet-check.mjs 反向构造判别力缺失(删掉清单必含文件后仍通过)\n退出码 '
635
+ + broken.status + '\n输出:\n' + broken.output);
636
+ }
637
+ console.log(' workflow contract 检查: 权威源 exit 0(workflow-contract-ok)+ 缺件副本必失败 ✓');
638
+ }
639
+
603
640
  // ③ bin 双入口契约:两个命令名同指同一安装器(同一实现 = 行为一致的结构事实)。返回安装器绝对路径。
604
641
  function assertBinContract(pkg, root) {
605
642
  const binTarget = 'scripts/prepare-env.mjs';
@@ -701,6 +738,214 @@ function assertInitTokenContract(installer, cwd) {
701
738
  console.log(' init 词元: `init --help` 退 0 且含 fcomet init / 裸形态行为不变 / 变形·重复词元 4 例退 1 且报未知参数 ✓');
702
739
  }
703
740
 
741
+ // ---------- 安装器升级路径清理断言助手(生成物镜像面:权威源已删除 / 改名的条目不得残留) ----------
742
+
743
+ // 升级路径清理断言(分发面:安装器的生成物镜像面)——判据 = 真实安装器命令序列 + 文件系统事实,
744
+ // 而不是「安装器退出码为 0」(后者会被「安装照常成功」恒真满足,清理实现整体缺席也不会变红):
745
+ // ① 删该删的:镜像目录内「权威源已不存在」的条目,重装后必须消失(含清空后的目录本身);
746
+ // ② 不该删的必不删(反向探针,逐条):权威源仍存在的文件 / 用户自有技能(无 flow-comet
747
+ // 命名空间)/ 命名空间内但权威源整个技能目录不在场(安装器没有生成清单,无法判定该目录
748
+ // 「确由上次生成写入」)/ copyTree 目标但路径不含命名空间(.claude/rules)/ 项目根用户文件;
749
+ // ③ 输出可核对:被清理条目逐条打印;④ 幂等:第二次重装零清理项、零报错。
750
+ // 夹具名刻意取合成形态,不占用真实工件名(将来权威源重新引入同名文件时夹具前提不失配)——
751
+ // 同时以「权威源确实不含该名」为前提断言,防止夹具退化成恒真空过。
752
+ function assertInstallerUpgradePathCleanup(scratch) {
753
+ const pkgCtx = resolvePackageContext();
754
+ if (pkgCtx.kind === 'copy') {
755
+ console.log(' 不适用(安装副本侧:' + pkgCtx.reason + ')——安装器升级路径清理断言仅权威源侧可判,本项计通过');
756
+ return;
757
+ }
758
+ const installer = path.join(pkgCtx.root, 'scripts', 'prepare-env.mjs');
759
+ const target = path.join(scratch, 'upgrade-path');
760
+ fs.mkdirSync(target, { recursive: true });
761
+ seedForeignFlowKit(target); // 预置同名非上游目录:flow-kit 走「已跳过」路径,零网络接触
762
+ const skillsRoot = path.join(target, '.claude', 'skills');
763
+ const runInstall = () => runInstallerOnce(installer, target);
764
+ const mustNotExist = (rel, label) => {
765
+ const p = path.join(skillsRoot, rel);
766
+ if (fs.existsSync(p)) throw new Error('升级重装后权威源已不存在的生成物仍残留(' + label + '): ' + p);
767
+ };
768
+ const mustExist = (rel, label) => {
769
+ const p = path.join(skillsRoot, rel);
770
+ if (!fs.existsSync(p)) throw new Error('升级重装误删了不该删的条目(' + label + '): ' + p);
771
+ };
772
+ // ① 首次安装(等价「上一代生成物」:内容与权威源一致)
773
+ assertExit(runInstall(), 0);
774
+ // ② 夹具:模拟上一代生成、而权威源已删除 / 改名的三类形态(文件 / 嵌套文件 / 目录树 + 空目录)
775
+ const staleFile = 'flow-comet/legacy-guidance.md';
776
+ const staleNested = 'flow-comet/reference/legacy-notes.md';
777
+ const staleDir = 'flow-comet/reference/legacy-subagents';
778
+ const staleEmptyDir = 'flow-comet/reference/legacy-empty';
779
+ writeFile(target, path.posix.join('.claude/skills', staleFile), 'stale\n');
780
+ writeFile(target, path.posix.join('.claude/skills', staleNested), 'stale\n');
781
+ writeFile(target, path.posix.join('.claude/skills', staleDir, 'author.md'), 'stale\n');
782
+ fs.mkdirSync(path.join(skillsRoot, staleEmptyDir), { recursive: true });
783
+ for (const rel of [staleFile, staleNested, staleDir, staleEmptyDir]) {
784
+ if (fs.existsSync(path.join(pkgCtx.root, '.flow-comet', 'skills', rel))) {
785
+ throw new Error('夹具前提失效:权威源已含 ' + rel + '——请改用其它合成名');
786
+ }
787
+ }
788
+ // ③ 反向探针夹具(不该删的必不删)
789
+ writeFile(target, '.claude/skills/my-own-skill/SKILL.md', 'user skill\n');
790
+ writeFile(target, '.claude/skills/flow-comet-fork/SKILL.md', 'unattributable dir\n');
791
+ writeFile(target, '.claude/rules/user-rule.md', 'user rule\n');
792
+ writeFile(target, 'USER_KEEP.md', 'user file\n');
793
+ // ④ 升级重装(真实安装器第二次运行同一平台)
794
+ const upgrade = runInstall();
795
+ assertExit(upgrade, 0);
796
+ // ⑤ 删该删的(三类形态逐条)
797
+ mustNotExist(staleFile, '改名残留文件');
798
+ mustNotExist(staleNested, '移出残留文件');
799
+ mustNotExist(staleDir, '残留目录(内容清空后应一并移除)');
800
+ mustNotExist(staleEmptyDir, '残留空目录');
801
+ // ⑥ 不该删的必不删(逐条反向探针)
802
+ mustExist('flow-comet/reference/entry-detail.md', '权威源仍存在的文件');
803
+ mustExist('flow-comet/SKILL.md', '权威源技能主体');
804
+ mustExist('my-own-skill/SKILL.md', '用户自有技能(无 flow-comet 命名空间)');
805
+ mustExist('flow-comet-fork/SKILL.md', '命名空间内但权威源整个技能目录不在场——归属不可判定,fail-closed 保留');
806
+ if (!fs.existsSync(path.join(target, '.claude', 'rules', 'user-rule.md'))) {
807
+ throw new Error('白名单外生成面(.claude/rules)的用户文件被误删');
808
+ }
809
+ if (!fs.existsSync(path.join(target, 'USER_KEEP.md'))) throw new Error('项目根用户文件被误删');
810
+ // ⑦ 输出可核对:被清理条目逐条打印(人可复核「删了什么」)
811
+ for (const rel of [staleFile, staleNested, staleDir, staleEmptyDir]) {
812
+ const name = path.posix.basename(rel);
813
+ if (!upgrade.output.includes(name)) {
814
+ throw new Error('清理输出未逐条打印被清理条目(缺 ' + name + '):\n' + upgrade.output);
815
+ }
816
+ }
817
+ // ⑦b 播报标记钉死:⑧ 的「重跑无清理项」是**负向**断言——标记一旦改名它便恒真;正向锚在此
818
+ // (标记须在首次升级输出里在场),标记契约的漂移因此必然红,而不是静默失效。
819
+ if (!upgrade.output.includes('镜像清理: 已删除')) {
820
+ throw new Error('升级重装输出缺清理播报标记「镜像清理: 已删除」:\n' + upgrade.output);
821
+ }
822
+ // ⑧ 幂等:第二次重装零清理项、零报错(重复跑不删多、不重复打印)
823
+ const again = runInstall();
824
+ assertExit(again, 0);
825
+ if (again.output.includes('镜像清理')) {
826
+ throw new Error('幂等失配:第二次重装仍报告清理动作:\n' + again.output);
827
+ }
828
+ console.log(' 升级路径清理: 残留 4 项消失(文件 / 嵌套文件 / 目录树 / 空目录)+ 6 条反向探针保留 + 输出可核对 + 幂等 ✓');
829
+ }
830
+
831
+ // 安装器单次真实运行(两处安装器分发面断言共用同一命令形态——同一知识只有一份实现)
832
+ function runInstallerOnce(script, target) {
833
+ const res = spawnSync(process.execPath, [script, '--target', target, '--platform', 'claude-code'], {
834
+ cwd: target, encoding: 'utf8', timeout: 120000,
835
+ });
836
+ return { status: res.status ?? 1, output: String(res.stdout || '') + String(res.stderr || '') };
837
+ }
838
+
839
+ // 把 linkPath 置为指向 targetDir 的链接(夹具构造与清理共用):递归删除会跟随链接目标,
840
+ // 故先按链接自身解链,再删可能残留的普通目录。
841
+ function replaceWithLink(linkPath, targetDir) {
842
+ try {
843
+ if (fs.lstatSync(linkPath).isSymbolicLink()) fs.unlinkSync(linkPath);
844
+ } catch { /* 不在场——无需解链 */ }
845
+ fs.rmSync(linkPath, { recursive: true, force: true });
846
+ fs.mkdirSync(path.dirname(linkPath), { recursive: true });
847
+ fs.symlinkSync(targetDir, linkPath, 'junction');
848
+ }
849
+
850
+ // 镜像清理的**根级** fail-closed 断言(同上一条属同一分发面项)——判据 = 真实安装器命令序列 + 文件系统事实:
851
+ // 根以下的条目层检查拦不住「镜像根自身是链接」:readdir 会跟随进链接目标,清理动作落在**项目之外**,
852
+ // 而播报打印的仍是项目内的表象路径(真实落点不可见)。两条判据各需一个变体驱动,缺任一变体则
853
+ // 对应那条判据整体缺席也不会有红灯:
854
+ // 变体 A「镜像根自身是指向项目外目录的链接」 ⇒ 根级链接判据(不跟随);
855
+ // 变体 B「父级目录是链接、镜像根自身是普通目录」 ⇒ 真实路径包含性判据(词法路径仍在项目内,
856
+ // 只有解析真实路径才能证否;此变体下 A 判据必然不命中,故它是包含性判据的独占探针)。
857
+ // 断言(两变体同):链接目标内的项目外文件**必不消失** + 输出含逐条保留原因 + 重复运行零删除项。
858
+ // 反向构造见 assertMirrorRootReverseConstruction(同一判据驱动,证明断言不恒真空过)。
859
+ function assertMirrorRootLinkFailClosed(scratch, pkgCtx) {
860
+ if (pkgCtx.kind === 'copy') {
861
+ console.log(' 不适用(安装副本侧:' + pkgCtx.reason + ')——镜像清理根级判据的探针仅权威源侧可判,本组计通过');
862
+ return;
863
+ }
864
+ const installer = path.join(pkgCtx.root, 'scripts', 'prepare-env.mjs');
865
+ // 变体 A:镜像根自身 = 指向项目外目录的链接
866
+ const targetA = path.join(scratch, 'mirror-root-link-self');
867
+ const outsideA = path.join(scratch, 'mirror-root-link-self-outside');
868
+ seedForeignFlowKit(targetA);
869
+ writeFile(outsideA, 'EXTERNAL-NOTE.md', 'out-of-tree user content\n');
870
+ writeFile(outsideA, path.posix.join('nested', 'DEEP-NOTE.md'), 'out-of-tree user content\n');
871
+ replaceWithLink(path.join(targetA, '.claude', 'skills', 'flow-comet'), outsideA);
872
+ // 变体 B:父级目录 = 链接(镜像根自身是目标内的普通目录)
873
+ const targetB = path.join(scratch, 'mirror-root-link-ancestor');
874
+ const outsideB = path.join(scratch, 'mirror-root-link-ancestor-outside');
875
+ seedForeignFlowKit(targetB);
876
+ writeFile(outsideB, path.posix.join('flow-comet', 'EXTERNAL-NOTE.md'), 'out-of-tree user content\n');
877
+ replaceWithLink(path.join(targetB, '.claude', 'skills'), outsideB);
878
+ const mirrorB = path.join(targetB, '.claude', 'skills', 'flow-comet');
879
+ if (!fs.existsSync(mirrorB) || fs.lstatSync(mirrorB).isSymbolicLink()) {
880
+ throw new Error('变体 B 前提失效:镜像根自身不是普通目录(应只有父级是链接): ' + mirrorB);
881
+ }
882
+ const variants = [
883
+ { label: '镜像根自身为链接', target: targetA, outsideFile: path.join(outsideA, 'EXTERNAL-NOTE.md'), reasonPattern: /镜像根是符号链接\/junction/ },
884
+ { label: '镜像根真实路径越界', target: targetB, outsideFile: path.join(outsideB, 'flow-comet', 'EXTERNAL-NOTE.md'), reasonPattern: /越出目标项目根/ },
885
+ ];
886
+ for (const v of variants) assertLinkTargetPreserved(installer, v);
887
+ assertMirrorRootReverseConstruction(scratch, pkgCtx, installer, variants);
888
+ console.log(' 镜像清理根级判据: 根自身为链接 / 真实路径越界 两变体下项目外文件保全 + 保留原因可见 + 幂等;'
889
+ + '反向构造(判据改恒真)两变体必被越界删除 ✓');
890
+ }
891
+
892
+ // 「链接目标内的项目外文件必不消失」断言(两变体同形):项目外文件仍在 + 输出含逐条保留原因 +
893
+ // 原因指明命中的判据 + 重复运行零删除项且文件仍在(保留是**可见的决定**,不是静默跳过)。
894
+ function assertLinkTargetPreserved(installer, { label, target, outsideFile, reasonPattern }) {
895
+ const first = runInstallerOnce(installer, target);
896
+ assertExit(first, 0);
897
+ if (!fs.existsSync(outsideFile)) {
898
+ throw new Error(label + ':镜像清理越界删除了项目之外的文件(真实落点 ' + outsideFile + ')\n输出:\n' + first.output);
899
+ }
900
+ if (!first.output.includes('镜像清理保留')) {
901
+ throw new Error(label + ':输出未逐条打印保留原因——fail-closed 保留必须是可见的决定\n输出:\n' + first.output);
902
+ }
903
+ if (!reasonPattern.test(first.output)) {
904
+ throw new Error(label + ':保留原因未指明命中判据(缺 ' + reasonPattern + ')\n输出:\n' + first.output);
905
+ }
906
+ const second = runInstallerOnce(installer, target);
907
+ assertExit(second, 0);
908
+ if (second.output.includes('镜像清理: 已删除')) {
909
+ throw new Error(label + ':重复运行仍报告删除动作(幂等失配)\n输出:\n' + second.output);
910
+ }
911
+ if (!fs.existsSync(outsideFile)) {
912
+ throw new Error(label + ':重复运行后项目之外的文件消失(' + outsideFile + ')');
913
+ }
914
+ }
915
+
916
+ // 反向构造(同一判据驱动):把两处根级判据分别中和为恒真后重跑同一变体 ⇒ 项目外文件**必被删除**;
917
+ // 判据落点漂移(判据句被改写)时「前提不成立」先行报错,避免变异无处落点而假绿。
918
+ // 变异副本建在临时载体上并自带捆绑源(安装器从**自身位置**推导权威树,故载体需含 .flow-comet/skills)。
919
+ function assertMirrorRootReverseConstruction(scratch, pkgCtx, installer, variants) {
920
+ const carrier = path.join(scratch, 'mirror-root-carrier');
921
+ const original = fs.readFileSync(installer, 'utf8');
922
+ const neutralizedContainment = original.replace(
923
+ 'if (!isRealPathInside(dstRoot, projectRoot)) {',
924
+ 'if (false && !isRealPathInside(dstRoot, projectRoot)) {'
925
+ );
926
+ if (neutralizedContainment === original) {
927
+ throw new Error('反向构造前提不成立:真实路径包含性判据的落点未找到(判据句已漂移,变异无处落点)');
928
+ }
929
+ const neutralized = neutralizedContainment.replace(
930
+ 'if (rootStat.isSymbolicLink()) {',
931
+ 'if (false && rootStat.isSymbolicLink()) {'
932
+ );
933
+ if (neutralized === neutralizedContainment) {
934
+ throw new Error('反向构造前提不成立:根级链接判据的落点未找到(判据句已漂移,变异无处落点)');
935
+ }
936
+ fs.mkdirSync(path.join(carrier, 'scripts'), { recursive: true });
937
+ fs.writeFileSync(path.join(carrier, 'scripts', 'prepare-env.mjs'), neutralized, 'utf8');
938
+ fs.cpSync(path.join(pkgCtx.root, '.flow-comet', 'skills'), path.join(carrier, '.flow-comet', 'skills'), { recursive: true });
939
+ const mutated = path.join(carrier, 'scripts', 'prepare-env.mjs');
940
+ for (const v of variants) {
941
+ const res = runInstallerOnce(mutated, v.target);
942
+ assertExit(res, 0);
943
+ if (fs.existsSync(v.outsideFile)) {
944
+ throw new Error(v.label + ' 反向构造判别力缺失:判据被中和后项目之外的文件仍在(断言可能是恒真空过)\n输出:\n' + res.output);
945
+ }
946
+ }
947
+ }
948
+
704
949
  // ---------- 桥接 loader 版本戳重装断言助手(临时 DSH_HOME 重装链路) ----------
705
950
 
706
951
  // 从权威源 loader 提取版本戳(与安装器/检查器同一锚点标记行;动态取值,版本演进零维护)
@@ -845,6 +1090,20 @@ function execSummaryFixture(taskId) {
845
1090
  ].join('\n');
846
1091
  }
847
1092
 
1093
+ // 同夹具的「段内大写 Z 早于方法名」变体(真实机检标记形态):6 维自查段体首行是含大写 Z 的机检
1094
+ // 标记说明,方法声明行在其后。段尾判定若把大写 Z 当串尾(惰性段体在段内首个 Z 处提前收尾),
1095
+ // 方法声明被截掉 ⇒ execute 家族出口误判「6 维自查未声明自检方法」而 BLOCK。
1096
+ // 夹具前提不成立(段标题形态变化)即抛错——不让变体静默退化成与基线逐字节相同的形态。
1097
+ function execSummaryWithMachineMarker(taskId) {
1098
+ const base = execSummaryFixture(taskId);
1099
+ const sixDimHead = '## 6 维自查\n\n';
1100
+ if (!base.includes(sixDimHead)) {
1101
+ throw new Error('夹具前提失效:SUMMARY 夹具缺 6 维自查段标题形态 ' + JSON.stringify(sixDimHead));
1102
+ }
1103
+ return base.replace(sixDimHead,
1104
+ sixDimHead + '> 本任务 diff 属零逻辑改动(机检标记 ZERO-LOGIC-CHANGE-OK),按协议执行 PR Review。\n\n');
1105
+ }
1106
+
848
1107
  // ---------- Fix 批次真实命令链路夹具(A21~A23 共用) ----------
849
1108
 
850
1109
  // 串行任务块(字段齐备:可过 task-parsing 解析与 guard 结构校验)
@@ -962,6 +1221,310 @@ function assertNotNodeLine(res, nodeId) {
962
1221
  }
963
1222
  }
964
1223
 
1224
+ // ---------- explain <node> 契约对账(节点现问) ----------
1225
+ // 期望值一律**现场从协议 JSON 派生**(本段不手抄第二份字段表):解析实现输出后逐字段与
1226
+ // `nodes[] / outputSchemas[]` 的声明比对。行前缀与分隔符是契约形态的一部分——不可解析即报问题
1227
+ // (不静默跳过)。反向构造探针复用同一判据(声明侧抽掉一条 guardrail / 一个 artifact / 改描述)。
1228
+
1229
+ // ARTIFACT 行:`<id> [<kind>] required|optional → <路径 | 路径>`(kind 可缺省;无路径 → 未声明路径)。
1230
+ function parseExplainArtifactLine(value) {
1231
+ const arrow = value.split(' → ');
1232
+ if (arrow.length !== 2) throw new Error('ARTIFACT 行缺「… → 路径」形态: ' + value);
1233
+ const requiredMatch = arrow[0].match(/ (required|optional)$/);
1234
+ if (!requiredMatch) throw new Error('ARTIFACT 行缺 required/optional 标注: ' + value);
1235
+ const head = arrow[0].slice(0, arrow[0].length - requiredMatch[0].length);
1236
+ const kindMatch = head.match(/^(.*) \[([^\]]+)\]$/);
1237
+ return {
1238
+ id: kindMatch ? kindMatch[1] : head,
1239
+ kind: kindMatch ? kindMatch[2] : null,
1240
+ required: requiredMatch[1] === 'required',
1241
+ paths: arrow[1] === '(未声明路径)' ? [] : arrow[1].split(' | '),
1242
+ };
1243
+ }
1244
+
1245
+ // GUARDRAIL 行:`<id> | <label> | <validation>`。
1246
+ function parseExplainGuardrailLine(value) {
1247
+ const parts = value.split(' | ');
1248
+ if (parts.length !== 3) throw new Error('GUARDRAIL 行缺三段(id | label | validation): ' + value);
1249
+ return { id: parts[0], label: parts[1], validation: parts[2] };
1250
+ }
1251
+
1252
+ // REQUIRED-SKILL 行:`<skill> | scope=<…> | enforcement=<…> | reason=<…>`。
1253
+ function parseExplainSkillLine(value) {
1254
+ const parts = value.split(' | ');
1255
+ if (parts.length !== 4) throw new Error('REQUIRED-SKILL 行缺四段(skill | scope= | enforcement= | reason=): ' + value);
1256
+ const [skill, scope, enforcement, reason] = parts;
1257
+ if (!scope.startsWith('scope=') || !enforcement.startsWith('enforcement=') || !reason.startsWith('reason=')) {
1258
+ throw new Error('REQUIRED-SKILL 行的键名形态不符: ' + value);
1259
+ }
1260
+ return { skill, scope: scope.slice(6), enforcement: enforcement.slice(12), reason: reason.slice(7) };
1261
+ }
1262
+
1263
+ function parseExplainOutput(output) {
1264
+ const parsed = {
1265
+ attributes: {}, schemas: [], artifacts: [], evidence: [], guardrails: [], guardrailsNone: false,
1266
+ skills: [], skillsNone: false, commands: [],
1267
+ };
1268
+ let schemaIndex = -1;
1269
+ for (const rawLine of String(output).split(/\r?\n/)) {
1270
+ const line = rawLine.trim();
1271
+ if (line === '') continue;
1272
+ const value = line.slice(line.indexOf(': ') + 2);
1273
+ if (line.startsWith('NODE: ')) parsed.attributes.node = value;
1274
+ else if (line.startsWith('LABEL: ')) parsed.attributes.label = value;
1275
+ else if (line.startsWith('KIND: ')) parsed.attributes.kind = value;
1276
+ else if (line.startsWith('DISABLED: ')) parsed.attributes.disabled = value;
1277
+ else if (line.startsWith('OUTPUT-SCHEMA: ')) {
1278
+ parsed.schemas.push(value);
1279
+ schemaIndex += 1;
1280
+ parsed.artifacts.push([]);
1281
+ parsed.evidence.push([]);
1282
+ } else if (line.startsWith('ARTIFACT: ')) {
1283
+ if (schemaIndex < 0) throw new Error('ARTIFACT 行先于 OUTPUT-SCHEMA 行: ' + line);
1284
+ parsed.artifacts[schemaIndex].push(parseExplainArtifactLine(value));
1285
+ } else if (line.startsWith('EVIDENCE: ')) {
1286
+ if (schemaIndex < 0) throw new Error('EVIDENCE 行先于 OUTPUT-SCHEMA 行: ' + line);
1287
+ parsed.evidence[schemaIndex].push(value);
1288
+ } else if (line.startsWith('GUARDRAIL: ')) {
1289
+ if (value === '(none)') parsed.guardrailsNone = true;
1290
+ else parsed.guardrails.push(parseExplainGuardrailLine(value));
1291
+ } else if (line.startsWith('REQUIRED-SKILL: ')) {
1292
+ if (value === '(none)') parsed.skillsNone = true;
1293
+ else parsed.skills.push(parseExplainSkillLine(value));
1294
+ } else if (line.startsWith('COMMAND ')) parsed.commands.push(line);
1295
+ else throw new Error('explain 输出含未识别的行形态: ' + line);
1296
+ }
1297
+ return parsed;
1298
+ }
1299
+
1300
+ // 期望值比对(解析结果 vs 协议声明;两侧同源,锚里不手抄字段表)。
1301
+ function expectExplainField(problems, nodeId, actual, declared, field) {
1302
+ if (actual !== declared) {
1303
+ problems.push('节点 ' + nodeId + ' 的 ' + field + ' 与协议声明不一致: 输出 '
1304
+ + JSON.stringify(actual) + ' / 声明 ' + JSON.stringify(declared));
1305
+ }
1306
+ }
1307
+
1308
+ // ① outputSchema 名与描述 + ② 每个 artifact 的 id·kind·required·路径(pathBase: specs-root ⇒ .specs/
1309
+ // 前缀)与每个 evidence 的 id (required)。
1310
+ function explainSchemaProblems(node, parsed, schemaById) {
1311
+ const problems = [];
1312
+ const declaredSchemas = node.outputSchemas ?? [];
1313
+ const expectedSchemaLines = declaredSchemas.length === 0
1314
+ ? ['(none)']
1315
+ : declaredSchemas.map((schemaId) => {
1316
+ const schema = schemaById.get(schemaId);
1317
+ return schemaId + (schema && schema.description ? ' — ' + schema.description : '');
1318
+ });
1319
+ expectExplainField(problems, node.id, parsed.schemas.join(' ␟ '), expectedSchemaLines.join(' ␟ '), 'OUTPUT-SCHEMA 行');
1320
+ declaredSchemas.forEach((schemaId, index) => {
1321
+ const schema = schemaById.get(schemaId);
1322
+ const declaredArtifacts = (schema?.artifacts ?? []).map((artifact) => ({
1323
+ id: artifact.id ?? '(unnamed)',
1324
+ kind: artifact.kind ?? null,
1325
+ required: artifact.required !== false,
1326
+ paths: (artifact.paths ?? []).map((declaredPath) =>
1327
+ (artifact.pathBase === 'specs-root' ? '.specs/' : '') + String(declaredPath)),
1328
+ }));
1329
+ const actualArtifacts = parsed.artifacts[index] ?? [];
1330
+ const artifactsMatch = actualArtifacts.length === declaredArtifacts.length
1331
+ && actualArtifacts.every((actual, position) => actual.id === declaredArtifacts[position].id
1332
+ && actual.kind === declaredArtifacts[position].kind
1333
+ && actual.required === declaredArtifacts[position].required
1334
+ && actual.paths.join(' | ') === declaredArtifacts[position].paths.join(' | '));
1335
+ if (!artifactsMatch) {
1336
+ problems.push('节点 ' + node.id + '/' + schemaId + ' 的 artifact 对账不一致: 输出 '
1337
+ + JSON.stringify(actualArtifacts) + ' / 声明 ' + JSON.stringify(declaredArtifacts));
1338
+ }
1339
+ const declaredEvidence = (schema?.evidence ?? []).length === 0
1340
+ ? '(none)'
1341
+ : (schema.evidence ?? []).map((evidence) =>
1342
+ evidence.id + (evidence.required === false ? ' (optional)' : ' (required)')).join(' | ');
1343
+ expectExplainField(problems, node.id, (parsed.evidence[index] ?? []).join(' | '),
1344
+ declaredEvidence, schemaId + ' 的 EVIDENCE 行');
1345
+ });
1346
+ return problems;
1347
+ }
1348
+
1349
+ // ③ 每条 guardrail 的 id·label·validation 与 ④ 每条 requiredSkillCall 的 skill·scope·enforcement·reason
1350
+ // (空集合 → '(none)' 行的在场性同判)。
1351
+ function explainGuardrailAndSkillProblems(node, parsed) {
1352
+ const problems = [];
1353
+ const declaredGuardrails = (node.guardrails ?? []).map((guardrail) => ({
1354
+ id: guardrail.id ?? '(unnamed)', label: guardrail.label ?? '-', validation: guardrail.validation ?? '-',
1355
+ }));
1356
+ if ((declaredGuardrails.length === 0) !== parsed.guardrailsNone) {
1357
+ problems.push('节点 ' + node.id + ' 的 guardrail 空集合形态与声明不一致((none) 行在场性不符)');
1358
+ }
1359
+ expectExplainField(problems, node.id, JSON.stringify(parsed.guardrails), JSON.stringify(declaredGuardrails), 'guardrail');
1360
+ const declaredSkills = (node.requiredSkillCalls ?? []).map((call) => ({
1361
+ skill: call.skill ?? '(unnamed)', scope: call.scope ?? '-',
1362
+ enforcement: call.enforcement ?? '-', reason: call.reason ?? '-',
1363
+ }));
1364
+ if ((declaredSkills.length === 0) !== parsed.skillsNone) {
1365
+ problems.push('节点 ' + node.id + ' 的 requiredSkillCall 空集合形态与声明不一致((none) 行在场性不符)');
1366
+ }
1367
+ expectExplainField(problems, node.id, JSON.stringify(parsed.skills), JSON.stringify(declaredSkills), 'requiredSkillCall');
1368
+ return problems;
1369
+ }
1370
+
1371
+ // ⑤ 三条命令:节点 id 与 --apply 形态 + 脚本根形态(三条同根、指向技能包 scripts 目录)+ 脚本
1372
+ // 路径整体带双引号(含空格的安装根下不被 shell 分词——引号是契约形态的一部分,缺引号即红)。
1373
+ function explainCommandProblems(node, parsed) {
1374
+ const commandPatterns = [
1375
+ [/^COMMAND entry: node "(.+?)\/workflow-guard\.mjs" entry (.+)$/, 'entry'],
1376
+ [/^COMMAND exit: node "(.+?)\/workflow-guard\.mjs" exit (.+) --apply$/, 'exit'],
1377
+ [/^COMMAND record: node "(.+?)\/workflow-state\.mjs" record (.+) '\{"summary":"<完成摘要>"\}'$/, 'record'],
1378
+ ];
1379
+ if (parsed.commands.length !== commandPatterns.length) {
1380
+ return ['节点 ' + node.id + ' 的 COMMAND 行数 ' + parsed.commands.length + ' ≠ 3'];
1381
+ }
1382
+ const problems = [];
1383
+ const scriptsRoots = new Set();
1384
+ parsed.commands.forEach((line, index) => {
1385
+ const [pattern, kind] = commandPatterns[index];
1386
+ const match = line.match(pattern);
1387
+ if (!match) {
1388
+ problems.push('节点 ' + node.id + ' 的 ' + kind + ' 命令形态不符: ' + line);
1389
+ return;
1390
+ }
1391
+ scriptsRoots.add(match[1]);
1392
+ if (match[2] !== node.id) problems.push('节点 ' + node.id + ' 的 ' + kind + ' 命令节点 id 不符: ' + match[2]);
1393
+ });
1394
+ if (scriptsRoots.size !== 1) {
1395
+ problems.push('节点 ' + node.id + ' 的三条命令脚本根不一致: ' + [...scriptsRoots].join(' / '));
1396
+ }
1397
+ const scriptsRoot = [...scriptsRoots][0] ?? '';
1398
+ if (!/skills\/flow-comet\/scripts$/.test(scriptsRoot)) {
1399
+ problems.push('节点 ' + node.id + ' 的命令脚本根不指向技能包 scripts 目录: ' + scriptsRoot);
1400
+ } else if (__dirname.replace(/\\/g, '/').includes('/.flow-comet/skills/')
1401
+ && scriptsRoot !== '.claude/skills/flow-comet/scripts') {
1402
+ // 权威源检出:命令路径 = 设计形态(安装副本按运行根形态化,已由上面同一判据约束)
1403
+ problems.push('权威源检出的命令脚本根应为设计形态 .claude/skills/flow-comet/scripts: ' + scriptsRoot);
1404
+ }
1405
+ return problems;
1406
+ }
1407
+
1408
+ // 逐字段对账(单一实现:真实判据与反向构造探针共用):四类字段 + 三条命令。
1409
+ function explainContractProblems(protocol, explainOutputs) {
1410
+ const problems = [];
1411
+ const schemaById = new Map((protocol.outputSchemas ?? []).map((schema) => [schema.id, schema]));
1412
+ for (const node of protocol.nodes ?? []) {
1413
+ const output = explainOutputs.get(node.id);
1414
+ if (typeof output !== 'string') {
1415
+ problems.push('节点 ' + node.id + ' 缺 explain 输出(未对账)');
1416
+ continue;
1417
+ }
1418
+ let parsed;
1419
+ try {
1420
+ parsed = parseExplainOutput(output);
1421
+ } catch (error) {
1422
+ problems.push('节点 ' + node.id + ' 的 explain 输出形态不可解析: ' + error.message);
1423
+ continue;
1424
+ }
1425
+ expectExplainField(problems, node.id, parsed.attributes.node, node.id, 'NODE');
1426
+ expectExplainField(problems, node.id, parsed.attributes.label ?? null, node.label ?? null, 'LABEL');
1427
+ expectExplainField(problems, node.id, parsed.attributes.kind ?? null, node.kind ?? null, 'KIND');
1428
+ expectExplainField(problems, node.id, parsed.attributes.disabled ?? null,
1429
+ node.disabled === true ? 'true(该节点在当前协议中被停用)' : null, 'DISABLED');
1430
+ problems.push(...explainSchemaProblems(node, parsed, schemaById));
1431
+ problems.push(...explainGuardrailAndSkillProblems(node, parsed));
1432
+ problems.push(...explainCommandProblems(node, parsed));
1433
+ }
1434
+ return problems;
1435
+ }
1436
+
1437
+ // explain 的三种 fail-closed 形态(非法节点 / 缺参 / 拿选项当节点名):都非零退出并列出全部合法节点。
1438
+ function assertExplainFailClosed(dir, protocolDecl) {
1439
+ const legalNodes = protocolDecl.nodes.map((protocolNode) => protocolNode.id).join('/');
1440
+ const forms = [
1441
+ ['非法节点', ['explain', 'not-a-node'], 'explain node 非法: not-a-node'],
1442
+ ['缺参', ['explain'], 'explain requires a <node> id'],
1443
+ ['选项当节点名', ['explain', '--help'], 'explain requires a <node> id'],
1444
+ ];
1445
+ for (const [form, args, expected] of forms) {
1446
+ const res = runState(args, dir);
1447
+ assertExit(res, 1);
1448
+ assertOut(res, expected);
1449
+ assertOut(res, legalNodes);
1450
+ if (form === '非法节点') assertOut(res, '(协议节点: ' + legalNodes + ')');
1451
+ }
1452
+ }
1453
+
1454
+ // 夹具协议(声明副本)下的 explain 输出——真实协议 env 通道;夹具文件跑完即清。
1455
+ function explainOutputsForDeclaration(dir, decl) {
1456
+ const probeProtocolFile = path.join(dir, 'reference', 'workflow-protocol-probe.json');
1457
+ fs.writeFileSync(probeProtocolFile, JSON.stringify(decl, null, 2), 'utf8');
1458
+ const outputs = new Map();
1459
+ for (const protocolNode of decl.nodes) {
1460
+ const res = runState(['explain', protocolNode.id], dir, { FLOW_COMET_PROTOCOL: probeProtocolFile });
1461
+ assertExit(res, 0);
1462
+ outputs.set(protocolNode.id, res.output);
1463
+ }
1464
+ fs.rmSync(probeProtocolFile, { force: true });
1465
+ return outputs;
1466
+ }
1467
+
1468
+ // 反向构造(L-106):把协议声明副本的一条 guardrail / 一个 artifact 抽掉、改一条 schema 描述 ⇒ 对账
1469
+ // 必报对应字段;再把真实输出里的脚本路径引号去掉 ⇒ 必报命令形态不符(证明断言不恒真空过——
1470
+ // 没有这一侧,把引号从实现里拿掉也能全绿)。返回问题描述数组(空 = 判别力齐备)。
1471
+ function explainReverseConstructionProblems(dir, protocolDecl, explainOutputs) {
1472
+ const probeNode = protocolDecl.nodes.find((protocolNode) => (protocolNode.guardrails ?? []).length > 0);
1473
+ const probeSchema = (protocolDecl.outputSchemas ?? []).find((schema) => (schema.artifacts ?? []).length > 0);
1474
+ const owner = probeSchema === undefined ? undefined
1475
+ : protocolDecl.nodes.find((protocolNode) => (protocolNode.outputSchemas ?? []).includes(probeSchema.id));
1476
+ if (probeNode === undefined || probeSchema === undefined || owner === undefined) {
1477
+ return ['反向构造前提不成立:协议声明里找不到带 guardrail 的节点 / 带 artifact 的 schema / schema 归属节点'];
1478
+ }
1479
+ const variants = [
1480
+ ['抽掉一条 guardrail', (decl) => {
1481
+ decl.nodes.find((protocolNode) => protocolNode.id === probeNode.id).guardrails = [];
1482
+ }, probeNode.id, 'guardrail'],
1483
+ ['抽掉一个 artifact', (decl) => {
1484
+ decl.outputSchemas.find((schema) => schema.id === probeSchema.id).artifacts = [];
1485
+ }, owner.id, 'artifact'],
1486
+ ['改掉一条 schema 描述', (decl) => {
1487
+ const target = decl.outputSchemas.find((schema) => schema.id === probeSchema.id);
1488
+ target.description = (probeSchema.description ?? '') + '(反向构造探针)';
1489
+ }, owner.id, 'OUTPUT-SCHEMA'],
1490
+ ];
1491
+ const problems = [];
1492
+ for (const [form, mutate, affectedNodeId, expectedField] of variants) {
1493
+ const mutatedDecl = JSON.parse(JSON.stringify(protocolDecl));
1494
+ mutate(mutatedDecl);
1495
+ const probeOutputs = explainOutputsForDeclaration(dir, mutatedDecl);
1496
+ if (probeOutputs.get(affectedNodeId) === explainOutputs.get(affectedNodeId)) {
1497
+ problems.push('反向构造前提不成立(' + form + ':夹具协议未改变 explain 输出——协议 env 通道未生效)');
1498
+ continue;
1499
+ }
1500
+ const probeProblems = explainContractProblems(protocolDecl, probeOutputs);
1501
+ if (!probeProblems.some((problem) => problem.includes(expectedField))) {
1502
+ problems.push('反向构造判别力缺失(' + form + ' 未被判分叉): ' + (probeProblems.join('; ') || '(零问题)'));
1503
+ }
1504
+ }
1505
+ // ④ 引号形态(③ 的另一面,不需重跑):真实输出去掉脚本路径引号 ⇒ 逐节点必报命令形态不符。
1506
+ const dequoted = new Map();
1507
+ for (const [nodeId, output] of explainOutputs) {
1508
+ const text = String(output);
1509
+ const stripped = text.replace(/(node )"([^"\n]*\.mjs)"/g, '$1$2');
1510
+ if (stripped === text) {
1511
+ problems.push('反向构造前提不成立(节点 ' + nodeId + ' 的输出里没有带引号的脚本路径——引号判据无从判别)');
1512
+ continue;
1513
+ }
1514
+ dequoted.set(nodeId, stripped);
1515
+ }
1516
+ if (dequoted.size > 0) {
1517
+ const dequotedProblems = explainContractProblems(protocolDecl, new Map([...explainOutputs, ...dequoted]));
1518
+ for (const nodeId of dequoted.keys()) {
1519
+ if (!dequotedProblems.some((problem) => problem.includes('节点 ' + nodeId + ' 的')
1520
+ && problem.includes('命令形态不符'))) {
1521
+ problems.push('反向构造判别力缺失(去掉节点 ' + nodeId + ' 的脚本路径引号未被判命令形态不符)');
1522
+ }
1523
+ }
1524
+ }
1525
+ return problems;
1526
+ }
1527
+
965
1528
  // 混排多波 TASK:双并行开路 → 串行衔接(依赖双并行)→ 收尾并行(依赖串行衔接)。
966
1529
  // 各任务 status 由入参映射(任务 id → 'pending'|'done')控制;status 变更不影响任务集签名
967
1530
  // (签名仅保留 id/parallel 与块内容,剥离 status 类属性)。串行衔接置于两并行波之间——
@@ -1289,7 +1852,7 @@ const TEST_ITEMS = [
1289
1852
  },
1290
1853
 
1291
1854
  {
1292
- name: 'A4 status:节点推导与无活跃兜底',
1855
+ name: 'A4 status/explain:节点推导、节点现问契约(逐字段对账 + fail-closed + 只读)与无活跃兜底',
1293
1856
  run: (dir) => {
1294
1857
  assertExit(runState(['init', CHANGE_ID], dir), 0);
1295
1858
  // 无产物 → 首节点
@@ -1301,6 +1864,31 @@ const TEST_ITEMS = [
1301
1864
  const s2 = runState(['status'], dir);
1302
1865
  assertExit(s2, 0);
1303
1866
  assertOut(s2, '"currentNode": "design"');
1867
+ // —— explain <node>:节点现问契约(真实子进程,零 mock;契约声明源 = 协议 JSON)——
1868
+ // 8 节点逐个逐字段对账(label / kind / outputSchema 名与描述 / artifact / evidence / guardrail /
1869
+ // requiredSkillCall / 三条命令)+ 三种 fail-closed 形态 + 只读性 + 反向构造(声明副本抽掉一条
1870
+ // guardrail / 一个 artifact、改一条 schema 描述 ⇒ 对账必报;判据与探针见模块级单一实现)。
1871
+ const protocolDecl = JSON.parse(fs.readFileSync(path.join(dir, 'reference', 'workflow-protocol.json'), 'utf8'));
1872
+ const stateFilePath = path.join(dir, '.flow-comet', 'flow-comet-state.json');
1873
+ const stateHashBefore = createHash('sha256').update(fs.readFileSync(stateFilePath)).digest('hex');
1874
+ const statusBefore = runState(['status'], dir);
1875
+ const explainOutputs = new Map();
1876
+ for (const protocolNode of protocolDecl.nodes) {
1877
+ const res = runState(['explain', protocolNode.id], dir);
1878
+ assertExit(res, 0);
1879
+ assertOut(res, 'NODE: ' + protocolNode.id);
1880
+ explainOutputs.set(protocolNode.id, res.output);
1881
+ }
1882
+ const contractProblems = explainContractProblems(protocolDecl, explainOutputs);
1883
+ assertTrue(contractProblems.length === 0,
1884
+ 'explain 输出与协议 JSON 声明不一致: ' + contractProblems.join('; '));
1885
+ // 只读性:调用前后状态文件 sha256 全等 + status 读数逐字不变(explain 不写 state、不改路由)
1886
+ assertEqual(createHash('sha256').update(fs.readFileSync(stateFilePath)).digest('hex'), stateHashBefore,
1887
+ 'explain 改写了状态文件(只读通道被破坏)');
1888
+ assertEqual(runState(['status'], dir).output, statusBefore.output, 'explain 改动了路由读数(只读通道被破坏)');
1889
+ assertExplainFailClosed(dir, protocolDecl);
1890
+ const probeProblems = explainReverseConstructionProblems(dir, protocolDecl, explainOutputs);
1891
+ assertTrue(probeProblems.length === 0, '反向构造判别力缺失: ' + probeProblems.join('; '));
1304
1892
  // 无 state 无工件 → no-change 兜底
1305
1893
  fs.rmSync(path.join(dir, '.flow-comet'), { recursive: true });
1306
1894
  const s3 = runState(['status'], dir);
@@ -1823,7 +2411,7 @@ const TEST_ITEMS = [
1823
2411
  // 补显式 depends_on 后放行;旧 change 形态仅 WARN 不阻断;修复任务族(id 带修复前缀)
1824
2412
  // 不参与该族——其顺序由修复生命周期保证,回修同一文件是必然形态。修复前 plan 出口无这些
1825
2413
  // 检测 = 预期 RED。
1826
- name: 'A16 plan 出口文件依赖检出:写写重叠 BLOCK 与恢复 + 读写弱判 WARN + 同文件跨任务无依赖路径(真实命令)',
2414
+ name: 'A16 plan 出口文件依赖检出:写写重叠 BLOCK 与恢复 + glob 单侧/双侧/不重叠 + 读写弱判 WARN + 同文件跨任务无依赖路径(真实命令)',
1827
2415
  run: (dir) => {
1828
2416
  driveThroughDesign(dir);
1829
2417
  const planEnv = { FLOW_COMET_PROTOCOL: path.join(dir, 'reference', 'workflow-protocol.json') };
@@ -1855,6 +2443,39 @@ const TEST_ITEMS = [
1855
2443
  assertOut(blocked, 'BLOCKED');
1856
2444
  assertOut(blocked, 'bak_a.txt');
1857
2445
  assertOut(blocked, 'depends_on');
2446
+ // glob 形态重叠(单侧元字符 × 字面路径):修复前逐字相等判定漏检 ⇒ 静默放行(本段即 RED);
2447
+ // 反向构造:改为互不重叠 / 段数不等 / 段内不匹配 ⇒ 放行(判据不恒真空过);双侧 glob ⇒ 保守判重叠。
2448
+ const globPair = (firstWrite, secondWrite, secondDeps = '') =>
2449
+ C1 +
2450
+ '<task id="G01" parallel="true" status="pending"><action>实现 G01</action><write_files>' + firstWrite + '</write_files><verify>node --check src/x.mjs</verify></task>\n' +
2451
+ '<task id="G02" parallel="true" status="pending"><action>实现 G02</action><write_files>' + secondWrite + '</write_files><verify>node --check src/x.mjs</verify>' + secondDeps + '</task>\n';
2452
+ planTask(globPair('src/glob/*.mjs', 'src/glob/foo.mjs'));
2453
+ const globBlocked = exitPlanNoApply();
2454
+ assertExit(globBlocked, 1);
2455
+ assertOut(globBlocked, 'BLOCKED');
2456
+ assertOut(globBlocked, 'G01×G02');
2457
+ assertOut(globBlocked, 'src/glob/*.mjs');
2458
+ assertOut(globBlocked, 'src/glob/foo.mjs');
2459
+ assertOut(globBlocked, 'depends_on');
2460
+ planTask(globPair('src/glob/*.mjs', 'src/glob/deep/foo.mjs'));
2461
+ const depthMismatch = exitPlanNoApply();
2462
+ assertExit(depthMismatch, 0);
2463
+ assertNotOut(depthMismatch, 'BLOCKED');
2464
+ planTask(globPair('src/glob/*.mjs', 'src/glob/foo.js'));
2465
+ const suffixMismatch = exitPlanNoApply();
2466
+ assertExit(suffixMismatch, 0);
2467
+ assertNotOut(suffixMismatch, 'BLOCKED');
2468
+ planTask(globPair('src/glob/*.mjs', 'src/glob/*.js'));
2469
+ const doubleGlob = exitPlanNoApply();
2470
+ assertExit(doubleGlob, 1);
2471
+ assertOut(doubleGlob, 'BLOCKED');
2472
+ assertOut(doubleGlob, 'G01×G02');
2473
+ // 恢复(真实链路):按指引补显式 depends_on(重叠路径不改)⇒ 同一出口放行
2474
+ planTask(globPair('src/glob/*.mjs', 'src/glob/foo.mjs', '<depends_on>G01</depends_on>'));
2475
+ const globRecovered = exitPlanNoApply();
2476
+ assertExit(globRecovered, 0);
2477
+ assertOut(globRecovered, 'ALL CHECKS PASSED');
2478
+ assertNotOut(globRecovered, 'BLOCKED');
1858
2479
  // 同一文件跨任务族(负例):两个非修复任务写入同一文件、彼此无依赖路径(串行拆分同样构成
1859
2480
  // 「未显式排序的同文件多任务」)→ 新 change BLOCKED,消息含任务对与重叠文件 + 恢复指引。
1860
2481
  // 同夹具并列一对修复任务(id 带修复前缀)写同一文件且无依赖路径——该族不参与判定,
@@ -3236,6 +3857,55 @@ const TEST_ITEMS = [
3236
3857
  throw new Error('零提交 result 应真实写入 state');
3237
3858
  }
3238
3859
 
3860
+ // ⑫b 并行 × 零提交(真实 request/result 链路):同一零提交资格在 parallel="true" 任务上
3861
+ // 照常成立——并行维度不改四属性映射:① 写权限走身份通道、② 提交隔离走既有 noCommit
3862
+ // 资格(零提交 ⇒ 无提交,提交隔离由「无提交」满足)。任务归属 subagent-execute
3863
+ // (并行 pending),request 记 noCommit:true、result 回传无 commitHash 的零提交契约
3864
+ // ⇒ exit 0、不因并行维度被契约校验拦。前提在场锚:TASK.md 该任务确带 parallel="true",
3865
+ // 且归属校验真实执行(协议可读、节点已 entry——不静默退化成串行/跳过形态)。
3866
+ const parallelTaskPath = path.join(dir, '.specs', CHANGE_ID, 'TASK.md');
3867
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md',
3868
+ '# TASK\n\n<task id="P16" parallel="true" status="pending"><action>并行账本同步</action>'
3869
+ + '<write_files>.specs/' + CHANGE_ID + '/P16-SUMMARY.md</write_files>'
3870
+ + '<verify>echo ok</verify></task>\n');
3871
+ if (!fs.readFileSync(parallelTaskPath, 'utf8').includes('<task id="P16" parallel="true" status="pending">')) {
3872
+ throw new Error('并行 × 零提交锚的前提失效:TASK.md 未标 parallel="true"');
3873
+ }
3874
+ assertExit(runState(['skill-load', 'subagent-execute', 'flow-comet-dev', '--prompt', 'flow-kit/prompts/4-dev.md'], dir), 0);
3875
+ const stParallel = readStateFile(dir);
3876
+ stParallel.currentNode = 'subagent-execute';
3877
+ stParallel.enteredNodes = ['open', 'design', 'plan', 'execute', 'subagent-execute'];
3878
+ stParallel.newChange = true;
3879
+ writeState(dir, stParallel);
3880
+ const parallelEnv = { FLOW_COMET_PROTOCOL: path.join(dir, 'reference', 'workflow-protocol.json') };
3881
+ const reqParallel = runHandoff(['request', 'P16', '并行零提交任务委托'], dir, parallelEnv);
3882
+ assertExit(reqParallel, 0);
3883
+ assertOut(reqParallel, 'HANDOFF REQUEST: P16');
3884
+ assertOut(reqParallel, 'HANDOFF 零提交资格: P16');
3885
+ assertNotOut(reqParallel, '本次未执行归属校验');
3886
+ assertNotOut(reqParallel, '尚未 entry');
3887
+ const parallelReqRecord = readStateFile(dir).evidence['subagent-execute'].handoffRequests.P16;
3888
+ if (!parallelReqRecord || parallelReqRecord.noCommit !== true) {
3889
+ throw new Error('并行任务的字面 gitignored write_files 应同样记录 noCommit:true: ' + JSON.stringify(parallelReqRecord));
3890
+ }
3891
+ const resParallel = runHandoff(['result', 'P16', JSON.stringify({
3892
+ status: 'DONE', taskId: 'P16', noCommit: true,
3893
+ completedChecks: ['required-skill:subagent-execute.flow-comet-dev'],
3894
+ redEvidence: { command: 'echo ok' },
3895
+ greenEvidence: { command: 'echo ok', output: 'ok' },
3896
+ })], dir);
3897
+ assertExit(resParallel, 0);
3898
+ assertOut(resParallel, 'HANDOFF RESULT: P16');
3899
+ assertOut(resParallel, 'HANDOFF 零提交: P16');
3900
+ assertNotOut(resParallel, 'HANDOFF ERROR');
3901
+ assertNotOut(resParallel, 'BLOCKED');
3902
+ const parallelResultRecord = readStateFile(dir).evidence['subagent-execute'].handoffResult.P16;
3903
+ if (!parallelResultRecord || parallelResultRecord.result?.noCommit !== true
3904
+ || parallelResultRecord.result.commitHash !== undefined) {
3905
+ throw new Error('并行零提交 result 应写入无 commitHash 的契约: ' + JSON.stringify(parallelResultRecord));
3906
+ }
3907
+ console.log(' AC-9 并行×零提交: parallel="true" 任务 request 记 noCommit:true → result 无 commitHash 契约通过(exit 0)✓');
3908
+
3239
3909
  // ⑬ 零提交负例:无资格形态(glob / .. 越界 / 非 git 仓 / tracked 文件)→ request 不记 noCommit
3240
3910
  const assertNoCommitNotRecorded = (root, taskId, label) => {
3241
3911
  const requestState = readStateFile(root);
@@ -3584,7 +4254,7 @@ const TEST_ITEMS = [
3584
4254
  },
3585
4255
 
3586
4256
  {
3587
- name: 'C3 委托后 exit:证据键名契约与契约校验(通过 / 空交接拦截)',
4257
+ name: 'C3 委托后 exit:证据键名契约与契约校验(通过 / 空交接拦截 / 在飞委托拦·收工放行 / 留痕可读)',
3588
4258
  run: (dir) => {
3589
4259
  gitInit(dir);
3590
4260
  writeFile(dir, 'src/p1.mjs', 'export const x = 1;\n');
@@ -3652,6 +4322,74 @@ const TEST_ITEMS = [
3652
4322
  const rDeclPass = runGuard(['exit', 'subagent-execute'], dir);
3653
4323
  assertExit(rDeclPass, 0);
3654
4324
  assertOut(rDeclPass, 'ALL CHECKS PASSED');
4325
+ // ⑬ 验证隔离真实链路(在飞委托 = 写者未收工):登记第二个委托请求而不落结果 ⇒ 出口
4326
+ // BLOCKED 并点名未收工任务 + 恢复指引;收工(落结果)后同一出口放行——「同一时刻只有
4327
+ // 一个写者」的机器可判形态走真实命令序列(request → exit 拦 → result → exit 放行)。
4328
+ writeFile(dir, 'src/p2.mjs', 'export const y = 2;\n');
4329
+ execFileSync('git', ['add', 'src/p2.mjs'], { cwd: dir });
4330
+ execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'feat: p2'], { cwd: dir });
4331
+ const hash2 = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim();
4332
+ assertExit(runHandoff(['request', 'P02', '委托实现 P02', '--write-files', 'src/p2.mjs'], dir), 0);
4333
+ const inFlightBlocked = runGuard(['exit', 'subagent-execute'], dir);
4334
+ assertExit(inFlightBlocked, 1);
4335
+ assertOut(inFlightBlocked, '在飞委托');
4336
+ assertOut(inFlightBlocked, '待写入者收工后重跑');
4337
+ assertOut(inFlightBlocked, 'P02');
4338
+ assertExit(runHandoff(['result', 'P02', fullContract(hash2, 'P02')], dir), 0);
4339
+ const collected = runGuard(['exit', 'subagent-execute'], dir);
4340
+ assertExit(collected, 0);
4341
+ assertOut(collected, 'ALL CHECKS PASSED');
4342
+ assertNotOut(collected, '在飞委托');
4343
+ // ⑮ 撤回通道真实链路(被遗弃的交接的受支持出口):登记第三个委托而不落结果 ⇒ 出口拦并给出
4344
+ // 该命令的恢复指引;用 workflow-handoff.mjs withdraw 撤回(原地留痕 withdrawnAt /
4345
+ // withdrawnBy,历史不删)⇒ 同一出口放行。反向构造:守卫不忽略已撤回的 request ⇒ 放行断言
4346
+ // 必红;撤回是终态 ⇒ 同一条目再次 result 被拒(撤回不被事后「复活」)。
4347
+ assertExit(runHandoff(['request', 'P03', '委托实现 P03', '--write-files', 'src/p3.mjs'], dir), 0);
4348
+ const abandonedBlocked = runGuard(['exit', 'subagent-execute'], dir);
4349
+ assertExit(abandonedBlocked, 1);
4350
+ assertOut(abandonedBlocked, '在飞委托');
4351
+ assertOut(abandonedBlocked, 'workflow-handoff.mjs withdraw');
4352
+ const noSource = runHandoff(['withdraw', 'P03'], dir);
4353
+ assertExit(noSource, 1);
4354
+ assertOut(noSource, '--by');
4355
+ const withdrawRes = runHandoff(['withdraw', 'P03', '--by', 'coordinator', '--reason', '零提交复验失败后作废'], dir);
4356
+ assertExit(withdrawRes, 0);
4357
+ assertOut(withdrawRes, 'HANDOFF WITHDRAW: P03');
4358
+ const stWithdraw = readStateFile(dir);
4359
+ const p03 = stWithdraw.evidence?.['subagent-execute']?.handoffRequests?.P03;
4360
+ if (!p03 || typeof p03.withdrawnAt !== 'string' || p03.withdrawnAt.trim() === '' || p03.withdrawnBy !== 'coordinator') {
4361
+ throw new Error('撤回留痕未落原记录(withdrawnAt + withdrawnBy): ' + JSON.stringify(p03));
4362
+ }
4363
+ if (!Array.isArray(p03.writeFiles) || p03.writeFiles[0] !== 'src/p3.mjs') {
4364
+ throw new Error('撤回不得删除原 request 字段(writeFiles 应原样保留): ' + JSON.stringify(p03));
4365
+ }
4366
+ // 时间纪律(真实链路):新写入路径走 time-utils 单一权威 ⇒ withdrawnAt 为标准形态
4367
+ // (本地时间 + 显式偏移),非裸 Z 拼接。
4368
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$/.test(p03.withdrawnAt)) {
4369
+ throw new Error('withdrawnAt 应为标准形态(本地时间 + 显式偏移,走 time-utils 的 nowTimestamp): '
4370
+ + JSON.stringify(p03.withdrawnAt));
4371
+ }
4372
+ const releasedExit = runGuard(['exit', 'subagent-execute'], dir);
4373
+ assertExit(releasedExit, 0);
4374
+ assertOut(releasedExit, 'ALL CHECKS PASSED');
4375
+ assertNotOut(releasedExit, '在飞委托');
4376
+ const revived = runHandoff(['result', 'P03', fullContract(hash2, 'P03')], dir);
4377
+ assertExit(revived, 1);
4378
+ assertOut(revived, '已撤回(终态)');
4379
+ // ⑯ 派遣留痕可读且零新增 state 顶层字段:留痕落在既有嵌套字段(与 handoffRequests /
4380
+ // handoffResult 同族),state 顶层不得出现任何留痕族键。
4381
+ const stTrace = readStateFile(dir);
4382
+ if (!stTrace.evidence?.['subagent-execute']?.handoffRequests?.P02) {
4383
+ throw new Error('委派留痕未落嵌套证据字段(handoffRequests.P02 缺失): ' + JSON.stringify(stTrace.evidence));
4384
+ }
4385
+ if (stTrace.handoffRequests !== undefined || stTrace.handoffResult !== undefined) {
4386
+ throw new Error('留痕出现在 state 顶层字段(应为嵌套同族形态)');
4387
+ }
4388
+ for (const key of Object.keys(stTrace)) {
4389
+ if (/handoff|delegation|dispatch|trace/i.test(key)) {
4390
+ throw new Error('state 顶层出现留痕族字段: ' + key + '(零新增顶层字段约束被破坏)');
4391
+ }
4392
+ }
3655
4393
  },
3656
4394
  },
3657
4395
 
@@ -4307,7 +5045,8 @@ const TEST_ITEMS = [
4307
5045
  writeFile(dir, '.specs/' + CHANGE_ID + '/DESIGN.md',
4308
5046
  '# DESIGN\n\n- **Change ID**: ' + CHANGE_ID + '\n\n## 0. 技术栈选定\n\nNode.js(ESM)\n\n## 决策清单\n\n- [ ] 循环路由\n');
4309
5047
  writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', fixBatchTaskText('pending'));
4310
- writeFile(dir, '.specs/' + CHANGE_ID + '/T01-SUMMARY.md', execSummaryFixture('T01'));
5048
+ // 段内大写 Z 形态的 SUMMARY(方法声明在其后):该出口的 exit 0 即「段尾判定正确」的真实链路锚
5049
+ writeFile(dir, '.specs/' + CHANGE_ID + '/T01-SUMMARY.md', execSummaryWithMachineMarker('T01'));
4311
5050
  // 源节点前序产物齐备:REVIEW.md 在场(已处置)——否则回源 verify 出口后的产物推导会把
4312
5051
  // 下一跳判回 review(产物即真相),组合链路的终点断言无法到达 archive。
4313
5052
  writeFile(dir, '.specs/' + CHANGE_ID + '/REVIEW.md', fixBatchReviewDoc(true));
@@ -4332,6 +5071,10 @@ const TEST_ITEMS = [
4332
5071
  const execExit = runGuard(['exit', 'execute', '--apply'], dir, env);
4333
5072
  assertExit(execExit, 0);
4334
5073
  assertOut(execExit, 'ALL CHECKS PASSED');
5074
+ // 段尾判定锚(新 / 旧 change 两态都不许出现该拦因):T01 的 6 维自查段内大写 Z 在方法声明
5075
+ // **之前**——段体若把大写 Z 当串尾而提前收尾,该出口会报「6 维自查未声明使用」(新 change
5076
+ // BLOCK / 旧 change 同句 WARN),本条对两态都构成判别。
5077
+ assertNotOut(execExit, '6 维自查未声明使用');
4335
5078
  assertOut(execExit, 'FIX-BATCH: 回源节点 verify(execute 出口已完成)');
4336
5079
  assertNodeLine(execExit, 'verify');
4337
5080
  assertNotNodeLine(execExit, 'archive');
@@ -4349,6 +5092,19 @@ const TEST_ITEMS = [
4349
5092
  throw new Error(summaryName + ' 缺六维自查 / 自检方法段(execute 家族出口之一)');
4350
5093
  }
4351
5094
  }
5095
+ // 夹具形态自证(判别力前提 · 抽掉必报的反面):T01 的 6 维自查段内「大写 Z 说明行」必须
5096
+ // **早于**方法声明、且两者都在该段内——否则上面那次出口放行与该段尾判定无关,锚会静默
5097
+ // 退化成假绿(形态不符即抛错,不静默跳过)。
5098
+ const t01SummaryText = fs.readFileSync(path.join(dir, '.specs', CHANGE_ID, 'T01-SUMMARY.md'), 'utf8');
5099
+ const sixDimAt = t01SummaryText.indexOf('## 6 维自查');
5100
+ const nextSectionAt = sixDimAt >= 0 ? t01SummaryText.indexOf('\n## ', sixDimAt) : -1;
5101
+ const zMarkerAt = sixDimAt >= 0 ? t01SummaryText.indexOf('ZERO-LOGIC-CHANGE-OK', sixDimAt) : -1;
5102
+ const declaredAt = sixDimAt >= 0 ? t01SummaryText.indexOf('brooks-review', sixDimAt) : -1;
5103
+ if (!(sixDimAt >= 0 && zMarkerAt > sixDimAt && declaredAt > zMarkerAt
5104
+ && (nextSectionAt === -1 || declaredAt < nextSectionAt))) {
5105
+ throw new Error('T01-SUMMARY 的 6 维自查段须为「大写 Z 说明行在前、方法声明行在后」形态(段尾判定锚的判别力前提): '
5106
+ + JSON.stringify({ sixDimAt, zMarkerAt, declaredAt, nextSectionAt }));
5107
+ }
4352
5108
  const execEvent = (chainState.history || [])
4353
5109
  .filter((e) => e.event === 'exit-applied' && e.node === 'execute')
4354
5110
  .pop();
@@ -5321,7 +6077,7 @@ const TEST_ITEMS = [
5321
6077
  // 形状不符 fail-closed/项目根包含性含 8.3 短路径/退出码映射/guard 路径存在漂移防护;
5322
6078
  // apply 集成:tools/pre-execute 监听器分派——子代理放行/协调者走 guard/越界·形状 deny 不受身份)
5323
6079
  {
5324
- name: 'K11 桥接 loader:纯函数与 apply 分派断言(映射/包含性/退出映射/身份分派)',
6080
+ name: 'K11 桥接 loader:纯函数与 apply 分派断言(映射/包含性/退出映射/身份分派/最小保护集)',
5325
6081
  run: async (dir) => {
5326
6082
  const repoRoot = path.resolve(__dirname, '..', '..', '..', '..');
5327
6083
  if (!fs.existsSync(path.join(repoRoot, '.flow-comet', 'skills', 'flow-comet'))) return; // 安装副本无权威源
@@ -5484,14 +6240,15 @@ const TEST_ITEMS = [
5484
6240
  // 项目根常规用长形态(与桥接对 file_path 的规范化一致,对应真实会话规范 cwd);
5485
6241
  // 短形态 cwd 的场景由桥接的项目根规范化修复,⑦f 断言锁死(fail-open 已封闭)。
5486
6242
  const longTarget = bridge.realpathExistingPath(target); // realpathSync.native——展开 8.3 短名
5487
- // ⑦a 子代理(depth=1)写项目内源码 → next() 被调(跳过 guard 白名单放行)
6243
+ // ⑦a 子代理(depth=1)写项目内源码 → next() 被调(守卫按身份分派放行——桥接不短路,
6244
+ // 身份深度随 env 透传,判定与最小保护集统一由守卫拥有)
5488
6245
  {
5489
6246
  let usedNext = false;
5490
6247
  const res = await preExec(
5491
6248
  { name: 'Write', arguments: { file_path: path.join(longTarget, 'src', 'a.mjs') }, agent: { cwd: longTarget, session: { header: { delegationDepth: 1 } } } },
5492
6249
  () => { usedNext = true; },
5493
6250
  );
5494
- if (!usedNext) throw new Error('子代理写源码应放行(next 被调)——5.5 分派分支缺失');
6251
+ if (!usedNext) throw new Error('子代理写源码应放行(next 被调)——身份分派分支缺失');
5495
6252
  if (res) throw new Error('子代理写源码不应返回 deny: ' + JSON.stringify(res));
5496
6253
  }
5497
6254
  // ⑦b 协调者(delegationDepth 缺失=0)同目标写 → 走真实 guard 白名单 → BLOCK deny
@@ -5556,7 +6313,106 @@ const TEST_ITEMS = [
5556
6313
  throw new Error('短形态 cwd 协调者写源码应走 guard 白名单拦截(deny): ' + JSON.stringify(res));
5557
6314
  }
5558
6315
  }
5559
- console.log(' bridge.apply 分派集成(子代理放行/协调者拦/越界·形状 deny 不受身份)✓');
6316
+ // ⑦g 最小保护集在桥接侧真实生效(身份放行不放行机器面):子代理(depth=1)写项目内
6317
+ // 机器状态文件 → 桥接透传身份深度、守卫保护集 BLOCK → deny;对照 = ⑦a 同身份写源码
6318
+ // 放行。反向构造:桥接恢复「身份短路直接 next」⇒ 本断言必红(保护集形同虚设)。
6319
+ {
6320
+ let usedNext = false;
6321
+ const res = await preExec(
6322
+ { name: 'Write', arguments: { file_path: path.join(longTarget, '.flow-comet', 'flow-comet-state.json') }, agent: { cwd: longTarget, session: { header: { delegationDepth: 1 } } } },
6323
+ () => { usedNext = true; },
6324
+ );
6325
+ if (usedNext) throw new Error('子代理写机器状态文件不应 next——身份放行不得放行最小保护集');
6326
+ if (!res || res.kind !== 'deny' || !res.reason.includes('state 文件')) {
6327
+ throw new Error('子代理写机器状态文件应 deny(含 state 文件语义): ' + JSON.stringify(res));
6328
+ }
6329
+ }
6330
+ // ⑦h 最小保护集的协议目标同判:子代理(depth=1)写本次运行实际生效的协议文件
6331
+ // (守卫按自身 packageRoot 解析——安装副本内的 reference/workflow-protocol.json)
6332
+ // → deny;该路径在项目根内,故本断言与 ⑦d 的越界 deny 相互独立(保护集非越界判定)。
6333
+ {
6334
+ const protocolInTarget = path.join(longTarget, '.dsh', 'skills', 'flow-comet', 'reference', 'workflow-protocol.json');
6335
+ let usedNext = false;
6336
+ const res = await preExec(
6337
+ { name: 'Write', arguments: { file_path: protocolInTarget }, agent: { cwd: longTarget, session: { header: { delegationDepth: 1 } } } },
6338
+ () => { usedNext = true; },
6339
+ );
6340
+ if (usedNext) throw new Error('子代理写协议保护路径不应 next——身份放行不得放行协议面');
6341
+ if (!res || res.kind !== 'deny' || !res.reason.includes('协议文件')) {
6342
+ throw new Error('子代理写协议保护路径应 deny(含协议文件语义): ' + JSON.stringify(res));
6343
+ }
6344
+ }
6345
+ // ⑦i 最小保护集对盘符根拼写(Windows 上 Git-Bash 类 shell 的 `/d/<剩余>` 形态)同样成立:
6346
+ // Bash 命令级写入的目标经既有提取器抽出后按写入目标解析的字面归一处理 ⇒ 与盘符拼写
6347
+ // 同判 deny。归一前该拼写被错解到「当前盘根之下」⇒ 保护集两道判据同时空转(身份放行
6348
+ // 下静默 next = fail-open)。对照 = 同一身份的盘符根拼写源码仍放行(保护集不扩大)。
6349
+ // 该拼写是 Windows 上 Git-Bash 类 shell 的自然产物;非 win32 载体上它是普通 POSIX 绝对
6350
+ // 路径,语义不同 ⇒ 显式不适用(不静默跳过——未验证 ≠ 通过)。
6351
+ const hasDriveRoot = /^[A-Za-z]:[\\/]/.test(longTarget);
6352
+ if (process.platform === 'win32' && hasDriveRoot) {
6353
+ const driveRootSpelling = (p) => '/' + p[0].toLowerCase() + p.slice(2).replaceAll('\\', '/');
6354
+ const spellingCases = [
6355
+ ['机器状态文件', driveRootSpelling(path.join(longTarget, '.flow-comet', 'flow-comet-state.json')), 'state 文件'],
6356
+ ['项目内源码', driveRootSpelling(path.join(longTarget, 'src', 'a.mjs')), null],
6357
+ ];
6358
+ for (const [label, spelled, denyMarker] of spellingCases) {
6359
+ let usedNext = false;
6360
+ const res = await preExec(
6361
+ { name: 'Bash', arguments: { command: 'cp "' + spelled + '" "' + spelled + '"' }, agent: { cwd: longTarget, session: { header: { delegationDepth: 1 } } } },
6362
+ () => { usedNext = true; },
6363
+ );
6364
+ if (denyMarker === null) {
6365
+ if (!usedNext) throw new Error(label + '的盘符根拼写应放行(next)——保护集不得扩大: ' + JSON.stringify(res));
6366
+ continue;
6367
+ }
6368
+ if (usedNext) throw new Error(label + '的盘符根拼写不应 next——身份放行不得放行最小保护集');
6369
+ if (!res || res.kind !== 'deny' || !res.reason.includes(denyMarker)) {
6370
+ throw new Error(label + '的盘符根拼写应 deny(含 ' + denyMarker + ' 语义): ' + JSON.stringify(res));
6371
+ }
6372
+ }
6373
+ console.log(' 盘符根拼写与盘符拼写同判(机器面 deny / 源码放行)✓');
6374
+ } else {
6375
+ console.log(' (盘符根拼写断言显式不适用——非 win32 载体上该拼写是普通 POSIX 绝对路径)');
6376
+ }
6377
+ // ⑦j 桥接通道标记的作用域收紧(同型真实链路格):CC / Codex 生成的 hook **直接**调用守卫、
6378
+ // 不经桥接——同一目标、同一深度值,经桥接 ⇒ 放行(⑦a 已覆盖),绕过桥接直接调守卫
6379
+ // ⇒ 深度变量虽在场也不作数:守卫按协调者语义走白名单 ⇒ deny;同一调用补上通道标记
6380
+ // ⇒ 按键控的身份通道放行(证明判据键在标记上,不是「直接调用一律拦」)。
6381
+ // 反向构造:守卫去掉标记要求 ⇒ 继承形态必红(继承来的深度变量被当成子代理身份 ⇒ 源码写入放行)。
6382
+ {
6383
+ const guardAbs = path.join(longTarget, guardRel);
6384
+ const probeInput = JSON.stringify({
6385
+ tool_name: 'Write',
6386
+ tool_input: { file_path: path.join(longTarget, 'src', 'c.mjs') },
6387
+ });
6388
+ const directEnvs = [
6389
+ ['继承形态(无通道标记)', { FLOW_COMET_AGENT_DEPTH: '1' }, 2],
6390
+ ['通道标记在场', { FLOW_COMET_AGENT_DEPTH: '1', FLOW_COMET_AGENT_DEPTH_SOURCE: 'dsh-bridge' }, 0],
6391
+ ['标记值不符(近形状)', { FLOW_COMET_AGENT_DEPTH: '1', FLOW_COMET_AGENT_DEPTH_SOURCE: 'dsh' }, 2],
6392
+ ];
6393
+ for (const [label, overrides, expected] of directEnvs) {
6394
+ const res = spawnSync(process.execPath, [guardAbs, 'before_tool'], {
6395
+ cwd: longTarget,
6396
+ input: probeInput,
6397
+ env: { ...process.env, ...overrides },
6398
+ encoding: 'utf8',
6399
+ timeout: 60000,
6400
+ });
6401
+ const out = String(res.stdout || '') + String(res.stderr || '');
6402
+ if ((res.status ?? 1) !== expected) {
6403
+ throw new Error('桥接通道标记直接调用格「' + label + '」预期 exit ' + expected
6404
+ + ',实际 exit ' + String(res.status) + ': ' + out.trim().slice(0, 160));
6405
+ }
6406
+ if (expected === 2 && !out.includes('BLOCKED')) {
6407
+ throw new Error('桥接通道标记直接调用格「' + label + '」拦截报文缺 BLOCKED: ' + out.trim().slice(0, 160));
6408
+ }
6409
+ if (expected === 0 && !out.includes('(subagent identity)')) {
6410
+ throw new Error('桥接通道标记直接调用格「' + label + '」应走身份通道放行: ' + out.trim().slice(0, 160));
6411
+ }
6412
+ }
6413
+ console.log(' 桥接通道标记:继承形态按协调者拦 / 标记在场走身份放行 / 近形状标记不认 ✓');
6414
+ }
6415
+ console.log(' bridge.apply 分派集成(子代理放行/协调者拦/越界·形状 deny 不受身份/保护集拦)✓');
5560
6416
  },
5561
6417
  },
5562
6418
 
@@ -6052,10 +6908,14 @@ const TEST_ITEMS = [
6052
6908
  },
6053
6909
  },
6054
6910
 
6055
- // K18: 分发面(npm 包形态)——可发布性清单 + 包体边界 + bin 双入口 + init 词元形态与红线。
6911
+ // K18: 分发面(npm 包形态)——可发布性清单 + 包体边界 + bin 双入口 + init 词元形态与红线
6912
+ // + 安装器升级路径清理(镜像目录内「权威源已不存在」的条目在重装后必须消失:含反向探针
6913
+ // 与幂等断言;`.claude/rules` 一类无命名空间的生成面 fail-closed 不纳入删除面)
6914
+ // + 安装器镜像清理的**根级** fail-closed(镜像根自身为链接 / 真实路径越出项目根两变体:
6915
+ // 项目外文件必不消失 + 保留原因可见 + 幂等 + 反向构造证明判别力)。
6056
6916
  // 权威源侧真跑断言(npm pack --dry-run 的真实产物清单在场才算通过);安装副本侧输出显式
6057
6917
  // 「不适用」行并回传同语义的结果标记计通过(禁止静默跳过——「未验证 ≠ 通过」)。
6058
- // 四组断言见上方同名助手;结果标记由运行器按环境判据断言(distributionSurface 契约)。
6918
+ // 各断言见上方同名助手;结果标记由运行器按环境判据断言(distributionSurface 契约)。
6059
6919
  {
6060
6920
  name: 'K18 分发面:环境判据与包体边界·bin 双入口(权威源真跑/副本显式不适用)与 init 词元红线',
6061
6921
  distributionSurface: true,
@@ -6065,12 +6925,19 @@ const TEST_ITEMS = [
6065
6925
  assertPackageContextJudgment(dir);
6066
6926
  const pkgCtx = resolvePackageContext();
6067
6927
  const marker = DISTRIBUTION_MARKERS[pkgCtx.kind];
6928
+ // 安装器分发面断言(升级路径清理):权威源侧真跑真实命令序列,安装副本侧输出显式
6929
+ // 「不适用」行(两侧都出声——副本侧不是静默跳过);故置于环境分支之前调用。
6930
+ assertInstallerUpgradePathCleanup(dir);
6931
+ // 安装器分发面断言(镜像清理的根级 fail-closed):同一注入点的第二组判据——根自身为链接 /
6932
+ // 真实路径越界两变体 + 反向构造;副本侧同样输出显式「不适用」行。
6933
+ assertMirrorRootLinkFailClosed(dir, pkgCtx);
6068
6934
  if (pkgCtx.kind === 'copy') {
6069
6935
  console.log(' 不适用(安装副本侧:' + pkgCtx.reason + ')——包体边界/bin 断言仅权威源侧可判,本项计通过');
6070
6936
  return marker;
6071
6937
  }
6072
6938
  assertPublishableManifest(pkgCtx.pkg);
6073
6939
  assertPackageBoundary(pkgCtx.root);
6940
+ assertWorkflowContractCheck(dir);
6074
6941
  assertInitTokenContract(assertBinContract(pkgCtx.pkg, pkgCtx.root), dir);
6075
6942
  return marker;
6076
6943
  },