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,1338 @@
1
+ // 场景组 k — 受控重入 · 计划重校重签 · 强制推进留痕
2
+ // 元素形态:`{ name, run }`;计数由 `lib/count-derivation.mjs` 从本目录聚合,不手抄数字。
3
+ // 组界:场景序列按组文件规模上限连续分区——本文件头部两项(259 · 260)落在 scenarios/j.mjs 尾部;
4
+ // 分区只搬文件,场景名/内容与拼接顺序不变(见 scenarios/j.mjs 头注)。
5
+
6
+ import fs from 'fs';
7
+ import os from 'os';
8
+ import path from 'path';
9
+ import { createHash } from 'crypto';
10
+ import { isDeepStrictEqual } from 'util';
11
+ import {
12
+ assertExit,
13
+ assertNotOut,
14
+ assertOut,
15
+ baseState,
16
+ runGuard,
17
+ writeFile,
18
+ writeState,
19
+ } from '../lib/test-helpers.mjs';
20
+ import {
21
+ CHANGE_ID,
22
+ CROSS_TASK_FIX_PAIR,
23
+ CROSS_TASK_FIX_SECTION_PAIR,
24
+ CROSS_TASK_MIXED_PAIR,
25
+ CROSS_TASK_PLAIN_PAIR,
26
+ FIX_PREFIX_LITERAL_TEXT,
27
+ SCRIPTS_DIR,
28
+ TASK_DEP_CYCLE,
29
+ TASK_MISSING_DEP,
30
+ TASK_PARALLEL_READ_OVERLAP,
31
+ TASK_PARALLEL_WRITE_CONFLICT,
32
+ customProtocol,
33
+ dropNamedImport,
34
+ engineCodeText,
35
+ engineConsumersOf,
36
+ engineDefinitionHits,
37
+ engineDefinitionModule,
38
+ engineReachableFrom,
39
+ engineScriptFiles,
40
+ engineScriptTexts,
41
+ fixFamilyBoundaryProblems,
42
+ runPlanExit,
43
+ strictSummary,
44
+ writeIntakeArtifacts,
45
+ } from '../lib/test-fixtures.mjs';
46
+ import {
47
+ REENTRY_EXPECTED_INTERSECTION,
48
+ REENTRY_FULL_COMPLETED,
49
+ REPLAN_STALE_SIGNATURE,
50
+ REPLAN_TASK_INITIAL,
51
+ REPLAN_TASK_NO_VERIFY,
52
+ REPLAN_TASK_REVISED,
53
+ advanceForcedEvent,
54
+ assertOutMatches,
55
+ assertReentryAuthorizationShape,
56
+ assertReplanAuthorizationShape,
57
+ assertReplanSignatureRecorded,
58
+ assertStateBytesUnchanged,
59
+ outputText,
60
+ parseStatusJson,
61
+ readScenarioProtocol,
62
+ readScenarioState,
63
+ readStateBytes,
64
+ reentryArchiveState,
65
+ reentryBackupFiles,
66
+ reentryHistoryEvent,
67
+ replanBackupFiles,
68
+ replanEventsOf,
69
+ replanExecuteState,
70
+ replanHistoryEvent,
71
+ requireRouteNodeExport,
72
+ runReenter,
73
+ runStateWithProtocol,
74
+ writeReentryChangeDir,
75
+ } from '../lib/test-assertions.mjs';
76
+ import {
77
+ singleSourceImportProblems,
78
+ } from '../lib/text-anchor-checks.mjs';
79
+
80
+ export const ENTRIES = [
81
+
82
+ {
83
+ name: '261a 受控重入越界:目标白名单 / disabled 节点 / 源非 archive / completed 全 BLOCK 零改写',
84
+ run: (dir) => {
85
+ writeReentryChangeDir(dir);
86
+ // ① 目标不在白名单(design / open / archive 自身)
87
+ for (const target of ['design', 'open', 'archive']) {
88
+ writeReentryChangeDir(dir);
89
+ writeState(dir, reentryArchiveState());
90
+ const bytes = readStateBytes(dir);
91
+ const res = runReenter(dir, target, { source: 'user-approval', reason: 'x' });
92
+ assertExit(res, 1);
93
+ assertOut(res, 'BLOCKED');
94
+ assertStateBytesUnchanged(dir, bytes, '目标越界: ' + target);
95
+ }
96
+ // ② 协议 disabled 节点不可作目标(自定义协议禁用 verify)
97
+ const customProtocolPath = path.join(dir, 'reentry-protocol-disabled.json');
98
+ const customProtocol = readScenarioProtocol(dir);
99
+ customProtocol.nodes.find((n) => n.id === 'verify').disabled = true;
100
+ writeFile(dir, 'reentry-protocol-disabled.json', JSON.stringify(customProtocol, null, 2) + '\n');
101
+ writeState(dir, reentryArchiveState());
102
+ const bytesDisabled = readStateBytes(dir);
103
+ const resDisabled = runReenter(dir, 'verify', {
104
+ source: 'user-approval', reason: 'x', extra: ['--protocol', customProtocolPath],
105
+ });
106
+ assertExit(resDisabled, 1);
107
+ assertOut(resDisabled, 'BLOCKED');
108
+ assertStateBytesUnchanged(dir, bytesDisabled, '协议 disabled 节点');
109
+ // ③ 源不是 archive(execute 驻留;目标 verify 形态未成立 → 不被空操作短路)
110
+ writeState(dir, reentryArchiveState({ currentNode: 'execute' }));
111
+ const bytesSource = readStateBytes(dir);
112
+ const resSource = runReenter(dir, 'verify', { source: 'user-approval', reason: 'x' });
113
+ assertExit(resSource, 1);
114
+ assertOut(resSource, 'BLOCKED');
115
+ assertStateBytesUnchanged(dir, bytesSource, '源不是 archive');
116
+ // ④ status=completed(归档已出口 / 已发布形态)→ BLOCK + 人工处置或新 change 指引
117
+ writeState(dir, reentryArchiveState({ status: 'completed' }));
118
+ const bytesCompleted = readStateBytes(dir);
119
+ const resCompleted = runReenter(dir, 'verify', { source: 'user-approval', reason: 'x' });
120
+ assertExit(resCompleted, 1);
121
+ assertOut(resCompleted, 'BLOCKED');
122
+ assertOutMatches(resCompleted, /人工|新 ?change|hotfix/, 'status=completed 指引');
123
+ assertStateBytesUnchanged(dir, bytesCompleted, 'status=completed');
124
+ },
125
+ },
126
+
127
+ // 261b: 轮次族——归档移动已发生 / 超轮次上限(本 change 3 条事件后第 4 次)/ 轮次按 change 隔离
128
+ // (他 change 的历史事件不占本 change 配额)——同族同时断言 BLOCK 与放行两态。
129
+ {
130
+ name: '261b 受控重入轮次:归档移动已发生 / 超上限 BLOCK + 跨 change 隔离放行',
131
+ run: (dir) => {
132
+ writeReentryChangeDir(dir);
133
+ // ⑤ 归档移动已发生(.specs/<id>/ 不在原位,已搬入 .specs/archive/<日期>-<id>/)
134
+ fs.rmSync(path.join(dir, '.specs', CHANGE_ID), { recursive: true, force: true });
135
+ writeFile(dir, '.specs/archive/2026-09-26-' + CHANGE_ID + '/CHANGE.md', '# CHANGE\n\n## Why\n\n已归档。\n');
136
+ writeState(dir, reentryArchiveState());
137
+ const bytesMoved = readStateBytes(dir);
138
+ const resMoved = runReenter(dir, 'verify', { source: 'user-approval', reason: 'x' });
139
+ assertExit(resMoved, 1);
140
+ assertOut(resMoved, 'BLOCKED');
141
+ assertOutMatches(resMoved, /人工|新 ?change|hotfix/, '归档移动已发生指引');
142
+ assertStateBytesUnchanged(dir, bytesMoved, '归档移动已发生');
143
+ // ⑥ 超轮次上限:本 change 已有 3 条 reentry-applied → 第 4 次 BLOCK + 「继续 / 停止」指引
144
+ writeReentryChangeDir(dir);
145
+ writeState(dir, reentryArchiveState({
146
+ history: [reentryHistoryEvent(1), reentryHistoryEvent(2), reentryHistoryEvent(3)],
147
+ }));
148
+ const bytesCapped = readStateBytes(dir);
149
+ const resCapped = runReenter(dir, 'verify', { source: 'user-approval', reason: 'x' });
150
+ assertExit(resCapped, 1);
151
+ assertOut(resCapped, 'BLOCKED');
152
+ assertOut(resCapped, '继续');
153
+ assertOut(resCapped, '停止');
154
+ assertStateBytesUnchanged(dir, bytesCapped, '超轮次上限');
155
+ // ⑦ 轮次跨 change 隔离:他 change 的 3 条事件不占本 change 配额 → 放行且为第 1 轮
156
+ writeState(dir, reentryArchiveState({
157
+ history: [
158
+ reentryHistoryEvent(1, 'other-change'),
159
+ reentryHistoryEvent(2, 'other-change'),
160
+ reentryHistoryEvent(3, 'other-change'),
161
+ ],
162
+ }));
163
+ const resIsolated = runReenter(dir, 'verify', { source: 'user-approval', reason: 'x' });
164
+ assertExit(resIsolated, 0);
165
+ assertOut(resIsolated, '1/3');
166
+ const isolatedState = readScenarioState(dir);
167
+ const appliedEvent = (isolatedState.history || [])
168
+ .find((e) => e.event === 'reentry-applied' && e.change === CHANGE_ID);
169
+ if (!appliedEvent || appliedEvent.round !== 1) {
170
+ throw new Error('他 change 的轮次事件不应占用本 change 配额(本 change 应为第 1 轮),实际 '
171
+ + JSON.stringify(appliedEvent));
172
+ }
173
+ },
174
+ },
175
+
176
+ // 261c: 换键绕过族——select 拒绝多段路径 / 保留目录名 / 大小写与首尾空白变体;change 键被换成
177
+ // 归档相对路径时写盘前 BLOCK;history 非数组 fail-closed(不得静默清空审计历史)。
178
+ {
179
+ name: '261c 受控重入换键绕过:select 变体拒绝 / 相对路径 change 名 / 损坏 history 全 BLOCK',
180
+ run: (dir) => {
181
+ writeReentryChangeDir(dir);
182
+ // select 族的前置:本 change 处于 archive 源可重入态(与 261b 的放行态同一形态)
183
+ writeState(dir, reentryArchiveState());
184
+ // ⑧ select 入口收紧:多段路径(归档相对路径形态)与保留目录名不得被选为 activeChange
185
+ fs.mkdirSync(path.join(dir, '.specs', 'archive', '2026-09-26-' + CHANGE_ID), { recursive: true });
186
+ const beforeSelect = readStateBytes(dir);
187
+ assertExit(runStateWithProtocol(dir, ['select', 'archive/2026-09-26-' + CHANGE_ID]), 1);
188
+ assertStateBytesUnchanged(dir, beforeSelect, 'select 归档相对路径');
189
+ assertExit(runStateWithProtocol(dir, ['select', 'archive']), 1);
190
+ assertStateBytesUnchanged(dir, beforeSelect, 'select 保留目录名');
191
+ // ⑧b 名字变体族:保留目录名大小写变体(ARCHIVE/Archive)、真实目录名的大小写变体(CH)与
192
+ // 首尾空白变体在大小写不敏感文件系统上同样可达,但会让 activeChange 与实际目录名不一致
193
+ // (轮次事件按 activeChange 精确匹配 → 配额被换键重置)→ 一律拒绝且 state 字节零改写
194
+ assertExit(runStateWithProtocol(dir, ['select', 'ARCHIVE']), 1);
195
+ assertStateBytesUnchanged(dir, beforeSelect, 'select 保留目录名大小写变体');
196
+ assertExit(runStateWithProtocol(dir, ['select', 'Archive']), 1);
197
+ assertStateBytesUnchanged(dir, beforeSelect, 'select 保留目录名混合大小写变体');
198
+ const caseVariant = String(CHANGE_ID).toUpperCase();
199
+ if (caseVariant !== CHANGE_ID) {
200
+ assertExit(runStateWithProtocol(dir, ['select', caseVariant]), 1);
201
+ assertStateBytesUnchanged(dir, beforeSelect, 'select 真实目录名大小写变体');
202
+ }
203
+ assertExit(runStateWithProtocol(dir, ['select', ' ' + CHANGE_ID + ' ']), 1);
204
+ assertStateBytesUnchanged(dir, beforeSelect, 'select 首尾空白变体');
205
+ if (readScenarioState(dir).activeChange !== CHANGE_ID) {
206
+ throw new Error('被拒绝的 select 不得改写 activeChange:' + JSON.stringify(readScenarioState(dir).activeChange));
207
+ }
208
+ // ⑨ change 键被换成归档相对路径(换键重置轮次配额的绕过形态)→ 写盘前 BLOCK:本 change 的
209
+ // 3 条事件既不得被换键忽略,也不得产生新事件 / 备份 / 机器字段改写
210
+ writeState(dir, reentryArchiveState({
211
+ activeChange: 'archive/2026-09-26-' + CHANGE_ID,
212
+ history: [reentryHistoryEvent(1), reentryHistoryEvent(2), reentryHistoryEvent(3)],
213
+ }));
214
+ const nestedBytes = readStateBytes(dir);
215
+ const nestedBackupsBefore = reentryBackupFiles(dir).length;
216
+ const nestedRes = runReenter(dir, 'verify', { source: 'user-approval', reason: '换键重入' });
217
+ assertExit(nestedRes, 1);
218
+ assertOut(nestedRes, 'BLOCKED');
219
+ assertStateBytesUnchanged(dir, nestedBytes, '归档相对路径 change 名');
220
+ if (reentryBackupFiles(dir).length !== nestedBackupsBefore) {
221
+ throw new Error('归档相对路径 change 名不得产生备份');
222
+ }
223
+ // ⑩ history 存在但非数组 → fail-closed BLOCK,不得静默清空覆盖审计历史
224
+ writeReentryChangeDir(dir);
225
+ writeState(dir, reentryArchiveState({ history: 'corrupted-history' }));
226
+ const corruptBytes = readStateBytes(dir);
227
+ const corruptRes = runReenter(dir, 'verify', { source: 'user-approval', reason: 'history 损坏' });
228
+ assertExit(corruptRes, 1);
229
+ assertOut(corruptRes, 'BLOCKED');
230
+ assertOut(corruptRes, 'history');
231
+ assertStateBytesUnchanged(dir, corruptBytes, '非数组 history');
232
+ if (readScenarioState(dir).history !== 'corrupted-history') {
233
+ throw new Error('损坏的 history 不得被静默清空覆盖:' + JSON.stringify(readScenarioState(dir).history));
234
+ }
235
+ // ⑪ 备份写入包含性:.specs/<change> 为 junction(指向 runRoot 外)→ BLOCK 零改写,
236
+ // runRoot 外不得出现任何备份字节
237
+ const linkedOutsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'flow-comet-reentry-outside-'));
238
+ writeFile(linkedOutsideDir, 'CHANGE.md', '# CHANGE\n\n## Why\n\njunction 目标。\n');
239
+ const linkedName = 'linked-change';
240
+ fs.symlinkSync(linkedOutsideDir, path.join(dir, '.specs', linkedName), 'junction');
241
+ writeState(dir, reentryArchiveState({ activeChange: linkedName }));
242
+ const linkedBytes = readStateBytes(dir);
243
+ const linkedRes = runReenter(dir, 'verify', { source: 'user-approval', reason: 'junction 逃逸' });
244
+ assertExit(linkedRes, 1);
245
+ assertOut(linkedRes, 'BLOCKED');
246
+ assertStateBytesUnchanged(dir, linkedBytes, 'junction 逃逸');
247
+ if (fs.existsSync(path.join(linkedOutsideDir, '.reentry-backups'))) {
248
+ throw new Error('junction 逃逸不得在 runRoot 外产生备份:'
249
+ + JSON.stringify(fs.readdirSync(path.join(linkedOutsideDir, '.reentry-backups'))));
250
+ }
251
+ fs.rmSync(linkedOutsideDir, { recursive: true, force: true });
252
+ try { fs.rmSync(path.join(dir, '.specs', linkedName), { recursive: true, force: true }); } catch { /* 场景目录整体清理兜底 */ }
253
+ // ⑫ 上限后的显式授权续轮(AC-7 后半句):合法授权 → 放行并计下一轮(事件 / 授权留痕带
254
+ // 续轮标记与原因);授权轮次不足或未达上限即传续轮 → BLOCK 且 state 字节零改写
255
+ const threeRounds = [reentryHistoryEvent(1), reentryHistoryEvent(2), reentryHistoryEvent(3)];
256
+ writeReentryChangeDir(dir);
257
+ writeState(dir, reentryArchiveState({ history: threeRounds }));
258
+ const continued = runReenter(dir, 'verify', {
259
+ source: 'admin-approval', reason: '上限后显式授权续轮', extra: ['--continue-round', '4'],
260
+ });
261
+ assertExit(continued, 0);
262
+ assertOut(continued, 'REENTRY');
263
+ assertOut(continued, '续轮');
264
+ const continuedState = readScenarioState(dir);
265
+ if (continuedState.currentNode !== 'verify') {
266
+ throw new Error('续轮放行后 currentNode 应为 verify,实际 ' + JSON.stringify(continuedState.currentNode));
267
+ }
268
+ const continuedEvent = (continuedState.history || [])
269
+ .filter((e) => e.event === 'reentry-applied')
270
+ .pop();
271
+ if (!continuedEvent || continuedEvent.round !== 4 || continuedEvent.change !== CHANGE_ID
272
+ || continuedEvent.continuationAuthorized !== true
273
+ || continuedEvent.reason !== '上限后显式授权续轮') {
274
+ throw new Error('续轮审计事件字段不符(round=4 / change / 续轮标记 / reason):' + JSON.stringify(continuedEvent));
275
+ }
276
+ const continuedRecord = continuedState.evidence?.verify?.reentryAuthorization;
277
+ if (!continuedRecord || continuedRecord.continuationAuthorized !== true
278
+ || continuedRecord.reason !== '上限后显式授权续轮') {
279
+ throw new Error('续轮授权留痕不符:' + JSON.stringify(continuedRecord));
280
+ }
281
+ writeState(dir, reentryArchiveState({ history: threeRounds }));
282
+ const insufficientBytes = readStateBytes(dir);
283
+ const insufficient = runReenter(dir, 'verify', {
284
+ source: 'admin-approval', reason: '轮次不足', extra: ['--continue-round', '3'],
285
+ });
286
+ assertExit(insufficient, 1);
287
+ assertOut(insufficient, 'BLOCKED');
288
+ assertStateBytesUnchanged(dir, insufficientBytes, '续轮授权轮次不足');
289
+ writeState(dir, reentryArchiveState());
290
+ const earlyBytes = readStateBytes(dir);
291
+ const early = runReenter(dir, 'verify', {
292
+ source: 'admin-approval', reason: '未达上限', extra: ['--continue-round', '4'],
293
+ });
294
+ assertExit(early, 1);
295
+ assertOut(early, 'BLOCKED');
296
+ assertStateBytesUnchanged(dir, earlyBytes, '未达上限即传续轮');
297
+ // ⑬ 写盘失败路径:原子写因临时路径被占而失败 → 非零退出、state 不截断、本次孤儿备份回滚
298
+ writeReentryChangeDir(dir);
299
+ writeState(dir, reentryArchiveState());
300
+ const atomicBytes = readStateBytes(dir);
301
+ const atomicBackupsBefore = reentryBackupFiles(dir);
302
+ const blockedTempDir = path.join(dir, '.flow-comet', 'flow-comet-state.json.tmp');
303
+ fs.mkdirSync(blockedTempDir, { recursive: true });
304
+ const atomicRes = runReenter(dir, 'verify', { source: 'user-approval', reason: '模拟写盘失败' });
305
+ assertExit(atomicRes, 1);
306
+ assertStateBytesUnchanged(dir, atomicBytes, '写盘失败路径');
307
+ if (!isDeepStrictEqual(reentryBackupFiles(dir), atomicBackupsBefore)) {
308
+ throw new Error('写盘失败必须回滚本次孤儿备份:before=' + JSON.stringify(atomicBackupsBefore)
309
+ + ' after=' + JSON.stringify(reentryBackupFiles(dir)));
310
+ }
311
+ fs.rmSync(blockedTempDir, { recursive: true, force: true });
312
+ },
313
+ },
314
+
315
+ // 262: 恢复链(AC-2 的「BLOCK → 补全授权 → 放行」/ 编排顺序 / 幂等重放)——未授权 BLOCK 且
316
+ // 字节零改写、零备份;补齐授权三元组后放行(备份 + 转移 + 审计);重复同目标调用 = 空操作
317
+ // (放行 + 可见提示 + 零备份新增 + 零计数 + 零事件 + 字节零改写)。
318
+ {
319
+ name: '262 恢复链:未授权 BLOCK → 补全授权放行 → 重复同目标空操作(零副作用)',
320
+ run: (dir) => {
321
+ writeReentryChangeDir(dir);
322
+ writeState(dir, reentryArchiveState());
323
+ const blockedBytes = readStateBytes(dir);
324
+ const resBlocked = runReenter(dir, 'verify');
325
+ assertExit(resBlocked, 1);
326
+ assertOut(resBlocked, 'BLOCKED');
327
+ assertStateBytesUnchanged(dir, blockedBytes, '未授权 BLOCK');
328
+ if (reentryBackupFiles(dir).length !== 0) {
329
+ throw new Error('未授权 BLOCK 不得产生备份');
330
+ }
331
+ const resAllowed = runReenter(dir, 'verify', { source: 'user-approval', reason: '用户显式授权重入' });
332
+ assertExit(resAllowed, 0);
333
+ assertOut(resAllowed, 'REENTRY');
334
+ const appliedState = readScenarioState(dir);
335
+ if (appliedState.currentNode !== 'verify') {
336
+ throw new Error('补全授权后应放行并把 currentNode 置为 verify,实际 ' + JSON.stringify(appliedState.currentNode));
337
+ }
338
+ const backupsAfterApply = reentryBackupFiles(dir);
339
+ if (backupsAfterApply.length !== 1) {
340
+ throw new Error('放行应恰产生 1 份备份,实际 ' + JSON.stringify(backupsAfterApply));
341
+ }
342
+ const appliedEvents = (appliedState.history || []).filter((e) => e.event === 'reentry-applied');
343
+ if (appliedEvents.length !== 1) {
344
+ throw new Error('放行应恰写 1 条 reentry-applied 事件,实际 ' + JSON.stringify(appliedEvents));
345
+ }
346
+ const noopBytes = readStateBytes(dir);
347
+ const resNoop = runReenter(dir, 'verify', { source: 'user-approval', reason: '重复调用同目标' });
348
+ assertExit(resNoop, 0);
349
+ assertNotOut(resNoop, 'BLOCKED');
350
+ if (outputText(resNoop).trim() === '') {
351
+ throw new Error('空操作应打印一条可见提示');
352
+ }
353
+ assertStateBytesUnchanged(dir, noopBytes, '重复同目标空操作');
354
+ if (!isDeepStrictEqual(reentryBackupFiles(dir), backupsAfterApply)) {
355
+ throw new Error('空操作不得新增备份:' + JSON.stringify(reentryBackupFiles(dir)));
356
+ }
357
+ const noopState = readScenarioState(dir);
358
+ if ((noopState.history || []).length !== (appliedState.history || []).length) {
359
+ throw new Error('空操作不得写事件:history 长度由 ' + (appliedState.history || []).length
360
+ + ' 变为 ' + (noopState.history || []).length);
361
+ }
362
+ },
363
+ },
364
+
365
+ // 263: 旧 change(无 newChange 字段 · AC-3 与本 change 的显式例外)——授权门禁对一切
366
+ // change 无条件 fail-closed:旧 change 未授权同样 BLOCK(安全面不因 change 新旧降级);
367
+ // 合法授权放行并与新 change 走同一转移 / 审计路径。
368
+ {
369
+ name: '263 旧 change:未授权仍 BLOCK(显式例外)+ 合法授权放行',
370
+ run: (dir) => {
371
+ writeReentryChangeDir(dir);
372
+ const legacyState = reentryArchiveState();
373
+ delete legacyState.newChange;
374
+ writeState(dir, legacyState);
375
+ const blockedBytes = readStateBytes(dir);
376
+ const resBlocked = runReenter(dir, 'verify');
377
+ assertExit(resBlocked, 1);
378
+ assertOut(resBlocked, 'BLOCKED');
379
+ assertStateBytesUnchanged(dir, blockedBytes, '旧 change 未授权');
380
+ if (reentryBackupFiles(dir).length !== 0) {
381
+ throw new Error('旧 change 未授权 BLOCK 不得产生备份');
382
+ }
383
+ const resAllowed = runReenter(dir, 'verify', { source: 'user-approval', reason: '旧 change 显式授权' });
384
+ assertExit(resAllowed, 0);
385
+ assertOut(resAllowed, 'REENTRY');
386
+ const st = readScenarioState(dir);
387
+ if (st.currentNode !== 'verify') {
388
+ throw new Error('旧 change 合法授权应放行并转移,实际 ' + JSON.stringify(st.currentNode));
389
+ }
390
+ if (!isDeepStrictEqual(st.completedNodes, REENTRY_EXPECTED_INTERSECTION.verify)) {
391
+ throw new Error('旧 change 转移后 completedNodes 应为前驱交集,实际 ' + JSON.stringify(st.completedNodes));
392
+ }
393
+ const appliedEvent = (st.history || []).find((e) => e.event === 'reentry-applied');
394
+ if (!appliedEvent || appliedEvent.change !== CHANGE_ID || appliedEvent.round !== 1) {
395
+ throw new Error('旧 change 的审计事件应带 change 且为第 1 轮,实际 ' + JSON.stringify(appliedEvent));
396
+ }
397
+ // 最小旧 state(仅 7 个键、无 readState 兼容默认字段):apply 只写本次实际改动的字段,
398
+ // 兼容默认值不得随重入回写(键集逐项不变——「其余字段零改写」口径覆盖真实最小旧 state)
399
+ const minimalLegacy = {
400
+ activeChange: CHANGE_ID,
401
+ currentNode: 'archive',
402
+ completedNodes: [...REENTRY_FULL_COMPLETED],
403
+ evidence: {},
404
+ verifyFailures: 0,
405
+ status: 'running',
406
+ history: [{ event: 'exit-applied', node: 'verify', at: '2026-09-20T00:00:00.000Z', change: CHANGE_ID }],
407
+ };
408
+ writeState(dir, minimalLegacy);
409
+ const minimalKeysBefore = Object.keys(readScenarioState(dir)).sort();
410
+ const minimalRes = runReenter(dir, 'verify', { source: 'user-approval', reason: '最小旧 state 重入' });
411
+ assertExit(minimalRes, 0);
412
+ assertOut(minimalRes, 'REENTRY');
413
+ const minimalAfter = readScenarioState(dir);
414
+ const minimalKeysAfter = Object.keys(minimalAfter).sort();
415
+ if (!isDeepStrictEqual(minimalKeysAfter, minimalKeysBefore)) {
416
+ throw new Error('最小旧 state 重入后键集必须逐项不变(兼容默认值不得回写):before='
417
+ + JSON.stringify(minimalKeysBefore) + ' after=' + JSON.stringify(minimalKeysAfter));
418
+ }
419
+ for (const defaultKey of ['executionMode', 'directOverride', 'branchMode', 'enablePrReview', 'branchPrefix']) {
420
+ if (defaultKey in minimalAfter) {
421
+ throw new Error('readState 兼容默认字段不得随重入回写: ' + defaultKey);
422
+ }
423
+ }
424
+ },
425
+ },
426
+
427
+ // 264: history 事件类型集合静态锚(唯一事件类型例外 / 禁止扩散)——扫描**引擎实现面**(入口 ∪
428
+ // `lib/**`,递归)的事件类型字面量:写侧集合必须恰为 {exit-applied, reentry-applied,
429
+ // replan-applied, advance-forced}(新增类型必须由引擎写侧真实落地 + 显式更新本锚,未落地即
430
+ // RED),读侧集合必须 ⊆ 允许集(出现允许集外的事件类型即红);另锚新的两类写点必须带跨 change
431
+ // 归属字段(replan-applied → change)与「被跳过的出口门禁」标识(advance-forced → skipped:
432
+ // exit:<node>),事件对象的动态断言在 259 / 263 / 受控计划重校场景族。
433
+ {
434
+ name: '264 history 事件类型集合静态锚:既有类型 + replan-applied / advance-forced(新增即红、判据不放宽)',
435
+ run: () => {
436
+ const allowed = ['exit-applied', 'reentry-applied', 'replan-applied', 'advance-forced'];
437
+ const scripts = engineScriptFiles();
438
+ const writers = new Set();
439
+ const readers = new Set();
440
+ const writeSites = new Map();
441
+ for (const file of scripts) {
442
+ const text = fs.readFileSync(path.join(SCRIPTS_DIR, file), 'utf8');
443
+ for (const match of text.matchAll(/event:\s*'([a-z][a-z-]*)'/g)) {
444
+ writers.add(match[1]);
445
+ writeSites.set(match[1], { file, text, index: match.index });
446
+ }
447
+ for (const match of text.matchAll(/\.event\s*(?:===|!==)\s*'([a-z][a-z-]*)'/g)) {
448
+ readers.add(match[1]);
449
+ }
450
+ }
451
+ const extra = [...new Set([...writers, ...readers])].filter((type) => !allowed.includes(type));
452
+ if (extra.length > 0) {
453
+ throw new Error('history 事件类型出现允许集外的新类型(唯一事件类型例外不得扩散): ' + extra.join(', ')
454
+ + ';写侧=' + [...writers].join(',') + ';读侧=' + [...readers].join(','));
455
+ }
456
+ const missingWriters = allowed.filter((type) => !writers.has(type));
457
+ if (missingWriters.length > 0) {
458
+ throw new Error('history 事件类型写侧缺类型(受控通道未落地即 RED): ' + missingWriters.join(', ')
459
+ + ';实际写侧=' + [...writers].join(','));
460
+ }
461
+ // 跨 change 归属字段锚:轮次/配额按 change 隔离依赖事件的 change 字段(reentry / replan 同判据)
462
+ const changeFieldTypes = ['reentry-applied', 'replan-applied'];
463
+ for (const type of changeFieldTypes) {
464
+ const site = writeSites.get(type);
465
+ if (!site) throw new Error(type + ' 写点缺失(审计事件必须由引擎脚本写入)');
466
+ const windowText = site.text.slice(site.index, site.index + 800);
467
+ if (!/\bchange\s*:/.test(windowText)) {
468
+ throw new Error(type + ' 写点必须带 change 字段(跨 change 轮次隔离依据): ' + site.file);
469
+ }
470
+ }
471
+ // 强制推进留痕锚:事件必须记录被跳过的出口门禁标识(skipped: ['exit:<node>'])
472
+ const forcedSite = writeSites.get('advance-forced');
473
+ if (!forcedSite) throw new Error('advance-forced 写点缺失(逃生口留痕必须由引擎脚本写入)');
474
+ const forcedWindow = forcedSite.text.slice(forcedSite.index, forcedSite.index + 800);
475
+ if (!/\bskipped\s*:/.test(forcedWindow)) {
476
+ throw new Error('advance-forced 写点必须带 skipped 字段(记录被跳过的出口门禁): ' + forcedSite.file);
477
+ }
478
+ if (!/exit:/.test(forcedWindow)) {
479
+ throw new Error('advance-forced 写点的 skipped 值必须标识 exit:<node> 形态的门禁: ' + forcedSite.file);
480
+ }
481
+ },
482
+ },
483
+
484
+ // 265: 幂等锚(空操作判定)——目标形态已成立(currentNode=target 且 completedNodes 已等于
485
+ // 前驱交集)时重复调用 = 空操作:放行 + 可见提示 + 不备份 / 不计数 / 不写事件 / state 字节
486
+ // 零改写。夹具直接构造目标形态(不经 apply 路径),同时锁定判定顺序:空操作短路必须先于
487
+ // 源判定——否则 currentNode=verify ≠ archive 会先被源门禁误 BLOCK;但空操作短路不得先于
488
+ // 上限判定——达上限的同目标形态必须走人工裁决 BLOCK(不得以空操作退出 0)。
489
+ {
490
+ name: '265 幂等锚:目标形态已成立的重复调用 = 空操作(零备份·零计数·零事件·零改写),超限同目标仍 BLOCK',
491
+ run: (dir) => {
492
+ writeReentryChangeDir(dir);
493
+ writeState(dir, reentryArchiveState({
494
+ currentNode: 'verify',
495
+ completedNodes: [...REENTRY_EXPECTED_INTERSECTION.verify],
496
+ }));
497
+ const bytes = readStateBytes(dir);
498
+ const beforeHistoryLength = (readScenarioState(dir).history || []).length;
499
+ const res = runReenter(dir, 'verify', { source: 'user-approval', reason: '重复调用同目标' });
500
+ assertExit(res, 0);
501
+ assertNotOut(res, 'BLOCKED');
502
+ if (outputText(res).trim() === '') {
503
+ throw new Error('空操作应打印一条可见提示');
504
+ }
505
+ assertStateBytesUnchanged(dir, bytes, '目标形态已成立的空操作');
506
+ if (reentryBackupFiles(dir).length !== 0) {
507
+ throw new Error('空操作不得备份:' + JSON.stringify(reentryBackupFiles(dir)));
508
+ }
509
+ const st = readScenarioState(dir);
510
+ if ((st.history || []).length !== beforeHistoryLength) {
511
+ throw new Error('空操作不得写事件:history 长度由 ' + beforeHistoryLength + ' 变为 ' + (st.history || []).length);
512
+ }
513
+ if ((st.history || []).some((e) => e.event === 'reentry-applied')) {
514
+ throw new Error('空操作不得写入 reentry-applied 事件');
515
+ }
516
+ // 上限判定必须先于空操作短路:达到上限的 change 即使处于同目标形态也走人工裁决 BLOCK,
517
+ // 不得以空操作退出 0(幂等豁免不越过上限;state 仍字节零改写)
518
+ writeState(dir, reentryArchiveState({
519
+ currentNode: 'verify',
520
+ completedNodes: [...REENTRY_EXPECTED_INTERSECTION.verify],
521
+ history: [reentryHistoryEvent(1), reentryHistoryEvent(2), reentryHistoryEvent(3)],
522
+ }));
523
+ const cappedBytes = readStateBytes(dir);
524
+ const cappedRes = runReenter(dir, 'verify', { source: 'user-approval', reason: '超限同目标' });
525
+ assertExit(cappedRes, 1);
526
+ assertOut(cappedRes, 'BLOCKED');
527
+ assertOut(cappedRes, '继续');
528
+ assertOut(cappedRes, '停止');
529
+ assertNotOut(cappedRes, '空操作');
530
+ assertStateBytesUnchanged(dir, cappedBytes, '超限同目标形态');
531
+ if (reentryBackupFiles(dir).length !== 0) {
532
+ throw new Error('超限同目标形态不得产生备份:' + JSON.stringify(reentryBackupFiles(dir)));
533
+ }
534
+ if ((readScenarioState(dir).history || []).length !== 3) {
535
+ throw new Error('超限同目标形态不得追加审计事件');
536
+ }
537
+ },
538
+ },
539
+
540
+ // 266: replan 授权 fail-closed(AC-2 / ADR-013 决策 5)——缺 --authorized-by / 空串 /
541
+ // 纯空白 / 缺 <reason> / 纯空白 reason → BLOCKED、state 字节(sha256)零改写、零备份、零事件;
542
+ // 授权形态由 route-node 纯函数单一权威判定(malformed → block + 合法形态放行对照)。
543
+ {
544
+ name: '266 replan 授权 fail-closed:缺/空/纯空白授权与缺原因 → BLOCKED 零改写 + 形态纯函数锚',
545
+ run: (dir) => {
546
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', REPLAN_TASK_INITIAL);
547
+ writeState(dir, replanExecuteState());
548
+ // entry 形态:真实记录修订前的任务集签名(后续修订使其成为「到期签名」)
549
+ assertExit(runGuard(['entry', 'execute'], dir), 0);
550
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', REPLAN_TASK_REVISED);
551
+ const bytes = readStateBytes(dir);
552
+ const shaBefore = createHash('sha256').update(bytes, 'utf8').digest('hex');
553
+ const blockedCases = [
554
+ ['缺 --authorized-by(仅位置 reason)', ['replan', '计划有缺陷:新增并行任务']],
555
+ ['--authorized-by 空串', ['replan', '计划有缺陷:新增并行任务', '--authorized-by', '']],
556
+ ['--authorized-by 纯空白', ['replan', '计划有缺陷:新增并行任务', '--authorized-by', ' ']],
557
+ ['缺 <reason>(仅授权)', ['replan', '--authorized-by', 'user-approval']],
558
+ ['<reason> 纯空白', ['replan', ' ', '--authorized-by', 'user-approval']],
559
+ ];
560
+ for (const [label, args] of blockedCases) {
561
+ const res = runStateWithProtocol(dir, args);
562
+ assertExit(res, 1);
563
+ assertOut(res, 'BLOCKED');
564
+ assertStateBytesUnchanged(dir, bytes, label);
565
+ const shaNow = createHash('sha256').update(readStateBytes(dir), 'utf8').digest('hex');
566
+ if (shaNow !== shaBefore) {
567
+ throw new Error(label + ':state sha256 应零改写,实际 ' + shaNow + ' ≠ ' + shaBefore);
568
+ }
569
+ }
570
+ if (replanBackupFiles(dir).length !== 0) {
571
+ throw new Error('授权非法路径不得产生备份:' + JSON.stringify(replanBackupFiles(dir)));
572
+ }
573
+ if (replanEventsOf(readScenarioState(dir)).length !== 0) {
574
+ throw new Error('授权非法路径不得写审计事件:' + JSON.stringify(replanEventsOf(readScenarioState(dir))));
575
+ }
576
+ // 授权形态纯函数锚:malformed 一律 ok:false;合法形态 ok:true 且归一化字段完整
577
+ const valid = {
578
+ round: 1,
579
+ at: '2026-09-27T00:00:00.000Z',
580
+ source: 'user-approval',
581
+ reason: '计划有缺陷',
582
+ node: 'execute',
583
+ };
584
+ const parsedValid = assertReplanAuthorizationShape(valid, 'execute', true, '合法授权三元组');
585
+ if (!parsedValid.authorization || parsedValid.authorization.source !== 'user-approval'
586
+ || parsedValid.authorization.reason !== '计划有缺陷' || parsedValid.authorization.node !== 'execute') {
587
+ throw new Error('合法授权的归一化结果不完整:' + JSON.stringify(parsedValid.authorization));
588
+ }
589
+ const malformed = [
590
+ ['缺 authorization', undefined],
591
+ ['authorization 为数组', []],
592
+ ['round=0', { ...valid, round: 0 }],
593
+ ['round 非整数', { ...valid, round: 1.5 }],
594
+ ['round 类型错误', { ...valid, round: '1' }],
595
+ ['at 空串', { ...valid, at: '' }],
596
+ ['at 纯空白', { ...valid, at: ' ' }],
597
+ ['at 类型错误', { ...valid, at: 42 }],
598
+ ['source 空串', { ...valid, source: '' }],
599
+ ['source 纯空白', { ...valid, source: ' ' }],
600
+ ['source 类型错误', { ...valid, source: [] }],
601
+ ['node 与调用不一致', { ...valid, node: 'subagent-execute' }],
602
+ ];
603
+ for (const [label, authorization] of malformed) {
604
+ assertReplanAuthorizationShape(authorization, 'execute', false, label);
605
+ }
606
+ // 综合判定的未授权路径:非法授权 → block(不抛异常、不写盘;零改写由上方 CLI 用例锚定)
607
+ const decide = requireRouteNodeExport('resolveReplanDecision');
608
+ const decideState = replanExecuteState();
609
+ for (const [label, authorization] of malformed) {
610
+ const decision = decide({ protocol: readScenarioProtocol(dir), state: decideState, authorization });
611
+ if (!decision || decision.ok !== false || decision.action !== 'block') {
612
+ throw new Error('[' + label + '] resolveReplanDecision 应返回 block,实际 ' + JSON.stringify(decision));
613
+ }
614
+ }
615
+ // 纯函数族存在性锚(T03 交付面):五项导出缺任一即本场景 RED
616
+ requireRouteNodeExport('replanRoundCount');
617
+ requireRouteNodeExport('replanRoundDecision');
618
+ requireRouteNodeExport('replanNoOpDecision');
619
+ },
620
+ },
621
+
622
+ // 267a: replan 校验不豁免(ADR-013 决策 3 / 明确 out:replan 绝不做校验豁免)——依赖环 /
623
+ // 缺失依赖 / 缺 <verify> / 并行写冲突四类任务集在 replan 上一律 BLOCKED 且状态零改写;
624
+ // 并且 plan 出口与 replan 对同一输入给出同一机器分类。
625
+ {
626
+ name: '267a replan 校验不豁免:四类任务集 BLOCKED 零改写 + 任务图分析/写冲突检测单源锚',
627
+ run: async (dir) => {
628
+ const cases = [
629
+ ['依赖环', TASK_DEP_CYCLE, '依赖环', '依赖环'],
630
+ ['依赖不存在的任务', TASK_MISSING_DEP, '依赖不存在的任务', '依赖'],
631
+ ['缺 <verify> 字段', REPLAN_TASK_NO_VERIFY, '缺 <verify> 字段', 'verify'],
632
+ ['并行写冲突', TASK_PARALLEL_WRITE_CONFLICT, 'write_files', '并行写冲突'],
633
+ ];
634
+ for (const [label, taskContent, planExpected, replanExpected] of cases) {
635
+ // ① plan 出口(既有判定路径)对同一输入的机器分类
636
+ const planState = baseState('plan');
637
+ planState.evidence.plan = { summary: 'plan done' };
638
+ planState.newChange = true;
639
+ writeState(dir, planState);
640
+ const planRes = runPlanExit(dir, taskContent);
641
+ assertExit(planRes, 1);
642
+ assertOut(planRes, 'BLOCKED');
643
+ assertOut(planRes, planExpected);
644
+ // ② replan 对同一输入:同一分类 + BLOCKED + state 零改写
645
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', taskContent);
646
+ writeState(dir, replanExecuteState({ taskHash: REPLAN_STALE_SIGNATURE }));
647
+ const bytes = readStateBytes(dir);
648
+ const replanRes = runStateWithProtocol(dir, ['replan', '计划缺陷重校', '--authorized-by', 'user-approval']);
649
+ assertExit(replanRes, 1);
650
+ assertOut(replanRes, 'BLOCKED');
651
+ assertOut(replanRes, replanExpected);
652
+ assertStateBytesUnchanged(dir, bytes, 'replan ' + label);
653
+ // 显式 sha256 前后相同(字节零改写的独立哈希表达:断言覆盖完整契约而非关键词)
654
+ const shaBefore = createHash('sha256').update(bytes).digest('hex');
655
+ const shaAfter = createHash('sha256').update(readStateBytes(dir)).digest('hex');
656
+ if (shaBefore !== shaAfter) {
657
+ throw new Error(label + ':replan BLOCK 路径 state sha256 应前后相同,实际 '
658
+ + shaBefore + ' → ' + shaAfter);
659
+ }
660
+ if (replanBackupFiles(dir).length !== 0) {
661
+ throw new Error(label + ':校验失败路径不得产生备份');
662
+ }
663
+ if (replanEventsOf(readScenarioState(dir)).length !== 0) {
664
+ throw new Error(label + ':校验失败路径不得写审计事件');
665
+ }
666
+ }
667
+ // 读写弱判(read∩write,plan 出口同判据):仅 WARN 不阻断——replan 照常重签、写重签前备份、
668
+ // 写审计事件(覆盖写写强判之外的非阻断分支)。
669
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', TASK_PARALLEL_READ_OVERLAP);
670
+ writeState(dir, replanExecuteState({ taskHash: REPLAN_STALE_SIGNATURE }));
671
+ const readWarnRes = runStateWithProtocol(dir, ['replan', '计划缺陷重校', '--authorized-by', 'user-approval']);
672
+ assertExit(readWarnRes, 0);
673
+ assertOut(readWarnRes, 'REPLAN:');
674
+ assertOut(readWarnRes, 'WARN: TASK.md 并行任务 read∩write 隐式依赖嫌疑');
675
+ assertOut(readWarnRes, 'P02×P01(src/shared.mjs)'); // 输出为「读取方×写入方」(P02 读 P01 写路径)
676
+ if (replanBackupFiles(dir).length !== 1) {
677
+ throw new Error('read∩write 弱判不得阻断 replan:应恰有 1 份重签前备份,实际 '
678
+ + replanBackupFiles(dir).length);
679
+ }
680
+ if (replanEventsOf(readScenarioState(dir)).length !== 1) {
681
+ throw new Error('read∩write 弱判不得阻断 replan:应写入 1 条 replan-applied 审计事件,实际 '
682
+ + replanEventsOf(readScenarioState(dir)).length);
683
+ }
684
+ // 同源结构锚:任务图分析全引擎只有一处定义,且位于 route-node.mjs(可由 replan 复用)
685
+ const analyze = requireRouteNodeExport('analyzeDependencyGraph');
686
+ const cyclicBlocks = TASK_DEP_CYCLE.match(/<task[\s\S]*?<\/task>/g) || [];
687
+ const verdict = analyze(cyclicBlocks);
688
+ if (!verdict || verdict.cyclic !== true || !Array.isArray(verdict.cycleIds) || verdict.cycleIds.length === 0) {
689
+ throw new Error('route-node 导出的任务图分析对依赖环应返回 cyclic=true + cycleIds,实际 ' + JSON.stringify(verdict));
690
+ }
691
+ const missingVerdict = analyze(TASK_MISSING_DEP.match(/<task[\s\S]*?<\/task>/g) || []);
692
+ if (!missingVerdict || missingVerdict.missing.length === 0 || missingVerdict.cyclic !== false) {
693
+ throw new Error('route-node 导出的任务图分析对缺失依赖应返回 missing 明细,实际 ' + JSON.stringify(missingVerdict));
694
+ }
695
+ // 同源结构锚:任务图分析与并行写冲突检测在**引擎面内**只有一处定义,消费方(入口 ∪
696
+ // `lib/**`,由真实引用派生)一律从单源取用——「实现位于哪个文件名」不再在锚里存第二份事实
697
+ //(落点由导出符号反查),模块再切分 / 再搬家不必改锚。判据与反向构造探针共用
698
+ // `singleSourceImportProblems`(单一实现)。
699
+ const engineTexts = engineScriptTexts();
700
+ const singleSourceCases = [
701
+ ['analyzeDependencyGraph', '任务图分析'],
702
+ ['findParallelWriteConflicts', '并行写冲突检测'],
703
+ ];
704
+ for (const [symbol, label] of singleSourceCases) {
705
+ const source = engineDefinitionModule(symbol);
706
+ if (source === null) {
707
+ throw new Error(label + '必须只有一份实现(全引擎面内),实际定义处: '
708
+ + JSON.stringify(engineDefinitionHits(symbol)));
709
+ }
710
+ const sourceProblems = singleSourceImportProblems({ symbol, sourceRel: source.file, texts: engineTexts });
711
+ if (sourceProblems.length > 0) {
712
+ throw new Error(label + '单源面被破坏(消费方须从 ' + source.file + ' 或其再导出枢纽取用): '
713
+ + sourceProblems.join(' | '));
714
+ }
715
+ // 反向构造(同一判据驱动 · 探针目标数据驱动):① 消费方自建第二份定义 ⇒ 必红;
716
+ // ② 消费方 import 被抽掉 ⇒ 必红;两项都改坏后判据仍须在还原输入上复绿。
717
+ const consumer = engineConsumersOf(symbol).find((rel) => rel !== source.file);
718
+ if (consumer === undefined) throw new Error('反向构造前提不成立:' + symbol + ' 找不到消费方');
719
+ const consumerText = engineTexts.get(consumer);
720
+ const probes = [
721
+ [consumer + ' 自建第二份定义',
722
+ new Map(engineTexts).set(consumer, consumerText + '\nfunction ' + symbol + '(probe) { return null; }\n'),
723
+ '单一来源被破坏'],
724
+ [consumer + ' 不再取用(import 被抽掉)',
725
+ new Map(engineTexts).set(consumer, dropNamedImport(consumerText, symbol)),
726
+ '未从'],
727
+ ];
728
+ for (const [probeLabel, mutated, expected] of probes) {
729
+ const reported = singleSourceImportProblems({ symbol, sourceRel: source.file, texts: mutated });
730
+ if (!reported.some((problem) => problem.includes(expected))) {
731
+ throw new Error('反向构造判别力缺失(' + probeLabel + ' 未被判违规): ' + JSON.stringify(reported));
732
+ }
733
+ }
734
+ }
735
+ // 第三族结果的产者/消费者面:产出只在唯一模块(下面 267b ① 覆盖构件面),此处锁「guard 链
736
+ // 必须真的消费它」——消费方由真实引用派生,落在 guard 入口的 import 闭包内(不写文件名)。
737
+ const guardClosure = engineReachableFrom(['workflow-guard.mjs']);
738
+ const thirdFamilyConsumers = engineConsumersOf('crossTaskConflicts')
739
+ .filter((rel) => guardClosure.has(rel));
740
+ if (thirdFamilyConsumers.length === 0) {
741
+ throw new Error('workflow-guard 的判定链未消费第三族结果(plan 出口判定缺失;消费方须在 guard 入口的 import 闭包内)');
742
+ }
743
+ },
744
+ },
745
+
746
+ // 267b: 同源静态锚(第三族:同文件跨任务且无依赖路径)——判定构件与结果产出在**引擎面**(入口 ∪
747
+ // `lib/**`,由真实引用派生)里只能出现一次(落点由符号反查,不写文件名);修复族「只表达一次」
748
+ // 边界锚 + 该判据自身的合成夹具锚;replan 侧结构锚(解构 / BLOCK 早于备份 / 消息与恢复指引与
749
+ // plan 出口同族)。
750
+ {
751
+ name: '267b 第三族同源静态锚:构件唯一表达 + 修复族边界锚 + replan 消费锚',
752
+ run: (dir) => {
753
+ // —— 本批 in-place 增锚(第三族:同文件跨任务且无依赖路径)——
754
+ // ① 单一表达锚(结构事实而非注释声明):第三族的构件(修复任务族前缀常量 / 任务对键 /
755
+ // 依赖可达闭包)与结果产出在引擎面内只能出现一次——消费脚本内自建第二份(依赖闭包或
756
+ // 写入面交集实现)会在此变红。落点不写文件名(构件在哪个模块由符号自身回答);注释行
757
+ // 不计(注释里提到标识符是说明,不是第二份实现)。
758
+ // 真实判据与下方的反向构造探针**共用本函数**(同一判据只有一处实现,探针才不会与锚漂移)。
759
+ const thirdFamilyProblems = (texts) => {
760
+ const out = [];
761
+ for (const piece of ['FIX_TASK_ID_PREFIX', 'taskPairKey', 'reachableTaskIds']) {
762
+ const pieceRe = new RegExp('\\b' + piece + '\\b');
763
+ const holders = [...texts.entries()]
764
+ .filter(([, text]) => pieceRe.test(engineCodeText(text))).map(([rel]) => rel);
765
+ if (holders.length !== 1) {
766
+ out.push('第三族判定构件 ' + piece + ' 必须只在一个引擎模块里表达,实际: ' + JSON.stringify(holders));
767
+ }
768
+ }
769
+ const producers = [...texts.entries()]
770
+ .filter(([, text]) => /const\s+crossTaskConflicts\s*=/.test(engineCodeText(text))).map(([rel]) => rel);
771
+ if (producers.length !== 1) {
772
+ out.push('第三族结果只能由一个引擎模块产出(不得在消费脚本内内联),实际: ' + JSON.stringify(producers));
773
+ }
774
+ return out;
775
+ };
776
+ const thirdFamilyTexts = engineScriptTexts();
777
+ const thirdFamilyFound = thirdFamilyProblems(thirdFamilyTexts);
778
+ if (thirdFamilyFound.length > 0) throw new Error(thirdFamilyFound.join(' | '));
779
+ // ①b 反向构造(判别力**数据驱动**,不依赖全局计数地板):把构件名 / 结果产出扩散到第二个
780
+ // 引擎模块 ⇒ 同一判据必红;还原输入 ⇒ 复绿。
781
+ const thirdFamilyProbes = [
782
+ ['构件名扩散到第二个模块', 'lib/guard-gates.mjs', '\nconst probeTaskPairKey = taskPairKey;\n'],
783
+ ['第三族结果在第二个模块产出', 'lib/guard-gates.mjs', '\nconst crossTaskConflicts = [];\n'],
784
+ ];
785
+ for (const [probeLabel, rel, injected] of thirdFamilyProbes) {
786
+ const mutated = new Map(thirdFamilyTexts).set(rel, thirdFamilyTexts.get(rel) + injected);
787
+ if (thirdFamilyProblems(mutated).length === 0) {
788
+ throw new Error('反向构造判别力缺失(' + probeLabel + ' 未被判违规)');
789
+ }
790
+ }
791
+ if (thirdFamilyProblems(thirdFamilyTexts).length !== 0) {
792
+ throw new Error('反向构造还原后未复绿(判据受输入顺序影响)');
793
+ }
794
+ // ①b 修复族约定「只表达一次」锚(判别力升级:按表达式形态计数,不再只数标识符名)——
795
+ // 两条边界(id 前缀 / 「位于修复段内」)各只允许一处实现,第三族参与者排除与修复族
796
+ // 标记必须共用同一分类器;第二份等价前缀表达式(含内联前缀判定)在此变红。
797
+ // 旧锚只统计"哪个文件含该常量名":第二份写法(不含该名字的等价正则)必然被放过——
798
+ // 本锚即对该盲区的判别力补齐。
799
+ for (const problem of fixFamilyBoundaryProblems()) {
800
+ throw new Error('修复族约定未被唯一表达: ' + problem);
801
+ }
802
+ // ①b-1 该判据自身的夹具锚(常驻判别力,不依赖外部临时注入):同源形态 → 无问题;
803
+ // 逐条注入"同一约定被表达两次"的变体 → 逐条专项报告。夹具目录即判据的 scriptsDir
804
+ // 接缝(合成引擎脚本,不被执行、只被扫描)。
805
+ const engineFixtureDir = path.join(dir, 'engine-fixture');
806
+ // 夹具文本的权威前缀表达式自模块常量拼接(不在夹具里再写一份字面量——同源才测得准)
807
+ const canonicalPrefixDecl = 'const FIX_TASK_ID_PREFIX = ' + FIX_PREFIX_LITERAL_TEXT + ';';
808
+ const canonicalEngine = [
809
+ canonicalPrefixDecl,
810
+ 'function fixTaskClassifier(taskContent, fixSectionTitle) {',
811
+ ' const section = fixSectionBody(taskContent, fixSectionTitle);',
812
+ ' const sectionBlocks = new Set(section === null ? [] : taskBlocks(section));',
813
+ ' return (block) => FIX_TASK_ID_PREFIX.test(taskOpeningAttrs(block).id) || sectionBlocks.has(block);',
814
+ '}',
815
+ 'function fixTaskMarker(taskContent, fixSectionTitle) {',
816
+ ' const isFixTask = fixTaskClassifier(taskContent, fixSectionTitle);',
817
+ ' return taskBlocks(String(taskContent ?? "")).some((block) => isFixTask(block));',
818
+ '}',
819
+ 'function collectCrossTaskConflicts({ taskContent = "", allBlocks = [] } = {}) {',
820
+ ' const isFixTask = fixTaskClassifier(taskContent);',
821
+ ' return allBlocks.filter((block) => !isFixTask(block));',
822
+ '}',
823
+ '',
824
+ ].join('\n');
825
+ const fixtureFileRel = path.join('engine-fixture', 'route-node.mjs');
826
+ writeFile(dir, fixtureFileRel, canonicalEngine);
827
+ const canonicalProblems = fixFamilyBoundaryProblems(engineFixtureDir);
828
+ if (canonicalProblems.length !== 0) {
829
+ throw new Error('唯一表达形态不得报问题(判据夹具模板): ' + JSON.stringify(canonicalProblems));
830
+ }
831
+ const boundaryCases = [
832
+ ['第二份前缀表达式', canonicalEngine + 'const legacyFixPrefix = /^(T-FIX|P-FIX)/i;\n',
833
+ '第二份修复族 id 前缀表达式'],
834
+ ['内联前缀判定(id 字面量)', canonicalEngine + 'const legacyIds = ["T-FIX-01"];\n',
835
+ '修复族 id 字面量'],
836
+ ['前缀边界被删', canonicalEngine.replace(canonicalPrefixDecl, 'const FIX_TASK_ID_PREFIX = /nope/;'),
837
+ '修复族 id 前缀边界必须只表达一次'],
838
+ ['段内成员判定第二份',
839
+ canonicalEngine.replace(' return allBlocks.filter((block) => !isFixTask(block));',
840
+ ' sectionBlocks.has({});\n return allBlocks.filter((block) => !isFixTask(block));'),
841
+ '段内成员判定)必须只表达一次'],
842
+ ['消费方自持边界(不共用分类器)',
843
+ canonicalEngine.replace(' const isFixTask = fixTaskClassifier(taskContent);',
844
+ ' const isFixTask = () => false;'),
845
+ '必须经唯一分类器判定修复族'],
846
+ ];
847
+ for (const [label, mutated, expected] of boundaryCases) {
848
+ writeFile(dir, fixtureFileRel, mutated);
849
+ const mutatedProblems = fixFamilyBoundaryProblems(engineFixtureDir);
850
+ if (!mutatedProblems.some((p) => p.includes(expected))) {
851
+ throw new Error('修复族边界反向夹具(' + label + ')未按预期报告「' + expected + '」: '
852
+ + JSON.stringify(mutatedProblems));
853
+ }
854
+ }
855
+ // ①c replan 消费锚(结构锚;replan 的真实命令链路由系统测试集承担,此处不重复造链路):
856
+ // 第三族必须①被解构(只解构两族 = 静默丢失该判据,即修订通道可静默引入该形态)、
857
+ // ②在 BLOCK 早于备份与写盘的位置判定、③消息与恢复指引与 plan 出口同族(新 change
858
+ // 阻断 / 旧 change 渐进)。判据读的是**replan 命令实现所在模块**的文本——落点由导出
859
+ // 符号反查(`runReplan`),不写文件名(模块再切分不必改锚)。
860
+ const replanModule = engineDefinitionModule('runReplan');
861
+ if (replanModule === null) {
862
+ throw new Error('replan 命令的实现落点不唯一(应恰一处): '
863
+ + JSON.stringify(engineDefinitionHits('runReplan')));
864
+ }
865
+ const stateText = replanModule.text;
866
+ const replanProblems = (text) => {
867
+ const out = [];
868
+ const destructured = text.match(/const\s*\{([^}]*)\}\s*=\s*await\s+findParallelWriteConflicts\s*\(/);
869
+ if (destructured === null || !/\bcrossTaskConflicts\b/.test(destructured[1])) {
870
+ out.push('replan 必须解构第三族结果(只解构两族即静默丢失该判据): '
871
+ + JSON.stringify(destructured === null ? null : destructured[1].trim()));
872
+ }
873
+ const crossJudgeAt = text.indexOf('crossTaskConflicts.length > 0');
874
+ const backupAt = text.indexOf('-pre-replan.json');
875
+ if (crossJudgeAt < 0) out.push('replan 未消费第三族(缺判定分支)');
876
+ else if (backupAt < 0 || crossJudgeAt > backupAt) {
877
+ out.push('replan 的第三族判定必须早于重签前备份(BLOCK 早于落盘的零改写语义): '
878
+ + '判定位置 ' + crossJudgeAt + ' / 备份位置 ' + backupAt);
879
+ }
880
+ for (const message of ['同文件跨任务且无依赖路径', '补显式 depends_on 或合并为一个任务']) {
881
+ if (!text.includes(message)) out.push('replan 的第三族消息必须与 plan 出口同族(缺「' + message + '」)');
882
+ }
883
+ return out;
884
+ };
885
+ const replanFound = replanProblems(stateText);
886
+ if (replanFound.length > 0) throw new Error(replanModule.file + ': ' + replanFound.join(' | '));
887
+ // 反向构造(同一判据驱动 · 目标数据驱动):逐项抽掉承载 ⇒ 必红;还原 ⇒ 复绿。
888
+ const replanProbes = [
889
+ ['第三族解构被抽掉',
890
+ stateText.replace('crossTaskConflicts, ', ''), 'replan 必须解构第三族结果'],
891
+ ['第三族判定被抽掉',
892
+ stateText.replace('crossTaskConflicts.length > 0', 'writeConflicts.length > 0'), 'replan 未消费第三族'],
893
+ ['判定挪到备份之后',
894
+ stateText.replace('-pre-replan.json', 'crossTaskConflicts.length > 0')
895
+ .replace('crossTaskConflicts.length > 0', '-pre-replan.json'), '必须早于重签前备份'],
896
+ ['同族消息被抽掉',
897
+ stateText.replaceAll('同文件跨任务且无依赖路径', '(反向构造:抽掉)'), '必须与 plan 出口同族'],
898
+ ];
899
+ for (const [probeLabel, mutated, expected] of replanProbes) {
900
+ if (mutated === stateText) throw new Error('反向构造前提不成立(' + probeLabel + ' 未改变输入)');
901
+ if (!replanProblems(mutated).some((problem) => problem.includes(expected))) {
902
+ throw new Error('反向构造判别力缺失(' + probeLabel + ' 未被判违规)');
903
+ }
904
+ }
905
+ if (replanProblems(stateText).length !== 0) throw new Error('反向构造还原后未复绿');
906
+ if (!/WARN: TASK\.md 同文件跨任务且无依赖路径(旧 change 渐进不阻断)/.test(stateText)) {
907
+ throw new Error('replan 的第三族必须保留旧 change 渐进分支(WARN 不阻断)');
908
+ }
909
+ },
910
+ },
911
+
912
+ // 267c: 第三族的判定行为与出口链路——非修复同文件对命中、修复族对不参与(含段归属与 CRLF
913
+ // 行尾归一)、plan 出口 BLOCKED 消息带任务对与重叠文件、混合夹具只报非修复对。
914
+ {
915
+ name: '267c 第三族行为与出口链路:判定命中 / 修复族排除 / BLOCKED 消息 / 混合夹具',
916
+ run: async (dir) => {
917
+ const findConflicts = requireRouteNodeExport('findParallelWriteConflicts');
918
+ // ② 行为锚(直接驱动判定函数,plan 出口与 replan 共用同一实现):非修复同文件对命中、
919
+ // 修复任务族对不参与(其顺序由修复生命周期保证,回修同文件是必然形态)。
920
+
921
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', '# TASK\n\n## 任务清单\n\n' + CROSS_TASK_PLAIN_PAIR);
922
+ const plainConflicts = await findConflicts(path.join(dir, '.specs', CHANGE_ID));
923
+ if (plainConflicts.crossTaskConflicts.length !== 1
924
+ || plainConflicts.crossTaskConflicts[0].files.join(',') !== 'src/shared.mjs') {
925
+ throw new Error('非修复同文件无依赖对必须命中第三族: ' + JSON.stringify(plainConflicts.crossTaskConflicts));
926
+ }
927
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', '# TASK\n\n## 任务清单\n\n' + CROSS_TASK_FIX_PAIR);
928
+ const fixConflicts = await findConflicts(path.join(dir, '.specs', CHANGE_ID));
929
+ if (fixConflicts.crossTaskConflicts.length !== 0 || fixConflicts.writeConflicts.length !== 0) {
930
+ throw new Error('修复任务族对不得进入第三族(也不得进入写写强判): ' + JSON.stringify(fixConflicts));
931
+ }
932
+ // ②-附 段归属分支 + 行尾归一(LF 与 CRLF 两形态都必须识别为修复族):
933
+ // 段内块来自 LF 归一后的段体,而待判 block 来自原文——Windows 下原文是 CRLF,
934
+ // 不归一会让段内匹配失败 → 修复族对被当普通参与者误拦。
935
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md',
936
+ '# TASK\n\n## 任务清单\n\n' + CROSS_TASK_FIX_SECTION_PAIR);
937
+ const sectionConflicts = await findConflicts(path.join(dir, '.specs', CHANGE_ID));
938
+ if (sectionConflicts.crossTaskConflicts.length !== 0 || sectionConflicts.writeConflicts.length !== 0) {
939
+ throw new Error('修复段内**非前缀 id** 的任务对不得进入第三族(段归属分支): '
940
+ + JSON.stringify(sectionConflicts));
941
+ }
942
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md',
943
+ '# TASK\r\n\r\n## 任务清单\r\n\r\n' + CROSS_TASK_FIX_SECTION_PAIR.replace(/\n/g, '\r\n'));
944
+ const crlfConflicts = await findConflicts(path.join(dir, '.specs', CHANGE_ID));
945
+ if (crlfConflicts.crossTaskConflicts.length !== 0 || crlfConflicts.writeConflicts.length !== 0) {
946
+ throw new Error('CRLF 行尾下修复段归属判定必须一致(行尾归一口径): ' + JSON.stringify(crlfConflicts));
947
+ }
948
+ // ③ 出口链路锚(新 change):非修复对照对 → BLOCKED 且消息带任务对与重叠文件;
949
+ // 修复族对 → exit 0 且不出现该族消息(BLOCKED / WARN 两形态都不许有)。
950
+ const crossState = baseState('plan');
951
+ crossState.evidence.plan = { summary: 'plan done' };
952
+ crossState.newChange = true;
953
+ writeState(dir, crossState);
954
+ const plainRes = runPlanExit(dir, CROSS_TASK_PLAIN_PAIR);
955
+ assertExit(plainRes, 1);
956
+ assertOut(plainRes, 'BLOCKED');
957
+ assertOut(plainRes, '同文件跨任务且无依赖路径');
958
+ assertOut(plainRes, 'T01×T02');
959
+ assertOut(plainRes, 'src/shared.mjs');
960
+ assertOut(plainRes, 'depends_on');
961
+ writeState(dir, crossState);
962
+ const fixRes = runPlanExit(dir, CROSS_TASK_FIX_PAIR);
963
+ assertExit(fixRes, 0);
964
+ assertNotOut(fixRes, '同文件跨任务');
965
+ assertNotOut(fixRes, 'BLOCKED');
966
+ // ④ 混合夹具:两类并存 → 只报非修复对(修复族对不出现在消息里)
967
+ writeState(dir, crossState);
968
+ const mixedRes = runPlanExit(dir, CROSS_TASK_MIXED_PAIR);
969
+ assertExit(mixedRes, 1);
970
+ assertOut(mixedRes, 'BLOCKED');
971
+ assertOut(mixedRes, 'T01×T02');
972
+ assertNotOut(mixedRes, 'T-FIX-01×T-FIX-02');
973
+ },
974
+ },
975
+
976
+ // 268: replan 轮次上限与显式续轮(AC-3 / ADR-013 决策 6)——按 history 中本 change 的
977
+ // replan-applied 事件计数,上限 3:第 4 次 BLOCKED 且给出「继续 / 停止」人工裁决指引;
978
+ // --continue-round <n> 满足 n ≥ 已用 + 1 才放行并计入下一轮(审计事件 / 授权留痕带续轮标记);
979
+ // n 不足则 BLOCK 零改写;轮次按 change 隔离(他 change 的事件不占本 change 配额)。
980
+ {
981
+ name: '268 replan 轮次上限 3 与显式续轮:超限 BLOCK 人工裁决·续轮放行计下一轮·授权不足 BLOCK·跨 change 隔离',
982
+ run: (dir) => {
983
+ const baseHistory = [replanHistoryEvent(1), replanHistoryEvent(2), replanHistoryEvent(3)];
984
+ const blockedCases = [
985
+ ['超限未续轮', []],
986
+ ['续轮授权轮次不足(n=3 < 已用+1)', ['--continue-round', '3']],
987
+ ];
988
+ for (const [label, extra] of blockedCases) {
989
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', REPLAN_TASK_REVISED);
990
+ writeState(dir, replanExecuteState({ history: [...baseHistory], taskHash: REPLAN_STALE_SIGNATURE }));
991
+ const bytes = readStateBytes(dir);
992
+ const res = runStateWithProtocol(dir, ['replan', '计划缺陷重校', '--authorized-by', 'user-approval', ...extra]);
993
+ assertExit(res, 1);
994
+ assertOut(res, 'BLOCKED');
995
+ assertOut(res, '继续');
996
+ assertOut(res, '停止');
997
+ assertStateBytesUnchanged(dir, bytes, label);
998
+ if (replanBackupFiles(dir).length !== 0) {
999
+ throw new Error(label + ':上限拦截不得产生备份');
1000
+ }
1001
+ if (replanEventsOf(readScenarioState(dir)).length !== 3) {
1002
+ throw new Error(label + ':上限拦截不得追加审计事件');
1003
+ }
1004
+ }
1005
+ // 显式续轮放行:n = 已用 + 1 → 计入第 4 轮(审计行标注续轮)
1006
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', REPLAN_TASK_REVISED);
1007
+ writeState(dir, replanExecuteState({ history: [...baseHistory], taskHash: REPLAN_STALE_SIGNATURE }));
1008
+ const continued = runStateWithProtocol(
1009
+ dir, ['replan', '计划缺陷重校(上限后显式续轮)', '--authorized-by', 'admin-approval', '--continue-round', '4']);
1010
+ assertExit(continued, 0);
1011
+ assertOut(continued, 'REPLAN');
1012
+ assertOut(continued, '续轮');
1013
+ const continuedState = readScenarioState(dir);
1014
+ const continuedEvents = replanEventsOf(continuedState);
1015
+ if (continuedEvents.length !== 4) {
1016
+ throw new Error('续轮放行应写入第 4 条 replan-applied 事件,实际 ' + JSON.stringify(continuedEvents.length));
1017
+ }
1018
+ const continuedEvent = continuedEvents[continuedEvents.length - 1];
1019
+ if (continuedEvent.round !== 4 || continuedEvent.change !== CHANGE_ID
1020
+ || continuedEvent.reason !== '计划缺陷重校(上限后显式续轮)'
1021
+ || continuedEvent.continuationAuthorized !== true) {
1022
+ throw new Error('续轮审计事件字段不符(round=4 / change / 续轮标记 / reason):' + JSON.stringify(continuedEvent));
1023
+ }
1024
+ const continuedRecord = continuedState.evidence?.execute?.replanAuthorization;
1025
+ if (!continuedRecord || continuedRecord.continuationAuthorized !== true
1026
+ || continuedRecord.round !== 4 || continuedRecord.source !== 'admin-approval') {
1027
+ throw new Error('续轮授权留痕不符:' + JSON.stringify(continuedRecord));
1028
+ }
1029
+ assertReplanSignatureRecorded(continuedState, REPLAN_TASK_REVISED, '续轮放行');
1030
+ if (replanBackupFiles(dir).length !== 1) {
1031
+ throw new Error('续轮放行应产生一份备份,实际 ' + JSON.stringify(replanBackupFiles(dir)));
1032
+ }
1033
+ // 跨 change 隔离:他 change 的 3 条事件不占本 change 配额 → 本 change 为第 1 轮
1034
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', REPLAN_TASK_REVISED);
1035
+ writeState(dir, replanExecuteState({
1036
+ history: [replanHistoryEvent(1, 'other-change'), replanHistoryEvent(2, 'other-change'), replanHistoryEvent(3, 'other-change')],
1037
+ taskHash: REPLAN_STALE_SIGNATURE,
1038
+ }));
1039
+ const isolated = runStateWithProtocol(dir, ['replan', '计划缺陷重校', '--authorized-by', 'user-approval']);
1040
+ assertExit(isolated, 0);
1041
+ assertOut(isolated, 'REPLAN');
1042
+ assertOut(isolated, '1/3');
1043
+ const isolatedEvent = replanEventsOf(readScenarioState(dir)).find((e) => e.change === CHANGE_ID);
1044
+ if (!isolatedEvent || isolatedEvent.round !== 1) {
1045
+ throw new Error('他 change 的轮次事件不应占用本 change 配额(本 change 应为第 1 轮),实际 '
1046
+ + JSON.stringify(isolatedEvent));
1047
+ }
1048
+ // 轮次判定纯函数锚(阈值只从实现常量取——本锚同时锁上限 = 3)
1049
+ const roundCount = requireRouteNodeExport('replanRoundCount');
1050
+ if (roundCount({ history: baseHistory, changeName: CHANGE_ID }) !== 3) {
1051
+ throw new Error('replanRoundCount 应统计本 change 的 replan-applied 事件数(3)');
1052
+ }
1053
+ if (roundCount({ history: baseHistory, changeName: 'other-change' }) !== 0) {
1054
+ throw new Error('replanRoundCount 应按 change 过滤(他 change 应为 0)');
1055
+ }
1056
+ if (roundCount({ history: 'corrupted', changeName: CHANGE_ID }) !== 0) {
1057
+ throw new Error('replanRoundCount 对非数组 history 应返回 0(旧 state 形态)');
1058
+ }
1059
+ const roundDecision = requireRouteNodeExport('replanRoundDecision');
1060
+ const available = roundDecision({ history: [replanHistoryEvent(1)], changeName: CHANGE_ID });
1061
+ if (!available || available.ok !== true || available.nextRound !== 2 || available.limit !== 3) {
1062
+ throw new Error('replanRoundDecision 未达上限应放行并给出下一轮:' + JSON.stringify(available));
1063
+ }
1064
+ const capped = roundDecision({ history: baseHistory, changeName: CHANGE_ID });
1065
+ if (!capped || capped.ok !== false || capped.limit !== 3) {
1066
+ throw new Error('replanRoundDecision 达上限且无续轮应 blocked:' + JSON.stringify(capped));
1067
+ }
1068
+ const continuation = roundDecision({ history: baseHistory, changeName: CHANGE_ID, continuationAuthorized: true });
1069
+ if (!continuation || continuation.ok !== true || continuation.nextRound !== 4) {
1070
+ throw new Error('replanRoundDecision 持显式续轮授权应放行第 4 轮:' + JSON.stringify(continuation));
1071
+ }
1072
+ },
1073
+ },
1074
+
1075
+ // 269: replan 幂等空操作(AC-5 / ADR-013 决策 9)——目标形态已成立(state.taskHash 已等于
1076
+ // 当前 TASK.md 签名)时重复调用 = 空操作:可见提示 + 零备份 / 零轮次计数 / 零事件 /
1077
+ // state 字节零改写(与 archive 重入的幂等锚同构)。
1078
+ {
1079
+ name: '269 replan 幂等空操作:重签后重复同形态 → 零备份·零轮次·零事件·零改写',
1080
+ run: (dir) => {
1081
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', REPLAN_TASK_REVISED);
1082
+ writeState(dir, replanExecuteState({ taskHash: REPLAN_STALE_SIGNATURE }));
1083
+ const first = runStateWithProtocol(dir, ['replan', '计划缺陷重校', '--authorized-by', 'user-approval']);
1084
+ assertExit(first, 0);
1085
+ assertOut(first, 'REPLAN');
1086
+ const afterApply = readStateBytes(dir);
1087
+ const appliedState = readScenarioState(dir);
1088
+ if (replanEventsOf(appliedState).length !== 1) {
1089
+ throw new Error('首次重签应恰写 1 条 replan-applied 事件,实际 '
1090
+ + JSON.stringify(replanEventsOf(appliedState).length));
1091
+ }
1092
+ const backupsAfterApply = replanBackupFiles(dir);
1093
+ if (backupsAfterApply.length !== 1) {
1094
+ throw new Error('首次重签应恰产生一份备份,实际 ' + JSON.stringify(backupsAfterApply));
1095
+ }
1096
+ assertReplanSignatureRecorded(appliedState, REPLAN_TASK_REVISED, '首次重签');
1097
+ // 同形态重复调用 → 空操作(零副作用)
1098
+ const noop = runStateWithProtocol(dir, ['replan', '重复调用同形态', '--authorized-by', 'user-approval']);
1099
+ assertExit(noop, 0);
1100
+ assertOut(noop, '空操作');
1101
+ assertNotOut(noop, 'BLOCKED');
1102
+ assertStateBytesUnchanged(dir, afterApply, '重复同形态空操作');
1103
+ if (!isDeepStrictEqual(replanBackupFiles(dir), backupsAfterApply)) {
1104
+ throw new Error('空操作不得新增备份:' + JSON.stringify(replanBackupFiles(dir)));
1105
+ }
1106
+ if (replanEventsOf(readScenarioState(dir)).length !== 1) {
1107
+ throw new Error('空操作不得写审计事件(history 长度漂移)');
1108
+ }
1109
+ // 空操作判定纯函数存在性锚(T04 编排消费的判定点)
1110
+ requireRouteNodeExport('replanNoOpDecision');
1111
+ },
1112
+ },
1113
+
1114
+ // 270: 重签后 execute 出口放行(AC-1)——entry 后修订任务集(计划外新增并行就绪任务)使
1115
+ // exit execute 撞签名门禁 → replan 重校重签 → 同一出口再跑通过(不再报签名不匹配)→
1116
+ // next 正常路由到委托节点;审计事件 / 授权留痕 / 备份快照齐备,重签值与会话当前 TASK.md 同签。
1117
+ {
1118
+ name: '270 replan 重签后 exit execute --apply 通过:修订任务集(含并行就绪任务)→ 签名 BLOCKED → 重签 → 出口放行',
1119
+ run: (dir) => {
1120
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', REPLAN_TASK_INITIAL);
1121
+ writeFile(dir, '.specs/' + CHANGE_ID + '/S01-SUMMARY.md', strictSummary('S01'));
1122
+ // 夹具忠实性修复(协调者授权 A · 夹具缺陷而非放宽带锚):resolveNextNode 的 execute 前
1123
+ // 产物门控按文件存在性判定(不读 completedNodes)——路由到委托节点要求 open / design 的
1124
+ // 前置产物在场。此处补齐 CHANGE.md / REQUIREMENT.md / DESIGN.md(writeIntakeArtifacts
1125
+ // 三件全写,其定义内已含 DESIGN.md),使夹具与真实链路的产物现场一致;不改任何断言 / 锚 /
1126
+ // 判据 / 计数。
1127
+ writeIntakeArtifacts(dir);
1128
+ writeState(dir, replanExecuteState());
1129
+ assertExit(runGuard(['entry', 'execute'], dir), 0);
1130
+ // 任务集修订(#119 死锁现场):新增计划外的并行就绪任务
1131
+ writeFile(dir, '.specs/' + CHANGE_ID + '/TASK.md', REPLAN_TASK_REVISED);
1132
+ const blockedBytes = readStateBytes(dir);
1133
+ const blocked = runGuard(['exit', 'execute', '--apply'], dir);
1134
+ assertExit(blocked, 1);
1135
+ assertOut(blocked, 'BLOCKED');
1136
+ assertOut(blocked, '签名不匹配');
1137
+ assertStateBytesUnchanged(dir, blockedBytes, '修订任务集后的签名门禁 BLOCK');
1138
+ // 受控重校重签
1139
+ const reason = '计划有缺陷:新增并行任务 P02';
1140
+ const beforeReplan = readScenarioState(dir);
1141
+ const res = runStateWithProtocol(dir, ['replan', reason, '--authorized-by', 'user-approval']);
1142
+ assertExit(res, 0);
1143
+ assertOut(res, 'REPLAN');
1144
+ assertOut(res, 'execute');
1145
+ assertOut(res, '1/3');
1146
+ assertOut(res, 'user-approval');
1147
+ assertOut(res, reason);
1148
+ const st = readScenarioState(dir);
1149
+ // 留痕(双写):history 事件 + evidence.<node>.replanAuthorization
1150
+ const events = replanEventsOf(st);
1151
+ if (events.length !== 1) {
1152
+ throw new Error('重签应恰写 1 条 replan-applied 事件,实际 ' + JSON.stringify(events));
1153
+ }
1154
+ const event = events[0];
1155
+ if (event.change !== CHANGE_ID || event.node !== 'execute' || event.round !== 1
1156
+ || event.authorizedBy !== 'user-approval' || event.reason !== reason
1157
+ || typeof event.at !== 'string' || Number.isNaN(Date.parse(event.at))) {
1158
+ throw new Error('replan-applied 事件字段不完整(change / node / round / reason / authorizedBy / at):'
1159
+ + JSON.stringify(event));
1160
+ }
1161
+ const record = st.evidence?.execute?.replanAuthorization;
1162
+ if (!record || record.source !== 'user-approval' || record.reason !== reason || record.round !== 1
1163
+ || typeof record.at !== 'string' || record.at.trim() === '') {
1164
+ throw new Error('evidence.execute.replanAuthorization 授权留痕不完整:' + JSON.stringify(record));
1165
+ }
1166
+ // 重签值 = 当前 TASK.md 签名(事件同步记录同一签名)
1167
+ const signed = assertReplanSignatureRecorded(st, REPLAN_TASK_REVISED, '重签');
1168
+ if (!requireRouteNodeExport('sameTaskSetSignature')(event.taskSetSignature, signed)) {
1169
+ throw new Error('replan-applied 事件记录的签名应与 state.taskHash 同签:'
1170
+ + JSON.stringify({ event: event.taskSetSignature, state: st.taskHash }));
1171
+ }
1172
+ // 转移前备份:全量快照 + sha256 指纹在任何留痕面可核验(ADR-013 决策 7)
1173
+ const backups = replanBackupFiles(dir);
1174
+ if (backups.length !== 1) {
1175
+ throw new Error('重签应恰产生一份备份,实际 ' + JSON.stringify(backups));
1176
+ }
1177
+ if (!/-pre-replan\.json$/.test(backups[0])) {
1178
+ throw new Error('备份命名应为 <UTC ISO>-pre-replan.json,实际 ' + backups[0]);
1179
+ }
1180
+ const backupBytes = fs.readFileSync(path.join(dir, '.specs', CHANGE_ID, 'replan-backups', backups[0]));
1181
+ const backupState = JSON.parse(backupBytes.toString('utf8'));
1182
+ if (!isDeepStrictEqual(backupState, beforeReplan)) {
1183
+ throw new Error('备份应为重签前的 state 全量快照');
1184
+ }
1185
+ const fingerprint = createHash('sha256').update(backupBytes).digest('hex');
1186
+ const haystack = (JSON.stringify(st) + '\n' + outputText(res)).toLowerCase();
1187
+ if (!haystack.includes(fingerprint)) {
1188
+ throw new Error('备份 sha256 指纹未在任何留痕面出现(备份不可核验): ' + fingerprint);
1189
+ }
1190
+ // 同一出口再跑:签名已重签 → 放行;并行就绪任务使 next 路由到委托节点
1191
+ const exitRes = runGuard(['exit', 'execute', '--apply'], dir);
1192
+ assertExit(exitRes, 0);
1193
+ assertOut(exitRes, 'ALL CHECKS PASSED');
1194
+ if (!/^NODE: subagent-execute$/m.test(outputText(exitRes))) {
1195
+ throw new Error('重签后出口应路由到委托节点(并行就绪任务),实际输出:\n' + outputText(exitRes));
1196
+ }
1197
+ const next = runStateWithProtocol(dir, ['next']);
1198
+ assertExit(next, 0);
1199
+ if (!/^NODE: subagent-execute$/m.test(outputText(next))) {
1200
+ throw new Error('next 应正常路由到 subagent-execute,实际输出:\n' + outputText(next));
1201
+ }
1202
+ },
1203
+ },
1204
+
1205
+ // 271: advance 留痕 + 状态可见(AC-4)——advance 仍推进(语义不变),但必须写
1206
+ // history 事件 advance-forced(node + skipped: ['exit:<node>'] + reason: 'advance')并打印
1207
+ // ADVANCE-AUDIT;status 输出派生字段 forcedNodes 以 history 中本 change 的 advance-forced
1208
+ // 事件为准——record 后 advance / replanAuthorization 留痕后
1209
+ // advance 两类真实反例都不得漏报;旧 state(无 history 字段)回退「completedNodes 含而
1210
+ // evidence 不含」判据(当时 advance 无痕,无事件可依)。
1211
+ // 正反断言:被强制推进的节点必现;有出口证据但未被强制的不现。
1212
+ {
1213
+ name: '271 advance 留痕:advance-forced 事件 + status.forcedNodes 派生视图(含反向断言)',
1214
+ run: (dir) => {
1215
+ assertExit(runStateWithProtocol(dir, ['init', CHANGE_ID]), 0);
1216
+ writeFile(dir, '.specs/' + CHANGE_ID + '/CHANGE.md', '# CHANGE\n\n## Why\n\n推进留痕夹具。\n');
1217
+ writeFile(dir, '.specs/' + CHANGE_ID + '/REQUIREMENT.md',
1218
+ '# REQUIREMENT\n\n## 用户故事\n\nx\n\n## 验收准则(AC)\n\n- 通过\n');
1219
+ const res = runStateWithProtocol(dir, ['advance']);
1220
+ assertExit(res, 0);
1221
+ assertOut(res, 'Advanced to: design');
1222
+ assertOut(res, 'ADVANCE-AUDIT');
1223
+ assertOut(res, 'open');
1224
+ const st = readScenarioState(dir);
1225
+ const events = (st.history || []).filter((e) => e && e.event === 'advance-forced');
1226
+ if (events.length !== 1) {
1227
+ throw new Error('advance 应恰写 1 条 advance-forced 事件,实际 ' + JSON.stringify(events));
1228
+ }
1229
+ const event = events[0];
1230
+ if (event.change !== CHANGE_ID || event.node !== 'open') {
1231
+ throw new Error('advance-forced 事件应记录 change / 被推进节点,实际 ' + JSON.stringify(event));
1232
+ }
1233
+ if (!isDeepStrictEqual(event.skipped, ['exit:open'])) {
1234
+ throw new Error("advance-forced 事件应记录被跳过的出口门禁 skipped: ['exit:open'],实际 "
1235
+ + JSON.stringify(event.skipped));
1236
+ }
1237
+ if (event.reason !== 'advance') {
1238
+ throw new Error('advance-forced 事件应记录 reason: \'advance\',实际 ' + JSON.stringify(event.reason));
1239
+ }
1240
+ if (typeof event.at !== 'string' || Number.isNaN(Date.parse(event.at))) {
1241
+ throw new Error('advance-forced 事件应带可解析时间戳,实际 ' + JSON.stringify(event.at));
1242
+ }
1243
+ const status = runStateWithProtocol(dir, ['status']);
1244
+ assertExit(status, 0);
1245
+ const parsed = parseStatusJson(status);
1246
+ if (!Array.isArray(parsed.forcedNodes) || !parsed.forcedNodes.includes('open')) {
1247
+ throw new Error('status.forcedNodes 应包含被强制推进且无出口证据的 open,实际 '
1248
+ + JSON.stringify(parsed.forcedNodes));
1249
+ }
1250
+ if (parsed.forcedNodes.includes('design')) {
1251
+ throw new Error('status.forcedNodes 只能包含已完成节点,实际 ' + JSON.stringify(parsed.forcedNodes));
1252
+ }
1253
+ // 反向:有出口证据且未被 advance 强制的 completed 节点不得进入 forcedNodes;
1254
+ // 无出口证据但被 advance 强制的节点仍收录(事件判据)。事件派生下「强制」由 history 决定:
1255
+ // 夹具把 advance-forced 事件挂到 design(open 只留 exit 证据),反向断言语义保持不变。
1256
+ const st2 = readScenarioState(dir);
1257
+ st2.completedNodes = ['open', 'design'];
1258
+ st2.currentNode = 'plan';
1259
+ st2.evidence = { ...(st2.evidence || {}), open: { summary: 'open exited' } };
1260
+ st2.history = [advanceForcedEvent('design')];
1261
+ writeState(dir, st2);
1262
+ const status2 = runStateWithProtocol(dir, ['status']);
1263
+ assertExit(status2, 0);
1264
+ const parsed2 = parseStatusJson(status2);
1265
+ if (!Array.isArray(parsed2.forcedNodes) || !parsed2.forcedNodes.includes('design')) {
1266
+ throw new Error('无出口证据的 completed 节点应进入 forcedNodes,实际 ' + JSON.stringify(parsed2.forcedNodes));
1267
+ }
1268
+ if (parsed2.forcedNodes.includes('open')) {
1269
+ throw new Error('有出口证据的 completed 节点不得进入 forcedNodes,实际 ' + JSON.stringify(parsed2.forcedNodes));
1270
+ }
1271
+ // (i) 有 record 出口证据且被 advance 强制 → 必须出现(旧「缺 evidence」推断会漏报)
1272
+ const stRecord = replanExecuteState({
1273
+ completedNodes: ['open', 'design'],
1274
+ currentNode: 'plan',
1275
+ evidence: { open: { summary: 'record 出口证据(advance 事件之外的真实证据)' } },
1276
+ history: [advanceForcedEvent('open')],
1277
+ });
1278
+ writeState(dir, stRecord);
1279
+ const statusRecord = runStateWithProtocol(dir, ['status']);
1280
+ assertExit(statusRecord, 0);
1281
+ const parsedRecord = parseStatusJson(statusRecord);
1282
+ const failures271 = [];
1283
+ if (!Array.isArray(parsedRecord.forcedNodes) || !parsedRecord.forcedNodes.includes('open')) {
1284
+ failures271.push('(i) 有 record 证据且被 advance 强制的 open 应进入 forcedNodes,实际 '
1285
+ + JSON.stringify(parsedRecord.forcedNodes));
1286
+ }
1287
+ // (ii) 只有 replanAuthorization 授权留痕且被 advance 强制 → 必须出现(旧对象判据会漏报)
1288
+ const stAuth = replanExecuteState({
1289
+ completedNodes: ['open', 'design'],
1290
+ currentNode: 'plan',
1291
+ evidence: {
1292
+ open: { summary: 'open exited' },
1293
+ design: {
1294
+ replanAuthorization: {
1295
+ round: 1,
1296
+ at: '2026-09-28T00:00:00.000Z',
1297
+ source: 'user',
1298
+ reason: '计划重校',
1299
+ backup: '.specs/' + CHANGE_ID + '/replan-backups/x.json',
1300
+ fingerprint: '0'.repeat(64),
1301
+ },
1302
+ },
1303
+ },
1304
+ history: [advanceForcedEvent('design')],
1305
+ });
1306
+ writeState(dir, stAuth);
1307
+ const statusAuth = runStateWithProtocol(dir, ['status']);
1308
+ assertExit(statusAuth, 0);
1309
+ const parsedAuth = parseStatusJson(statusAuth);
1310
+ if (!Array.isArray(parsedAuth.forcedNodes) || !parsedAuth.forcedNodes.includes('design')) {
1311
+ failures271.push('(ii) 仅有 replanAuthorization 留痕且被 advance 强制的 design 应进入 forcedNodes,实际 '
1312
+ + JSON.stringify(parsedAuth.forcedNodes));
1313
+ }
1314
+ // (iv) 旧 state(无 history 字段)→ 回退「缺 evidence」判据仍生效
1315
+ const stLegacy = replanExecuteState({
1316
+ completedNodes: ['open', 'design'],
1317
+ currentNode: 'plan',
1318
+ evidence: { open: { summary: 'open exited' } },
1319
+ });
1320
+ delete stLegacy.history;
1321
+ writeState(dir, stLegacy);
1322
+ const statusLegacy = runStateWithProtocol(dir, ['status']);
1323
+ assertExit(statusLegacy, 0);
1324
+ const parsedLegacy = parseStatusJson(statusLegacy);
1325
+ if (!Array.isArray(parsedLegacy.forcedNodes) || !parsedLegacy.forcedNodes.includes('design')) {
1326
+ failures271.push('(iv) 旧 state(无 history)应回退缺 evidence 判据:design 应在 forcedNodes,实际 '
1327
+ + JSON.stringify(parsedLegacy.forcedNodes));
1328
+ }
1329
+ if (parsedLegacy.forcedNodes.includes('open')) {
1330
+ failures271.push('(iv) 旧 state(无 history)有出口证据的 open 不得进入 forcedNodes,实际 '
1331
+ + JSON.stringify(parsedLegacy.forcedNodes));
1332
+ }
1333
+ if (failures271.length > 0) {
1334
+ throw new Error('advance-forced 事件派生判据失败: ' + failures271.join(' | '));
1335
+ }
1336
+ },
1337
+ },
1338
+ ];