flow-comet 1.5.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.flow-comet/rules/flow-comet-orchestration.md +13 -0
  2. package/.flow-comet/skills/flow-comet/GUIDANCE.md +196 -0
  3. package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -0
  4. package/.flow-comet/skills/flow-comet/SKILL.md +196 -0
  5. package/.flow-comet/skills/flow-comet/reference/KNOWN-ISSUES-template.md +19 -0
  6. package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +115 -0
  7. package/.flow-comet/skills/flow-comet/reference/authoring-lanes.json +33 -0
  8. package/.flow-comet/skills/flow-comet/reference/composition-report.md +65 -0
  9. package/.flow-comet/skills/flow-comet/reference/decision-points.md +64 -0
  10. package/.flow-comet/skills/flow-comet/reference/dirty-worktree.md +30 -0
  11. package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +169 -0
  12. package/.flow-comet/skills/flow-comet/reference/init-detection.md +58 -0
  13. package/.flow-comet/skills/flow-comet/reference/recovery.md +20 -0
  14. package/.flow-comet/skills/flow-comet/reference/resolved-skills.json +661 -0
  15. package/.flow-comet/skills/flow-comet/reference/skill-review.md +13 -0
  16. package/.flow-comet/skills/flow-comet/reference/subagents/script-author.md +7 -0
  17. package/.flow-comet/skills/flow-comet/reference/workflow-protocol.json +681 -0
  18. package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +52 -0
  19. package/.flow-comet/skills/flow-comet/scripts/comet-check.mjs +61 -0
  20. package/.flow-comet/skills/flow-comet/scripts/comet-hook-guard.mjs +909 -0
  21. package/.flow-comet/skills/flow-comet/scripts/comet-plan.mjs +2 -0
  22. package/.flow-comet/skills/flow-comet/scripts/context-init.mjs +312 -0
  23. package/.flow-comet/skills/flow-comet/scripts/contract-check.mjs +136 -0
  24. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +7331 -0
  25. package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +376 -0
  26. package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +230 -0
  27. package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +99 -0
  28. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +4017 -0
  29. package/.flow-comet/skills/flow-comet/scripts/task-parsing.mjs +28 -0
  30. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +2396 -0
  31. package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +378 -0
  32. package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +1263 -0
  33. package/.flow-comet/skills/flow-comet-archive/SKILL.md +195 -0
  34. package/.flow-comet/skills/flow-comet-change/SKILL.md +29 -0
  35. package/.flow-comet/skills/flow-comet-compose/SKILL.md +249 -0
  36. package/.flow-comet/skills/flow-comet-design/GUIDANCE.md +23 -0
  37. package/.flow-comet/skills/flow-comet-design/SKILL.md +161 -0
  38. package/.flow-comet/skills/flow-comet-dev/SKILL.md +51 -0
  39. package/.flow-comet/skills/flow-comet-evolve/SKILL.md +26 -0
  40. package/.flow-comet/skills/flow-comet-execute/SKILL.md +182 -0
  41. package/.flow-comet/skills/flow-comet-health/SKILL.md +31 -0
  42. package/.flow-comet/skills/flow-comet-integration/SKILL.md +45 -0
  43. package/.flow-comet/skills/flow-comet-open/GUIDANCE.md +36 -0
  44. package/.flow-comet/skills/flow-comet-open/SKILL.md +161 -0
  45. package/.flow-comet/skills/flow-comet-plan/GUIDANCE.md +33 -0
  46. package/.flow-comet/skills/flow-comet-plan/SKILL.md +169 -0
  47. package/.flow-comet/skills/flow-comet-requirement/SKILL.md +27 -0
  48. package/.flow-comet/skills/flow-comet-review/SKILL.md +204 -0
  49. package/.flow-comet/skills/flow-comet-subagent-execute/GUIDANCE.md +29 -0
  50. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +214 -0
  51. package/.flow-comet/skills/flow-comet-task/SKILL.md +33 -0
  52. package/.flow-comet/skills/flow-comet-test/SKILL.md +41 -0
  53. package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +26 -0
  54. package/.flow-comet/skills/flow-comet-verify/SKILL.md +164 -0
  55. package/LICENSE +21 -0
  56. package/README.md +255 -0
  57. package/package.json +27 -0
  58. package/scripts/dsh-bridge.mjs +461 -0
  59. package/scripts/prepare-env.mjs +1526 -0
