@leocm/flowcraft 2.2.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 +7 -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 -162
  25. package/setup/.claude/hooks/permission-request.py +132 -132
  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 -186
  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 -91
  37. package/setup/.claude/settings.json +233 -233
  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 -199
  96. package/setup/tests/test_task_manager.py +148 -148
package/setup/CLAUDE.md CHANGED
@@ -136,6 +136,13 @@ stages:
136
136
  - **Automatic task identification**: "implement / fix / refactor / what changes / add / modify" → **modification task** → automatically enter P1. "analyze / explain / view / why / how" → **consultation task** → answer directly in P0, do not enter P1. After an old task completes, a new request → archive to `completed_tasks` + reset task fields + new P1. **`project_roadmap` / `completed_tasks` / `global_architecture` are never reset**
137
137
  - **Problem rollback**: when an issue is found in completed functionality → enter P0.5, do not modify code casually
138
138
  - **Version selection must be user-confirmed**: when adding new dependencies/components, the P1 phase must first run `/oss-version-check` to verify the real latest stable version and known vulnerabilities (Maven Central / GitHub Releases / OSV), then provide version suggestions (current stable / latest / LTS) with a version verification table, and **wait for user confirmation before use**. Choosing a version on your own is forbidden. If the network is unavailable, mark the suggestion as "unverified" and re-verify after the network recovers.
139
+ - **Criterion first (判据先行)**: before acting, define a decidable success criterion (number/state/diff). If you cannot answer "how do I know it worked", do not start.
140
+ - **Single variable (单变量)**: change one variable at a time, keep everything else unchanged, and record it.
141
+ - **Enumerate candidates (枚举候选)**: when the target is uncertain, enumerate all candidates and verify one by one; inferring a single candidate is forbidden.
142
+ - **Switch dimension after 3 failures (三次换维度)**: 3 consecutive failures in the same dimension force a dimension switch (object/channel/coordinate/timing/permission); stuck = 3 rounds with no real progress.
143
+ - **No conclusion escalation (结论不升级)**: one failure only yields "this method failed", never "impossible". Reports use four parts: conclusion / done / not done & why (facts only) / next action.
144
+
145
+ > Full methodology (applies to every requirement, not only debugging): `methodology` skill.
139
146
 
140
147
  ## Wiki Cross-Validation Rules (Mandatory)
141
148
 
@@ -219,6 +226,7 @@ Before declaring a coding task complete (and before AI code review), answer thre
219
226
  1. **Correctness (正确性)** — does the change actually solve the problem? Any typos, missing imports, wrong paths, off-by-one errors?
220
227
  2. **Side effects (副作用)** — does it break callers/tests? Have you traced every caller of every function you modified?
221
228
  3. **Closure (收尾)** — have you met every PRD acceptance criterion? What is still not done?
229
+ 4. **Criterion (判据)** — does every PRD acceptance criterion have a decidable, machine-checkable verdict? (methodology: criterion first)
222
230
  If any answer is "not sure", go back and verify — never declare completion without the self-review.
223
231
  Completion marker:
