@leocm/flowcraft 2.0.0 → 2.2.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.
- package/README.md +33 -12
- package/bin/cli.js +8 -2
- package/lib/args.js +7 -3
- package/lib/config.js +4 -4
- package/lib/wizard.js +3 -3
- package/package.json +1 -1
- package/setup/.claude/hooks/check-phase-advancement.py +1 -1
- package/setup/.claude/hooks/check-phase-write.py +5 -2
- package/setup/.claude/hooks/dispatch.py +3 -0
- package/setup/.claude/hooks/flowcraft_env.py +63 -0
- package/setup/.claude/hooks/log_session.py +2 -0
- package/setup/.claude/hooks/permission-request.py +11 -4
- package/setup/.claude/hooks/post-tool-failure.py +2 -0
- package/setup/.claude/hooks/pre-compact.py +2 -0
- package/setup/.claude/hooks/review-runner.py +2 -0
- package/setup/.claude/hooks/session-end.py +3 -1
- package/setup/.claude/hooks/setup-keys.py +2 -0
- package/setup/.claude/hooks/statusline.py +2 -0
- package/setup/.claude/hooks/stop-check.py +43 -26
- package/setup/.claude/hooks/subagent-start.py +2 -0
- package/setup/.claude/hooks/subagent-stop.py +2 -0
- package/setup/.claude/hooks/task-completed.py +2 -0
- package/setup/.claude/hooks/user-prompt-submit.py +6 -0
- package/setup/.claude/settings.json +0 -4
- package/setup/.codex/hooks/log_session.py +7 -0
- package/setup/.codex/hooks/review-runner.py +7 -0
- package/setup/.codex/hooks/sdlc-codex-hook.cjs +22 -3
- package/setup/.codex/hooks/setup-keys.py +7 -0
- package/setup/tests/test_hook_guards.py +17 -1
- package/setup/tests/test_sessionlog_switch.py +199 -0
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
#
|
|
1
|
+
# FLowCraft框架
|
|
2
2
|
|
|
3
3
|
> Claude Code 开发流程框架 - 标准化需求→设计→编码→测试→审查→交付
|
|
4
4
|
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
|
|
20
20
|
## 项目简介
|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
FLowCraft框架是一套基于 Claude Code 的智能开发流程管理系统。它通过自动化 hooks、标准化流程和 AI 辅助技能,帮助开发者实现从需求分析到交付的全流程规范化管理。
|
|
23
23
|
|
|
24
24
|
### 核心价值
|
|
25
25
|
|
|
@@ -104,17 +104,28 @@ SDLC(Software Development Life Cycle)框架是一套基于 Claude Code 的
|
|
|
104
104
|
### 方式零:npm 包安装(跨平台,无 bash 依赖)
|
|
105
105
|
|
|
106
106
|
```bash
|
|
107
|
-
# 打包(仓库内执行,产出 leocm-flowcraft-2.
|
|
107
|
+
# 打包(仓库内执行,产出 leocm-flowcraft-2.2.0.tgz)
|
|
108
108
|
npm pack ./flowcraft
|
|
109
109
|
|
|
110
110
|
# 全局安装后提供 flowcraft 命令
|
|
111
|
-
npm i -g leocm-flowcraft-2.
|
|
111
|
+
npm i -g leocm-flowcraft-2.2.0.tgz
|
|
112
112
|
|
|
113
113
|
# 常用命令(与 install.sh 参数面等价)
|
|
114
114
|
flowcraft install --quick # 项目安装
|
|
115
115
|
flowcraft install --global # 用户级全局安装
|
|
116
116
|
flowcraft init # 当前目录最小化初始化
|
|
117
117
|
flowcraft install --preset backend # 应用预设
|
|
118
|
+
|
|
119
|
+
# Sessionlog 分发(默认关闭,明确启用才分发)
|
|
120
|
+
flowcraft install --sessionlog # 分发默认 http://127.0.0.1:8181/api/logs
|
|
121
|
+
flowcraft install --sessionlog http://host:8181/api/logs # 分发指定地址
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
本地会话日志开关(`flowcraft.yaml`,默认开;`false` 时停止写入 `.claude/session_log.json`):
|
|
125
|
+
|
|
126
|
+
```yaml
|
|
127
|
+
sessionlog:
|
|
128
|
+
local: false
|
|
118
129
|
```
|
|
119
130
|
|
|
120
131
|
### 方式一:自动安装(推荐)
|
|
@@ -126,7 +137,7 @@ flowcraft install --preset backend # 应用预设
|
|
|
126
137
|
|
|
127
138
|
### claude (推荐)
|
|
128
139
|
```bash
|
|
129
|
-
安装
|
|
140
|
+
安装 FLowCraft install.sh
|
|
130
141
|
|
|
131
142
|
chmod +x ~/.flowcraft/hooks/*.py
|
|
132
143
|
|
|
@@ -171,7 +182,7 @@ cd your-project
|
|
|
171
182
|
|
|
172
183
|
### 方式二:通过 Claude Code 重新安装
|
|
173
184
|
|
|
174
|
-
适用于已安装过
|
|
185
|
+
适用于已安装过 FLowCraft 框架的项目,用于升级或修复。
|
|
175
186
|
|
|
176
187
|
#### 前置条件
|
|
177
188
|
|
|
@@ -182,7 +193,7 @@ cd your-project
|
|
|
182
193
|
在 Claude Code 中执行:
|
|
183
194
|
|
|
184
195
|
```
|
|
185
|
-
重新安装
|
|
196
|
+
重新安装FLowCraft
|
|
186
197
|
```
|
|
187
198
|
|
|
188
199
|
#### 说明
|
|
@@ -258,7 +269,7 @@ Claude 会自动:
|
|
|
258
269
|
|
|
259
270
|
```
|
|
260
271
|
┌─────────────────────────────────────────────────────────────┐
|
|
261
|
-
│
|
|
272
|
+
│ FLowCraft 工作流程 │
|
|
262
273
|
├─────────────────────────────────────────────────────────────┤
|
|
263
274
|
│ │
|
|
264
275
|
│ P0 等待任务 │
|
|
@@ -637,7 +648,7 @@ completed_tasks:
|
|
|
637
648
|
|
|
638
649
|
```
|
|
639
650
|
your-project/
|
|
640
|
-
├── CLAUDE.md #
|
|
651
|
+
├── CLAUDE.md # FLowCraft 流程定义(核心)
|
|
641
652
|
└── .claude/
|
|
642
653
|
├── project-state.md # 项目状态(活文档)
|
|
643
654
|
├── prd.md # PRD 文档
|
|
@@ -666,7 +677,7 @@ your-project/
|
|
|
666
677
|
│ ├── gitnexus/
|
|
667
678
|
│ ├── playwright/
|
|
668
679
|
│ └── ...
|
|
669
|
-
├──
|
|
680
|
+
├── FLowCraft/ # FLowCraft 规则文档
|
|
670
681
|
│ └── rules/
|
|
671
682
|
│ ├── 01-lifecycle-phases.md
|
|
672
683
|
│ ├── 02-coding-standards.md
|
|
@@ -694,7 +705,7 @@ your-project/
|
|
|
694
705
|
### 核心文件说明
|
|
695
706
|
|
|
696
707
|
#### `CLAUDE.md`
|
|
697
|
-
|
|
708
|
+
FLowCraft 流程定义文件,包含:
|
|
698
709
|
- 启动指令
|
|
699
710
|
- 核心规则
|
|
700
711
|
- 阶段流程
|
|
@@ -810,7 +821,7 @@ Hooks 在 `settings.json` 中配置,支持以下事件:
|
|
|
810
821
|
## 技术支持
|
|
811
822
|
|
|
812
823
|
- **问题反馈**:提交 GitHub Issue
|
|
813
|
-
- **文档更新**:查看 `.claude/
|
|
824
|
+
- **文档更新**:查看 `.claude/FLowCraft/rules/` 目录
|
|
814
825
|
- **技能说明**:查看 `.claude/skills/` 目录
|
|
815
826
|
|
|
816
827
|
---
|
|
@@ -823,6 +834,16 @@ MIT License
|
|
|
823
834
|
|
|
824
835
|
## 更新日志
|
|
825
836
|
|
|
837
|
+
### v2.2.0 (2026-10-15)
|
|
838
|
+
- 本地会话日志开关:`flowcraft.yaml` 新增 `sessionlog.local`(默认开;false 停止写入 `.claude/session_log.json`)
|
|
839
|
+
- 修复重启/新建会话后首消息卡顿:settings.json 模板不再默认启用未安装插件(enabledPlugins 移除)
|
|
840
|
+
- 守卫根解析对齐:permission-request 子目录会话不再误判 P0 拦截代码写入
|
|
841
|
+
|
|
842
|
+
### v2.1.0 (2026-10-12)
|
|
843
|
+
- Sessionlog 分发改为明确启用:`--sessionlog [url]`(默认不分发;裸旗标分发 `http://127.0.0.1:8181/api/logs`);默认地址 `192.168.2.99`→`127.0.0.1`
|
|
844
|
+
- 守卫修复:`.claude/` 拦截锚定 project_root,用户级 `~/.claude/**`(如计划草稿)放行;白名单补 `plans/`
|
|
845
|
+
- 钩子输出 UTF-8 双保险:消除 Windows GBK 乱码(进程内 reconfigure + dispatch 子进程 UTF-8)
|
|
846
|
+
|
|
826
847
|
### v2.0.0 (2026-09-24)
|
|
827
848
|
- `--global` 补全用户级安装:skills/commands 分发(Claude + Codex 全局兜底)、Codex 全局 hooks 注册(`~/.codex/hooks.json` 绝对路径)、config.toml `[features]` 特性开关合并
|
|
828
849
|
- 项目级安装不再复制 hooks/skills/commands(仅建空目录,统一由用户级提供)
|
package/bin/cli.js
CHANGED
|
@@ -59,9 +59,15 @@ async function runInstall(opts) {
|
|
|
59
59
|
addPathToHooks(target);
|
|
60
60
|
const fixCount = fixLineEndings(target);
|
|
61
61
|
const replaceCount = replacePythonCommands(target, py);
|
|
62
|
-
|
|
62
|
+
// R1/R2:仅 --sessionlog 明确启用才分发(null=未给不分发,''=裸旗标用默认URL)
|
|
63
|
+
let urlCount = 0;
|
|
64
|
+
let sessionlogUrl = null;
|
|
65
|
+
if (opts.sessionlog !== null) {
|
|
66
|
+
sessionlogUrl = opts.sessionlog || SESSIONLOG_URL;
|
|
67
|
+
urlCount = replaceSessionlogUrl(sessionlogUrl, target, path.join(PKG_ROOT, 'setup', '.claude'));
|
|
68
|
+
}
|
|
63
69
|
writeVersionFile(target, process.cwd(), presetMode || 'default');
|
|
64
|
-
showStats({ copyCount, fixCount, replaceCount, urlCount }, process.cwd(),
|
|
70
|
+
showStats({ copyCount, fixCount, replaceCount, urlCount }, process.cwd(), sessionlogUrl);
|
|
65
71
|
showNextSteps();
|
|
66
72
|
}
|
|
67
73
|
|
package/lib/args.js
CHANGED
|
@@ -6,10 +6,10 @@
|
|
|
6
6
|
/**
|
|
7
7
|
* 解析命令行参数
|
|
8
8
|
* @param {string[]} argv 进程参数(不含 node 与脚本路径)
|
|
9
|
-
* @returns {{mode:string,presetArg:string|null,presetMode:string,quick:boolean,interactive:boolean,unknown:string[]}} 解析结果
|
|
9
|
+
* @returns {{mode:string,presetArg:string|null,presetMode:string,quick:boolean,interactive:boolean,sessionlog:string|null,unknown:string[]}} 解析结果
|
|
10
10
|
*/
|
|
11
11
|
function parseArgs(argv) {
|
|
12
|
-
const out = { mode: 'install', presetArg: null, presetMode: '', quick: false, interactive: false, unknown: [] };
|
|
12
|
+
const out = { mode: 'install', presetArg: null, presetMode: '', quick: false, interactive: false, sessionlog: null, unknown: [] };
|
|
13
13
|
const rest = [...argv];
|
|
14
14
|
while (rest.length > 0) {
|
|
15
15
|
const a = rest.shift();
|
|
@@ -20,7 +20,11 @@ function parseArgs(argv) {
|
|
|
20
20
|
out.quick = true;
|
|
21
21
|
out.presetMode = 'default';
|
|
22
22
|
} else if (a === '--interactive') out.interactive = true;
|
|
23
|
-
else if (a === '--
|
|
23
|
+
else if (a === '--sessionlog') {
|
|
24
|
+
// 三态:null=未给(不分发)、''=裸旗标(默认URL)、字符串=指定URL;仅消费 http(s) 参数防吞旗标
|
|
25
|
+
const nxt = rest[0];
|
|
26
|
+
out.sessionlog = nxt && /^https?:\/\//.test(nxt) ? rest.shift() : '';
|
|
27
|
+
} else if (a === '--preset') {
|
|
24
28
|
out.presetArg = rest.shift() || null;
|
|
25
29
|
if (!out.presetArg) out.unknown.push('--preset(缺参数)');
|
|
26
30
|
else out.presetMode = out.presetArg.replace(/\.yaml$/, '');
|
package/lib/config.js
CHANGED
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
*/
|
|
4
4
|
'use strict';
|
|
5
5
|
|
|
6
|
-
/** 默认 sessionlog MCP
|
|
7
|
-
const SESSIONLOG_URL = 'http://
|
|
6
|
+
/** 默认 sessionlog MCP 地址(仅 --sessionlog 裸旗标启用分发时使用;默认不分发) */
|
|
7
|
+
const SESSIONLOG_URL = 'http://127.0.0.1:8181/api/logs';
|
|
8
8
|
|
|
9
|
-
/** 框架版本(与
|
|
10
|
-
const FRAMEWORK_VERSION = '2.
|
|
9
|
+
/** 框架版本(与 package.json version / README 一致,发版时两处同步) */
|
|
10
|
+
const FRAMEWORK_VERSION = '2.2.0';
|
|
11
11
|
|
|
12
12
|
/** 需要 PATH 注入的 hook 文件清单(对齐 install.sh add_path_to_hooks) */
|
|
13
13
|
const HOOK_FILES = [
|
package/lib/wizard.js
CHANGED
|
@@ -96,10 +96,10 @@ async function askConfig(rl, pkgRoot) {
|
|
|
96
96
|
}
|
|
97
97
|
|
|
98
98
|
/**
|
|
99
|
-
* 显示安装统计(对齐 show_stats
|
|
99
|
+
* 显示安装统计(对齐 show_stats;Sessionlog 行仅在启用分发时输出)
|
|
100
100
|
* @param {object} stats 统计对象
|
|
101
101
|
* @param {string} projectRoot 项目根
|
|
102
|
-
* @param {string} url sessionlog URL
|
|
102
|
+
* @param {string|null} url 已启用分发的 sessionlog URL(null=未启用,不输出该行)
|
|
103
103
|
* @returns {void}
|
|
104
104
|
*/
|
|
105
105
|
function showStats(stats, projectRoot, url) {
|
|
@@ -109,7 +109,7 @@ function showStats(stats, projectRoot, url) {
|
|
|
109
109
|
console.log(`Codex hooks: ${fs.existsSync(path.join(projectRoot, '.codex', 'hooks.json')) ? '已安装' : '未安装'}`);
|
|
110
110
|
console.log(`修复行尾符: ${stats.fixCount} 个文件`);
|
|
111
111
|
console.log(`替换 Python: ${stats.replaceCount} 个文件`);
|
|
112
|
-
console.log(`Sessionlog URL: ${url}(已分发 ${stats.urlCount} 个文件)`);
|
|
112
|
+
if (url) console.log(`Sessionlog URL: ${url}(已分发 ${stats.urlCount} 个文件)`);
|
|
113
113
|
}
|
|
114
114
|
|
|
115
115
|
/**
|
package/package.json
CHANGED
|
@@ -11,7 +11,7 @@ import sys
|
|
|
11
11
|
from datetime import datetime
|
|
12
12
|
from pathlib import Path
|
|
13
13
|
|
|
14
|
-
from flowcraft_env import extract_nested, get_project_root
|
|
14
|
+
from flowcraft_env import extract_nested, get_project_root, is_under_root
|
|
15
15
|
from task_manager import get_task_state
|
|
16
16
|
|
|
17
17
|
CODE_EXTS = {
|
|
@@ -169,11 +169,14 @@ def main() -> int:
|
|
|
169
169
|
pass
|
|
170
170
|
elif re.search(
|
|
171
171
|
r"/\.claude/(project-state\.md|session_log\.json|prd\.md|code-review-report\.md|"
|
|
172
|
-
r"reports/.*|hooks/.*|skills/.*|memory/.*|docs/.*|tasks/[^/]+\.md)|/plan/",
|
|
172
|
+
r"reports/.*|hooks/.*|skills/.*|memory/.*|docs/.*|plans/.*|tasks/[^/]+\.md)|/plan/",
|
|
173
173
|
file_path,
|
|
174
174
|
):
|
|
175
175
|
return 0
|
|
176
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
|
|
177
180
|
print(f"[FlowCraft 守卫] 禁止修改框架文件: {file_path}", file=sys.stderr)
|
|
178
181
|
print("[FlowCraft 守卫] 如需修改框架文件,请手动编辑。", file=sys.stderr)
|
|
179
182
|
return 2
|
|
@@ -53,6 +53,9 @@ def main() -> int:
|
|
|
53
53
|
return 0
|
|
54
54
|
raw = sys.stdin.buffer.read()
|
|
55
55
|
env = os.environ.copy()
|
|
56
|
+
# R2 保险2:子钩子输出固定 UTF-8(消除 Windows GBK 乱码)
|
|
57
|
+
env["PYTHONIOENCODING"] = "utf-8"
|
|
58
|
+
env["PYTHONUTF8"] = "1"
|
|
56
59
|
session_id = extract_session_id(raw)
|
|
57
60
|
if session_id:
|
|
58
61
|
env["FLOWCRAFT_SESSION_ID"] = session_id
|
|
@@ -8,6 +8,7 @@ extract_nested() for unified hook payload field extraction (R5).
|
|
|
8
8
|
import json
|
|
9
9
|
import os
|
|
10
10
|
import re
|
|
11
|
+
import sys
|
|
11
12
|
from pathlib import Path
|
|
12
13
|
|
|
13
14
|
|
|
@@ -67,6 +68,43 @@ def get_claude_dir(script_path: str = None) -> Path:
|
|
|
67
68
|
return get_project_root(script_path) / ".claude"
|
|
68
69
|
|
|
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
|
+
|
|
70
108
|
def extract_nested(raw, key):
|
|
71
109
|
"""Extract a string field from a hook payload (R5 unified extraction).
|
|
72
110
|
|
|
@@ -97,3 +135,28 @@ def extract_nested(raw, key):
|
|
|
97
135
|
# Regex fallback for unparseable payloads
|
|
98
136
|
m = re.search(r'"%s"\s*:\s*"((?:[^"\\]|\\.)*)"' % re.escape(key), text)
|
|
99
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,16 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""PermissionRequest - generic security permission check (no phase limit)."""
|
|
3
3
|
import json
|
|
4
|
-
import os
|
|
5
4
|
import re
|
|
6
5
|
import sys
|
|
7
|
-
from pathlib import Path
|
|
8
6
|
|
|
9
|
-
from flowcraft_env import extract_nested
|
|
7
|
+
from flowcraft_env import extract_nested, get_project_root
|
|
10
8
|
|
|
11
9
|
|
|
12
10
|
def phase_number() -> int:
|
|
13
|
-
|
|
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"
|
|
14
21
|
if not state_file.is_file():
|
|
15
22
|
return 0
|
|
16
23
|
try:
|
|
@@ -8,8 +8,10 @@ import urllib.request
|
|
|
8
8
|
from datetime import datetime
|
|
9
9
|
from pathlib import Path
|
|
10
10
|
|
|
11
|
+
import flowcraft_env # noqa: F401 — UTF-8 stdio 双保险(R2)
|
|
11
12
|
|
|
12
|
-
|
|
13
|
+
|
|
14
|
+
MCP_URL = "http://127.0.0.1:8181/api/logs"
|
|
13
15
|
|
|
14
16
|
|
|
15
17
|
def generate_session_log(state_content: str, session_log: Path, jsonl_dir: str) -> list:
|
|
@@ -9,6 +9,9 @@ import tempfile
|
|
|
9
9
|
import time
|
|
10
10
|
from pathlib import Path
|
|
11
11
|
|
|
12
|
+
import flowcraft_env # noqa: F401 — UTF-8 stdio 双保险(R2)
|
|
13
|
+
from flowcraft_env import sessionlog_local_enabled # R1: 本地日志开关
|
|
14
|
+
|
|
12
15
|
|
|
13
16
|
def _sanitize(text: str) -> str:
|
|
14
17
|
"""Strip UTF-16 surrogates that json.loads may preserve on Windows."""
|
|
@@ -74,6 +77,43 @@ def _update_decision_marker(project_dir: Path, ai_message: str) -> None:
|
|
|
74
77
|
pass
|
|
75
78
|
|
|
76
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
|
+
|
|
77
117
|
def main() -> int:
|
|
78
118
|
raw = sys.stdin.read()
|
|
79
119
|
|
|
@@ -121,32 +161,9 @@ def main() -> int:
|
|
|
121
161
|
pass
|
|
122
162
|
ai_message = _sanitize(ai_message)
|
|
123
163
|
if ai_message:
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
["git", "config", "user.name"],
|
|
128
|
-
capture_output=True,
|
|
129
|
-
text=True,
|
|
130
|
-
timeout=3,
|
|
131
|
-
)
|
|
132
|
-
if r.returncode == 0 and r.stdout.strip():
|
|
133
|
-
git_user = r.stdout.strip()
|
|
134
|
-
except Exception:
|
|
135
|
-
pass
|
|
136
|
-
fd, temp_input = tempfile.mkstemp()
|
|
137
|
-
try:
|
|
138
|
-
with os.fdopen(fd, "w", encoding="utf-8") as tf:
|
|
139
|
-
tf.write(ai_message)
|
|
140
|
-
env = dict(os.environ)
|
|
141
|
-
env["SESSION_LOG"] = str(session_log)
|
|
142
|
-
env["GIT_USER"] = git_user
|
|
143
|
-
env["TEMP_INPUT"] = temp_input
|
|
144
|
-
subprocess.run([sys.executable, str(log_script), "assistant"], env=env)
|
|
145
|
-
finally:
|
|
146
|
-
try:
|
|
147
|
-
os.unlink(temp_input)
|
|
148
|
-
except OSError:
|
|
149
|
-
pass
|
|
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)
|
|
150
167
|
|
|
151
168
|
# R4/R5: 待决决策标记维护(决策卡写入,其余回合清除)
|
|
152
169
|
_update_decision_marker(Path(project_dir), ai_message)
|
|
@@ -7,6 +7,8 @@ import sys
|
|
|
7
7
|
import tempfile
|
|
8
8
|
from pathlib import Path
|
|
9
9
|
|
|
10
|
+
from flowcraft_env import sessionlog_local_enabled # R1: 本地日志开关
|
|
11
|
+
|
|
10
12
|
|
|
11
13
|
def _sanitize(text: str) -> str:
|
|
12
14
|
"""Strip UTF-16 surrogates that json.loads may preserve on Windows."""
|
|
@@ -49,6 +51,10 @@ def main() -> int:
|
|
|
49
51
|
except OSError:
|
|
50
52
|
pass
|
|
51
53
|
|
|
54
|
+
# R1: 本地日志开关——sessionlog.local=false 时跳过写入(默认开)
|
|
55
|
+
if not sessionlog_local_enabled(Path(project_dir)):
|
|
56
|
+
return 0
|
|
57
|
+
|
|
52
58
|
# Get the git user name
|
|
53
59
|
git_user = "unknown"
|
|
54
60
|
try:
|
|
@@ -207,10 +207,6 @@
|
|
|
207
207
|
"command": "python ~/.flowcraft/hooks/dispatch.py statusline",
|
|
208
208
|
"padding": 1
|
|
209
209
|
},
|
|
210
|
-
"enabledPlugins": {
|
|
211
|
-
"superpowers@claude-plugins-official": true,
|
|
212
|
-
"context-hub-plugin@forgetful-plugins": true
|
|
213
|
-
},
|
|
214
210
|
"language": "zh-CN",
|
|
215
211
|
"sandbox": {
|
|
216
212
|
"enabled": true,
|
|
@@ -12,6 +12,13 @@ import tempfile
|
|
|
12
12
|
from datetime import datetime
|
|
13
13
|
from pathlib import Path
|
|
14
14
|
|
|
15
|
+
# R2 UTF-8 stdio 双保险(消除 Windows GBK 乱码)
|
|
16
|
+
for _s in (sys.stdout, sys.stderr):
|
|
17
|
+
try:
|
|
18
|
+
_s.reconfigure(encoding="utf-8", errors="replace")
|
|
19
|
+
except Exception:
|
|
20
|
+
pass
|
|
21
|
+
|
|
15
22
|
|
|
16
23
|
def log_session(role: str, content: str) -> None:
|
|
17
24
|
"""
|
|
@@ -31,6 +31,13 @@ import urllib.request
|
|
|
31
31
|
from datetime import datetime
|
|
32
32
|
from pathlib import Path
|
|
33
33
|
|
|
34
|
+
# R2 UTF-8 stdio 双保险(消除 Windows GBK 乱码)
|
|
35
|
+
for _s in (sys.stdout, sys.stderr):
|
|
36
|
+
try:
|
|
37
|
+
_s.reconfigure(encoding="utf-8", errors="replace")
|
|
38
|
+
except Exception:
|
|
39
|
+
pass
|
|
40
|
+
|
|
34
41
|
|
|
35
42
|
def parse_args(argv):
|
|
36
43
|
args = {
|
|
@@ -40,6 +40,7 @@ const CLAUDE_ALLOWED_FRAGMENTS = [
|
|
|
40
40
|
'/skills/',
|
|
41
41
|
'/memory/',
|
|
42
42
|
'/docs/',
|
|
43
|
+
'/plans/',
|
|
43
44
|
'/plan/',
|
|
44
45
|
];
|
|
45
46
|
|
|
@@ -511,15 +512,33 @@ function getExtension(filePath) {
|
|
|
511
512
|
}
|
|
512
513
|
|
|
513
514
|
/**
|
|
514
|
-
*
|
|
515
|
+
* 判断目标路径是否位于 root 之下(R1: 守卫只管项目内文件)
|
|
516
|
+
*
|
|
517
|
+
* @param {string} filePath 规范化路径
|
|
518
|
+
* @param {string} root 项目根目录
|
|
519
|
+
* @returns {boolean} 是否位于 root 之下
|
|
520
|
+
*/
|
|
521
|
+
function isUnderRoot(filePath, root) {
|
|
522
|
+
const target = path.resolve(filePath).toLowerCase().replace(/\\/g, '/');
|
|
523
|
+
const base = path.resolve(root).toLowerCase().replace(/\\/g, '/');
|
|
524
|
+
return target === base || target.startsWith(base + '/');
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* 判断是否为受保护的 .claude 文件(非白名单路径;仅项目内 .claude 受管)
|
|
515
529
|
*
|
|
516
530
|
* @param {string} normalized 规范化路径
|
|
531
|
+
* @param {string} root 项目根目录
|
|
517
532
|
* @returns {boolean} 是否为受保护框架文件
|
|
518
533
|
*/
|
|
519
|
-
function isProtectedClaudeFile(normalized) {
|
|
534
|
+
function isProtectedClaudeFile(normalized, root) {
|
|
520
535
|
if (!normalized.includes('/.claude/') && !normalized.startsWith('.claude/')) {
|
|
521
536
|
return false;
|
|
522
537
|
}
|
|
538
|
+
// R1: 用户级 ~/.claude(如 Claude Code plans 草稿)不归守卫管
|
|
539
|
+
if (root && !isUnderRoot(normalized, root)) {
|
|
540
|
+
return false;
|
|
541
|
+
}
|
|
523
542
|
return !CLAUDE_ALLOWED_FRAGMENTS.some((fragment) => normalized.includes(fragment));
|
|
524
543
|
}
|
|
525
544
|
|
|
@@ -546,7 +565,7 @@ function checkPhaseWrite(input, root, stateText) {
|
|
|
546
565
|
if (normalized.includes('flowcraft/')) {
|
|
547
566
|
continue; // 框架自身文件允许修改
|
|
548
567
|
}
|
|
549
|
-
if (isProtectedClaudeFile(normalized)) {
|
|
568
|
+
if (isProtectedClaudeFile(normalized, root)) {
|
|
550
569
|
emitDecision('deny', `【SDLC 守卫】禁止修改 SDLC 框架文件: ${rawFile},如需修改请手动编辑。`);
|
|
551
570
|
return;
|
|
552
571
|
}
|
|
@@ -17,6 +17,13 @@ import sys
|
|
|
17
17
|
import urllib.parse
|
|
18
18
|
from pathlib import Path
|
|
19
19
|
|
|
20
|
+
# R2 UTF-8 stdio 双保险(消除 Windows GBK 乱码)
|
|
21
|
+
for _s in (sys.stdout, sys.stderr):
|
|
22
|
+
try:
|
|
23
|
+
_s.reconfigure(encoding="utf-8", errors="replace")
|
|
24
|
+
except Exception:
|
|
25
|
+
pass
|
|
26
|
+
|
|
20
27
|
SCRIPT_DIR = Path(__file__).resolve().parent
|
|
21
28
|
if SCRIPT_DIR.name == "hooks":
|
|
22
29
|
REPO = SCRIPT_DIR.parent.parent
|
|
@@ -128,10 +128,26 @@ class TestCheckPhaseWrite:
|
|
|
128
128
|
assert p.returncode == 0
|
|
129
129
|
|
|
130
130
|
def test_framework_file_blocked(self, tmp_path):
|
|
131
|
+
"""R1: 项目内 .claude 框架文件仍拦(守卫只守本项目,项目内不放开)。"""
|
|
131
132
|
make_state(tmp_path, "P2")
|
|
132
|
-
|
|
133
|
+
target = tmp_path / ".claude" / "settings.json"
|
|
134
|
+
p = run_hook("check-phase-write.py", edit_payload(str(target)), tmp_path)
|
|
133
135
|
assert p.returncode == 2
|
|
134
136
|
|
|
137
|
+
def test_user_level_claude_allowed(self, tmp_path):
|
|
138
|
+
"""R1: 非项目内的 .claude(如 ~/.claude/plans/ 计划草稿)不归守卫管,放行。"""
|
|
139
|
+
make_state(tmp_path, "P2")
|
|
140
|
+
outside = tmp_path.parent / "fake-home" / ".claude" / "plans" / "draft.md"
|
|
141
|
+
p = run_hook("check-phase-write.py", edit_payload(str(outside)), tmp_path)
|
|
142
|
+
assert p.returncode == 0
|
|
143
|
+
|
|
144
|
+
def test_project_claude_plans_allowed(self, tmp_path):
|
|
145
|
+
"""R2: 白名单补 plans/,项目内计划草稿目录放行。"""
|
|
146
|
+
make_state(tmp_path, "P2")
|
|
147
|
+
target = tmp_path / ".claude" / "plans" / "x.md"
|
|
148
|
+
p = run_hook("check-phase-write.py", edit_payload(str(target)), tmp_path)
|
|
149
|
+
assert p.returncode == 0
|
|
150
|
+
|
|
135
151
|
def test_task_state_file_allowed(self, tmp_path):
|
|
136
152
|
"""R6: .claude/tasks/*.md editable (multi-task state files)."""
|
|
137
153
|
make_state(tmp_path, "P2")
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Session-log local switch (PRD R1) + settings template plugin cleanup (PRD R2)
|
|
2
|
+
+ permission-request root fallback (PRD R4).
|
|
3
|
+
|
|
4
|
+
R1: flowcraft.yaml `sessionlog.local` gates local session_log.json writes;
|
|
5
|
+
default (key absent / unparseable) keeps the legacy always-write behaviour.
|
|
6
|
+
R2: the Claude settings template must not enable uninstalled plugins.
|
|
7
|
+
R4: permission-request.py resolves the project root via walk-up, so
|
|
8
|
+
subdirectory-launched sessions see the same phase as the rest of the hooks.
|
|
9
|
+
"""
|
|
10
|
+
import importlib.util
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import pytest
|
|
18
|
+
|
|
19
|
+
HOOKS = Path(__file__).resolve().parents[1] / ".claude" / "hooks"
|
|
20
|
+
SETTINGS_TEMPLATE = HOOKS.parent / "settings.json"
|
|
21
|
+
sys.path.insert(0, str(HOOKS))
|
|
22
|
+
|
|
23
|
+
# Stub log_session.py: drop a marker next to .claude/ when invoked, so the
|
|
24
|
+
# tests observe the *call*, not the JSON payload.
|
|
25
|
+
STUB_LOG = (
|
|
26
|
+
"from pathlib import Path\n"
|
|
27
|
+
"Path(__file__).resolve().parent.parent.joinpath('log_called.marker').write_text('1', encoding='utf-8')\n"
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def load_hook_module(name, filename):
|
|
32
|
+
"""Load a hook script as a module for unit tests."""
|
|
33
|
+
spec = importlib.util.spec_from_file_location(name, HOOKS / filename)
|
|
34
|
+
mod = importlib.util.module_from_spec(spec)
|
|
35
|
+
spec.loader.exec_module(mod)
|
|
36
|
+
return mod
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
flowcraft_env = load_hook_module("flowcraft_env_switch_ut", "flowcraft_env.py")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def make_project(root, local=None):
|
|
43
|
+
"""Create a minimal SDLC project; optionally configure sessionlog.local."""
|
|
44
|
+
(root / ".claude").mkdir(parents=True, exist_ok=True)
|
|
45
|
+
(root / ".claude" / "project-state.md").write_text(
|
|
46
|
+
'current_phase: P2\ntask_description: "t"\n', encoding="utf-8"
|
|
47
|
+
)
|
|
48
|
+
hooks = root / ".claude" / "hooks"
|
|
49
|
+
hooks.mkdir(exist_ok=True)
|
|
50
|
+
(hooks / "log_session.py").write_text(STUB_LOG, encoding="utf-8")
|
|
51
|
+
if local is not None:
|
|
52
|
+
(root / "flowcraft.yaml").write_text(
|
|
53
|
+
f"sessionlog:\n local: {str(local).lower()}\n", encoding="utf-8"
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def run_hook(name, payload, cwd):
|
|
58
|
+
"""Run a hook script against a fake project via CLAUDE_PROJECT_DIR."""
|
|
59
|
+
env = os.environ.copy()
|
|
60
|
+
env["CLAUDE_PROJECT_DIR"] = str(cwd)
|
|
61
|
+
env.pop("FLOWCRAFT_TASK_ID", None)
|
|
62
|
+
env.pop("FLOWCRAFT_SESSION_ID", None)
|
|
63
|
+
return subprocess.run(
|
|
64
|
+
[sys.executable, str(HOOKS / name)],
|
|
65
|
+
input=payload,
|
|
66
|
+
capture_output=True,
|
|
67
|
+
encoding="utf-8",
|
|
68
|
+
errors="replace",
|
|
69
|
+
cwd=str(cwd),
|
|
70
|
+
env=env,
|
|
71
|
+
timeout=60,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def marker(root):
|
|
76
|
+
"""Path of the stub log marker file."""
|
|
77
|
+
return root / ".claude" / "log_called.marker"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# ---------- R1: flowcraft.yaml config parsing ----------
|
|
81
|
+
|
|
82
|
+
class TestSessionlogLocalConfig:
|
|
83
|
+
def test_no_yaml_defaults_true(self, tmp_path):
|
|
84
|
+
assert flowcraft_env.sessionlog_local_enabled(tmp_path) is True
|
|
85
|
+
|
|
86
|
+
def test_false_disables(self, tmp_path):
|
|
87
|
+
(tmp_path / "flowcraft.yaml").write_text("sessionlog:\n local: false\n", encoding="utf-8")
|
|
88
|
+
assert flowcraft_env.sessionlog_local_enabled(tmp_path) is False
|
|
89
|
+
|
|
90
|
+
def test_true_enables(self, tmp_path):
|
|
91
|
+
(tmp_path / "flowcraft.yaml").write_text("sessionlog:\n local: true\n", encoding="utf-8")
|
|
92
|
+
assert flowcraft_env.sessionlog_local_enabled(tmp_path) is True
|
|
93
|
+
|
|
94
|
+
def test_malformed_yaml_defaults_true(self, tmp_path):
|
|
95
|
+
(tmp_path / "flowcraft.yaml").write_text("sessionlog: [broken\n", encoding="utf-8")
|
|
96
|
+
assert flowcraft_env.sessionlog_local_enabled(tmp_path) is True
|
|
97
|
+
|
|
98
|
+
def test_other_section_local_not_misread(self, tmp_path):
|
|
99
|
+
"""审查修复: 其他配置节的缩进 local: 不得被误读为日志开关。"""
|
|
100
|
+
(tmp_path / "flowcraft.yaml").write_text(
|
|
101
|
+
"sessionlog:\n url: http://x\nother:\n local: false\n", encoding="utf-8"
|
|
102
|
+
)
|
|
103
|
+
assert flowcraft_env.sessionlog_local_enabled(tmp_path) is True
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ---------- R1: user-prompt-submit hook gating ----------
|
|
107
|
+
|
|
108
|
+
class TestUserPromptSubmitSwitch:
|
|
109
|
+
def test_default_writes(self, tmp_path):
|
|
110
|
+
make_project(tmp_path)
|
|
111
|
+
run_hook("user-prompt-submit.py", "hi", tmp_path)
|
|
112
|
+
assert marker(tmp_path).exists()
|
|
113
|
+
|
|
114
|
+
def test_local_false_skips(self, tmp_path):
|
|
115
|
+
make_project(tmp_path, local=False)
|
|
116
|
+
p = run_hook("user-prompt-submit.py", "hi", tmp_path)
|
|
117
|
+
assert p.returncode == 0
|
|
118
|
+
assert not marker(tmp_path).exists()
|
|
119
|
+
|
|
120
|
+
def test_local_true_writes(self, tmp_path):
|
|
121
|
+
make_project(tmp_path, local=True)
|
|
122
|
+
run_hook("user-prompt-submit.py", "hi", tmp_path)
|
|
123
|
+
assert marker(tmp_path).exists()
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# ---------- R1: stop-check hook gating ----------
|
|
127
|
+
|
|
128
|
+
class TestStopCheckSwitch:
|
|
129
|
+
def test_default_writes(self, tmp_path):
|
|
130
|
+
make_project(tmp_path)
|
|
131
|
+
run_hook("stop-check.py", json.dumps({"last_assistant_message": "hi"}), tmp_path)
|
|
132
|
+
assert marker(tmp_path).exists()
|
|
133
|
+
|
|
134
|
+
def test_local_false_skips(self, tmp_path):
|
|
135
|
+
make_project(tmp_path, local=False)
|
|
136
|
+
p = run_hook("stop-check.py", json.dumps({"last_assistant_message": "hi"}), tmp_path)
|
|
137
|
+
assert p.returncode == 0
|
|
138
|
+
assert not marker(tmp_path).exists()
|
|
139
|
+
|
|
140
|
+
def test_local_true_writes(self, tmp_path):
|
|
141
|
+
make_project(tmp_path, local=True)
|
|
142
|
+
run_hook("stop-check.py", json.dumps({"last_assistant_message": "hi"}), tmp_path)
|
|
143
|
+
assert marker(tmp_path).exists()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ---------- R2: settings template has no enabled plugins ----------
|
|
147
|
+
|
|
148
|
+
class TestSettingsTemplateNoPlugins:
|
|
149
|
+
def test_no_enabled_plugins(self):
|
|
150
|
+
"""PRD R2: 模板不再默认启用未安装插件(消除启动期网络解析)。"""
|
|
151
|
+
text = SETTINGS_TEMPLATE.read_text(encoding="utf-8")
|
|
152
|
+
assert "enabledPlugins" not in text
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# ---------- R4: permission-request root fallback ----------
|
|
156
|
+
|
|
157
|
+
def run_permission_request(cwd, payload):
|
|
158
|
+
"""Run permission-request.py without CLAUDE_PROJECT_DIR (subdir session)."""
|
|
159
|
+
env = os.environ.copy()
|
|
160
|
+
env.pop("CLAUDE_PROJECT_DIR", None)
|
|
161
|
+
env.pop("FLOWCRAFT_TASK_ID", None)
|
|
162
|
+
env.pop("FLOWCRAFT_SESSION_ID", None)
|
|
163
|
+
return subprocess.run(
|
|
164
|
+
[sys.executable, str(HOOKS / "permission-request.py")],
|
|
165
|
+
input=payload,
|
|
166
|
+
capture_output=True,
|
|
167
|
+
encoding="utf-8",
|
|
168
|
+
errors="replace",
|
|
169
|
+
cwd=str(cwd),
|
|
170
|
+
env=env,
|
|
171
|
+
timeout=60,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def write_payload(path):
|
|
176
|
+
"""Build a Write-tool payload for a .py target."""
|
|
177
|
+
return json.dumps({"tool_name": "Write", "tool_input": {"file_path": str(path)}})
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class TestPermissionRequestRootFallback:
|
|
181
|
+
def test_subdir_session_resolves_parent_state(self, tmp_path):
|
|
182
|
+
"""R4: 子目录启动会话经 walk-up 解析到根状态(P2)→代码写入放行。"""
|
|
183
|
+
root = tmp_path / "proj"
|
|
184
|
+
sub = root / "sub"
|
|
185
|
+
sub.mkdir(parents=True)
|
|
186
|
+
(root / ".claude").mkdir()
|
|
187
|
+
(root / ".claude" / "project-state.md").write_text(
|
|
188
|
+
'current_phase: P2\ntask_description: "t"\n', encoding="utf-8"
|
|
189
|
+
)
|
|
190
|
+
p = run_permission_request(sub, write_payload(sub / "x.py"))
|
|
191
|
+
out = json.loads(p.stdout)
|
|
192
|
+
assert out["hookSpecificOutput"]["decision"]["behavior"] == "allow"
|
|
193
|
+
|
|
194
|
+
def test_no_state_keeps_p0_semantics(self, tmp_path):
|
|
195
|
+
"""R4: 无状态文件项目保持 P0 语义(代码写入拒绝)。"""
|
|
196
|
+
p = run_permission_request(tmp_path, write_payload(tmp_path / "x.py"))
|
|
197
|
+
out = json.loads(p.stdout)
|
|
198
|
+
assert out["hookSpecificOutput"]["decision"]["behavior"] == "deny"
|
|
199
|
+
assert "P0" in out["hookSpecificOutput"]["decision"]["message"]
|