pystepmap 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-0.1.0.dist-info/METADATA +54 -0
- pystepmap-0.1.0.dist-info/RECORD +26 -0
- pystepmap-0.1.0.dist-info/WHEEL +4 -0
- pystepmap-0.1.0.dist-info/entry_points.txt +2 -0
- pystepmap-0.1.0.dist-info/licenses/LICENSE +21 -0
- pystepmap_server/__init__.py +3 -0
- pystepmap_server/api.py +890 -0
- pystepmap_server/app.py +151 -0
- pystepmap_server/cli.py +138 -0
- pystepmap_server/flows.py +542 -0
- pystepmap_server/live.py +151 -0
- pystepmap_server/locks.py +139 -0
- pystepmap_server/mcp_server.py +216 -0
- pystepmap_server/mcp_tools.py +1901 -0
- pystepmap_server/procinfo.py +61 -0
- pystepmap_server/requirements_view.py +63 -0
- pystepmap_server/runner.py +673 -0
- pystepmap_server/shared.py +198 -0
- pystepmap_server/sources.py +126 -0
- pystepmap_server/status.py +116 -0
- pystepmap_server/store.py +1091 -0
- pystepmap_server/testflows.py +648 -0
- pystepmap_server/web/assets/index-CkPpOJq9.js +1748 -0
- pystepmap_server/web/assets/index-NTWdqvqI.css +1 -0
- pystepmap_server/web/index.html +14 -0
- pystepmap_server/worker.py +303 -0
|
@@ -0,0 +1,1901 @@
|
|
|
1
|
+
"""MCP 工具:pystepmap mcp 给 Claude Code 用的十五个工具,每个返回一段给 AI 读的中文文本。协议层在 mcp_server.py。
|
|
2
|
+
|
|
3
|
+
- 怎么指项目:project 可以是项目 id、名字或目录(目录、文件在某个项目里面也算);不给时用 MCP 进程的当前目录去找包含
|
|
4
|
+
它的项目,找不到时 ToolError,信息里列出已有的项目。
|
|
5
|
+
- 怎么指功能线:flow 是功能线 sid(或 id),或标题:完全相同的优先,其次片段,唯一才算;手工改过的标题和原来的标题
|
|
6
|
+
都算,显示时用改过的。
|
|
7
|
+
- 读图的工具(除 list_projects、analyze_project、check)每次调用算一次过期检查(status.staleness),图过期时结果最前面
|
|
8
|
+
加一段"⚠ 代码已变更……";读不了的文件只在 project_status 里说。
|
|
9
|
+
- 读图的缓存:按分析 id 缓存解析好的图,最多 GRAPH_CACHE 张;每次调用先从库里取最新的分析 id(界面那边可能刚重新
|
|
10
|
+
分析过),所以缓存不会过时(分析 id 不重用)。
|
|
11
|
+
- 添加、重新分析走 flows 里的流程(不接受分析配置:配置只能在平台界面上改),失败时把流程给的原因作为 ToolError。
|
|
12
|
+
- 每个工具的结果最多 MAX_CHARS 字,超出时在行边界截断,最后一行说明省略了多少、怎么缩小范围。
|
|
13
|
+
- 测试运行:uncovered_outcomes 和 project_status 的最后一段读平台上跑过的测试的结果(库里的 runs:计数、核对、运行
|
|
14
|
+
路径),只读。没有任何工具能启动、取消测试或填测试命令——运行测试只能在平台界面上点(执行项目代码的那条路在
|
|
15
|
+
runner.py,这里不导入它)。
|
|
16
|
+
|
|
17
|
+
只读被分析项目的源码(读源码片段走 sources.py 的路径检查),不导入、不执行项目代码。这里不是流程代码,不加 pystepkit 标记。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import logging
|
|
24
|
+
import os
|
|
25
|
+
import posixpath
|
|
26
|
+
import threading
|
|
27
|
+
import time
|
|
28
|
+
import urllib.error
|
|
29
|
+
import urllib.parse
|
|
30
|
+
import urllib.request
|
|
31
|
+
from collections import Counter, OrderedDict
|
|
32
|
+
from collections.abc import Callable
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
from datetime import datetime
|
|
35
|
+
from functools import wraps
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
|
|
38
|
+
from pystepmap import requirements as rq
|
|
39
|
+
from pystepmap.diff import GraphDiff, diff_from_json, diff_graphs, diff_text
|
|
40
|
+
from pystepmap.entries import entry_notes
|
|
41
|
+
from pystepmap.model import (
|
|
42
|
+
Edge,
|
|
43
|
+
FlowLine,
|
|
44
|
+
FunctionGraph,
|
|
45
|
+
LineTask,
|
|
46
|
+
Node,
|
|
47
|
+
ProjectGraph,
|
|
48
|
+
from_json,
|
|
49
|
+
)
|
|
50
|
+
from pystepmap.outline import (
|
|
51
|
+
function_outline,
|
|
52
|
+
line_mermaid,
|
|
53
|
+
line_outline,
|
|
54
|
+
node_ref,
|
|
55
|
+
node_text,
|
|
56
|
+
)
|
|
57
|
+
from pystepmap.query import (
|
|
58
|
+
PathStep,
|
|
59
|
+
caught_on_chain,
|
|
60
|
+
entry_chain,
|
|
61
|
+
find_by_function,
|
|
62
|
+
find_by_location,
|
|
63
|
+
find_outcomes,
|
|
64
|
+
line_functions,
|
|
65
|
+
lines_of_functions,
|
|
66
|
+
paths_to,
|
|
67
|
+
)
|
|
68
|
+
from pystepmap.runpath import Outcome
|
|
69
|
+
from pystepmap.selfcheck import NOISE_RECEIVERS, UnresolvedSite, classify_unresolved
|
|
70
|
+
|
|
71
|
+
from . import procinfo
|
|
72
|
+
from .flows import add_project, home_conflict, is_analyzing, reanalyze_project
|
|
73
|
+
from .shared import FactsCache, Uncovered, identity, uncovered_of
|
|
74
|
+
from .sources import SourceError, read_snippet, resolve_source_path, root_problem
|
|
75
|
+
from .status import staleness
|
|
76
|
+
from .store import Store, serve_port
|
|
77
|
+
from .worker import analyze_timeout, check_in_subprocess
|
|
78
|
+
|
|
79
|
+
logger = logging.getLogger(__name__)
|
|
80
|
+
|
|
81
|
+
MAX_CHARS = 40_000 # 每个工具结果的上限(含最后那行提示)
|
|
82
|
+
FLOW_BUDGET = MAX_CHARS - 2_000 # get_flow 的大纲超过这么多字就退到小一级的 depth(留给开头的过期提示和说明)
|
|
83
|
+
MAX_DEPTH = 3 # get_flow 的 depth 限制在 0~3
|
|
84
|
+
DEFAULT_LIMIT = 10 # paths_to_outcome 每个结局默认列几条路径
|
|
85
|
+
MAX_LIMIT = 30
|
|
86
|
+
MAX_HITS = 30 # find_nodes 最多列几处命中
|
|
87
|
+
MAX_OUTCOMES = 30 # paths_to_outcome 最多列几个结局
|
|
88
|
+
MAX_CHOICES = 20 # 没有匹配的结局时列出几个可选的
|
|
89
|
+
MAX_LINE_ROWS = 20 # 一处命中、一个节点最多列几条功能线
|
|
90
|
+
MAX_CHAINS = 3 # find_nodes 每处命中最多给几条功能线写入口链
|
|
91
|
+
CLOSING_RESERVE = 300 # 自己控制长度的工具给最后那行提示留的字数
|
|
92
|
+
# 路径是图上的连线拼出来的:两个判断之间的赋值、+=、del 不出节点,条件前后是否矛盾判断不了,所以一条都不略去
|
|
93
|
+
UNCAUGHT_ANSWER = "这是隐含的结局:函数里任何没被捕获的异常都从这里离开,图上不画进它的连线,所以没有路径可列。"
|
|
94
|
+
OPENSPEC_HOW = ("把改完之后的流程写成 OpenSpec 变更的 design.md 里的一个 ```flow 代码块:块里第一行写 `功能线:<功能线的标题>`,"
|
|
95
|
+
"下面每行一个节点(`步骤:标题`、`判断:标题` 下面缩进 `是:` / `否:`、`循环:标题`、`结局(成功|跳过|失败):标题`),"
|
|
96
|
+
"标题和代码里图上节点的标题一致;入口函数成功的那条路不写 return 时(没有返回内容的接口),成功的结局写 "
|
|
97
|
+
"`结局(成功):执行到函数末尾`。写好后调 get_requirement(编号就是变更名),把它给的流程图地址交给用户看图确认;"
|
|
98
|
+
"实现并 analyze_project 之后再用 get_requirement 对照。")
|
|
99
|
+
PATHS_CAVEAT = "下面列的是图上能走到各个结局的路径:只按连线,不判断前后条件是否互相矛盾,可能含实际走不到的组合;转述前对照源码核对。"
|
|
100
|
+
MAX_ITEMS = 30 # project_status 里每类问题最多列几处
|
|
101
|
+
MAX_BLIND = 20 # project_status 里最多列几处可能落在项目代码上的调用
|
|
102
|
+
MAX_FILES = 50 # project_status 里每类文件最多列几个
|
|
103
|
+
MAX_LINE_REFS = 10 # 过期提示里最多列几条功能线
|
|
104
|
+
GRAPH_CACHE = 2
|
|
105
|
+
FACTS_CACHE = 8
|
|
106
|
+
NEVER_RAN = "还没有在平台上运行过测试(运行测试只能在平台界面上点)"
|
|
107
|
+
# 项目锁被拿着:分析和平台上的测试运行拿同一把锁,MCP 是另一个进程,分不出是哪个
|
|
108
|
+
BUSY_ELSEWHERE = "这个项目正在分析或正在跑测试(平台界面上点的),稍后再试"
|
|
109
|
+
SNIPPET_CONTEXT = 3 # get_node 的源码片段:节点前后各几行
|
|
110
|
+
|
|
111
|
+
_FN_KIND = {"route": "接口", "task": "任务", "workflow": "工作流", "step": "步骤", "condition": "判断函数"}
|
|
112
|
+
_LINE_KIND = {"route": "接口", "task": "任务", "workflow": "工作流"}
|
|
113
|
+
_TYPE = {"start": "开始", "step": "步骤", "cond": "判断", "loop": "循环", "catch": "捕获", "end": "结局"}
|
|
114
|
+
_END = {"ok": "正常", "skipped": "跳过", "failed": "失败", "exception": "异常"}
|
|
115
|
+
_KIND_WORD = {"next": "接着", "yes": "是", "no": "否", "case": "分支", "loop_each": "每次", "loop_exit": "循环结束",
|
|
116
|
+
"loop_back": "回到循环", "break": "跳出循环", "finally": "进入 finally", "raise": "出错"}
|
|
117
|
+
_RESOLUTION = {"exact": "精确", "guessed": "推测", "unresolved": "目标不明", "external": "项目之外"}
|
|
118
|
+
_DIFF_STATUS = {"added": "新增", "removed": "删除", "changed": "改动"}
|
|
119
|
+
_HOW = {"covers": "这一行在这个节点上", "nearest": "这一行不出节点,前面最近的节点是它", "definition": "定义",
|
|
120
|
+
"call_site": "调用处"}
|
|
121
|
+
_RUN_STATUS = {"ok": "通过", "tests_failed": "有失败的测试", "error": "出错", "timeout": "超时", "cancelled": "已取消"}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class ToolError(Exception):
|
|
125
|
+
"""工具没法给出结果:信息是给 AI 看的中文(说清怎么改参数)。mcp_server 把它变成 isError 的文本结果。"""
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
DEFAULT_WAIT = 120 # run_line_tests 默认最多等几秒
|
|
129
|
+
MAX_WAIT = 600
|
|
130
|
+
|
|
131
|
+
# ---------- 工具表 ----------
|
|
132
|
+
|
|
133
|
+
_PROJECT = {"type": "string", "description": "项目:项目 id、名字或目录(目录、文件在项目里面也算)。不给时用当前目录所在的项目"}
|
|
134
|
+
_FLOW = {"type": "string", "description": "功能线:sid(如 line:app/orders.py::place_order),或标题(完全相同的优先,其次片段,要唯一)"}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _spec(name: str, description: str, properties: dict, required: tuple[str, ...] = ()) -> dict:
|
|
138
|
+
schema: dict = {"type": "object", "properties": properties, "additionalProperties": False}
|
|
139
|
+
if required:
|
|
140
|
+
schema["required"] = list(required)
|
|
141
|
+
return {"name": name, "description": description, "inputSchema": schema}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
TOOL_SPECS: list[dict] = [
|
|
145
|
+
_spec("list_projects",
|
|
146
|
+
"列出 pystepmap 里已添加的项目:名字、id、目录、功能线条数、分析时间、代码在分析之后改过没有(图是否过期)、"
|
|
147
|
+
"有没有未看的流程变化。不知道项目叫什么、或想确认当前目录在不在某个项目里时先调它。", {}),
|
|
148
|
+
_spec("analyze_project",
|
|
149
|
+
"分析项目:目录没添加过就添加(第一次分析),添加过就重新分析。返回分析摘要和相对上一次分析的流程变化(还有更早"
|
|
150
|
+
"没看过的变化时另外说一句,用 diff_flows 看全部)。流程变化默认这样写:改动、删除的函数逐个列节点和连线;新增的"
|
|
151
|
+
"函数不逐个节点列——新功能线的入口函数写一行(各类节点的个数和结局的标题),它用到的新步骤、判断函数并成一行标题,"
|
|
152
|
+
"要看里面的节点用 get_flow。detail 可以改:"
|
|
153
|
+
"\"summary\" 每个函数都只写一行(只想确认成没成线、哪些线变了时用,最省字数),\"full\" 新增的函数也逐个节点列。"
|
|
154
|
+
"改完带标记的流程代码之后调它更新图;别的工具提示\"⚠ 代码已变更\"时也调它。不接受分析配置(配置只能在平台界面上改)。",
|
|
155
|
+
{"path": {"type": "string", "description": "项目目录(绝对路径,或相对当前目录);在已添加的项目里面时重新分析那个项目"},
|
|
156
|
+
"project": {**_PROJECT, "description": "已添加的项目(id、名字或目录),重新分析它;和 path 只给一个。都不给时重新分析"
|
|
157
|
+
"当前目录所在的项目;当前目录不在任何项目里时报错(不会自动添加,要添加就给 path)"},
|
|
158
|
+
"name": {"type": "string", "description": "添加时的项目名(默认是目录名);重新分析时不用"},
|
|
159
|
+
"detail": {"type": "string", "enum": ["normal", "summary", "full"], "default": "normal",
|
|
160
|
+
"description": "流程变化写多细:normal(默认)新增的函数只写一行,其余逐个节点列;summary 每个函数都只写"
|
|
161
|
+
"一行;full 全部逐个节点列"}}),
|
|
162
|
+
_spec("project_status",
|
|
163
|
+
"项目的自检报告:走不到的节点、没有出路的节点、目标不明 / 推测的调用、跳过的文件;以及代码在分析之后改了哪些文件、"
|
|
164
|
+
"涉及哪些功能线、有没有读不了的文件。怀疑图不准、或者想知道图是否过期时用。", {"project": _PROJECT}),
|
|
165
|
+
_spec("list_flows",
|
|
166
|
+
"按分组列出项目的功能线(业务流程):标题、sid、类型(接口 / 任务 / 工作流)、入口函数的文件和行号、有没有未看的"
|
|
167
|
+
"流程变化。要找某个业务流程的 sid 时先用它;query 按标题、分组、sid、文件名的片段筛选。",
|
|
168
|
+
{"project": _PROJECT,
|
|
169
|
+
"query": {"type": "string", "description": "筛选:标题、分组、sid 或入口函数文件名的片段(不分大小写)"},
|
|
170
|
+
"group": {"type": "string", "description": "只列这个分组(完整的分组名)"}}),
|
|
171
|
+
_spec("get_flow",
|
|
172
|
+
"取一条功能线的流程大纲:缩进文本,每个节点一行,带节点 sid 和行号,判断、循环的各条分支缩进写出,派发的任务各成"
|
|
173
|
+
"一段;或者 Mermaid 流程图。改业务逻辑之前先用它看清要改的地方在流程的哪一步。功能线很长时先用默认的 depth=0 "
|
|
174
|
+
"看全貌,再给 function 只看其中一个函数(行尾标着\"⇒ 可展开\"的那些)。depth 大到结果放不下时,自动退到放得下的"
|
|
175
|
+
"最大深度并在开头说明。flow 和 function 至少给一个:只给 function 时看项目里任何一个函数的流程,它不在功能线上也行。",
|
|
176
|
+
{"project": _PROJECT, "flow": {**_FLOW, "description": _FLOW["description"] + ";只看一个函数时可以不给"},
|
|
177
|
+
"function": {"type": "string",
|
|
178
|
+
"description": "只看这一个函数的大纲(函数 sid、限定名或函数名);给了 flow 时先在那条线上找,"
|
|
179
|
+
"不给 flow 时在整个项目里找"},
|
|
180
|
+
"depth": {"type": "integer", "minimum": 0, "maximum": MAX_DEPTH, "default": 0,
|
|
181
|
+
"description": "步骤调用的项目内函数在步骤下面展开几层(0~3,默认 0:只在行尾标\"⇒ 可展开\")"},
|
|
182
|
+
"format": {"type": "string", "enum": ["outline", "mermaid"], "default": "outline",
|
|
183
|
+
"description": "outline(缩进大纲,默认)或 mermaid(flowchart TD)"}},
|
|
184
|
+
()),
|
|
185
|
+
_spec("find_nodes",
|
|
186
|
+
"反查节点:给文件和行号(file + line),找这一行在哪个函数的哪个节点上、这个函数在哪些功能线上;或者给函数名"
|
|
187
|
+
"(function),找它的定义和所有调用处。改某段代码之前用它弄清这段代码属于哪条流程的哪一步。",
|
|
188
|
+
{"project": _PROJECT,
|
|
189
|
+
"file": {"type": "string", "description": "文件:相对项目根目录的路径,或项目里的绝对路径;和 line 一起给"},
|
|
190
|
+
"line": {"type": "integer", "minimum": 1, "description": "行号(从 1 起)"},
|
|
191
|
+
"function": {"type": "string", "description": "函数名、限定名(Class.method)或函数 sid;不和 file、line 一起给"}}),
|
|
192
|
+
_spec("paths_to_outcome",
|
|
193
|
+
"在一条功能线里找结局,列出怎么走到它:从功能线入口经过哪些函数(派发、调用)到结局所在的函数,再列出函数里经过"
|
|
194
|
+
"哪些判断的哪个分支(\"判断 X:是 → 判断 Y:否 → …\")。回答\"什么情况下会失败 / 会走到某个结局\"时用。"
|
|
195
|
+
"路径只按图上的连线走,不判断前后条件是否互相矛盾,可能含实际走不到的组合;转述前对照源码核对。",
|
|
196
|
+
{"project": _PROJECT, "flow": _FLOW,
|
|
197
|
+
"outcome": {"type": "string",
|
|
198
|
+
"description": "结局:结局节点的 sid、结局标题的片段,或 ok / skipped / failed / exception(按结局类型;"
|
|
199
|
+
"只算图上的结局节点,隐含的\"未捕获异常退出\"不列)"},
|
|
200
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": MAX_LIMIT, "default": DEFAULT_LIMIT,
|
|
201
|
+
"description": f"每个结局最多列几条路径(默认 {DEFAULT_LIMIT},最多 {MAX_LIMIT})"}},
|
|
202
|
+
("flow", "outcome")),
|
|
203
|
+
_spec("get_node",
|
|
204
|
+
"看一个节点的详情:标题、类型、文件和行号、节点前后各 3 行源码(带行号)、它的调用(目标和解析等级)、进出的连线、"
|
|
205
|
+
"所在的功能线。function、node 用 get_flow、find_nodes 输出里方括号中的 sid。",
|
|
206
|
+
{"project": _PROJECT,
|
|
207
|
+
"function": {"type": "string", "description": "函数 sid(如 app/orders.py::place_order)"},
|
|
208
|
+
"node": {"type": "string", "description": "节点 sid(如 step:1a2b3c4d、cond:…、end:…、start)"}},
|
|
209
|
+
("function", "node")),
|
|
210
|
+
_spec("diff_flows",
|
|
211
|
+
"最新一次分析相对对比基准的流程变化——对比基准是上次标为已看时(没标过就是第一次分析),所以是还没看过的全部"
|
|
212
|
+
"变化:哪些功能线、函数、节点、连线新增 / 删除 / 改动了,带文件和行号。改完代码、调过 analyze_project 之后,用它把流程"
|
|
213
|
+
"的变化写进给用户的回复。没有基准时说明原因(只有一次分析、变化已标为已看,或重新分析过流程没有变化)。",
|
|
214
|
+
{"project": _PROJECT, "flow": {**_FLOW, "description": "只看这条功能线(sid 或标题);不给时看全部"},
|
|
215
|
+
"record": {"type": "integer", "minimum": 1,
|
|
216
|
+
"description": "看一条以前的变更记录(用户在平台上标为已看时存下的那次变化)的明细;编号见不带 record "
|
|
217
|
+
"时结果末尾的\"变更记录\"列表"}}),
|
|
218
|
+
_spec("check",
|
|
219
|
+
"流程约束检查(SM001 编排函数只调用步骤、SM002 判断条件里不做计算、SM003 步骤不调用步骤、SM004 编排函数里不定义"
|
|
220
|
+
"内部函数),列出违规:规则号、文件、行、说明。改了带 pystepkit 标记的流程代码之后用它检查。只读;path 可以是没添加过的"
|
|
221
|
+
"目录(不能是用户主目录、根目录),项目里面的目录按项目的分析配置检查;在子进程里跑,超过 PYSTEPMAP_ANALYZE_TIMEOUT 秒中止。",
|
|
222
|
+
{"project": _PROJECT,
|
|
223
|
+
"path": {"type": "string", "description": "要检查的目录(可以是没添加过的;绝对路径或相对当前目录);和 project 只给一个"},
|
|
224
|
+
"files": {"type": "array", "items": {"type": "string"},
|
|
225
|
+
"description": "只报告这些文件里的违规(相对检查的目录)"}}),
|
|
226
|
+
_spec("uncovered_outcomes",
|
|
227
|
+
"最近一次在平台上跑完的测试里,没有任何测试走到的结局:按功能线分组,每个带结局节点 sid、所在函数、文件和行号;"
|
|
228
|
+
"运行之后代码改过、对不上的结局单独列出。想补测试、或者判断某个分支是不是根本没被测到时用它。只读:结果来自用户"
|
|
229
|
+
"在平台界面上启动的那次测试,本工具不跑测试;最近的结果比最新的分析旧时开头会提醒。",
|
|
230
|
+
{"project": _PROJECT, "flow": {**_FLOW, "description": "只看这条功能线(sid 或标题);不给时看全部"}}),
|
|
231
|
+
_spec("list_requirements",
|
|
232
|
+
"列出项目里的业务需求:项目目录下 .pystepmap/requirements/ 里的文件,以及项目用 OpenSpec 时 OpenSpec 文件"
|
|
233
|
+
"(openspec/changes/<变更>/ 和 openspec/specs/ 下的 Markdown)里的 ```flow 代码块。每条有编号、标题、状态、涉及的"
|
|
234
|
+
"功能线,以及设计的流程和代码现在的流程对不对得上。接到新需求、或者想知道某条需求做到哪一步时先调它。只读。",
|
|
235
|
+
{"project": _PROJECT}),
|
|
236
|
+
_spec("get_requirement",
|
|
237
|
+
"读一条需求并对照:说明、设计的流程(缩进文本)、这份设计画成图的平台地址(给用户看图用)、和代码现在的流程的差异(设计里有实现里没有的、实现里多出来的、"
|
|
238
|
+
"结局分类不一样的、走向不一致的)、设计的每个结局有没有测试走到、按对照结果现在够得上哪个状态。动手实现之前读它;"
|
|
239
|
+
"实现并调过 analyze_project 之后再读一次,把差异告诉用户。只读。",
|
|
240
|
+
{"project": _PROJECT,
|
|
241
|
+
"requirement": {"type": "string",
|
|
242
|
+
"description": "需求:编号(如 R003;OpenSpec 里的是变更名,如 add-manual-review),或标题的片段(要唯一)"}},
|
|
243
|
+
("requirement",)),
|
|
244
|
+
_spec("save_requirement",
|
|
245
|
+
"新建或整条改写一条需求,**写进项目目录**(.pystepmap/requirements/<编号>-<标题>.md;这是 pystepmap 的 MCP 里唯一写"
|
|
246
|
+
"项目文件的工具)。项目用 OpenSpec 管需求(有 openspec/ 目录)时不要用它:把设计的流程写成 OpenSpec 变更的 design.md 里"
|
|
247
|
+
"的一个 ```flow 代码块(块里第一行 `功能线:<功能线的标题>`,下面的写法相同),list_requirements / get_requirement "
|
|
248
|
+
"直接读它。不用 OpenSpec、接到业务需求时:先用 get_flow 看现在的流程,把改完之后的流程写成 flow,状态用\"草稿\"保存,"
|
|
249
|
+
"给用户看;用户确认后再用同一个编号保存成\"已确认\",然后才写代码。flow 的写法:每行一个节点,缩进表示从属——"
|
|
250
|
+
"`步骤:标题`(下面可以缩进 `失败时:` 再缩进写出错之后的内容)、`判断:标题`(下面缩进 `是:` / `否:`,各自再"
|
|
251
|
+
"缩进写内容)、`循环:标题`(下面缩进写循环体)、`结局(成功|跳过|失败):标题`。标题就是图上节点的中文标题:"
|
|
252
|
+
"步骤是 @step 的 title,判断是 @condition 的 title,结局是 outcome 的 title;入口函数成功的那条路不写 return 时"
|
|
253
|
+
"(没有返回内容的接口,比如 204 的删除),成功的结局写 `结局(成功):执行到函数末尾`。返回保存的文件、这份设计"
|
|
254
|
+
"画成图的平台地址(把它给用户:用户看图确认,不要只贴缩进文本)和对照结果。",
|
|
255
|
+
{"project": _PROJECT,
|
|
256
|
+
"title": {"type": "string", "description": "需求的标题(一句话)"},
|
|
257
|
+
"flow": {"type": "string", "description": "设计的流程(缩进文本,写法见工具说明)"},
|
|
258
|
+
"line": {"type": "string", "description": "涉及的功能线:标题或 sid;要新建的功能线写打算用的标题(@workflow 的 title)"},
|
|
259
|
+
"description": {"type": "string", "description": "业务上要什么、为什么(几句话)"},
|
|
260
|
+
"status": {"type": "string", "enum": ["草稿", "已确认", "已实现", "已完成"], "default": "草稿",
|
|
261
|
+
"description": "状态:草稿(等用户确认)、已确认、已实现(对照没有差异)、已完成(并且每个结局有测试走到)"},
|
|
262
|
+
"id": {"type": "string", "description": "要改写的需求的编号(如 R003);新建时不给,编号自动接着排"}},
|
|
263
|
+
("title", "flow")),
|
|
264
|
+
_spec("run_line_tests",
|
|
265
|
+
"请正在运行的 pystepmap 平台(pystepmap serve)**运行一条功能线的测试**,等它跑完,返回结果:通过 / 失败的测试、"
|
|
266
|
+
"图和实际执行是否一致、这条线上还有哪些结局没有被这些测试走到。只跑上一次全量运行里走过这条线的那些测试,用的是"
|
|
267
|
+
"用户在平台界面上填好并确认过的测试命令;会真的执行项目的测试(可能访问开发数据库等外部服务)。只有用户在平台的"
|
|
268
|
+
"测试命令设置里打开了\"允许 AI 运行单条功能线的测试\"的项目才能用;不能运行全部测试、不能改或确认测试命令。"
|
|
269
|
+
"实现或修改一条功能线之后,用它验证。平台没在运行、项目没开这个开关、还没有跑过全量测试时会说明原因。"
|
|
270
|
+
"start 为 false 时不启动,只看这条线最近一次的结果(或正在跑的进度)。",
|
|
271
|
+
{"project": _PROJECT, "flow": _FLOW,
|
|
272
|
+
"start": {"type": "boolean", "default": True, "description": "true(默认)启动一次运行;false 只看最近一次的结果"},
|
|
273
|
+
"wait_seconds": {"type": "integer", "minimum": 0, "maximum": MAX_WAIT, "default": DEFAULT_WAIT,
|
|
274
|
+
"description": f"最多等多少秒(默认 {DEFAULT_WAIT},最多 {MAX_WAIT});到时间还没跑完就先返回进度,"
|
|
275
|
+
"之后用 start=false 再看"}},
|
|
276
|
+
("flow",)),
|
|
277
|
+
]
|
|
278
|
+
|
|
279
|
+
_SPECS = {s["name"]: s for s in TOOL_SPECS}
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
# ---------- 文本的小工具 ----------
|
|
283
|
+
|
|
284
|
+
def _cap(text: str, hint: str) -> str:
|
|
285
|
+
"""结果不超过 MAX_CHARS 字:超出时在行边界截断,最后一行说省略了多少、怎么缩小范围。"""
|
|
286
|
+
if len(text) <= MAX_CHARS:
|
|
287
|
+
return text
|
|
288
|
+
budget = MAX_CHARS - len(hint) - 120 # 留给最后那行
|
|
289
|
+
cut = text.rfind("\n", 0, budget + 1)
|
|
290
|
+
if cut <= 0: # 一行就超了
|
|
291
|
+
cut = budget
|
|
292
|
+
kept = text[:cut]
|
|
293
|
+
rest = text[cut:].lstrip("\n")
|
|
294
|
+
rows = rest.count("\n") + 1 if rest else 0
|
|
295
|
+
tail = f"…(输出超过 {MAX_CHARS} 字,后面 {rows} 行、{len(rest)} 字没有列出。{hint})"
|
|
296
|
+
return f"{kept}\n{tail}"
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _capped(hint: str) -> Callable:
|
|
300
|
+
"""工具方法的结果按 _cap 截断;hint 说怎么缩小范围。"""
|
|
301
|
+
def wrap(fn: Callable[..., str]) -> Callable[..., str]:
|
|
302
|
+
@wraps(fn)
|
|
303
|
+
def inner(self: Tools, **kwargs: object) -> str:
|
|
304
|
+
return _cap(fn(self, **kwargs), hint)
|
|
305
|
+
return inner
|
|
306
|
+
return wrap
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _when(iso: str | None) -> str:
|
|
310
|
+
"""库里的 UTC 时间写成本机时间。"""
|
|
311
|
+
if not iso:
|
|
312
|
+
return "时间不明"
|
|
313
|
+
try:
|
|
314
|
+
return datetime.fromisoformat(iso).astimezone().strftime("%Y-%m-%d %H:%M")
|
|
315
|
+
except ValueError:
|
|
316
|
+
return iso
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def fn_label(fg: FunctionGraph, *, titled: bool = False) -> str:
|
|
320
|
+
"""函数一行:种类 限定名(路由) 文件:def 行 [函数 sid]——和大纲的函数头同样的写法,种类多分出步骤、判断函数。
|
|
321
|
+
titled 时限定名后面再写「函数的标题」(标题就是函数名时不写)。"""
|
|
322
|
+
name = fg.qualname + (f"({fg.route})" if fg.route else "")
|
|
323
|
+
title = fg.title_full or fg.title
|
|
324
|
+
if titled and title and title not in (fg.qualname, fg.qualname.rsplit(".", 1)[-1]):
|
|
325
|
+
name += f"「{title}」"
|
|
326
|
+
return f"{_FN_KIND.get(fg.kind, '函数')} {name} {fg.file}:{fg.line} [{fg.sid or fg.key}]"
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def node_line(fg: FunctionGraph, node: Node) -> str:
|
|
330
|
+
"""节点一行:[节点 sid] L行号 文字——和大纲的节点行同样的写法。"""
|
|
331
|
+
return f"{node_ref(fg, node)} " + (f"L{node.line} " if node.line else "") + node_text(node)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _no_line(cmp: rq.Comparison) -> rq.Difference | None:
|
|
335
|
+
"""对照时图上找不到这条需求的功能线(还没有实现,或者名字对不上):那一条说明;找到了时 None。"""
|
|
336
|
+
return next((d for d in cmp.differences if d.kind == "no_line"), None)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _verdict(cmp: rq.Comparison) -> str:
|
|
340
|
+
"""一条需求的对照结果一句话,和界面上的标记同一个口径:对得上 / 找不到功能线 / 有几处不一致。找不到功能线时
|
|
341
|
+
设计的每个节点都记了一条"还没有实现"(Comparison.differences),不把它们数成"几处不一致"。"""
|
|
342
|
+
if cmp.matches:
|
|
343
|
+
return "设计和实现对得上"
|
|
344
|
+
no_line = _no_line(cmp)
|
|
345
|
+
if no_line is not None:
|
|
346
|
+
n = len(cmp.differences) - 1
|
|
347
|
+
return no_line.text + (f";设计的 {n} 个节点都还没有实现" if n else "")
|
|
348
|
+
return f"和实现有 {len(cmp.differences)} 处不一致"
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _summary_text(s: dict) -> str:
|
|
352
|
+
blind = s.get("unresolved_blind") # 旧的分析没有记这一项:只写总数
|
|
353
|
+
text = (f"分析摘要:函数 {s.get('functions', 0)} 个,功能线 {s.get('lines', 0)} 条,公共任务 {s.get('common_tasks', 0)} 个;"
|
|
354
|
+
f"推测的调用 {s.get('guessed_calls', 0)} 处,目标不明的调用 {s.get('unresolved_calls', 0)} 处"
|
|
355
|
+
+ (f"(可能落在项目代码上的 {blind} 处)" if blind is not None else "") + ";"
|
|
356
|
+
f"跳过的文件 {len(s.get('skipped_files') or [])} 个;走不到的节点 {s.get('unreachable', 0)} 个,"
|
|
357
|
+
f"没有出路的节点 {s.get('dead_ends', 0)} 个;用时 {s.get('seconds', 0)} 秒。")
|
|
358
|
+
notes = s.get("entry_notes")
|
|
359
|
+
text += "".join(f"\n{n}" for n in s.get("unlisted_notes") or [])
|
|
360
|
+
text += "".join(f"\n⚠ {n}" for n in (s.get("mark_notes") or [])[:MAX_ITEMS])
|
|
361
|
+
if notes:
|
|
362
|
+
text += "".join(f"\n{n}" for n in notes)
|
|
363
|
+
elif notes is None and s.get("has_entries") is False: # 旧的分析没有记 entry_notes
|
|
364
|
+
text += "\n没有识别到入口(路由、任务、工作流):功能线是空的;可以在平台界面上改分析配置(extra_entries)。"
|
|
365
|
+
return text
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _edge_word(src: Node, e: Edge | PathStep) -> str:
|
|
369
|
+
"""一条连线怎么走:判断节点的分支写 是 / 否 / `模式` / 都不匹配(continue、break 另注),其余按 kind。"""
|
|
370
|
+
if src.type != "cond" or e.kind == "raise":
|
|
371
|
+
return _KIND_WORD.get(e.kind, e.kind)
|
|
372
|
+
which = e.branch or {"yes": "yes", "no": "no"}.get(e.kind, "")
|
|
373
|
+
if which in ("yes", "no"):
|
|
374
|
+
word = "是" if which == "yes" else "否"
|
|
375
|
+
elif which == "else" or (not which and e.label == "都不匹配"):
|
|
376
|
+
word = "都不匹配"
|
|
377
|
+
elif which or e.label:
|
|
378
|
+
word = f"`{e.label or which}`"
|
|
379
|
+
else:
|
|
380
|
+
return _KIND_WORD.get(e.kind, e.kind)
|
|
381
|
+
if e.kind in ("break", "loop_back", "finally"):
|
|
382
|
+
word += f"({_KIND_WORD[e.kind]})"
|
|
383
|
+
return word
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _path_text(fg: FunctionGraph, steps: list[PathStep]) -> str:
|
|
387
|
+
"""函数里的一条路径写成"判断 X:是 → 循环 Y:每次 → … → 结局":只写判断、循环、捕获、出错和跳转,顺序走过的步骤不写。"""
|
|
388
|
+
nodes = {n.id: n for n in fg.nodes}
|
|
389
|
+
words: list[str] = []
|
|
390
|
+
for s in steps[:-1]:
|
|
391
|
+
n = nodes[s.node]
|
|
392
|
+
if s.kind == "raise":
|
|
393
|
+
words.append(f"{node_text(n)} 出错")
|
|
394
|
+
elif n.type in ("cond", "loop"):
|
|
395
|
+
words.append(f"{node_text(n)}:{_edge_word(n, s)}")
|
|
396
|
+
elif n.type == "catch":
|
|
397
|
+
words.append(node_text(n))
|
|
398
|
+
elif s.kind in ("break", "finally") or (s.kind == "loop_back" and (s.branch or s.label)):
|
|
399
|
+
words.append(_KIND_WORD[s.kind])
|
|
400
|
+
end = node_text(nodes[steps[-1].node])
|
|
401
|
+
return " → ".join(words + [end]) if words else f"不经过任何判断 → {end}"
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _size(rows: list[str]) -> int:
|
|
405
|
+
"""这些行接在已有的行后面(每行前面一个换行符)占多少字。"""
|
|
406
|
+
return sum(len(r) + 1 for r in rows)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _fit(rows: list[str], room: int) -> list[str]:
|
|
410
|
+
"""从前往后留下放得进 room 字的行;一行就放不下时截这一行。"""
|
|
411
|
+
out: list[str] = []
|
|
412
|
+
for r in rows:
|
|
413
|
+
if _size(out) + len(r) + 1 > room:
|
|
414
|
+
left = room - _size(out) - 1
|
|
415
|
+
if left > 0:
|
|
416
|
+
out.append(r[:left])
|
|
417
|
+
break
|
|
418
|
+
out.append(r)
|
|
419
|
+
return out
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _names_root(g: ProjectGraph, line: FlowLine, name: str) -> bool:
|
|
423
|
+
"""name 是这条线根函数的名字、限定名、函数 sid 或 key。"""
|
|
424
|
+
fg = g.functions.get(line.root.function)
|
|
425
|
+
return fg is not None and name in (fg.qualname, fg.qualname.rsplit(".", 1)[-1], fg.sid, fg.key)
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _tasks(task: LineTask) -> list[str]:
|
|
429
|
+
"""派发树上的任务 key,先序,不重复。"""
|
|
430
|
+
out: dict[str, None] = {}
|
|
431
|
+
stack = [task]
|
|
432
|
+
while stack:
|
|
433
|
+
t = stack.pop()
|
|
434
|
+
out[t.function] = None
|
|
435
|
+
stack.extend(reversed(t.children))
|
|
436
|
+
return list(out)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _containing(projects: list[dict], path: Path) -> dict | None:
|
|
440
|
+
"""path(解析过的绝对路径)所在的项目:就是项目根目录或在它里面。先按路径字符串比;比不上时按 inode 比(大小写
|
|
441
|
+
不敏感的文件系统上写法不同的同一个目录),这时根目录已经不是添加时那个真实目录的项目不参与(顺着换上的链接比会
|
|
442
|
+
误判,见 flows._overlap_with)。项目之间不会嵌套,最多一个。"""
|
|
443
|
+
text = str(path)
|
|
444
|
+
for p in projects:
|
|
445
|
+
root = p["root"]
|
|
446
|
+
if text == root or text.startswith(root.rstrip(os.sep) + os.sep):
|
|
447
|
+
return p
|
|
448
|
+
ids = {i for i in (identity(path), *(identity(x) for x in path.parents)) if i is not None}
|
|
449
|
+
for p in projects:
|
|
450
|
+
if root_problem(p["root"]) is None and identity(p["root"]) in ids:
|
|
451
|
+
return p
|
|
452
|
+
return None
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
# ---------- 一次调用读到的东西 ----------
|
|
456
|
+
|
|
457
|
+
@dataclass
|
|
458
|
+
class _View:
|
|
459
|
+
"""读图的工具一次调用用到的:项目、最新一次分析、图、手工改的标题分组、过期检查的结果(每次调用只算一次)。"""
|
|
460
|
+
|
|
461
|
+
project: dict
|
|
462
|
+
analysis: dict
|
|
463
|
+
graph: ProjectGraph
|
|
464
|
+
overrides: dict[str, dict]
|
|
465
|
+
stale: dict
|
|
466
|
+
|
|
467
|
+
def sid(self, line: FlowLine) -> str:
|
|
468
|
+
return line.sid or line.id
|
|
469
|
+
|
|
470
|
+
def title(self, line: FlowLine) -> str:
|
|
471
|
+
return self.overrides.get(self.sid(line), {}).get("title") or line.title_full or line.title
|
|
472
|
+
|
|
473
|
+
def group(self, line: FlowLine) -> str:
|
|
474
|
+
return self.overrides.get(self.sid(line), {}).get("group") or line.group
|
|
475
|
+
|
|
476
|
+
def titles(self, line: FlowLine) -> list[str]:
|
|
477
|
+
"""这条线认的标题:改过的、原来的完整标题、原来的显示标题。"""
|
|
478
|
+
return list(dict.fromkeys(t for t in (self.title(line), line.title_full, line.title) if t))
|
|
479
|
+
|
|
480
|
+
def ref(self, line: FlowLine) -> str:
|
|
481
|
+
return f"{self.title(line)} [{self.sid(line)}]"
|
|
482
|
+
|
|
483
|
+
def row(self, line: FlowLine) -> str:
|
|
484
|
+
return f"{self.title(line)} [{self.sid(line)}] 分组:{self.group(line)}"
|
|
485
|
+
|
|
486
|
+
def by_sid(self, sid: str) -> FlowLine | None:
|
|
487
|
+
return next((ln for ln in self.graph.lines if self.sid(ln) == sid), None)
|
|
488
|
+
|
|
489
|
+
def by_ids(self, ids: list[str] | tuple[str, ...]) -> list[FlowLine]:
|
|
490
|
+
"""功能线 id(根函数 key,可能重复)对应的线,按图里的顺序,不重复。"""
|
|
491
|
+
wanted = set(ids)
|
|
492
|
+
return [ln for ln in self.graph.lines if ln.id in wanted]
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
class Tools:
|
|
496
|
+
"""pystepmap mcp 的十五个工具。store 是平台的库(和 pystepmap serve 共用一个数据目录);cwd 是 MCP 进程的当前目录(不给
|
|
497
|
+
project 时用它找项目)。每个工具一个方法,参数全是关键字参数,返回给 AI 读的文本;没法给出结果时抛 ToolError。
|
|
498
|
+
可以在多个线程里同时调用(缓存有锁)。"""
|
|
499
|
+
|
|
500
|
+
def __init__(self, store: Store, cwd: Path | None):
|
|
501
|
+
self.store = store
|
|
502
|
+
self.cwd = Path(os.path.realpath(cwd)) if cwd is not None else None
|
|
503
|
+
self._graphs: OrderedDict[int, ProjectGraph] = OrderedDict()
|
|
504
|
+
self._facts_cache = FactsCache(store, FACTS_CACHE)
|
|
505
|
+
self._uncovered: OrderedDict[tuple[int, int], Uncovered] = OrderedDict() # (分析,运行)→ 算好的结果
|
|
506
|
+
self._lock = threading.Lock()
|
|
507
|
+
self._analysing: set[str] = set() # 这个进程里正在重新分析的项目 id
|
|
508
|
+
|
|
509
|
+
# ---------- 按名字调用 ----------
|
|
510
|
+
|
|
511
|
+
def call(self, name: str, arguments: dict | None) -> str:
|
|
512
|
+
"""按工具名调用,先按 TOOL_SPECS 检查参数(不认识的、缺的、类型不对的都是 ToolError)。空字符串等于没给。"""
|
|
513
|
+
spec = _SPECS.get(name)
|
|
514
|
+
if spec is None:
|
|
515
|
+
raise ToolError(f"没有这个工具:{name}(有:{'、'.join(_SPECS)})")
|
|
516
|
+
arguments = {} if arguments is None else arguments
|
|
517
|
+
if not isinstance(arguments, dict):
|
|
518
|
+
raise ToolError("参数应该是一个 JSON 对象")
|
|
519
|
+
props = spec["inputSchema"]["properties"]
|
|
520
|
+
unknown = sorted(set(arguments) - set(props))
|
|
521
|
+
if unknown:
|
|
522
|
+
raise ToolError(f"不认识的参数:{'、'.join(unknown)}({name} 的参数:{'、'.join(props) or '无'})")
|
|
523
|
+
kwargs = {}
|
|
524
|
+
for key, value in arguments.items():
|
|
525
|
+
value = _coerce(key, props[key], value)
|
|
526
|
+
if value is not None:
|
|
527
|
+
kwargs[key] = value
|
|
528
|
+
missing = [k for k in spec["inputSchema"].get("required", []) if k not in kwargs]
|
|
529
|
+
if missing:
|
|
530
|
+
raise ToolError(f"缺少参数:{'、'.join(missing)}")
|
|
531
|
+
# 这个进程跑的是旧代码时(磁盘上的代码在启动之后更新过),每个工具的结果最前面都说一句:分析在子进程里跑、用的是
|
|
532
|
+
# 新代码,光看分析的引擎标识看不出这个进程是旧的
|
|
533
|
+
old = procinfo.stale_warning()
|
|
534
|
+
return (old + "\n\n" if old else "") + getattr(self, name)(**kwargs)
|
|
535
|
+
|
|
536
|
+
# ---------- 项目、图 ----------
|
|
537
|
+
|
|
538
|
+
def _abs(self, text: str, *, resolve: bool = True) -> Path | None:
|
|
539
|
+
"""用户给的路径:展开 ~,相对路径按当前目录算;resolve 时再解析符号链接。不合法时 None。"""
|
|
540
|
+
if "\0" in text:
|
|
541
|
+
return None
|
|
542
|
+
try:
|
|
543
|
+
path = Path(text).expanduser()
|
|
544
|
+
if not path.is_absolute():
|
|
545
|
+
if self.cwd is None:
|
|
546
|
+
return None
|
|
547
|
+
path = self.cwd / path
|
|
548
|
+
return Path(os.path.realpath(path)) if resolve else Path(os.path.normpath(path))
|
|
549
|
+
except (OSError, ValueError, RuntimeError):
|
|
550
|
+
return None
|
|
551
|
+
|
|
552
|
+
def _known(self, projects: list[dict]) -> str:
|
|
553
|
+
if not projects:
|
|
554
|
+
return "还没有添加任何项目:用 analyze_project(path 给项目目录)添加。"
|
|
555
|
+
rows = [f"- {p['name']} [id {p['id']}] {p['root']}" for p in projects]
|
|
556
|
+
return "已添加的项目:\n" + "\n".join(rows) + \
|
|
557
|
+
"\n用 project 参数指定(id、名字或目录);要添加新项目,用 analyze_project 给出目录(path)。"
|
|
558
|
+
|
|
559
|
+
def _project(self, ref: str | None, projects: list[dict] | None = None) -> dict:
|
|
560
|
+
"""按 id、名字、目录(或当前目录)找项目,返回 Store.list_projects 的一项(带最新一次分析的信息)。"""
|
|
561
|
+
projects = self.store.list_projects() if projects is None else projects
|
|
562
|
+
if ref is None:
|
|
563
|
+
found = _containing(projects, self.cwd) if self.cwd is not None else None
|
|
564
|
+
if found is None:
|
|
565
|
+
raise ToolError(f"当前目录({self.cwd})不在任何已添加的项目里。{self._known(projects)}")
|
|
566
|
+
return found
|
|
567
|
+
for p in projects:
|
|
568
|
+
if p["id"] == ref:
|
|
569
|
+
return p
|
|
570
|
+
named = [p for p in projects if p["name"] == ref]
|
|
571
|
+
if len(named) == 1:
|
|
572
|
+
return named[0]
|
|
573
|
+
if named:
|
|
574
|
+
rows = "\n".join(f"- {p['name']} [id {p['id']}] {p['root']}" for p in named)
|
|
575
|
+
raise ToolError(f"有 {len(named)} 个项目都叫「{ref}」,请用 id 指定:\n{rows}")
|
|
576
|
+
path = self._abs(ref)
|
|
577
|
+
# 路径要真的存在:写错的名字("abacuss")按相对路径算总落在当前目录的项目里,不能悄悄用它
|
|
578
|
+
found = _containing(projects, path) if path is not None and path.exists() else None
|
|
579
|
+
if found is None:
|
|
580
|
+
raise ToolError(f"找不到项目「{ref}」:不是项目的 id、名字,也不在哪个项目的目录里。{self._known(projects)}")
|
|
581
|
+
return found
|
|
582
|
+
|
|
583
|
+
def _graph(self, analysis_id: int) -> ProjectGraph | None:
|
|
584
|
+
with self._lock:
|
|
585
|
+
if analysis_id in self._graphs:
|
|
586
|
+
self._graphs.move_to_end(analysis_id)
|
|
587
|
+
return self._graphs[analysis_id]
|
|
588
|
+
text = self.store.graph_json(analysis_id)
|
|
589
|
+
if text is None: # 刚被清理掉了
|
|
590
|
+
return None
|
|
591
|
+
graph = from_json(text)
|
|
592
|
+
with self._lock:
|
|
593
|
+
self._graphs[analysis_id] = graph
|
|
594
|
+
while len(self._graphs) > GRAPH_CACHE:
|
|
595
|
+
self._graphs.popitem(last=False)
|
|
596
|
+
return graph
|
|
597
|
+
|
|
598
|
+
def _staleness(self, project: dict, analysis_id: int, graph: ProjectGraph | None = None) -> dict:
|
|
599
|
+
if graph is None:
|
|
600
|
+
with self._lock:
|
|
601
|
+
graph = self._graphs.get(analysis_id) # 已经解析过的图:不用再解析一次图 JSON
|
|
602
|
+
facts = self._facts_cache.get(analysis_id, graph)
|
|
603
|
+
if facts is None:
|
|
604
|
+
return {"checked": False, "reason": "这次分析刚被清理掉了"}
|
|
605
|
+
config = facts.config if facts.config is not None else project["config"]
|
|
606
|
+
return staleness(project["root"], config, facts.hashes, facts.file_lines)
|
|
607
|
+
|
|
608
|
+
def _view(self, ref: str | None) -> _View:
|
|
609
|
+
p = self._project(ref)
|
|
610
|
+
analysis = p["analysis"]
|
|
611
|
+
for _ in range(3): # 最新一次在取图之前被别的进程清理掉了(极少见):重新取最新的
|
|
612
|
+
if analysis is None:
|
|
613
|
+
raise ToolError(f"项目「{p['name']}」还没有分析结果:先调用 analyze_project")
|
|
614
|
+
graph = self._graph(analysis["id"])
|
|
615
|
+
if graph is not None:
|
|
616
|
+
break
|
|
617
|
+
analysis = self.store.latest_analysis(p["id"])
|
|
618
|
+
else:
|
|
619
|
+
raise ToolError("分析结果刚被更新,请再调用一次")
|
|
620
|
+
return _View(p, analysis, graph, self.store.get_overrides(p["id"]),
|
|
621
|
+
self._staleness(p, analysis["id"], graph))
|
|
622
|
+
|
|
623
|
+
def _warning(self, v: _View) -> str:
|
|
624
|
+
"""读图的工具结果最前面的一段:图过期时说改了几个文件、涉及哪些功能线;没法检查时说原因。"""
|
|
625
|
+
st = v.stale
|
|
626
|
+
if not st.get("checked"):
|
|
627
|
+
return f"⚠ 没法检查代码在分析之后有没有改过:{st.get('reason', '')}\n\n"
|
|
628
|
+
if not st["stale"]:
|
|
629
|
+
return ""
|
|
630
|
+
t = st["total"]
|
|
631
|
+
sids = st["lines"]
|
|
632
|
+
if sids is None:
|
|
633
|
+
involved = "不清楚(这次分析是旧版本存的,没有记下功能线涉及的文件)"
|
|
634
|
+
elif not sids:
|
|
635
|
+
involved = "无(改动的文件不在任何功能线上)"
|
|
636
|
+
else:
|
|
637
|
+
refs = [v.ref(ln) if (ln := v.by_sid(s)) is not None else s for s in sids[:MAX_LINE_REFS]]
|
|
638
|
+
involved = "、".join(refs) + (f" 等 {len(sids)} 条" if len(sids) > MAX_LINE_REFS else "")
|
|
639
|
+
return (f"⚠ 代码已变更(改 {t['changed']}、增 {t['added']}、删 {t['removed']} 个文件),图可能过期。"
|
|
640
|
+
f"涉及功能线:{involved}。先调用 analyze_project 重新分析。\n\n")
|
|
641
|
+
|
|
642
|
+
def _line(self, v: _View, flow: str) -> FlowLine:
|
|
643
|
+
"""按顺序找功能线,要唯一:sid(或 id)→ 完全相同的标题 → 根函数(名字、限定名、函数 sid,或 sid 的结尾一段,
|
|
644
|
+
如 create_job、finetune.py::create_job)→ 标题的片段。都没有时 ToolError,列出 sid 里含它的功能线。"""
|
|
645
|
+
lines = v.graph.lines
|
|
646
|
+
needle = flow.casefold()
|
|
647
|
+
rules = (lambda ln: flow in (v.sid(ln), ln.id),
|
|
648
|
+
lambda ln: flow in v.titles(ln),
|
|
649
|
+
lambda ln: _names_root(v.graph, ln, flow) or any(v.sid(ln).endswith(sep + flow) for sep in ("/", ":")),
|
|
650
|
+
lambda ln: any(needle in t.casefold() for t in v.titles(ln)))
|
|
651
|
+
hits: list[FlowLine] = []
|
|
652
|
+
for rule in rules:
|
|
653
|
+
hits = [ln for ln in lines if rule(ln)]
|
|
654
|
+
if hits:
|
|
655
|
+
break
|
|
656
|
+
if len(hits) == 1:
|
|
657
|
+
return hits[0]
|
|
658
|
+
if not hits:
|
|
659
|
+
near = [ln for ln in lines if needle in v.sid(ln).casefold()]
|
|
660
|
+
listed = "".join(f"\n- {v.row(ln)}" for ln in near[:MAX_HITS])
|
|
661
|
+
more = f"\n…还有 {len(near) - MAX_HITS} 条" if len(near) > MAX_HITS else ""
|
|
662
|
+
hint = f"sid 里含「{flow}」的功能线:{listed}{more}" if near else "用 list_flows 看有哪些(可以用 query 筛选)。"
|
|
663
|
+
raise ToolError(f"没有这条功能线:「{flow}」(不是 sid、标题、标题的片段,也不是功能线入口函数的名字)。{hint}")
|
|
664
|
+
rows = "\n".join(f"- {v.row(ln)}" for ln in hits[:MAX_HITS])
|
|
665
|
+
more = f"\n…还有 {len(hits) - MAX_HITS} 条" if len(hits) > MAX_HITS else ""
|
|
666
|
+
raise ToolError(f"「{flow}」对应 {len(hits)} 条功能线,请用 sid 指定:\n{rows}{more}")
|
|
667
|
+
|
|
668
|
+
def _line_rows(self, v: _View, ids: list[str] | tuple[str, ...], indent: str, chain_to: str | None = None) -> list[str]:
|
|
669
|
+
"""功能线一行一条,最多 MAX_LINE_ROWS 条;chain_to(函数 key)给出时前 MAX_CHAINS 条线下面各写一行从入口到这个
|
|
670
|
+
函数的调用链(get_settings 这种到处用的函数,每条线一行链会有几万字)。"""
|
|
671
|
+
lines = v.by_ids(ids)
|
|
672
|
+
if not lines:
|
|
673
|
+
return [f"{indent}不在任何功能线上(没有入口能走到这个函数)"]
|
|
674
|
+
out = []
|
|
675
|
+
for i, ln in enumerate(lines[:MAX_LINE_ROWS]):
|
|
676
|
+
out.append(f"{indent}- {v.row(ln)}")
|
|
677
|
+
if chain_to is not None and i < MAX_CHAINS:
|
|
678
|
+
out.append(f"{indent} 入口链:{_chain_text(v.graph, ln, chain_to)}")
|
|
679
|
+
if len(lines) > MAX_LINE_ROWS:
|
|
680
|
+
out.append(f"{indent}…还有 {len(lines) - MAX_LINE_ROWS} 条功能线(用 list_flows / get_flow 看)")
|
|
681
|
+
if chain_to is not None:
|
|
682
|
+
out.append(f"{indent}(入口链是从入口到这里最短的一条,可能还有别的走法:对链上的函数用 find_nodes 的 function "
|
|
683
|
+
"看它的全部调用、派发处)")
|
|
684
|
+
if chain_to is not None and len(lines) > MAX_CHAINS:
|
|
685
|
+
out.append(f"{indent}(入口链只写了前 {MAX_CHAINS} 条功能线的,别的用 get_flow 看)")
|
|
686
|
+
return out
|
|
687
|
+
|
|
688
|
+
# ---------- list_projects ----------
|
|
689
|
+
|
|
690
|
+
@_capped("项目太多:用 project 参数直接指定要用的项目")
|
|
691
|
+
def list_projects(self) -> str:
|
|
692
|
+
"""列出已添加的项目"""
|
|
693
|
+
projects = self.store.list_projects()
|
|
694
|
+
if not projects:
|
|
695
|
+
return "还没有添加项目。用 analyze_project(path 给项目目录)添加一个。"
|
|
696
|
+
here = _containing(projects, self.cwd) if self.cwd is not None else None
|
|
697
|
+
out = [f"共 {len(projects)} 个项目:"]
|
|
698
|
+
for p in projects:
|
|
699
|
+
mark = "(当前目录在这个项目里)" if here is not None and here["id"] == p["id"] else ""
|
|
700
|
+
out.append(f"- {p['name']} [id {p['id']}]{mark} 目录 {p['root']}")
|
|
701
|
+
a = p["analysis"]
|
|
702
|
+
if a is None:
|
|
703
|
+
out.append(" 还没有分析结果")
|
|
704
|
+
continue
|
|
705
|
+
s = a["summary"]
|
|
706
|
+
out.append(f" 功能线 {s.get('lines', 0)} 条,函数 {s.get('functions', 0)} 个;"
|
|
707
|
+
f"分析于 {_when(a['created_at'])}(分析 #{a['id']})")
|
|
708
|
+
st = self._staleness(p, a["id"])
|
|
709
|
+
if not st.get("checked"):
|
|
710
|
+
out.append(f" 没法检查是否过期:{st.get('reason', '')}")
|
|
711
|
+
elif st["stale"]:
|
|
712
|
+
t = st["total"]
|
|
713
|
+
out.append(f" 已过期(改 {t['changed']}、增 {t['added']}、删 {t['removed']} 个文件):先调用 analyze_project 重新分析")
|
|
714
|
+
else:
|
|
715
|
+
out.append(" 未过期:代码在分析之后没有改过")
|
|
716
|
+
out.append(" 有未看的流程变化(diff_flows 查看)" if a["has_diff"] else " 没有未看的流程变化")
|
|
717
|
+
if is_analyzing(self.store, p["id"]):
|
|
718
|
+
out.append(" 正在分析或正在跑测试(平台界面上点的)")
|
|
719
|
+
return "\n".join(out)
|
|
720
|
+
|
|
721
|
+
# ---------- analyze_project ----------
|
|
722
|
+
|
|
723
|
+
@_capped("流程变化太多:用 diff_flows 的 flow 参数一条一条看")
|
|
724
|
+
def analyze_project(self, *, path: str | None = None, project: str | None = None, name: str | None = None,
|
|
725
|
+
detail: str = "normal") -> str:
|
|
726
|
+
"""分析(或重新分析)一个项目"""
|
|
727
|
+
if detail not in ("normal", "summary", "full"):
|
|
728
|
+
raise ToolError(f"detail 要是 normal、summary、full 之一,不是 {detail!r}")
|
|
729
|
+
if path is not None and project is not None:
|
|
730
|
+
raise ToolError("path 和 project 只给一个:path 是目录(没添加过就添加),project 是已添加的项目(重新分析)")
|
|
731
|
+
projects = self.store.list_projects()
|
|
732
|
+
if project is not None:
|
|
733
|
+
return self._reanalyze(self._project(project, projects), name, detail)
|
|
734
|
+
where = self._abs(path) if path is not None else self.cwd
|
|
735
|
+
if where is None:
|
|
736
|
+
raise ToolError(f"目录路径不合法:{path}" if path is not None else "不知道当前目录:请用 path 给出项目目录")
|
|
737
|
+
target = _containing(projects, where)
|
|
738
|
+
if target is None and path is None: # 不把当前目录悄悄添加成项目:要添加就明说 path
|
|
739
|
+
raise ToolError(f"没有指定要分析的目录:给 path(要添加的代码目录)或 project(已添加的项目)。"
|
|
740
|
+
f"当前目录({where})不在任何已添加的项目里。{self._known(projects)}")
|
|
741
|
+
if target is not None:
|
|
742
|
+
out = self._reanalyze(target, name, detail)
|
|
743
|
+
if path is not None and str(where) != target["root"]:
|
|
744
|
+
out += f"\n({path} 在项目「{target['name']}」里面,重新分析的是整个项目 {target['root']})"
|
|
745
|
+
return out
|
|
746
|
+
return self._add(str(self._abs(path, resolve=False)), name)
|
|
747
|
+
|
|
748
|
+
def _add(self, root: str, name: str | None) -> str:
|
|
749
|
+
result = add_project(self.store, root, name, None)
|
|
750
|
+
if result["kind"] != "ok":
|
|
751
|
+
raise ToolError(result["reason"])
|
|
752
|
+
p = self.store.get_project(result["project_id"]) or {"name": name or root, "id": result["project_id"], "root": root}
|
|
753
|
+
return "\n".join([
|
|
754
|
+
f"已添加项目「{p['name']}」[id {p['id']}],目录 {p['root']}(分析 #{result['analysis_id']})。",
|
|
755
|
+
_summary_text(result["summary"]),
|
|
756
|
+
"这是第一次分析,没有可比的上一次。用 list_flows 看它的功能线。"])
|
|
757
|
+
|
|
758
|
+
def _reanalyze(self, p: dict, name: str | None, detail: str = "normal") -> str:
|
|
759
|
+
with self._lock: # 客户端取消了的 analyze_project 还在后台跑(工作线程不能中途停):是自己这次没结束
|
|
760
|
+
mine = p["id"] in self._analysing
|
|
761
|
+
self._analysing.add(p["id"])
|
|
762
|
+
if mine:
|
|
763
|
+
raise ToolError("这个项目正在分析(上一次 analyze_project 调用还没结束),稍后再试")
|
|
764
|
+
try:
|
|
765
|
+
before = self.store.latest_analysis(p["id"])
|
|
766
|
+
before_extra = {} if before is None else (self.store.analysis_extra(before["id"]) or {})
|
|
767
|
+
before_sha, before_diff = before_extra.get("graph_sha"), before_extra.get("diff")
|
|
768
|
+
result = reanalyze_project(self.store, p["id"])
|
|
769
|
+
finally:
|
|
770
|
+
with self._lock:
|
|
771
|
+
self._analysing.discard(p["id"])
|
|
772
|
+
if result["kind"] != "ok":
|
|
773
|
+
if result.get("code") == "busy":
|
|
774
|
+
raise ToolError(BUSY_ELSEWHERE)
|
|
775
|
+
raise ToolError(result["reason"])
|
|
776
|
+
aid = result["analysis_id"]
|
|
777
|
+
extra = self.store.analysis_extra(aid) or {}
|
|
778
|
+
head = f"已重新分析项目「{p['name']}」[id {p['id']}](分析 #{aid})。"
|
|
779
|
+
if name:
|
|
780
|
+
head += "(name 只在添加项目时用,这次是重新分析,没有改名)"
|
|
781
|
+
out = [head, _summary_text(result["summary"])]
|
|
782
|
+
out += _newly_skipped(before, result["summary"])
|
|
783
|
+
if before is None:
|
|
784
|
+
out.append("相对上一次:没有上一次分析。")
|
|
785
|
+
return "\n".join(out)
|
|
786
|
+
same = bool(before_sha) and before_sha == extra.get("graph_sha")
|
|
787
|
+
delta = None if same else self._delta(before["id"], aid)
|
|
788
|
+
earlier = before_diff is not None # 上一次分析时就有没看的变化(对比基准只在标为已看时移动,它们还在)
|
|
789
|
+
if not same and delta is None:
|
|
790
|
+
out.append("相对上一次:这次没能和上一次比较(比较时出错,日志在标准错误里),流程有没有变化说不准;"
|
|
791
|
+
"这次的分析照常存好了。")
|
|
792
|
+
elif same or delta.empty:
|
|
793
|
+
why = "和上一次分析出的图完全相同" if same else "改的是格式、注释或流程以外的代码"
|
|
794
|
+
out.append(f"相对上一次:流程没有变化({why})。")
|
|
795
|
+
if extra.get("diff") is not None:
|
|
796
|
+
out.append("之前还有没看的流程变化:用 diff_flows 查看。")
|
|
797
|
+
else:
|
|
798
|
+
brief = {"summary": "all", "full": ""}.get(detail, "added")
|
|
799
|
+
out += ["相对上一次分析的流程变化:",
|
|
800
|
+
diff_text(_with_overrides(delta, self.store.get_overrides(p["id"])), brief=brief,
|
|
801
|
+
engines=(before["engine_version"], (self.store.latest_analysis(p["id"]) or before)["engine_version"]))]
|
|
802
|
+
hidden = [fc for fc in delta.functions.values() if fc.status != "removed" and (brief == "all" or fc.status == "added")]
|
|
803
|
+
if brief and hidden:
|
|
804
|
+
out.append(f"({'每个函数' if brief == 'all' else '新增的函数'}只写了一行:要看节点用 get_flow,要看逐个节点的变化用 "
|
|
805
|
+
"diff_flows 或 detail=\"full\")")
|
|
806
|
+
if extra.get("diff") is None and extra.get("base_id") is not None: # 改回去了:和对比基准又一样
|
|
807
|
+
out.append("流程又和对比基准一样了,没有未看的变化(这次把上次标为已看以来、没标过就是第一次分析以来的"
|
|
808
|
+
"改动又改回去了)。")
|
|
809
|
+
elif extra.get("diff") is None: # 有变化却既没存下差异也没有基准:保存时的比较出错了(日志里有)
|
|
810
|
+
out.append("这次没能和上一次比较并存下流程差异(比较时出错,日志在标准错误里):平台界面和 diff_flows 不会"
|
|
811
|
+
"标出上面这些变化。")
|
|
812
|
+
if earlier and extra.get("diff") is not None:
|
|
813
|
+
out.append("另有更早的未看变化,用 diff_flows 看全部(上次标为已看以来、没标过就是第一次分析以来的变化)。")
|
|
814
|
+
return "\n".join(out)
|
|
815
|
+
|
|
816
|
+
def _delta(self, old_id: int, new_id: int) -> GraphDiff | None:
|
|
817
|
+
"""上一次分析到这次的流程差异(当场算,不用存着的:存着的是相对对比基准的,可能比上一次更早)。读不出图、
|
|
818
|
+
比较出错时 None。"""
|
|
819
|
+
try:
|
|
820
|
+
old, new = self._graph(old_id), self._graph(new_id)
|
|
821
|
+
return None if old is None or new is None else diff_graphs(old, new)
|
|
822
|
+
except Exception:
|
|
823
|
+
logger.exception("重新比较分析 %s 和 %s 出错", old_id, new_id)
|
|
824
|
+
return None
|
|
825
|
+
|
|
826
|
+
# ---------- project_status ----------
|
|
827
|
+
|
|
828
|
+
@_capped("内容太多:用 find_nodes、get_node 查具体的位置")
|
|
829
|
+
def project_status(self, *, project: str | None = None) -> str:
|
|
830
|
+
"""项目的自检报告和是否过期"""
|
|
831
|
+
v = self._view(project)
|
|
832
|
+
g, sc, a = v.graph, v.graph.selfcheck, v.analysis
|
|
833
|
+
out = [f"项目「{v.project['name']}」[id {v.project['id']}] 目录 {v.project['root']}",
|
|
834
|
+
(f"最新一次分析:#{a['id']},{_when(a['created_at'])},引擎 {a['engine_version']};函数 {len(g.functions)} 个,"
|
|
835
|
+
f"功能线 {len(g.lines)} 条,公共任务 {len(g.common_tasks)} 个"),
|
|
836
|
+
procinfo.process_line(), "", "## 自检"]
|
|
837
|
+
out += self._node_problems("走不到的节点", sc.unreachable, g)
|
|
838
|
+
out += self._node_problems("没有出路的节点", sc.dead_ends, g)
|
|
839
|
+
out += self._unresolved(v, sc.unresolved_calls)
|
|
840
|
+
out += self._guessed(g, sc.guessed_calls)
|
|
841
|
+
out.append(f"跳过的文件:{len(sc.skipped_files)} 个" + ("(解析不了,图里没有它们)" if sc.skipped_files else ""))
|
|
842
|
+
out += [f" {f}:{why}" for f, why in sc.skipped_files[:MAX_FILES]]
|
|
843
|
+
out += entry_notes(g)
|
|
844
|
+
marks = (a.get("summary") or {}).get("mark_notes") or []
|
|
845
|
+
out += [f"标记里读不出来的参数:{len(marks)} 处", *(f" {n}" for n in marks[:MAX_ITEMS])] if marks else []
|
|
846
|
+
out += ["", "## 代码在分析之后有没有改过"] + self._stale_details(v)
|
|
847
|
+
out += ["", "## 流程变化",
|
|
848
|
+
"有未看的流程变化:用 diff_flows 查看" if a["has_diff"] else "没有未看的流程变化"]
|
|
849
|
+
out += ["", "## 测试运行", *self._run_details(v)]
|
|
850
|
+
return self._warning(v) + "\n".join(out)
|
|
851
|
+
|
|
852
|
+
def _run_details(self, v: _View) -> list[str]:
|
|
853
|
+
"""project_status 的最后一段:最近一次**全量**运行的时间、状态、用例数、核对三项、没走到的结局个数(和
|
|
854
|
+
uncovered_outcomes 同一个口径:只跑一条功能线的运行走不到别的线,拿它数"没走到的结局"会多出一大截)。它之后
|
|
855
|
+
还有只跑一条线的运行时另说一句;只有单条线的运行、没有全量的时,只报那次运行,不报结局个数。"""
|
|
856
|
+
runs = self.store.list_runs(v.project["id"])
|
|
857
|
+
if not runs:
|
|
858
|
+
return [NEVER_RAN]
|
|
859
|
+
latest = runs[0]
|
|
860
|
+
run = next((r for r in runs if r.get("scope") is None), None) # 没跑完的全量运行也算:状态要如实报
|
|
861
|
+
if run is None:
|
|
862
|
+
scope = latest.get("scope") or {}
|
|
863
|
+
return [f"还没有全量的测试运行。最近一次只跑了功能线「{scope.get('line_title', '')}」的测试:{_run_head(latest)}",
|
|
864
|
+
"没有测试走到的结局要按全量运行算:在平台上运行全部测试之后再看。"]
|
|
865
|
+
s = run["summary"]
|
|
866
|
+
out = [f"最近一次全量运行:{_run_head(run)}"]
|
|
867
|
+
if latest["id"] != run["id"]:
|
|
868
|
+
scope = latest.get("scope") or {}
|
|
869
|
+
out.append(f"(之后还有只跑功能线「{scope.get('line_title', '')}」的运行 {_run_head(latest)}——它只回答那条线,"
|
|
870
|
+
"下面的核对和结局个数不按它算)")
|
|
871
|
+
if run["analysis_id"] != v.analysis["id"]:
|
|
872
|
+
out.append(f"⚠ 这次运行用的是分析 #{run['analysis_id']},之后重新分析过(现在是 #{v.analysis['id']}):下面的核对和"
|
|
873
|
+
"结局个数都是按那次的图算的,不是现在的图;之后改动的代码有没有测试走到,要在平台上重新运行测试才知道。")
|
|
874
|
+
verify = s.get("verify")
|
|
875
|
+
if verify is None or verify.get("ok") is None: # 没跑完、记录读不了、一条记录都没收到:什么都没核对
|
|
876
|
+
out.append("核对:没有(测试没有跑完,或者没有收到记录)")
|
|
877
|
+
else:
|
|
878
|
+
m = verify.get("mismatches", {})
|
|
879
|
+
out.append(f"核对:连线不符 {m.get('edge', 0)}、结局不符 {m.get('end', 0)}、调用不符 {m.get('call', 0)}"
|
|
880
|
+
+ ("" if verify.get("ok") else "(不符的位置在平台界面的运行详情里)"))
|
|
881
|
+
if verify.get("stale"):
|
|
882
|
+
out.append(f"运行期间这些文件改过,路径可能对不上图:{'、'.join(verify['stale'])}")
|
|
883
|
+
c = s.get("coverage")
|
|
884
|
+
if c:
|
|
885
|
+
left = c["outcomes"] - c["outcomes_covered"] - c.get("outcomes_uncertain", 0)
|
|
886
|
+
out.append(f"没有测试走到的结局 {left} 个(共 {c['outcomes']} 个;按那次运行用的图算,uncovered_outcomes 查看)")
|
|
887
|
+
if s.get("note"):
|
|
888
|
+
out.append(f"说明:{s['note']}")
|
|
889
|
+
return out
|
|
890
|
+
|
|
891
|
+
def _node_problems(self, title: str, items: list[tuple[str, str]], g: ProjectGraph) -> list[str]:
|
|
892
|
+
out = [f"{title}:{len(items)} 个"]
|
|
893
|
+
for key, nid in items[:MAX_ITEMS]:
|
|
894
|
+
fg = g.functions.get(key)
|
|
895
|
+
node = None if fg is None else next((n for n in fg.nodes if n.id == nid), None)
|
|
896
|
+
out.append(f" - {node_line(fg, node)}({fg.qualname},{fg.file})" if node is not None else f" - {key} {nid}")
|
|
897
|
+
if len(items) > MAX_ITEMS:
|
|
898
|
+
out.append(f" …还有 {len(items) - MAX_ITEMS} 个")
|
|
899
|
+
return out
|
|
900
|
+
|
|
901
|
+
def _unresolved(self, v: _View, total: int) -> list[str]:
|
|
902
|
+
"""目标不明的调用:名字在项目里压根没有定义的(第三方、标准库)、太常见的名字(get、append 这类)和日志
|
|
903
|
+
不逐条列——它们几乎不可能落在项目代码上,列出来只是噪音,各折进一行给个数;可能落在项目代码上的才逐条
|
|
904
|
+
列出,在功能线上的排在前面,再按文件、行。"""
|
|
905
|
+
g = v.graph
|
|
906
|
+
out = [f"目标不明的调用:{total} 处"]
|
|
907
|
+
if not total:
|
|
908
|
+
return out
|
|
909
|
+
noise = (v.project.get("config") or {}).get("noise_receivers") or NOISE_RECEIVERS
|
|
910
|
+
groups = classify_unresolved(g.functions, noise)
|
|
911
|
+
on_lines = lines_of_functions(g)
|
|
912
|
+
sites = sorted((s.key not in on_lines, s.file, s.line, s.name) for s in groups.blind)
|
|
913
|
+
if sites:
|
|
914
|
+
out.append(f" 可能落在项目代码上的 {len(sites)} 处(名字在项目里有同名定义,但判断不出接收者的类型;"
|
|
915
|
+
"在功能线上的排在前面):")
|
|
916
|
+
out += [f" {f}:{line} {name}" + ("" if off else "(在功能线上)") for off, f, line, name in sites[:MAX_BLIND]]
|
|
917
|
+
if len(sites) > MAX_BLIND:
|
|
918
|
+
out.append(f" …还有 {len(sites) - MAX_BLIND} 处")
|
|
919
|
+
rest = []
|
|
920
|
+
if groups.outside:
|
|
921
|
+
rest.append(f"第三方 / 标准库 {len(groups.outside)} 处(最常见 {_top_names(groups.outside)})")
|
|
922
|
+
if groups.common:
|
|
923
|
+
rest.append(f"名字太常见 {len(groups.common)} 处({_top_names(groups.common)} 这类,"
|
|
924
|
+
"项目里虽有同名定义,多半是字典、列表的方法)")
|
|
925
|
+
if groups.logs:
|
|
926
|
+
rest.append(f"日志 {len(groups.logs)} 处")
|
|
927
|
+
if rest:
|
|
928
|
+
n = len(groups.outside) + len(groups.common) + len(groups.logs)
|
|
929
|
+
out.append(f" 其余 {n} 处不逐条列(几乎不可能落在项目代码上):" + "、".join(rest))
|
|
930
|
+
return out
|
|
931
|
+
|
|
932
|
+
def _guessed(self, g: ProjectGraph, total: int) -> list[str]:
|
|
933
|
+
sites = [(fg.file, n.line, ref.name, ref.target) for fg in g.functions.values() for n in fg.nodes
|
|
934
|
+
for ref in n.calls if ref.resolution == "guessed"]
|
|
935
|
+
out = [f"推测的调用:{total} 处" + ("(按名字推测的目标,可能不对)" if total else "")]
|
|
936
|
+
for f, line, name, target in sites[:MAX_ITEMS]:
|
|
937
|
+
fg = g.functions.get(target or "")
|
|
938
|
+
out.append(f" {f}:{line} {name} → {fn_label(fg) if fg is not None else target}")
|
|
939
|
+
if len(sites) > MAX_ITEMS:
|
|
940
|
+
out.append(f" …还有 {len(sites) - MAX_ITEMS} 处")
|
|
941
|
+
return out
|
|
942
|
+
|
|
943
|
+
def _stale_details(self, v: _View) -> list[str]:
|
|
944
|
+
st = v.stale
|
|
945
|
+
if not st.get("checked"):
|
|
946
|
+
return [f"没法检查:{st.get('reason', '')}"]
|
|
947
|
+
t = st["total"]
|
|
948
|
+
out = ["代码已变更:改 {changed} 个、增 {added} 个、删 {removed} 个文件(图可能过期,先调用 analyze_project 重新分析)。"
|
|
949
|
+
.format(**t) if st["stale"] else "代码没有变更:和分析时相同。"]
|
|
950
|
+
for key, word in (("changed", "改"), ("added", "增"), ("removed", "删")):
|
|
951
|
+
files = st[key][:MAX_FILES]
|
|
952
|
+
if files:
|
|
953
|
+
more = f" 等 {t[key]} 个" if t[key] > len(files) else ""
|
|
954
|
+
out.append(f"{word}:{'、'.join(files)}{more}")
|
|
955
|
+
if st["stale"]:
|
|
956
|
+
sids = st["lines"]
|
|
957
|
+
if sids is None:
|
|
958
|
+
out.append("涉及的功能线:不清楚(这次分析是旧版本存的,没有记下功能线涉及的文件)")
|
|
959
|
+
elif not sids:
|
|
960
|
+
out.append("涉及的功能线:无(改动的文件不在任何功能线上)")
|
|
961
|
+
else:
|
|
962
|
+
out.append(f"涉及的功能线({len(sids)} 条):")
|
|
963
|
+
out += [f" - {v.ref(ln) if (ln := v.by_sid(s)) is not None else s}" for s in sids[:MAX_FILES]]
|
|
964
|
+
if st.get("unreadable"):
|
|
965
|
+
files = st["unreadable"][:MAX_FILES]
|
|
966
|
+
more = f" 等 {t['unreadable']} 个" if t["unreadable"] > len(files) else ""
|
|
967
|
+
out.append(f"{st.get('note', '有文件读不了,没有比对')}(没有权限、所在目录进不去,或换成了指到项目外的链接):"
|
|
968
|
+
f"{'、'.join(files)}{more}")
|
|
969
|
+
return out
|
|
970
|
+
|
|
971
|
+
# ---------- list_flows ----------
|
|
972
|
+
|
|
973
|
+
@_capped("功能线太多:用 query 或 group 缩小范围")
|
|
974
|
+
def list_flows(self, *, project: str | None = None, query: str | None = None, group: str | None = None) -> str:
|
|
975
|
+
"""按分组列出功能线"""
|
|
976
|
+
v = self._view(project)
|
|
977
|
+
changed, removed = self._changed_lines(v)
|
|
978
|
+
needle = query.casefold() if query is not None else None
|
|
979
|
+
|
|
980
|
+
def wanted(texts: list[str], grp: str) -> bool:
|
|
981
|
+
if group is not None and grp != group:
|
|
982
|
+
return False
|
|
983
|
+
return needle is None or any(needle in t.casefold() for t in texts)
|
|
984
|
+
|
|
985
|
+
groups: dict[str, list[str]] = {}
|
|
986
|
+
for ln in v.graph.lines:
|
|
987
|
+
fg = v.graph.functions.get(ln.root.function)
|
|
988
|
+
file = fg.file if fg is not None else ""
|
|
989
|
+
sid, grp = v.sid(ln), v.group(ln)
|
|
990
|
+
route = (fg.route if fg is not None else None) or ""
|
|
991
|
+
if not wanted([*v.titles(ln), grp, sid, file, route], grp):
|
|
992
|
+
continue
|
|
993
|
+
where = f"{fg.file}:{fg.line}" if fg is not None else ln.root.function
|
|
994
|
+
shown = v.title(ln) + (f"({route})" if route and route != v.title(ln) else "") # 标题旁写"方法 路径"
|
|
995
|
+
row = f"- {shown} [{sid}] {_LINE_KIND.get(ln.kind, '函数')} {where}"
|
|
996
|
+
if sid in changed:
|
|
997
|
+
row += f" ⚑ 有未看的流程变化({_DIFF_STATUS.get(changed[sid], changed[sid])})"
|
|
998
|
+
groups.setdefault(grp, []).append(row)
|
|
999
|
+
gone = [c for c in removed if wanted([c.get("title", ""), c.get("group", ""), c.get("sid", "")], c.get("group", ""))]
|
|
1000
|
+
total = sum(len(rows) for rows in groups.values())
|
|
1001
|
+
name = v.project["name"]
|
|
1002
|
+
if not v.graph.lines and not gone:
|
|
1003
|
+
return self._warning(v) + (f"项目「{name}」:这个项目没有功能线。" + "".join(entry_notes(v.graph)) + "。也可以用 "
|
|
1004
|
+
"get_flow 的 function 参数直接看任何一个函数的流程,或者用 find_nodes 按文件和行号查函数。")
|
|
1005
|
+
if not total and not gone:
|
|
1006
|
+
known = "、".join(sorted({v.group(ln) for ln in v.graph.lines}))
|
|
1007
|
+
filters = ",".join(f"{k}={x}" for k, x in (("query", query), ("group", group)) if x is not None)
|
|
1008
|
+
return self._warning(v) + f"项目「{name}」没有匹配的功能线({filters})。分组有:{known}。"
|
|
1009
|
+
filtered = query is not None or group is not None
|
|
1010
|
+
out = [f"项目「{name}」共 {len(v.graph.lines)} 条功能线" + (f",匹配的 {total} 条" if filtered else "") + ":"]
|
|
1011
|
+
for grp in sorted(groups):
|
|
1012
|
+
out += ["", f"## {grp}({len(groups[grp])} 条)", *groups[grp]]
|
|
1013
|
+
if gone:
|
|
1014
|
+
out += ["", "## 相对对比基准删除了的功能线(diff_flows 查看)"]
|
|
1015
|
+
out += [f"- {v.overrides.get(c.get('sid', ''), {}).get('title') or c.get('title', '')} [{c.get('sid', '')}] "
|
|
1016
|
+
f"分组:{v.overrides.get(c.get('sid', ''), {}).get('group') or c.get('group', '')}" for c in gone]
|
|
1017
|
+
return self._warning(v) + "\n".join(out)
|
|
1018
|
+
|
|
1019
|
+
def _changed_lines(self, v: _View) -> tuple[dict[str, str], list[dict]]:
|
|
1020
|
+
"""最新一次分析存着的流程差异里有变化的功能线:({sid: status}, [删除了的线])。没有差异时都为空。"""
|
|
1021
|
+
state = self.store.latest_diff(v.project["id"])
|
|
1022
|
+
if state is None or state["diff"] is None or state["head"]["id"] != v.analysis["id"]:
|
|
1023
|
+
return {}, []
|
|
1024
|
+
lines = [c for c in state["diff"].get("lines", []) if isinstance(c, dict)]
|
|
1025
|
+
return ({c.get("sid", ""): c.get("status", "") for c in lines},
|
|
1026
|
+
[c for c in lines if c.get("status") == "removed"])
|
|
1027
|
+
|
|
1028
|
+
# ---------- get_flow ----------
|
|
1029
|
+
|
|
1030
|
+
@_capped("要看全:用更小的 depth、指定一条具体的功能线(flow),或用 find_nodes、get_node(function + node)只看要改的节点")
|
|
1031
|
+
def get_flow(self, *, project: str | None = None, flow: str | None = None, depth: int = 0, format: str = "outline",
|
|
1032
|
+
function: str | None = None) -> str:
|
|
1033
|
+
"""一条功能线的流程(大纲或 Mermaid);只给 function 时是项目里任何一个函数的流程(不管它在不在功能线上)"""
|
|
1034
|
+
if format not in ("outline", "mermaid"):
|
|
1035
|
+
raise ToolError(f"format 只能是 outline 或 mermaid,这次是 {format}")
|
|
1036
|
+
v = self._view(project)
|
|
1037
|
+
depth = max(0, min(depth, MAX_DEPTH))
|
|
1038
|
+
if flow is None:
|
|
1039
|
+
if function is None:
|
|
1040
|
+
raise ToolError("要给 flow(功能线的 sid 或标题),或者只给 function(看任何一个函数的流程)")
|
|
1041
|
+
if format == "mermaid":
|
|
1042
|
+
raise ToolError("function 只能和 outline 一起用(Mermaid 图画的是整条功能线)")
|
|
1043
|
+
key = self._function_on_line(v, None, function)
|
|
1044
|
+
return self._warning(v) + self._fitting(depth, lambda d: "\n".join(function_outline(v.graph, key, depth=d)))
|
|
1045
|
+
line = self._line(v, flow)
|
|
1046
|
+
if function is not None:
|
|
1047
|
+
if format == "mermaid":
|
|
1048
|
+
raise ToolError("function 只能和 outline 一起用(Mermaid 图画的是整条功能线)")
|
|
1049
|
+
key = self._function_on_line(v, line, function)
|
|
1050
|
+
return self._warning(v) + self._fitting(depth, lambda d: "\n".join(function_outline(v.graph, key, depth=d)))
|
|
1051
|
+
if format == "mermaid":
|
|
1052
|
+
return self._warning(v) + line_mermaid(v.graph, line)
|
|
1053
|
+
return self._warning(v) + self._fitting(depth, lambda d: self._line_text(v, line, d))
|
|
1054
|
+
|
|
1055
|
+
def _fitting(self, depth: int, render: Callable[[int], str]) -> str:
|
|
1056
|
+
"""render(depth) 放得下就用它;放不下时退到放得下的最大深度(内容完整,比从尾部截断有用),开头说明。depth=0
|
|
1057
|
+
还放不下时原样返回,由 _cap 截断。"""
|
|
1058
|
+
text = render(depth)
|
|
1059
|
+
used = depth
|
|
1060
|
+
while len(text) > FLOW_BUDGET and used > 0:
|
|
1061
|
+
used -= 1
|
|
1062
|
+
text = render(used)
|
|
1063
|
+
if used == depth:
|
|
1064
|
+
return text
|
|
1065
|
+
return (f"(depth={depth} 的大纲超过 {MAX_CHARS} 字的上限,下面是 depth={used} 的,没有截断。要看某个步骤里面:"
|
|
1066
|
+
"再调用一次 get_flow,用 function 指定行尾\"⇒ 可展开\"后面方括号里的那个函数)\n" + text)
|
|
1067
|
+
|
|
1068
|
+
def _function_on_line(self, v: _View, line: FlowLine | None, name: str) -> str:
|
|
1069
|
+
"""get_flow 的 function → 函数 key:先在这条功能线涉及的函数里找,找不到再在整个项目里找(没给功能线时直接在
|
|
1070
|
+
整个项目里找);要唯一。"""
|
|
1071
|
+
g = v.graph
|
|
1072
|
+
keys = [h.function for h in find_by_function(g, name) if h.how == "definition"]
|
|
1073
|
+
on_line = set(line_functions(g, line)) if line is not None else set()
|
|
1074
|
+
hits = [k for k in keys if k in on_line] or keys
|
|
1075
|
+
if len(hits) == 1:
|
|
1076
|
+
return hits[0]
|
|
1077
|
+
if not hits:
|
|
1078
|
+
raise ToolError(f"没有叫「{name}」的函数(可以给函数名、限定名 Class.method,或函数 sid)")
|
|
1079
|
+
rows = "\n".join(f"- {fn_label(g.functions[k])}" for k in hits[:MAX_HITS])
|
|
1080
|
+
raise ToolError(f"「{name}」对应 {len(hits)} 个函数,请用方括号里的函数 sid 指定:\n{rows}")
|
|
1081
|
+
|
|
1082
|
+
def _line_text(self, v: _View, line: FlowLine, depth: int) -> str:
|
|
1083
|
+
text = line_outline(v.graph, line, depth=depth)
|
|
1084
|
+
if v.sid(line) in v.overrides: # 手工改过标题或分组:标题行用改过的
|
|
1085
|
+
rows = text.split("\n")
|
|
1086
|
+
rows[0] = f"# {v.title(line)} [{v.sid(line)}] 分组:{v.group(line)}"
|
|
1087
|
+
text = "\n".join(rows)
|
|
1088
|
+
return text
|
|
1089
|
+
|
|
1090
|
+
# ---------- find_nodes ----------
|
|
1091
|
+
|
|
1092
|
+
@_capped("命中太多:给具体的 file + line,或者用函数 sid 代替函数名")
|
|
1093
|
+
def find_nodes(self, *, project: str | None = None, file: str | None = None, line: int | None = None,
|
|
1094
|
+
function: str | None = None) -> str:
|
|
1095
|
+
"""按文件和行号、或按函数名反查节点"""
|
|
1096
|
+
if function is not None and (file is not None or line is not None):
|
|
1097
|
+
raise ToolError("file + line 和 function 只给一种")
|
|
1098
|
+
if function is None and (file is None or line is None):
|
|
1099
|
+
raise ToolError("要给 file 和 line(文件和行号),或者给 function(函数名)")
|
|
1100
|
+
if line is not None and line < 1:
|
|
1101
|
+
raise ToolError(f"行号从 1 起,这次是 {line}")
|
|
1102
|
+
v = self._view(project)
|
|
1103
|
+
g = v.graph
|
|
1104
|
+
if function is not None:
|
|
1105
|
+
hits = find_by_function(g, function)
|
|
1106
|
+
if not hits:
|
|
1107
|
+
return self._warning(v) + f"没有叫「{function}」的函数(可以给函数名、限定名 Class.method,或函数 sid)。"
|
|
1108
|
+
head = [f"函数「{function}」:{len(hits)} 处命中"]
|
|
1109
|
+
else:
|
|
1110
|
+
rel, hits = self._locate(v, file, line)
|
|
1111
|
+
if not hits:
|
|
1112
|
+
if rel is None or not any(fg.file == rel for fg in g.functions.values()):
|
|
1113
|
+
why = (f"文件 {file} 不在图里:不是这个项目里分析过的 .py 文件(文件路径相对项目根目录 "
|
|
1114
|
+
f"{v.project['root']}),或者在排除的目录里,或者里面没有函数。")
|
|
1115
|
+
else:
|
|
1116
|
+
why = f"{rel} 第 {line} 行不在任何函数里(import、模块级代码、类体里的语句不出节点)。"
|
|
1117
|
+
return self._warning(v) + why
|
|
1118
|
+
head = [f"{rel} 第 {line} 行:{len(hits)} 处命中"]
|
|
1119
|
+
if rel in v.stale.get("changed", []):
|
|
1120
|
+
head.append("注意:这个文件在分析之后改过,行号可能对不上图;先调用 analyze_project 重新分析。")
|
|
1121
|
+
warning = self._warning(v)
|
|
1122
|
+
out = list(head)
|
|
1123
|
+
budget = MAX_CHARS - len(warning) - CLOSING_RESERVE # 给最后那行"…还有 N 处"留地方,不让截断吃掉它
|
|
1124
|
+
size = _size(out)
|
|
1125
|
+
defined = [h.function for h in hits if h.how == "definition"]
|
|
1126
|
+
shown = 0
|
|
1127
|
+
for i, hit in enumerate(hits[:MAX_HITS], 1):
|
|
1128
|
+
fg = g.functions[hit.function]
|
|
1129
|
+
node = next(n for n in fg.nodes if n.id == hit.node)
|
|
1130
|
+
how = _HOW[hit.how]
|
|
1131
|
+
if hit.how == "call_site" and len(defined) > 1: # 同名的定义有几个:说调用的是哪一个
|
|
1132
|
+
called = [k for k in defined if any(ref.target == k for ref in node.calls)]
|
|
1133
|
+
how += "(调用 " + "、".join(f"[{g.functions[k].sid or k}]" for k in called) + ")"
|
|
1134
|
+
block = ["", f"{i}. {node_line(fg, node)}", f" 怎么命中:{how}", f" 所在函数:{fn_label(fg, titled=True)}",
|
|
1135
|
+
" 在这些功能线上:", *self._line_rows(v, hit.lines, " ", hit.function)]
|
|
1136
|
+
if size + _size(block) > budget:
|
|
1137
|
+
if shown: # 在命中之间截断
|
|
1138
|
+
break
|
|
1139
|
+
block = _fit(block, budget - size) + [" …(这一处太长,后面的没有列出)"] # 第一处就放不下
|
|
1140
|
+
out += block
|
|
1141
|
+
size += _size(block)
|
|
1142
|
+
shown += 1
|
|
1143
|
+
if shown < len(hits):
|
|
1144
|
+
out += ["", f"…还有 {len(hits) - shown} 处命中没有列出(给具体的 file + line,或者用函数 sid 代替函数名)"]
|
|
1145
|
+
return warning + "\n".join(out)
|
|
1146
|
+
|
|
1147
|
+
def _locate(self, v: _View, file: str, line: int) -> tuple[str | None, list]:
|
|
1148
|
+
"""按 file:line 反查:file 先当作相对项目根目录(或项目里的绝对路径),找不到时再按相对当前目录试一次。返回
|
|
1149
|
+
(相对项目根的路径 | None, 命中)。"""
|
|
1150
|
+
candidates = [file]
|
|
1151
|
+
if not os.path.isabs(file) and self.cwd is not None and str(self.cwd) != v.project["root"]:
|
|
1152
|
+
candidates.append(str(self.cwd / file))
|
|
1153
|
+
first = None
|
|
1154
|
+
for c in candidates:
|
|
1155
|
+
rel = _relative(v.graph.root, c)
|
|
1156
|
+
first = first or rel
|
|
1157
|
+
hits = find_by_location(v.graph, c, line)
|
|
1158
|
+
if hits:
|
|
1159
|
+
return rel, hits
|
|
1160
|
+
return first, []
|
|
1161
|
+
|
|
1162
|
+
# ---------- paths_to_outcome ----------
|
|
1163
|
+
|
|
1164
|
+
@_capped("结局或路径太多:用结局的 sid 只看一个结局,或减小 limit")
|
|
1165
|
+
def paths_to_outcome(self, *, project: str | None = None, flow: str, outcome: str,
|
|
1166
|
+
limit: int = DEFAULT_LIMIT) -> str:
|
|
1167
|
+
"""从入口到某个结局的路径"""
|
|
1168
|
+
v = self._view(project)
|
|
1169
|
+
g = v.graph
|
|
1170
|
+
line = self._line(v, flow)
|
|
1171
|
+
limit = max(1, min(limit, MAX_LIMIT))
|
|
1172
|
+
targets = self._outcomes(g, line, outcome)
|
|
1173
|
+
if not targets and self._is_uncaught_sid(g, line, outcome):
|
|
1174
|
+
return self._warning(v) + (f"功能线「{v.title(line)}」[{v.sid(line)}] 里的 [{outcome}]:{UNCAUGHT_ANSWER}"
|
|
1175
|
+
"要看会抛哪些异常,用 get_flow 看各函数里的步骤和捕获,或者直接读源码。")
|
|
1176
|
+
if not targets:
|
|
1177
|
+
raise ToolError(f"功能线「{v.title(line)}」[{v.sid(line)}] 里没有匹配「{outcome}」的结局"
|
|
1178
|
+
f"(outcome 可以是结局节点的 sid、标题的片段,或 ok / skipped / failed / exception;"
|
|
1179
|
+
f"未捕获异常退出不算)。{self._outcome_choices(g, line)}")
|
|
1180
|
+
targets, caught = self._split_caught(g, line, targets)
|
|
1181
|
+
if not targets:
|
|
1182
|
+
return self._warning(v) + "\n".join([
|
|
1183
|
+
(f"功能线「{v.title(line)}」[{v.sid(line)}] 里没有以「{outcome}」结束的结局:匹配到的 {len(caught)} 个都是被调函数里"
|
|
1184
|
+
"抛出、又在调用它的函数里被接住的异常。"), *caught])
|
|
1185
|
+
out = [f"功能线「{v.title(line)}」[{v.sid(line)}] 里匹配「{outcome}」的结局 {len(targets)} 个"
|
|
1186
|
+
+ (f"(列出前 {MAX_OUTCOMES} 个)" if len(targets) > MAX_OUTCOMES else "") + "。", PATHS_CAVEAT]
|
|
1187
|
+
for key, nid in targets[:MAX_OUTCOMES]:
|
|
1188
|
+
fg = g.functions[key]
|
|
1189
|
+
node = next(n for n in fg.nodes if n.id == nid)
|
|
1190
|
+
out += ["", f"### {node_text(node)} [{node.sid or node.id}] " + (f"{fg.file}:{node.line}" if node.line else fg.file),
|
|
1191
|
+
f"所在函数:{fn_label(fg, titled=True)}", "从功能线入口到这个函数:" + _chain_text(g, line, key)]
|
|
1192
|
+
paths, more = paths_to(g, key, nid, limit=limit)
|
|
1193
|
+
if not paths:
|
|
1194
|
+
out.append("函数里没有走到它的路径(从函数开始走不到)")
|
|
1195
|
+
continue
|
|
1196
|
+
out.append(f"函数里走到它的路径({len(paths)} 条" + (f",只列前 {limit} 条" if more else "")
|
|
1197
|
+
+ ",顺序走过的步骤不写):")
|
|
1198
|
+
out += [f"{i}. {_path_text(fg, p)}" for i, p in enumerate(paths, 1)]
|
|
1199
|
+
if len(targets) > MAX_OUTCOMES:
|
|
1200
|
+
out += ["", f"…还有 {len(targets) - MAX_OUTCOMES} 个结局没有列出(用结局的 sid 或更具体的标题片段)"]
|
|
1201
|
+
if caught:
|
|
1202
|
+
out += ["", f"### 不算这条线的结局:被接住的异常 {len(caught)} 个",
|
|
1203
|
+
"它们是被调函数里的 raise,但调用它的函数接住了,功能线从接住的地方接着往下走,不会以它们结束:", *caught]
|
|
1204
|
+
return self._warning(v) + "\n".join(out)
|
|
1205
|
+
|
|
1206
|
+
def _split_caught(self, g: ProjectGraph, line: FlowLine,
|
|
1207
|
+
targets: list[tuple[str, str]]) -> tuple[list[tuple[str, str]], list[str]]:
|
|
1208
|
+
"""把匹配到的结局分成两份:真会让功能线结束的,和被调函数里抛出、在调用链上被接住的异常(每个一行说明:是哪个
|
|
1209
|
+
结局、在哪个函数的哪个捕获节点被接住)。"""
|
|
1210
|
+
kept: list[tuple[str, str]] = []
|
|
1211
|
+
caught: list[str] = []
|
|
1212
|
+
for key, nid in targets:
|
|
1213
|
+
fg = g.functions[key]
|
|
1214
|
+
node = next(n for n in fg.nodes if n.id == nid)
|
|
1215
|
+
hit = caught_on_chain(g, entry_chain(g, line, key) or [], node)
|
|
1216
|
+
if hit is None:
|
|
1217
|
+
kept.append((key, nid))
|
|
1218
|
+
continue
|
|
1219
|
+
by, catch = g.functions[hit[0]], hit[1]
|
|
1220
|
+
caught.append(f"- {node_text(node)} [{node.sid or node.id}] {fg.file}:{node.line}(函数 {fg.qualname})"
|
|
1221
|
+
f" —— 在 {_FN_KIND.get(by.kind, '函数')} {by.qualname} 的 {node_ref(by, catch)} L{catch.line}"
|
|
1222
|
+
f"「{catch.title}」被接住")
|
|
1223
|
+
return kept, caught
|
|
1224
|
+
|
|
1225
|
+
def _outcomes(self, g: ProjectGraph, line: FlowLine, text: str) -> list[tuple[str, str]]:
|
|
1226
|
+
"""匹配的结局 [(函数 key, 节点 id)]:节点 sid 完全相同的;ok / skipped / failed / exception 按结局类型(不看标题:
|
|
1227
|
+
find_outcomes 对它们也按标题片段找,"返回 {"failed": 0}"、含 token 的标题会混进来);别的文字按 find_outcomes
|
|
1228
|
+
找标题片段。去掉未捕获异常退出(它没有入边,走不到)。派发树上的任务里的排在前面,其余(被调函数里的)在后。"""
|
|
1229
|
+
keys = line_functions(g, line)
|
|
1230
|
+
by_sid = [(k, n.id) for k in keys for n in g.functions[k].nodes
|
|
1231
|
+
if n.type == "end" and n.sid == text and not _uncaught(n)]
|
|
1232
|
+
if by_sid:
|
|
1233
|
+
return by_sid
|
|
1234
|
+
if text in _END:
|
|
1235
|
+
found = [(k, n.id) for k in keys for n in g.functions[k].nodes if n.type == "end" and n.end_kind == text]
|
|
1236
|
+
else:
|
|
1237
|
+
found = find_outcomes(g, line, text)
|
|
1238
|
+
found = [(k, nid) for k, nid in found if not _uncaught(next(n for n in g.functions[k].nodes if n.id == nid))]
|
|
1239
|
+
tasks = set(_tasks(line.root))
|
|
1240
|
+
return sorted(found, key=lambda item: item[0] not in tasks)
|
|
1241
|
+
|
|
1242
|
+
def _is_uncaught_sid(self, g: ProjectGraph, line: FlowLine, text: str) -> bool:
|
|
1243
|
+
"""text 是这条线上某个函数的"未捕获异常退出"的 sid(get_flow 里每个函数都有的 [end:uncaught])。"""
|
|
1244
|
+
return any(n.sid == text and _uncaught(n) for k in line_functions(g, line) for n in g.functions[k].nodes)
|
|
1245
|
+
|
|
1246
|
+
def _outcome_choices(self, g: ProjectGraph, line: FlowLine) -> str:
|
|
1247
|
+
"""这条线上的结局(派发树上的任务里的在前,再是被调函数里的;不含未捕获异常退出),给 ToolError 列可选的。"""
|
|
1248
|
+
tasks = set(_tasks(line.root))
|
|
1249
|
+
keys = sorted(line_functions(g, line), key=lambda k: k not in tasks)
|
|
1250
|
+
rows = [f"- [{n.sid or n.id}] {node_text(n)} ({g.functions[k].qualname})"
|
|
1251
|
+
for k in keys for n in g.functions[k].nodes if n.type == "end" and not _uncaught(n)]
|
|
1252
|
+
if not rows:
|
|
1253
|
+
return ""
|
|
1254
|
+
more = f"\n…还有 {len(rows) - MAX_CHOICES} 个" if len(rows) > MAX_CHOICES else ""
|
|
1255
|
+
return "这条线上的结局(任务里的在前):\n" + "\n".join(rows[:MAX_CHOICES]) + more
|
|
1256
|
+
|
|
1257
|
+
# ---------- get_node ----------
|
|
1258
|
+
|
|
1259
|
+
@_capped("内容太多:源码片段之外的部分用 get_flow 看")
|
|
1260
|
+
def get_node(self, *, project: str | None = None, function: str, node: str) -> str:
|
|
1261
|
+
"""一个节点的详情"""
|
|
1262
|
+
v = self._view(project)
|
|
1263
|
+
g = v.graph
|
|
1264
|
+
key = g.sids.get(function) or (function if function in g.functions else None)
|
|
1265
|
+
if key is None:
|
|
1266
|
+
raise ToolError(f"没有这个函数:{function}(function 要给函数 sid,就是 get_flow、find_nodes 输出里函数头"
|
|
1267
|
+
f"方括号中的那个,如 app/orders.py::place_order)")
|
|
1268
|
+
fg = g.functions[key]
|
|
1269
|
+
n = next((x for x in fg.nodes if x.sid == node), None) or next((x for x in fg.nodes if x.id == node), None)
|
|
1270
|
+
if n is None:
|
|
1271
|
+
raise ToolError(f"函数 {fg.sid or key} 里没有这个节点:{node}(节点 sid 是大纲每行开头方括号里的,"
|
|
1272
|
+
f"如 step:1a2b3c4d、cond:…、end:…)")
|
|
1273
|
+
sub = n.subtitle_full or n.subtitle
|
|
1274
|
+
kind = _TYPE.get(n.type, n.type) + (f"({_END[n.end_kind]})" if n.type == "end" and n.end_kind in _END else "")
|
|
1275
|
+
where = (f"{fg.file}:{n.line}" + (f"–{n.end_line}" if n.end_line > n.line else "")) if n.line \
|
|
1276
|
+
else "隐含节点,没有行号(开始、执行到函数末尾、未捕获异常退出)"
|
|
1277
|
+
out = [f"节点 {node_line(fg, n)}", f"标题:{n.title_full or n.title}"]
|
|
1278
|
+
if sub:
|
|
1279
|
+
out.append(f"{'条件 / 原文' if n.type in ('cond', 'loop', 'catch') else '调用名'}:{sub}")
|
|
1280
|
+
out += [f"类型:{kind}", f"位置:{where}", f"所在函数:{fn_label(fg, titled=True)}"]
|
|
1281
|
+
if n.fields:
|
|
1282
|
+
out.append("结局带的字段:" + "、".join(f"{k}={x}" for k, x in n.fields.items()))
|
|
1283
|
+
if n.passthrough:
|
|
1284
|
+
target = g.functions.get(n.passthrough)
|
|
1285
|
+
out.append(f"转交返回:{fn_label(target) if target is not None else n.passthrough}")
|
|
1286
|
+
out += ["", *self._snippet(v, fg, n), "", *self._calls(g, n), "", *self._edges(fg, n),
|
|
1287
|
+
"", "所在的功能线:", *self._line_rows(v, lines_of_functions(g).get(key, []), " ")]
|
|
1288
|
+
return self._warning(v) + "\n".join(out)
|
|
1289
|
+
|
|
1290
|
+
def _snippet(self, v: _View, fg: FunctionGraph, n: Node) -> list[str]:
|
|
1291
|
+
if not n.line:
|
|
1292
|
+
return ["源码:隐含节点没有源码"]
|
|
1293
|
+
last = max(n.end_line, n.line)
|
|
1294
|
+
try:
|
|
1295
|
+
path = resolve_source_path(v.project["root"], fg.file)
|
|
1296
|
+
snip = read_snippet(path, fg.file, max(1, n.line - SNIPPET_CONTEXT), last + SNIPPET_CONTEXT,
|
|
1297
|
+
v.graph.file_hashes.get(fg.file))
|
|
1298
|
+
except SourceError as e:
|
|
1299
|
+
return [f"源码:读不了({e.message})"]
|
|
1300
|
+
except OSError as e:
|
|
1301
|
+
return [f"源码:读不了({e.strerror or e})"]
|
|
1302
|
+
if not snip["lines"]:
|
|
1303
|
+
return [f"源码:文件只有 {snip['total']} 行,读不到第 {n.line} 行(文件在分析之后改过)"]
|
|
1304
|
+
out = [f"源码({fg.file} 第 {snip['start']}–{snip['end']} 行,→ 标出节点所在的行):"]
|
|
1305
|
+
if snip["stale"]:
|
|
1306
|
+
out.append("注意:这个文件在分析之后改过,下面的源码可能和图对不上;先调用 analyze_project 重新分析。")
|
|
1307
|
+
width = len(str(snip["end"]))
|
|
1308
|
+
for i, text in enumerate(snip["lines"], snip["start"]):
|
|
1309
|
+
out.append(f"{'→' if n.line <= i <= last else ' '} {i:>{width}} | {text}")
|
|
1310
|
+
return out
|
|
1311
|
+
|
|
1312
|
+
def _calls(self, g: ProjectGraph, n: Node) -> list[str]:
|
|
1313
|
+
if not n.calls:
|
|
1314
|
+
return ["调用:无"]
|
|
1315
|
+
out = ["调用:"]
|
|
1316
|
+
for ref in n.calls:
|
|
1317
|
+
target = g.functions.get(ref.target) if ref.target else None
|
|
1318
|
+
if target is not None:
|
|
1319
|
+
what = ("派发 " if ref.is_dispatch else "") + fn_label(target)
|
|
1320
|
+
elif ref.resolution == "external":
|
|
1321
|
+
what = "项目之外的函数"
|
|
1322
|
+
else:
|
|
1323
|
+
what = ref.target or "目标不明"
|
|
1324
|
+
notes = []
|
|
1325
|
+
if ref.conditional:
|
|
1326
|
+
notes.append("在三元表达式、and / or 或 case 守卫里,不一定执行")
|
|
1327
|
+
if ref.dispatches:
|
|
1328
|
+
names = [g.functions[k].qualname if k in g.functions else k for k in ref.dispatches]
|
|
1329
|
+
notes.append("内部派发 " + "、".join(names))
|
|
1330
|
+
out.append(f" - {ref.name} → {what}({_RESOLUTION.get(ref.resolution, ref.resolution)})"
|
|
1331
|
+
+ (f";{';'.join(notes)}" if notes else ""))
|
|
1332
|
+
return out
|
|
1333
|
+
|
|
1334
|
+
def _edges(self, fg: FunctionGraph, n: Node) -> list[str]:
|
|
1335
|
+
nodes = {x.id: x for x in fg.nodes}
|
|
1336
|
+
ins = [e for e in fg.edges if e.dst == n.id and e.src in nodes]
|
|
1337
|
+
outs = [e for e in fg.edges if e.src == n.id and e.dst in nodes]
|
|
1338
|
+
out = ["进来的连线:" + ("" if ins else "无")]
|
|
1339
|
+
out += [f" - {node_line(fg, nodes[e.src])} —{_edge_word(nodes[e.src], e)}→ 这里" for e in ins]
|
|
1340
|
+
out.append("出去的连线:" + ("" if outs else "无"))
|
|
1341
|
+
out += [f" - {_edge_word(n, e)} → {node_line(fg, nodes[e.dst])}" for e in outs]
|
|
1342
|
+
return out
|
|
1343
|
+
|
|
1344
|
+
# ---------- diff_flows ----------
|
|
1345
|
+
|
|
1346
|
+
@_capped("变化太多:用 flow 参数只看一条功能线")
|
|
1347
|
+
def diff_flows(self, *, project: str | None = None, flow: str | None = None, record: int | None = None) -> str:
|
|
1348
|
+
"""流程和对比基准相比的变化"""
|
|
1349
|
+
v = self._view(project)
|
|
1350
|
+
if record is not None:
|
|
1351
|
+
return self._review_text(v, record, flow)
|
|
1352
|
+
state = self.store.latest_diff(v.project["id"])
|
|
1353
|
+
if state is None:
|
|
1354
|
+
raise ToolError(f"项目「{v.project['name']}」还没有分析结果:先调用 analyze_project")
|
|
1355
|
+
head, base = state["head"], state["base"]
|
|
1356
|
+
past = self._reviews_footer(v)
|
|
1357
|
+
if base is None:
|
|
1358
|
+
return self._warning(v) + ("没有未看的流程变化:只有一次分析,或者变化已在平台上标为已看,或者重新分析过、流程"
|
|
1359
|
+
"没有变化。改了代码之后先调用 analyze_project 重新分析,再来看。") + past
|
|
1360
|
+
out = [f"最新一次分析(#{head['id']},{_when(head['created_at'])}){_baseline_text(state)}的流程变化:"]
|
|
1361
|
+
if state["diff"] is None:
|
|
1362
|
+
out.append("流程没有变化")
|
|
1363
|
+
return self._warning(v) + "\n".join(out) + past
|
|
1364
|
+
d = _load_diff(state["diff"])
|
|
1365
|
+
engines = (base["engine_version"], head["engine_version"])
|
|
1366
|
+
if flow is None:
|
|
1367
|
+
out.append(diff_text(_with_overrides(d, v.overrides), engines=engines))
|
|
1368
|
+
else:
|
|
1369
|
+
sid = self._diff_line(v, d, flow)
|
|
1370
|
+
out.append(diff_text(_with_overrides(d, v.overrides), line_sid=sid, engines=engines))
|
|
1371
|
+
if all(ln.sid != sid for ln in d.lines) and not d.empty:
|
|
1372
|
+
out.append("(别的功能线或函数有变化:不给 flow 可以看全部)")
|
|
1373
|
+
return self._warning(v) + "\n".join(out) + past
|
|
1374
|
+
|
|
1375
|
+
def _reviews_footer(self, v: _View) -> str:
|
|
1376
|
+
"""diff_flows 结果末尾的"变更记录"列表:以前标为已看的那些变化(最近 10 条)。没有时空串。"""
|
|
1377
|
+
records = self.store.list_reviews(v.project["id"])
|
|
1378
|
+
if not records:
|
|
1379
|
+
return ""
|
|
1380
|
+
rows = ["", "", f"变更记录(以前在平台上标为已看的变化,最近 {len(records)} 条;用 record 看明细):"]
|
|
1381
|
+
for r in records:
|
|
1382
|
+
s = r["summary"]
|
|
1383
|
+
lines = "、".join(ln["title"] for ln in s["lines"][:5]) + ("等" if len(s["lines"]) > 5 else "")
|
|
1384
|
+
rows.append(f"- #{r['id']} {_when(r['acked_at'])} 标为已看:{len(s['lines'])} 条功能线({lines or '无'}),"
|
|
1385
|
+
f"节点新增 {s['added']}、删除 {s['removed']}、改动 {s['changed']}")
|
|
1386
|
+
return "\n".join(rows)
|
|
1387
|
+
|
|
1388
|
+
def _review_text(self, v: _View, record: int, flow: str | None) -> str:
|
|
1389
|
+
found = self.store.get_review(v.project["id"], record)
|
|
1390
|
+
if found is None:
|
|
1391
|
+
have = "、".join(f"#{r['id']}" for r in self.store.list_reviews(v.project["id"])) or "(还没有)"
|
|
1392
|
+
raise ToolError(f"没有变更记录 #{record}(只留最近 10 条)。现有的:{have}")
|
|
1393
|
+
d = _load_diff(found["diff"])
|
|
1394
|
+
head = (f"变更记录 #{found['id']}({_when(found['acked_at'])} 标为已看):分析 #{found['head_id']}"
|
|
1395
|
+
f"({_when(found['head_at'])})相对分析 #{found['base_id']}({_when(found['base_at'])})的流程变化。"
|
|
1396
|
+
"这是当时的变化,文件和行号是当时的,现在的代码可能已经不同:")
|
|
1397
|
+
if flow is None:
|
|
1398
|
+
return _cap(head + "\n" + diff_text(d), "这条记录太长:用 flow 只看一条功能线")
|
|
1399
|
+
hits = [ln for ln in d.lines if flow in (ln.sid, ln.title)]
|
|
1400
|
+
if len(hits) != 1:
|
|
1401
|
+
raise ToolError(f"这条记录里没有功能线「{flow}」。有变化的:{'、'.join(ln.title for ln in d.lines) or '无'}")
|
|
1402
|
+
return _cap(head + "\n" + diff_text(d, line_sid=hits[0].sid), "这条记录太长:在平台的变更记录里看")
|
|
1403
|
+
|
|
1404
|
+
def _diff_line(self, v: _View, d: GraphDiff, flow: str) -> str:
|
|
1405
|
+
"""diff_flows 的 flow:先在现在的图里找;找不到时(这条线删掉了)在差异里按 sid、标题找。"""
|
|
1406
|
+
try:
|
|
1407
|
+
return v.sid(self._line(v, flow))
|
|
1408
|
+
except ToolError:
|
|
1409
|
+
gone = [ln for ln in d.lines if flow in (ln.sid, ln.title)]
|
|
1410
|
+
if len(gone) == 1:
|
|
1411
|
+
return gone[0].sid
|
|
1412
|
+
raise
|
|
1413
|
+
|
|
1414
|
+
# ---------- check ----------
|
|
1415
|
+
|
|
1416
|
+
@_capped("违规太多:用 files 只检查几个文件")
|
|
1417
|
+
def check(self, *, project: str | None = None, path: str | None = None, files: list[str] | None = None) -> str:
|
|
1418
|
+
"""检查流程代码有没有违反约束"""
|
|
1419
|
+
if project is not None and path is not None:
|
|
1420
|
+
raise ToolError("project 和 path 只给一个")
|
|
1421
|
+
projects = self.store.list_projects()
|
|
1422
|
+
if path is not None:
|
|
1423
|
+
target = self._abs(path)
|
|
1424
|
+
if target is None or not target.is_dir():
|
|
1425
|
+
raise ToolError(f"不是目录:{path}")
|
|
1426
|
+
if home_conflict(target): # 和添加项目同样的规矩:走一遍整个主目录要几分钟、几 GB 内存
|
|
1427
|
+
raise ToolError(f"不能检查根目录、用户主目录或包含用户主目录的目录,请给具体的代码目录:{target}")
|
|
1428
|
+
p = _containing(projects, target)
|
|
1429
|
+
else:
|
|
1430
|
+
try:
|
|
1431
|
+
p = self._project(project, projects)
|
|
1432
|
+
except ToolError as e:
|
|
1433
|
+
raise ToolError(f"{e}\n检查没添加过的目录:用 path 给出目录。") from None
|
|
1434
|
+
target = Path(p["root"])
|
|
1435
|
+
prefix = ""
|
|
1436
|
+
if p is None:
|
|
1437
|
+
root, config_json, used = target, {}, "默认配置(这个目录不在已添加的项目里)"
|
|
1438
|
+
else:
|
|
1439
|
+
problem = root_problem(p["root"])
|
|
1440
|
+
if problem is not None:
|
|
1441
|
+
raise ToolError(problem[1])
|
|
1442
|
+
root, config_json, used = Path(p["root"]), p["config"], f"项目「{p['name']}」的分析配置"
|
|
1443
|
+
if target != root: # 项目里面的目录:按项目根目录和项目的配置检查,只报告这个目录里的
|
|
1444
|
+
try:
|
|
1445
|
+
prefix = target.relative_to(root).as_posix()
|
|
1446
|
+
except ValueError: # 按 inode 认出的(写法大小写不同):就检查这个目录本身
|
|
1447
|
+
root = target
|
|
1448
|
+
given = {posixpath.normpath(posixpath.join(prefix, f)): f for f in files} if files and prefix else {}
|
|
1449
|
+
only = list(given) if given else files
|
|
1450
|
+
result = check_in_subprocess(str(root), config_json, only, timeout=analyze_timeout(), cwd=self.store.path.parent)
|
|
1451
|
+
if not result["ok"]:
|
|
1452
|
+
raise ToolError(result["reason"])
|
|
1453
|
+
|
|
1454
|
+
def inside(f: str) -> bool:
|
|
1455
|
+
return not prefix or f == prefix or f.startswith(prefix + "/")
|
|
1456
|
+
|
|
1457
|
+
violations = [x for x in result["violations"] if inside(x["file"])]
|
|
1458
|
+
skipped = [x for x in result["skipped"] if inside(x[0])]
|
|
1459
|
+
ignored = [x for x in result["ignored"] if inside(x[0])]
|
|
1460
|
+
out = [f"{x['file']}:{x['line']}: {x['code']} {x['message']}" for x in violations]
|
|
1461
|
+
where = f"检查的目录:{target}" + (f"(路径相对项目根目录 {root})" if prefix else "")
|
|
1462
|
+
scope = f",只报告 {'、'.join(files)} 里的" if files else ""
|
|
1463
|
+
out.append(f"共 {len(violations)} 处违规({where}{scope};用的配置:{used})")
|
|
1464
|
+
out += [f"警告:files 里的 {f} 不对应项目里的任何 .py 文件(相对检查的目录;排除的目录不算)"
|
|
1465
|
+
for f in (given.get(x, x) for x in result["unmatched"])]
|
|
1466
|
+
if skipped:
|
|
1467
|
+
out.append(f"以下 {len(skipped)} 个文件解析不了,没有检查:")
|
|
1468
|
+
out += [f" {f}:{why}" for f, why in skipped]
|
|
1469
|
+
if ignored:
|
|
1470
|
+
out.append(f"以下 {len(ignored)} 个 .py 路径不是项目里的源文件,没有检查:")
|
|
1471
|
+
out += [f" {f}:{why}" for f, why in ignored]
|
|
1472
|
+
return "\n".join(out)
|
|
1473
|
+
|
|
1474
|
+
|
|
1475
|
+
# ---------- 需求 ----------
|
|
1476
|
+
|
|
1477
|
+
def list_requirements(self, *, project: str | None = None) -> str:
|
|
1478
|
+
"""列出项目里的需求和各自的对照结果"""
|
|
1479
|
+
v = self._view(project)
|
|
1480
|
+
found = rq.load_requirements(Path(v.project["root"]))
|
|
1481
|
+
root = Path(v.project["root"])
|
|
1482
|
+
if not found and rq.uses_openspec(root):
|
|
1483
|
+
return (f"项目「{v.project['name']}」用 OpenSpec 管需求,OpenSpec 的文件里还没有设计的流程。{OPENSPEC_HOW}")
|
|
1484
|
+
if not found:
|
|
1485
|
+
return (f"项目「{v.project['name']}」里还没有需求({v.project['root']}/{rq.DIR}/ 下没有 .md 文件)。"
|
|
1486
|
+
"接到业务需求时用 save_requirement 新建一条。")
|
|
1487
|
+
own = sum(r.source == "pystepmap" for r in found)
|
|
1488
|
+
where = "、".join(w for w, n in ((f"{rq.DIR}/ 里 {own} 条", own), (f"OpenSpec 文件里 {len(found) - own} 条", len(found) - own)) if n)
|
|
1489
|
+
out = [self._warning(v) + f"项目「{v.project['name']}」的需求 {len(found)} 条({where}):", ""]
|
|
1490
|
+
old = sum(r.archived for r in found)
|
|
1491
|
+
for i, r in enumerate(found): # 已归档的排在最后(load_openspec 的顺序)
|
|
1492
|
+
if r.archived and (i == 0 or not found[i - 1].archived):
|
|
1493
|
+
out += ["", f"已归档的变更里的 {old} 条(当时的设计:和现在的代码不一致不算问题,不用照着改代码):"]
|
|
1494
|
+
status = "OpenSpec 已归档" if r.archived else "OpenSpec" if r.source == "openspec" else r.status or "?"
|
|
1495
|
+
out.append(f"- {r.id or '(没有编号)'} {r.title} [{status}] 功能线:{r.line or '(没写)'}")
|
|
1496
|
+
if r.errors:
|
|
1497
|
+
out.append(f" 读不懂({r.file}):{';'.join(r.errors[:3])}")
|
|
1498
|
+
continue
|
|
1499
|
+
cmp = rq.compare(r, v.graph)
|
|
1500
|
+
out.append(" " + (_verdict(cmp) + ("" if cmp.matches or _no_line(cmp) else "(get_requirement 看详情)")))
|
|
1501
|
+
return _cap("\n".join(out), "需求太多:用 get_requirement 看具体的一条")
|
|
1502
|
+
|
|
1503
|
+
def _requirement(self, v: _View, ref: str) -> rq.Requirement:
|
|
1504
|
+
found = rq.load_requirements(Path(v.project["root"]))
|
|
1505
|
+
hits = [r for r in found if r.id == ref] or [r for r in found if ref.casefold() in r.title.casefold()]
|
|
1506
|
+
if len(hits) != 1:
|
|
1507
|
+
have = "、".join(f"{r.id} {r.title}" for r in found[:20]) or "(一条都没有)"
|
|
1508
|
+
raise ToolError(f"{'找不到' if not hits else '对上不止一条'}需求「{ref}」。现有的:{have}")
|
|
1509
|
+
return hits[0]
|
|
1510
|
+
|
|
1511
|
+
def get_requirement(self, *, project: str | None = None, requirement: str) -> str:
|
|
1512
|
+
"""读一条需求,把设计的流程和实现对照"""
|
|
1513
|
+
v = self._view(project)
|
|
1514
|
+
return _cap(self._warning(v) + self._requirement_text(v, self._requirement(v, requirement)),
|
|
1515
|
+
"这条需求太长:直接读项目里的需求文件")
|
|
1516
|
+
|
|
1517
|
+
def _requirement_text(self, v: _View, r: rq.Requirement) -> str:
|
|
1518
|
+
external = r.source == "openspec" # 写在 OpenSpec 文件里的:状态不存在文件里,改它就是改那个文件
|
|
1519
|
+
status = "已归档(OpenSpec 归档的变更:这是当时的设计,和现在的代码不一致不算问题)" if r.archived else \
|
|
1520
|
+
"由 OpenSpec 的变更流程管(这里不存)" if external else r.status
|
|
1521
|
+
out = [f"需求 {r.id}「{r.title}」 状态:{status} 功能线:{r.line or '(没写)'}",
|
|
1522
|
+
f"文件:{r.file}" + ("(OpenSpec 文件里的 flow 代码块;要改设计就改这个文件)" if external else ""), ""]
|
|
1523
|
+
if r.description:
|
|
1524
|
+
out += ["说明:", r.description, ""]
|
|
1525
|
+
out += ["设计的流程:", r.flow_text, ""]
|
|
1526
|
+
if r.errors:
|
|
1527
|
+
return "\n".join([*out, "这条需求读不懂,没有对照:", *(f"- {e}" for e in r.errors)])
|
|
1528
|
+
out += [self._picture(v, r), ""]
|
|
1529
|
+
cmp = rq.compare(r, v.graph)
|
|
1530
|
+
no_line = _no_line(cmp)
|
|
1531
|
+
if cmp.matches:
|
|
1532
|
+
out.append(f"对照:设计和实现对得上(功能线 {cmp.line_title} [{cmp.line_sid}])。")
|
|
1533
|
+
elif no_line: # 没有可以对照的实现:不是"几处不一致",设计的节点也不逐个再列一遍
|
|
1534
|
+
out.append(f"对照:{_verdict(cmp)}。")
|
|
1535
|
+
else:
|
|
1536
|
+
where = f"(功能线 {cmp.line_title} [{cmp.line_sid}])" if cmp.line_sid else ""
|
|
1537
|
+
out.append(f"对照:和实现有 {len(cmp.differences)} 处不一致{where}:")
|
|
1538
|
+
out += [f"- {d.text}" + (f" [{d.node}]" if d.node else "") for d in cmp.differences]
|
|
1539
|
+
out += [f"注意:{n}" for n in cmp.notes]
|
|
1540
|
+
covered, rows = self._outcome_coverage(v, cmp)
|
|
1541
|
+
if rows:
|
|
1542
|
+
out += ["", "设计的结局有没有测试走到:", *rows]
|
|
1543
|
+
can = rq.reachable_status(r, cmp, covered)
|
|
1544
|
+
if r.archived:
|
|
1545
|
+
pass # 当时的设计:不催着改
|
|
1546
|
+
elif external:
|
|
1547
|
+
done = ",设计的每个结局都有测试走到" if can == "已完成" else ""
|
|
1548
|
+
out += ["", f"按现在的对照结果:设计和实现对得上{done}。" if cmp.matches else
|
|
1549
|
+
"按现在的对照结果:这条功能线还没有实现(已经实现了的话,是需求里写的功能线名字和图上的对不上)。" if no_line else
|
|
1550
|
+
"按现在的对照结果:实现和设计还不一致——是代码要改还是设计要改,由用户定;改完再对照一次。"]
|
|
1551
|
+
elif can != r.status:
|
|
1552
|
+
out += ["", (f"按现在的对照结果,这条需求够得上的状态是「{can}」(现在写的是「{r.status}」);"
|
|
1553
|
+
"要改就用 save_requirement 带上编号和原来的内容再保存一次。")]
|
|
1554
|
+
return "\n".join(out)
|
|
1555
|
+
|
|
1556
|
+
def _picture(self, v: _View, r: rq.Requirement) -> str:
|
|
1557
|
+
"""设计的流程画成图在哪里看:平台(pystepmap serve)在运行时给这条需求的地址——上面的缩进文本用户不好读,图是
|
|
1558
|
+
平台按同一份文件画的,和实现不一致的节点标在图上;没在运行时说怎么打开。地址的写法同界面(#/<项目>/req:<需求>)。"""
|
|
1559
|
+
port = serve_port(self.store.path.parent)
|
|
1560
|
+
if port is None:
|
|
1561
|
+
return ("设计的流程图:平台没有在运行。用户想看图时,请用户启动 pystepmap serve,在这个项目的「需求」列表里选这一条"
|
|
1562
|
+
"(画的就是上面这份设计,和实现不一致的节点标在图上)。")
|
|
1563
|
+
same = [x for x in rq.load_requirements(Path(v.project["root"])) if x.id == r.id]
|
|
1564
|
+
tail = r.id[r.id.rfind("#"):] if "#" in r.id and r.id[r.id.rfind("#") + 1:].isdigit() else ""
|
|
1565
|
+
ref = r.id if r.id and len(same) == 1 else r.file + tail
|
|
1566
|
+
q = lambda text: urllib.parse.quote(text, safe="")
|
|
1567
|
+
return (f"设计的流程图(把这个地址给用户看图确认,不要只贴上面的缩进文本):http://127.0.0.1:{port}/#/{q(v.project['id'])}/"
|
|
1568
|
+
f"{q('req:' + ref)}")
|
|
1569
|
+
|
|
1570
|
+
def _outcome_coverage(self, v: _View, cmp: rq.Comparison) -> tuple[bool | None, list[str]]:
|
|
1571
|
+
"""(设计的每个结局是不是都有测试走到——不知道时 None, 每个结局一行)。用最近一次跑完的测试运行。"""
|
|
1572
|
+
if not cmp.line_sid or not cmp.outcomes:
|
|
1573
|
+
return None, []
|
|
1574
|
+
run = self.store.latest_full_run(v.project["id"]) # 只看全量的运行
|
|
1575
|
+
if run is None:
|
|
1576
|
+
return None, ["- 平台上还没有跑完的全量测试运行,不知道(在平台上运行一次全部测试)"]
|
|
1577
|
+
try:
|
|
1578
|
+
missed = self._uncovered_of(v, run["id"]).outcomes(cmp.line_sid)
|
|
1579
|
+
except LookupError:
|
|
1580
|
+
return None, []
|
|
1581
|
+
state = {o.node: ("那次运行里还没有这个结局(运行之后才写的,重新运行测试才知道)" if o.added else
|
|
1582
|
+
"不确定(运行之后代码改过,对不上;重新运行测试才知道)" if o.uncertain else "没有测试走到")
|
|
1583
|
+
for o in missed}
|
|
1584
|
+
rows, all_covered = [], True
|
|
1585
|
+
for title, kind, sid in cmp.outcomes:
|
|
1586
|
+
how = "实现里还没有" if not sid else state.get(sid, "有测试走到")
|
|
1587
|
+
all_covered = all_covered and how == "有测试走到"
|
|
1588
|
+
rows.append(f"- {rq.END_NAMES[kind]}「{title}」:{how}")
|
|
1589
|
+
return all_covered, [f"(用的是测试运行 #{run['id']})", *rows]
|
|
1590
|
+
|
|
1591
|
+
def save_requirement(self, *, project: str | None = None, title: str, flow: str, line: str = "",
|
|
1592
|
+
description: str = "", status: str = "草稿", id: str | None = None) -> str:
|
|
1593
|
+
"""新建或改写一条需求(写进项目目录)"""
|
|
1594
|
+
v = self._view(project)
|
|
1595
|
+
try:
|
|
1596
|
+
saved = rq.save_requirement(Path(v.project["root"]), title=title, line=line, description=description, flow=flow,
|
|
1597
|
+
status=status, id=id)
|
|
1598
|
+
except rq.RequirementError as e:
|
|
1599
|
+
raise ToolError(f"没有保存:{e}") from None
|
|
1600
|
+
except OSError as e:
|
|
1601
|
+
raise ToolError(f"没有保存:写不进项目目录({e.strerror or e})") from None
|
|
1602
|
+
head = f"已保存到 {v.project['root']}/{saved.file}({'改写' if id else '新建'})。\n\n"
|
|
1603
|
+
return _cap(self._warning(v) + head + self._requirement_text(v, saved), "这条需求太长:直接读项目里的需求文件")
|
|
1604
|
+
|
|
1605
|
+
# ---------- run_line_tests:请平台运行一条功能线的测试 ----------
|
|
1606
|
+
|
|
1607
|
+
def _platform(self, method: str, path: str, body: dict | None = None) -> tuple[int, dict]:
|
|
1608
|
+
"""向正在运行的 pystepmap serve 发一个请求,返回 (状态码, JSON)。平台没在运行、连不上时抛 ToolError。测试由平台
|
|
1609
|
+
进程运行(这个进程不执行项目代码):用户在界面上看得到进度、可以取消。"""
|
|
1610
|
+
port = serve_port(self.store.path.parent)
|
|
1611
|
+
if port is None:
|
|
1612
|
+
raise ToolError("pystepmap 平台没有在运行:测试由平台运行,请用户先启动 pystepmap serve(同一个数据目录)")
|
|
1613
|
+
data = None if body is None else json.dumps(body).encode("utf-8")
|
|
1614
|
+
req = urllib.request.Request(f"http://127.0.0.1:{port}/api{path}", data=data, method=method,
|
|
1615
|
+
headers={"Content-Type": "application/json"} if data else {})
|
|
1616
|
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # 本机的请求不走代理
|
|
1617
|
+
try:
|
|
1618
|
+
with opener.open(req, timeout=30) as resp:
|
|
1619
|
+
return resp.status, json.loads(resp.read() or b"{}")
|
|
1620
|
+
except urllib.error.HTTPError as e:
|
|
1621
|
+
try:
|
|
1622
|
+
return e.code, json.loads(e.read() or b"{}")
|
|
1623
|
+
except ValueError:
|
|
1624
|
+
return e.code, {}
|
|
1625
|
+
except (OSError, ValueError) as e:
|
|
1626
|
+
raise ToolError(f"连不上 pystepmap 平台(127.0.0.1:{port}):{getattr(e, 'reason', None) or e}") from None
|
|
1627
|
+
|
|
1628
|
+
def run_line_tests(self, *, project: str | None = None, flow: str, start: bool = True,
|
|
1629
|
+
wait_seconds: int = DEFAULT_WAIT) -> str:
|
|
1630
|
+
"""请平台运行一条功能线的测试,等它跑完"""
|
|
1631
|
+
v = self._view(project)
|
|
1632
|
+
line = self._line(v, flow)
|
|
1633
|
+
sid, pid = v.sid(line), v.project["id"]
|
|
1634
|
+
base = f"/projects/{urllib.parse.quote(pid, safe='')}"
|
|
1635
|
+
head = f"功能线「{v.title(line)}」[{sid}]"
|
|
1636
|
+
last = max((r["id"] for r in self.store.list_runs(pid)), default=0)
|
|
1637
|
+
if start:
|
|
1638
|
+
status, data = self._platform("POST", f"{base}/runs", {"line": sid, "via": "mcp"})
|
|
1639
|
+
if status != 202:
|
|
1640
|
+
raise ToolError(f"没有运行{head}的测试:{data.get('error') or f'平台返回 {status}'}")
|
|
1641
|
+
deadline = time.monotonic() + max(0, min(int(wait_seconds), MAX_WAIT))
|
|
1642
|
+
while True:
|
|
1643
|
+
_, now = self._platform("GET", f"{base}/runs")
|
|
1644
|
+
if not now.get("running"):
|
|
1645
|
+
break
|
|
1646
|
+
if time.monotonic() >= deadline:
|
|
1647
|
+
p = now["running"].get("progress") or {}
|
|
1648
|
+
done = f",已跑完 {p['done']} / {p.get('collected') or '?'} 个" if p else ""
|
|
1649
|
+
return (f"{head}的测试还在平台上跑({now['running'].get('phase')}{done})。过一会儿用 start=false 再看结果;"
|
|
1650
|
+
"不要重复启动。")
|
|
1651
|
+
time.sleep(1.0)
|
|
1652
|
+
run = next((r for r in now.get("runs", []) if (r.get("scope") or {}).get("line") == sid
|
|
1653
|
+
and (not start or r["id"] > last)), None)
|
|
1654
|
+
if run is None:
|
|
1655
|
+
failure = now.get("last_failure")
|
|
1656
|
+
if start and failure:
|
|
1657
|
+
raise ToolError(f"{head}的测试没有跑成:{failure.get('title')}——{failure.get('reason')}")
|
|
1658
|
+
return f"{head}还没有单独运行过测试的结果。"
|
|
1659
|
+
return _cap(self._line_run_text(base, head, sid, run), "结果太长:在平台的\"运行路径\"页签里看这次运行")
|
|
1660
|
+
|
|
1661
|
+
def _line_run_text(self, base: str, head: str, sid: str, run: dict) -> str:
|
|
1662
|
+
s, scope = run["summary"], run["scope"]
|
|
1663
|
+
out = [(f"{head}的测试运行 #{run['id']}({_RUN_STATUS.get(run['status'], run['status'])}):名单 {scope['tests']} 个测试"
|
|
1664
|
+
f"(取自全量运行 #{scope['base_run']}),跑了 {s.get('tests', 0)} 个用例,通过 {s.get('passed', 0)}、"
|
|
1665
|
+
f"失败 {s.get('failed', 0)}、出错 {s.get('errors', 0)}、跳过 {s.get('skipped', 0)},用时 {s.get('seconds', 0):.1f} 秒。")]
|
|
1666
|
+
if s.get("note"):
|
|
1667
|
+
out.append(f"说明:{s['note']}")
|
|
1668
|
+
verify = s.get("verify") or {}
|
|
1669
|
+
if verify.get("ok") is True:
|
|
1670
|
+
out.append("图和实际执行一致。")
|
|
1671
|
+
elif verify.get("ok") is False:
|
|
1672
|
+
out.append(f"图和实际执行不一致:{verify.get('mismatches')}(在平台上看详情;多半是图过期了,先 analyze_project)。")
|
|
1673
|
+
_, detail = self._platform("GET", f"{base}/runs/{run['id']}")
|
|
1674
|
+
bad = [t for t in detail.get("tests", []) if t.get("outcome") in ("failed", "error")]
|
|
1675
|
+
if bad:
|
|
1676
|
+
out += ["", "没有通过的测试(失败的原因平台不存,自己运行这个测试看输出):"]
|
|
1677
|
+
out += [f"- {t['test']}({'失败' if t['outcome'] == 'failed' else '出错'})" for t in bad[:50]]
|
|
1678
|
+
if run.get("paths_size") is not None:
|
|
1679
|
+
status, unc = self._platform("GET", f"{base}/runs/{run['id']}/uncovered?line={urllib.parse.quote(sid, safe='')}")
|
|
1680
|
+
missed = [o for o in unc.get("outcomes", []) if not o.get("uncertain")] if status == 200 else []
|
|
1681
|
+
if missed:
|
|
1682
|
+
out += ["", f"这条线上这些测试没有走到的结局 {len(missed)} 个:"]
|
|
1683
|
+
out += [f"- {o['title']}({_END.get(o['end_kind'], o['end_kind'])}) {o['file']}:{o['line']}" for o in missed[:50]]
|
|
1684
|
+
elif status == 200:
|
|
1685
|
+
out += ["", "这条线上的每个结局都被这些测试走到了。"]
|
|
1686
|
+
out += ["", "注意:只跑了全量运行里走过这条线的测试;之后新写的测试不在名单里——让用户在平台上再运行一次全部测试。"]
|
|
1687
|
+
return "\n".join(out)
|
|
1688
|
+
|
|
1689
|
+
# ---------- uncovered_outcomes ----------
|
|
1690
|
+
|
|
1691
|
+
def uncovered_outcomes(self, *, project: str | None = None, flow: str | None = None) -> str:
|
|
1692
|
+
"""列出没有测试走到的结局。结果超过上限时截断(_cap):没给 flow 时提示用 flow 只看一条功能线;已经给了时提示去平台看、或只看具体的函数。"""
|
|
1693
|
+
hint = ("结局太多:用 flow 只看一条功能线" if flow is None
|
|
1694
|
+
else "这条功能线的结局太多:在平台的\"运行路径\"页签里看它(\"没走到的结局\"一节),或用 get_flow、find_nodes 只看具体的函数")
|
|
1695
|
+
return _cap(self._uncovered_text(project, flow), hint)
|
|
1696
|
+
|
|
1697
|
+
def _uncovered_text(self, project: str | None, flow: str | None) -> str:
|
|
1698
|
+
v = self._view(project)
|
|
1699
|
+
lines = v.graph.lines if flow is None else [self._line(v, flow)]
|
|
1700
|
+
# 新的在前;只有信息,不读路径。只看全量的运行:只跑一条功能线的运行说明不了别的线
|
|
1701
|
+
runs = [r for r in self.store.list_runs(v.project["id"]) if r.get("scope") is None]
|
|
1702
|
+
if not runs:
|
|
1703
|
+
return self._warning(v) + NEVER_RAN
|
|
1704
|
+
run = next((r for r in runs if r["paths_size"] is not None), None)
|
|
1705
|
+
head: list[str] = []
|
|
1706
|
+
if run is not runs[0]:
|
|
1707
|
+
latest = runs[0]
|
|
1708
|
+
head.append(f"最近一次运行(#{latest['id']})没有跑完({_RUN_STATUS.get(latest['status'], latest['status'])}),"
|
|
1709
|
+
+ ("没有运行路径。" if run is None else f"下面用的是跑完了的 #{run['id']}。"))
|
|
1710
|
+
if run is None:
|
|
1711
|
+
return self._warning(v) + "\n".join(head + ["平台上还没有跑完、有运行路径的测试运行。"])
|
|
1712
|
+
found_all = self._uncovered_of(v, run["id"])
|
|
1713
|
+
warning = self._warning(v)
|
|
1714
|
+
if run["analysis_id"] != v.analysis["id"]:
|
|
1715
|
+
newer = ("运行之后才有的函数和结局、对不上的结局单列在最后(不算没走到)" if found_all.known_then else
|
|
1716
|
+
"对不上的结局单列在最后;那次分析的图已经清理掉了,分不出哪些函数和结局是运行之后才加的——下面\"没有"
|
|
1717
|
+
"测试走到\"的里面可能有那次运行时还不存在的代码")
|
|
1718
|
+
warning += (f"⚠ 最近一次运行(#{run['id']})用的是分析 #{run['analysis_id']},之后重新分析过(现在是 "
|
|
1719
|
+
f"#{v.analysis['id']}):结局按 sid 对到最新的图上,{newer};之后改动的代码有没有"
|
|
1720
|
+
f"测试走到,要在平台上重新运行测试才知道。\n\n")
|
|
1721
|
+
head.append(f"项目「{v.project['name']}」的测试运行 {_run_head(run)}")
|
|
1722
|
+
missed: list[str] = []
|
|
1723
|
+
unsure: list[str] = []
|
|
1724
|
+
seen_missed: set[tuple[str, str]] = set()
|
|
1725
|
+
seen_unsure: set[tuple[str, str]] = set()
|
|
1726
|
+
for ln in lines:
|
|
1727
|
+
found = found_all.outcomes(v.sid(ln))
|
|
1728
|
+
rows_missed = [self._outcome_row(v.graph, o) for o in found if not o.uncertain]
|
|
1729
|
+
rows_unsure = [self._outcome_row(v.graph, o) for o in found if o.uncertain]
|
|
1730
|
+
seen_missed.update((o.function, o.node) for o in found if not o.uncertain)
|
|
1731
|
+
seen_unsure.update((o.function, o.node) for o in found if o.uncertain)
|
|
1732
|
+
if rows_missed:
|
|
1733
|
+
missed += ["", f"## {v.ref(ln)}", *rows_missed]
|
|
1734
|
+
if rows_unsure:
|
|
1735
|
+
unsure += ["", f"## {v.ref(ln)}", *rows_unsure]
|
|
1736
|
+
where = f"功能线「{v.title(lines[0])}」里" if flow is not None else "功能线上"
|
|
1737
|
+
out = [*head, ""]
|
|
1738
|
+
if seen_missed:
|
|
1739
|
+
out.append(f"{where}没有测试走到的结局 {len(seen_missed)} 个(按功能线分组,同一个结局在几条线上时每条都列;"
|
|
1740
|
+
f"未捕获异常退出不算):")
|
|
1741
|
+
out += missed
|
|
1742
|
+
else:
|
|
1743
|
+
out.append(f"{where}的每个结局都有测试走到(未捕获异常退出不算)。")
|
|
1744
|
+
if seen_unsure:
|
|
1745
|
+
out += ["", (f"需要重新运行测试才知道的结局 {len(seen_unsure)} 个(运行之后才有的函数、结局,或者运行之后"
|
|
1746
|
+
f"函数的节点变了、同文本的几个结局分不清运行时走的是哪一个;既不算走到也不算没走到):")]
|
|
1747
|
+
out += unsure
|
|
1748
|
+
return warning + "\n".join(out)
|
|
1749
|
+
|
|
1750
|
+
def _outcome_row(self, g: ProjectGraph, o: Outcome) -> str:
|
|
1751
|
+
fg = g.functions.get(g.sids.get(o.function) or o.function)
|
|
1752
|
+
name = fg.qualname if fg is not None else o.function
|
|
1753
|
+
where = f"{o.file}:{o.line}" if o.line else f"{o.file}(执行到函数末尾)"
|
|
1754
|
+
return f"- [{o.node}] {o.title}({_END.get(o.end_kind, o.end_kind)}) {where} 函数 {name} [{o.function}]"
|
|
1755
|
+
|
|
1756
|
+
def _uncovered_of(self, v: _View, run_id: int) -> Uncovered:
|
|
1757
|
+
"""这次运行的路径叠到 v 的图(最新一次分析)上算出的没走到的结局;按(分析,运行)缓存最近 GRAPH_CACHE 对。"""
|
|
1758
|
+
key = (v.analysis["id"], run_id)
|
|
1759
|
+
with self._lock:
|
|
1760
|
+
if key in self._uncovered:
|
|
1761
|
+
self._uncovered.move_to_end(key)
|
|
1762
|
+
return self._uncovered[key]
|
|
1763
|
+
try:
|
|
1764
|
+
found = uncovered_of(self.store, v.project["id"], run_id, v.analysis["id"], v.graph)
|
|
1765
|
+
except (OSError, EOFError, ValueError) as e:
|
|
1766
|
+
raise ToolError(f"运行 #{run_id} 存着的运行路径读不出来:{e}") from None
|
|
1767
|
+
if found is None:
|
|
1768
|
+
raise ToolError("这次运行刚被清理掉了,请再调用一次")
|
|
1769
|
+
with self._lock:
|
|
1770
|
+
self._uncovered[key] = found
|
|
1771
|
+
while len(self._uncovered) > GRAPH_CACHE:
|
|
1772
|
+
self._uncovered.popitem(last=False)
|
|
1773
|
+
return found
|
|
1774
|
+
|
|
1775
|
+
|
|
1776
|
+
# ---------- 模块级的小工具(要用到上面的类型) ----------
|
|
1777
|
+
|
|
1778
|
+
def _top_names(sites: list[UnresolvedSite]) -> str:
|
|
1779
|
+
"""这些调用里最常见的几个名字:"commit 88、execute 60、where 54"。"""
|
|
1780
|
+
counts = Counter(s.name.rpartition(".")[2] for s in sites)
|
|
1781
|
+
return "、".join(f"{name} {n}" for name, n in counts.most_common(3))
|
|
1782
|
+
|
|
1783
|
+
|
|
1784
|
+
def _run_head(run: dict) -> str:
|
|
1785
|
+
"""一次运行一句话:#id(时间,状态,用的是分析 #n):N 个用例,通过 a、失败 b……"""
|
|
1786
|
+
s = run["summary"]
|
|
1787
|
+
counts = f"{s.get('tests', 0)} 个用例,通过 {s.get('passed', 0)}、失败 {s.get('failed', 0)}"
|
|
1788
|
+
if s.get("errors"):
|
|
1789
|
+
counts += f"、出错 {s['errors']}"
|
|
1790
|
+
if s.get("skipped"):
|
|
1791
|
+
counts += f"、跳过 {s['skipped']}"
|
|
1792
|
+
return (f"#{run['id']}({_when(run['finished_at'])},状态:{_RUN_STATUS.get(run['status'], run['status'])},用的是分析 "
|
|
1793
|
+
f"#{run['analysis_id']}):{counts};测试命令跑了 {s.get('seconds', 0)} 秒")
|
|
1794
|
+
|
|
1795
|
+
|
|
1796
|
+
def _uncaught(n: Node) -> bool:
|
|
1797
|
+
""""未捕获异常退出":隐含的异常结局,没有入边。"""
|
|
1798
|
+
return n.type == "end" and n.end_kind == "exception" and not n.line
|
|
1799
|
+
|
|
1800
|
+
|
|
1801
|
+
def _chain_text(g: ProjectGraph, line: FlowLine, key: str) -> str:
|
|
1802
|
+
chain = entry_chain(g, line, key)
|
|
1803
|
+
if chain is None:
|
|
1804
|
+
return "(找不到从入口到它的调用链)"
|
|
1805
|
+
if not chain:
|
|
1806
|
+
return "就在功能线的根函数里"
|
|
1807
|
+
parts = []
|
|
1808
|
+
for link in chain:
|
|
1809
|
+
fg = g.functions[link.function]
|
|
1810
|
+
n = next(x for x in fg.nodes if x.id == link.node)
|
|
1811
|
+
at = f"L{n.line} " if n.line else ""
|
|
1812
|
+
parts.append(f"{_FN_KIND.get(fg.kind, '函数')} {fg.qualname} 在 {node_ref(fg, n)} {at}"
|
|
1813
|
+
f"{'派发' if link.how == 'dispatch' else '调用'}")
|
|
1814
|
+
target = g.functions[key]
|
|
1815
|
+
return " → ".join([*parts, f"{_FN_KIND.get(target.kind, '函数')} {target.qualname}"])
|
|
1816
|
+
|
|
1817
|
+
|
|
1818
|
+
def _relative(root: str, file: str) -> str | None:
|
|
1819
|
+
"""给提示用的相对路径:相对路径规范化;绝对路径要在 root 下。"""
|
|
1820
|
+
path = file.replace("\\", "/")
|
|
1821
|
+
if os.path.isabs(path):
|
|
1822
|
+
for base in dict.fromkeys((root.rstrip("/"), os.path.realpath(root).rstrip("/"))):
|
|
1823
|
+
if path.startswith(base + "/"):
|
|
1824
|
+
return posixpath.normpath(path[len(base) + 1:])
|
|
1825
|
+
return None
|
|
1826
|
+
path = posixpath.normpath(path)
|
|
1827
|
+
return None if path.startswith("../") or path == ".." else path
|
|
1828
|
+
|
|
1829
|
+
|
|
1830
|
+
def _load_diff(data: dict) -> GraphDiff:
|
|
1831
|
+
try:
|
|
1832
|
+
return diff_from_json(data)
|
|
1833
|
+
except ValueError as e:
|
|
1834
|
+
raise ToolError(f"存着的流程差异读不出来:{e}") from None
|
|
1835
|
+
|
|
1836
|
+
|
|
1837
|
+
MAX_NEW_SKIPPED = 10
|
|
1838
|
+
|
|
1839
|
+
|
|
1840
|
+
def _newly_skipped(before: dict | None, summary: dict) -> list[str]:
|
|
1841
|
+
"""这次分析新出现的解析不了的文件(上一次不在跳过的文件里),最多点名 MAX_NEW_SKIPPED 个;没有时空列表。这些文件里的
|
|
1842
|
+
函数不在图上,流程差异会把它们报成删除。"""
|
|
1843
|
+
old = {item.get("file") for item in ((before or {}).get("summary") or {}).get("skipped_files", []) if isinstance(item, dict)}
|
|
1844
|
+
new = [item for item in summary.get("skipped_files", []) if isinstance(item, dict) and item.get("file") not in old]
|
|
1845
|
+
if not new:
|
|
1846
|
+
return []
|
|
1847
|
+
named = "、".join(f"{item.get('file')}({item.get('reason', '')})" for item in new[:MAX_NEW_SKIPPED])
|
|
1848
|
+
more = f" 等 {len(new)} 个" if len(new) > MAX_NEW_SKIPPED else ""
|
|
1849
|
+
return [(f"这次有 {len(new)} 个文件解析不了(图里没有它们):{named}{more}。下面流程变化里报成删除的函数可能只是因为"
|
|
1850
|
+
f"所在的文件解析不了,并没有真的删掉;修好文件再调用 analyze_project。")]
|
|
1851
|
+
|
|
1852
|
+
|
|
1853
|
+
def _baseline_text(state: dict) -> str:
|
|
1854
|
+
"""对比基准说成什么:相对上次标为已看时(那次分析的时间)/ 相对第一次分析(时间);旧数据没有说法时按分析编号。"""
|
|
1855
|
+
baseline, base = state.get("baseline"), state["base"]
|
|
1856
|
+
if baseline and baseline.get("kind") == "acknowledged":
|
|
1857
|
+
return f"相对上次标为已看时({_when(baseline['at'])})"
|
|
1858
|
+
if baseline and baseline.get("kind") == "first":
|
|
1859
|
+
return f"相对第一次分析({_when(baseline['at'])})"
|
|
1860
|
+
return f"相对对比基准(#{base['id']},{_when(base['created_at'])})"
|
|
1861
|
+
|
|
1862
|
+
|
|
1863
|
+
def _with_overrides(d: GraphDiff, overrides: dict[str, dict]) -> GraphDiff:
|
|
1864
|
+
"""差异里的功能线用手工改过的标题和分组(和别的工具一致);标题改过时括号里带原来的。原地改 d,返回它。"""
|
|
1865
|
+
for ln in d.lines:
|
|
1866
|
+
item = overrides.get(ln.sid, {})
|
|
1867
|
+
if item.get("title") and item["title"] != ln.title:
|
|
1868
|
+
ln.title = f"{item['title']}(原标题:{ln.title})"
|
|
1869
|
+
if item.get("group"):
|
|
1870
|
+
ln.group = item["group"]
|
|
1871
|
+
return d
|
|
1872
|
+
|
|
1873
|
+
|
|
1874
|
+
def _coerce(key: str, prop: dict, value: object) -> object:
|
|
1875
|
+
"""按参数的 JSON schema 规整值;空字符串、null 当作没给(None)。类型不对时 ToolError。"""
|
|
1876
|
+
if value is None or (isinstance(value, str) and not value.strip()):
|
|
1877
|
+
return None
|
|
1878
|
+
kind = prop.get("type")
|
|
1879
|
+
if kind == "integer":
|
|
1880
|
+
if isinstance(value, bool):
|
|
1881
|
+
raise ToolError(f"{key} 应该是整数")
|
|
1882
|
+
if isinstance(value, int):
|
|
1883
|
+
return value
|
|
1884
|
+
if isinstance(value, float) and value.is_integer():
|
|
1885
|
+
return int(value)
|
|
1886
|
+
if isinstance(value, str) and value.strip().lstrip("-").isdigit():
|
|
1887
|
+
return int(value.strip())
|
|
1888
|
+
raise ToolError(f"{key} 应该是整数,这次是 {json.dumps(value, ensure_ascii=False)[:40]}")
|
|
1889
|
+
if kind == "boolean":
|
|
1890
|
+
if isinstance(value, bool):
|
|
1891
|
+
return value
|
|
1892
|
+
if isinstance(value, str) and value.strip().lower() in ("true", "false"):
|
|
1893
|
+
return value.strip().lower() == "true"
|
|
1894
|
+
raise ToolError(f"{key} 应该是 true 或 false")
|
|
1895
|
+
if kind == "array":
|
|
1896
|
+
if not isinstance(value, list) or not all(isinstance(x, str) for x in value):
|
|
1897
|
+
raise ToolError(f"{key} 应该是字符串列表")
|
|
1898
|
+
return value
|
|
1899
|
+
if not isinstance(value, str):
|
|
1900
|
+
raise ToolError(f"{key} 应该是字符串")
|
|
1901
|
+
return value.strip()
|