224
232
  ```
@@ -250,6 +258,7 @@ Completion marker:
250
258
  ## P0.5 Problem Rollback (on demand)
251
259
 
252
260
  Receive issue report → record symptom → root-cause analysis (requirement ambiguity / design flaw / implementation bug) → A/B/C decision → wait for user choice, then execute:
261
+ Apply the `methodology` skill before deciding: state the criterion, enumerate candidates, and switch dimension if the same fix already failed 3 times.
253
262
  - **A** Optimize on original approach → P1 (approach has direction but has flaws)
254
263
  - **B** Redo requirements → P1 (requirements themselves are problematic)
255
264
  - **C** Fix code directly (not recommended, only when error is clear and does not affect approach)
@@ -279,6 +288,7 @@ At P1 start, ask the user to choose the requirement clarification method:
279
288
 
280
289
  ### 1. brainstorming requirement clarification
281
290
  Use the brainstorming skill to systematically clarify requirements; output the requirement list and design doc.
291
+ Every requirement must carry a decidable criterion ("how will we know it works"); a requirement without one goes back for clarification (see `methodology` skill).
282
292
 
283
293
  **【Decision Point 1: requirement confirmation】**
284
294
 
@@ -314,7 +324,7 @@ Flow: ask user if needed → scan HTTP/HTTPS calls in `modified_files` → choos
314
324
  - Wiki directory does not exist: skip
315
325
 
316
326
  ### 3. Generate report
317
- Auto-run `/P5report` to generate the task summary report.
327
+ Auto-run `/P5report` to generate the task summary report. The report follows the four-part format: 结论 / 已完成 / 未完成及原因 / 下一步 (see `methodology` skill).
318
328
 
319
329
  ### 4. Delivery confirmation
320
330
  Show the user the deliverable list and report summary; confirm completion.
package/setup/install.sh CHANGED
@@ -1,24 +1,24 @@
1
- #!/bin/bash
2
- # install.sh - FlowCraft 框架安装工具(薄包装:Node 为唯一安装逻辑源)
3
- # 用法: ./install.sh [install|init] [--global] [--preset <name|file>] [--quick] [--interactive]
4
- # 实现见 bin/cli.js 与 lib/(方案A 单实现收敛:本脚本仅探测 node 并转调)
5
-
6
- SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
7
-
8
- # 探测 Node(>=20),缺失时尝试安装后重试一次
9
- if ! node --version >/dev/null 2>&1; then
10
- echo "[运行时] 未检测到 Node.js,尝试安装 Node.js 24 ..."
11
- if command -v winget >/dev/null 2>&1; then
12
- winget install -e --id OpenJS.NodeJS.24 --accept-source-agreements --accept-package-agreements >/dev/null 2>&1
13
- elif command -v brew >/dev/null 2>&1; then
14
- brew install node@24 >/dev/null 2>&1
15
- elif command -v apt-get >/dev/null 2>&1; then
16
- sudo apt-get install -y nodejs >/dev/null 2>&1
17
- fi
18
- if ! node --version >/dev/null 2>&1; then
19
- echo "错误: 未找到 Node.js(>=20),请先安装 https://nodejs.org/ 后重试"
20
- exit 1
21
- fi
22
- fi
23
-
24
- exec node "$SCRIPT_DIR/bin/cli.js" "$@"
1
+ #!/bin/bash
2
+ # install.sh - FlowCraft 框架安装工具(薄包装:Node 为唯一安装逻辑源)
3
+ # 用法: ./install.sh [install|init] [--global] [--preset <name|file>] [--quick] [--interactive]
4
+ # 实现见 bin/cli.js 与 lib/(方案A 单实现收敛:本脚本仅探测 node 并转调)
5
+
6
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
7
+
8
+ # 探测 Node(>=20),缺失时尝试安装后重试一次
9
+ if ! node --version >/dev/null 2>&1; then
10
+ echo "[运行时] 未检测到 Node.js,尝试安装 Node.js 24 ..."
11
+ if command -v winget >/dev/null 2>&1; then
12
+ winget install -e --id OpenJS.NodeJS.24 --accept-source-agreements --accept-package-agreements >/dev/null 2>&1
13
+ elif command -v brew >/dev/null 2>&1; then
14
+ brew install node@24 >/dev/null 2>&1
15
+ elif command -v apt-get >/dev/null 2>&1; then
16
+ sudo apt-get install -y nodejs >/dev/null 2>&1
17
+ fi
18
+ if ! node --version >/dev/null 2>&1; then
19
+ echo "错误: 未找到 Node.js(>=20),请先安装 https://nodejs.org/ 后重试"
20
+ exit 1
21
+ fi
22
+ fi
23
+
24
+ exec node "$SCRIPT_DIR/bin/cli.js" "$@"
@@ -1,241 +1,241 @@
1
- """Decision-timeout auto-default tests for PRD R1-R7 (lazy channel).
2
-
3
- Covers: decision-card parsing (R4), timeout config (R3), pending-marker
4
- write/cleanup (R4), danger-card exclusion (R2), user-input resolution (R7),
5
- expired-marker injection on session start (R5), Codex parity (R5/R6).
6
- """
7
- import importlib.util
8
- import json
9
- import os
10
- import subprocess
11
- import sys
12
- import time
13
- from pathlib import Path
14
-
15
- import pytest
16
-
17
- HOOKS = Path(__file__).resolve().parents[1] / ".claude" / "hooks"
18
- CODEX_HOOK = Path(__file__).resolve().parents[1] / ".codex" / "hooks" / "sdlc-codex-hook.cjs"
19
- sys.path.insert(0, str(HOOKS))
20
-
21
-
22
- def load_hook_module(name, filename):
23
- """Load a hyphenated hook script as a module for unit tests.
24
-
25
- Args:
26
- name: Module name to register.
27
- filename: Hook file name under the hooks directory.
28
- Returns:
29
- The loaded module object.
30
- """
31
- spec = importlib.util.spec_from_file_location(name, HOOKS / filename)
32
- mod = importlib.util.module_from_spec(spec)
33
- spec.loader.exec_module(mod)
34
- return mod
35
-
36
-
37
- stop_check = load_hook_module("stop_check_under_test", "stop-check.py")
38
-
39
- CARD = (
40
- "**🧭 决策点 3 | PRD 确认**\n"
41
- "⏱ 120s 未选择 → 自动按推荐项执行\n\n"
42
- "**✅ 推荐 · A. 确认 PRD**\n"
43
- "**选择规则 / Selection rule**: 请选择 A / B。"
44
- )
45
-
46
-
47
- def make_project(root):
48
- """Create a minimal SDLC project skeleton for hook integration tests."""
49
- (root / ".claude").mkdir(parents=True, exist_ok=True)
50
- (root / ".claude" / "project-state.md").write_text(
51
- 'current_phase: P2\ntask_description: "t"\n', encoding="utf-8"
52
- )
53
- hooks = root / ".claude" / "hooks"
54
- hooks.mkdir(exist_ok=True)
55
- (hooks / "log_session.py").write_text("import sys\nsys.exit(0)\n", encoding="utf-8")
56
-
57
-
58
- def run_hook(name, payload, cwd):
59
- """Run a hook script against a fake project via CLAUDE_PROJECT_DIR."""
60
- env = os.environ.copy()
61
- env["CLAUDE_PROJECT_DIR"] = str(cwd)
62
- env.pop("FLOWCRAFT_TASK_ID", None)
63
- env.pop("FLOWCRAFT_SESSION_ID", None)
64
- return subprocess.run(
65
- [sys.executable, str(HOOKS / name)],
66
- input=payload,
67
- capture_output=True,
68
- encoding="utf-8",
69
- errors="replace",
70
- cwd=str(cwd),
71
- env=env,
72
- timeout=60,
73
- )
74
-
75
-
76
- # ---------- R2/R4: decision-card parsing ----------
77
-
78
- class TestParseDecisionCard:
79
- def test_card_with_recommendation(self):
80
- point, rec = stop_check._parse_decision_card(CARD)
81
- assert point == "PRD 确认"
82
- assert rec == "A"
83
-
84
- def test_plain_reply_no_card(self):
85
- assert stop_check._parse_decision_card("实现完成,无决策。") == ("", "")
86
-
87
- def test_card_without_recommendation_yields_empty(self):
88
- """解析不出推荐项 → 不写标记(宁缺勿误执行)。"""
89
- point, rec = stop_check._parse_decision_card("🧭 决策点 | 测试\n请选择 A / B。")
90
- assert point == "测试"
91
- assert rec == ""
92
-
93
-
94
- # ---------- R3: timeout config ----------
95
-
96
- class TestReadTimeout:
97
- def test_default_120(self, tmp_path):
98
- assert stop_check._read_timeout(tmp_path) == 120
99
-
100
- def test_value_from_yaml(self, tmp_path):
101
- (tmp_path / "flowcraft.yaml").write_text("decision_timeout: 30\n", encoding="utf-8")
102
- assert stop_check._read_timeout(tmp_path) == 30
103
-
104
-
105
- # ---------- R2/R4/R7: marker lifecycle (integration) ----------
106
-
107
- class TestMarkerLifecycle:
108
- def test_card_stop_writes_marker(self, tmp_path):
109
- make_project(tmp_path)
110
- p = run_hook("stop-check.py", json.dumps({"last_assistant_message": CARD}), tmp_path)
111
- assert p.returncode == 0
112
- data = json.loads((tmp_path / ".claude" / "decision-pending.json").read_text(encoding="utf-8"))
113
- assert data["point"] == "PRD 确认"
114
- assert data["recommended"] == "A"
115
- assert data["timeout"] == 120
116
- assert data["deadline"] > time.time()
117
-
118
- def test_danger_card_writes_no_marker(self, tmp_path):
119
- make_project(tmp_path)
120
- card = "**🧭 决策点 | 删除确认**\n**✅ 推荐 · A. 删除文件**\n请选择 A / B。"
121
- run_hook("stop-check.py", json.dumps({"last_assistant_message": card}), tmp_path)
122
- assert not (tmp_path / ".claude" / "decision-pending.json").exists()
123
-
124
- def test_non_card_stop_clears_marker(self, tmp_path):
125
- make_project(tmp_path)
126
- marker = tmp_path / ".claude" / "decision-pending.json"
127
- marker.write_text("{}", encoding="utf-8")
128
- run_hook("stop-check.py", json.dumps({"last_assistant_message": "任务完成。"}), tmp_path)
129
- assert not marker.exists()
130
-
131
- def test_user_input_clears_marker(self, tmp_path):
132
- """R7: 任意用户输入即视为已响应。"""
133
- make_project(tmp_path)
134
- marker = tmp_path / ".claude" / "decision-pending.json"
135
- marker.write_text("{}", encoding="utf-8")
136
- p = run_hook("user-prompt-submit.py", "A", tmp_path)
137
- assert p.returncode == 0
138
- assert not marker.exists()
139
-
140
-
141
- # ---------- R5: lazy check on session start ----------
142
-
143
- class TestSessionStartLazyCheck:
144
- def test_expired_marker_injects_auto_execute(self, tmp_path):
145
- make_project(tmp_path)
146
- (tmp_path / ".claude" / "decision-pending.json").write_text(
147
- json.dumps({"point": "PRD 确认", "recommended": "A", "deadline": int(time.time()) - 1, "timeout": 120}),
148
- encoding="utf-8",
149
- )
150
- p = run_hook("session-start.py", json.dumps({"source": "startup", "session_id": "s"}), tmp_path)
151
- out = json.loads(p.stdout)
152
- ctx = out["hookSpecificOutput"]["additionalContext"]
153
- assert "已超时" in ctx
154
- assert "PRD 确认" in ctx
155
-
156
- def test_unexpired_marker_not_injected(self, tmp_path):
157
- make_project(tmp_path)
158
- (tmp_path / ".claude" / "decision-pending.json").write_text(
159
- json.dumps({"point": "PRD 确认", "recommended": "A", "deadline": int(time.time()) + 600, "timeout": 120}),
160
- encoding="utf-8",
161
- )
162
- p = run_hook("session-start.py", json.dumps({"source": "startup", "session_id": "s"}), tmp_path)
163
- ctx = json.loads(p.stdout)["hookSpecificOutput"]["additionalContext"]
164
- assert "已超时" not in ctx
165
-
166
- def test_codex_expired_marker_injects(self, tmp_path):
167
- """Codex 侧对等:懒检查注入(R5 兜底通道)。"""
168
- copy_dir = tmp_path / "hookcopy"
169
- copy_dir.mkdir()
170
- target = copy_dir / "sdlc-codex-hook.cjs"
171
- target.write_bytes(CODEX_HOOK.read_bytes())
172
- proj = tmp_path / "proj"
173
- proj.mkdir()
174
- (proj / ".codex").mkdir()
175
- (proj / ".codex" / "project-state.md").write_text('current_phase: P2\ntask_description: "t"\n', encoding="utf-8")
176
- (proj / ".codex" / "decision-pending.json").write_text(
177
- json.dumps({"point": "PRD 确认", "recommended": "A", "deadline": int(time.time()) - 1, "timeout": 120}),
178
- encoding="utf-8",
179
- )
180
- p = subprocess.run(
181
- ["node", str(target), "session-start"],
182
- input=json.dumps({"cwd": str(proj), "source": "startup"}),
183
- capture_output=True,
184
- encoding="utf-8",
185
- errors="replace",
186
- cwd=str(proj),
187
- timeout=60,
188
- )
189
- assert p.returncode == 0
190
- assert "已超时" in p.stdout
191
- assert "PRD 确认" in p.stdout
192
-
193
-
194
- # ---------- R4/R5: Codex marker lifecycle parity ----------
195
-
196
- def make_codex_project(root):
197
- """Create a minimal Codex-side SDLC project skeleton."""
198
- (root / ".codex").mkdir(parents=True, exist_ok=True)
199
- (root / ".codex" / "project-state.md").write_text(
200
- 'current_phase: P2\ntask_description: "t"\n', encoding="utf-8"
201
- )
202
-
203
-
204
- def run_codex_hook(tmp_path, proj, event, payload):
205
- """Run a copied codex hook against a fake project (neutral __dirname)."""
206
- copy_dir = tmp_path / "codexcopy"
207
- copy_dir.mkdir(exist_ok=True)
208
- target = copy_dir / "sdlc-codex-hook.cjs"
209
- if not target.exists():
210
- target.write_bytes(CODEX_HOOK.read_bytes())
211
- return subprocess.run(
212
- ["node", str(target), event],
213
- input=json.dumps(payload),
214
- capture_output=True,
215
- encoding="utf-8",
216
- errors="replace",
217
- cwd=str(proj),
218
- timeout=60,
219
- )
220
-
221
-
222
- class TestCodexMarkerLifecycle:
223
- def test_card_stop_writes_marker(self, tmp_path):
224
- proj = tmp_path / "proj"
225
- proj.mkdir()
226
- make_codex_project(proj)
227
- p = run_codex_hook(tmp_path, proj, "stop-check", {"cwd": str(proj), "last_assistant_message": CARD})
228
- assert p.returncode == 0
229
- data = json.loads((proj / ".codex" / "decision-pending.json").read_text(encoding="utf-8"))
230
- assert data["point"] == "PRD 确认"
231
- assert data["recommended"] == "A"
232
-
233
- def test_non_card_stop_clears_marker(self, tmp_path):
234
- proj = tmp_path / "proj"
235
- proj.mkdir()
236
- make_codex_project(proj)
237
- marker = proj / ".codex" / "decision-pending.json"
238
- marker.write_text("{}", encoding="utf-8")
239
- p = run_codex_hook(tmp_path, proj, "stop-check", {"cwd": str(proj), "last_assistant_message": "任务完成。"})
240
- assert p.returncode == 0
241
- assert not marker.exists()
1
+ """Decision-timeout auto-default tests for PRD R1-R7 (lazy channel).
2
+
3
+ Covers: decision-card parsing (R4), timeout config (R3), pending-marker
4
+ write/cleanup (R4), danger-card exclusion (R2), user-input resolution (R7),
5
+ expired-marker injection on session start (R5), Codex parity (R5/R6).
6
+ """
7
+ import importlib.util
8
+ import json
9
+ import os
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+
15
+ import pytest
16
+
17
+ HOOKS = Path(__file__).resolve().parents[1] / ".claude" / "hooks"
18
+ CODEX_HOOK = Path(__file__).resolve().parents[1] / ".codex" / "hooks" / "sdlc-codex-hook.cjs"
19
+ sys.path.insert(0, str(HOOKS))
20
+
21
+
22
+ def load_hook_module(name, filename):
23
+ """Load a hyphenated hook script as a module for unit tests.
24
+
25
+ Args:
26
+ name: Module name to register.
27
+ filename: Hook file name under the hooks directory.
28
+ Returns:
29
+ The loaded module object.
30
+ """
31
+ spec = importlib.util.spec_from_file_location(name, HOOKS / filename)
32
+ mod = importlib.util.module_from_spec(spec)
33
+ spec.loader.exec_module(mod)
34
+ return mod
35
+
36
+
37
+ stop_check = load_hook_module("stop_check_under_test", "stop-check.py")
38
+
39
+ CARD = (
40
+ "**🧭 决策点 3 | PRD 确认**\n"
41
+ "⏱ 120s 未选择 → 自动按推荐项执行\n\n"
42
+ "**✅ 推荐 · A. 确认 PRD**\n"
43
+ "**选择规则 / Selection rule**: 请选择 A / B。"
44
+ )
45
+
46
+
47
+ def make_project(root):
48
+ """Create a minimal SDLC project skeleton for hook integration tests."""
49
+ (root / ".claude").mkdir(parents=True, exist_ok=True)
50
+ (root / ".claude" / "project-state.md").write_text(
51
+ 'current_phase: P2\ntask_description: "t"\n', encoding="utf-8"
52
+ )
53
+ hooks = root / ".claude" / "hooks"
54
+ hooks.mkdir(exist_ok=True)
55
+ (hooks / "log_session.py").write_text("import sys\nsys.exit(0)\n", encoding="utf-8")
56
+
57
+
58
+ def run_hook(name, payload, cwd):
59
+ """Run a hook script against a fake project via CLAUDE_PROJECT_DIR."""
60
+ env = os.environ.copy()
61
+ env["CLAUDE_PROJECT_DIR"] = str(cwd)
62
+ env.pop("FLOWCRAFT_TASK_ID", None)
63
+ env.pop("FLOWCRAFT_SESSION_ID", None)
64
+ return subprocess.run(
65
+ [sys.executable, str(HOOKS / name)],
66
+ input=payload,
67
+ capture_output=True,
68
+ encoding="utf-8",
69
+ errors="replace",
70
+ cwd=str(cwd),
71
+ env=env,
72
+ timeout=60,
73
+ )
74
+
75
+
76
+ # ---------- R2/R4: decision-card parsing ----------
77
+
78
+ class TestParseDecisionCard:
79
+ def test_card_with_recommendation(self):
80
+ point, rec = stop_check._parse_decision_card(CARD)
81
+ assert point == "PRD 确认"
82
+ assert rec == "A"
83
+
84
+ def test_plain_reply_no_card(self):
85
+ assert stop_check._parse_decision_card("实现完成,无决策。") == ("", "")
86
+
87
+ def test_card_without_recommendation_yields_empty(self):
88
+ """解析不出推荐项 → 不写标记(宁缺勿误执行)。"""
89
+ point, rec = stop_check._parse_decision_card("🧭 决策点 | 测试\n请选择 A / B。")
90
+ assert point == "测试"
91
+ assert rec == ""
92
+
93
+
94
+ # ---------- R3: timeout config ----------
95
+
96
+ class TestReadTimeout:
97
+ def test_default_120(self, tmp_path):
98
+ assert stop_check._read_timeout(tmp_path) == 120
99
+
100
+ def test_value_from_yaml(self, tmp_path):
101
+ (tmp_path / "flowcraft.yaml").write_text("decision_timeout: 30\n", encoding="utf-8")
102
+ assert stop_check._read_timeout(tmp_path) == 30
103
+
104
+
105
+ # ---------- R2/R4/R7: marker lifecycle (integration) ----------
106
+
107
+ class TestMarkerLifecycle:
108
+ def test_card_stop_writes_marker(self, tmp_path):
109
+ make_project(tmp_path)
110
+ p = run_hook("stop-check.py", json.dumps({"last_assistant_message": CARD}), tmp_path)
111
+ assert p.returncode == 0
112
+ data = json.loads((tmp_path / ".claude" / "decision-pending.json").read_text(encoding="utf-8"))
113
+ assert data["point"] == "PRD 确认"
114
+ assert data["recommended"] == "A"
115
+ assert data["timeout"] == 120
116
+ assert data["deadline"] > time.time()
117
+
118
+ def test_danger_card_writes_no_marker(self, tmp_path):
119
+ make_project(tmp_path)
120
+ card = "**🧭 决策点 | 删除确认**\n**✅ 推荐 · A. 删除文件**\n请选择 A / B。"
121
+ run_hook("stop-check.py", json.dumps({"last_assistant_message": card}), tmp_path)
122
+ assert not (tmp_path / ".claude" / "decision-pending.json").exists()
123
+
124
+ def test_non_card_stop_clears_marker(self, tmp_path):
125
+ make_project(tmp_path)
126
+ marker = tmp_path / ".claude" / "decision-pending.json"
127
+ marker.write_text("{}", encoding="utf-8")
128
+ run_hook("stop-check.py", json.dumps({"last_assistant_message": "任务完成。"}), tmp_path)
129
+ assert not marker.exists()
130
+
131
+ def test_user_input_clears_marker(self, tmp_path):
132
+ """R7: 任意用户输入即视为已响应。"""
133
+ make_project(tmp_path)
134
+ marker = tmp_path / ".claude" / "decision-pending.json"
135
+ marker.write_text("{}", encoding="utf-8")
136
+ p = run_hook("user-prompt-submit.py", "A", tmp_path)
137
+ assert p.returncode == 0
138
+ assert not marker.exists()
139
+
140
+
141
+ # ---------- R5: lazy check on session start ----------
142
+
143
+ class TestSessionStartLazyCheck:
144
+ def test_expired_marker_injects_auto_execute(self, tmp_path):
145
+ make_project(tmp_path)
146
+ (tmp_path / ".claude" / "decision-pending.json").write_text(
147
+ json.dumps({"point": "PRD 确认", "recommended": "A", "deadline": int(time.time()) - 1, "timeout": 120}),
148
+ encoding="utf-8",
149
+ )
150
+ p = run_hook("session-start.py", json.dumps({"source": "startup", "session_id": "s"}), tmp_path)
151
+ out = json.loads(p.stdout)
152
+ ctx = out["hookSpecificOutput"]["additionalContext"]
153
+ assert "已超时" in ctx
154
+ assert "PRD 确认" in ctx
155
+
156
+ def test_unexpired_marker_not_injected(self, tmp_path):
157
+ make_project(tmp_path)
158
+ (tmp_path / ".claude" / "decision-pending.json").write_text(
159
+ json.dumps({"point": "PRD 确认", "recommended": "A", "deadline": int(time.time()) + 600, "timeout": 120}),
160
+ encoding="utf-8",
161
+ )
162
+ p = run_hook("session-start.py", json.dumps({"source": "startup", "session_id": "s"}), tmp_path)
163
+ ctx = json.loads(p.stdout)["hookSpecificOutput"]["additionalContext"]
164
+ assert "已超时" not in ctx
165
+
166
+ def test_codex_expired_marker_injects(self, tmp_path):
167
+ """Codex 侧对等:懒检查注入(R5 兜底通道)。"""
168
+ copy_dir = tmp_path / "hookcopy"
169
+ copy_dir.mkdir()
170
+ target = copy_dir / "sdlc-codex-hook.cjs"
171
+ target.write_bytes(CODEX_HOOK.read_bytes())
172
+ proj = tmp_path / "proj"
173
+ proj.mkdir()
174
+ (proj / ".codex").mkdir()
175
+ (proj / ".codex" / "project-state.md").write_text('current_phase: P2\ntask_description: "t"\n', encoding="utf-8")
176
+ (proj / ".codex" / "decision-pending.json").write_text(
177
+ json.dumps({"point": "PRD 确认", "recommended": "A", "deadline": int(time.time()) - 1, "timeout": 120}),
178
+ encoding="utf-8",
179
+ )
180
+ p = subprocess.run(
181
+ ["node", str(target), "session-start"],
182
+ input=json.dumps({"cwd": str(proj), "source": "startup"}),
183
+ capture_output=True,
184
+ encoding="utf-8",
185
+ errors="replace",
186
+ cwd=str(proj),
187
+ timeout=60,
188
+ )
189
+ assert p.returncode == 0
190
+ assert "已超时" in p.stdout
191
+ assert "PRD 确认" in p.stdout
192
+
193
+
194
+ # ---------- R4/R5: Codex marker lifecycle parity ----------
195
+
196
+ def make_codex_project(root):
197
+ """Create a minimal Codex-side SDLC project skeleton."""
198
+ (root / ".codex").mkdir(parents=True, exist_ok=True)
199
+ (root / ".codex" / "project-state.md").write_text(
200
+ 'current_phase: P2\ntask_description: "t"\n', encoding="utf-8"
201
+ )
202
+
203
+
204
+ def run_codex_hook(tmp_path, proj, event, payload):
205
+ """Run a copied codex hook against a fake project (neutral __dirname)."""
206
+ copy_dir = tmp_path / "codexcopy"
207
+ copy_dir.mkdir(exist_ok=True)
208
+ target = copy_dir / "sdlc-codex-hook.cjs"
209
+ if not target.exists():
210
+ target.write_bytes(CODEX_HOOK.read_bytes())
211
+ return subprocess.run(
212
+ ["node", str(target), event],
213
+ input=json.dumps(payload),
214
+ capture_output=True,
215
+ encoding="utf-8",
216
+ errors="replace",
217
+ cwd=str(proj),
218
+ timeout=60,
219
+ )
220
+
221
+
222
+ class TestCodexMarkerLifecycle:
223
+ def test_card_stop_writes_marker(self, tmp_path):
224
+ proj = tmp_path / "proj"
225
+ proj.mkdir()
226
+ make_codex_project(proj)
227
+ p = run_codex_hook(tmp_path, proj, "stop-check", {"cwd": str(proj), "last_assistant_message": CARD})
228
+ assert p.returncode == 0
229
+ data = json.loads((proj / ".codex" / "decision-pending.json").read_text(encoding="utf-8"))
230
+ assert data["point"] == "PRD 确认"
231
+ assert data["recommended"] == "A"
232
+
233
+ def test_non_card_stop_clears_marker(self, tmp_path):
234
+ proj = tmp_path / "proj"
235
+ proj.mkdir()
236
+ make_codex_project(proj)
237
+ marker = proj / ".codex" / "decision-pending.json"
238
+ marker.write_text("{}", encoding="utf-8")
239
+ p = run_codex_hook(tmp_path, proj, "stop-check", {"cwd": str(proj), "last_assistant_message": "任务完成。"})
240
+ assert p.returncode == 0
241
+ assert not marker.exists()