pystepmap-core 0.1.0__py3-none-any.whl

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.
pystepmap/kit.py ADDED
@@ -0,0 +1,431 @@
1
+ """把约束套件装进别的项目(pystepmap kit install / uninstall)。这是 pystepmap 唯一往别的项目写文件的功能,只在
2
+ 用户明确运行这条命令时发生:先列出要写什么,确认之后才写;写了什么记在清单里,uninstall 照清单撤销。
3
+
4
+ 装进目标项目的东西:
5
+ - .claude/skills/flow-style/ 流程代码怎么写的 skill(SKILL.md、dbos.md、requirements.md、routes.md、示例 transfer_workflow.py、给 OpenSpec 用的
6
+ 规则片段 openspec-flow-rules.yaml)
7
+ - .claude/hooks/pystepmap_check.py 编辑 .py 之后的检查脚本;.claude/settings.json 里加一条 PostToolUse 钩子运行它
8
+ (给了 --local-settings 时写进不入库的 .claude/settings.local.json;另一个设置文件读不了时不碰它、不挡安装和撤销)
9
+ - .mcp.json 加一个 pystepmap 的 MCP 服务(Claude Code 查流程、重新分析、看流程差异);给了 --no-mcp 时不碰这个文件
10
+ (pystepmap 的 MCP 已经在用户级配过的,项目里再写一份就重复了)
11
+ - 给了 --pre-commit 时:.claude/hooks/pystepmap_pre_commit.py 和 .git/hooks/pre-commit(已经有提交前钩子、
12
+ 或者设了 core.hooksPath 的仓库不装,并说明)
13
+ - .claude/pystepmap-kit.json 清单:写了哪些文件(内容的 sha256)、加了哪条钩子、MCP 服务是不是自己装的、.mcp.json 里
14
+ 原来有没有同名服务
15
+
16
+ 已有的 .claude/settings.json、.mcp.json 只加自己的那一项,别的不动;不是合法 JSON 时什么都不写。已有的同名文件
17
+ (skill、脚本)内容不一样时不覆盖,除非是上一次自己装的(清单里的 sha256 对得上)。撤销时只删内容没被改过的文件。
18
+
19
+ 钩子和 MCP 用的命令是运行这条命令的那个 pystepmap 的绝对路径(--command 可以换,比如 "uvx pystepmap")。
20
+ pystepkit(标记包)不替项目安装:只说明怎么装。只用标准库。
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import hashlib
26
+ import json
27
+ import shlex
28
+ import subprocess
29
+ import sys
30
+ from dataclasses import dataclass, field
31
+ from pathlib import Path
32
+
33
+ MANIFEST = ".claude/pystepmap-kit.json"
34
+ SKILL_DIR = ".claude/skills/flow-style"
35
+ HOOK_FILE = ".claude/hooks/pystepmap_check.py"
36
+ PRE_COMMIT_FILE = ".claude/hooks/pystepmap_pre_commit.py"
37
+ GIT_PRE_COMMIT = ".git/hooks/pre-commit"
38
+ SETTINGS = ".claude/settings.json"
39
+ SETTINGS_LOCAL = ".claude/settings.local.json"
40
+ MCP_FILE = ".mcp.json"
41
+ MCP_NAME = "pystepmap"
42
+ HOOK_MATCHER = "Edit|Write|MultiEdit"
43
+ EXAMPLE_NAME = "transfer_workflow.py"
44
+ OPENSPEC_NAME = "openspec-flow-rules.yaml"
45
+ CMD = "{cmd}" # skill 文本里放检查器命令的位置
46
+
47
+
48
+ class KitError(Exception):
49
+ """装不了 / 撤销不了:说明原因,什么都没写。"""
50
+
51
+
52
+ # skill 里只对 pystepmap 自己的仓库成立的说法 → 装进别的项目时的说法。每一条都必须在源文件里对得上(测试保证),
53
+ # 换完之后不能再出现 FORBIDDEN 里的字样。
54
+ SKILL_SUBS: list[tuple[str, str]] = [
55
+ ("在本仓库(pystepmap)里", "在本项目里"),
56
+ ("(SM001–SM004,代码在 `core/src/pystepmap/lint.py`)", "(SM001–SM004)"),
57
+ ("`kit/hooks/check_edited_file.py`", f"`{HOOK_FILE}`"),
58
+ ("`kit/hooks/pre-commit`", "提交前检查(装了的话)"),
59
+ (";测试 `kit/tests/test_skill.py` 会把每个代码块放进\n临时项目跑检查,确认违规写法恰好报这些行、改法零违规。", "。"),
60
+ # 示例装在 .claude 下,从项目根检查 / 分析时这个目录是排除的(什么都查不到):演示用的命令把 skill 目录当项目目录
61
+ ("1. 在仓库根目录检查改过的文件(路径相对仓库根,可以列多个):",
62
+ (f"1. 检查改过的文件:在项目根目录运行 `{CMD} check . --files <改过的文件>`(路径相对项目根,可以列多个)。下面拿本 skill\n"
63
+ f" 自带的示例演示;它在 `.claude` 下,从项目根检查时这个目录是排除的,所以演示里把 skill 目录当项目目录:")),
64
+ ("uv run pystepmap check . --files examples/transfer/transfer_workflow.py", f"{CMD} check {SKILL_DIR} --files {EXAMPLE_NAME}"),
65
+ ("uv run pystepmap analyze examples/transfer ", f"{CMD} analyze {SKILL_DIR} "),
66
+ ("examples/transfer/transfer_workflow.py", f"{SKILL_DIR}/{EXAMPLE_NAME}"),
67
+ ("本仓库目前不用 DBOS。", ""),
68
+ ]
69
+ REQUIREMENTS_SUBS: list[tuple[str, str]] = [
70
+ ("`kit/openspec/flow-rules.yaml`", f"`{SKILL_DIR}/{OPENSPEC_NAME}`"),
71
+ ]
72
+ DBOS_SUBS: list[tuple[str, str]] = [
73
+ (";本仓库目前\n不用 DBOS。依据是 `core/src/pystepmap/lint.py` 的 `_DBOS_PRIMITIVES`。", "。"),
74
+ ]
75
+ FORBIDDEN = ("本仓库", "kit/", "examples/", "docs/", "core/src", "uv run pystepmap") # 最后一个:命令都要换成 CMD
76
+
77
+
78
+ def _package_assets() -> Path:
79
+ return Path(__file__).resolve().parent / "kit_assets"
80
+
81
+
82
+ def asset_sources() -> dict[str, Path]:
83
+ """套件的源文件:装成包时在包里的 kit_assets/(打包时放进去的);从源码仓库运行时在仓库里原来的位置。"""
84
+ packed = _package_assets()
85
+ if (packed / "SKILL.md").is_file():
86
+ return {"skill": packed / "SKILL.md", "dbos": packed / "dbos.md", "requirements": packed / "requirements.md",
87
+ "routes": packed / "routes.md", "example": packed / EXAMPLE_NAME,
88
+ "hook": packed / "check_edited_file.py", "pre_commit": packed / "pre-commit",
89
+ "openspec": packed / OPENSPEC_NAME}
90
+ repo = Path(__file__).resolve().parents[3]
91
+ found = {"skill": repo / ".claude/skills/flow-style/SKILL.md", "dbos": repo / ".claude/skills/flow-style/dbos.md",
92
+ "requirements": repo / ".claude/skills/flow-style/requirements.md",
93
+ "routes": repo / ".claude/skills/flow-style/routes.md",
94
+ "example": repo / "examples/transfer" / EXAMPLE_NAME, "hook": repo / "kit/hooks/check_edited_file.py",
95
+ "pre_commit": repo / "kit/hooks/pre-commit", "openspec": repo / "kit/openspec/flow-rules.yaml"}
96
+ missing = [str(p) for p in found.values() if not p.is_file()]
97
+ if missing:
98
+ raise KitError(f"找不到套件的文件:{'、'.join(missing)}")
99
+ return found
100
+
101
+
102
+ def render(text: str, subs: list[tuple[str, str]], command: str) -> str:
103
+ """把 skill 文本换成装进别的项目的说法;有一条对不上、或者换完还有只对本仓库成立的字样时抛 KitError。"""
104
+ for old, new in subs:
105
+ if old not in text:
106
+ raise KitError(f"skill 的文本变了,安装器的替换表没跟上(找不到:{old[:40]!r})")
107
+ text = text.replace(old, new)
108
+ left = [w for w in FORBIDDEN if w in text]
109
+ if left:
110
+ raise KitError(f"skill 换完之后还有只对 pystepmap 仓库成立的字样:{'、'.join(left)}")
111
+ return text.replace(CMD, command)
112
+
113
+
114
+ def default_command() -> list[str]:
115
+ """运行这条命令的那个 pystepmap:解释器旁边的 pystepmap 可执行文件,没有时 `解释器 -m pystepmap.cli`。"""
116
+ exe = Path(sys.executable).parent / "pystepmap"
117
+ return [str(exe)] if exe.is_file() else [sys.executable, "-m", "pystepmap.cli"]
118
+
119
+
120
+ def _sha(data: bytes) -> str:
121
+ return hashlib.sha256(data).hexdigest()
122
+
123
+
124
+ def _read_json(path: Path, what: str) -> dict:
125
+ if not path.exists():
126
+ return {}
127
+ try:
128
+ data = json.loads(path.read_text(encoding="utf-8"))
129
+ except (OSError, ValueError) as e:
130
+ raise KitError(f"{what}({path})读不了或不是合法的 JSON:{e}。没有改动任何文件") from None
131
+ if not isinstance(data, dict):
132
+ raise KitError(f"{what}({path})的顶层不是对象。没有改动任何文件")
133
+ return data
134
+
135
+
136
+ def _dump(data: dict) -> bytes:
137
+ return (json.dumps(data, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
138
+
139
+
140
+ @dataclass
141
+ class Plan:
142
+ root: Path
143
+ files: dict[str, bytes] = field(default_factory=dict) # 相对路径 -> 要写的内容(新建,或覆盖上次自己装的)
144
+ unchanged: list[str] = field(default_factory=list) # 已经是这个内容,不用写
145
+ hook_command: str = ""
146
+ settings_file: str = SETTINGS # 钩子写进哪个设置文件(--local-settings 时是 SETTINGS_LOCAL)
147
+ settings: dict | None = None # 要写回的 settings_file(None = 钩子已经在里面)
148
+ other_settings: dict | None = None # 另一个设置文件里去掉我们的钩子之后的内容({} = 空了、删掉;None = 那里没有我们的钩子)
149
+ mcp: dict | None = None # 要写回的 .mcp.json(None = 已经是这个服务)
150
+ mcp_previous: object = None # .mcp.json 里原来的同名服务(没有时 None)
151
+ skip_mcp: bool = False # --no-mcp:这一次不碰 .mcp.json
152
+ git_pre_commit: bytes | None = None
153
+ notes: list[str] = field(default_factory=list)
154
+
155
+ def lines(self) -> list[str]:
156
+ out = [f"目标项目:{self.root}", "要写的文件:"]
157
+ out += [f" 新建 / 更新 {rel}" for rel in self.files]
158
+ if self.settings is not None:
159
+ out.append(f" 修改 {self.settings_file}:加一条 PostToolUse 钩子({HOOK_MATCHER} 之后运行 {HOOK_FILE})")
160
+ if self.other_settings is not None:
161
+ out.append(f" 修改 {_other(self.settings_file)}:去掉原来的编辑后检查钩子(挪到 {self.settings_file})")
162
+ if self.mcp is not None:
163
+ how = "替换原来的同名服务" if self.mcp_previous is not None else "加一个 MCP 服务"
164
+ out.append(f" 修改 {MCP_FILE}:{how} {MCP_NAME}")
165
+ if self.git_pre_commit is not None:
166
+ out.append(f" 新建 {GIT_PRE_COMMIT}:提交前检查")
167
+ out.append(f" 新建 / 更新 {MANIFEST}(清单,撤销时用)")
168
+ if self.unchanged:
169
+ out.append(f"已经是最新、不用写的:{'、'.join(self.unchanged)}")
170
+ out += [f"注意:{n}" for n in self.notes]
171
+ return out
172
+
173
+
174
+ def plan_install(root: Path, command: list[str] | None = None, pre_commit: bool = False, mcp: bool = True,
175
+ local_settings: bool = False) -> Plan:
176
+ """算出要往 root 里写什么(不写)。装不了时抛 KitError。mcp=False(--no-mcp):不碰 .mcp.json。
177
+ local_settings=True:钩子写进 .claude/settings.local.json 而不是 settings.json。"""
178
+ root = root.expanduser().resolve()
179
+ if not root.is_dir():
180
+ raise KitError(f"不是目录:{root}")
181
+ cmd = shlex.join(command or default_command())
182
+ src = asset_sources()
183
+ old = _read_json(root / MANIFEST, "上一次安装的清单").get("files", {})
184
+ wanted = {
185
+ f"{SKILL_DIR}/SKILL.md": render(src["skill"].read_text(encoding="utf-8"), SKILL_SUBS, cmd).encode("utf-8"),
186
+ f"{SKILL_DIR}/dbos.md": render(src["dbos"].read_text(encoding="utf-8"), DBOS_SUBS, cmd).encode("utf-8"),
187
+ f"{SKILL_DIR}/requirements.md": render(src["requirements"].read_text(encoding="utf-8"), REQUIREMENTS_SUBS,
188
+ cmd).encode("utf-8"),
189
+ f"{SKILL_DIR}/routes.md": render(src["routes"].read_text(encoding="utf-8"), [], cmd).encode("utf-8"),
190
+ f"{SKILL_DIR}/{EXAMPLE_NAME}": src["example"].read_bytes(),
191
+ f"{SKILL_DIR}/{OPENSPEC_NAME}": src["openspec"].read_bytes(),
192
+ HOOK_FILE: src["hook"].read_bytes(),
193
+ }
194
+ plan = Plan(root)
195
+ if pre_commit:
196
+ _plan_pre_commit(plan, root, cmd, src["pre_commit"].read_bytes(), wanted)
197
+ for rel, data in wanted.items():
198
+ path = root / rel
199
+ if path.is_symlink() or (path.exists() and not path.is_file()):
200
+ raise KitError(f"{rel} 已经存在,而且不是普通文件。没有改动任何文件")
201
+ if path.exists():
202
+ have = path.read_bytes()
203
+ if have == data:
204
+ plan.unchanged.append(rel)
205
+ continue
206
+ if old.get(rel) != _sha(have): # 不是上次自己装的原样:是用户的文件,或者用户改过
207
+ raise KitError(f"{rel} 已经存在,内容和要装的不一样(不是上次安装留下的原样)。"
208
+ "先挪开或删掉它再装。没有改动任何文件")
209
+ plan.files[rel] = data
210
+
211
+ plan.hook_command = (f'PYSTEPMAP_HOOK_ROOT="$CLAUDE_PROJECT_DIR" PYSTEPMAP_HOOK_CMD={shlex.quote(cmd)} '
212
+ f'python3 "$CLAUDE_PROJECT_DIR/{HOOK_FILE}"')
213
+ plan.settings_file = SETTINGS_LOCAL if local_settings else SETTINGS
214
+ settings = _read_json(root / plan.settings_file, "Claude Code 的项目设置")
215
+ if _add_hook(settings, plan.hook_command, plan.settings_file):
216
+ plan.settings = settings
217
+ try: # 另一个设置文件不是我们要写的:读不了就不碰,不挡安装
218
+ other = _read_json(root / _other(plan.settings_file), "Claude Code 的项目设置")
219
+ except KitError:
220
+ plan.notes.append(f"{_other(plan.settings_file)} 不是合法的 JSON 对象,没有检查里面有没有原来装的 pystepmap 钩子,也没有改它")
221
+ else:
222
+ if _remove_hook(other): # 上一次装在另一个文件里:挪过来
223
+ plan.other_settings = other
224
+ if local_settings:
225
+ plan.notes.append(f"--local-settings:钩子写在 {SETTINGS_LOCAL}(Claude Code 约定不入库),只对这台机器生效;"
226
+ f"不想让 {HOOK_FILE} 和清单入库的话,把它们加进 .gitignore")
227
+ if mcp:
228
+ _plan_mcp(plan, root, cmd)
229
+ else:
230
+ plan.skip_mcp = True
231
+ plan.notes.append(f"--no-mcp:没有碰 {MCP_FILE}。skill 里说的 pystepmap MCP 用你已经配好的那个(比如用户级的);"
232
+ "还没配过的话,find_nodes、get_flow、diff_flows 这些工具用不了")
233
+ plan.notes.append("标记包 pystepkit 不会替你安装:在项目的环境里装上它(uv add pystepkit 或 pip install pystepkit),"
234
+ "代码里才能 from pystepkit import workflow, step")
235
+ plan.notes.append("装好后重启 Claude Code(或重新打开这个项目),skill 和钩子才生效" if plan.skip_mcp else
236
+ "装好后重启 Claude Code(或重新打开这个项目),skill、钩子和 MCP 才生效;MCP 第一次用时在 Claude Code 里同意它")
237
+ return plan
238
+
239
+
240
+ def _plan_mcp(plan: Plan, root: Path, cmd: str) -> None:
241
+ mcp = _read_json(root / MCP_FILE, "MCP 配置")
242
+ servers = mcp.setdefault("mcpServers", {})
243
+ if not isinstance(servers, dict):
244
+ raise KitError(f"{MCP_FILE} 里的 mcpServers 不是对象。没有改动任何文件")
245
+ parts = shlex.split(cmd)
246
+ server = {"command": parts[0], "args": [*parts[1:], "mcp"]}
247
+ if servers.get(MCP_NAME) != server:
248
+ plan.mcp_previous = servers.get(MCP_NAME)
249
+ servers[MCP_NAME] = server
250
+ plan.mcp = mcp
251
+
252
+
253
+ def _plan_pre_commit(plan: Plan, root: Path, cmd: str, script: bytes, wanted: dict[str, bytes]) -> None:
254
+ if not (root / ".git").is_dir():
255
+ plan.notes.append("不是 git 仓库的根目录,提交前检查没有装")
256
+ return
257
+ r = subprocess.run(["git", "config", "core.hooksPath"], cwd=root, capture_output=True, text=True, check=False)
258
+ if r.stdout.strip():
259
+ plan.notes.append(f"这个仓库设了 core.hooksPath({r.stdout.strip()}),提交前检查没有装:在你自己的钩子里运行 "
260
+ f"PYSTEPMAP_HOOK_CMD={shlex.quote(cmd)} python3 {PRE_COMMIT_FILE}")
261
+ wanted[PRE_COMMIT_FILE] = script
262
+ return
263
+ wrapper = (f"#!/bin/sh\n# pystepmap kit install 装的提交前检查(pystepmap kit uninstall 撤销)\n"
264
+ f"PYSTEPMAP_HOOK_CMD={shlex.quote(cmd)} exec python3 \"$(git rev-parse --show-toplevel)/{PRE_COMMIT_FILE}\"\n"
265
+ ).encode()
266
+ target = root / GIT_PRE_COMMIT
267
+ if target.exists() and target.read_bytes() != wrapper:
268
+ plan.notes.append(f"{GIT_PRE_COMMIT} 已经有了,提交前检查没有装:在它里面加一行 "
269
+ f"PYSTEPMAP_HOOK_CMD={shlex.quote(cmd)} python3 {PRE_COMMIT_FILE}")
270
+ wanted[PRE_COMMIT_FILE] = script
271
+ return
272
+ wanted[PRE_COMMIT_FILE] = script
273
+ if not target.exists():
274
+ plan.git_pre_commit = wrapper
275
+
276
+
277
+ def _other(settings_file: str) -> str:
278
+ return SETTINGS if settings_file == SETTINGS_LOCAL else SETTINGS_LOCAL
279
+
280
+
281
+ def _our_hook(hook: object) -> bool:
282
+ return isinstance(hook, dict) and isinstance(hook.get("command"), str) and HOOK_FILE in hook["command"]
283
+
284
+
285
+ def _add_hook(settings: dict, command: str, name: str = SETTINGS) -> bool:
286
+ """在 settings 的 hooks.PostToolUse 里放上(或换成)我们的钩子;已经是这一条时返回 False。"""
287
+ hooks = settings.setdefault("hooks", {})
288
+ post = hooks.setdefault("PostToolUse", []) if isinstance(hooks, dict) else None
289
+ if not isinstance(post, list):
290
+ raise KitError(f"{name} 里的 hooks.PostToolUse 不是列表。没有改动任何文件")
291
+ entry = {"matcher": HOOK_MATCHER, "hooks": [{"type": "command", "command": command}]}
292
+ if entry in post:
293
+ return False
294
+ _remove_hook(settings)
295
+ settings.setdefault("hooks", {}).setdefault("PostToolUse", []).append(entry)
296
+ return True
297
+
298
+
299
+ def _remove_hook(settings: dict) -> bool:
300
+ """去掉 settings 里我们的钩子(别的钩子不动);空下来的列表、对象一并去掉。返回有没有去掉东西。"""
301
+ hooks = settings.get("hooks")
302
+ post = hooks.get("PostToolUse") if isinstance(hooks, dict) else None
303
+ if not isinstance(post, list):
304
+ return False
305
+ removed = False
306
+ for group in list(post):
307
+ inner = group.get("hooks") if isinstance(group, dict) else None
308
+ if not isinstance(inner, list) or not any(_our_hook(h) for h in inner):
309
+ continue
310
+ removed = True
311
+ inner[:] = [h for h in inner if not _our_hook(h)]
312
+ if not inner:
313
+ post.remove(group)
314
+ if removed and not post:
315
+ del hooks["PostToolUse"]
316
+ if not hooks:
317
+ del settings["hooks"]
318
+ return removed
319
+
320
+
321
+ def _write(path: Path, data: bytes, mode: int | None = None) -> None:
322
+ path.parent.mkdir(parents=True, exist_ok=True)
323
+ path.write_bytes(data)
324
+ if mode is not None:
325
+ path.chmod(mode)
326
+
327
+
328
+ def apply_install(plan: Plan) -> None:
329
+ root = plan.root
330
+ old = _read_json(root / MANIFEST, "上一次安装的清单")
331
+ files = dict(old.get("files", {}))
332
+ for rel, data in plan.files.items():
333
+ _write(root / rel, data)
334
+ files[rel] = _sha(data)
335
+ for rel in plan.unchanged:
336
+ files.setdefault(rel, _sha((root / rel).read_bytes()))
337
+ if plan.settings is not None:
338
+ _write(root / plan.settings_file, _dump(plan.settings))
339
+ if plan.other_settings is not None:
340
+ other_path = root / _other(plan.settings_file)
341
+ if plan.other_settings:
342
+ _write(other_path, _dump(plan.other_settings))
343
+ else:
344
+ other_path.unlink()
345
+ # mcp:.mcp.json 里的 pystepmap 是不是我们装的(撤销时才动它)。这一次没碰(--no-mcp)时照上一次的;旧清单没有
346
+ # 这个字段,那时总是装的
347
+ manifest = {"version": 1, "files": files, "hook": True, "settings": plan.settings_file,
348
+ "mcp": not plan.skip_mcp or (bool(old) and old.get("mcp", True)),
349
+ "mcp_previous": old.get("mcp_previous") if plan.mcp is None else plan.mcp_previous,
350
+ "mcp_file_created": old.get("mcp_file_created", False),
351
+ "git_pre_commit": old.get("git_pre_commit", False)}
352
+ if plan.mcp is not None:
353
+ if not (root / MCP_FILE).exists():
354
+ manifest["mcp_file_created"] = True
355
+ _write(root / MCP_FILE, _dump(plan.mcp))
356
+ if plan.git_pre_commit is not None:
357
+ _write(root / GIT_PRE_COMMIT, plan.git_pre_commit, 0o755)
358
+ manifest["git_pre_commit"] = _sha(plan.git_pre_commit)
359
+ _write(root / MANIFEST, _dump(manifest))
360
+
361
+
362
+ def uninstall(root: Path) -> list[str]:
363
+ """照清单撤销,返回说明做了什么的几行。没有清单时抛 KitError。"""
364
+ root = root.expanduser().resolve()
365
+ if not (root / MANIFEST).is_file():
366
+ raise KitError(f"{root} 里没有安装清单({MANIFEST}):这里没有用 pystepmap kit install 装过")
367
+ manifest = _read_json(root / MANIFEST, "安装清单")
368
+ out: list[str] = []
369
+ # 先把设置文件读好、算好:清单里记的那个读不了就在动任何东西之前报错;另一个读不了就留着不动,不让撤销做一半
370
+ target = manifest.get("settings") if manifest.get("settings") in (SETTINGS, SETTINGS_LOCAL) else SETTINGS
371
+ settings_edits: list[tuple[Path, dict, str]] = []
372
+ for rel in (target, _other(target)): # 旧清单没有 settings 字段:当作 settings.json
373
+ settings_path = root / rel
374
+ if not settings_path.exists():
375
+ continue
376
+ try:
377
+ settings = _read_json(settings_path, "Claude Code 的项目设置")
378
+ except KitError:
379
+ if rel == target:
380
+ raise
381
+ out.append(f"保留 {rel}(不是合法的 JSON 对象,没有检查里面有没有 pystepmap 的钩子)")
382
+ continue
383
+ if _remove_hook(settings):
384
+ settings_edits.append((settings_path, settings, rel))
385
+ # .mcp.json 也先读好:读不了就在动任何东西之前报错("没有改动任何文件"才是真的)
386
+ mcp_path = root / MCP_FILE
387
+ mcp = None
388
+ if manifest.get("mcp", True) and mcp_path.exists(): # --no-mcp 装的:里面的同名服务是用户自己的,不动
389
+ mcp = _read_json(mcp_path, "MCP 配置")
390
+ targets = dict(manifest.get("files", {}))
391
+ if isinstance(manifest.get("git_pre_commit"), str):
392
+ targets[GIT_PRE_COMMIT] = manifest["git_pre_commit"]
393
+ for rel, sha in targets.items():
394
+ path = root / rel
395
+ if not path.is_file():
396
+ continue
397
+ if _sha(path.read_bytes()) != sha:
398
+ out.append(f"保留 {rel}(装了之后改过)")
399
+ continue
400
+ path.unlink()
401
+ out.append(f"删除 {rel}")
402
+ for rel in (SKILL_DIR, ".claude/hooks", ".claude/skills"): # 空下来的目录(.claude 本身留到最后看)
403
+ d = root / rel
404
+ if d.is_dir() and not any(d.iterdir()):
405
+ d.rmdir()
406
+ for settings_path, settings, rel in settings_edits:
407
+ if settings:
408
+ _write(settings_path, _dump(settings))
409
+ else:
410
+ settings_path.unlink()
411
+ out.append(f"修改 {rel}:去掉了编辑后的检查钩子")
412
+ if mcp is not None:
413
+ servers = mcp.get("mcpServers")
414
+ if isinstance(servers, dict) and MCP_NAME in servers:
415
+ if manifest.get("mcp_previous") is not None:
416
+ servers[MCP_NAME] = manifest["mcp_previous"]
417
+ out.append(f"修改 {MCP_FILE}:{MCP_NAME} 换回了原来的那个")
418
+ else:
419
+ del servers[MCP_NAME]
420
+ out.append(f"修改 {MCP_FILE}:去掉了 {MCP_NAME}")
421
+ if not servers:
422
+ del mcp["mcpServers"]
423
+ if mcp or not manifest.get("mcp_file_created"):
424
+ _write(mcp_path, _dump(mcp))
425
+ else:
426
+ mcp_path.unlink()
427
+ (root / MANIFEST).unlink()
428
+ out.append(f"删除 {MANIFEST}")
429
+ if (root / ".claude").is_dir() and not any((root / ".claude").iterdir()):
430
+ (root / ".claude").rmdir()
431
+ return out