flow-comet 1.6.2 → 1.6.4

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 (107) 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 +266 -25
  12. package/.flow-comet/skills/flow-comet/scripts/context-init.mjs +2 -2
  13. package/.flow-comet/skills/flow-comet/scripts/evolve.mjs +6 -6
  14. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +67 -16325
  15. package/.flow-comet/skills/flow-comet/scripts/health.mjs +1 -1
  16. package/.flow-comet/skills/flow-comet/scripts/items/a.mjs +1030 -0
  17. package/.flow-comet/skills/flow-comet/scripts/items/b.mjs +830 -0
  18. package/.flow-comet/skills/flow-comet/scripts/items/c.mjs +781 -0
  19. package/.flow-comet/skills/flow-comet/scripts/items/d.mjs +99 -0
  20. package/.flow-comet/skills/flow-comet/scripts/items/e.mjs +185 -0
  21. package/.flow-comet/skills/flow-comet/scripts/items/f.mjs +90 -0
  22. package/.flow-comet/skills/flow-comet/scripts/items/g.mjs +59 -0
  23. package/.flow-comet/skills/flow-comet/scripts/items/h.mjs +815 -0
  24. package/.flow-comet/skills/flow-comet/scripts/items/i.mjs +77 -0
  25. package/.flow-comet/skills/flow-comet/scripts/items/j.mjs +75 -0
  26. package/.flow-comet/skills/flow-comet/scripts/items/k.mjs +1427 -0
  27. package/.flow-comet/skills/flow-comet/scripts/items/l.mjs +275 -0
  28. package/.flow-comet/skills/flow-comet/scripts/items/m.mjs +614 -0
  29. package/.flow-comet/skills/flow-comet/scripts/lib/count-derivation.mjs +97 -0
  30. package/.flow-comet/skills/flow-comet/scripts/lib/fix-loop-node.mjs +196 -0
  31. package/.flow-comet/skills/flow-comet/scripts/lib/guard-evidence-gates.mjs +553 -0
  32. package/.flow-comet/skills/flow-comet/scripts/lib/guard-gates.mjs +837 -0
  33. package/.flow-comet/skills/flow-comet/scripts/lib/guard-routing.mjs +404 -0
  34. package/.flow-comet/skills/flow-comet/scripts/lib/guard-state-io.mjs +404 -0
  35. package/.flow-comet/skills/flow-comet/scripts/lib/guard-template-fidelity.mjs +302 -0
  36. package/.flow-comet/skills/flow-comet/scripts/lib/guard-uidesign.mjs +133 -0
  37. package/.flow-comet/skills/flow-comet/scripts/lib/reentry-node.mjs +237 -0
  38. package/.flow-comet/skills/flow-comet/scripts/lib/replan-node.mjs +209 -0
  39. package/.flow-comet/skills/flow-comet/scripts/lib/state-branch.mjs +49 -0
  40. package/.flow-comet/skills/flow-comet/scripts/lib/state-bridgecheck.mjs +201 -0
  41. package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-admin.mjs +141 -0
  42. package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-flow.mjs +700 -0
  43. package/.flow-comet/skills/flow-comet/scripts/lib/state-commands-recovery.mjs +578 -0
  44. package/.flow-comet/skills/flow-comet/scripts/lib/state-determine.mjs +52 -0
  45. package/.flow-comet/skills/flow-comet/scripts/lib/state-evolve-hint.mjs +55 -0
  46. package/.flow-comet/skills/flow-comet/scripts/lib/state-explain.mjs +106 -0
  47. package/.flow-comet/skills/flow-comet/scripts/lib/state-intelscan.mjs +58 -0
  48. package/.flow-comet/skills/flow-comet/scripts/lib/state-io.mjs +147 -0
  49. package/.flow-comet/skills/flow-comet/scripts/lib/state-skillmarkers.mjs +189 -0
  50. package/.flow-comet/skills/flow-comet/scripts/lib/system-fixtures.mjs +1441 -0
  51. package/.flow-comet/skills/flow-comet/scripts/lib/task-graph.mjs +471 -0
  52. package/.flow-comet/skills/flow-comet/scripts/lib/test-assertions.mjs +509 -0
  53. package/.flow-comet/skills/flow-comet/scripts/lib/test-fixtures.mjs +1228 -0
  54. package/.flow-comet/skills/flow-comet/scripts/lib/test-helpers.mjs +237 -0
  55. package/.flow-comet/skills/flow-comet/scripts/lib/text-anchor-checks.mjs +2484 -0
  56. package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +2 -2
  57. package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +73 -1077
  58. package/.flow-comet/skills/flow-comet/scripts/scenarios/a.mjs +966 -0
  59. package/.flow-comet/skills/flow-comet/scripts/scenarios/b.mjs +1233 -0
  60. package/.flow-comet/skills/flow-comet/scripts/scenarios/c.mjs +1382 -0
  61. package/.flow-comet/skills/flow-comet/scripts/scenarios/d.mjs +483 -0
  62. package/.flow-comet/skills/flow-comet/scripts/scenarios/e.mjs +1388 -0
  63. package/.flow-comet/skills/flow-comet/scripts/scenarios/f.mjs +1466 -0
  64. package/.flow-comet/skills/flow-comet/scripts/scenarios/g.mjs +1364 -0
  65. package/.flow-comet/skills/flow-comet/scripts/scenarios/h.mjs +1287 -0
  66. package/.flow-comet/skills/flow-comet/scripts/scenarios/i.mjs +1436 -0
  67. package/.flow-comet/skills/flow-comet/scripts/scenarios/j.mjs +1384 -0
  68. package/.flow-comet/skills/flow-comet/scripts/scenarios/k.mjs +1338 -0
  69. package/.flow-comet/skills/flow-comet/scripts/scenarios/l.mjs +1484 -0
  70. package/.flow-comet/skills/flow-comet/scripts/scenarios/m.mjs +971 -0
  71. package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +14 -1
  72. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +58 -6692
  73. package/.flow-comet/skills/flow-comet/scripts/time-utils.mjs +4 -4
  74. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +151 -2428
  75. package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +116 -9
  76. package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +29 -2086
  77. package/.flow-comet/skills/flow-comet-archive/SKILL.md +10 -19
  78. package/.flow-comet/skills/flow-comet-change/SKILL.md +2 -3
  79. package/.flow-comet/skills/flow-comet-compose/SKILL.md +1 -1
  80. package/.flow-comet/skills/flow-comet-design/SKILL.md +6 -6
  81. package/.flow-comet/skills/flow-comet-execute/SKILL.md +58 -16
  82. package/.flow-comet/skills/flow-comet-integration/SKILL.md +8 -5
  83. package/.flow-comet/skills/flow-comet-open/SKILL.md +5 -1
  84. package/.flow-comet/skills/flow-comet-plan/GUIDANCE.md +1 -1
  85. package/.flow-comet/skills/flow-comet-plan/SKILL.md +8 -8
  86. package/.flow-comet/skills/flow-comet-review/SKILL.md +9 -12
  87. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +59 -16
  88. package/.flow-comet/skills/flow-comet-task/SKILL.md +3 -2
  89. package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +3 -3
  90. package/.flow-comet/skills/flow-comet-verify/SKILL.md +8 -17
  91. package/README.md +53 -70
  92. package/package.json +3 -2
  93. package/scripts/dsh-bridge.mjs +59 -26
  94. package/scripts/lib/installer-cleanup.mjs +152 -0
  95. package/scripts/lib/installer-flowkit.mjs +119 -0
  96. package/scripts/lib/installer-hooks.mjs +363 -0
  97. package/scripts/lib/installer-loader.mjs +220 -0
  98. package/scripts/lib/installer-migrate.mjs +236 -0
  99. package/scripts/lib/installer-platforms.mjs +314 -0
  100. package/scripts/prepare-env.mjs +36 -1164
  101. package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +0 -116
  102. package/.flow-comet/skills/flow-comet/reference/composition-report.md +0 -65
  103. package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +0 -184
  104. package/.flow-comet/skills/flow-comet/reference/resolved-skills.json +0 -661
  105. package/.flow-comet/skills/flow-comet/reference/skill-review.md +0 -13
  106. package/.flow-comet/skills/flow-comet/reference/subagents/script-author.md +0 -7
  107. package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +0 -70
