@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,63 +1,63 @@
1
- #!/usr/bin/env python3
2
- """statusline - show the current task status."""
3
- import json
4
- import os
5
- import re
6
- import sys
7
- from pathlib import Path
8
-
9
- from task_manager import get_task_state_path, resolve_task_id
10
-
11
- import flowcraft_env # noqa: F401 — UTF-8 stdio 双保险(R2)
12
-
13
-
14
- def main() -> int:
15
- """Print the phase, task description and active task id for the status line.
16
-
17
- Returns:
18
- Process exit code.
19
- """
20
- raw = sys.stdin.read()
21
- project_dir = os.environ.get("CLAUDE_PROJECT_DIR") or ""
22
- if not project_dir:
23
- try:
24
- data = json.loads(raw) if raw.strip() else {}
25
- if isinstance(data, dict):
26
- workspace = data.get("workspace", {})
27
- if isinstance(workspace, dict):
28
- project_dir = workspace.get("project_dir") or data.get("cwd") or ""
29
- else:
30
- project_dir = data.get("cwd") or ""
31
- except Exception:
32
- m = re.search(r'"cwd"\s*:\s*"([^"]*)"', raw)
33
- if m:
34
- project_dir = m.group(1)
35
- if project_dir:
36
- # Git Bash path conversion: /d/ -> D:/
37
- project_dir = re.sub(r"^/[dD]/", "D:/", project_dir).rstrip("/")
38
-
39
- project_root = Path(project_dir)
40
- state_file = get_task_state_path(project_root)
41
- if not state_file.is_file():
42
- return 0
43
- content = state_file.read_text(encoding="utf-8")
44
-
45
- phase = ""
46
- m = re.search(r"^current_phase:\s*([P0-9.]+)", content, re.M)
47
- if m:
48
- phase = m.group(1)
49
- task = ""
50
- m = re.search(r'^task_description:\s*"([^"]*)"', content, re.M)
51
- if m:
52
- task = m.group(1)
53
-
54
- active = resolve_task_id(project_root) or "-"
55
- if not task:
56
- print(f"[{phase}] 等待新任务 @{active}")
57
- else:
58
- print(f"[{phase}] {task[:40]} @{active}")
59
- return 0
60
-
61
-
62
- if __name__ == "__main__":
63
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """statusline - show the current task status."""
3
+ import json
4
+ import os
5
+ import re
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from task_manager import get_task_state_path, resolve_task_id
10
+
11
+ import flowcraft_env # noqa: F401 — UTF-8 stdio 双保险(R2)
12
+
13
+
14
+ def main() -> int:
15
+ """Print the phase, task description and active task id for the status line.
16
+
17
+ Returns:
18
+ Process exit code.
19
+ """
20
+ raw = sys.stdin.read()
21
+ project_dir = os.environ.get("CLAUDE_PROJECT_DIR") or ""
22
+ if not project_dir:
23
+ try:
24
+ data = json.loads(raw) if raw.strip() else {}
25
+ if isinstance(data, dict):
26
+ workspace = data.get("workspace", {})
27
+ if isinstance(workspace, dict):
28
+ project_dir = workspace.get("project_dir") or data.get("cwd") or ""
29
+ else:
30
+ project_dir = data.get("cwd") or ""
31
+ except Exception:
32
+ m = re.search(r'"cwd"\s*:\s*"([^"]*)"', raw)
33
+ if m:
34
+ project_dir = m.group(1)
35
+ if project_dir:
36
+ # Git Bash path conversion: /d/ -> D:/
37
+ project_dir = re.sub(r"^/[dD]/", "D:/", project_dir).rstrip("/")
38
+
39
+ project_root = Path(project_dir)
40
+ state_file = get_task_state_path(project_root)
41
+ if not state_file.is_file():
42
+ return 0
43
+ content = state_file.read_text(encoding="utf-8")
44
+
45
+ phase = ""
46
+ m = re.search(r"^current_phase:\s*([P0-9.]+)", content, re.M)
47
+ if m:
48
+ phase = m.group(1)
49
+ task = ""
50
+ m = re.search(r'^task_description:\s*"([^"]*)"', content, re.M)
51
+ if m:
52
+ task = m.group(1)
53
+
54
+ active = resolve_task_id(project_root) or "-"
55
+ if not task:
56
+ print(f"[{phase}] 等待新任务 @{active}")
57
+ else:
58
+ print(f"[{phase}] {task[:40]} @{active}")
59
+ return 0
60
+
61
+
62
+ if __name__ == "__main__":
63
+ sys.exit(main())
@@ -1,171 +1,186 @@
1
- #!/usr/bin/env python3
2
- """Stop - record the AI reply to session_log.json + lightweight self-check."""
3
- import json
4
- import os
5
- import re
6
- import subprocess
7
- import sys
8
- import tempfile
9
- import time
10
- from pathlib import Path
11
-
12
- import flowcraft_env # noqa: F401 — UTF-8 stdio 双保险(R2)
13
-
14
-
15
- def _sanitize(text: str) -> str:
16
- """Strip UTF-16 surrogates that json.loads may preserve on Windows."""
17
- return text.encode("utf-8", errors="surrogatepass").decode("utf-8", errors="replace")
18
-
19
-
20
- # 危险操作关键词(R2):命中则决策点不启用超时
21
- DANGER_KEYWORDS = ("删除", "推送", "合并", "rebase", "reset", "force", "回退")
22
-
23
-
24
- def _read_timeout(project_dir: Path) -> int:
25
- """Read decision_timeout from flowcraft.yaml; default 120 seconds (R3)."""
26
- cfg = Path(project_dir) / "flowcraft.yaml"
27
- if cfg.is_file():
28
- m = re.search(r"^decision_timeout:\s*(\d+)", cfg.read_text(encoding="utf-8"), re.M)
29
- if m:
30
- return int(m.group(1))
31
- return 120
32
-
33
-
34
- def _parse_decision_card(text: str) -> tuple:
35
- """Extract (point, recommended) from a decision-card reply (R4).
36
-
37
- Args:
38
- text: The assistant's reply text.
39
- Returns:
40
- Tuple (point, recommended); both empty when no card is detected.
41
- """
42
- if "🧭" not in text or "请选择" not in text:
43
- return "", ""
44
- m = re.search(r"🧭\s*决策点[^\n||]*[||]\s*\*{0,2}([^*\n]+)\*{0,2}", text)
45
- point = m.group(1).strip() if m else "决策点"
46
- m = re.search(r"✅[^\n]*?·\s*([A-Z])\s*[..、]", text)
47
- return point, (m.group(1) if m else "")
48
-
49
-
50
- def _update_decision_marker(project_dir: Path, ai_message: str) -> None:
51
- """Maintain the pending-decision marker (R4/R5).
52
-
53
- Writes .claude/decision-pending.json on a decision-card stop;
54
- deletes it on any other stop (decision resolved).
55
-
56
- Args:
57
- project_dir: Project root directory.
58
- ai_message: The assistant's reply text for this stop.
59
- """
60
- marker = project_dir / ".claude" / "decision-pending.json"
61
- point, rec = _parse_decision_card(ai_message)
62
- if point and rec and not any(k in point for k in DANGER_KEYWORDS):
63
- timeout = _read_timeout(project_dir)
64
- data = {
65
- "point": point,
66
- "recommended": rec,
67
- "deadline": int(time.time()) + timeout,
68
- "timeout": timeout,
69
- "session_id": os.environ.get("FLOWCRAFT_SESSION_ID", ""),
70
- }
71
- marker.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
72
- elif marker.is_file():
73
- try:
74
- marker.unlink()
75
- except OSError:
76
- pass
77
-
78
-
79
- def main() -> int:
80
- raw = sys.stdin.read()
81
-
82
- # Prevent infinite loops when the stop hook itself is active
83
- if '"stop_hook_active"' in raw and "true" in raw:
84
- return 0
85
-
86
- project_dir = os.environ.get("CLAUDE_PROJECT_DIR") or "."
87
- state_file = Path(project_dir) / ".claude" / "project-state.md"
88
- session_log = Path(project_dir) / ".claude" / "session_log.json"
89
- log_script = Path(project_dir) / ".claude" / "hooks" / "log_session.py"
90
-
91
- if not state_file.is_file():
92
- return 0
93
-
94
- content = state_file.read_text(encoding="utf-8")
95
-
96
- def field(pattern):
97
- m = re.search(pattern, content, re.M)
98
- return m.group(1).strip().strip('"') if m else ""
99
-
100
- task = field(r'^task_description:\s*(.*)$')
101
- key_ctx = field(r'^key_context:\s*(.*)$')
102
- phase = field(r'^current_phase:\s*(.*)$')
103
- files_count = 0
104
- in_files = False
105
- for line in content.split("\n"):
106
- if line.startswith("modified_files:"):
107
- in_files = True
108
- continue
109
- if in_files:
110
- if line and not line[0].isspace():
111
- break
112
- if re.match(r"^\s*-\s+", line):
113
- files_count += 1
114
-
115
- # Record the AI reply to session_log.json (always when present)
116
- if raw.strip():
117
- ai_message = ""
118
- try:
119
- data = json.loads(raw)
120
- if isinstance(data, dict):
121
- ai_message = data.get("last_assistant_message") or ""
122
- except Exception:
123
- pass
124
- ai_message = _sanitize(ai_message)
125
- if ai_message:
126
- git_user = "unknown"
127
- try:
128
- r = subprocess.run(
129
- ["git", "config", "user.name"],
130
- capture_output=True,
131
- text=True,
132
- timeout=3,
133
- )
134
- if r.returncode == 0 and r.stdout.strip():
135
- git_user = r.stdout.strip()
136
- except Exception:
137
- pass
138
- fd, temp_input = tempfile.mkstemp()
139
- try:
140
- with os.fdopen(fd, "w", encoding="utf-8") as tf:
141
- tf.write(ai_message)
142
- env = dict(os.environ)
143
- env["SESSION_LOG"] = str(session_log)
144
- env["GIT_USER"] = git_user
145
- env["TEMP_INPUT"] = temp_input
146
- subprocess.run([sys.executable, str(log_script), "assistant"], env=env)
147
- finally:
148
- try:
149
- os.unlink(temp_input)
150
- except OSError:
151
- pass
152
-
153
- # R4/R5: 待决决策标记维护(决策卡写入,其余回合清除)
154
- _update_decision_marker(Path(project_dir), ai_message)
155
-
156
- # Self-check logic (only when a task exists)
157
- if task:
158
- checks = ""
159
- if not key_ctx:
160
- checks = "key_context 为空,请更新 project-state.md。"
161
- if files_count > 0:
162
- checks += f" 已修改 {files_count} 个文件。"
163
- if not checks:
164
- return 0
165
- context = f"[自检] 任务={task}。{checks}"
166
- print(json.dumps({"stopReason": context}, ensure_ascii=False))
167
- return 0
168
-
169
-
170
- if __name__ == "__main__":
171
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """Stop - record the AI reply to session_log.json + lightweight self-check."""
3
+ import json
4
+ import os
5
+ import re
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import time
10
+ from pathlib import Path
11
+
12
+ import flowcraft_env # noqa: F401 — UTF-8 stdio 双保险(R2)
13
+ from flowcraft_env import sessionlog_local_enabled # R1: 本地日志开关
14
+
15
+
16
+ def _sanitize(text: str) -> str:
17
+ """Strip UTF-16 surrogates that json.loads may preserve on Windows."""
18
+ return text.encode("utf-8", errors="surrogatepass").decode("utf-8", errors="replace")
19
+
20
+
21
+ # 危险操作关键词(R2):命中则决策点不启用超时
22
+ DANGER_KEYWORDS = ("删除", "推送", "合并", "rebase", "reset", "force", "回退")
23
+
24
+
25
+ def _read_timeout(project_dir: Path) -> int:
26
+ """Read decision_timeout from flowcraft.yaml; default 120 seconds (R3)."""
27
+ cfg = Path(project_dir) / "flowcraft.yaml"
28
+ if cfg.is_file():
29
+ m = re.search(r"^decision_timeout:\s*(\d+)", cfg.read_text(encoding="utf-8"), re.M)
30
+ if m:
31
+ return int(m.group(1))
32
+ return 120
33
+
34
+
35
+ def _parse_decision_card(text: str) -> tuple:
36
+ """Extract (point, recommended) from a decision-card reply (R4).
37
+
38
+ Args:
39
+ text: The assistant's reply text.
40
+ Returns:
41
+ Tuple (point, recommended); both empty when no card is detected.
42
+ """
43
+ if "🧭" not in text or "请选择" not in text:
44
+ return "", ""
45
+ m = re.search(r"🧭\s*决策点[^\n||]*[||]\s*\*{0,2}([^*\n]+)\*{0,2}", text)
46
+ point = m.group(1).strip() if m else "决策点"
47
+ m = re.search(r"✅[^\n]*?·\s*([A-Z])\s*[..、]", text)
48
+ return point, (m.group(1) if m else "")
49
+
50
+
51
+ def _update_decision_marker(project_dir: Path, ai_message: str) -> None:
52
+ """Maintain the pending-decision marker (R4/R5).
53
+
54
+ Writes .claude/decision-pending.json on a decision-card stop;
55
+ deletes it on any other stop (decision resolved).
56
+
57
+ Args:
58
+ project_dir: Project root directory.
59
+ ai_message: The assistant's reply text for this stop.
60
+ """
61
+ marker = project_dir / ".claude" / "decision-pending.json"
62
+ point, rec = _parse_decision_card(ai_message)
63
+ if point and rec and not any(k in point for k in DANGER_KEYWORDS):
64
+ timeout = _read_timeout(project_dir)
65
+ data = {
66
+ "point": point,
67
+ "recommended": rec,
68
+ "deadline": int(time.time()) + timeout,
69
+ "timeout": timeout,
70
+ "session_id": os.environ.get("FLOWCRAFT_SESSION_ID", ""),
71
+ }
72
+ marker.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
73
+ elif marker.is_file():
74
+ try:
75
+ marker.unlink()
76
+ except OSError:
77
+ pass
78
+
79
+
80
+ def _write_session_log(project_dir: Path, session_log: Path, log_script: Path, ai_message: str) -> None:
81
+ """Write the assistant message to the local session log via log_session.py.
82
+
83
+ Args:
84
+ project_dir: Project root directory.
85
+ session_log: Path to session_log.json.
86
+ log_script: Path to the log_session.py hook script.
87
+ ai_message: Sanitized assistant message text.
88
+ """
89
+ git_user = "unknown"
90
+ try:
91
+ r = subprocess.run(
92
+ ["git", "config", "user.name"],
93
+ capture_output=True,
94
+ text=True,
95
+ timeout=3,
96
+ )
97
+ if r.returncode == 0 and r.stdout.strip():
98
+ git_user = r.stdout.strip()
99
+ except Exception:
100
+ pass
101
+ fd, temp_input = tempfile.mkstemp()
102
+ try:
103
+ with os.fdopen(fd, "w", encoding="utf-8") as tf:
104
+ tf.write(ai_message)
105
+ env = dict(os.environ)
106
+ env["SESSION_LOG"] = str(session_log)
107
+ env["GIT_USER"] = git_user
108
+ env["TEMP_INPUT"] = temp_input
109
+ subprocess.run([sys.executable, str(log_script), "assistant"], env=env)
110
+ finally:
111
+ try:
112
+ os.unlink(temp_input)
113
+ except OSError:
114
+ pass
115
+
116
+
117
+ def main() -> int:
118
+ raw = sys.stdin.read()
119
+
120
+ # Prevent infinite loops when the stop hook itself is active
121
+ if '"stop_hook_active"' in raw and "true" in raw:
122
+ return 0
123
+
124
+ project_dir = os.environ.get("CLAUDE_PROJECT_DIR") or "."
125
+ state_file = Path(project_dir) / ".claude" / "project-state.md"
126
+ session_log = Path(project_dir) / ".claude" / "session_log.json"
127
+ log_script = Path(project_dir) / ".claude" / "hooks" / "log_session.py"
128
+
129
+ if not state_file.is_file():
130
+ return 0
131
+
132
+ content = state_file.read_text(encoding="utf-8")
133
+
134
+ def field(pattern):
135
+ m = re.search(pattern, content, re.M)
136
+ return m.group(1).strip().strip('"') if m else ""
137
+
138
+ task = field(r'^task_description:\s*(.*)$')
139
+ key_ctx = field(r'^key_context:\s*(.*)$')
140
+ phase = field(r'^current_phase:\s*(.*)$')
141
+ files_count = 0
142
+ in_files = False
143
+ for line in content.split("\n"):
144
+ if line.startswith("modified_files:"):
145
+ in_files = True
146
+ continue
147
+ if in_files:
148
+ if line and not line[0].isspace():
149
+ break
150
+ if re.match(r"^\s*-\s+", line):
151
+ files_count += 1
152
+
153
+ # Record the AI reply to session_log.json (always when present)
154
+ if raw.strip():
155
+ ai_message = ""
156
+ try:
157
+ data = json.loads(raw)
158
+ if isinstance(data, dict):
159
+ ai_message = data.get("last_assistant_message") or ""
160
+ except Exception:
161
+ pass
162
+ ai_message = _sanitize(ai_message)
163
+ if ai_message:
164
+ # R1: 本地日志开关——sessionlog.local=false 时跳过写入(默认开)
165
+ if sessionlog_local_enabled(Path(project_dir)):
166
+ _write_session_log(Path(project_dir), session_log, log_script, ai_message)
167
+
168
+ # R4/R5: 待决决策标记维护(决策卡写入,其余回合清除)
169
+ _update_decision_marker(Path(project_dir), ai_message)
170
+
171
+ # Self-check logic (only when a task exists)
172
+ if task:
173
+ checks = ""
174
+ if not key_ctx:
175
+ checks = "key_context 为空,请更新 project-state.md。"
176
+ if files_count > 0:
177
+ checks += f" 已修改 {files_count} 个文件。"
178
+ if not checks:
179
+ return 0
180
+ context = f"[自检] 任务={task}。{checks}"
181
+ print(json.dumps({"stopReason": context}, ensure_ascii=False))
182
+ return 0
183
+
184
+
185
+ if __name__ == "__main__":
186
+ sys.exit(main())
@@ -1,50 +1,50 @@
1
- #!/usr/bin/env python3
2
- """SubagentStart - inject context when a sub-agent starts."""
3
- import json
4
- import os
5
- import re
6
- import sys
7
- from pathlib import Path
8
-
9
- import flowcraft_env # noqa: F401 — UTF-8 stdio 双保险(R2)
10
-
11
-
12
- def _clean(value: str) -> str:
13
- value = re.sub(r"\s*#.*$", "", value)
14
- return value.strip().strip('"')
15
-
16
-
17
- def main() -> int:
18
- state_file = Path(os.environ.get("CLAUDE_PROJECT_DIR") or ".") / ".claude" / "project-state.md"
19
- if not state_file.is_file():
20
- return 0
21
- content = state_file.read_text(encoding="utf-8")
22
-
23
- task = ""
24
- m = re.search(r"^task_description:\s*(.*)$", content, re.M)
25
- if m:
26
- task = _clean(m.group(1))
27
- kc = ""
28
- m = re.search(r"^key_context:\s*(.*)$", content, re.M)
29
- if m:
30
- kc = _clean(m.group(1))
31
-
32
- if not task:
33
- return 0
34
-
35
- context = (
36
- f"[子 Agent] 任务={task}。上下文={kc}。编码规范:函数≤50行、嵌套≤3层、"
37
- "命名遵循语言约定。完成后报告修改的文件列表。"
38
- )
39
- out = {
40
- "hookSpecificOutput": {
41
- "hookEventName": "SubagentStart",
42
- "additionalContext": context,
43
- }
44
- }
45
- print(json.dumps(out, ensure_ascii=False))
46
- return 0
47
-
48
-
49
- if __name__ == "__main__":
50
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """SubagentStart - inject context when a sub-agent starts."""
3
+ import json
4
+ import os
5
+ import re
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import flowcraft_env # noqa: F401 — UTF-8 stdio 双保险(R2)
10
+
11
+
12
+ def _clean(value: str) -> str:
13
+ value = re.sub(r"\s*#.*$", "", value)
14
+ return value.strip().strip('"')
15
+
16
+
17
+ def main() -> int:
18
+ state_file = Path(os.environ.get("CLAUDE_PROJECT_DIR") or ".") / ".claude" / "project-state.md"
19
+ if not state_file.is_file():
20
+ return 0
21
+ content = state_file.read_text(encoding="utf-8")
22
+
23
+ task = ""
24
+ m = re.search(r"^task_description:\s*(.*)$", content, re.M)
25
+ if m:
26
+ task = _clean(m.group(1))
27
+ kc = ""
28
+ m = re.search(r"^key_context:\s*(.*)$", content, re.M)
29
+ if m:
30
+ kc = _clean(m.group(1))
31
+
32
+ if not task:
33
+ return 0
34
+
35
+ context = (
36
+ f"[子 Agent] 任务={task}。上下文={kc}。编码规范:函数≤50行、嵌套≤3层、"
37
+ "命名遵循语言约定。完成后报告修改的文件列表。"
38
+ )
39
+ out = {
40
+ "hookSpecificOutput": {
41
+ "hookEventName": "SubagentStart",
42
+ "additionalContext": context,
43
+ }
44
+ }
45
+ print(json.dumps(out, ensure_ascii=False))
46
+ return 0
47
+
48
+
49
+ if __name__ == "__main__":
50
+ sys.exit(main())