@leocm/flowcraft 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +19 -2
  2. package/bin/cli.js +108 -108
  3. package/flowcraft.yaml +30 -30
  4. package/install.sh +24 -24
  5. package/lib/args.js +38 -38
  6. package/lib/config.js +20 -20
  7. package/lib/copy.js +131 -131
  8. package/lib/fix.js +110 -110
  9. package/lib/fsutil.js +104 -104
  10. package/lib/global.js +229 -229
  11. package/lib/init.js +43 -43
  12. package/lib/runtime.js +84 -84
  13. package/lib/version.js +55 -55
  14. package/lib/wizard.js +125 -125
  15. package/package.json +33 -33
  16. package/presets/backend.yaml +20 -20
  17. package/presets/default.yaml +15 -15
  18. package/presets/frontend.yaml +20 -20
  19. package/presets/quick-fix.yaml +15 -15
  20. package/setup/.claude/hooks/check-phase-test.py +152 -152
  21. package/setup/.claude/hooks/check-phase-write.py +235 -235
  22. package/setup/.claude/hooks/dispatch.py +67 -67
  23. package/setup/.claude/hooks/file-suggestion.py +45 -45
  24. package/setup/.claude/hooks/flowcraft_env.py +162 -137
  25. package/setup/.claude/hooks/permission-request.py +132 -125
  26. package/setup/.claude/hooks/post-tool-failure.py +36 -36
  27. package/setup/.claude/hooks/pre-compact.py +66 -66
  28. package/setup/.claude/hooks/review-runner.py +846 -846
  29. package/setup/.claude/hooks/setup-keys.py +282 -282
  30. package/setup/.claude/hooks/statusline.py +63 -63
  31. package/setup/.claude/hooks/stop-check.py +186 -171
  32. package/setup/.claude/hooks/subagent-start.py +50 -50
  33. package/setup/.claude/hooks/subagent-stop.py +63 -63
  34. package/setup/.claude/hooks/task-completed.py +57 -57
  35. package/setup/.claude/hooks/task_manager.py +592 -592
  36. package/setup/.claude/hooks/user-prompt-submit.py +91 -85
  37. package/setup/.claude/settings.json +233 -237
  38. package/setup/.claude/skills/Pstatus/SKILL.md +68 -68
  39. package/setup/.claude/skills/archive/SKILL.md +195 -195
  40. package/setup/.claude/skills/brainstorming/SKILL.md +5 -5
  41. package/setup/.claude/skills/brainstorming/scripts/server.cjs +723 -723
  42. package/setup/.claude/skills/brainstorming/scripts/start-server.py +245 -245
  43. package/setup/.claude/skills/brainstorming/scripts/stop-server.py +178 -178
  44. package/setup/.claude/skills/brainstorming/visual-companion.md +298 -298
  45. package/setup/.claude/skills/chrome-integration/SKILL.md +66 -66
  46. package/setup/.claude/skills/code-review/SKILL.md +264 -264
  47. package/setup/.claude/skills/executing-plans/SKILL.md +1 -1
  48. package/setup/.claude/skills/gitnexus/gitnexus-cli/SKILL.md +67 -67
  49. package/setup/.claude/skills/gitnexus/gitnexus-debugging/SKILL.md +1 -1
  50. package/setup/.claude/skills/gitnexus/gitnexus-exploring/SKILL.md +1 -1
  51. package/setup/.claude/skills/gitnexus/gitnexus-guide/SKILL.md +1 -1
  52. package/setup/.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md +1 -1
  53. package/setup/.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md +1 -1
  54. package/setup/.claude/skills/methodology/SKILL.md +124 -0
  55. package/setup/.claude/skills/phase/SKILL.md +62 -62
  56. package/setup/.claude/skills/playwright/SKILL.md +85 -85
  57. package/setup/.claude/skills/review/SKILL.md +97 -97
  58. package/setup/.claude/skills/task/SKILL.md +26 -26
  59. package/setup/.claude/skills/test-driven-development/SKILL.md +1 -1
  60. package/setup/.claude/skills/ui-ux-pro-max/SKILL.md +1 -1
  61. package/setup/.claude/skills/verification-before-completion/SKILL.md +1 -1
  62. package/setup/.claude/skills/writing-plans/SKILL.md +1 -1
  63. package/setup/.codex/.agents/skills/archive/SKILL.md +195 -195
  64. package/setup/.codex/.agents/skills/brainstorming/SKILL.md +5 -5
  65. package/setup/.codex/.agents/skills/brainstorming/scripts/server.cjs +723 -723
  66. package/setup/.codex/.agents/skills/brainstorming/scripts/start-server.py +245 -245
  67. package/setup/.codex/.agents/skills/brainstorming/scripts/stop-server.py +178 -178
  68. package/setup/.codex/.agents/skills/brainstorming/visual-companion.md +298 -298
  69. package/setup/.codex/.agents/skills/chrome-integration/SKILL.md +66 -66
  70. package/setup/.codex/.agents/skills/code-review/SKILL.md +264 -264
  71. package/setup/.codex/.agents/skills/executing-plans/SKILL.md +1 -1
  72. package/setup/.codex/.agents/skills/gitnexus/gitnexus-cli/SKILL.md +67 -67
  73. package/setup/.codex/.agents/skills/gitnexus/gitnexus-debugging/SKILL.md +1 -1
  74. package/setup/.codex/.agents/skills/gitnexus/gitnexus-exploring/SKILL.md +1 -1
  75. package/setup/.codex/.agents/skills/gitnexus/gitnexus-guide/SKILL.md +1 -1
  76. package/setup/.codex/.agents/skills/gitnexus/gitnexus-impact-analysis/SKILL.md +1 -1
  77. package/setup/.codex/.agents/skills/gitnexus/gitnexus-refactoring/SKILL.md +1 -1
  78. package/setup/.codex/.agents/skills/methodology/SKILL.md +124 -0
  79. package/setup/.codex/.agents/skills/phase/SKILL.md +62 -62
  80. package/setup/.codex/.agents/skills/playwright/SKILL.md +85 -85
  81. package/setup/.codex/.agents/skills/review/SKILL.md +97 -97
  82. package/setup/.codex/.agents/skills/task/SKILL.md +27 -27
  83. package/setup/.codex/.agents/skills/test-driven-development/SKILL.md +1 -1
  84. package/setup/.codex/.agents/skills/ui-ux-pro-max/SKILL.md +1 -1
  85. package/setup/.codex/.agents/skills/verification-before-completion/SKILL.md +1 -1
  86. package/setup/.codex/.agents/skills/writing-plans/SKILL.md +1 -1
  87. package/setup/.codex/hooks/review-runner.py +851 -851
  88. package/setup/.codex/hooks/setup-keys.py +287 -287
  89. package/setup/AGENTS.md +11 -1
  90. package/setup/CLAUDE.md +11 -1
  91. package/setup/install.sh +24 -24
  92. package/setup/tests/test_decision_timeout.py +241 -241
  93. package/setup/tests/test_hook_guards.py +357 -357
  94. package/setup/tests/test_sdlc_bootstrap.py +167 -167
  95. package/setup/tests/test_sessionlog_switch.py +199 -0
  96. package/setup/tests/test_task_manager.py +148 -148
