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/cli.py ADDED
@@ -0,0 +1,427 @@
1
+ """命令行入口:
2
+ pystepmap analyze <项目目录> [--config 配置.json] [-o 图.json]
3
+ pystepmap check <项目目录> [--config 配置.json] [--treat-as-marked 规则名...] [--files 文件...]
4
+ pystepmap verify <图.json> <记录.jsonl> [--allow-stale]
5
+ pystepmap serve [--port 5179] [--no-open]
6
+ pystepmap mcp
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import shlex
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ from pystepmap.analyze import AnalysisNotes, analyze_with_notes
17
+ from pystepmap.config import ConfigError, ProjectConfig, load_config
18
+ from pystepmap.entries import entry_notes
19
+ from pystepmap.index import decode_source, source_lines
20
+ from pystepmap.lint import check_project
21
+ from pystepmap.model import ProjectGraph, from_json, parse_key, to_json
22
+ from pystepmap.rules import known_rule_names, rule_entry_kinds
23
+ from pystepmap.selfcheck import classify_unresolved
24
+ from pystepmap.verify import (
25
+ DynamicCall,
26
+ RecordError,
27
+ StaleGraphError,
28
+ VerifyReport,
29
+ read_records,
30
+ verify,
31
+ )
32
+
33
+ _LIST_LIMIT = 30 # 近似、隐式调用、强匹配的动态调用各最多列出几处(弱匹配的动态调用全部列出)
34
+ _ENTRY_KINDS = ("route", "task", "workflow")
35
+ _KIND_NAMES = {"route": "接口", "task": "任务", "condition": "判断函数"}
36
+
37
+
38
+ class _Stop(Exception):
39
+ """命令没法做下去:main 打印这一行中文说明(stderr),退出码 2。"""
40
+
41
+
42
+ def _project_dir(path: str) -> Path:
43
+ root = Path(path)
44
+ if not root.is_dir():
45
+ raise _Stop(f"找不到目录: {root}")
46
+ return root
47
+
48
+
49
+ def _config(args: argparse.Namespace):
50
+ try:
51
+ return load_config(Path(args.config) if args.config else None)
52
+ except (OSError, ValueError) as e: # 读不到、不是合法 JSON、字段不合法(ConfigError)
53
+ raise _Stop(f"无法读取配置文件 {args.config}: {e}") from None
54
+
55
+
56
+ def _summary(graph: ProjectGraph, notes: AnalysisNotes, config: ProjectConfig | None = None) -> str:
57
+ sc = graph.selfcheck
58
+ # 目标不明的调用大半是第三方、标准库和日志(名字项目里没有定义过,不可能落在项目代码上):把真正可能是
59
+ # 项目内调用的那部分单独写出来,这个数才有意义
60
+ blind = len(classify_unresolved(graph.functions, (config or ProjectConfig()).noise_receivers).blind)
61
+ rules = ", ".join(notes.rules) if notes.rules else "无"
62
+ excluded = ", ".join(name if n == 1 else f"{name} ×{n}" for name, n in notes.excluded.items()) or "无"
63
+ here = f".(包 {notes.package})" if notes.package else "." # 分析的目录本身是包:模块也按包名登记
64
+ out = [
65
+ f"启用的识别规则: {rules}",
66
+ f"源码根: {', '.join(r or here for r in notes.source_roots)}",
67
+ f"排除的目录: {excluded}",
68
+ f"函数: {len(graph.functions)}",
69
+ f"功能线: {len(graph.lines)}",
70
+ f"公共任务: {len(graph.common_tasks)}",
71
+ f"跳过的文件: {len(sc.skipped_files)}",
72
+ *(f" {f}: {why}" for f, why in sc.skipped_files),
73
+ f"目标不明的调用: {sc.unresolved_calls}(可能落在项目代码上的 {blind})",
74
+ f"推测的调用: {sc.guessed_calls}",
75
+ f"走不到的节点: {len(sc.unreachable)}",
76
+ f"无出口的节点: {len(sc.dead_ends)}",
77
+ ]
78
+ out += entry_notes(graph) + notes.marks
79
+ return "\n".join(out) + "\n"
80
+
81
+
82
+ def _cmd_analyze(args: argparse.Namespace) -> int:
83
+ """分析一个项目,输出图 JSON"""
84
+ root = _project_dir(args.project)
85
+ config = _config(args)
86
+ if args.output and not Path(args.output).parent.is_dir(): # 先查:别分析完了才发现写不进去
87
+ raise _Stop(f"输出目录不存在: {Path(args.output).parent}")
88
+ graph, notes = analyze_with_notes(root, config)
89
+ text = to_json(graph)
90
+ summary = _summary(graph, notes, config)
91
+ if args.output:
92
+ try:
93
+ Path(args.output).write_text(text, encoding="utf-8")
94
+ except OSError as e:
95
+ raise _Stop(f"无法写入 {args.output}: {e.strerror or e}") from None
96
+ sys.stdout.write(summary)
97
+ else:
98
+ sys.stdout.write(text + "\n")
99
+ sys.stderr.write(summary)
100
+ return 0
101
+
102
+
103
+ def _cmd_check(args: argparse.Namespace) -> int:
104
+ """检查流程代码有没有违反约束"""
105
+ root = _project_dir(args.project)
106
+ config = _config(args)
107
+ unknown = sorted(set(args.treat_as_marked or []) - known_rule_names(config))
108
+ if unknown:
109
+ raise _Stop(f"--treat-as-marked 里有不认识的识别规则: {', '.join(unknown)}"
110
+ f"(可用的: {', '.join(sorted(known_rule_names(config)))})")
111
+ # 检查只看工作流和步骤:只识别接口 / 任务的规则当作已标记也不会多查一个函数,说清楚,不让人以为它们被检查了
112
+ kinds = rule_entry_kinds(config)
113
+ useless = [n for n in dict.fromkeys(args.treat_as_marked or [])
114
+ if n != "pystepkit" and not kinds[n] & {"workflow", "step"}]
115
+ if useless:
116
+ found = ";".join(f"{n} 只识别{'、'.join(_KIND_NAMES.get(k, k) for k in sorted(kinds[n])) or '派发,不识别入口'}"
117
+ for n in useless)
118
+ raise _Stop(f"--treat-as-marked {' '.join(useless)} 不起作用:检查只看工作流和步骤,{found}。"
119
+ "接口、任务要用 pystepkit 的 @workflow 标记才会被检查(和路由、任务的装饰器写在同一个函数上)")
120
+ result = check_project(root, config, treat_as_marked=frozenset(args.treat_as_marked or []),
121
+ only_files=args.files)
122
+ for f in result.unmatched:
123
+ print(f"警告: --files 里的 {f} 不对应项目里的任何 .py 文件(相对项目根目录;排除的目录不算)", file=sys.stderr)
124
+ for v in result.violations:
125
+ print(f"{v.file}:{v.line}: {v.code} {v.message}")
126
+ print(f"共 {len(result.violations)} 处违规")
127
+ if result.ignored: # 指到项目之外或指到非 .py 的符号链接、FIFO 等:不是源文件,只提醒,不影响退出码
128
+ print(f"警告: 以下 {len(result.ignored)} 个 .py 路径不是项目里的源文件,没有读,也没有检查:", file=sys.stderr)
129
+ for f, why in result.ignored:
130
+ print(f" {f}: {why}", file=sys.stderr)
131
+ if result.skipped:
132
+ print(f"以下 {len(result.skipped)} 个文件解析不了,没有检查:", file=sys.stderr)
133
+ for f, why in result.skipped:
134
+ print(f" {f}: {why}", file=sys.stderr)
135
+ return 2
136
+ return 1 if result.violations else 0
137
+
138
+
139
+ class _Source:
140
+ """按需读项目里的源码行,供核对报告引用。"""
141
+
142
+ def __init__(self, root: str):
143
+ self.root = Path(root)
144
+ self._lines: dict[str, list[str]] = {}
145
+
146
+ def __call__(self, file: str, line: int) -> str:
147
+ if file not in self._lines:
148
+ try:
149
+ self._lines[file] = source_lines(decode_source((self.root / file).read_bytes()))
150
+ except (OSError, SyntaxError, UnicodeDecodeError): # 读不到、编码声明不认识、按声明的编码解不开
151
+ self._lines[file] = []
152
+ rows = self._lines[file]
153
+ return rows[line - 1].strip()[:100] if 0 < line <= len(rows) else ""
154
+
155
+
156
+ def _verify_text(r: VerifyReport, graph: ProjectGraph) -> str:
157
+ count = {kind: sum(m.count for m in r.mismatches if m.kind == kind) for kind in ("edge", "end", "call")}
158
+ strong = sum(d.count for d in r.dynamic_call_list if d.strong)
159
+ out = [
160
+ f"图中函数: {r.functions_in_graph}",
161
+ f"执行到的函数: {r.functions_seen}",
162
+ f"不同的真实路径: {r.distinct_paths}",
163
+ f"走过的步数: {r.steps_total}",
164
+ f"在图上: {r.steps_on_graph}",
165
+ f"异常与收尾入口(近似): {r.approx_entries}",
166
+ f"未捕获异常退出: {r.uncaught_exits}",
167
+ f"核对的调用: {r.calls_total}",
168
+ f"隐式调用(属性、魔术方法): {r.implicit_calls}",
169
+ f"动态调用(静态未确定目标): {r.dynamic_calls}",
170
+ f"动态调用中的强匹配: {strong}",
171
+ f"动态调用中的弱匹配: {r.dynamic_calls - strong}",
172
+ f"截断的记录: {r.truncated_records}",
173
+ f"图里没有的函数: {r.unknown_functions}",
174
+ f"插件错误: {r.plugin_errors}",
175
+ f"连线不在图上: {count['edge']}",
176
+ f"结局不在图上: {count['end']}",
177
+ f"调用不在图上: {count['call']}",
178
+ ]
179
+ src = _Source(graph.root)
180
+ titles = {"edge": "连线不在图上", "end": "结局不在图上", "call": "调用不在图上"}
181
+ for kind, title in titles.items():
182
+ found = [m for m in r.mismatches if m.kind == kind]
183
+ if not found:
184
+ continue
185
+ out += ["", f"== {title}({len(found)} 处,按出现次数从多到少)"]
186
+ for m in found:
187
+ file = parse_key(m.fn)[0]
188
+ if kind == "edge":
189
+ out += [f" {m.count}× {m.fn} 第 {m.from_line} 行 → 第 {m.to_line} 行({m.detail})",
190
+ f" {m.from_line} | {src(file, m.from_line)}",
191
+ f" {m.to_line} | {src(file, m.to_line)}"]
192
+ elif kind == "end":
193
+ out += [f" {m.count}× {m.fn} 第 {m.from_line} 行({m.detail})",
194
+ f" {m.from_line} | {src(file, m.from_line)}"]
195
+ else:
196
+ callee_file = m.detail.split("::", 1)[0]
197
+ out += [f" {m.count}× {m.fn} 第 {m.from_line} 行 → {m.detail}",
198
+ f" {file}:{m.from_line} | {src(file, m.from_line)}",
199
+ f" {callee_file}:{m.to_line} | {src(callee_file, m.to_line)}"]
200
+ if r.approx_list:
201
+ shown = r.approx_list[:_LIST_LIMIT]
202
+ out += ["", f"== 异常与收尾的近似(共 {len(r.approx_list)} 处,按出现次数列出前 {len(shown)} 处)"]
203
+ for a in shown:
204
+ file = parse_key(a.fn)[0]
205
+ to = f"第 {a.to_line} 行" if a.to_line else "函数末尾" # 0:隐含的"执行到函数末尾"
206
+ out += [f" {a.count}× {a.fn} 第 {a.from_line} 行 → {to}(入口)",
207
+ f" {a.from_line} | {src(file, a.from_line)}"]
208
+ if a.to_line:
209
+ out.append(f" {a.to_line} | {src(file, a.to_line)}")
210
+ if r.implicit_call_list:
211
+ shown = r.implicit_call_list[:_LIST_LIMIT]
212
+ out += ["", f"== 隐式调用(属性、魔术方法,共 {len(r.implicit_call_list)} 处,按出现次数列出前 {len(shown)} 处)"]
213
+ reasons = {"property": "属性", "dunder": "魔术方法"}
214
+ out += [f" {d.count}× {d.caller} → {d.callee}({reasons[d.reason]})" for d in shown]
215
+ weak = [d for d in r.dynamic_call_list if not d.strong]
216
+ if weak:
217
+ out += ["", f"== 动态调用 · 弱匹配(共 {len(weak)} 处,全部列出,按出现次数)"]
218
+ out += [line for d in weak for line in _dynamic_lines(d, src)]
219
+ strong_list = [d for d in r.dynamic_call_list if d.strong]
220
+ if strong_list:
221
+ shown = strong_list[:_LIST_LIMIT]
222
+ out += ["", f"== 动态调用 · 强匹配(共 {len(strong_list)} 处,按出现次数列出前 {len(shown)} 处)"]
223
+ out += [line for d in shown for line in _dynamic_lines(d, src)]
224
+ if r.plugin_error_list:
225
+ out += ["", "== 插件错误"] + [f" {e}" for e in r.plugin_error_list]
226
+ return "\n".join(out) + "\n"
227
+
228
+
229
+ def _dynamic_lines(d: DynamicCall, src: _Source) -> list[str]:
230
+ file = parse_key(d.caller)[0]
231
+ mark = "强匹配,回调" if d.callback else "强匹配" if d.strong else "弱匹配"
232
+ note = "同一语句里作为参数传出" if d.callback else "同一语句里无法判断目标的调用"
233
+ return [f" {d.count}× {d.caller} 第 {d.line} 行 → {d.callee}({mark})",
234
+ f" {file}:{d.line} | {src(file, d.line)}",
235
+ f" {note}:{'、'.join(d.names)}"]
236
+
237
+
238
+ def _cmd_verify(args: argparse.Namespace) -> int:
239
+ """用测试的执行记录核对图"""
240
+ try:
241
+ graph = from_json(Path(args.graph).read_text(encoding="utf-8"))
242
+ except (OSError, ValueError, KeyError, TypeError) as e:
243
+ raise _Stop(f"无法读取图文件 {args.graph}: {e}") from None
244
+ try:
245
+ report = verify(graph, read_records(args.trace), allow_stale=args.allow_stale)
246
+ except StaleGraphError as e:
247
+ if e.changed:
248
+ print("图已过期,以下文件在分析后发生了变化:", file=sys.stderr)
249
+ for f in e.changed:
250
+ print(f" {f}", file=sys.stderr)
251
+ if e.unreadable:
252
+ print(f"图已过期,以下文件读不到(被删除、移动或没有权限;图的根目录 {graph.root}):", file=sys.stderr)
253
+ for f in e.unreadable:
254
+ print(f" {f}", file=sys.stderr)
255
+ print("请重新分析并重跑测试;确实要用旧图核对时加 --allow-stale", file=sys.stderr)
256
+ return 2
257
+ except (OSError, RecordError) as e:
258
+ raise _Stop(f"无法读取记录文件 {args.trace}: {e}") from None
259
+ sys.stdout.write(_verify_text(report, graph))
260
+ if report.plugin_errors:
261
+ print(f"核对不算数:记录插件出过 {report.plugin_errors} 次错误,记录不完整(见上面的插件错误)", file=sys.stderr)
262
+ return 2
263
+ if report.functions_seen == 0:
264
+ print("核对不算数:记录里没有一个函数对得上图(记录是空的,或者不是用这张图录的)", file=sys.stderr)
265
+ return 2
266
+ return 0 if report.ok else 1
267
+
268
+
269
+ def _cmd_serve(args: argparse.Namespace) -> int:
270
+ """启动平台"""
271
+ if not 1 <= args.port <= 65535:
272
+ raise _Stop(f"端口要在 1 到 65535 之间,实际是 {args.port}")
273
+ try: # 平台后端是另一个包(发布名 pystepmap,依赖 FastAPI):用到时才导入,core 自己只依赖标准库
274
+ from pystepmap_server.cli import serve
275
+ except ModuleNotFoundError as e:
276
+ raise _Stop(_BACKEND_HINT.format(name=e.name, cmd="serve")) from None
277
+ return serve(port=args.port, open_browser=not args.no_open)
278
+
279
+
280
+ _BACKEND_HINT = ("没有安装平台后端(缺少 {name}):只装了 pystepmap-core(分析引擎和命令行)时,用 pip install pystepmap"
281
+ "(或 uv tool install pystepmap)装上平台和 MCP 服务;从源码仓库运行时在仓库根目录运行 uv sync,"
282
+ "再用 uv run pystepmap {cmd} 启动")
283
+
284
+
285
+ def _cmd_mcp(args: argparse.Namespace) -> int:
286
+ """启动给 Claude Code 用的 MCP 服务"""
287
+ try: # 和 serve 一样用到时才导入后端(它依赖 MCP SDK);导入失败的提示只写标准错误,标准输出留给协议
288
+ from pystepmap_server.mcp_server import run
289
+ except ModuleNotFoundError as e:
290
+ raise _Stop(_BACKEND_HINT.format(name=e.name, cmd="mcp")) from None
291
+ return run()
292
+
293
+
294
+ def _cmd_requirements(args: argparse.Namespace) -> int:
295
+ """列出项目里的需求,把设计的流程和实现对照"""
296
+ from pystepmap import requirements as rq
297
+
298
+ root = _project_dir(args.project)
299
+ found = rq.load_requirements(root)
300
+ if not found:
301
+ print(f"{root} 里没有需求({rq.DIR}/*.md,或 OpenSpec 文件里的 ```flow 代码块)")
302
+ return 0
303
+ graph, _ = analyze_with_notes(root, _config(args))
304
+ worst = 0
305
+ for r in found:
306
+ print(f"{r.id or '(没有编号)'} {r.title} [{r.status or '?'}] {r.file}")
307
+ if r.errors:
308
+ worst = 2
309
+ print(" 这条需求读不懂,没有对照:")
310
+ print("\n".join(f" {e}" for e in r.errors))
311
+ continue
312
+ cmp = rq.compare(r, graph)
313
+ if cmp.matches:
314
+ print(f" 设计和实现对得上(功能线:{cmp.line_title})")
315
+ else:
316
+ if r.archived: # 已归档的是当时的设计:和现在的代码不一致照样列,不算没通过
317
+ print(" (已归档的变更:下面的不一致不影响退出码)")
318
+ else:
319
+ worst = max(worst, 1)
320
+ no_line = next((d for d in cmp.differences if d.kind == "no_line"), None)
321
+ if no_line is not None: # 没有可以对照的实现:不数成"几处不一致",设计的节点也不逐个列
322
+ print(f" {no_line.text};设计的 {len(cmp.differences) - 1} 个节点都还没有实现")
323
+ else:
324
+ print(f" 和实现有 {len(cmp.differences)} 处不一致(功能线:{cmp.line_title}):")
325
+ print("\n".join(f" {d.text}" for d in cmp.differences))
326
+ print("\n".join(f" 注意:{n}" for n in cmp.notes), end="\n" if cmp.notes else "")
327
+ return worst
328
+
329
+
330
+ def _cmd_kit(args: argparse.Namespace) -> int:
331
+ """把约束套件装进别的项目,或者撤销"""
332
+ from pystepmap import kit
333
+
334
+ root = Path(args.project)
335
+ try:
336
+ if args.action == "uninstall":
337
+ if not args.yes and not _confirm(f"撤销 {root.expanduser().resolve()} 里装的约束套件?"):
338
+ print("没有改动任何文件")
339
+ return 1
340
+ print("\n".join(kit.uninstall(root)))
341
+ return 0
342
+ plan = kit.plan_install(root, shlex.split(args.command) if args.command else None, args.pre_commit,
343
+ mcp=not args.no_mcp, local_settings=args.local_settings)
344
+ print("\n".join(plan.lines()))
345
+ if args.dry_run:
346
+ print("(--dry-run:只列出,没有写)")
347
+ return 0
348
+ if not args.yes and not _confirm("写入这些文件?"):
349
+ print("没有改动任何文件")
350
+ return 1
351
+ kit.apply_install(plan)
352
+ print(f"装好了。撤销:pystepmap kit uninstall {shlex.quote(str(plan.root))}")
353
+ return 0
354
+ except kit.KitError as e:
355
+ print(e, file=sys.stderr)
356
+ return 2
357
+
358
+
359
+ def _confirm(question: str) -> bool:
360
+ """在终端上问一句,回答 y / yes 才算同意;不是终端(没法问)时不同意——要用 --yes 明说。"""
361
+ if not sys.stdin.isatty():
362
+ print(f"{question} 这里不是终端,没法确认:加上 --yes 再运行", file=sys.stderr)
363
+ return False
364
+ try:
365
+ return input(f"{question} [y/N] ").strip().lower() in ("y", "yes")
366
+ except EOFError:
367
+ return False
368
+
369
+
370
+ def main(argv: list[str] | None = None) -> int:
371
+ parser = argparse.ArgumentParser(prog="pystepmap", description="把 Python 后端代码静态分析成流程图")
372
+ sub = parser.add_subparsers(dest="command")
373
+ p = sub.add_parser("analyze", help="分析项目并输出图 JSON")
374
+ p.add_argument("project", help="项目目录")
375
+ p.add_argument("--config", help="配置文件(JSON)")
376
+ p.add_argument("-o", "--output", help="图 JSON 的输出路径;省略时写到标准输出")
377
+ p.set_defaults(func=_cmd_analyze)
378
+ c = sub.add_parser("check", help="检查带标记的函数是否符合编排约束")
379
+ c.add_argument("project", help="项目目录")
380
+ c.add_argument("--config", help="配置文件(JSON)")
381
+ c.add_argument("--treat-as-marked", nargs="+", metavar="规则名",
382
+ help="把这些识别规则(如 dbos)识别出的工作流和步骤也当作已标记;只识别接口、任务的规则(fastapi、taskiq)不能给")
383
+ c.add_argument("--files", nargs="+", metavar="文件", help="只报告这些文件(相对项目根目录)里的违规")
384
+ c.set_defaults(func=_cmd_check)
385
+ v = sub.add_parser("verify", help="把测试中记录的真实执行路径放到图上核对")
386
+ v.add_argument("graph", help="pystepmap analyze 产出的图 JSON")
387
+ v.add_argument("trace", help="pytest -p pystepmap.trace 产出的执行记录(JSONL)")
388
+ v.add_argument("--allow-stale", action="store_true", help="源码在分析之后改过也照样核对(行号可能对不上)")
389
+ v.set_defaults(func=_cmd_verify)
390
+ s = sub.add_parser("serve", help="启动本机平台(只监听 127.0.0.1),在浏览器里浏览项目的功能线")
391
+ s.add_argument("--port", type=int, default=5179, help="端口(默认 5179)")
392
+ s.add_argument("--no-open", action="store_true", help="不自动打开浏览器")
393
+ s.set_defaults(func=_cmd_serve)
394
+ m = sub.add_parser("mcp", help="在标准输入输出上提供 MCP 服务,给 Claude Code 查询项目的流程(和 serve 共用数据目录)")
395
+ m.set_defaults(func=_cmd_mcp)
396
+ r = sub.add_parser("requirements", help="列出项目里的需求(.pystepmap/requirements/ 和 OpenSpec 文件里的 flow 代码块),把设计的流程和代码的流程对照")
397
+ r.add_argument("project", help="项目目录")
398
+ r.add_argument("--config", help="配置文件(JSON)")
399
+ r.set_defaults(func=_cmd_requirements)
400
+ k = sub.add_parser("kit", help="把约束套件(skill、编辑后的检查钩子、MCP 配置)装进别的项目,或者撤销")
401
+ k.add_argument("action", choices=["install", "uninstall"])
402
+ k.add_argument("project", help="目标项目的根目录")
403
+ k.add_argument("--yes", action="store_true", help="不问,直接写(不在终端里运行时必须给)")
404
+ k.add_argument("--dry-run", action="store_true", help="只列出要写什么,不写")
405
+ k.add_argument("--pre-commit", action="store_true", help="同时装 git 的提交前检查(已有提交前钩子的仓库不装)")
406
+ k.add_argument("--no-mcp", action="store_true",
407
+ help="不往项目的 .mcp.json 里写 pystepmap 的 MCP 服务(已经在用户级配过时用)")
408
+ k.add_argument("--local-settings", action="store_true",
409
+ help="钩子写进 .claude/settings.local.json(不入库,只对本机生效)")
410
+ k.add_argument("--command", help="钩子和 MCP 用来运行 pystepmap 的命令(默认是现在这个 pystepmap 的绝对路径)")
411
+ k.set_defaults(func=_cmd_kit)
412
+ args = parser.parse_args(argv)
413
+ if not getattr(args, "func", None):
414
+ parser.print_usage(sys.stderr)
415
+ return 2
416
+ try:
417
+ return args.func(args)
418
+ except _Stop as e:
419
+ print(e, file=sys.stderr)
420
+ return 2
421
+ except ConfigError as e: # 运行中才发现的配置问题(如 source_roots 里的目录不存在)
422
+ print(f"配置不合法: {e}", file=sys.stderr)
423
+ return 2
424
+
425
+
426
+ if __name__ == "__main__":
427
+ sys.exit(main())
pystepmap/config.py ADDED
@@ -0,0 +1,144 @@
1
+ """项目配置:控制索引排除目录、噪音过滤、结局字段识别等。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from dataclasses import dataclass, field, fields
8
+ from pathlib import Path
9
+ from typing import get_args
10
+
11
+ from .model import FnKind, OutcomeKind
12
+
13
+ NOISE_RECEIVERS = ("logger", "log", "logging") # 这些名字上的调用是日志(noise_receivers 的默认值)
14
+ # .claude:kit install 装进去的 skill 示例(transfer_workflow.py)和钩子脚本不是项目的业务代码
15
+ DEFAULT_EXCLUDE = [".venv", "venv", "node_modules", "__pycache__", ".git", ".history", ".claude",
16
+ "site-packages", "dist", "build", "tests"]
17
+
18
+ _RULE_KINDS = tuple(k for k in get_args(FnKind) if k != "function") # extra_rules 里入口装饰器可以给的类型
19
+ _RULE_KEYS = {"name", "entry_decorators", "dispatch", "retry_keywords"}
20
+ _DISPATCH_KEYS = {"methods", "task_from", "dynamic_ok"}
21
+
22
+
23
+ class ConfigError(ValueError):
24
+ """配置不合法(字段类型、取值、源码根目录等)。信息是给用户看的中文。"""
25
+
26
+
27
+ def _str_list(value: object, where: str) -> None:
28
+ if not (isinstance(value, list) and all(isinstance(x, str) for x in value)):
29
+ raise ConfigError(f"{where} 必须是字符串列表,实际是 {json.dumps(value, ensure_ascii=False)}")
30
+
31
+
32
+ def _check_extra_rule(rule: object, where: str) -> None:
33
+ if not isinstance(rule, dict):
34
+ raise ConfigError(f"{where} 必须是对象")
35
+ unknown = sorted(set(rule) - _RULE_KEYS)
36
+ if unknown:
37
+ raise ConfigError(f"{where} 含未知字段:{', '.join(unknown)}(可用 {', '.join(sorted(_RULE_KEYS))})")
38
+ if not isinstance(rule.get("name", "extra"), str):
39
+ raise ConfigError(f"{where}.name 必须是字符串")
40
+ entries = rule.get("entry_decorators", [])
41
+ if not isinstance(entries, list):
42
+ raise ConfigError(f"{where}.entry_decorators 必须是 [正则, 类型] 的列表")
43
+ for i, pair in enumerate(entries):
44
+ at = f"{where}.entry_decorators[{i}]"
45
+ if not (isinstance(pair, list) and len(pair) == 2 and all(isinstance(x, str) for x in pair)):
46
+ raise ConfigError(f"{at} 必须是 [正则, 类型]")
47
+ try:
48
+ re.compile(pair[0])
49
+ except re.error as e:
50
+ raise ConfigError(f"{at} 的正则 {pair[0]!r} 写错了:{e}") from None
51
+ if pair[1] not in _RULE_KINDS:
52
+ raise ConfigError(f"{at} 的类型 {pair[1]!r} 不认识(可用 {', '.join(_RULE_KINDS)})")
53
+ dispatch = rule.get("dispatch", [])
54
+ if not isinstance(dispatch, list):
55
+ raise ConfigError(f"{where}.dispatch 必须是列表")
56
+ for i, d in enumerate(dispatch):
57
+ at = f"{where}.dispatch[{i}]"
58
+ if not isinstance(d, dict) or set(d) - _DISPATCH_KEYS:
59
+ raise ConfigError(f"{at} 必须是只含 {', '.join(sorted(_DISPATCH_KEYS))} 的对象")
60
+ _str_list(d.get("methods", []), f"{at}.methods")
61
+ if d.get("task_from", "arg0") not in ("receiver", "arg0"):
62
+ raise ConfigError(f"{at}.task_from 只能是 receiver 或 arg0,实际是 {d.get('task_from')!r}")
63
+ if not isinstance(d.get("dynamic_ok", True), bool):
64
+ raise ConfigError(f"{at}.dynamic_ok 必须是 true 或 false")
65
+ _str_list(rule.get("retry_keywords", []), f"{where}.retry_keywords")
66
+
67
+
68
+ @dataclass
69
+ class ProjectConfig:
70
+ # 不进入的目录名(任何一层)。给出时取代默认列表 DEFAULT_EXCLUDE(.venv、node_modules、tests……),要保留默认的就
71
+ # 一起写上;只想多排除几个目录时用 extra_exclude
72
+ exclude: list[str] = field(default_factory=lambda: list(DEFAULT_EXCLUDE))
73
+ extra_exclude: list[str] = field(default_factory=list) # 在 exclude(默认的或给出的)之外再排除的目录名
74
+ noise_receivers: list[str] = field(default_factory=lambda: list(NOISE_RECEIVERS)) # 以这些名字开头的接收者上的调用是噪音
75
+ noise_functions: list[str] = field(default_factory=list) # 这些项目内函数不算步骤
76
+ outcome_fields: list[str] = field(default_factory=lambda: ["status", "kind", "verdict", "reason"])
77
+ outcome_kinds: dict[str, dict[str, str]] = field(
78
+ default_factory=lambda: {"kind": {"skipped": "skipped", "failed": "failed"}})
79
+ common_task_threshold: int = 6
80
+ extra_rules: list[dict] = field(default_factory=list)
81
+ # 额外的入口:[{"match": "文件::限定名" 的通配模式(* ? [...],按 fnmatch 区分大小写), "group": 分组名(可省略)}]。
82
+ # 对上的普通函数各成一条功能线——给不是用装饰器注册的入口用(命令行的子命令、按名字分发的工具方法)
83
+ extra_entries: list[dict] = field(default_factory=list)
84
+ # 没有 await 的调用落在项目外对象上时(db.execute、requests.post、self.session.commit)也画成步骤,见 external.py;
85
+ # false 时只有项目内函数、派发和被 await 的调用是步骤(2026-11-19 之前的行为)
86
+ external_calls: bool = True
87
+ # 一个入口都没认出来时,把没有人调用的顶层函数当入口,保证项目有功能线,见 lines.py;false 时功能线就是空的
88
+ fallback_entries: bool = True
89
+ source_roots: list[str] | None = None # 源码根(相对项目根目录的目录,"." 是根目录本身);给出时取代自动检测
90
+
91
+ def __post_init__(self) -> None:
92
+ """检查每个字段的类型和取值,不合法时抛 ConfigError(不论来自配置文件还是代码)。"""
93
+ for name in ("exclude", "extra_exclude", "noise_receivers", "noise_functions", "outcome_fields"):
94
+ _str_list(getattr(self, name), name)
95
+ kinds = get_args(OutcomeKind)
96
+ if not isinstance(self.outcome_kinds, dict) or not all(
97
+ isinstance(k, str) and isinstance(m, dict) for k, m in self.outcome_kinds.items()):
98
+ raise ConfigError("outcome_kinds 必须是 {字段名: {字段值: 结局}} 的对象")
99
+ for name, mapping in self.outcome_kinds.items():
100
+ for value, kind in mapping.items():
101
+ if kind not in kinds:
102
+ raise ConfigError(f"outcome_kinds.{name}.{value} 的结局 {kind!r} 不认识(可用 {', '.join(kinds)})")
103
+ if type(self.common_task_threshold) is not int or self.common_task_threshold < 1:
104
+ raise ConfigError(f"common_task_threshold 必须是正整数,实际是 {self.common_task_threshold!r}")
105
+ if not isinstance(self.extra_rules, list):
106
+ raise ConfigError("extra_rules 必须是规则对象的列表")
107
+ for i, rule in enumerate(self.extra_rules):
108
+ _check_extra_rule(rule, f"extra_rules[{i}]")
109
+ if not isinstance(self.extra_entries, list):
110
+ raise ConfigError("extra_entries 必须是 {\"match\": 模式, \"group\": 分组} 对象的列表")
111
+ for i, e in enumerate(self.extra_entries):
112
+ if not isinstance(e, dict) or set(e) - {"match", "group"} or not isinstance(e.get("match"), str) \
113
+ or not e["match"] or not isinstance(e.get("group", ""), str):
114
+ raise ConfigError(f"extra_entries[{i}] 必须是 {{\"match\": 非空的模式, \"group\": 分组名(可省略)}}")
115
+ for name in ("external_calls", "fallback_entries"):
116
+ if not isinstance(getattr(self, name), bool):
117
+ raise ConfigError(f"{name} 必须是 true 或 false")
118
+ if self.source_roots is not None:
119
+ _str_list(self.source_roots, "source_roots")
120
+
121
+ @property
122
+ def exclude_dirs(self) -> list[str]:
123
+ """实际排除的目录名:exclude 加上 extra_exclude(重复的只算一次,exclude 在前)。"""
124
+ return list(dict.fromkeys([*self.exclude, *self.extra_exclude]))
125
+
126
+
127
+ def load_config(path: Path | None) -> ProjectConfig:
128
+ """读取 JSON 配置;path 为 None 时返回默认值。文件不是合法 JSON 时抛 json.JSONDecodeError,
129
+ 出现未知字段或字段不合法时抛 ConfigError。"""
130
+ if path is None:
131
+ return ProjectConfig()
132
+ return parse_config(json.loads(Path(path).read_text(encoding="utf-8")))
133
+
134
+
135
+ def parse_config(data: object) -> ProjectConfig:
136
+ """把配置 JSON 的内容(已解析成 Python 对象)变成 ProjectConfig;顶层不是对象、出现未知字段或字段不合法时抛
137
+ ConfigError。平台保存的项目配置也走这里,和 --config 文件的规则一致。"""
138
+ if not isinstance(data, dict):
139
+ raise ConfigError("配置文件顶层必须是对象")
140
+ known = {f.name for f in fields(ProjectConfig)}
141
+ unknown = sorted(set(data) - known)
142
+ if unknown:
143
+ raise ConfigError(f"配置文件含未知字段:{', '.join(unknown)}")
144
+ return ProjectConfig(**data)