@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,45 +1,45 @@
1
- #!/usr/bin/env python3
2
- """fileSuggestion - @ file completion, prioritising Superpowers project files.
3
-
4
- Receives stdin JSON: {"query": "..."}
5
- Outputs: one file path per line (core files + rules + up to 10 skills).
6
- """
7
- import os
8
- import sys
9
- from pathlib import Path
10
-
11
-
12
- def main() -> int:
13
- project_dir = os.environ.get("CLAUDE_PROJECT_DIR") or "."
14
- root = Path(project_dir)
15
-
16
- # Superpowers project core files (always shown first)
17
- core_files = [
18
- ".claude/project-state.md",
19
- "CLAUDE.md",
20
- ".claude/settings.json",
21
- ]
22
- for f in core_files:
23
- if (root / f).is_file():
24
- print(f)
25
-
26
- # Superpowers rule files
27
- rules_dir = root / ".claude" / "sdlc" / "rules"
28
- if rules_dir.is_dir():
29
- for f in sorted(rules_dir.glob("*.md")):
30
- print(f".claude/sdlc/rules/{f.name}")
31
-
32
- # Skills files (max 10)
33
- skills_dir = root / ".claude" / "skills"
34
- if skills_dir.is_dir():
35
- count = 0
36
- for f in sorted(skills_dir.glob("*/SKILL.md")):
37
- if count >= 10:
38
- break
39
- print(f".claude/skills/{f.parent.name}/SKILL.md")
40
- count += 1
41
- return 0
42
-
43
-
44
- if __name__ == "__main__":
45
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """fileSuggestion - @ file completion, prioritising Superpowers project files.
3
+
4
+ Receives stdin JSON: {"query": "..."}
5
+ Outputs: one file path per line (core files + rules + up to 10 skills).
6
+ """
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+
12
+ def main() -> int:
13
+ project_dir = os.environ.get("CLAUDE_PROJECT_DIR") or "."
14
+ root = Path(project_dir)
15
+
16
+ # Superpowers project core files (always shown first)
17
+ core_files = [
18
+ ".claude/project-state.md",
19
+ "CLAUDE.md",
20
+ ".claude/settings.json",
21
+ ]
22
+ for f in core_files:
23
+ if (root / f).is_file():
24
+ print(f)
25
+
26
+ # Superpowers rule files
27
+ rules_dir = root / ".claude" / "sdlc" / "rules"
28
+ if rules_dir.is_dir():
29
+ for f in sorted(rules_dir.glob("*.md")):
30
+ print(f".claude/sdlc/rules/{f.name}")
31
+
32
+ # Skills files (max 10)
33
+ skills_dir = root / ".claude" / "skills"
34
+ if skills_dir.is_dir():
35
+ count = 0
36
+ for f in sorted(skills_dir.glob("*/SKILL.md")):
37
+ if count >= 10:
38
+ break
39
+ print(f".claude/skills/{f.parent.name}/SKILL.md")
40
+ count += 1
41
+ return 0
42
+
43
+
44
+ if __name__ == "__main__":
45
+ sys.exit(main())
@@ -1,137 +1,162 @@
1
- #!/usr/bin/env python3
2
- """FlowCraft environment detection - shared by all hook scripts.
3
-
4
- Provides get_project_root() to find the project's .claude/ directory,
5
- supporting both project-level and global (--global) installations, and
6
- extract_nested() for unified hook payload field extraction (R5).
7
- """
8
- import json
9
- import os
10
- import re
11
- import sys
12
- from pathlib import Path
13
-
14
-
15
- def get_project_root(script_path: str = None) -> Path:
16
- """Find the project root directory.
17
-
18
- Priority:
19
- 1. CLAUDE_PROJECT_DIR env var (set by Claude Code)
20
- 2. Walk up from CWD looking for .claude/project-state.md
21
- 3. Fallback: assume script is at {root}/.claude/hooks/ (project mode)
22
-
23
- Args:
24
- script_path: Path(__file__) from the calling script (for fallback)
25
- Returns:
26
- Path to project root directory
27
- """
28
- # 1. Claude Code sets this env var
29
- env_dir = os.environ.get("CLAUDE_PROJECT_DIR")
30
- if env_dir:
31
- p = Path(env_dir)
32
- if (p / ".claude").is_dir():
33
- return p
34
-
35
- # 2. Walk up from CWD looking for .claude/project-state.md (strict R3:
36
- # only a state file qualifies - a non-empty .claude dir without one,
37
- # e.g. the user-level ~/.claude, must never be treated as a project)
38
- cwd = Path.cwd()
39
- home_dir = Path.home()
40
- for parent in [cwd, *cwd.parents]:
41
- if (parent / ".claude" / "project-state.md").is_file():
42
- # R3 AC2: the user-level ~/.claude never serves as a project
43
- # root via walk-up (only when cwd is the home dir itself)
44
- if parent != cwd and parent.resolve() == home_dir.resolve():
45
- continue
46
- return parent
47
-
48
- # 3. Fallback: script at {root}/.claude/hooks/xxx.py (project mode)
49
- if script_path:
50
- script = Path(script_path).resolve()
51
- # Try parents[2] first (standard layout: .claude/hooks/xxx.py)
52
- candidate = script.parents[2] if len(script.parents) >= 3 else script.parent
53
- if (candidate / ".claude" / "project-state.md").is_file():
54
- # Same user-level exclusion as step 2 (global hook scripts)
55
- if not (candidate != cwd and candidate.resolve() == home_dir.resolve()):
56
- return candidate
57
-
58
- # Last resort: CWD
59
- return cwd
60
-
61
-
62
- def get_claude_dir(script_path: str = None) -> Path:
63
- """Find the .claude/ directory for the current project.
64
-
65
- Returns:
66
- Path to .claude/ directory
67
- """
68
- return get_project_root(script_path) / ".claude"
69
-
70
-
71
- def force_utf8_stdio() -> None:
72
- """把 stdout/stderr 固定为 UTF-8(R2: 消除 Windows GBK 乱码双保险之进程内保险).
73
-
74
- hook 失败须静默放行,因此任何异常都不外抛。
75
- """
76
- for stream in (sys.stdout, sys.stderr):
77
- try:
78
- stream.reconfigure(encoding="utf-8", errors="replace")
79
- except Exception:
80
- pass
81
-
82
-
83
- # 导入即生效:所有 import flowcraft_env 的钩子自动获得 UTF-8 stdio
84
- force_utf8_stdio()
85
-
86
-
87
- def is_under_root(file_path: str, root: Path) -> bool:
88
- """判断目标路径是否位于 root 之下(R1: 守卫只管项目内文件).
89
-
90
- Windows 路径按 normcase 归一(大小写/分隔符不敏感)后比较,避免
91
- 项目根解析与载荷路径书写形式不同导致误判。
92
-
93
- Args:
94
- file_path: 目标文件路径(任意分隔符)
95
- root: 项目根目录
96
- Returns:
97
- True 表示目标在 root 之下(含 root 自身)
98
- """
99
- try:
100
- target = os.path.normcase(os.path.abspath(str(file_path)))
101
- base = os.path.normcase(os.path.abspath(str(root)))
102
- return target == base or target.startswith(base + os.sep)
103
- except Exception:
104
- # 解析失败按"项目内"处理:守卫失败须保守(保持拦截),不静默放行
105
- return True
106
-
107
-
108
- def extract_nested(raw, key):
109
- """Extract a string field from a hook payload (R5 unified extraction).
110
-
111
- Priority: tool_input.{key} (nested, real Claude Code payload) →
112
- top-level {key} (flat payloads) → regex fallback (malformed JSON).
113
-
114
- Args:
115
- raw: Raw hook payload (str or bytes).
116
- key: Field name to extract.
117
- Returns:
118
- Field value as str, or "" when absent/empty.
119
- """
120
- text = raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else str(raw)
121
- data = {}
122
- try:
123
- parsed = json.loads(text) if text.strip() else {}
124
- if isinstance(parsed, dict):
125
- data = parsed
126
- except Exception:
127
- data = {}
128
- # Nested: real PreToolUse payloads keep tool args under tool_input
129
- tool_input = data.get("tool_input")
130
- if isinstance(tool_input, dict) and tool_input.get(key):
131
- return str(tool_input[key])
132
- # Flat: legacy payloads carry fields at top level
133
- if data.get(key):
134
- return str(data[key])
135
- # Regex fallback for unparseable payloads
136
- m = re.search(r'"%s"\s*:\s*"((?:[^"\\]|\\.)*)"' % re.escape(key), text)
137
- return m.group(1) if m else ""
1
+ #!/usr/bin/env python3
2
+ """FlowCraft environment detection - shared by all hook scripts.
3
+
4
+ Provides get_project_root() to find the project's .claude/ directory,
5
+ supporting both project-level and global (--global) installations, and
6
+ extract_nested() for unified hook payload field extraction (R5).
7
+ """
8
+ import json
9
+ import os
10
+ import re
11
+ import sys
12
+ from pathlib import Path
13
+
14
+
15
+ def get_project_root(script_path: str = None) -> Path:
16
+ """Find the project root directory.
17
+
18
+ Priority:
19
+ 1. CLAUDE_PROJECT_DIR env var (set by Claude Code)
20
+ 2. Walk up from CWD looking for .claude/project-state.md
21
+ 3. Fallback: assume script is at {root}/.claude/hooks/ (project mode)
22
+
23
+ Args:
24
+ script_path: Path(__file__) from the calling script (for fallback)
25
+ Returns:
26
+ Path to project root directory
27
+ """
28
+ # 1. Claude Code sets this env var
29
+ env_dir = os.environ.get("CLAUDE_PROJECT_DIR")
30
+ if env_dir:
31
+ p = Path(env_dir)
32
+ if (p / ".claude").is_dir():
33
+ return p
34
+
35
+ # 2. Walk up from CWD looking for .claude/project-state.md (strict R3:
36
+ # only a state file qualifies - a non-empty .claude dir without one,
37
+ # e.g. the user-level ~/.claude, must never be treated as a project)
38
+ cwd = Path.cwd()
39
+ home_dir = Path.home()
40
+ for parent in [cwd, *cwd.parents]:
41
+ if (parent / ".claude" / "project-state.md").is_file():
42
+ # R3 AC2: the user-level ~/.claude never serves as a project
43
+ # root via walk-up (only when cwd is the home dir itself)
44
+ if parent != cwd and parent.resolve() == home_dir.resolve():
45
+ continue
46
+ return parent
47
+
48
+ # 3. Fallback: script at {root}/.claude/hooks/xxx.py (project mode)
49
+ if script_path:
50
+ script = Path(script_path).resolve()
51
+ # Try parents[2] first (standard layout: .claude/hooks/xxx.py)
52
+ candidate = script.parents[2] if len(script.parents) >= 3 else script.parent
53
+ if (candidate / ".claude" / "project-state.md").is_file():
54
+ # Same user-level exclusion as step 2 (global hook scripts)
55
+ if not (candidate != cwd and candidate.resolve() == home_dir.resolve()):
56
+ return candidate
57
+
58
+ # Last resort: CWD
59
+ return cwd
60
+
61
+
62
+ def get_claude_dir(script_path: str = None) -> Path:
63
+ """Find the .claude/ directory for the current project.
64
+
65
+ Returns:
66
+ Path to .claude/ directory
67
+ """
68
+ return get_project_root(script_path) / ".claude"
69
+
70
+
71
+ def force_utf8_stdio() -> None:
72
+ """把 stdout/stderr 固定为 UTF-8(R2: 消除 Windows GBK 乱码双保险之进程内保险).
73
+
74
+ hook 失败须静默放行,因此任何异常都不外抛。
75
+ """
76
+ for stream in (sys.stdout, sys.stderr):
77
+ try:
78
+ stream.reconfigure(encoding="utf-8", errors="replace")
79
+ except Exception:
80
+ pass
81
+
82
+
83
+ # 导入即生效:所有 import flowcraft_env 的钩子自动获得 UTF-8 stdio
84
+ force_utf8_stdio()
85
+
86
+
87
+ def is_under_root(file_path: str, root: Path) -> bool:
88
+ """判断目标路径是否位于 root 之下(R1: 守卫只管项目内文件).
89
+
90
+ Windows 路径按 normcase 归一(大小写/分隔符不敏感)后比较,避免
91
+ 项目根解析与载荷路径书写形式不同导致误判。
92
+
93
+ Args:
94
+ file_path: 目标文件路径(任意分隔符)
95
+ root: 项目根目录
96
+ Returns:
97
+ True 表示目标在 root 之下(含 root 自身)
98
+ """
99
+ try:
100
+ target = os.path.normcase(os.path.abspath(str(file_path)))
101
+ base = os.path.normcase(os.path.abspath(str(root)))
102
+ return target == base or target.startswith(base + os.sep)
103
+ except Exception:
104
+ # 解析失败按"项目内"处理:守卫失败须保守(保持拦截),不静默放行
105
+ return True
106
+
107
+
108
+ def extract_nested(raw, key):
109
+ """Extract a string field from a hook payload (R5 unified extraction).
110
+
111
+ Priority: tool_input.{key} (nested, real Claude Code payload) →
112
+ top-level {key} (flat payloads) → regex fallback (malformed JSON).
113
+
114
+ Args:
115
+ raw: Raw hook payload (str or bytes).
116
+ key: Field name to extract.
117
+ Returns:
118
+ Field value as str, or "" when absent/empty.
119
+ """
120
+ text = raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else str(raw)
121
+ data = {}
122
+ try:
123
+ parsed = json.loads(text) if text.strip() else {}
124
+ if isinstance(parsed, dict):
125
+ data = parsed
126
+ except Exception:
127
+ data = {}
128
+ # Nested: real PreToolUse payloads keep tool args under tool_input
129
+ tool_input = data.get("tool_input")
130
+ if isinstance(tool_input, dict) and tool_input.get(key):
131
+ return str(tool_input[key])
132
+ # Flat: legacy payloads carry fields at top level
133
+ if data.get(key):
134
+ return str(data[key])
135
+ # Regex fallback for unparseable payloads
136
+ m = re.search(r'"%s"\s*:\s*"((?:[^"\\]|\\.)*)"' % re.escape(key), text)
137
+ return m.group(1) if m else ""
138
+
139
+
140
+ def sessionlog_local_enabled(project_root: Path = None) -> bool:
141
+ """Read sessionlog.local from flowcraft.yaml (PRD R1); default True.
142
+
143
+ Args:
144
+ project_root: Project root dir; None resolves via get_project_root().
145
+ Returns:
146
+ False only when flowcraft.yaml sets ``sessionlog.local: false``;
147
+ True otherwise (absent key / malformed config keeps legacy behaviour).
148
+ """
149
+ try:
150
+ root = Path(project_root) if project_root else get_project_root()
151
+ cfg = root / "flowcraft.yaml"
152
+ if cfg.is_file():
153
+ m = re.search(
154
+ r"^sessionlog:\s*$(?:(?!^[^\s]).)*?^ local:\s*(true|false)",
155
+ cfg.read_text(encoding="utf-8"),
156
+ re.M | re.S,
157
+ )
158
+ if m:
159
+ return m.group(1).lower() != "false"
160
+ except Exception:
161
+ pass
162
+ return True
@@ -1,125 +1,132 @@
1
- #!/usr/bin/env python3
2
- """PermissionRequest - generic security permission check (no phase limit)."""
3
- import json
4
- import os
5
- import re
6
- import sys
7
- from pathlib import Path
8
-
9
- from flowcraft_env import extract_nested
10
-
11
-
12
- def phase_number() -> int:
13
- state_file = Path(os.environ.get("CLAUDE_PROJECT_DIR") or ".") / ".claude" / "project-state.md"
14
- if not state_file.is_file():
15
- return 0
16
- try:
17
- content = state_file.read_text(encoding="utf-8")
18
- m = re.search(r"^current_phase:\s*P(\d+)", content, re.M)
19
- if m:
20
- return int(m.group(1))
21
- except Exception:
22
- pass
23
- return 0
24
-
25
-
26
- def main() -> int:
27
- raw = sys.stdin.read()
28
- phase_num = phase_number()
29
-
30
- try:
31
- data = json.loads(raw) if raw.strip() else {}
32
- if not isinstance(data, dict):
33
- return 0
34
- except Exception:
35
- return 0
36
-
37
- tool_name = data.get("tool_name") or ""
38
- if not tool_name:
39
- return 0
40
- # R5: unified nested/flat extraction; "command" may be empty, so chain keys
41
- tool_action = extract_nested(raw, "file_path") or extract_nested(raw, "command") or ""
42
-
43
- behavior = "allow"
44
- message = ""
45
-
46
- if tool_name in ("Write", "Edit"):
47
- m = re.search(r"\.([^.\\/]+)$", tool_action)
48
- ext = m.group(1).lower() if m else ""
49
- if ext in (
50
- "md", "txt", "json", "yaml", "yml", "toml", "ini",
51
- "cfg", "conf", "csv", "xml", "svg", "log",
52
- ):
53
- behavior = "allow"
54
- elif ext in ("html", "css"):
55
- if phase_num >= 1:
56
- behavior = "allow"
57
- else:
58
- behavior = "deny"
59
- message = f"阶段 P{phase_num} 不允许修改文件"
60
- else:
61
- if phase_num >= 2:
62
- behavior = "allow"
63
- else:
64
- behavior = "deny"
65
- message = f"阶段 P{phase_num} 不允许修改代码文件(P2 起可用,P1 仅允许原型 HTML/CSS)"
66
- elif tool_name == "Bash":
67
- action = tool_action
68
- if re.match(r"git\s+(status|diff|log|branch|stash)\b", action):
69
- behavior = "allow"
70
- elif re.search(r"rm\s+-rf|--force|reset\s+--hard", action):
71
- return 0 # dangerous commands go to the user
72
- elif re.match(r"git\s+(commit|push|tag|merge)\b", action):
73
- if phase_num >= 5:
74
- behavior = "allow"
75
- else:
76
- behavior = "deny"
77
- message = "Git 提交操作仅 P5 允许"
78
- elif re.match(
79
- r"(npm\s+test|npx\s+(jest|vitest|mocha)|yarn\s+test|pnpm\s+test|"
80
- r"pytest|go\s+test|cargo\s+test|mvn\s+test|mvnd\s+test|jest\s+|"
81
- r"vitest\s+|mocha\s+)",
82
- action,
83
- ):
84
- if phase_num >= 3:
85
- behavior = "allow"
86
- else:
87
- behavior = "deny"
88
- message = "测试命令仅 P3 起允许"
89
- elif re.match(r"npx\s+(eslint|tsc)|npm\s+run\s+(lint|build)", action):
90
- behavior = "allow"
91
- else:
92
- if phase_num >= 2:
93
- behavior = "allow"
94
- elif tool_name == "Chrome":
95
- if phase_num == 1 or phase_num >= 3:
96
- behavior = "allow"
97
- else:
98
- behavior = "deny"
99
- message = "Chrome 仅在 P1(原型展示)和 P3+(测试/审查)阶段允许"
100
- elif tool_name in ("Read", "Glob", "Grep", "WebSearch", "WebFetch"):
101
- behavior = "allow"
102
- else:
103
- return 0 # unknown tools are not intercepted
104
-
105
- if behavior == "deny" and message:
106
- out = {
107
- "hookSpecificOutput": {
108
- "hookEventName": "PermissionRequest",
109
- "decision": {"behavior": "deny", "message": message},
110
- }
111
- }
112
- print(json.dumps(out, ensure_ascii=False))
113
- elif behavior == "allow":
114
- out = {
115
- "hookSpecificOutput": {
116
- "hookEventName": "PermissionRequest",
117
- "decision": {"behavior": "allow"},
118
- }
119
- }
120
- print(json.dumps(out, ensure_ascii=False))
121
- return 0
122
-
123
-
124
- if __name__ == "__main__":
125
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """PermissionRequest - generic security permission check (no phase limit)."""
3
+ import json
4
+ import re
5
+ import sys
6
+
7
+ from flowcraft_env import extract_nested, get_project_root
8
+
9
+
10
+ def phase_number() -> int:
11
+ """Resolve the current SDLC phase (R4: root resolution aligned with other hooks).
12
+
13
+ Uses flowcraft_env.get_project_root() so sessions launched from a project
14
+ subdirectory resolve the same project-state.md as the rest of the hook
15
+ chain (CLAUDE_PROJECT_DIR → cwd walk-up → script-location fallback).
16
+
17
+ Returns:
18
+ Phase number, or 0 when no state file exists (P0 semantics).
19
+ """
20
+ state_file = get_project_root() / ".claude" / "project-state.md"
21
+ if not state_file.is_file():
22
+ return 0
23
+ try:
24
+ content = state_file.read_text(encoding="utf-8")
25
+ m = re.search(r"^current_phase:\s*P(\d+)", content, re.M)
26
+ if m:
27
+ return int(m.group(1))
28
+ except Exception:
29
+ pass
30
+ return 0
31
+
32
+
33
+ def main() -> int:
34
+ raw = sys.stdin.read()
35
+ phase_num = phase_number()
36
+
37
+ try:
38
+ data = json.loads(raw) if raw.strip() else {}
39
+ if not isinstance(data, dict):
40
+ return 0
41
+ except Exception:
42
+ return 0
43
+
44
+ tool_name = data.get("tool_name") or ""
45
+ if not tool_name:
46
+ return 0
47
+ # R5: unified nested/flat extraction; "command" may be empty, so chain keys
48
+ tool_action = extract_nested(raw, "file_path") or extract_nested(raw, "command") or ""
49
+
50
+ behavior = "allow"
51
+ message = ""
52
+
53
+ if tool_name in ("Write", "Edit"):
54
+ m = re.search(r"\.([^.\\/]+)$", tool_action)
55
+ ext = m.group(1).lower() if m else ""
56
+ if ext in (
57
+ "md", "txt", "json", "yaml", "yml", "toml", "ini",
58
+ "cfg", "conf", "csv", "xml", "svg", "log",
59
+ ):
60
+ behavior = "allow"
61
+ elif ext in ("html", "css"):
62
+ if phase_num >= 1:
63
+ behavior = "allow"
64
+ else:
65
+ behavior = "deny"
66
+ message = f"阶段 P{phase_num} 不允许修改文件"
67
+ else:
68
+ if phase_num >= 2:
69
+ behavior = "allow"
70
+ else:
71
+ behavior = "deny"
72
+ message = f"阶段 P{phase_num} 不允许修改代码文件(P2 起可用,P1 仅允许原型 HTML/CSS)"
73
+ elif tool_name == "Bash":
74
+ action = tool_action
75
+ if re.match(r"git\s+(status|diff|log|branch|stash)\b", action):
76
+ behavior = "allow"
77
+ elif re.search(r"rm\s+-rf|--force|reset\s+--hard", action):
78
+ return 0 # dangerous commands go to the user
79
+ elif re.match(r"git\s+(commit|push|tag|merge)\b", action):
80
+ if phase_num >= 5:
81
+ behavior = "allow"
82
+ else:
83
+ behavior = "deny"
84
+ message = "Git 提交操作仅 P5 允许"
85
+ elif re.match(
86
+ r"(npm\s+test|npx\s+(jest|vitest|mocha)|yarn\s+test|pnpm\s+test|"
87
+ r"pytest|go\s+test|cargo\s+test|mvn\s+test|mvnd\s+test|jest\s+|"
88
+ r"vitest\s+|mocha\s+)",
89
+ action,
90
+ ):
91
+ if phase_num >= 3:
92
+ behavior = "allow"
93
+ else:
94
+ behavior = "deny"
95
+ message = "测试命令仅 P3 起允许"
96
+ elif re.match(r"npx\s+(eslint|tsc)|npm\s+run\s+(lint|build)", action):
97
+ behavior = "allow"
98
+ else:
99
+ if phase_num >= 2:
100
+ behavior = "allow"
101
+ elif tool_name == "Chrome":
102
+ if phase_num == 1 or phase_num >= 3:
103
+ behavior = "allow"
104
+ else:
105
+ behavior = "deny"
106
+ message = "Chrome 仅在 P1(原型展示)和 P3+(测试/审查)阶段允许"
107
+ elif tool_name in ("Read", "Glob", "Grep", "WebSearch", "WebFetch"):
108
+ behavior = "allow"
109
+ else:
110
+ return 0 # unknown tools are not intercepted
111
+
112
+ if behavior == "deny" and message:
113
+ out = {
114
+ "hookSpecificOutput": {
115
+ "hookEventName": "PermissionRequest",
116
+ "decision": {"behavior": "deny", "message": message},
117
+ }
118
+ }
119
+ print(json.dumps(out, ensure_ascii=False))
120
+ elif behavior == "allow":
121
+ out = {
122
+ "hookSpecificOutput": {
123
+ "hookEventName": "PermissionRequest",
124
+ "decision": {"behavior": "allow"},
125
+ }
126
+ }
127
+ print(json.dumps(out, ensure_ascii=False))
128
+ return 0
129
+
130
+
131
+ if __name__ == "__main__":
132
+ sys.exit(main())