@@ -0,0 +1,1287 @@
1
+ // 场景组 h — 运行时位置迁移 · 感知层剥离 · 自检清单 · hook 双判定 · 迁移错误分类 · BOM 容忍 · purge 时序
2
+ // 元素形态:`{ name, run }`;计数由 `lib/count-derivation.mjs` 从本目录聚合,不手抄数字。
3
+ // 组界按场景名前缀与文件内既有分段划,与入口 `SCENARIOS` 的拼接顺序一致。
4
+
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import { spawnSync } from 'child_process';
8
+ import { scenarioCount } from '../lib/count-derivation.mjs';
9
+ import {
10
+ assertExit,
11
+ assertNotOut,
12
+ assertOut,
13
+ baseState,
14
+ runGuard,
15
+ runHook,
16
+ writeFile,
17
+ writeState,
18
+ } from '../lib/test-helpers.mjs';
19
+ import {
20
+ BUILTIN_PROTOCOL_SOURCE,
21
+ CHANGE_ID,
22
+ GUARD,
23
+ HOOK,
24
+ LEGACY_RUNTIME_DIR,
25
+ MIGRATION_CHANGE,
26
+ PREPARE_ENV,
27
+ REPO_ROOT,
28
+ RUNTIME_DIR,
29
+ RUNTIME_STATE_NAME,
30
+ SCRIPTS_DIR,
31
+ assertGitignoreManaged,
32
+ bridgeIdentityEnv,
33
+ makeTmp,
34
+ migratableStateBytes,
35
+ migrationBackups,
36
+ normalizeRoot,
37
+ runGitignoreForm,
38
+ runInstalled,
39
+ runPrepareEnv,
40
+ writeClassicCometAssets,
41
+ writeIntakeArtifacts,
42
+ writeMigratedProjectArtifacts,
43
+ writeSharedCometDir,
44
+ } from '../lib/test-fixtures.mjs';
45
+ import {
46
+ outputText,
47
+ runStateWithProtocol,
48
+ scenarioProtocolPath,
49
+ } from '../lib/test-assertions.mjs';
50
+ import {
51
+ REFERENCE_FACE_DIR_REL,
52
+ SCENARIO_COUNT_FILES,
53
+ applyPatchAnchorProblems,
54
+ exerciseSystemTestCountCheck,
55
+ scenarioCountSyncProblems,
56
+ staleCountProblems,
57
+ } from '../lib/text-anchor-checks.mjs';
58
+
59
+ export const ENTRIES = [
60
+
61
+ // ---------- 位置迁移 / 备份 / 感知层剥离(真实安装器 + 真实文件系统,端到端执行断言) ----------
62
+
63
+ // AC-1 迁移正例:旧命名空间三方共占(flow-comet 运行时文件 + Comet 资产 + 用户自有文件),
64
+ // 安装器只搬白名单在册的运行时文件——新位置逐字节一致、旧位置移除,其余内容原位不动
65
+ // (不搬迁 / 不删除 / 不改写),且不会被按前缀/模式误搬进新命名空间。
66
+ {
67
+ name: '220 状态迁移白名单:仅运行时文件搬移,Comet 资产与用户文件原位不动(AC-1)',
68
+ run: (dir) => {
69
+ if (!fs.existsSync(PREPARE_ENV)) return; // 安装副本无安装器脚本(与场景 105 同判据)
70
+ const proj = path.join(dir, 'proj');
71
+ const stateBytes = migratableStateBytes();
72
+ const kept = writeSharedCometDir(proj, stateBytes);
73
+ const res = runPrepareEnv(['--target', proj, '--platform', 'claude-code'], dir);
74
+ assertExit(res, 0);
75
+ assertOut(res, '已迁移');
76
+ // ① 新位置落位且逐字节一致
77
+ const newState = path.join(proj, RUNTIME_DIR, RUNTIME_STATE_NAME);
78
+ if (!fs.existsSync(newState)) throw new Error('迁移后新位置状态文件缺失: ' + newState);
79
+ if (!fs.readFileSync(newState).equals(stateBytes)) throw new Error('新位置状态与迁移前不逐字节一致');
80
+ // ② 旧位置运行时文件已移除(搬移语义,非复制)
81
+ if (fs.existsSync(path.join(proj, LEGACY_RUNTIME_DIR, RUNTIME_STATE_NAME))) {
82
+ throw new Error('迁移后旧位置运行时文件应已移除');
83
+ }
84
+ // ③ Comet 资产与用户自有文件原位未动(位置 + 内容都未变)
85
+ for (const item of kept) {
86
+ const target = path.join(proj, LEGACY_RUNTIME_DIR, item.rel);
87
+ if (!fs.existsSync(target)) throw new Error('非白名单内容被搬迁/删除: ' + item.rel);
88
+ if (!fs.readFileSync(target).equals(item.bytes)) throw new Error('非白名单内容被改写: ' + item.rel);
89
+ }
90
+ // ④ 用户自有备份文件未被搬入新命名空间(白名单按精确文件名,不做前缀/模式匹配)
91
+ const leaked = path.join(proj, RUNTIME_DIR, RUNTIME_STATE_NAME + '.bak-20260901-user');
92
+ if (fs.existsSync(leaked)) throw new Error('用户自有文件被搬入新命名空间(白名单过宽): ' + leaked);
93
+ },
94
+ },
95
+
96
+ // AC-15 迁移前备份:备份在迁移动作之前生成于新命名空间,内容与迁移前逐字节一致、命名含
97
+ // 时间戳、迁移成功后仍保留;且仅凭这份备份即可恢复出可用的旧状态(状态文件不进版本控制的
98
+ // 项目没有 git 回滚载体——备份是唯一回退依据)。
99
+ {
100
+ name: '221 迁移前备份:逐字节一致且迁移后保留,可据以恢复旧状态(AC-15)',
101
+ run: (dir) => {
102
+ if (!fs.existsSync(PREPARE_ENV)) return;
103
+ const proj = path.join(dir, 'proj');
104
+ const stateBytes = migratableStateBytes();
105
+ writeSharedCometDir(proj, stateBytes);
106
+ writeMigratedProjectArtifacts(proj);
107
+ const res = runPrepareEnv(['--target', proj, '--platform', 'claude-code'], dir);
108
+ assertExit(res, 0);
109
+ assertOut(res, '迁移前备份');
110
+ // ① 备份恰一份,命名含时间戳(.bak-<ISO 时间戳>)
111
+ const backups = migrationBackups(proj);
112
+ if (backups.length !== 1) throw new Error('迁移应恰生成 1 份备份,实际: ' + JSON.stringify(backups));
113
+ if (!/^flow-comet-state\.json\.bak-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/.test(backups[0])) {
114
+ throw new Error('备份命名非 .bak-<时间戳> 形态: ' + backups[0]);
115
+ }
116
+ // ② 备份与迁移前逐字节一致
117
+ const backupPath = path.join(proj, RUNTIME_DIR, backups[0]);
118
+ if (!fs.readFileSync(backupPath).equals(stateBytes)) throw new Error('备份与迁移前不逐字节一致');
119
+ // ③ 迁移成功后备份仍保留(安装器不读取、不清理)——再跑一次安装后仍应恰一份
120
+ assertExit(runPrepareEnv(['--target', proj, '--platform', 'claude-code'], dir), 0);
121
+ if (migrationBackups(proj).length !== 1) throw new Error('重跑安装后备份应保留且不新增');
122
+ // ④ 仅凭备份即可恢复出可用的旧状态:把备份覆盖回状态文件 → 安装副本读到同一 change/节点
123
+ fs.copyFileSync(backupPath, path.join(proj, RUNTIME_DIR, RUNTIME_STATE_NAME));
124
+ const st = runInstalled(proj, '.claude', 'workflow-state.mjs', ['status']);
125
+ assertExit(st, 0);
126
+ assertOut(st, '"change": "' + MIGRATION_CHANGE + '"');
127
+ assertOut(st, '"currentNode": "design"');
128
+ },
129
+ },
130
+
131
+ // AC-13 边界①:新位置与旧位置同时存在 → 不覆盖任何一方、报错中止(列出两处路径与人工
132
+ // 处置指引),且中止发生在部署与纳管之前(不产生安装产物、不改 gitignore、不生成备份)。
133
+ {
134
+ name: '222 迁移边界 新旧并存:不覆盖任一方,报错中止(AC-13)',
135
+ run: (dir) => {
136
+ if (!fs.existsSync(PREPARE_ENV)) return;
137
+ const proj = path.join(dir, 'proj');
138
+ const oldBytes = migratableStateBytes();
139
+ const newBytes = Buffer.from('{\n "activeChange": "already-migrated"\n}\n', 'utf8');
140
+ writeSharedCometDir(proj, oldBytes);
141
+ const newPath = path.join(proj, RUNTIME_DIR, RUNTIME_STATE_NAME);
142
+ fs.mkdirSync(path.dirname(newPath), { recursive: true });
143
+ fs.writeFileSync(newPath, newBytes);
144
+ const res = runPrepareEnv(['--target', proj, '--platform', 'claude-code'], dir);
145
+ if (res.status === 0) throw new Error('新旧并存应报错中止(exit 非 0),实际 exit 0');
146
+ // 报错须列出两处路径(供人工比对判断),并给出处置指引
147
+ assertOut(res, path.join(proj, LEGACY_RUNTIME_DIR, RUNTIME_STATE_NAME));
148
+ assertOut(res, newPath);
149
+ assertOut(res, '不覆盖任何一方');
150
+ assertOut(res, '重跑安装器');
151
+ // 双方内容都未被改动
152
+ if (!fs.readFileSync(path.join(proj, LEGACY_RUNTIME_DIR, RUNTIME_STATE_NAME)).equals(oldBytes)) {
153
+ throw new Error('旧件被改写');
154
+ }
155
+ if (!fs.readFileSync(newPath).equals(newBytes)) throw new Error('新件被覆盖');
156
+ // 中止于部署/纳管之前
157
+ if (migrationBackups(proj).length !== 0) throw new Error('中止时不应产生备份');
158
+ if (fs.existsSync(path.join(proj, '.claude'))) throw new Error('中止时不应产生安装产物');
159
+ if (fs.existsSync(path.join(proj, '.gitignore'))) throw new Error('中止时不应改写 gitignore');
160
+ },
161
+ },
162
+
163
+ // AC-13 边界②:旧件是符号链接 → 不跟随链接搬移(避免穿越到项目外)、报错中止;
164
+ // 链接本身与链接指向的真实内容都未被改动,新位置不生成文件。
165
+ {
166
+ name: '223 迁移边界 符号链接:不跟随链接搬移,报错中止(AC-13)',
167
+ run: (dir) => {
168
+ if (!fs.existsSync(PREPARE_ENV)) return;
169
+ const proj = path.join(dir, 'proj');
170
+ const outside = path.join(dir, 'outside-real-dir');
171
+ fs.mkdirSync(outside, { recursive: true });
172
+ fs.writeFileSync(path.join(outside, 'real.txt'), 'real\n');
173
+ fs.mkdirSync(path.join(proj, LEGACY_RUNTIME_DIR), { recursive: true });
174
+ const linkPath = path.join(proj, LEGACY_RUNTIME_DIR, RUNTIME_STATE_NAME);
175
+ // 受限形态如实声明:Windows 无文件符号链接权限(EPERM)时用目录 junction——判定走同一
176
+ // isSymbolicLink() 分支;两种链接都建不出来时显式跳过(不静默冒充已覆盖)
177
+ let linkForm = 'junction';
178
+ try {
179
+ fs.symlinkSync(outside, linkPath, process.platform === 'win32' ? 'junction' : 'dir');
180
+ } catch (e1) {
181
+ linkForm = 'file-symlink';
182
+ try {
183
+ fs.symlinkSync(outside, linkPath, 'file');
184
+ } catch (e2) {
185
+ console.log(' (本机无创建链接的权限,跳过符号链接夹具——' + (e2.code || e2.message) + ')');
186
+ return;
187
+ }
188
+ }
189
+ const res = runPrepareEnv(['--target', proj, '--platform', 'claude-code'], dir);
190
+ if (res.status === 0) throw new Error('符号链接旧件应报错中止(exit 非 0),实际 exit 0(形态=' + linkForm + ')');
191
+ assertOut(res, '符号链接');
192
+ assertOut(res, '不跟随');
193
+ if (!fs.lstatSync(linkPath).isSymbolicLink()) throw new Error('链接本身被改动(不再是链接)');
194
+ if (!fs.readFileSync(path.join(outside, 'real.txt')).equals(Buffer.from('real\n', 'utf8'))) {
195
+ throw new Error('链接指向的真实内容被改动');
196
+ }
197
+ if (fs.existsSync(path.join(proj, RUNTIME_DIR, RUNTIME_STATE_NAME))) throw new Error('新位置不应生成文件');
198
+ if (fs.existsSync(path.join(proj, '.claude'))) throw new Error('中止时不应产生安装产物');
199
+ },
200
+ },
201
+
202
+ // AC-13 边界③:旧件内容损坏(JSON 解析失败)→ 保留原件未改动、报错中止并给修复指引;
203
+ // 中止发生在写入之前(新位置不生成文件、不产生备份)。
204
+ {
205
+ name: '224 迁移边界 JSON 损坏:保留原件报错中止(AC-13)',
206
+ run: (dir) => {
207
+ if (!fs.existsSync(PREPARE_ENV)) return;
208
+ const proj = path.join(dir, 'proj');
209
+ const broken = Buffer.from('{ "activeChange": \n', 'utf8');
210
+ fs.mkdirSync(path.join(proj, LEGACY_RUNTIME_DIR), { recursive: true });
211
+ fs.writeFileSync(path.join(proj, LEGACY_RUNTIME_DIR, RUNTIME_STATE_NAME), broken);
212
+ const res = runPrepareEnv(['--target', proj, '--platform', 'claude-code'], dir);
213
+ if (res.status === 0) throw new Error('损坏状态应报错中止(exit 非 0),实际 exit 0');
214
+ assertOut(res, '不是合法 JSON');
215
+ assertOut(res, '保留原件');
216
+ if (!fs.readFileSync(path.join(proj, LEGACY_RUNTIME_DIR, RUNTIME_STATE_NAME)).equals(broken)) {
217
+ throw new Error('损坏原件被改写');
218
+ }
219
+ if (fs.existsSync(path.join(proj, RUNTIME_DIR, RUNTIME_STATE_NAME))) throw new Error('新位置不应生成文件');
220
+ if (migrationBackups(proj).length !== 0) throw new Error('中止于写入之前,不应产生备份');
221
+ if (fs.existsSync(path.join(proj, '.claude'))) throw new Error('中止时不应产生安装产物');
222
+ },
223
+ },
224
+
225
+ // AC-7 迁移失败不丢数据:迁移目标不可建立(路径异常——目标目录位置被普通文件占用)时,
226
+ // 旧文件完整保留、报错并给出恢复指引,不删除任何既有内容。
227
+ {
228
+ name: '225 迁移失败保护:目标不可建立时旧文件完整保留(AC-7)',
229
+ run: (dir) => {
230
+ if (!fs.existsSync(PREPARE_ENV)) return;
231
+ const proj = path.join(dir, 'proj');
232
+ const stateBytes = migratableStateBytes();
233
+ writeSharedCometDir(proj, stateBytes);
234
+ const occupied = path.join(proj, RUNTIME_DIR);
235
+ fs.writeFileSync(occupied, 'occupied\n'); // 目标目录位置被普通文件占用(确定性的路径异常形态)
236
+ const res = runPrepareEnv(['--target', proj, '--platform', 'claude-code'], dir);
237
+ if (res.status === 0) throw new Error('迁移目标不可建立应报错中止(exit 非 0),实际 exit 0');
238
+ assertOut(res, '旧文件完整保留');
239
+ assertOut(res, '重跑安装器');
240
+ if (!fs.readFileSync(path.join(proj, LEGACY_RUNTIME_DIR, RUNTIME_STATE_NAME)).equals(stateBytes)) {
241
+ throw new Error('失败路径下旧文件被改写');
242
+ }
243
+ if (!fs.lstatSync(occupied).isFile()) throw new Error('占位文件被改动(既有内容不得被处置)');
244
+ if (fs.existsSync(path.join(proj, '.claude'))) throw new Error('中止时不应产生安装产物');
245
+ },
246
+ },
247
+
248
+ // AC-8 gitignore 形态①(逐条路径):既有条目一律保留原样(不"更新"为新路径),仅缺失时
249
+ // 追加新命名空间条目;连续两次安装不产生重复行;追加内容沿用既有行尾风格。
250
+ {
251
+ name: '226 gitignore 纳管 逐条路径形态:既有条目保留 + 追加幂等(AC-8)',
252
+ run: (dir) => {
253
+ if (!fs.existsSync(PREPARE_ENV)) return;
254
+ const proj = path.join(dir, 'proj');
255
+ fs.mkdirSync(path.join(proj, LEGACY_RUNTIME_DIR, 'runs'), { recursive: true }); // Comet 资产在场
256
+ fs.writeFileSync(path.join(proj, LEGACY_RUNTIME_DIR, 'runs', 'run-001.json'), '{"comet":true}\n');
257
+ const legacyLine = LEGACY_RUNTIME_DIR + '/' + RUNTIME_STATE_NAME;
258
+ const initial = legacyLine + '\r\nnode_modules/\r\n# user note\r\n*.bak-*\r\n';
259
+ const result = runGitignoreForm(dir, proj, initial);
260
+ assertGitignoreManaged(result);
261
+ if (!result.afterFirst.startsWith(initial)) {
262
+ throw new Error('既有内容未逐字保留:\n' + JSON.stringify(result.afterFirst));
263
+ }
264
+ if (!result.afterFirst.split(/\r?\n/).includes(legacyLine)) {
265
+ throw new Error('既有逐条路径条目被改写/删除: ' + legacyLine);
266
+ }
267
+ const appended = result.afterFirst.slice(initial.length);
268
+ if (!appended.includes('\r\n') || /(^|[^\r])\n/.test(appended)) {
269
+ throw new Error('追加内容未沿用既有行尾风格(CRLF): ' + JSON.stringify(appended));
270
+ }
271
+ },
272
+ },
273
+
274
+ // AC-8 gitignore 形态②(整目录 .comet/):整目录条目原样保留——该目录中仍有 Comet 资产,
275
+ // 改写会误伤用户对它们的忽略意图;同样只追加缺失的新命名空间条目且幂等。
276
+ {
277
+ name: '227 gitignore 纳管 整目录形态:既有条目保留 + 追加幂等(AC-8)',
278
+ run: (dir) => {
279
+ if (!fs.existsSync(PREPARE_ENV)) return;
280
+ const proj = path.join(dir, 'proj');
281
+ fs.mkdirSync(path.join(proj, LEGACY_RUNTIME_DIR, 'runs'), { recursive: true });
282
+ fs.writeFileSync(path.join(proj, LEGACY_RUNTIME_DIR, 'runs', 'run-001.json'), '{"comet":true}\n');
283
+ const initial = LEGACY_RUNTIME_DIR + '/\nnode_modules/\n# user note\n';
284
+ const result = runGitignoreForm(dir, proj, initial);
285
+ assertGitignoreManaged(result);
286
+ if (!result.afterFirst.startsWith(initial)) {
287
+ throw new Error('既有内容未逐字保留:\n' + JSON.stringify(result.afterFirst));
288
+ }
289
+ if (!result.afterFirst.split(/\r?\n/).includes(LEGACY_RUNTIME_DIR + '/')) {
290
+ throw new Error('整目录既有条目被改写/删除: ' + LEGACY_RUNTIME_DIR + '/');
291
+ }
292
+ const appended = result.afterFirst.slice(initial.length);
293
+ if (appended.includes('\r\n')) throw new Error('追加内容引入了 CRLF(既有为 LF): ' + JSON.stringify(appended));
294
+ },
295
+ },
296
+
297
+ // AC-8 gitignore 形态③(完全无条目):用户其他内容(无关行 / 注释 / 无末行换行)不被改写,
298
+ // 仅追加缺失条目且连续两次安装逐字节不变。
299
+ {
300
+ name: '228 gitignore 纳管 无条目形态:用户内容原样保留 + 追加幂等(AC-8)',
301
+ run: (dir) => {
302
+ if (!fs.existsSync(PREPARE_ENV)) return;
303
+ const proj = path.join(dir, 'proj');
304
+ fs.mkdirSync(proj, { recursive: true });
305
+ const initial = 'node_modules/\n# keep\n*.log'; // 末行无换行——追加不得粘接到用户行上
306
+ const result = runGitignoreForm(dir, proj, initial);
307
+ assertGitignoreManaged(result);
308
+ if (!result.afterFirst.startsWith(initial)) {
309
+ throw new Error('既有内容未逐字保留:\n' + JSON.stringify(result.afterFirst));
310
+ }
311
+ if (!/^\*\.log$/m.test(result.afterFirst)) throw new Error('用户末行被改写/粘接: ' + JSON.stringify(result.afterFirst));
312
+ },
313
+ },
314
+
315
+ // AC-5 剥离①:同一运行中 workflow 下,Comet classic 资产(.comet/config.yaml + classic
316
+ // change 目录 + overlay 证据)在场与缺席时,hook 与 guard 的判定(退出码 + 归一化输出)
317
+ // 完全一致——判定与这些文件是否存在无关;判定本身非空洞(hook 拦越权写源码 / guard 放行合规出口)。
318
+ {
319
+ name: '229 感知层剥离:classic 资产有无不改变 hook 与 guard 判定(AC-5)',
320
+ run: (dir) => {
321
+ const builtin = scenarioProtocolPath(dir);
322
+ const build = (name, withClassic) => {
323
+ const proj = path.join(dir, name);
324
+ fs.mkdirSync(path.join(proj, 'reference'), { recursive: true });
325
+ fs.copyFileSync(builtin, path.join(proj, 'reference', 'workflow-protocol.json'));
326
+ writeIntakeArtifacts(proj);
327
+ const st = baseState('open');
328
+ st.status = 'running';
329
+ st.evidence.open = { summary: 'intake complete' };
330
+ writeState(proj, st);
331
+ if (withClassic) writeClassicCometAssets(proj);
332
+ return proj;
333
+ };
334
+ const judge = (proj) => ({
335
+ hook: runHook(['before_tool'], proj,
336
+ { tool_name: 'Write', tool_input: { file_path: path.join(proj, 'src', 'evil.mjs') } }),
337
+ guard: runGuard(['exit', 'open'], proj),
338
+ });
339
+ const withClassic = build('with-classic', true);
340
+ const withoutClassic = build('without-classic', false);
341
+ const a = judge(withClassic);
342
+ const b = judge(withoutClassic);
343
+ // 判定非空洞:运行中 workflow 越权写源码被拦;合规出口放行
344
+ assertExit(a.hook, 2);
345
+ assertOut(a.hook, 'BLOCKED');
346
+ assertExit(a.guard, 0);
347
+ assertOut(a.guard, 'ALL CHECKS PASSED');
348
+ // 一致性:退出码 + 归一化输出逐字相同(路径差异抹除后)
349
+ const norm = (res, proj) => normalizeRoot(outputText(res), proj, dir);
350
+ if (a.hook.status !== b.hook.status || norm(a.hook, withClassic) !== norm(b.hook, withoutClassic)) {
351
+ throw new Error('hook 判定随 classic 资产变化(感知层未剥离干净):\n' +
352
+ JSON.stringify({ withClassic: norm(a.hook, withClassic), withoutClassic: norm(b.hook, withoutClassic) }, null, 2));
353
+ }
354
+ if (a.guard.status !== b.guard.status || norm(a.guard, withClassic) !== norm(b.guard, withoutClassic)) {
355
+ throw new Error('guard 判定随 classic 资产变化(感知层未剥离干净):\n' +
356
+ JSON.stringify({ withClassic: norm(a.guard, withClassic), withoutClassic: norm(b.guard, withoutClassic) }, null, 2));
357
+ }
358
+ },
359
+ },
360
+
361
+ // AC-5 剥离②:kind 为 comet-five-phase-overlay 的协议不再进入叠加分支——与同节点、
362
+ // kind=workflow-kernel 的协议在完全相同的夹具(含 classic 活动 change)上判定一致;
363
+ // 叠加分支的专属信号(无活动 Comet change / 多 Comet change)不再出现;
364
+ // 另做源码符号检索,确认感知层符号在判定脚本中零残留。
365
+ {
366
+ name: '230 感知层剥离:overlay 协议不再进入叠加分支(AC-5)',
367
+ run: (dir) => {
368
+ const builtinProtocol = JSON.parse(fs.readFileSync(BUILTIN_PROTOCOL_SOURCE, 'utf8'));
369
+ const build = (name, kind) => {
370
+ const proj = path.join(dir, name);
371
+ const protocol = JSON.parse(JSON.stringify(builtinProtocol));
372
+ protocol.kind = kind;
373
+ fs.mkdirSync(path.join(proj, 'reference'), { recursive: true });
374
+ fs.copyFileSync(scenarioProtocolPath(dir), path.join(proj, 'reference', 'workflow-protocol.json'));
375
+ writeFile(proj, 'overlay-protocol.json', JSON.stringify(protocol, null, 2) + '\n');
376
+ writeIntakeArtifacts(proj);
377
+ const st = baseState('open');
378
+ st.status = 'running';
379
+ st.evidence.open = { summary: 'intake complete' };
380
+ writeState(proj, st);
381
+ writeClassicCometAssets(proj); // 叠加分支的前置(classic 活动 change)在场
382
+ return proj;
383
+ };
384
+ const overlayProj = build('overlay-kind', 'comet-five-phase-overlay');
385
+ const kernelProj = build('kernel-kind', 'workflow-kernel');
386
+ const runExit = (proj) => runGuard(['exit', 'open', '--protocol', path.join(proj, 'overlay-protocol.json')], proj);
387
+ const a = runExit(overlayProj);
388
+ const b = runExit(kernelProj);
389
+ assertExit(a, 0);
390
+ assertOut(a, 'ALL CHECKS PASSED');
391
+ assertNotOut(a, 'active Comet change');
392
+ if (a.status !== b.status
393
+ || normalizeRoot(outputText(a), overlayProj, dir) !== normalizeRoot(outputText(b), kernelProj, dir)) {
394
+ throw new Error('overlay 协议与同节点 kernel 协议判定不一致(叠加分支未剥离):\n' +
395
+ JSON.stringify({ overlay: normalizeRoot(outputText(a), overlayProj, dir), kernel: normalizeRoot(outputText(b), kernelProj, dir) }, null, 2));
396
+ }
397
+ // 源码符号检索:感知层符号在判定脚本中零残留
398
+ const SYMBOLS = [
399
+ 'isCometOverlay', 'comet-five-phase-overlay', 'resolveCometOverlayChange',
400
+ 'activeCometChanges', 'overlayNodeFromState', 'hasOverlayEvidence',
401
+ 'readWorkflowProjectPathConfig', 'workflowPathBaseRoot',
402
+ ];
403
+ for (const [label, file] of [['workflow-guard.mjs', GUARD], ['comet-hook-guard.mjs', HOOK]]) {
404
+ const src = fs.readFileSync(file, 'utf8');
405
+ for (const symbol of SYMBOLS) {
406
+ if (src.includes(symbol)) throw new Error(label + ' 仍含 Comet 感知层符号: ' + symbol);
407
+ }
408
+ }
409
+ },
410
+ },
411
+
412
+ // AC-14 自检清单有效性:条目齐备且同步 → 零问题;条目缺失 → 显式报告(含文件名),
413
+ // 不得静默跳过("永不生效的条目"无处藏身);条目在场但计数未同步 → 同样上报。
414
+ // 用真实清单常量与真实文件系统驱动自检实现(受检根替换为场景临时目录)。
415
+ // ③ 起为系统测试集项数受检面(与场景数面同构,判据同一)。
416
+ {
417
+ name: '231 自检清单:条目缺失被显式报告而非静默跳过(AC-14)',
418
+ run: async (dir) => {
419
+ const n = 7; // 夹具自定场景数(受检文件内容与之一致)
420
+ // 当前场景数经计数派生通道取(与入口 runner 打印的 scenarioTotal 同源:同一批组文件)
421
+ const scenarioTotal = await scenarioCount();
422
+ const synced = 'ALL ' + n + ' SCENARIOS PASSED\n';
423
+ for (const rel of SCENARIO_COUNT_FILES) writeFile(dir, rel, synced);
424
+ const clean = scenarioCountSyncProblems(n, dir);
425
+ if (clean.length !== 0) throw new Error('条目齐备且同步时不应报告问题: ' + JSON.stringify(clean));
426
+ // ① 移走一个条目(幽灵条目形态)→ 显式报告缺失项(列出文件名)
427
+ const missingRel = 'docs/VERSIONS-zh.md';
428
+ if (!SCENARIO_COUNT_FILES.includes(missingRel)) throw new Error('夹具前提失效:' + missingRel + ' 不在受检清单内');
429
+ fs.rmSync(path.join(dir, missingRel));
430
+ const problems = scenarioCountSyncProblems(n, dir);
431
+ if (!problems.some((p) => p.includes('缺失') && p.includes(missingRel))) {
432
+ throw new Error('缺失条目未被显式报告: ' + JSON.stringify(problems));
433
+ }
434
+ // ② 条目在场但场景数未同步 → 同样上报(缺省放过即为静默失检)
435
+ writeFile(dir, missingRel, '未同步的内容\n');
436
+ const stale = scenarioCountSyncProblems(n, dir).join(' | ');
437
+ if (!stale.includes('未同步') || !stale.includes(missingRel)) {
438
+ throw new Error('未同步条目未被上报: ' + stale);
439
+ }
440
+ // ③ 系统测试集项数受检面:组文件派生 + 缺失 / 未同步 / 组判定 / 派生源缺失全分支
441
+ await exerciseSystemTestCountCheck(dir);
442
+ // ④ stale 检测(presence 之外的判别力):在场 ≠ 同步——旧值不在场才是同步的另一半。
443
+ // 受检面 = 维护者面(docs/internal/ 全册 + CLAUDE.md)+ 参考册(reference/*.md,路径从本
444
+ // 脚本自身位置推导);夹具用独立临时根驱动(夹具根下参考册缺席 → 该面为空,不误红)。
445
+ const staleRoot = makeTmp();
446
+ writeFile(staleRoot, 'docs/internal/DOC.md',
447
+ '当前 ' + scenarioTotal + ' 场景 全部通过。\n');
448
+ writeFile(staleRoot, 'CLAUDE.md', '回归基线:ALL ' + scenarioTotal + ' SCENARIOS PASSED\n');
449
+ if (staleCountProblems([scenarioTotal, 86], staleRoot).length !== 0) {
450
+ throw new Error('当前值不得被判成旧值: ' + JSON.stringify(staleCountProblems([scenarioTotal, 86], staleRoot)));
451
+ }
452
+ // 反例(旧 presence 判据必然放过:当前值在场即全绿,旁边的旧值不可见)
453
+ writeFile(staleRoot, 'docs/internal/DOC.md', '当前 ' + scenarioTotal + ' 场景;另有 120 场景 的记录。\n');
454
+ const staleOld = staleCountProblems([scenarioTotal, 86], staleRoot);
455
+ if (!(staleOld.some((p) => p.includes('旧值未标记') && p.includes('docs/internal/DOC.md:1')
456
+ && p.includes('120')))) {
457
+ throw new Error('无标记旧值未被报告(应含文件:行 + 旧值): ' + JSON.stringify(staleOld));
458
+ }
459
+ // 历史标记豁免:已标注的历史值不是"未标记旧值"(四枚标记各取一例——标记清单本身也受锚)
460
+ for (const marked of ['(历史)120 场景。\n', '该值 120 场景 已过时。\n', '回顾:120 场景(history)。\n',
461
+ '本轮踩坑:模板里写过 120 场景。\n']) {
462
+ writeFile(staleRoot, 'docs/internal/DOC.md', marked);
463
+ if (staleCountProblems([scenarioTotal, 86], staleRoot).length !== 0) {
464
+ throw new Error('带历史标记的行不得报告: ' + JSON.stringify([marked, staleCountProblems([scenarioTotal, 86], staleRoot)]));
465
+ }
466
+ }
467
+ // 量程门:30 以下 / 400 以上不参与(年份、编号一类数字挡在外面)
468
+ writeFile(staleRoot, 'docs/internal/DOC.md', '夹具 7 场景 与 9999 场景。\n');
469
+ if (staleCountProblems([scenarioTotal, 86], staleRoot).length !== 0) {
470
+ throw new Error('量程外的数字不得参与: ' + JSON.stringify(staleCountProblems([scenarioTotal, 86], staleRoot)));
471
+ }
472
+ // 通用比值门控:同行未点名套件的 N/N 不参与(覆盖率一类通用比值不误伤);点名套件才判
473
+ writeFile(staleRoot, 'docs/internal/DOC.md', '覆盖率 120/120。\n');
474
+ if (staleCountProblems([scenarioTotal, 86], staleRoot).length !== 0) {
475
+ throw new Error('同行未点名套件的通用比值不得参与: ' + JSON.stringify(staleCountProblems([scenarioTotal, 86], staleRoot)));
476
+ }
477
+ writeFile(staleRoot, 'docs/internal/DOC.md', 'guard-self-test 覆盖率 120/120。\n');
478
+ if (!staleCountProblems([scenarioTotal, 86], staleRoot).some((p) => p.includes('旧值未标记') && p.includes('120/120'))) {
479
+ throw new Error('点名套件的旧比值未被报告: ' + JSON.stringify(staleCountProblems([scenarioTotal, 86], staleRoot)));
480
+ }
481
+ writeFile(staleRoot, 'docs/internal/DOC.md', 'guard-self-test 覆盖率 120/121。\n');
482
+ if (staleCountProblems([scenarioTotal, 86], staleRoot).length !== 0) {
483
+ throw new Error('非等值比值不是计数形态(不得参与): ' + JSON.stringify(staleCountProblems([scenarioTotal, 86], staleRoot)));
484
+ }
485
+ // 声明的 CLAUDE.md 形态:维护者面逐册纳入(夹具根下 CLAUDE.md 在场即入面)
486
+ writeFile(staleRoot, 'CLAUDE.md', '自检套件 120 场景。\n');
487
+ if (!staleCountProblems([scenarioTotal, 86], staleRoot).some((p) => p.includes('CLAUDE.md:1') && p.includes('旧值未标记'))) {
488
+ throw new Error('CLAUDE.md 未纳入 stale 受检面: ' + JSON.stringify(staleCountProblems([scenarioTotal, 86], staleRoot)));
489
+ }
490
+ // 读取失败可见化:与维护文档机检同型(同名目录 → 读取错误,不得静默跳过)
491
+ fs.mkdirSync(path.join(staleRoot, 'docs', 'internal', 'DIR.md'), { recursive: true });
492
+ if (!staleCountProblems([scenarioTotal, 86], staleRoot).some((p) => p.includes('无法读取: docs/internal/DIR.md'))) {
493
+ throw new Error('stale 受检面里的不可读目标被静默跳过: ' + JSON.stringify(staleCountProblems([scenarioTotal, 86], staleRoot)));
494
+ }
495
+ fs.rmSync(staleRoot, { recursive: true, force: true }); // 夹具根清理(残留目录由底部统一校验)
496
+ // ⑤ 面路径的推导纪律锚(同类断言回扫):参考册受检面必须**从本脚本自身位置**推导——
497
+ // 权威源(.flow-comet/skills)与各安装副本(.claude / .agents / .dsh/skills)同一推导
498
+ // 覆盖;硬编码树根相对路径会在安装副本形态指向不存在的面(静默空面 = 未执行当通过)。
499
+ if (path.resolve(REPO_ROOT, REFERENCE_FACE_DIR_REL) !== path.resolve(SCRIPTS_DIR, '..', 'reference')) {
500
+ throw new Error('参考册受检面必须由脚本自身位置推导(不得硬编码树根相对路径),实际: ' + REFERENCE_FACE_DIR_REL);
501
+ }
502
+ if (path.basename(REFERENCE_FACE_DIR_REL) !== 'reference') {
503
+ throw new Error('参考册受检面路径异常: ' + REFERENCE_FACE_DIR_REL);
504
+ }
505
+ },
506
+ },
507
+
508
+ // ---------- hook 双判定路径 / 迁移错误分类 / BOM / purge 时序 ----------
509
+
510
+ // 232: worktree 隔离区放行的判定路径一致性——放行分支此前只挂在 file_path 判定处
511
+ // (Bash 分支先执行并直接按协调者白名单判定),同一路径用 Write/Edit 放行、用 Bash
512
+ // 重定向写却被拦(判定随工具而变)。修复后两条判定共用同一隔离区判据——同路径同结论。
513
+ // 穿越形态(`..` 逃出隔离区)在两条路径上都必须仍被拦截:放行不是无条件的。
514
+ // ④ 追加(物理包含性):隔离区**内**指向区外的符号链接/junction 是同一前缀下的第二种逃逸——
515
+ // 词法归一化对它无能为力(路径字符串确实以隔离区前缀开头),必须按真实落点判定。
516
+ {
517
+ name: '232 hook 判定一致性:worktree 放行双分支一致 + 穿越仍拦 + 身份三态 × 桥接标记在场判据 × 最小保护集 + runRoot 外对称',
518
+ run: (dir) => {
519
+ writeState(dir, { ...baseState('subagent-execute'), status: 'running' });
520
+ const insideWorktree = path.join(dir, '.claude', 'worktrees', 'agent-abc123', 'src', 'x.mjs');
521
+ const posix = (p) => p.split(path.sep).join('/');
522
+ // ① file_path 判定:隔离区内写入放行(既有行为,防回归)
523
+ const viaWrite = runHook(['before_tool'], dir,
524
+ { tool_name: 'Write', tool_input: { file_path: insideWorktree } });
525
+ assertExit(viaWrite, 0);
526
+ assertOut(viaWrite, 'workflow-hook-guard-ok');
527
+ // ② Bash 判定:同一路径的命令级写入同样放行(修复前按协调者白名单拦截 → RED)
528
+ const viaBash = runHook(['before_tool'], dir,
529
+ { tool_name: 'Bash', tool_input: { command: 'echo x > "' + posix(insideWorktree) + '"' } });
530
+ assertExit(viaBash, 0);
531
+ assertOut(viaBash, 'workflow-hook-guard-ok');
532
+ // ③ 穿越形态:`..` 归一化后逃出隔离区 → 两条判定都仍拦截
533
+ const escape = posix(path.join(dir, '.claude', 'worktrees', 'agent-abc123'))
534
+ + '/../../src/evil.mjs';
535
+ const viaWriteEscape = runHook(['before_tool'], dir,
536
+ { tool_name: 'Write', tool_input: { file_path: escape } });
537
+ assertExit(viaWriteEscape, 2);
538
+ assertOut(viaWriteEscape, 'BLOCKED');
539
+ const viaBashEscape = runHook(['before_tool'], dir,
540
+ { tool_name: 'Bash', tool_input: { command: 'echo x > "' + escape + '"' } });
541
+ assertExit(viaBashEscape, 2);
542
+ assertOut(viaBashEscape, 'BLOCKED');
543
+ // ④ 物理包含性:隔离区**内**指向区外的符号链接/junction——词法上仍以 `.claude/worktrees/`
544
+ // 开头,真实落点却在隔离区外。放行先于各自的白名单判定返回,故放行这类路径等于
545
+ // 没有任何后续校验兜底 → 两条判定都必须拦截(修复前按词法放行 = RED)。
546
+ // Windows 用 junction(建 junction 不需要符号链接特权,与真实环境权限无关);
547
+ // POSIX 用目录符号链接;平台确实无法构造链接时按下方 ⑤ 的兜底断言如实降级。
548
+ const outsideDir = path.join(dir, 'outside-zone');
549
+ fs.mkdirSync(outsideDir, { recursive: true });
550
+ const agentDir = path.join(dir, '.claude', 'worktrees', 'agent-abc123');
551
+ fs.mkdirSync(agentDir, { recursive: true });
552
+ let linkCreated = false;
553
+ try {
554
+ fs.symlinkSync(outsideDir, path.join(agentDir, 'link'),
555
+ process.platform === 'win32' ? 'junction' : 'dir');
556
+ linkCreated = true;
557
+ } catch { linkCreated = false; }
558
+ if (!linkCreated) {
559
+ console.error('WARN: 当前平台无法构造符号链接/junction,隔离区链接逃逸断言降级为兜底断言');
560
+ }
561
+ if (linkCreated) {
562
+ const escaping = posix(path.join(agentDir, 'link', 'evil.mjs'));
563
+ const viaWriteLink = runHook(['before_tool'], dir,
564
+ { tool_name: 'Write', tool_input: { file_path: escaping } });
565
+ assertExit(viaWriteLink, 2);
566
+ assertOut(viaWriteLink, 'BLOCKED');
567
+ const viaBashLink = runHook(['before_tool'], dir,
568
+ { tool_name: 'Bash', tool_input: { command: 'echo x > "' + escaping + '"' } });
569
+ assertExit(viaBashLink, 2);
570
+ assertOut(viaBashLink, 'BLOCKED');
571
+ }
572
+ // ⑤ 放行不得过宽:链接**旁**的真实隔离区路径仍须放行(把整个隔离区一并拦掉同样是回归),
573
+ // 非隔离区路径仍按原逻辑判定(协调者白名单拦截)。
574
+ const viaWriteNormal = runHook(['before_tool'], dir,
575
+ { tool_name: 'Write', tool_input: { file_path: path.join(agentDir, 'src', 'y.mjs') } });
576
+ assertExit(viaWriteNormal, 0);
577
+ assertOut(viaWriteNormal, 'workflow-hook-guard-ok');
578
+ const viaWriteOutside = runHook(['before_tool'], dir,
579
+ { tool_name: 'Write', tool_input: { file_path: path.join(dir, 'src', 'evil.mjs') } });
580
+ assertExit(viaWriteOutside, 2);
581
+ assertOut(viaWriteOutside, 'BLOCKED');
582
+
583
+ // ---------- in-place 扩展:身份分派 × 最小保护集 × 顺序锚 × 两分支对称 ----------
584
+ // ⑥ 身份三态(子代理语义的增量通道):载荷 agent_id 在场(CC / Codex 原生子代理的载荷形态)
585
+ // 或环境变量身份深度为正整数(dsh 桥接透传)⇒ 子代理语义放行;两者皆缺(主线程)⇒
586
+ // 维持既有路径判定——新判据是增量通道,不是对旧语义的替换(不放宽也不误拦)。
587
+ // 反向构造:把身份短路回退成纯路径判定 ⇒ ⑥a / ⑥c / ⑦a / ⑦c 必红(判别力见交付证据)。
588
+ const whitelistOutside = path.join(dir, 'src', 'foo.mjs');
589
+ const identityPayload = (extra) => ({
590
+ tool_name: 'Write',
591
+ tool_input: { file_path: whitelistOutside },
592
+ ...extra,
593
+ });
594
+ // ⑥a 含 agent_id(子代理)⇒ 放行(路径在协调者白名单之外,身份未短路时必 BLOCK ⇒ RED)
595
+ const viaAgentId = runHook(['before_tool'], dir, identityPayload({ agent_id: 'agent-abc123' }));
596
+ assertExit(viaAgentId, 0);
597
+ assertOut(viaAgentId, 'workflow-hook-guard-ok');
598
+ assertOut(viaAgentId, '(subagent identity)');
599
+ // ⑥b 不含 agent_id(主线程)⇒ 维持既有路径判定:白名单外源码仍 BLOCK
600
+ const viaMainThread = runHook(['before_tool'], dir, identityPayload({}));
601
+ assertExit(viaMainThread, 2);
602
+ assertOut(viaMainThread, 'BLOCKED');
603
+ // ⑥c dsh 桥接身份透传(环境变量正整数 + 桥接通道标记)⇒ 与载荷面归并为同一判据 ⇒ 放行
604
+ const viaDepth = runHook(['before_tool'], dir, identityPayload({}), bridgeIdentityEnv('1'));
605
+ assertExit(viaDepth, 0);
606
+ assertOut(viaDepth, '(subagent identity)');
607
+ // ⑥c2 env 面作用域收紧:**只有深度变量在场、桥接通道标记不在场** ⇒ 按协调者语义(白名单外
608
+ // 源码仍 BLOCK)——CC / Codex 生成的 hook 直接调用本文件、并不自证是桥接,继承来的深度
609
+ // 变量不得据此走子代理路径(否则守卫在 phase / worktree / runRoot 检查之前就返回)。
610
+ // 反向构造:守卫去掉标记要求 ⇒ ⑥c2 必红(同载荷被误判为子代理而放行)。
611
+ for (const inheritedDepth of ['1', '2', '9']) {
612
+ const inherited = runHook(['before_tool'], dir, identityPayload({}), { FLOW_COMET_AGENT_DEPTH: inheritedDepth });
613
+ assertExit(inherited, 2);
614
+ assertOut(inherited, 'BLOCKED');
615
+ assertNotOut(inherited, '(subagent identity)');
616
+ }
617
+ // ⑥c3 标记形态收窄(fail-closed):值不符 / 大小写变体 / 空白变体 / 空串 / 非桥接来源一律不算
618
+ for (const marker of ['', ' ', 'dsh', 'DSH-BRIDGE', 'Dsh-Bridge', 'dsh-bridge ', ' dsh-bridge', 'bridged']) {
619
+ const res = runHook(['before_tool'], dir, identityPayload({}),
620
+ { FLOW_COMET_AGENT_DEPTH: '1', FLOW_COMET_AGENT_DEPTH_SOURCE: marker });
621
+ assertExit(res, 2);
622
+ assertOut(res, 'BLOCKED');
623
+ }
624
+ // ⑥c4 标记在场但深度非法 ⇒ 仍非身份(两条判据都闭合:标记只证明通道,不代替取值形态收窄)
625
+ for (const raw of ['0', '', 'abc', '-1']) {
626
+ const res = runHook(['before_tool'], dir, identityPayload({}),
627
+ { FLOW_COMET_AGENT_DEPTH: raw, FLOW_COMET_AGENT_DEPTH_SOURCE: 'dsh-bridge' });
628
+ assertExit(res, 2);
629
+ assertOut(res, 'BLOCKED');
630
+ }
631
+ // ⑥d 取值形态收窄(fail-closed 方向):'0'(协调者)/ 空串 / 纯空白 / 非十进制 / 负数 /
632
+ // 小数 / 科学计数 / 带符号 一律非身份 ⇒ 退回路径判定(不得读成放宽)
633
+ for (const raw of ['0', '', ' ', 'abc', '-1', '1.5', '1e1', '+1', '2x']) {
634
+ const res = runHook(['before_tool'], dir, identityPayload({}), bridgeIdentityEnv(raw));
635
+ assertExit(res, 2);
636
+ assertOut(res, 'BLOCKED');
637
+ }
638
+ // ⑥e 载荷面收窄:agent_id 非字符串 / 空串 / 纯空白 ⇒ 非身份;agent_type 单独在场不构成
639
+ // 身份(实现判据只认 agent_id——文本与实现一致锚见技能文本锁场景)
640
+ for (const bad of [undefined, null, 42, '', ' ']) {
641
+ const res = runHook(['before_tool'], dir, identityPayload({ agent_id: bad }));
642
+ assertExit(res, 2);
643
+ assertOut(res, 'BLOCKED');
644
+ }
645
+ const viaAgentTypeOnly = runHook(['before_tool'], dir, identityPayload({ agent_type: 'codex-subagent' }));
646
+ assertExit(viaAgentTypeOnly, 2);
647
+ assertOut(viaAgentTypeOnly, 'BLOCKED');
648
+ // ⑥f 两平台对照(同一判据、无平台分支):codex 分支放行输出严格 JSON `{}`、拦截输出
649
+ // decision:block 且 exit 0;claude-code 分支放行输出既有文本、拦截 exit 2(见 ⑥a / ⑥b)
650
+ const codexAllow = runHook(['before_tool', '--platform', 'codex'], dir, identityPayload({ agent_id: 'agent-abc123' }));
651
+ assertExit(codexAllow, 0);
652
+ if (codexAllow.output.trim() !== '{}') {
653
+ throw new Error('codex 分支放行应输出严格 JSON {},实际: ' + JSON.stringify(codexAllow.output));
654
+ }
655
+ const codexBlock = runHook(['before_tool', '--platform', 'codex'], dir, identityPayload({}));
656
+ assertExit(codexBlock, 0);
657
+ assertOut(codexBlock, '"decision":"block"');
658
+
659
+ // ⑦ 顺序锚:身份判据**先于**路径判据求值——身份在场且目标在 runRoot 之外 ⇒ 放行。
660
+ // 顺序若反转(先解析路径)该目标必 BLOCK ⇒ 本断言本身即顺序判据(判定顺序可断言)。
661
+ const outsideRoot = path.join(dir, '..', 'outside-232', 'src', 'x.mjs');
662
+ const orderViaWrite = runHook(['before_tool'], dir,
663
+ { tool_name: 'Write', tool_input: { file_path: outsideRoot }, agent_id: 'agent-abc123' });
664
+ assertExit(orderViaWrite, 0);
665
+ assertOut(orderViaWrite, '(subagent identity)');
666
+ const orderViaBash = runHook(['before_tool'], dir,
667
+ { tool_name: 'Bash', tool_input: { command: 'echo x > "' + posix(outsideRoot) + '"' }, agent_id: 'agent-abc123' });
668
+ assertExit(orderViaBash, 0);
669
+ // ⑦b 载荷 cwd 不参与路径解释(会话 cwd 与实际工作目录不一致的实测形态):身份在场时
670
+ // cwd 指向别处 + 相对路径 ⇒ 仍按身份放行(不因 cwd 不一致而误拦)
671
+ const viaCwdDrift = runHook(['before_tool'], dir, {
672
+ tool_name: 'Write',
673
+ tool_input: { file_path: 'src/rel.mjs' },
674
+ cwd: path.join(dir, '..', 'elsewhere-232'),
675
+ agent_id: 'agent-abc123',
676
+ });
677
+ assertExit(viaCwdDrift, 0);
678
+ // ⑦c 同载荷无身份 ⇒ 相对路径按 runRoot 解析(cwd 不参与)⇒ 白名单外 BLOCK,且报文中不出现
679
+ // 按 cwd 解析出的错路径(cwd 漂移不得改变判定依据)
680
+ const cwdDriftMain = runHook(['before_tool'], dir, {
681
+ tool_name: 'Write',
682
+ tool_input: { file_path: 'src/rel.mjs' },
683
+ cwd: path.join(dir, '..', 'elsewhere-232'),
684
+ });
685
+ assertExit(cwdDriftMain, 2);
686
+ assertOut(cwdDriftMain, 'BLOCKED');
687
+ assertNotOut(cwdDriftMain, 'elsewhere-232');
688
+
689
+ // ⑧ runRoot 外写入的关断,两分支对称:同一目标经 Write / Edit(file_path 分支)与 Bash
690
+ // (命令级写入)同判 BLOCK——修复前 file_path 分支静默放行(fail-open)而 Bash 分支拦截。
691
+ // 反向构造:恢复 file_path 分支的静默放行 ⇒ ⑧a / ⑧b 必红。
692
+ const outsideWrite = runHook(['before_tool'], dir,
693
+ { tool_name: 'Write', tool_input: { file_path: outsideRoot } });
694
+ assertExit(outsideWrite, 2);
695
+ assertOut(outsideWrite, 'BLOCKED');
696
+ assertOut(outsideWrite, '项目根之外');
697
+ const outsideEdit = runHook(['before_tool'], dir,
698
+ { tool_name: 'Edit', tool_input: { file_path: outsideRoot } });
699
+ assertExit(outsideEdit, 2);
700
+ assertOut(outsideEdit, 'BLOCKED');
701
+ const outsideBash = runHook(['before_tool'], dir,
702
+ { tool_name: 'Bash', tool_input: { command: 'echo x > "' + posix(outsideRoot) + '"' } });
703
+ assertExit(outsideBash, 2);
704
+ assertOut(outsideBash, 'BLOCKED');
705
+ // ⑧b 身份在场时两分支同样对称放行(顺序锚在 Bash 分支上的对照——见 ⑦a 第二例)
706
+
707
+ // ⑨ 最小保护集:身份放行**不放行**两个机器面目标——机器状态文件与本次运行实际生效的
708
+ // 协议文件(三平台身份形态一致受拦)。反向构造:身份短路时跳过保护集判定 ⇒ ⑨ 必红。
709
+ const stateFileTarget = path.join(dir, '.flow-comet', 'flow-comet-state.json');
710
+ const protocolFileTarget = path.join(dir, 'reference', 'workflow-protocol.json');
711
+ for (const [label, target] of [['机器状态文件', stateFileTarget], ['协议保护路径', protocolFileTarget]]) {
712
+ const viaIdentityWrite = runHook(['before_tool'], dir,
713
+ { tool_name: 'Write', tool_input: { file_path: target }, agent_id: 'agent-abc123' });
714
+ assertExit(viaIdentityWrite, 2);
715
+ assertOut(viaIdentityWrite, 'BLOCKED');
716
+ const viaIdentityEdit = runHook(['before_tool'], dir,
717
+ { tool_name: 'Edit', tool_input: { file_path: target }, agent_id: 'agent-abc123' });
718
+ assertExit(viaIdentityEdit, 2);
719
+ assertOut(viaIdentityEdit, 'BLOCKED');
720
+ const viaIdentityBash = runHook(['before_tool'], dir,
721
+ { tool_name: 'Bash', tool_input: { command: 'echo x > "' + posix(target) + '"' }, agent_id: 'agent-abc123' });
722
+ assertExit(viaIdentityBash, 2);
723
+ assertOut(viaIdentityBash, 'BLOCKED');
724
+ const viaDepthWrite = runHook(['before_tool'], dir,
725
+ { tool_name: 'Write', tool_input: { file_path: target } }, bridgeIdentityEnv('2'));
726
+ assertExit(viaDepthWrite, 2);
727
+ assertOut(viaDepthWrite, 'BLOCKED');
728
+ // 报文须点名保护集类别(经桥接通道身份放行下的拦截理由):协调者路径的报语文义不同
729
+ // (state 文件另有同族点名的协调者分支,协议面则是「不在允许范围」)⇒ 本断言锁住「身份
730
+ // 在场仍走保护集判定」而非靠白名单兜底(判别力见 ⑥c2 的继承形态对照)。
731
+ assertOut(viaDepthWrite, label === '机器状态文件' ? 'state 文件' : '协议文件');
732
+ const codexIdentityBlock = runHook(['before_tool', '--platform', 'codex'], dir,
733
+ { tool_name: 'Write', tool_input: { file_path: target }, agent_id: 'agent-abc123' });
734
+ assertExit(codexIdentityBlock, 0);
735
+ assertOut(codexIdentityBlock, '"decision":"block"');
736
+ if (!codexIdentityBlock.output.includes(label === '机器状态文件' ? 'state 文件' : '协议文件')) {
737
+ throw new Error('保护集拦截报文应点名目标类别(' + label + '): ' + JSON.stringify(codexIdentityBlock.output));
738
+ }
739
+ }
740
+ // ⑨b 对照:同一身份写普通源码 / 工件路径 ⇒ 放行(保护集不扩大——只此两个目标)
741
+ const identityAllowedSource = runHook(['before_tool'], dir,
742
+ { tool_name: 'Write', tool_input: { file_path: whitelistOutside }, agent_id: 'agent-abc123' });
743
+ assertExit(identityAllowedSource, 0);
744
+ const identityAllowedArtifact = runHook(['before_tool'], dir,
745
+ { tool_name: 'Write', tool_input: { file_path: path.join(dir, '.specs', CHANGE_ID, 'note.md') }, agent_id: 'agent-abc123' });
746
+ assertExit(identityAllowedArtifact, 0);
747
+ // ⑨c 别名形态闭合(物理同一性):经 8.3 短路径 / 符号链接拼写的同一状态文件同样受拦
748
+ // (词法比较看不见别名——身份放行下保护集是唯一防线,故须闭合)。平台无法构造链接时
749
+ // 如实降级为可见提示,不静默跳过。
750
+ const stateAliasDir = path.join(dir, '.flow-comet-alias');
751
+ let aliasLinkCreated = false;
752
+ try {
753
+ fs.symlinkSync(path.join(dir, '.flow-comet'), stateAliasDir,
754
+ process.platform === 'win32' ? 'junction' : 'dir');
755
+ aliasLinkCreated = true;
756
+ } catch { aliasLinkCreated = false; }
757
+ if (aliasLinkCreated) {
758
+ const viaAlias = runHook(['before_tool'], dir,
759
+ { tool_name: 'Write', tool_input: { file_path: path.join(stateAliasDir, 'flow-comet-state.json') }, agent_id: 'agent-abc123' });
760
+ assertExit(viaAlias, 2);
761
+ assertOut(viaAlias, 'BLOCKED');
762
+ } else {
763
+ console.error('WARN: 当前平台无法构造目录链接,保护集别名形态断言降级(词法判定仍由 ⑨ 覆盖)');
764
+ }
765
+ // ⑨d 盘符根拼写(Windows 上 Git-Bash 类 shell 的 `/d/<剩余>` 形态)与盘符拼写**同判**:
766
+ // win32 的目标解析把 `/d/<剩余>` 读成「当前盘根下的 \d\<剩余>」而非 `D:\<剩余>` ⇒
767
+ // 词法相对化判为根外(相对路径为空)⇒ 状态文件判据被跳过;物理判据对错解路径 stat
768
+ // 失败 ⇒ 两道判据同时失守——身份放行下保护集形同虚设(fail-open)。归一入口唯一
769
+ // (既有写入目标解析),故两条判据同时闭合、各等价拼写同判。
770
+ // 该拼写是 Windows 上 Git-Bash 类 shell 的自然产物;非 win32 平台它是普通 POSIX
771
+ // 绝对路径,语义不同 ⇒ 显式不适用(不静默跳过——未验证 ≠ 通过)。
772
+ const hasDriveRoot = /^[A-Za-z]:[\\/]/.test(dir);
773
+ if (process.platform === 'win32' && hasDriveRoot) {
774
+ const driveRootSpelling = (p) => '/' + p[0].toLowerCase() + p.slice(2).replaceAll('\\', '/');
775
+ for (const [label, target, marker] of [
776
+ ['机器状态文件', stateFileTarget, 'state 文件'],
777
+ ['协议保护路径', protocolFileTarget, '协议文件'],
778
+ ]) {
779
+ const exits = [];
780
+ const forms = [['盘符根拼写', driveRootSpelling(target)], ['盘符拼写', posix(target)]];
781
+ for (const [formLabel, form] of forms) {
782
+ const viaWrite = runHook(['before_tool'], dir,
783
+ { tool_name: 'Write', tool_input: { file_path: form }, agent_id: 'agent-abc123' });
784
+ assertExit(viaWrite, 2);
785
+ assertOut(viaWrite, marker);
786
+ const viaBash = runHook(['before_tool'], dir,
787
+ { tool_name: 'Bash', tool_input: { command: 'cp "' + form + '" "' + form + '"' }, agent_id: 'agent-abc123' });
788
+ assertExit(viaBash, 2);
789
+ assertOut(viaBash, marker);
790
+ exits.push(viaWrite.status, viaBash.status);
791
+ if (formLabel === '盘符根拼写') {
792
+ // 盘符字母大写变体同归一(同族拼写不得因大小写漏判)
793
+ const upper = runHook(['before_tool'], dir,
794
+ { tool_name: 'Write', tool_input: { file_path: '/' + form[1].toUpperCase() + form.slice(2) }, agent_id: 'agent-abc123' });
795
+ assertExit(upper, 2);
796
+ assertOut(upper, marker);
797
+ }
798
+ }
799
+ if (exits.some((code) => code !== exits[0])) {
800
+ throw new Error(label + ' 的两种拼写应同判,实际 exit: ' + JSON.stringify(exits));
801
+ }
802
+ if (label === '机器状态文件') {
803
+ // 协调者路径(无身份)同样闭合:命令级写入的盘符根拼写命中状态文件判据 ⇒ 报文点名
804
+ // 目标类别(修复前落到「不在允许范围」兜底分支——证明目标确被抽取,缺口在判定)
805
+ const msysMain = driveRootSpelling(target);
806
+ const asMain = runHook(['before_tool'], dir,
807
+ { tool_name: 'Bash', tool_input: { command: 'cp "' + msysMain + '" "' + msysMain + '"' } });
808
+ assertExit(asMain, 2);
809
+ assertOut(asMain, marker);
810
+ }
811
+ }
812
+ // ⑨e 对照:同一身份写普通源码的盘符根拼写 ⇒ 放行(归一不得把保护集扩大到其余路径)
813
+ const msysSource = driveRootSpelling(whitelistOutside);
814
+ const msysSourceWrite = runHook(['before_tool'], dir,
815
+ { tool_name: 'Write', tool_input: { file_path: msysSource }, agent_id: 'agent-abc123' });
816
+ assertExit(msysSourceWrite, 0);
817
+ assertOut(msysSourceWrite, '(subagent identity)');
818
+ const msysSourceBash = runHook(['before_tool'], dir,
819
+ { tool_name: 'Bash', tool_input: { command: 'cp "' + msysSource + '" "' + msysSource + '"' }, agent_id: 'agent-abc123' });
820
+ assertExit(msysSourceBash, 0);
821
+ // ⑨f 单字母限定(`/dev`、`/etc` 一类多字母首段不得被当作盘符根):该目标按「当前盘根下的
822
+ // 同名目录」解析 ⇒ 项目根之外 ⇒ 协调者拦截报文带根外语义。若归一放宽为「首字母后不要求
823
+ // 分隔符」,目标被改写成盘符相对形态后落在项目根内 ⇒ 报文语义改变 ⇒ 本断言必红。
824
+ const notDriveRoot = '/' + dir[0].toLowerCase() + 'ev/probe.md';
825
+ const notDriveRootRes = runHook(['before_tool'], dir,
826
+ { tool_name: 'Write', tool_input: { file_path: notDriveRoot } });
827
+ assertExit(notDriveRootRes, 2);
828
+ assertOut(notDriveRootRes, '项目根之外');
829
+ } else {
830
+ // 非 win32:该拼写是**普通 POSIX 绝对路径**,归一只许在 win32 生效(否则同一目标会被改写成
831
+ // 项目根内的相对形态,报文失去根外语义)。本断言锁的是「平台限定」这半边——正向断言在
832
+ // 本平台不适用,故此处改为可判别的替代锚(断言失败即说明归一变无条件)。
833
+ const posixSpelling = '/d/probe.md';
834
+ const posixRes = runHook(['before_tool'], dir,
835
+ { tool_name: 'Write', tool_input: { file_path: posixSpelling } });
836
+ assertExit(posixRes, 2);
837
+ assertOut(posixRes, '项目根之外');
838
+ console.error('注意: 本平台无盘符根形态,盘符根拼写的归一等价性断言**显式不适用**'
839
+ + '(dsh/pwsh 与 Codex/cmd 不产生该拼写;win32 侧为唯一判别面)——已改为断言平台限定半边'
840
+ + '(该拼写在本平台不得被归一到项目根内);未验证 ≠ 通过');
841
+ }
842
+
843
+ // ⑩ apply_patch 承载形态的耐久锚(in-place 扩展):补丁正文写在 tool_input.command、
844
+ // 载荷无 file_path——目标须由补丁摘要行抽出后才进入既有判定入口(白名单与最小保护集
845
+ // 共用同一返回值)。判据与内建反向构造见模块级 applyPatchAnchorProblems。
846
+ const patchProblems = applyPatchAnchorProblems(dir);
847
+ if (patchProblems.length > 0) {
848
+ throw new Error('apply_patch 目标解析锚失败: ' + patchProblems.join('; '));
849
+ }
850
+ },
851
+ },
852
+
853
+ // 233: 迁移前置探测的错误分类——lstat 的**访问类**故障(EACCES/EPERM/EIO)不得被当作
854
+ // 「文件不存在」:吞掉会让迁移报告「已跳过:旧位置不存在」而安装照常继续,用户的旧状态
855
+ // 永远留在旧位置(静默的数据丢失风险)。修复后只有「确实不存在」类(ENOENT/ENOTDIR)
856
+ // 返回 null,其余原样抛出、安装中止并暴露问题。
857
+ // 构造方式:本机/CI 无法用真实文件系统稳定造出访问类故障(受权限与平台差异支配,
858
+ // 见场景 223 的链接权限先例),故用 `--require` 预加载在**子进程内**把 lstatSync 对
859
+ // 「旧位置状态文件」的探测替换为抛 EACCES(故障注入只命中该路径,其余调用走真实实现)——
860
+ // 驱动的仍是真实安装器主流程与真实文件系统状态。
861
+ {
862
+ name: '233 迁移探测错误分类:lstat 访问类故障中止安装,ENOENT 仍按不存在跳过',
863
+ run: (dir) => {
864
+ if (!fs.existsSync(PREPARE_ENV)) return;
865
+ // ① ENOENT(确实不存在)→ 仍按「无需迁移」跳过、安装继续(行为未变)
866
+ const noLegacy = path.join(dir, 'proj-no-legacy');
867
+ fs.mkdirSync(noLegacy, { recursive: true });
868
+ const skipped = runPrepareEnv(['--target', noLegacy, '--platform', 'claude-code'], dir);
869
+ assertExit(skipped, 0);
870
+ assertOut(skipped, '已跳过');
871
+ assertOut(skipped, '无需迁移');
872
+ // ② 访问类故障 → 中止(修复前被吞成「不存在」→ 已跳过 + 安装继续 → RED)
873
+ const proj = path.join(dir, 'proj-lstat-fault');
874
+ const stateBytes = migratableStateBytes();
875
+ writeSharedCometDir(proj, stateBytes);
876
+ const preloadName = 'lstat-fault-preload.cjs';
877
+ writeFile(dir, preloadName, [
878
+ "const fs = require('node:fs');",
879
+ "const path = require('node:path');",
880
+ 'const realLstatSync = fs.lstatSync;',
881
+ 'fs.lstatSync = function (target, ...rest) {',
882
+ ' const segments = path.resolve(String(target)).split(path.sep);',
883
+ " const isLegacyStateFile = segments[segments.length - 1] === 'flow-comet-state.json'",
884
+ " && segments[segments.length - 2] === '.comet';",
885
+ ' if (isLegacyStateFile) {',
886
+ " const error = new Error('EACCES: permission denied, lstat ' + JSON.stringify(String(target)));",
887
+ " error.code = 'EACCES';",
888
+ ' throw error;',
889
+ ' }',
890
+ ' return realLstatSync.call(fs, target, ...rest);',
891
+ '};',
892
+ '',
893
+ ].join('\n'));
894
+ const spawned = spawnSync(
895
+ process.execPath,
896
+ ['--require', path.join(dir, preloadName), PREPARE_ENV, '--target', proj, '--platform', 'claude-code'],
897
+ { cwd: dir, env: { ...process.env }, encoding: 'utf8', timeout: 120000 },
898
+ );
899
+ const res = { status: spawned.status ?? 1, output: String(spawned.stdout || '') + String(spawned.stderr || '') };
900
+ if (res.status === 0) throw new Error('访问类故障应中止安装(exit 非 0),实际 exit 0');
901
+ assertOut(res, 'EACCES');
902
+ assertNotOut(res, '已跳过');
903
+ assertNotOut(res, '已迁移');
904
+ // 旧件未被处置、新位置不生成文件(中止于任何写操作之前)
905
+ if (!fs.readFileSync(path.join(proj, LEGACY_RUNTIME_DIR, RUNTIME_STATE_NAME)).equals(stateBytes)) {
906
+ throw new Error('中止路径下旧件被改写');
907
+ }
908
+ if (fs.existsSync(path.join(proj, RUNTIME_DIR, RUNTIME_STATE_NAME))) throw new Error('中止时新位置不应生成文件');
909
+ if (migrationBackups(proj).length !== 0) throw new Error('中止时不应产生备份');
910
+ },
911
+ },
912
+
913
+ // 234: 迁移校验与运行时判定的 BOM 一致性——运行时(workflow-state.mjs readJson)明确容忍
914
+ // UTF-8 BOM(外部写入如会话 Write 可能带 BOM)。迁移侧此前不 strip BOM:同一份数据运行时
915
+ // 读得动、迁移判「不是合法 JSON」而中止安装。修复后校验侧同样容忍 BOM,且**只影响校验**——
916
+ // 备份与新落盘必须保留原始字节(不得改写用户数据)。
917
+ {
918
+ name: '234 状态迁移接受带 BOM 的旧状态:迁移成功且备份与新位置保留原始字节',
919
+ run: (dir) => {
920
+ if (!fs.existsSync(PREPARE_ENV)) return;
921
+ const proj = path.join(dir, 'proj');
922
+ const bomStateBytes = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), migratableStateBytes()]);
923
+ writeSharedCometDir(proj, bomStateBytes);
924
+ writeMigratedProjectArtifacts(proj); // ③ 运行时读取断言需要活动 change 目录在场
925
+ const res = runPrepareEnv(['--target', proj, '--platform', 'claude-code'], dir);
926
+ assertExit(res, 0);
927
+ assertOut(res, '已迁移');
928
+ // ① 新位置落位且逐字节一致(BOM 保留——校验容忍不改写数据)
929
+ const newState = path.join(proj, RUNTIME_DIR, RUNTIME_STATE_NAME);
930
+ if (!fs.readFileSync(newState).equals(bomStateBytes)) {
931
+ throw new Error('新位置状态未保留原始字节(BOM 被剥离或内容被改写)');
932
+ }
933
+ // ② 备份同样逐字节一致
934
+ const backups = migrationBackups(proj);
935
+ if (backups.length !== 1) throw new Error('迁移应恰生成 1 份备份,实际: ' + JSON.stringify(backups));
936
+ if (!fs.readFileSync(path.join(proj, RUNTIME_DIR, backups[0])).equals(bomStateBytes)) {
937
+ throw new Error('备份未保留原始字节(BOM 被剥离或内容被改写)');
938
+ }
939
+ // ③ 迁移后运行时能读(BOM 容忍是运行时的既有设计决策——两处判定一致)
940
+ const st = runInstalled(proj, '.claude', 'workflow-state.mjs', ['status']);
941
+ assertExit(st, 0);
942
+ assertOut(st, MIGRATION_CHANGE);
943
+ },
944
+ },
945
+
946
+ // 235: 被拒绝的命令不得产生副作用——`--purge` 缺 `--yes` 的确认校验此前排在运行时文件
947
+ // 迁移之后:命令最终被拒绝,但迁移已经执行、目标已被修改。修复后确认校验先于一切写操作。
948
+ {
949
+ name: '235 purge 缺 --yes:命令被拒且迁移未发生(零副作用)',
950
+ run: (dir) => {
951
+ if (!fs.existsSync(PREPARE_ENV)) return;
952
+ const proj = path.join(dir, 'proj');
953
+ const stateBytes = migratableStateBytes();
954
+ writeSharedCometDir(proj, stateBytes);
955
+ const res = runPrepareEnv(['--target', proj, '--platform', 'claude-code', '--purge'], dir);
956
+ if (res.status === 0) throw new Error('--purge 缺 --yes 应拒绝执行(exit 非 0),实际 exit 0');
957
+ assertOut(res, '--yes');
958
+ assertNotOut(res, '已迁移');
959
+ // 零副作用:旧件原位未动、新位置不生成文件、不产生备份、无安装产物
960
+ const oldPath = path.join(proj, LEGACY_RUNTIME_DIR, RUNTIME_STATE_NAME);
961
+ if (!fs.existsSync(oldPath)) throw new Error('被拒绝的命令仍执行了迁移(旧位置文件已消失)');
962
+ if (!fs.readFileSync(oldPath).equals(stateBytes)) throw new Error('被拒绝的命令改写了旧件');
963
+ if (fs.existsSync(path.join(proj, RUNTIME_DIR, RUNTIME_STATE_NAME))) throw new Error('被拒绝的命令仍写入了新位置');
964
+ if (migrationBackups(proj).length !== 0) throw new Error('被拒绝的命令仍产生了备份');
965
+ if (fs.existsSync(path.join(proj, '.claude'))) throw new Error('被拒绝的命令仍产生了安装产物');
966
+ },
967
+ },
968
+
969
+ // ---------- 命令写判定的写入目标取向(Copy/Move 与位置形态) ----------
970
+
971
+ // 236: 命令写判定的写入目标取向——Copy-Item/Move-Item 的 `-Path`/`-LiteralPath` 是**源**路径,
972
+ // 写入目标是 `-Destination`。修复前 cmdlet 模式只捕获 `-(Path|LiteralPath)`(源),且全无
973
+ // `-Destination` 模式 → 目标从不被检查(越界写整条放行);而同文件 .NET File API 分支按
974
+ // 「Copy/Move 目标 = 第二参数」取第二个捕获组——同一函数两个分支取向相反。
975
+ // 修复后按目的地取值(与 .NET 分支同向):① 目标越界 → BLOCK(修复前放行 → RED);
976
+ // ② 源在白名单外而目标在白名单内 → 放行(源是读取方向,不属写入判定;修复前拿源当目标 → 误拦 → RED);
977
+ // ③ 源与目标都在白名单内 → 放行(放行不得因本次修复收窄)。
978
+ {
979
+ name: '236 hook 命令写:Copy-Item/Move-Item 取 -Destination 为写入目标(目标越界拦、源路径不再误拦)',
980
+ run: (dir) => {
981
+ writeState(dir, { ...baseState('review'), status: 'running' });
982
+ const src = '.specs/' + CHANGE_ID + '/x.md';
983
+ const inside = '.specs/' + CHANGE_ID + '/copy.md';
984
+ // ① 逃逸:目标在协调者白名单(.specs/)之外
985
+ const escapeCopy = runHook(['before_tool'], dir, {
986
+ tool_name: 'Bash',
987
+ tool_input: { command: 'Copy-Item -Path ' + src + ' -Destination CLAUDE.md' },
988
+ });
989
+ assertExit(escapeCopy, 2);
990
+ assertOut(escapeCopy, 'BLOCKED');
991
+ assertOut(escapeCopy, 'CLAUDE.md');
992
+ const escapeMove = runHook(['before_tool'], dir, {
993
+ tool_name: 'Bash',
994
+ tool_input: { command: 'Move-Item -Path ' + src + ' -Destination docs/MECHANISM.md' },
995
+ });
996
+ assertExit(escapeMove, 2);
997
+ assertOut(escapeMove, 'BLOCKED');
998
+ assertOut(escapeMove, 'docs/MECHANISM.md');
999
+ // ② 源在白名单外、目标在白名单内 → 放行(读取方向不判定为写入)
1000
+ const sourceOutside = runHook(['before_tool'], dir, {
1001
+ tool_name: 'Bash',
1002
+ tool_input: { command: 'Copy-Item -LiteralPath CLAUDE.md -Destination ' + inside },
1003
+ });
1004
+ assertExit(sourceOutside, 0);
1005
+ assertOut(sourceOutside, 'workflow-hook-guard-ok');
1006
+ // ③ 源与目标都在白名单内 → 放行
1007
+ const bothInside = runHook(['before_tool'], dir, {
1008
+ tool_name: 'Bash',
1009
+ tool_input: { command: 'Copy-Item -Path ' + src + ' -Destination ' + inside },
1010
+ });
1011
+ assertExit(bothInside, 0);
1012
+ assertOut(bothInside, 'workflow-hook-guard-ok');
1013
+ },
1014
+ },
1015
+
1016
+ // 237: 位置形态 `cp <src> <dst>` / `mv <src> <dst>`——修复前命令写判定只认 PowerShell cmdlet、
1017
+ // shell 重定向与 .NET File API,位置形态无任何模式覆盖 → 越界写整条放行。
1018
+ // 修复后取最后一个位置参数为目标(开关及其取值不参与):① 目标越界 → BLOCK(修复前放行 → RED);
1019
+ // ② 目标在白名单内 → 放行;③ `cp` 只作为普通参数出现(不是命令词)时不产生写入目标
1020
+ // (命令位置锚定——否则 `grep -n cp <file>` 会把文件名当成写入目标 → 反过来造成误拦)。
1021
+ {
1022
+ name: '237 hook 命令写:cp/mv 位置形态取最后位置参数为目标(逃逸拦截,命令位置锚定不误判)',
1023
+ run: (dir) => {
1024
+ writeState(dir, { ...baseState('review'), status: 'running' });
1025
+ const src = '.specs/' + CHANGE_ID + '/x.md';
1026
+ const inside = '.specs/' + CHANGE_ID + '/copy.md';
1027
+ const cpEscape = runHook(['before_tool'], dir, {
1028
+ tool_name: 'Bash',
1029
+ tool_input: { command: 'cp ' + src + ' CLAUDE.md' },
1030
+ });
1031
+ assertExit(cpEscape, 2);
1032
+ assertOut(cpEscape, 'BLOCKED');
1033
+ assertOut(cpEscape, 'CLAUDE.md');
1034
+ const mvEscape = runHook(['before_tool'], dir, {
1035
+ tool_name: 'Bash',
1036
+ tool_input: { command: 'mv -f ' + src + ' README-zh.md' },
1037
+ });
1038
+ assertExit(mvEscape, 2);
1039
+ assertOut(mvEscape, 'BLOCKED');
1040
+ assertOut(mvEscape, 'README-zh.md');
1041
+ // 目标在白名单内 → 放行(含开关:开关与其取值不参与位置参数扫描)
1042
+ const cpInside = runHook(['before_tool'], dir, {
1043
+ tool_name: 'Bash',
1044
+ tool_input: { command: 'cp -f CLAUDE.md ' + inside },
1045
+ });
1046
+ assertExit(cpInside, 0);
1047
+ assertOut(cpInside, 'workflow-hook-guard-ok');
1048
+ // 命令位置锚定:`cp` 作为普通参数出现(grep 模式)不是写命令
1049
+ const notCommand = runHook(['before_tool'], dir, {
1050
+ tool_name: 'Bash',
1051
+ tool_input: { command: 'grep -n cp README.md' },
1052
+ });
1053
+ assertExit(notCommand, 0);
1054
+ assertOut(notCommand, 'workflow-hook-guard-ok');
1055
+ },
1056
+ },
1057
+
1058
+ // 238: 纯位置形态(`Copy-Item <src> <dst>`)与 `-FilePath`(Out-File 的惯用主参数)修复前均无
1059
+ // 模式覆盖 → 放行;修复后两者都按写入目标判定。同场景锚定既有 `-Path` 语义未被本次修复放宽
1060
+ // (Set-Content / Remove-Item 的 `-Path` 就是写入目标:越界拦、白名单内放行)。
1061
+ {
1062
+ name: '238 hook 命令写:纯位置形态与 -FilePath 目标覆盖,既有 -Path 语义保持',
1063
+ run: (dir) => {
1064
+ writeState(dir, { ...baseState('review'), status: 'running' });
1065
+ const src = '.specs/' + CHANGE_ID + '/x.md';
1066
+ const positional = runHook(['before_tool'], dir, {
1067
+ tool_name: 'Bash',
1068
+ tool_input: { command: 'Copy-Item ' + src + ' CLAUDE.md' },
1069
+ });
1070
+ assertExit(positional, 2);
1071
+ assertOut(positional, 'BLOCKED');
1072
+ assertOut(positional, 'CLAUDE.md');
1073
+ const filePath = runHook(['before_tool'], dir, {
1074
+ tool_name: 'Bash',
1075
+ tool_input: { command: 'Out-File -FilePath docs/MECHANISM.md' },
1076
+ });
1077
+ assertExit(filePath, 2);
1078
+ assertOut(filePath, 'BLOCKED');
1079
+ assertOut(filePath, 'docs/MECHANISM.md');
1080
+ // 开关取值不参与位置参数扫描:`-Filter *.md` 的 `*.md` 不是写入目标(当成目标即新的误拦)
1081
+ const filterValue = runHook(['before_tool'], dir, {
1082
+ tool_name: 'Bash',
1083
+ tool_input: { command: 'Remove-Item -Force -Filter *.md' },
1084
+ });
1085
+ assertExit(filterValue, 0);
1086
+ assertOut(filterValue, 'workflow-hook-guard-ok');
1087
+ // 既有 -Path 语义保持(回归锚):越界拦
1088
+ const removePath = runHook(['before_tool'], dir, {
1089
+ tool_name: 'Bash',
1090
+ tool_input: { command: 'Remove-Item -Path docs/MECHANISM.md' },
1091
+ });
1092
+ assertExit(removePath, 2);
1093
+ assertOut(removePath, 'BLOCKED');
1094
+ const setContentOut = runHook(['before_tool'], dir, {
1095
+ tool_name: 'Bash',
1096
+ tool_input: { command: 'Set-Content -Path docs/MECHANISM.md -Value x' },
1097
+ });
1098
+ assertExit(setContentOut, 2);
1099
+ assertOut(setContentOut, 'BLOCKED');
1100
+ // 既有 -Path 语义保持(回归锚):白名单内放行
1101
+ const setContentIn = runHook(['before_tool'], dir, {
1102
+ tool_name: 'Bash',
1103
+ tool_input: { command: 'Set-Content -Path ' + src + ' -Value x' },
1104
+ });
1105
+ assertExit(setContentIn, 0);
1106
+ assertOut(setContentIn, 'workflow-hook-guard-ok');
1107
+ },
1108
+ },
1109
+
1110
+ // 239: 目的地型命令的参数段必须止于换行——段捕获 `[^;|&]*` 不排除 `\r`/`\n`,`cp <src> <dst>`
1111
+ // 之后紧跟另一行命令时段会跨行吞并:「最后一个位置参数」取到下一行的参数(通常在白名单内)
1112
+ // → 整条命令放行,**真正被写的 <dst> 从不被检查**(逃逸方向)。修复后换行/回车都是段边界,
1113
+ // 每行命令按各自参数段判定。
1114
+ {
1115
+ name: '239 hook 命令写:目的地型命令的段不跨行(跨行吞并使真实目标漏检 → 拦)',
1116
+ run: (dir) => {
1117
+ writeState(dir, { ...baseState('review'), status: 'running' });
1118
+ const src = '.specs/' + CHANGE_ID + '/x.md';
1119
+ const inside = '.specs/' + CHANGE_ID + '/ok.md';
1120
+ // ① 目标越界、下一行参数在白名单内:修复前取到下一行参数 → 放行(逃逸)
1121
+ const crossLine = runHook(['before_tool'], dir, {
1122
+ tool_name: 'Bash',
1123
+ tool_input: { command: 'cp ' + src + ' CLAUDE.md\necho ' + inside },
1124
+ });
1125
+ assertExit(crossLine, 2);
1126
+ assertOut(crossLine, 'BLOCKED');
1127
+ assertOut(crossLine, 'CLAUDE.md');
1128
+ // ② CRLF 行尾(Windows 形态)同判:`\r` 也是段边界
1129
+ const crlf = runHook(['before_tool'], dir, {
1130
+ tool_name: 'Bash',
1131
+ tool_input: { command: 'cp ' + src + ' CLAUDE.md\r\necho ' + inside },
1132
+ });
1133
+ assertExit(crlf, 2);
1134
+ assertOut(crlf, 'BLOCKED');
1135
+ assertOut(crlf, 'CLAUDE.md');
1136
+ // ③ 行首是普通命令、写命令在第二行 → 第二行仍被独立判定(多行命令串的覆盖保持)
1137
+ const secondLine = runHook(['before_tool'], dir, {
1138
+ tool_name: 'Bash',
1139
+ tool_input: { command: 'echo ' + inside + '\nmv ' + src + ' README-zh.md' },
1140
+ });
1141
+ assertExit(secondLine, 2);
1142
+ assertOut(secondLine, 'BLOCKED');
1143
+ assertOut(secondLine, 'README-zh.md');
1144
+ // ④ 单行且目标在白名单内 → 放行(收紧段边界不得误伤合法形态)
1145
+ const singleLine = runHook(['before_tool'], dir, {
1146
+ tool_name: 'Bash',
1147
+ tool_input: { command: 'cp ' + src + ' ' + inside },
1148
+ });
1149
+ assertExit(singleLine, 0);
1150
+ assertOut(singleLine, 'workflow-hook-guard-ok');
1151
+ },
1152
+ },
1153
+
1154
+ // 240: GNU cp/mv 的**前置目的地**选项 `-t <dir>` / `--target-directory[= ]<dir>`——目的地不是
1155
+ // 最后一个位置参数而是开关的取值。修复前只把开关跳过取值、仍取「最后一个位置参数」= 源
1156
+ // (源通常在白名单内)→ 整条命令放行,真正被写的目录不被检查(逃逸方向)。
1157
+ {
1158
+ name: '240 hook 命令写:cp/mv 前置目的地 -t / --target-directory 取为写入目标',
1159
+ run: (dir) => {
1160
+ writeState(dir, { ...baseState('review'), status: 'running' });
1161
+ const src = '.specs/' + CHANGE_ID + '/x.md';
1162
+ const inside = '.specs/' + CHANGE_ID + '/ok.md';
1163
+ // ① `-t <dir>`:目的地越界 → 拦(修复前取源 → 放行)
1164
+ const shortForm = runHook(['before_tool'], dir, {
1165
+ tool_name: 'Bash',
1166
+ tool_input: { command: 'cp -t docs ' + src },
1167
+ });
1168
+ assertExit(shortForm, 2);
1169
+ assertOut(shortForm, 'BLOCKED');
1170
+ assertOut(shortForm, 'docs');
1171
+ // ② `--target-directory=<dir>`(等号形态)
1172
+ const longFormEquals = runHook(['before_tool'], dir, {
1173
+ tool_name: 'Bash',
1174
+ tool_input: { command: 'cp --target-directory=docs ' + src },
1175
+ });
1176
+ assertExit(longFormEquals, 2);
1177
+ assertOut(longFormEquals, 'BLOCKED');
1178
+ assertOut(longFormEquals, 'docs');
1179
+ // ③ `--target-directory <dir>`(空格形态)
1180
+ const longFormSpace = runHook(['before_tool'], dir, {
1181
+ tool_name: 'Bash',
1182
+ tool_input: { command: 'mv --target-directory docs ' + src },
1183
+ });
1184
+ assertExit(longFormSpace, 2);
1185
+ assertOut(longFormSpace, 'BLOCKED');
1186
+ assertOut(longFormSpace, 'docs');
1187
+ // ④ 前置目的地在白名单内 → 放行(不得因本次修复误拦)
1188
+ const insideTarget = runHook(['before_tool'], dir, {
1189
+ tool_name: 'Bash',
1190
+ tool_input: { command: 'mv -t .specs/' + CHANGE_ID + ' ' + src },
1191
+ });
1192
+ assertExit(insideTarget, 0);
1193
+ assertOut(insideTarget, 'workflow-hook-guard-ok');
1194
+ // ⑤ 反向锚:无前置目的地的普通形态仍按最后位置参数判定(既有语义保持)
1195
+ const plain = runHook(['before_tool'], dir, {
1196
+ tool_name: 'Bash',
1197
+ tool_input: { command: 'cp -f ' + src + ' ' + inside },
1198
+ });
1199
+ assertExit(plain, 0);
1200
+ assertOut(plain, 'workflow-hook-guard-ok');
1201
+ },
1202
+ },
1203
+
1204
+ // 241: 命令位置锚定必须引号感知——命令边界集 `[;&|(){}]` 不区分引号内外,`printf '(cp CLAUDE.md)'`
1205
+ // 引号内的括号被当成命令边界,括号里的文本被读成写命令 → **合法命令被拦**(误拦方向)。
1206
+ // 修复后边界只在引号外生效;引号外的真命令仍按原判据拦截(收紧不得放过真逃逸)。
1207
+ {
1208
+ name: '241 hook 命令写:引号内的命令分隔符不构成命令位置(合法命令不被读成写命令)',
1209
+ run: (dir) => {
1210
+ writeState(dir, { ...baseState('review'), status: 'running' });
1211
+ // ① 单引号内的括号:不是命令边界
1212
+ const singleQuoted = runHook(['before_tool'], dir, {
1213
+ tool_name: 'Bash',
1214
+ tool_input: { command: "printf '(cp CLAUDE.md)'" },
1215
+ });
1216
+ assertExit(singleQuoted, 0);
1217
+ assertOut(singleQuoted, 'workflow-hook-guard-ok');
1218
+ // ② 双引号内的分号:不是命令分隔符
1219
+ const doubleQuoted = runHook(['before_tool'], dir, {
1220
+ tool_name: 'Bash',
1221
+ tool_input: { command: 'echo "cp CLAUDE.md; mv x README.md"' },
1222
+ });
1223
+ assertExit(doubleQuoted, 0);
1224
+ assertOut(doubleQuoted, 'workflow-hook-guard-ok');
1225
+ // ③ 引号外的真写命令仍拦(同一命令串内引号内文本与真命令并存)
1226
+ const realCommand = runHook(['before_tool'], dir, {
1227
+ tool_name: 'Bash',
1228
+ tool_input: { command: 'printf "(cp x)" ; cp .specs/' + CHANGE_ID + '/x.md CLAUDE.md' },
1229
+ });
1230
+ assertExit(realCommand, 2);
1231
+ assertOut(realCommand, 'BLOCKED');
1232
+ assertOut(realCommand, 'CLAUDE.md');
1233
+ // ④ 既有意图保持:`cp` 只作为被检索文本出现时不构成命令位置(不误判为写命令)
1234
+ const notCommand = runHook(['before_tool'], dir, {
1235
+ tool_name: 'Bash',
1236
+ tool_input: { command: 'grep -n "cp" README.md' },
1237
+ });
1238
+ assertExit(notCommand, 0);
1239
+ assertOut(notCommand, 'workflow-hook-guard-ok');
1240
+ },
1241
+ },
1242
+
1243
+ // 242: ATX 标题的**闭合标记**(`## 名称 ##`——合法 Markdown)须在段名归一中被剥离。
1244
+ // 不剥离时段名归一为 `名称 ##`,与模板段名不等 → 七段全判缺失 → INIT-VALIDATE-FAILED,
1245
+ // 依赖 CONTEXT 结构校验的流程被误阻断(记录扫描时间的正常路径走不通)。
1246
+ // 与场景 90(同夹具、无闭合标记)成对:唯一变量就是闭合标记本身。
1247
+ {
1248
+ name: '242 CONTEXT 段标题带 ATX 闭合标记 → 段存在判定通过(INIT-DONE)',
1249
+ run: (dir) => {
1250
+ writeFile(dir, '.specs/CONTEXT.md', [
1251
+ '# CONTEXT',
1252
+ '## 项目概要 ##', 'x',
1253
+ '## 技术栈 ##', 'x',
1254
+ '## 域语言 ##', '| 术语 | 定义 |', '|---|---|', '| 例 | 定义 |',
1255
+ '## 已锁决策 ##', '- [2026-08-01] 决策一',
1256
+ '## 默认偏好 ##', 'x',
1257
+ '## 既有抽象索引 ##', 'x',
1258
+ '## intel-scan 元数据 ##', '- **last_intel_scan**: x', '- **scanner**: x', '- **下次重扫建议**: x',
1259
+ '',
1260
+ ].join('\n'));
1261
+ writeFile(dir, 'package.json', '{"name":"x"}');
1262
+ const res = runStateWithProtocol(dir, ['init', CHANGE_ID, '--init-context']);
1263
+ assertExit(res, 0);
1264
+ assertOut(res, 'INIT-DONE');
1265
+ const st = JSON.parse(fs.readFileSync(path.join(dir, '.flow-comet', 'flow-comet-state.json'), 'utf8'));
1266
+ if (!st.last_intel_scan) throw new Error('闭合标记形态应通过段存在判定并写 last_intel_scan');
1267
+ // ② 闭合标记须**前置空白**(CommonMark 语义):`## 项目概要#` 不是闭合形态,段名即
1268
+ // `项目概要#`——它不得被剥成 `项目概要`(否则缺段被假判为存在)。这条边界锁住剥离
1269
+ // 范围:将来把前置空白放宽成「任意位置」,此处即变红。
1270
+ writeFile(dir, '.specs/CONTEXT.md', [
1271
+ '# CONTEXT',
1272
+ '## 项目概要#', 'x',
1273
+ '## 技术栈 ##', 'x',
1274
+ '## 域语言 ##', '| 术语 | 定义 |', '|---|---|', '| 例 | 定义 |',
1275
+ '## 已锁决策 ##', '- [2026-08-01] 决策一',
1276
+ '## 默认偏好 ##', 'x',
1277
+ '## 既有抽象索引 ##', 'x',
1278
+ '## intel-scan 元数据 ##', '- **last_intel_scan**: x', '- **scanner**: x', '- **下次重扫建议**: x',
1279
+ '',
1280
+ ].join('\n'));
1281
+ const boundary = runStateWithProtocol(dir, ['init', CHANGE_ID + '-2', '--init-context']);
1282
+ assertExit(boundary, 0);
1283
+ assertOut(boundary, 'INIT-VALIDATE-FAILED');
1284
+ assertOut(boundary, '项目概要');
1285
+ },
1286
+ },
1287
+ ];