@@ -0,0 +1,909 @@
1
+ #!/usr/bin/env node
2
+ import { constants as fsConstants, promises as fs, existsSync as fsExistsSync } from 'fs';
3
+ import path from 'path';
4
+ import { fileURLToPath } from 'url';
5
+ import {
6
+ parseProtocolWriteWhitelist,
7
+ readProtocolFile,
8
+ resolveProtocol,
9
+ validateProtocolSchema,
10
+ } from './protocol-utils.mjs';
11
+ // 运行时路径常量(单一来源:state-schema.mjs)——本脚本每次工具调用都会执行,故此处只 import
12
+ // 同包内的本地 ESM 模块(与已存在的 protocol-utils.mjs import 同型,实测无可感知开销);
13
+ // 禁止在本文件重新硬编码命名空间/文件名。
14
+ import {
15
+ RUNTIME_DIR,
16
+ RUNTIME_STATE_FILE_NAME,
17
+ RUNTIME_STATE_PATH,
18
+ } from './state-schema.mjs';
19
+
20
+ const event = process.argv[2] ?? 'before_tool';
21
+ // 平台识别(1.4.0 多平台):--platform codex argv 参数(prepare-env 注入 hook 命令时带平台标记)。
22
+ // 缺省 claude-code = 既有行为(stdout 自由文本 + exit 2 block)。
23
+ // Codex 分支:stdout 严格 JSON schema(拦截输出 {"decision":"block"},放行输出 {}),exit 0。
24
+ function platformFromArgs(argv) {
25
+ for (let index = 0; index < argv.length; index++) {
26
+ if (argv[index] === '--platform') {
27
+ if (typeof argv[index + 1] === 'string' && argv[index + 1] !== '') return argv[index + 1];
28
+ }
29
+ if (typeof argv[index] === 'string' && argv[index].startsWith('--platform=')) {
30
+ const value = argv[index].slice('--platform='.length);
31
+ if (value !== '') return value;
32
+ }
33
+ }
34
+ return null;
35
+ }
36
+ const platform = platformFromArgs(process.argv.slice(2)) ?? 'claude-code';
37
+ const isCodex = platform === 'codex';
38
+
39
+ // 放行输出:Codex 分支只输出 {}(Codex 对 hook stdout 严格 schema 校验,额外字段整体无效);
40
+ // Claude Code 分支输出既有文本(workflow-hook-guard-ok + EVENT + 可选标注)。
41
+ function hookOk(extra) {
42
+ if (isCodex) {
43
+ console.log('{}');
44
+ return;
45
+ }
46
+ console.log('workflow-hook-guard-ok');
47
+ console.log('EVENT: ' + event + (extra ? ' ' + extra : ''));
48
+ }
49
+
50
+ // 拦截输出:Codex 分支输出 {"decision":"block",reason} + exit 0(实测确认的 Codex deny 通道——
51
+ // 2026-08-13 Codex 0.146:exit 2 / permissionDecision:"deny" 均不被 enforce,decision:"block"+exit 0 生效);
52
+ // Claude Code 分支既有文本 + exit 2。
53
+ function hookBlock(mainLine, detailLine) {
54
+ if (isCodex) {
55
+ console.log(JSON.stringify({ decision: 'block', reason: mainLine + (detailLine ? ' ' + detailLine : '') }));
56
+ process.exit(0);
57
+ }
58
+ console.error(mainLine);
59
+ if (detailLine) console.error(detailLine);
60
+ process.exit(2);
61
+ }
62
+
63
+ // Codex 平台写路径适配:PreToolUse 只拦截 shell(Bash)工具,Codex 在 Windows 经 PowerShell 写文件——
64
+ // tool_input 为 command 字符串(无 file_path)。按常见写入模式解析命令中的目标路径:
65
+ // ① PowerShell cmdlet 的 -Path/-LiteralPath 参数
66
+ // ② .NET File API 的第一个参数(路径)
67
+ // ③ shell 重定向 > / >>
68
+ // 命中任一模式即提取路径(供白名单判定);未命中 = 无写入语义,放行。
69
+ // 边界:检测为命令级——换写法(如其他 File API)可绕过,属平台限制;覆盖主流模式后越权写入
70
+ // 对执行者的阻力与可见性已足够(每次绕过都留下试错痕迹)。
71
+ // 目的地型命令的位置形态扫描:下面这些开关各吃一个取值,其取值 token 不是位置参数
72
+ // (不排除就会把 `-Filter *.md` 的 `*.md` 取成写入目标——修完取错方向又添新的误拦)
73
+ const DEST_VALUE_FLAGS = new Set([
74
+ 'destination', 'dest', 'path', 'literalpath', 'filepath', 'filter', 'include', 'exclude',
75
+ ]);
76
+
77
+ // 引号感知的命令结构扫描(目的地型命令的「命令位置」与「参数段边界」共用):
78
+ // masked[i] = 该位置在引号内(含引号字符本身,以及反斜杠转义的下一字符——转义字符是字面量,
79
+ // 不参与结构判定;被转义的换行是续行,不算命令分隔);
80
+ // starts = 候选命令位置(行首,以及未加引号的 `; & | ( ) { }` 或换行之后的首个非空白位置)。
81
+ // 逐字符扫描而非字符类正则:字符类不区分引号内外(引号内的括号/分号不是命令边界),
82
+ // 也不覆盖「引号内文本含命令名」的形态——详见下方目的地型模式的注释。
83
+ function scanCommandStructure(command) {
84
+ const masked = new Array(command.length).fill(false);
85
+ let inSingle = false;
86
+ let inDouble = false;
87
+ for (let i = 0; i < command.length; i++) {
88
+ const ch = command[i];
89
+ if (inSingle) {
90
+ masked[i] = true;
91
+ if (ch === "'") inSingle = false;
92
+ continue;
93
+ }
94
+ if (ch === '\\' && i + 1 < command.length) {
95
+ masked[i] = true;
96
+ masked[i + 1] = true;
97
+ i += 1;
98
+ continue;
99
+ }
100
+ if (inDouble) {
101
+ masked[i] = true;
102
+ if (ch === '"') inDouble = false;
103
+ continue;
104
+ }
105
+ if (ch === "'" || ch === '"') {
106
+ masked[i] = true;
107
+ if (ch === "'") inSingle = true;
108
+ else inDouble = true;
109
+ }
110
+ }
111
+ const starts = new Set();
112
+ let pending = true;
113
+ for (let i = 0; i < command.length; i++) {
114
+ if (masked[i]) continue;
115
+ const ch = command[i];
116
+ if (ch === ' ' || ch === '\t') continue;
117
+ if (ch === ';' || ch === '&' || ch === '|' || ch === '(' || ch === ')' || ch === '{' || ch === '}' || ch === '\n' || ch === '\r') {
118
+ pending = true;
119
+ continue;
120
+ }
121
+ if (pending) {
122
+ starts.add(i);
123
+ pending = false;
124
+ }
125
+ }
126
+ return { masked, starts };
127
+ }
128
+
129
+ // 参数段结束位置(引号感知):自 from 起第一个未在引号内的段边界(`;` / `|` / `&` 或换行/回车)。
130
+ // 换行与回车都算段边界——`\r`/`\n` 任一在场都把两行命令切开(CRLF 与 LF 同判)。
131
+ // 反斜杠续行由 masked 排除(被转义的换行不截断段),跨行的单条命令不会被误截成两段。
132
+ function unquotedSegmentEnd(command, masked, from) {
133
+ for (let i = from; i < command.length; i++) {
134
+ if (masked[i]) continue;
135
+ const ch = command[i];
136
+ if (ch === ';' || ch === '|' || ch === '&' || ch === '\n' || ch === '\r') return i;
137
+ }
138
+ return command.length;
139
+ }
140
+
141
+ function codexWriteTargetsFromCommand(command) {
142
+ if (typeof command !== 'string' || command.trim() === '') return [];
143
+ const targets = [];
144
+ // 目标归一化(剥引号 / 过滤空值与空设备 / 去重)——下方各模式共用,防多处口径漂移
145
+ const addTarget = (raw) => {
146
+ let t = raw && raw.trim();
147
+ if (t) t = t.replace(/^["']|["']$/g, ''); // 剥引号
148
+ if (t && t !== 'NUL' && t !== '/dev/null' && !targets.includes(t)) targets.push(t); // 去重
149
+ };
150
+ const patterns = [
151
+ // PowerShell **路径型**写类 cmdlet 的 -Path/-LiteralPath/-FilePath(引号内空格整体捕获并剥引号;
152
+ // 只匹配写类 cmdlet——读类(Get-Content 等)的 -Path 不提取;同一命令内 [^;|&]*? 防跨命令)。
153
+ // 路径型的 -Path 就是写入目标;**Copy-Item/Move-Item 不在此列**——它们的 -Path 是**源**路径
154
+ // (见下方目的地型模式):把源取成目标正是本函数曾经的取向错误——写入目标从不被检查,
155
+ // 源路径反而被误拦(只读命令也拦)。
156
+ /(?:Set-Content|Add-Content|New-Item|Out-File|Remove-Item|Set-Item|Export-Csv)[^;|&]*?-(?:Path|LiteralPath|FilePath)\s+("[^"]*"|'[^']*'|[^\s;|&]+)/gi,
157
+ // shell 重定向(含描述符变体:> / >> / 2> / 1>>)
158
+ /(?:^|[;\s|&])(?:[0-9]*>>?)\s*("[^"]*"|'[^']*'|[^\s;|&]+)/gi,
159
+ ];
160
+ for (const re of patterns) {
161
+ let m;
162
+ while ((m = re.exec(command)) !== null) addTarget(m[1]);
163
+ }
164
+ // **目的地型**命令(与上方 .NET File API 的 Copy/Move 分支同向:写目标是第二参数):
165
+ // Copy-Item / Move-Item / Remove-Item 与位置型形态 cp / mv
166
+ // 目标按命令语义分层取值:① `-Destination`/`-Dest`;② GNU 前置目的地
167
+ // `-t <dir>` / `--target-directory[= ]<dir>`(目的地是开关取值,不是位置参数);
168
+ // ③ 兜底取**最后一个位置参数**(`Copy-Item <src> <dst>` / `cp <src> <dst>`)。
169
+ // 命令位置锚定(行首/未加引号的命令分隔符或换行之后才认命令名):命令名与短名同样出现在普通
170
+ // 参数、路径片段与被检索文本里——不锚定会把 `grep -n cp <file>` 的 <file> 取成写入目标。
171
+ // 锚定与分段都走引号感知扫描(不用字符类正则),因为字符类不区分引号内外、也不认得跨行:
172
+ // ① `[;&|(){}]` 会把 `printf '(cp CLAUDE.md)'` 引号内的括号当成命令边界,括号里的文本被读成
173
+ // 写命令 → 合法命令被拦(误拦);② 段捕获 `[^;|&]*` 会跨行吞并——`cp <src> <dst>` 后跟另一
174
+ // 行命令时,「最后一个位置参数」取到下一行的参数,真正被写的 <dst> 反而从不被检查(逃逸)。
175
+ // 非命令位置的内嵌形态(如 powershell -Command "…")不提取,属命令级检测的既有边界。
176
+ const { masked, starts } = scanCommandStructure(command);
177
+ const destinationRe = /(?:Copy-Item|Move-Item|Remove-Item|cp|mv)/gi;
178
+ let destMatch;
179
+ while ((destMatch = destinationRe.exec(command)) !== null) {
180
+ const nameEnd = destMatch.index + destMatch[0].length;
181
+ if (!starts.has(destMatch.index)) continue; // 非命令位置(如 `grep -n cp <file>` 的参数)
182
+ const afterName = command[nameEnd];
183
+ if (afterName !== undefined && !/\s/.test(afterName)) continue; // 命令名后须接空白(`cpio` 不是 `cp`)
184
+ const segment = command.slice(nameEnd, unquotedSegmentEnd(command, masked, nameEnd));
185
+ const named = /-(?:Destination|Dest)(?::|\s)+("[^"]*"|'[^']*'|[^\s;|&]+)/i.exec(segment);
186
+ if (named) {
187
+ addTarget(named[1]);
188
+ continue;
189
+ }
190
+ // GNU 前置目的地:只把 `-t` 当普通开关跳过取值并不够——那样仍会取到最后一个位置参数
191
+ // (即源,通常在白名单内)而真正被写的目录不被检查(fail-open)。
192
+ const targetDir = /(?:^|[\s;&|])(?:--target-directory|-t)(?:\s*=\s*|\s+)("[^"]*"|'[^']*'|[^\s;|&]+)/i.exec(segment);
193
+ if (targetDir) {
194
+ addTarget(targetDir[1]);
195
+ continue;
196
+ }
197
+ // 位置形态:取最后一个位置参数——开关与开关取值不参与(Remove-Item 无 -Destination 语义,
198
+ // 其 -Path 由上方路径型模式按既有语义提取,此处只兜底纯位置形态)。
199
+ const tokens = segment.match(/"[^"]*"|'[^']*'|[^\s]+/g) || [];
200
+ let positional = '';
201
+ let skipValue = false;
202
+ for (const token of tokens) {
203
+ if (skipValue) {
204
+ skipValue = false; // 上一个开关的取值不是位置参数
205
+ continue;
206
+ }
207
+ if (token.startsWith('-')) {
208
+ const flag = token.replace(/^[-/]+/, '').replace(/:.*$/, '').toLowerCase();
209
+ skipValue = DEST_VALUE_FLAGS.has(flag);
210
+ continue;
211
+ }
212
+ positional = token;
213
+ }
214
+ addTarget(positional);
215
+ }
216
+ // .NET File API:写 API 的目标参数按语义区分——WriteAll*/AppendAll*/Delete 目标 = 第一参数;
217
+ // Copy(source, destination) / Move(source, destination) 目标 = 第二参数(第一参数是源路径,守卫应检查写入目标)
218
+ const apiRe = /\[System\.IO\.File\]::(WriteAllText|WriteAllBytes|AppendAllText|WriteAllLines|Copy|Move|Delete)\s*\(\s*("[^"]*"|'[^']*'|[^,\s)]+)(?:\s*,\s*("[^"]*"|'[^']*'|[^,\s)]+))?/gi;
219
+ let m;
220
+ while ((m = apiRe.exec(command)) !== null) {
221
+ const isCopyMove = m[1] === 'Copy' || m[1] === 'Move';
222
+ let t = (isCopyMove ? m[3] : m[2]) || '';
223
+ t = t.trim().replace(/^["']|["']$/g, '');
224
+ if (t && t !== 'NUL' && t !== '/dev/null' && !targets.includes(t)) targets.push(t);
225
+ }
226
+ return targets;
227
+ }
228
+
229
+ // writeWhitelist 路径支持 <change-id> 占位符(与 artifacts paths 同机制——协议复用自动适配
230
+ // 当前 change;无 activeChange 时字面匹配保底)
231
+ function replaceChangeId(prefix, activeChange) {
232
+ return (typeof prefix === 'string' && prefix.includes('<change-id>') && activeChange)
233
+ ? prefix.replaceAll('<change-id>', activeChange)
234
+ : prefix;
235
+ }
236
+
237
+ // 白名单判定(共享):目标相对路径前缀匹配(含 <change-id> 占位符替换)——file_path 路径与
238
+ // Codex Bash 命令写入路径两条判定共用,避免两处逻辑漂移
239
+ function targetAllowed(targetRel, whitelist, activeChange) {
240
+ return whitelist.some(prefix => {
241
+ const p = replaceChangeId(prefix, activeChange);
242
+ return p === '' || targetRel.startsWith(p);
243
+ });
244
+ }
245
+
246
+ // worktree 隔离区判定(共享):CC 的隔离委托把子代理工作区放在 <项目根>/.claude/worktrees/<agent-id>/
247
+ // 下。子代理在该区内写源码是设计意图(见上方 phase 白名单注释「源码由 worktree 子代理写」);
248
+ // 但 runRoot 锚定到主仓后(v1.5.0-rc.2 引入的锚定链),区内路径被相对化为
249
+ // .claude/worktrees/<id>/...,不在协调者白名单内 —— 子代理被误判为协调者而遭拦截
250
+ // (回归:rc.2 之前 runRoot 取 cwd=worktree,区内无 state 故按设计放行)。
251
+ // 该区与主仓状态隔离(区内无 state 文件),故按隔离区语义放行;内容边界仍由 TASK write_files
252
+ // 与提交子集校验约束。判据用归一化后的相对路径(防 ../../ 穿越绕过)。
253
+ // 单一实现:file_path 判定与 Bash 命令写入判定共用同一函数——两条判定路径必须同语义,
254
+ // 否则同一路径会因所选工具而异(Write/Edit 放行、Bash 重定向被拦)。
255
+ // 隔离区根(项目根相对,POSIX 形态)——词法判定与物理判定共用同一常量:隔离区位置是安全边界
256
+ // 的一部分,变更只应改这一处(两处各写一份字面量必然漂移)。
257
+ const AGENT_WORKTREE_ROOT_REL = '.claude/worktrees';
258
+ function isInsideAgentWorktree(targetRel) {
259
+ if (typeof targetRel !== 'string' || targetRel === '') return false;
260
+ const normalized = path.posix.normalize(targetRel.replaceAll('\\', '/'));
261
+ return normalized.startsWith(AGENT_WORKTREE_ROOT_REL + '/');
262
+ }
263
+
264
+ // worktree 隔离区的**物理**包含性判定(与上方词法判定的配对条件,放行的前置):
265
+ // 词法前缀匹配只证明"路径字符串以隔离区前缀开头",证明不了"写入真的落在隔离区内"——
266
+ // `.claude/worktrees/<id>/link/src/x.mjs` 中的 `link` 若是指向区外的符号链接/junction,
267
+ // 词法判定照样命中(该放行又在各自的白名单判定**之前**返回,没有任何后续校验能兜住)。
268
+ // 判据(fail-closed:不能证明落在区内即不放行):
269
+ // ① 自项目根逐分量 lstat——任一分量为符号链接/junction(Windows 两者在 lstat 下同为
270
+ // symbolic link)即拒:其真实落点不受词法位置约束;
271
+ // ② 每个已存在分量的真实路径须仍在项目根内(防项目根自身被链接分量替换的异常形态);
272
+ // ③ 首个不存在的分量之后按「最近已存在祖先的真实路径 + 余下分量」推导落点——目标文件/
273
+ // 目录尚不存在是常态(新建文件时目标必然不存在),不能因此拒判;
274
+ // 落点须位于 <真实项目根>/.claude/worktrees/ 之下(隔离区语义的物理版本);
275
+ // ④ 解析类故障(EACCES/ELOOP/悬挂链接/其它异常)一律拒。
276
+ // 性能:仅当词法前缀命中时才执行——普通协调者会话零开销;命中时每次至多 O(路径深度) 次
277
+ // lstat/realpath,且判定的路径形态固定(隔离区路径深度有限)。
278
+ async function agentWorktreeWriteStaysIsolated(targetRel) {
279
+ let realRoot;
280
+ try {
281
+ realRoot = await fs.realpath(runRoot);
282
+ } catch {
283
+ return false;
284
+ }
285
+ const segments = targetRel
286
+ .replaceAll('\\', '/')
287
+ .split('/')
288
+ .filter((segment) => segment !== '' && segment !== '.');
289
+ let cursor = runRoot;
290
+ let physicalCursor = realRoot;
291
+ let existingSegments = 0;
292
+ for (const segment of segments) {
293
+ cursor = path.join(cursor, segment);
294
+ let stat;
295
+ try {
296
+ stat = await fs.lstat(cursor);
297
+ } catch (error) {
298
+ if (
299
+ error &&
300
+ typeof error === 'object' &&
301
+ (error.code === 'ENOENT' || error.code === 'ENOTDIR')
302
+ ) {
303
+ break; // 余下分量为待新建——落点由最近已存在祖先的真实路径推导(见 ③)
304
+ }
305
+ return false; // 其它故障 fail-closed
306
+ }
307
+ if (stat.isSymbolicLink()) return false;
308
+ let real;
309
+ try {
310
+ real = await fs.realpath(cursor);
311
+ } catch {
312
+ return false;
313
+ }
314
+ if (!workflowPathInside(realRoot, real)) return false;
315
+ physicalCursor = real;
316
+ existingSegments += 1;
317
+ }
318
+ const destination = path.resolve(physicalCursor, ...segments.slice(existingSegments));
319
+ return workflowPathInside(
320
+ path.join(realRoot, ...AGENT_WORKTREE_ROOT_REL.split('/')),
321
+ destination,
322
+ );
323
+ }
324
+
325
+ // W4: state 文件禁手动工具写(directOverride 授权约束的写入路径物理控制)——
326
+ // 运行时状态文件(.flow-comet/flow-comet-state.json)是机器字段文件,只能由脚本通道(workflow-state 的
327
+ // execution-mode/record/init 等命令)管理;任何工具写(Write/Edit/Bash 命令级)→ BLOCK
328
+ // (fail-closed)。hook 拦工具不拦脚本——脚本通道天然不触发 PreToolUse,不受影响。
329
+ // 与 M1 归档白名单收窄同型:保护机器文件不被越权手改(含 direct 模式下白名单 [''] 曾
330
+ // 放行 state 写入的 fail-open 缺口——执行者自切 direct 越权写的物理入口)。
331
+ // 大小写变体闭合(CodeRabbit 采纳):win32/darwin 文件系统大小写不敏感,`.Flow-Comet/Flow-Comet-
332
+ // State.json` 与机器状态文件指向同一实体——目标路径先 toLowerCase() 再与机器状态相对路径
333
+ // 比较,变体同等 BLOCK(修复前精确等值比较被变体绕过 → fail-open)。其他平台
334
+ // (大小写敏感文件系统)变体是不同文件,保持精确等值比较(不误拦合法路径)。
335
+ // 取值唯一来源 = state-schema.mjs 的 RUNTIME_STATE_PATH(项目根相对的 POSIX 路径)。
336
+ // 本文件不再硬编码该路径——命名空间/文件名变更只改 state-schema.mjs 一处。
337
+ const STATE_FILE_REL = RUNTIME_STATE_PATH;
338
+ const CASE_INSENSITIVE_FS = process.platform === 'win32' || process.platform === 'darwin';
339
+ function blockedStateFileTarget(targetRel) {
340
+ return CASE_INSENSITIVE_FS
341
+ ? targetRel.toLowerCase() === STATE_FILE_REL
342
+ : targetRel === STATE_FILE_REL;
343
+ }
344
+
345
+ function blockStateFileWrite(target) {
346
+ hookBlock(
347
+ `BLOCKED: state 文件 "${target}" 禁手动工具写(机器字段由脚本通道管理——execution-mode/record/init 等命令正常)`,
348
+ '恢复: 用 workflow-state.mjs 的 execution-mode 等命令管理状态;禁止手改 state 机器字段'
349
+ );
350
+ }
351
+
352
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
353
+ const packageRoot = path.resolve(__dirname, '..');
354
+ // 项目根判定兜底链(级3 cwd 漂移实测暴露的 H5 残留缺口收口):
355
+ // ① FLOW_COMET_RUN_ROOT(测试/受限环境显式锚定)→ ② CLAUDE_PROJECT_DIR(Claude Code 在 hook env
356
+ // 注入项目根——会话 cwd 漂移后仍可正确定位)→ ③ 自 cwd 逐级向上锚定最近祖先:含
357
+ // .flow-comet/flow-comet-state.json 或 .claude/skills/flow-comet 即视为项目根 → ④ 兜底 cwd。
358
+ // 意义:漂移会话不再因“协议/状态按错误 cwd 解析失败 → 报错式放行”而漏拦;判定根与项目根一致。
359
+ const runRoot = (() => {
360
+ for (const candidate of [process.env.FLOW_COMET_RUN_ROOT, process.env.CLAUDE_PROJECT_DIR]) {
361
+ if (!candidate) continue;
362
+ // 候选须真实存在且含项目标记(state 或已装技能),陈旧/无效值不采纳 → 落入祖先/cwd 兜底
363
+ const resolved = path.resolve(candidate);
364
+ if (
365
+ fsExistsSync(resolved) &&
366
+ (fsExistsSync(path.join(resolved, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME)) ||
367
+ fsExistsSync(path.join(resolved, '.claude', 'skills', 'flow-comet')))
368
+ ) {
369
+ return resolved;
370
+ }
371
+ }
372
+ let current = path.resolve(process.cwd());
373
+ for (;;) {
374
+ if (
375
+ fsExistsSync(path.join(current, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME)) ||
376
+ fsExistsSync(path.join(current, '.claude', 'skills', 'flow-comet'))
377
+ ) {
378
+ return current;
379
+ }
380
+ const parent = path.dirname(current);
381
+ if (parent === current) break;
382
+ current = parent;
383
+ }
384
+ return path.resolve(process.cwd());
385
+ })();
386
+ // hook 由 settings.json 静态命令调用,不支持 CLI 参数(cliArgs 传 []):
387
+ // 协议路径取 env FLOW_COMET_PROTOCOL 或默认 <packageRoot>/reference/workflow-protocol.json
388
+ const protocolPath = resolveProtocol(packageRoot, runRoot, []);
389
+
390
+
391
+ const WORKFLOW_PROJECT_FILE_MAX_BYTES = 2 * 1024 * 1024;
392
+
393
+ // Phase 写入白名单:currentNode → 允许写入的(相对 runRoot 的)路径前缀
394
+ // '.specs/' 前缀表示只允许 .specs 目录下的文件(subagent-execute 始终协调者,只写工件;源码由 worktree 子代理写)
395
+ // 其他路径前缀精确匹配
396
+ // 注:白名单已声明化(协议 writeWhitelist 优先,缺失/读取失败时回退下方缺省表);
397
+ // execute 的名单由 state.executionMode 动态收窄(subagent=协调者 .specs/;direct=逃生口允许主代理直写源码),
398
+ // 收窄规则对缺省/声明表同样生效,见 resolvePhaseWriteWhitelist()
399
+
400
+ function workflowPathInside(root, target) {
401
+ const relative = path.relative(root, target);
402
+ return (
403
+ relative === '' ||
404
+ (!path.isAbsolute(relative) &&
405
+ relative !== '..' &&
406
+ !relative.startsWith('..' + path.sep))
407
+ );
408
+ }
409
+
410
+ async function inspectWorkflowProtectedPath(
411
+ projectRoot,
412
+ target,
413
+ label,
414
+ expected = 'any',
415
+ ) {
416
+ const lexicalRoot = path.resolve(projectRoot);
417
+ const lexicalTarget = path.resolve(target);
418
+ if (!workflowPathInside(lexicalRoot, lexicalTarget)) {
419
+ throw new Error(label + ' must stay inside the project root');
420
+ }
421
+ const rootStat = await fs.lstat(lexicalRoot);
422
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
423
+ throw new Error(label + ' project root must be a real directory');
424
+ }
425
+ const realRoot = await fs.realpath(lexicalRoot);
426
+ const relative = path.relative(lexicalRoot, lexicalTarget);
427
+ const segments = relative === '' ? [] : relative.split(path.sep);
428
+ let cursor = lexicalRoot;
429
+ for (let index = 0; index < segments.length; index++) {
430
+ cursor = path.join(cursor, segments[index]);
431
+ let stat;
432
+ try {
433
+ stat = await fs.lstat(cursor);
434
+ } catch (error) {
435
+ if (
436
+ error &&
437
+ typeof error === 'object' &&
438
+ (error.code === 'ENOENT' || error.code === 'ENOTDIR')
439
+ ) {
440
+ return { target: lexicalTarget, exists: false };
441
+ }
442
+ throw error;
443
+ }
444
+ const display = path.relative(lexicalRoot, cursor).replaceAll('\\', '/');
445
+ if (stat.isSymbolicLink()) {
446
+ throw new Error(label + ' crosses a symbolic link or junction at ' + display);
447
+ }
448
+ const final = index === segments.length - 1;
449
+ if (!final && !stat.isDirectory()) {
450
+ throw new Error(label + ' ancestor ' + display + ' must be a real directory');
451
+ }
452
+ if (
453
+ final &&
454
+ ((expected === 'file' && !stat.isFile()) ||
455
+ (expected === 'directory' && !stat.isDirectory()) ||
456
+ (expected === 'any' && !stat.isFile() && !stat.isDirectory()))
457
+ ) {
458
+ throw new Error(label + ' must be a real ' + expected);
459
+ }
460
+ const physical = await fs.realpath(cursor);
461
+ if (!workflowPathInside(realRoot, physical)) {
462
+ throw new Error(label + ' resolves outside the project root');
463
+ }
464
+ }
465
+ return { target: lexicalTarget, exists: true };
466
+ }
467
+
468
+ function workflowFileObjectIdentity(stat) {
469
+ return {
470
+ dev: stat.dev,
471
+ ino: stat.ino,
472
+ birthtime: typeof stat.birthtimeNs === 'bigint' ? stat.birthtimeNs : stat.birthtimeMs,
473
+ };
474
+ }
475
+
476
+ function workflowHasIdentity(value) {
477
+ return value !== 0 && value !== 0n && value !== '0';
478
+ }
479
+
480
+ function workflowSameFileObject(left, right) {
481
+ const comparableDevice = workflowHasIdentity(left.dev) && workflowHasIdentity(right.dev);
482
+ const comparableInode = workflowHasIdentity(left.ino) && workflowHasIdentity(right.ino);
483
+ if (comparableDevice && left.dev !== right.dev) return false;
484
+ if (comparableInode && left.ino !== right.ino) return false;
485
+ if (comparableDevice && comparableInode) return true;
486
+ return left.birthtime === right.birthtime;
487
+ }
488
+
489
+ function workflowSameFileStat(left, right) {
490
+ return (
491
+ workflowSameFileObject(
492
+ workflowFileObjectIdentity(left),
493
+ workflowFileObjectIdentity(right),
494
+ ) &&
495
+ left.size === right.size &&
496
+ left.ctimeNs === right.ctimeNs
497
+ );
498
+ }
499
+
500
+ async function readWorkflowProtectedFile(
501
+ projectRoot,
502
+ file,
503
+ label,
504
+ maxBytes,
505
+ hooks = {},
506
+ ) {
507
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {
508
+ throw new Error(label + ' byte limit must be a positive integer');
509
+ }
510
+ const inspection = await inspectWorkflowProtectedPath(
511
+ projectRoot,
512
+ file,
513
+ label,
514
+ 'file',
515
+ );
516
+ if (!inspection.exists) {
517
+ const error = new Error(label + ' does not exist');
518
+ error.code = 'ENOENT';
519
+ throw error;
520
+ }
521
+ const before = await fs.lstat(file, { bigint: true });
522
+ if (!before.isFile() || before.isSymbolicLink()) {
523
+ throw new Error(label + ' must be a real file');
524
+ }
525
+ if (before.size > BigInt(maxBytes)) {
526
+ throw new Error(label + ' exceeds ' + String(maxBytes) + ' bytes');
527
+ }
528
+ const beforeRealPath = await fs.realpath(file);
529
+ await hooks.afterLstat?.();
530
+ const flags =
531
+ process.platform === 'win32'
532
+ ? fsConstants.O_RDONLY
533
+ : fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK;
534
+ let handle;
535
+ try {
536
+ handle = await fs.open(file, flags);
537
+ } catch (error) {
538
+ if (error && typeof error === 'object' && error.code === 'ELOOP') {
539
+ throw new Error(label + ' must be a real file');
540
+ }
541
+ throw error;
542
+ }
543
+ try {
544
+ const [opened, afterOpen, afterOpenRealPath] = await Promise.all([
545
+ handle.stat({ bigint: true }),
546
+ fs.lstat(file, { bigint: true }),
547
+ fs.realpath(file),
548
+ ]);
549
+ if (
550
+ !opened.isFile() ||
551
+ !afterOpen.isFile() ||
552
+ afterOpen.isSymbolicLink() ||
553
+ afterOpenRealPath !== beforeRealPath ||
554
+ !workflowSameFileStat(before, opened) ||
555
+ !workflowSameFileStat(before, afterOpen)
556
+ ) {
557
+ throw new Error(label + ' changed while opening');
558
+ }
559
+ await inspectWorkflowProtectedPath(projectRoot, file, label, 'file');
560
+ await hooks.afterOpen?.();
561
+ const chunks = [];
562
+ let total = 0;
563
+ const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes + 1));
564
+ for (;;) {
565
+ const remaining = maxBytes + 1 - total;
566
+ const { bytesRead } = await handle.read(
567
+ buffer,
568
+ 0,
569
+ Math.min(buffer.length, remaining),
570
+ null,
571
+ );
572
+ if (bytesRead === 0) break;
573
+ total += bytesRead;
574
+ if (total > maxBytes) {
575
+ throw new Error(label + ' exceeds ' + String(maxBytes) + ' bytes');
576
+ }
577
+ chunks.push(Buffer.from(buffer.subarray(0, bytesRead)));
578
+ }
579
+ await hooks.beforeFinalCheck?.();
580
+ const [afterHandle, afterPath, afterRealPath] = await Promise.all([
581
+ handle.stat({ bigint: true }),
582
+ fs.lstat(file, { bigint: true }),
583
+ fs.realpath(file),
584
+ ]);
585
+ if (
586
+ !afterPath.isFile() ||
587
+ afterPath.isSymbolicLink() ||
588
+ afterRealPath !== beforeRealPath ||
589
+ !workflowSameFileStat(before, afterHandle) ||
590
+ !workflowSameFileStat(before, afterPath)
591
+ ) {
592
+ throw new Error(label + ' changed while reading');
593
+ }
594
+ await inspectWorkflowProtectedPath(projectRoot, file, label, 'file');
595
+ return Buffer.concat(chunks, total);
596
+ } finally {
597
+ await handle.close();
598
+ }
599
+ }
600
+
601
+ function workflowRelativeSegments(value, label, allowWildcards = false) {
602
+ if (typeof value !== 'string') throw new Error(label + ' must be a string');
603
+ const trimmed = value.trim().replaceAll('\\', '/');
604
+ if (
605
+ trimmed.length === 0 ||
606
+ path.posix.isAbsolute(trimmed) ||
607
+ path.win32.isAbsolute(trimmed) ||
608
+ trimmed.startsWith('~') ||
609
+ trimmed.startsWith('/') ||
610
+ trimmed.startsWith('\\')
611
+ ) {
612
+ throw new Error(label + ' must be relative to its declared path base');
613
+ }
614
+ const segments = trimmed.split('/');
615
+ if (segments.some((segment) => segment === '..')) {
616
+ const boundary = label === 'workflow-run statePath' ? 'the project root' : 'its declared path base';
617
+ throw new Error(label + ' must stay inside ' + boundary);
618
+ }
619
+ if (segments.some((segment) => segment === '' || segment === '.')) {
620
+ throw new Error(label + ' must not contain empty or dot path segments');
621
+ }
622
+ if (!allowWildcards && (trimmed.includes('*') || trimmed.includes('?'))) {
623
+ throw new Error(label + ' cannot contain wildcards');
624
+ }
625
+ return segments;
626
+ }
627
+
628
+ function resolveWorkflowRelativePath(base, value, label, allowWildcards = false) {
629
+ const segments = workflowRelativeSegments(value, label, allowWildcards);
630
+ const target = path.resolve(base, ...segments);
631
+ const relative = path.relative(path.resolve(base), target);
632
+ if (
633
+ path.isAbsolute(relative) ||
634
+ relative === '..' ||
635
+ relative.startsWith('..' + path.sep)
636
+ ) {
637
+ const boundary = label === 'workflow-run statePath' ? 'the project root' : 'its declared path base';
638
+ throw new Error(label + ' must stay inside ' + boundary);
639
+ }
640
+ return { target, segments };
641
+ }
642
+
643
+
644
+ async function statePath(protocol) {
645
+ // 协议未声明 state.statePath(最小 schema 协议)→ 回退默认运行时状态路径
646
+ // (与 workflow-state.mjs 写 state 的路径同源——同为 state-schema.mjs 常量,防最小协议在
647
+ // hook 下全量崩溃,顺带消除"相位白名单读硬编码路径 vs 主流程读协议路径"的两段不一致)
648
+ const preferred = String(protocol.state?.statePath ?? '') || RUNTIME_STATE_PATH;
649
+ const target = resolveWorkflowRelativePath(
650
+ runRoot,
651
+ preferred,
652
+ 'workflow-run statePath',
653
+ ).target;
654
+ await inspectWorkflowProtectedPath(
655
+ runRoot,
656
+ target,
657
+ 'workflow-run statePath',
658
+ 'file',
659
+ );
660
+ return target;
661
+ }
662
+
663
+ async function readStateJson(file) {
664
+ // 容忍 UTF-8 BOM(外部写入可能带 BOM)
665
+ return JSON.parse(
666
+ (
667
+ await readWorkflowProtectedFile(
668
+ runRoot,
669
+ file,
670
+ 'workflow-run state',
671
+ WORKFLOW_PROJECT_FILE_MAX_BYTES,
672
+ )
673
+ ).toString('utf8').replace(/^/, ''),
674
+ );
675
+ }
676
+
677
+ function route(protocol) {
678
+ return (protocol.nodes ?? []).filter((node) => !node.disabled);
679
+ }
680
+
681
+ function completedSet(state) {
682
+ return new Set(Array.isArray(state.completedNodes) ? state.completedNodes : []);
683
+ }
684
+
685
+ function nextNode(protocol, state) {
686
+ const completed = completedSet(state);
687
+ return route(protocol).find((node) => !completed.has(node.id)) ?? null;
688
+ }
689
+
690
+ // PreToolUse hook 输入从 stdin 传入(JSON:{ tool_name, tool_input: { file_path, ... } })。
691
+ // 解析失败 / 无输入时返回 null,phase 写入控制因此跳过(不阻断)。
692
+ async function readHookInput() {
693
+ try {
694
+ const chunks = [];
695
+ for await (const chunk of process.stdin) chunks.push(chunk);
696
+ const text = Buffer.concat(chunks).toString('utf8').trim();
697
+ return text ? JSON.parse(text.replace(/^/, '')) : null;
698
+ } catch {
699
+ return null;
700
+ }
701
+ }
702
+
703
+ // 计算写入目标相对 runRoot 的路径(正斜杠分隔,供 PHASE_WRITE_WHITELIST 前缀匹配)。
704
+ // 无法解析或目标在项目根之外时返回 null。
705
+ function writeTargetFromHookInput(input) {
706
+ if (!input || typeof input !== 'object') return null;
707
+ const toolInput =
708
+ input.tool_input && typeof input.tool_input === 'object' ? input.tool_input : null;
709
+ const filePath =
710
+ toolInput && typeof toolInput.file_path === 'string' ? toolInput.file_path : null;
711
+ if (!filePath) return null;
712
+ const absolute = path.isAbsolute(filePath)
713
+ ? path.resolve(filePath)
714
+ : path.resolve(runRoot, filePath);
715
+ const relative = path.relative(runRoot, absolute);
716
+ if (path.isAbsolute(relative) || relative === '..' || relative.startsWith('..' + path.sep)) {
717
+ return null;
718
+ }
719
+ return relative === '' ? '.' : relative.replaceAll('\\', '/');
720
+ }
721
+
722
+ // 声明化写入白名单:协议 writeWhitelist(节点 id → 路径前缀数组)优先;
723
+ // 协议读取/解析失败或未声明 writeWhitelist 时静默回退缺省表(fail-closed,不 throw、不阻断 hook 主体流程——
724
+ // 与 state 读取失败放行不同:白名单缺失会出洞,缺省表是最小安全兜底)
725
+ // execute 收窄为通用规则:无论 execute 来自缺省还是协议,subagent 模式一律收窄为 ['.specs/'](协调者只写工件),
726
+ // direct 模式用声明/缺省值(缺省 direct 允许所有 = 主代理直写源码)
727
+ async function resolvePhaseWriteWhitelist(executionMode) {
728
+ try {
729
+ const protocol = await readProtocolFile(runRoot, protocolPath);
730
+ validateProtocolSchema(protocol);
731
+ const declared = parseProtocolWriteWhitelist(protocol);
732
+ if (declared !== null) {
733
+ // 协议声明模式:返回声明表 + declared=true(main 中对未列出节点 fail-closed 拒绝)
734
+ return {
735
+ whitelist: executionMode === 'subagent'
736
+ ? { ...declared, execute: ['.specs/'] }
737
+ : declared,
738
+ declared: true,
739
+ };
740
+ }
741
+ } catch {
742
+ // 协议读取/解析失败 → 静默回退缺省表(不 throw)
743
+ }
744
+ const executeWhitelist = executionMode === 'direct' ? [''] : ['.specs/'];
745
+ return {
746
+ whitelist: {
747
+ 'open': ['.specs/'],
748
+ 'design': ['.specs/', '.specs/adr/'],
749
+ 'plan': ['.specs/'],
750
+ 'execute': executeWhitelist, // subagent: .specs/(协调者);direct: 允许所有(主代理直写)
751
+ 'subagent-execute': ['.specs/'], // 始终协调者(parallel 仍委托,防 execute 吞 parallel 回归)
752
+ 'review': ['.specs/'],
753
+ 'verify': ['.specs/'],
754
+ // archive 白名单:归档阶段仅遗留清单(KNOWN-ISSUES.md)可写入 change 目录(先写后移),
755
+ // 其余 change 工件不可改(收窄为精确文件——放宽到整个目录会让归档阶段可改任意
756
+ // 工件且无校验,防线变宽);<change-id> 占位符由 targetAllowed 替换为当前 change;
757
+ // 目录移动由 .specs/archive/ 覆盖(2026-08-15 修复:此前仅 .specs/archive/ 导致按文档
758
+ // 流程被 BLOCK;2026-08-16 收窄为精确文件)
759
+ 'archive': ['.specs/archive/', '.specs/<change-id>/KNOWN-ISSUES.md', '.specs/CHANGELOG.md', '.specs/LESSONS.md', 'STATE.md'],
760
+ },
761
+ declared: false,
762
+ };
763
+ }
764
+
765
+ async function main() {
766
+ const protocol = await readProtocolFile(runRoot, protocolPath);
767
+ validateProtocolSchema(protocol);
768
+ const nodes = route(protocol);
769
+ if (nodes.length === 0) {
770
+ throw new Error('workflow protocol has no enabled nodes');
771
+ }
772
+ // Phase 写入控制:按运行时状态文件的 currentNode 检查写入目标是否在白名单内
773
+ // state 文件读取失败时不阻断(state 可能不存在),继续执行后续安全检查
774
+ const stateFile = path.join(runRoot, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME);
775
+ let currentNode = null;
776
+ let executionMode = 'subagent';
777
+ let activeChange = null;
778
+ try {
779
+ const stateContent = await fs.readFile(stateFile, 'utf8');
780
+ const state = JSON.parse(stateContent);
781
+ currentNode = state.currentNode;
782
+ executionMode = state.executionMode ?? 'subagent';
783
+ activeChange = state.activeChange ?? null;
784
+ } catch {}
785
+
786
+ // 白名单声明化:协议 writeWhitelist 优先(节点 id → 路径前缀数组),缺失/读取失败时静默回退缺省表(fail-closed)
787
+ // execute 收窄规则对缺省/声明表同样生效(subagent → ['.specs/'] 协调者;direct → 声明/缺省值)
788
+ const { whitelist: PHASE_WRITE_WHITELIST, declared } = await resolvePhaseWriteWhitelist(executionMode);
789
+
790
+ const hookInput = await readHookInput();
791
+ const target = writeTargetFromHookInput(hookInput);
792
+
793
+ // R5: Bash 工具写路径适配(CC 与 Codex 通用)——Bash 工具的 command 字符串(无 file_path),
794
+ // 解析写入目标按当前节点白名单判定(与 file_path 判定同语义);未命中写入模式 = 无写入语义,放行。
795
+ // CC 侧 settings.local.json 的 matcher 含 Bash(协调者禁令物理化——Bash 写源码同样被拦截)
796
+ if (hookInput && typeof hookInput === 'object' && hookInput.tool_name === 'Bash') {
797
+ const command = hookInput.tool_input && typeof hookInput.tool_input === 'object' ? hookInput.tool_input.command : null;
798
+ const writeTargets = codexWriteTargetsFromCommand(command);
799
+ if (writeTargets.length > 0 && currentNode) {
800
+ const whitelist = PHASE_WRITE_WHITELIST[currentNode];
801
+ // 声明模式未列出节点 → fail-closed(同 file_path 判定);缺省表无此节点 → 协调者默认 .specs/
802
+ const effectiveWhitelist = whitelist || (declared ? null : ['.specs/']);
803
+ for (const t of writeTargets) {
804
+ const absolute = path.resolve(runRoot, t);
805
+ const rel = path.relative(runRoot, absolute);
806
+ const targetRel = (path.isAbsolute(rel) || rel === '..' || rel.startsWith('..' + path.sep)) ? null : rel.replaceAll('\\', '/');
807
+ if (targetRel !== null && blockedStateFileTarget(targetRel)) {
808
+ blockStateFileWrite(t);
809
+ }
810
+ // worktree 隔离区放行(与 file_path 判定共用同一判定——同路径同结论);
811
+ // 放行前置 = 物理包含性(词法命中但真实落点在区外 → 拒,不放行)
812
+ if (targetRel !== null && isInsideAgentWorktree(targetRel)) {
813
+ if (await agentWorktreeWriteStaysIsolated(targetRel)) continue;
814
+ hookBlock(
815
+ `BLOCKED: 命令写入 "${t}" 位于 worktree 隔离区但物理落点在区外(符号链接/junction 穿越)`,
816
+ '恢复: 改用隔离区内的真实路径(隔离区放行仅限物理位于 <项目根>/.claude/worktrees/ 之下的写入)'
817
+ );
818
+ }
819
+ const allowed = targetRel !== null && effectiveWhitelist !== null && targetAllowed(targetRel, effectiveWhitelist, activeChange);
820
+ if (!allowed) {
821
+ hookBlock(
822
+ `BLOCKED: 命令写入 "${t}" 不在当前节点 "${currentNode}" 允许范围`,
823
+ effectiveWhitelist === null
824
+ ? `请在协议 writeWhitelist 中为节点 "${currentNode}" 声明允许的路径前缀`
825
+ : `允许范围: ${effectiveWhitelist.join(', ')}`
826
+ );
827
+ }
828
+ }
829
+ }
830
+ }
831
+
832
+ // ── worktree 隔离区放行(CC Agent isolation:"worktree")────────────────────
833
+ // 判定实现见 isInsideAgentWorktree + agentWorktreeWriteStaysIsolated(与上方 Bash 命令写入
834
+ // 判定共用——同一路径不因工具而异);词法命中但物理落点在区外 → 拒(fail-closed)。
835
+ if (isInsideAgentWorktree(target)) {
836
+ if (!(await agentWorktreeWriteStaysIsolated(target))) {
837
+ hookBlock(
838
+ `BLOCKED: 写入 "${target}" 位于 worktree 隔离区但物理落点在区外(符号链接/junction 穿越)`,
839
+ '恢复: 改用隔离区内的真实路径(隔离区放行仅限物理位于 <项目根>/.claude/worktrees/ 之下的写入)'
840
+ );
841
+ }
842
+ hookOk();
843
+ return;
844
+ }
845
+
846
+ if (currentNode && target) {
847
+ if (blockedStateFileTarget(target)) {
848
+ blockStateFileWrite(target);
849
+ }
850
+ const whitelist = PHASE_WRITE_WHITELIST[currentNode];
851
+ if (whitelist) {
852
+ const allowed = targetAllowed(target, whitelist, activeChange);
853
+ if (!allowed) {
854
+ hookBlock(`BLOCKED: phase "${currentNode}" 不允许写入 "${target}"`, `允许范围: ${whitelist.join(', ')}`);
855
+ }
856
+ } else if (declared) {
857
+ // 审查补充(2026-08-08):协议声明了 writeWhitelist 但未列出当前节点 → fail-closed 拒绝
858
+ // (漏声明节点不放行——防协议作者漏列导致防线出洞)
859
+ hookBlock(`BLOCKED: phase "${currentNode}" 未在协议 writeWhitelist 中声明,默认拒绝写入 "${target}"`, `请在协议 writeWhitelist 中为节点 "${currentNode}" 声明允许的路径前缀`);
860
+ } else {
861
+ // :未声明 writeWhitelist 时,非内置节点(缺省表无此 id)→ 协调者默认 ['.specs/']
862
+ // ——与内置 execute/subagent-execute 协调者语义统一(写源码必须显式声明,防 fail-open 防线出洞)
863
+ const coordDefault = ['.specs/'];
864
+ const allowed = coordDefault.some(prefix => prefix === '' || target.startsWith(prefix));
865
+ if (!allowed) {
866
+ hookBlock(`BLOCKED: phase "${currentNode}" 不允许写入 "${target}"`, `允许范围: ${coordDefault.join(', ')}(未声明 writeWhitelist 的协调者默认)`);
867
+ }
868
+ }
869
+ }
870
+ let state;
871
+ try {
872
+ state = await readStateJson(await statePath(protocol));
873
+ } catch (error) {
874
+ if (error && typeof error === 'object' && error.code === 'ENOENT') {
875
+ // 无 state 文件(无活跃 workflow / 新克隆仓库)→ 放行,不阻断写入
876
+ hookOk('(no active workflow)');
877
+ return;
878
+ }
879
+ throw error;
880
+ }
881
+ // 判定语义——
882
+ // ① 无 activeChange(无论 status;与"无 state 文件"同语义,覆盖旧 state 归档后)→ 放行
883
+ // ② running(含旧 state 无 status 但有 activeChange,fail-closed 向后兼容)→ 白名单校验
884
+ // ③ completed(归档后)→ 放行;其他 → 拦截
885
+ if (!state.activeChange) {
886
+ hookOk('(no active workflow)');
887
+ return;
888
+ }
889
+ const running = state.status === 'running' || state.status === undefined;
890
+ if (!running) {
891
+ if (state.status === 'completed') {
892
+ hookOk('(workflow completed)');
893
+ return;
894
+ }
895
+ throw new Error('workflow is not running; current status is ' + String(state.status));
896
+ }
897
+ const current = state.currentNode ?? nextNode(protocol, state)?.id ?? null;
898
+ if (!current || !nodes.some((node) => node.id === current)) {
899
+ throw new Error('workflow state has no valid current Node');
900
+ }
901
+ hookOk();
902
+ if (isCodex) return;
903
+ console.log('NODE: ' + current);
904
+ }
905
+
906
+ main().catch((error) => {
907
+ console.error(error.message);
908
+ process.exit(1);
909
+ });