@@ -1,235 +1,235 @@
1
- #!/usr/bin/env python3
2
- """check-phase-write - PreToolUse hook for Write/Edit operations.
3
-
4
- Guards SDLC framework files and enforces phase-based code-edit restrictions.
5
- Reads flowcraft.yaml for stage configuration and complexity-based skipping.
6
-
7
- Auto-transition: P0 + code write → auto-enter P1 (no user prompt).
8
- """
9
- import re
10
- import sys
11
- from datetime import datetime
12
- from pathlib import Path
13
-
14
- from flowcraft_env import extract_nested, get_project_root, is_under_root
15
- from task_manager import get_task_state
16
-
17
- CODE_EXTS = {
18
- "java", "js", "ts", "jsx", "tsx", "py", "go", "rs", "c", "cpp", "h",
19
- "cs", "rb", "php", "swift", "kt", "dart", "vue", "svelte", "html", "css",
20
- }
21
-
22
- # Phases that can be skipped based on complexity
23
- SKIPPABLE_PHASES = {"P1", "P3", "P5"}
24
-
25
-
26
- def auto_transition_to_p1(state_file: Path) -> bool:
27
- """Auto-transition from P0 to P1 when code write is attempted.
28
-
29
- Updates project-state.md: current_phase → P1, adds phase_history entry.
30
-
31
- Args:
32
- state_file: Task/project state file to update.
33
- Returns:
34
- True when the state file was updated successfully.
35
- """
36
- try:
37
- content = state_file.read_text(encoding="utf-8")
38
- now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
39
-
40
- # Update current_phase
41
- content = re.sub(
42
- r"^current_phase:\s*\S+",
43
- "current_phase: P1",
44
- content,
45
- count=1,
46
- flags=re.M,
47
- )
48
- # Update last_updated
49
- content = re.sub(
50
- r"^last_updated:\s*\S+",
51
- f"last_updated: \"{now}\"",
52
- content,
53
- count=1,
54
- flags=re.M,
55
- )
56
- # Add phase_history entry (insert after "phase_history:")
57
- content = re.sub(
58
- r"(phase_history:\s*\n)",
59
- f'\\1 - phase: P1\n action: "auto-enter: code write detected"\n at: "{now}"\n',
60
- content,
61
- count=1,
62
- )
63
-
64
- state_file.write_text(content, encoding="utf-8")
65
- print(f"[FlowCraft] 检测到代码写入,自动进入 P1 需求阶段", file=sys.stderr)
66
- return True
67
- except Exception as e:
68
- print(f"[FlowCraft] 自动切换P1失败: {e}", file=sys.stderr)
69
- return False
70
-
71
-
72
- def load_flowcraft_config(project_root: Path) -> dict:
73
- """Load flowcraft.yaml configuration."""
74
- config_path = project_root / "flowcraft.yaml"
75
- if not config_path.is_file():
76
- return {}
77
- try:
78
- import yaml
79
- with open(config_path, "r", encoding="utf-8") as f:
80
- return yaml.safe_load(f) or {}
81
- except ImportError:
82
- # Fallback: parse simple YAML manually
83
- return _parse_yaml_simple(config_path)
84
- except Exception:
85
- return {}
86
-
87
-
88
- def _parse_yaml_simple(path: Path) -> dict:
89
- """Minimal YAML parser for flowcraft.yaml (no external dependency)."""
90
- config = {"stages": {}}
91
- try:
92
- for line in path.read_text(encoding="utf-8").splitlines():
93
- line = line.strip()
94
- if line.startswith("#") or not line or ":" not in line:
95
- continue
96
- # Handle stages section
97
- if re.match(r"^P\d+\.?\d*:", line):
98
- key, val = line.split(":", 1)
99
- config["stages"][key.strip()] = val.strip().strip('"').strip("'")
100
- except Exception:
101
- pass
102
- return config
103
-
104
-
105
- def get_complexity_level(state_file: Path) -> str:
106
- """Read complexity_level from the given state file."""
107
- if not state_file.is_file():
108
- return "medium"
109
- try:
110
- content = state_file.read_text(encoding="utf-8")
111
- m = re.search(r"^complexity_level:\s*(\S+)", content, re.M)
112
- if m:
113
- level = m.group(1).strip().lower()
114
- if level in ("low", "medium", "high"):
115
- return level
116
- except Exception:
117
- pass
118
- return "medium"
119
-
120
-
121
- def is_phase_skippable(phase: str, config: dict, complexity: str) -> bool:
122
- """Check if a phase should be skipped based on config and complexity."""
123
- stages = config.get("stages", {})
124
- phase_setting = stages.get(phase, "true")
125
-
126
- if phase_setting == "true":
127
- return False
128
- if phase_setting == "false":
129
- return True
130
- if phase_setting == "auto":
131
- # Auto mode: skip based on complexity
132
- if complexity == "low":
133
- return phase in SKIPPABLE_PHASES
134
- # medium and high: don't skip
135
- return False
136
- return False
137
-
138
-
139
- def main() -> int:
140
- raw = sys.stdin.read()
141
- # R1: real PreToolUse payloads nest the path under tool_input
142
- file_path = extract_nested(raw, "file_path")
143
- if not file_path:
144
- return 0
145
-
146
- # Windows path compatibility
147
- file_path = file_path.replace("\\", "/").replace("//", "/")
148
-
149
- project_root = get_project_root(__file__)
150
- state_file = get_task_state(__file__)
151
- current_phase = "P0"
152
- if state_file.is_file():
153
- try:
154
- m = re.search(r"^current_phase:\s*(\S+)", state_file.read_text(encoding="utf-8"), re.M)
155
- if m:
156
- current_phase = m.group(1).strip()
157
- except Exception:
158
- pass
159
-
160
- # No state file → non-SDLC project, allow everything (R3)
161
- if not state_file.is_file():
162
- return 0
163
-
164
- m = re.search(r"\.([^.\\/]+)$", file_path)
165
- ext = m.group(1).lower() if m else ""
166
-
167
- # Protect SDLC framework files (flowcraft/ paths continue to phase checks)
168
- if "flowcraft/" in file_path:
169
- pass
170
- elif re.search(
171
- r"/\.claude/(project-state\.md|session_log\.json|prd\.md|code-review-report\.md|"
172
- r"reports/.*|hooks/.*|skills/.*|memory/.*|docs/.*|plans/.*|tasks/[^/]+\.md)|/plan/",
173
- file_path,
174
- ):
175
- return 0
176
- elif "/.claude/" in file_path:
177
- # R1: 锚定 project_root——用户级 ~/.claude(如 Claude Code plans 草稿)不归守卫管
178
- if not is_under_root(file_path, project_root):
179
- return 0
180
- print(f"[FlowCraft 守卫] 禁止修改框架文件: {file_path}", file=sys.stderr)
181
- print("[FlowCraft 守卫] 如需修改框架文件,请手动编辑。", file=sys.stderr)
182
- return 2
183
-
184
- # Load flowcraft.yaml config and complexity
185
- config = load_flowcraft_config(project_root)
186
- complexity = get_complexity_level(state_file)
187
-
188
- # Check if current phase is skippable
189
- if is_phase_skippable(current_phase, config, complexity):
190
- return 0
191
-
192
- # P0: block the write and auto-enter P1 (R2)
193
- if current_phase == "P0" and ext in CODE_EXTS:
194
- ok = auto_transition_to_p1(state_file)
195
- print(f"[FlowCraft] P0阶段禁止直接修改代码: {file_path}", file=sys.stderr)
196
- print("", file=sys.stderr)
197
- if ok:
198
- print(" 已自动切换至 P1 需求阶段。", file=sys.stderr)
199
- print(" → 请先完成 P1 需求澄清与 PRD 确认后再编码", file=sys.stderr)
200
- return 2
201
-
202
- # P0.5: block code modifications (problem rollback mode)
203
- if current_phase == "P0.5" and ext in CODE_EXTS:
204
- print(f"[FlowCraft] P0.5问题回溯阶段,禁止修改代码: {file_path}", file=sys.stderr)
205
- print("", file=sys.stderr)
206
- print(" 请选择:", file=sys.stderr)
207
- print(" A. 优化原方案 → 运行 /P1", file=sys.stderr)
208
- print(" B. 重做需求 → 运行 /P1", file=sys.stderr)
209
- print(" C. 直接修复 → 需用户确认", file=sys.stderr)
210
- return 2
211
-
212
- # P1: only PRD and plan files
213
- if current_phase == "P1" and ext in CODE_EXTS:
214
- if re.search(r"/plan/|/\.claude/prd\.md", file_path):
215
- return 0
216
- print(f"[FlowCraft] P1阶段禁止修改代码文件: {file_path}", file=sys.stderr)
217
- print("", file=sys.stderr)
218
- print(" P1是需求设计阶段,只允许修改PRD和计划文件。", file=sys.stderr)
219
- print(" → 完成P1后自动进入P2编码阶段", file=sys.stderr)
220
- print(" → 或运行 /P2 强制跳转", file=sys.stderr)
221
- return 2
222
-
223
- # P5: code is frozen
224
- if current_phase == "P5" and ext in CODE_EXTS:
225
- print(f"[FlowCraft] P5交付阶段,代码已冻结: {file_path}", file=sys.stderr)
226
- print("", file=sys.stderr)
227
- print(" 代码已冻结,如需修改:", file=sys.stderr)
228
- print(" → 运行 /P0.5 进入问题回溯", file=sys.stderr)
229
- return 2
230
-
231
- return 0
232
-
233
-
234
- if __name__ == "__main__":
235
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """check-phase-write - PreToolUse hook for Write/Edit operations.
3
+
4
+ Guards SDLC framework files and enforces phase-based code-edit restrictions.
5
+ Reads flowcraft.yaml for stage configuration and complexity-based skipping.
6
+
7
+ Auto-transition: P0 + code write → auto-enter P1 (no user prompt).
8
+ """
9
+ import re
10
+ import sys
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+
14
+ from flowcraft_env import extract_nested, get_project_root, is_under_root
15
+ from task_manager import get_task_state
16
+
17
+ CODE_EXTS = {
18
+ "java", "js", "ts", "jsx", "tsx", "py", "go", "rs", "c", "cpp", "h",
19
+ "cs", "rb", "php", "swift", "kt", "dart", "vue", "svelte", "html", "css",
20
+ }
21
+
22
+ # Phases that can be skipped based on complexity
23
+ SKIPPABLE_PHASES = {"P1", "P3", "P5"}
24
+
25
+
26
+ def auto_transition_to_p1(state_file: Path) -> bool:
27
+ """Auto-transition from P0 to P1 when code write is attempted.
28
+
29
+ Updates project-state.md: current_phase → P1, adds phase_history entry.
30
+
31
+ Args:
32
+ state_file: Task/project state file to update.
33
+ Returns:
34
+ True when the state file was updated successfully.
35
+ """
36
+ try:
37
+ content = state_file.read_text(encoding="utf-8")
38
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
39
+
40
+ # Update current_phase
41
+ content = re.sub(
42
+ r"^current_phase:\s*\S+",
43
+ "current_phase: P1",
44
+ content,
45
+ count=1,
46
+ flags=re.M,
47
+ )
48
+ # Update last_updated
49
+ content = re.sub(
50
+ r"^last_updated:\s*\S+",
51
+ f"last_updated: \"{now}\"",
52
+ content,
53
+ count=1,
54
+ flags=re.M,
55
+ )
56
+ # Add phase_history entry (insert after "phase_history:")
57
+ content = re.sub(
58
+ r"(phase_history:\s*\n)",
59
+ f'\\1 - phase: P1\n action: "auto-enter: code write detected"\n at: "{now}"\n',
60
+ content,
61
+ count=1,
62
+ )
63
+
64
+ state_file.write_text(content, encoding="utf-8")
65
+ print(f"[FlowCraft] 检测到代码写入,自动进入 P1 需求阶段", file=sys.stderr)
66
+ return True
67
+ except Exception as e:
68
+ print(f"[FlowCraft] 自动切换P1失败: {e}", file=sys.stderr)
69
+ return False
70
+
71
+
72
+ def load_flowcraft_config(project_root: Path) -> dict:
73
+ """Load flowcraft.yaml configuration."""
74
+ config_path = project_root / "flowcraft.yaml"
75
+ if not config_path.is_file():
76
+ return {}
77
+ try:
78
+ import yaml
79
+ with open(config_path, "r", encoding="utf-8") as f:
80
+ return yaml.safe_load(f) or {}
81
+ except ImportError:
82
+ # Fallback: parse simple YAML manually
83
+ return _parse_yaml_simple(config_path)
84
+ except Exception:
85
+ return {}
86
+
87
+
88
+ def _parse_yaml_simple(path: Path) -> dict:
89
+ """Minimal YAML parser for flowcraft.yaml (no external dependency)."""
90
+ config = {"stages": {}}
91
+ try:
92
+ for line in path.read_text(encoding="utf-8").splitlines():
93
+ line = line.strip()
94
+ if line.startswith("#") or not line or ":" not in line:
95
+ continue
96
+ # Handle stages section
97
+ if re.match(r"^P\d+\.?\d*:", line):
98
+ key, val = line.split(":", 1)
99
+ config["stages"][key.strip()] = val.strip().strip('"').strip("'")
100
+ except Exception:
101
+ pass
102
+ return config
103
+
104
+
105
+ def get_complexity_level(state_file: Path) -> str:
106
+ """Read complexity_level from the given state file."""
107
+ if not state_file.is_file():
108
+ return "medium"
109
+ try:
110
+ content = state_file.read_text(encoding="utf-8")
111
+ m = re.search(r"^complexity_level:\s*(\S+)", content, re.M)
112
+ if m:
113
+ level = m.group(1).strip().lower()
114
+ if level in ("low", "medium", "high"):
115
+ return level
116
+ except Exception:
117
+ pass
118
+ return "medium"
119
+
120
+
121
+ def is_phase_skippable(phase: str, config: dict, complexity: str) -> bool:
122
+ """Check if a phase should be skipped based on config and complexity."""
123
+ stages = config.get("stages", {})
124
+ phase_setting = stages.get(phase, "true")
125
+
126
+ if phase_setting == "true":
127
+ return False
128
+ if phase_setting == "false":
129
+ return True
130
+ if phase_setting == "auto":
131
+ # Auto mode: skip based on complexity
132
+ if complexity == "low":
133
+ return phase in SKIPPABLE_PHASES
134
+ # medium and high: don't skip
135
+ return False
136
+ return False
137
+
138
+
139
+ def main() -> int:
140
+ raw = sys.stdin.read()
141
+ # R1: real PreToolUse payloads nest the path under tool_input
142
+ file_path = extract_nested(raw, "file_path")
143
+ if not file_path:
144
+ return 0
145
+
146
+ # Windows path compatibility
147
+ file_path = file_path.replace("\\", "/").replace("//", "/")
148
+
149
+ project_root = get_project_root(__file__)
150
+ state_file = get_task_state(__file__)
151
+ current_phase = "P0"
152
+ if state_file.is_file():
153
+ try:
154
+ m = re.search(r"^current_phase:\s*(\S+)", state_file.read_text(encoding="utf-8"), re.M)
155
+ if m:
156
+ current_phase = m.group(1).strip()
157
+ except Exception:
158
+ pass
159
+
160
+ # No state file → non-SDLC project, allow everything (R3)
161
+ if not state_file.is_file():
162
+ return 0
163
+
164
+ m = re.search(r"\.([^.\\/]+)$", file_path)
165
+ ext = m.group(1).lower() if m else ""
166
+
167
+ # Protect SDLC framework files (flowcraft/ paths continue to phase checks)
168
+ if "flowcraft/" in file_path:
169
+ pass
170
+ elif re.search(
171
+ r"/\.claude/(project-state\.md|session_log\.json|prd\.md|code-review-report\.md|"
172
+ r"reports/.*|hooks/.*|skills/.*|memory/.*|docs/.*|plans/.*|tasks/[^/]+\.md)|/plan/",
173
+ file_path,
174
+ ):
175
+ return 0
176
+ elif "/.claude/" in file_path:
177
+ # R1: 锚定 project_root——用户级 ~/.claude(如 Claude Code plans 草稿)不归守卫管
178
+ if not is_under_root(file_path, project_root):
179
+ return 0
180
+ print(f"[FlowCraft 守卫] 禁止修改框架文件: {file_path}", file=sys.stderr)
181
+ print("[FlowCraft 守卫] 如需修改框架文件,请手动编辑。", file=sys.stderr)
182
+ return 2
183
+
184
+ # Load flowcraft.yaml config and complexity
185
+ config = load_flowcraft_config(project_root)
186
+ complexity = get_complexity_level(state_file)
187
+
188
+ # Check if current phase is skippable
189
+ if is_phase_skippable(current_phase, config, complexity):
190
+ return 0
191
+
192
+ # P0: block the write and auto-enter P1 (R2)
193
+ if current_phase == "P0" and ext in CODE_EXTS:
194
+ ok = auto_transition_to_p1(state_file)
195
+ print(f"[FlowCraft] P0阶段禁止直接修改代码: {file_path}", file=sys.stderr)
196
+ print("", file=sys.stderr)
197
+ if ok:
198
+ print(" 已自动切换至 P1 需求阶段。", file=sys.stderr)
199
+ print(" → 请先完成 P1 需求澄清与 PRD 确认后再编码", file=sys.stderr)
200
+ return 2
201
+
202
+ # P0.5: block code modifications (problem rollback mode)
203
+ if current_phase == "P0.5" and ext in CODE_EXTS:
204
+ print(f"[FlowCraft] P0.5问题回溯阶段,禁止修改代码: {file_path}", file=sys.stderr)
205
+ print("", file=sys.stderr)
206
+ print(" 请选择:", file=sys.stderr)
207
+ print(" A. 优化原方案 → 运行 /P1", file=sys.stderr)
208
+ print(" B. 重做需求 → 运行 /P1", file=sys.stderr)
209
+ print(" C. 直接修复 → 需用户确认", file=sys.stderr)
210
+ return 2
211
+
212
+ # P1: only PRD and plan files
213
+ if current_phase == "P1" and ext in CODE_EXTS:
214
+ if re.search(r"/plan/|/\.claude/prd\.md", file_path):
215
+ return 0
216
+ print(f"[FlowCraft] P1阶段禁止修改代码文件: {file_path}", file=sys.stderr)
217
+ print("", file=sys.stderr)
218
+ print(" P1是需求设计阶段,只允许修改PRD和计划文件。", file=sys.stderr)
219
+ print(" → 完成P1后自动进入P2编码阶段", file=sys.stderr)
220
+ print(" → 或运行 /P2 强制跳转", file=sys.stderr)
221
+ return 2
222
+
223
+ # P5: code is frozen
224
+ if current_phase == "P5" and ext in CODE_EXTS:
225
+ print(f"[FlowCraft] P5交付阶段,代码已冻结: {file_path}", file=sys.stderr)
226
+ print("", file=sys.stderr)
227
+ print(" 代码已冻结,如需修改:", file=sys.stderr)
228
+ print(" → 运行 /P0.5 进入问题回溯", file=sys.stderr)
229
+ return 2
230
+
231
+ return 0
232
+
233
+
234
+ if __name__ == "__main__":
235
+ sys.exit(main())
@@ -1,67 +1,67 @@
1
- #!/usr/bin/env python3
2
- """Cross-platform hook dispatcher - Mac/Linux/Windows.
3
-
4
- Usage: dispatch.py <hook-name> [args...]
5
-
6
- Routes to the sibling ``<hook-name>.py`` script, forwarding stdin and the
7
- exit code. Extracts ``session_id`` from the hook payload and exposes it as
8
- FLOWCRAFT_SESSION_ID so task_manager can resolve per-session task bindings (R2).
9
- Supports both project-level (.claude/hooks/) and global (~/.flowcraft/hooks/)
10
- installations.
11
- """
12
- import json
13
- import os
14
- import re
15
- import subprocess
16
- import sys
17
- from pathlib import Path
18
-
19
-
20
- def extract_session_id(raw: bytes) -> str:
21
- """Extract session_id from the hook payload without altering it.
22
-
23
- Args:
24
- raw: Raw stdin bytes from the hook event.
25
- Returns:
26
- Session ID string, or empty when absent/unparseable.
27
- """
28
- try:
29
- text = raw.decode("utf-8", errors="replace")
30
- data = json.loads(text) if text.strip() else {}
31
- if isinstance(data, dict):
32
- return str(data.get("session_id") or "").strip()
33
- except Exception:
34
- pass
35
- m = re.search(rb'"session_id"\s*:\s*"([^"]+)"', raw)
36
- return m.group(1).decode("utf-8", errors="replace").strip() if m else ""
37
-
38
-
39
- def main() -> int:
40
- """Route the hook event to the target script with session context.
41
-
42
- Returns:
43
- The target script's exit code.
44
- """
45
- if len(sys.argv) < 2:
46
- print("Usage: dispatch.py <hook-name>", file=sys.stderr)
47
- return 1
48
- hook_name = sys.argv[1]
49
- script_dir = Path(__file__).resolve().parent
50
- target = script_dir / (hook_name + ".py")
51
- if not target.is_file():
52
- print(f"dispatch.py: hook not found: {target}", file=sys.stderr)
53
- return 0
54
- raw = sys.stdin.buffer.read()
55
- env = os.environ.copy()
56
- # R2 保险2:子钩子输出固定 UTF-8(消除 Windows GBK 乱码)
57
- env["PYTHONIOENCODING"] = "utf-8"
58
- env["PYTHONUTF8"] = "1"
59
- session_id = extract_session_id(raw)
60
- if session_id:
61
- env["FLOWCRAFT_SESSION_ID"] = session_id
62
- proc = subprocess.run([sys.executable, str(target), *sys.argv[2:]], input=raw, env=env)
63
- return proc.returncode
64
-
65
-
66
- if __name__ == "__main__":
67
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """Cross-platform hook dispatcher - Mac/Linux/Windows.
3
+
4
+ Usage: dispatch.py <hook-name> [args...]
5
+
6
+ Routes to the sibling ``<hook-name>.py`` script, forwarding stdin and the
7
+ exit code. Extracts ``session_id`` from the hook payload and exposes it as
8
+ FLOWCRAFT_SESSION_ID so task_manager can resolve per-session task bindings (R2).
9
+ Supports both project-level (.claude/hooks/) and global (~/.flowcraft/hooks/)
10
+ installations.
11
+ """
12
+ import json
13
+ import os
14
+ import re
15
+ import subprocess
16
+ import sys
17
+ from pathlib import Path
18
+
19
+
20
+ def extract_session_id(raw: bytes) -> str:
21
+ """Extract session_id from the hook payload without altering it.
22
+
23
+ Args:
24
+ raw: Raw stdin bytes from the hook event.
25
+ Returns:
26
+ Session ID string, or empty when absent/unparseable.
27
+ """
28
+ try:
29
+ text = raw.decode("utf-8", errors="replace")
30
+ data = json.loads(text) if text.strip() else {}
31
+ if isinstance(data, dict):
32
+ return str(data.get("session_id") or "").strip()
33
+ except Exception:
34
+ pass
35
+ m = re.search(rb'"session_id"\s*:\s*"([^"]+)"', raw)
36
+ return m.group(1).decode("utf-8", errors="replace").strip() if m else ""
37
+
38
+
39
+ def main() -> int:
40
+ """Route the hook event to the target script with session context.
41
+
42
+ Returns:
43
+ The target script's exit code.
44
+ """
45
+ if len(sys.argv) < 2:
46
+ print("Usage: dispatch.py <hook-name>", file=sys.stderr)
47
+ return 1
48
+ hook_name = sys.argv[1]
49
+ script_dir = Path(__file__).resolve().parent
50
+ target = script_dir / (hook_name + ".py")
51
+ if not target.is_file():
52
+ print(f"dispatch.py: hook not found: {target}", file=sys.stderr)
53
+ return 0
54
+ raw = sys.stdin.buffer.read()
55
+ env = os.environ.copy()
56
+ # R2 保险2:子钩子输出固定 UTF-8(消除 Windows GBK 乱码)
57
+ env["PYTHONIOENCODING"] = "utf-8"
58
+ env["PYTHONUTF8"] = "1"
59
+ session_id = extract_session_id(raw)
60
+ if session_id:
61
+ env["FLOWCRAFT_SESSION_ID"] = session_id
62
+ proc = subprocess.run([sys.executable, str(target), *sys.argv[2:]], input=raw, env=env)
63
+ return proc.returncode
64
+
65
+
66
+ if __name__ == "__main__":
67
+ sys.exit(main())