astsight 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.
- astsight/__init__.py +18 -0
- astsight/__main__.py +4 -0
- astsight/agent/__init__.py +44 -0
- astsight/agent/case_design.py +421 -0
- astsight/agent/casegen.py +196 -0
- astsight/agent/data_prep.py +265 -0
- astsight/agent/diagnosis.py +221 -0
- astsight/agent/errors.py +15 -0
- astsight/agent/flow.py +1345 -0
- astsight/agent/jar.py +235 -0
- astsight/agent/mock_semantics.py +136 -0
- astsight/agent/mockplan.py +481 -0
- astsight/agent/models.py +285 -0
- astsight/agent/repair.py +538 -0
- astsight/agent/rule_analysis.py +150 -0
- astsight/agent/semantic.py +250 -0
- astsight/agent/sut.py +442 -0
- astsight/artifacts.py +73 -0
- astsight/cases/__init__.py +5 -0
- astsight/cases/adapters.py +79 -0
- astsight/cases/context.py +764 -0
- astsight/cases/data_refs.py +167 -0
- astsight/cases/deleted_cleanup.py +121 -0
- astsight/cases/draft.py +575 -0
- astsight/cases/expressions.py +256 -0
- astsight/cases/proposal.py +1500 -0
- astsight/cases/regexsample.py +242 -0
- astsight/cases/relations.py +193 -0
- astsight/cases/requirements.py +269 -0
- astsight/cases/store.py +362 -0
- astsight/cases/strength.py +77 -0
- astsight/cases/templates.py +613 -0
- astsight/cases/validate.py +738 -0
- astsight/cases/validate_assertions.py +733 -0
- astsight/cases/validate_base.py +418 -0
- astsight/cases/validate_coverage.py +288 -0
- astsight/cases/validate_data.py +227 -0
- astsight/cases/validate_dubbo.py +300 -0
- astsight/cases/validate_mqmock.py +349 -0
- astsight/cases/validate_profile.py +168 -0
- astsight/cases/validate_rules.py +280 -0
- astsight/cases/validate_semantics.py +199 -0
- astsight/cases/validate_steps.py +510 -0
- astsight/changes/__init__.py +13 -0
- astsight/changes/contract_diff.py +310 -0
- astsight/changes/deleted.py +161 -0
- astsight/changes/git_diff.py +182 -0
- astsight/changes/impact.py +464 -0
- astsight/changes/symbol_diff.py +431 -0
- astsight/changes/transport_contracts.py +385 -0
- astsight/cli.py +1537 -0
- astsight/codegen/__init__.py +5 -0
- astsight/codegen/pytest_gen.py +1814 -0
- astsight/commands/__init__.py +1 -0
- astsight/commands/_shared.py +42 -0
- astsight/commands/data.py +490 -0
- astsight/commands/init.py +172 -0
- astsight/commands/mock.py +333 -0
- astsight/commands/rules.py +360 -0
- astsight/data/__init__.py +124 -0
- astsight/data/annotations.py +458 -0
- astsight/data/apply.py +310 -0
- astsight/data/catalog.py +402 -0
- astsight/data/codeconst.py +1281 -0
- astsight/data/connection.py +74 -0
- astsight/data/dbml.py +727 -0
- astsight/data/ddl.py +642 -0
- astsight/data/dialects.py +156 -0
- astsight/data/fixtures.py +193 -0
- astsight/data/plan.py +444 -0
- astsight/data/reflect.py +667 -0
- astsight/data/render.py +133 -0
- astsight/data/seed.py +142 -0
- astsight/data/semantics.py +211 -0
- astsight/data/states.py +1214 -0
- astsight/data/validate.py +234 -0
- astsight/evaluation.py +205 -0
- astsight/execute/__init__.py +6 -0
- astsight/execute/diagnose.py +192 -0
- astsight/execute/dubbo_targets.py +734 -0
- astsight/execute/runner.py +357 -0
- astsight/feedback.py +573 -0
- astsight/inventory.py +406 -0
- astsight/llm/__init__.py +28 -0
- astsight/llm/client.py +634 -0
- astsight/mock/__init__.py +122 -0
- astsight/mock/evidence.py +388 -0
- astsight/mock/gripmock_binary.py +246 -0
- astsight/mock/grpc_descriptor.py +299 -0
- astsight/mock/grpc_runtime.py +423 -0
- astsight/mock/identity.py +482 -0
- astsight/mock/matching.py +75 -0
- astsight/mock/plan.py +1246 -0
- astsight/mock/replies.py +84 -0
- astsight/mock/routes.py +231 -0
- astsight/mock/runtime.py +225 -0
- astsight/mock/semantic.py +539 -0
- astsight/mock/server.py +1481 -0
- astsight/mock/sessions.py +222 -0
- astsight/mq/__init__.py +1 -0
- astsight/mq/inject/capture.py +337 -0
- astsight/mq/inject/sitecustomize.py +14 -0
- astsight/persistence.py +86 -0
- astsight/pipeline.py +1733 -0
- astsight/profile/__init__.py +36 -0
- astsight/profile/builder.py +297 -0
- astsight/profile/callsite.py +46 -0
- astsight/profile/downstream.py +1967 -0
- astsight/profile/dubbo.py +2141 -0
- astsight/profile/grpc_downstream.py +758 -0
- astsight/profile/javaclass.py +431 -0
- astsight/profile/javadeps.py +277 -0
- astsight/profile/javatypes.py +1037 -0
- astsight/profile/langroutes.py +1051 -0
- astsight/profile/langscan.py +1363 -0
- astsight/profile/mq.py +804 -0
- astsight/profile/openapi.py +288 -0
- astsight/report/__init__.py +5 -0
- astsight/report/merge.py +1098 -0
- astsight/rules/__init__.py +102 -0
- astsight/rules/conflicts.py +269 -0
- astsight/rules/context.py +552 -0
- astsight/rules/contract.py +233 -0
- astsight/rules/contract_model.py +1361 -0
- astsight/rules/coverage.py +127 -0
- astsight/rules/diff.py +143 -0
- astsight/rules/draft.py +152 -0
- astsight/rules/grounding.py +110 -0
- astsight/rules/relations.py +319 -0
- astsight/rules/render.py +413 -0
- astsight/rules/store.py +547 -0
- astsight/rules/validate.py +399 -0
- astsight/sidecar/__init__.py +37 -0
- astsight/sidecar/dubbo.py +449 -0
- astsight/sidecar/package.py +251 -0
- astsight/sidecar/triple.py +258 -0
- astsight-0.1.0.dist-info/METADATA +1348 -0
- astsight-0.1.0.dist-info/RECORD +158 -0
- astsight-0.1.0.dist-info/WHEEL +5 -0
- astsight-0.1.0.dist-info/entry_points.txt +2 -0
- astsight-0.1.0.dist-info/top_level.txt +3 -0
- codegraph/__init__.py +55 -0
- codegraph/bridge/codegraph_worker.mjs +548 -0
- codegraph/client.py +158 -0
- codegraph/embedded.py +561 -0
- codegraph/memory.py +89 -0
- codegraph/route_repair.py +1680 -0
- codegraph/runtime.py +270 -0
- contracts/__init__.py +245 -0
- contracts/base.py +37 -0
- contracts/cases.py +100 -0
- contracts/data.py +209 -0
- contracts/entities.py +436 -0
- contracts/enums.py +355 -0
- contracts/mock.py +350 -0
- contracts/mock_plan.py +209 -0
- contracts/mock_semantic.py +89 -0
- contracts/rules.py +340 -0
astsight/agent/flow.py
ADDED
|
@@ -0,0 +1,1345 @@
|
|
|
1
|
+
"""端到端 Agent 流程(第一版):
|
|
2
|
+
|
|
3
|
+
代码变更 → 接口识别 → A1 语义分析 → A4 用例草案 → 校验/审核
|
|
4
|
+
→ Mock 计划与运行时 → 注入并启动 SUT → 执行 → A5/A6 诊断与修复(有界)
|
|
5
|
+
|
|
6
|
+
边界:
|
|
7
|
+
- 初始用例必须经过 proposal;`approve_as` 只自动批准 new/update/revive,
|
|
8
|
+
deprecate 永远 reject(人工逐项批准)。
|
|
9
|
+
- 运行期失败修复由 Agent 在同一节点诊断并打补丁,默认最多 3 轮;
|
|
10
|
+
用例补丁生成新的 proposal 并以 `astsight-agent:repair` 身份自动批准,
|
|
11
|
+
Mock 分支补丁直接热更新到已启动的 Mock 服务。两者都留下审计记录。
|
|
12
|
+
- 修复不得删除断言或降低断言强度;身份字段与需求归属不可改。
|
|
13
|
+
- 模型输出全部按不可信输入处理,证据校验失败即中止。
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import re
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from types import SimpleNamespace
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from contracts import DataCatalog, DataPlanBundle, MockSemantic, RuleSet
|
|
25
|
+
|
|
26
|
+
from ..artifacts import RunDir, new_run_id, utc_now
|
|
27
|
+
from ..feedback import collect_feedback
|
|
28
|
+
from ..report.merge import render_markdown
|
|
29
|
+
from ..cases.context import build_context
|
|
30
|
+
from ..cases.proposal import (
|
|
31
|
+
approve_proposal,
|
|
32
|
+
build_proposal,
|
|
33
|
+
list_pending_proposals,
|
|
34
|
+
)
|
|
35
|
+
from ..cases.store import (
|
|
36
|
+
approved_cases,
|
|
37
|
+
case_summary,
|
|
38
|
+
empty_case_set,
|
|
39
|
+
load_case_set,
|
|
40
|
+
requirement_coverage,
|
|
41
|
+
resolve_case_base,
|
|
42
|
+
store_hash,
|
|
43
|
+
)
|
|
44
|
+
from ..cases.validate import validate_draft
|
|
45
|
+
from ..changes.git_diff import diff_files, repo_root, resolve_range
|
|
46
|
+
from ..changes.impact import analyze_impact
|
|
47
|
+
from ..changes.symbol_diff import symbols_for_changes
|
|
48
|
+
from ..data import (
|
|
49
|
+
build_catalog,
|
|
50
|
+
build_data_plan_bundle,
|
|
51
|
+
dialect_from_url,
|
|
52
|
+
load_seed,
|
|
53
|
+
normalize_dialect,
|
|
54
|
+
parse_ddl,
|
|
55
|
+
validate_catalog,
|
|
56
|
+
)
|
|
57
|
+
from ..inventory import (
|
|
58
|
+
discover_openapi,
|
|
59
|
+
inventory_routes,
|
|
60
|
+
route_inventory_health,
|
|
61
|
+
)
|
|
62
|
+
from ..llm import LLMClient, load_config
|
|
63
|
+
from ..mock import MockPlanError, start_mock_plan
|
|
64
|
+
from ..mock.semantic import build_mock_semantic
|
|
65
|
+
from ..persistence import load_json, save_json_atomic
|
|
66
|
+
from ..pipeline import RunConfig, execute_cases, execute_with_runtime
|
|
67
|
+
from ..profile import load_spec, parse_operations
|
|
68
|
+
from ..profile.openapi import normalize_path
|
|
69
|
+
from ..rules import (
|
|
70
|
+
build_rules_context,
|
|
71
|
+
load_rule_set,
|
|
72
|
+
render_rule_set_markdown,
|
|
73
|
+
save_rule_set,
|
|
74
|
+
write_rules_context,
|
|
75
|
+
)
|
|
76
|
+
from .case_design import generate_case_design
|
|
77
|
+
from .data_prep import generate_data_plans, generate_data_semantics
|
|
78
|
+
from .errors import AgentError
|
|
79
|
+
from .mock_semantics import generate_mock_semantic_candidates
|
|
80
|
+
from .mockplan import build_mock_plan, sync_mock_semantic
|
|
81
|
+
from .repair import RepairOutcome, diagnose_and_repair
|
|
82
|
+
from .rule_analysis import (
|
|
83
|
+
generate_rule_draft,
|
|
84
|
+
import_rule_draft_for_flow,
|
|
85
|
+
rule_prompt_metadata,
|
|
86
|
+
)
|
|
87
|
+
from .sut import start_sut
|
|
88
|
+
|
|
89
|
+
_APPROVE_ACTIONS = {"new", "update", "revive"}
|
|
90
|
+
_REPAIR_REVIEWER = "astsight-agent:repair"
|
|
91
|
+
_SUT_ID_RE = re.compile(r"[^0-9A-Za-z_.-]+")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass
|
|
95
|
+
class FlowConfig:
|
|
96
|
+
project: str
|
|
97
|
+
requirements: list[str]
|
|
98
|
+
openapi: str | None = None
|
|
99
|
+
llm_config: str | None = None
|
|
100
|
+
mode: str = "full" # full | delta
|
|
101
|
+
base: str = "main"
|
|
102
|
+
target: str = "HEAD"
|
|
103
|
+
depth: int = 5
|
|
104
|
+
base_url: str | None = None
|
|
105
|
+
reset_url: str | None = None
|
|
106
|
+
dubbo_url: str | None = None
|
|
107
|
+
dubbo_host: str | None = None
|
|
108
|
+
dubbo_target: str | None = None
|
|
109
|
+
dubbo_targets: str | None = None
|
|
110
|
+
dubbo_source_sha256: str | None = None
|
|
111
|
+
dubbo_source_commit: str | None = None
|
|
112
|
+
dubbo_source_branch: str | None = None
|
|
113
|
+
dubbo_artifact: str | None = None
|
|
114
|
+
dubbo_target_override: bool = False
|
|
115
|
+
codegraph: str = "auto"
|
|
116
|
+
codegraph_module_root: str | None = None
|
|
117
|
+
full_index: bool | None = None
|
|
118
|
+
case_base: str | None = None
|
|
119
|
+
out: str = ".astsight/agent"
|
|
120
|
+
approve_as: str | None = None
|
|
121
|
+
max_repair_rounds: int = 3
|
|
122
|
+
max_cases: int = 200
|
|
123
|
+
sut_command: list[str] | None = None
|
|
124
|
+
sut_ready_url: str | None = None
|
|
125
|
+
sut_env: dict[str, str] = field(default_factory=dict)
|
|
126
|
+
sut_timeout: float = 60.0
|
|
127
|
+
timeout: float = 600.0
|
|
128
|
+
retries: int = 1
|
|
129
|
+
collect_only: bool = True
|
|
130
|
+
skip_execute: bool = False
|
|
131
|
+
allow_unmapped: bool = True
|
|
132
|
+
min_pass_rate: float = 0.95
|
|
133
|
+
mock_host: str = "127.0.0.1"
|
|
134
|
+
mock_port: int = 0
|
|
135
|
+
gripmock_path: str | None = None
|
|
136
|
+
feedback: str = "auto" # auto | always | off
|
|
137
|
+
rule_base: str | None = None
|
|
138
|
+
data_ddl: list[str] = field(default_factory=list)
|
|
139
|
+
data_seed: str | None = None
|
|
140
|
+
data_catalog: str | None = None
|
|
141
|
+
data_plan: str | None = None
|
|
142
|
+
database_url: str | None = None
|
|
143
|
+
data_dialect: str | None = None
|
|
144
|
+
skip_data: bool = False
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@dataclass
|
|
148
|
+
class FlowResult:
|
|
149
|
+
run_id: str
|
|
150
|
+
run_dir: Path
|
|
151
|
+
status: str
|
|
152
|
+
steps: dict[str, Any] = field(default_factory=dict)
|
|
153
|
+
warnings: list[str] = field(default_factory=list)
|
|
154
|
+
errors: list[str] = field(default_factory=list)
|
|
155
|
+
report: dict[str, Any] | None = None
|
|
156
|
+
llm_usage: list[dict[str, Any]] = field(default_factory=list)
|
|
157
|
+
|
|
158
|
+
def as_dict(self) -> dict[str, Any]:
|
|
159
|
+
return {
|
|
160
|
+
"run_id": self.run_id,
|
|
161
|
+
"run_dir": str(self.run_dir),
|
|
162
|
+
"status": self.status,
|
|
163
|
+
"steps": self.steps,
|
|
164
|
+
"warnings": self.warnings,
|
|
165
|
+
"errors": self.errors,
|
|
166
|
+
"report": self.report,
|
|
167
|
+
"llm_usage": self.llm_usage,
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _sut_id(project: Path) -> str:
|
|
172
|
+
cleaned = _SUT_ID_RE.sub("-", project.name).strip("-._")
|
|
173
|
+
return (cleaned or "sut")[:64]
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _full_scope(routes: list[dict]) -> tuple[list[dict], dict]:
|
|
177
|
+
changed_apis: list[dict] = []
|
|
178
|
+
for route in routes:
|
|
179
|
+
method = (route.get("method") or "").upper()
|
|
180
|
+
if not method:
|
|
181
|
+
continue
|
|
182
|
+
handler = route.get("handler", "")
|
|
183
|
+
changed_apis.append(
|
|
184
|
+
{
|
|
185
|
+
"handler": f"{method} {route.get('path')}",
|
|
186
|
+
"method": method,
|
|
187
|
+
"path": route.get("path", ""),
|
|
188
|
+
"route_handler": handler,
|
|
189
|
+
"confidence": "high",
|
|
190
|
+
"evidence": route.get("confidence", "verified"),
|
|
191
|
+
"changed_symbols": [],
|
|
192
|
+
"change_files": [route.get("file", "")],
|
|
193
|
+
"trace": [handler] if handler else [],
|
|
194
|
+
"route_source": route.get("source", ""),
|
|
195
|
+
"scope": "full",
|
|
196
|
+
}
|
|
197
|
+
)
|
|
198
|
+
return changed_apis, {
|
|
199
|
+
"mode": "full",
|
|
200
|
+
"note": "full 模式扫描全量路由,不依赖 git diff",
|
|
201
|
+
"changed_files": 0,
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _delta_scope(
|
|
206
|
+
project: Path, config: FlowConfig, routes: list[dict], graph_client: Any
|
|
207
|
+
) -> tuple[list[dict], dict, list[dict]]:
|
|
208
|
+
root = repo_root(project)
|
|
209
|
+
if root != project:
|
|
210
|
+
raise AgentError(
|
|
211
|
+
"delta_project_not_repo_root",
|
|
212
|
+
f"delta 模式要求 --project 指向仓库根,当前为子目录: {project}(根: {root})",
|
|
213
|
+
)
|
|
214
|
+
range_arg, comparison = resolve_range(project, config.base, config.target)
|
|
215
|
+
file_changes, changes_meta = diff_files(project, config.base, config.target)
|
|
216
|
+
changes_meta["comparison"] = comparison
|
|
217
|
+
changes_meta["range"] = range_arg
|
|
218
|
+
changed_symbols, unsupported = symbols_for_changes(
|
|
219
|
+
project,
|
|
220
|
+
config.base,
|
|
221
|
+
config.target,
|
|
222
|
+
file_changes,
|
|
223
|
+
codegraph_client=graph_client,
|
|
224
|
+
)
|
|
225
|
+
summary = analyze_impact(
|
|
226
|
+
changed_symbols,
|
|
227
|
+
routes,
|
|
228
|
+
graph_client,
|
|
229
|
+
depth=config.depth,
|
|
230
|
+
project_root=project,
|
|
231
|
+
)
|
|
232
|
+
impact = summary.as_dict()
|
|
233
|
+
impact["changed_symbols"] = [symbol.as_dict() for symbol in changed_symbols]
|
|
234
|
+
impact["unsupported_files"] = unsupported
|
|
235
|
+
changes_meta.update(
|
|
236
|
+
{
|
|
237
|
+
"files": [item.as_dict() for item in file_changes],
|
|
238
|
+
"symbols": [symbol.as_dict() for symbol in changed_symbols],
|
|
239
|
+
"unsupported_files": unsupported,
|
|
240
|
+
}
|
|
241
|
+
)
|
|
242
|
+
return impact.get("changed_apis") or [], changes_meta, unsupported
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _align_to_openapi(changed_apis: list[dict], operations: list[Any]) -> None:
|
|
246
|
+
index = {
|
|
247
|
+
(op.method.upper(), normalize_path(op.path)): op for op in operations
|
|
248
|
+
}
|
|
249
|
+
for api in changed_apis:
|
|
250
|
+
operation = index.get(
|
|
251
|
+
((api.get("method") or "").upper(), normalize_path(api.get("path", "")))
|
|
252
|
+
)
|
|
253
|
+
if operation is not None and operation.path != api.get("path"):
|
|
254
|
+
api["path_aligned_from"] = api.get("path", "")
|
|
255
|
+
api["path"] = operation.path
|
|
256
|
+
api["handler"] = f"{api.get('method', '').upper()} {operation.path}"
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _profile_routes(changed_apis: list[dict]) -> list[dict]:
|
|
260
|
+
return [
|
|
261
|
+
{
|
|
262
|
+
"method": api.get("method", ""),
|
|
263
|
+
"path": api.get("path", ""),
|
|
264
|
+
"handler": api.get("route_handler", ""),
|
|
265
|
+
"owner": api.get("route_owner", ""),
|
|
266
|
+
"file": api.get("route_file") or (api.get("change_files") or [""])[0],
|
|
267
|
+
"line": api.get("route_line", 0) or 0,
|
|
268
|
+
"source": api.get("route_source", ""),
|
|
269
|
+
"confidence": api.get("evidence", "inferred"),
|
|
270
|
+
}
|
|
271
|
+
for api in changed_apis
|
|
272
|
+
]
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _fill_decisions(review_path: Path, reviewer: str) -> dict[str, int]:
|
|
276
|
+
"""只自动批准新增/更新/恢复;废弃项一律 reject,等待人工逐项批准。"""
|
|
277
|
+
review = json.loads(review_path.read_text(encoding="utf-8"))
|
|
278
|
+
counts = {"approve": 0, "reject": 0}
|
|
279
|
+
for item in review.get("items") or []:
|
|
280
|
+
action = str(item.get("action") or "")
|
|
281
|
+
if action in _APPROVE_ACTIONS:
|
|
282
|
+
item["decision"] = "approve"
|
|
283
|
+
item["note"] = "agent flow: 自动批准(人工审核入口仍保留)"
|
|
284
|
+
counts["approve"] += 1
|
|
285
|
+
else:
|
|
286
|
+
item["decision"] = "reject"
|
|
287
|
+
item["note"] = f"agent flow: {action} 必须人工逐项批准"
|
|
288
|
+
counts["reject"] += 1
|
|
289
|
+
item["reviewer"] = reviewer
|
|
290
|
+
review_path.write_text(
|
|
291
|
+
json.dumps(review, ensure_ascii=False, indent=2),
|
|
292
|
+
encoding="utf-8",
|
|
293
|
+
)
|
|
294
|
+
return counts
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _scope_cases(store: Any, draft: Any) -> list[Any]:
|
|
298
|
+
allowed = {
|
|
299
|
+
(case.endpoint, case.case_key)
|
|
300
|
+
for case in getattr(draft, "cases", []) or []
|
|
301
|
+
}
|
|
302
|
+
return [
|
|
303
|
+
entry
|
|
304
|
+
for entry in approved_cases(store)
|
|
305
|
+
if (entry.endpoint, entry.case_key) in allowed
|
|
306
|
+
]
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _store_state(store: Any, store_path: Path) -> dict[str, Any]:
|
|
310
|
+
return {
|
|
311
|
+
"case_base": str(store_path),
|
|
312
|
+
"store_version": store.store_version,
|
|
313
|
+
"store_hash": store_hash(store),
|
|
314
|
+
"approved_at": store.approved_at,
|
|
315
|
+
"approved_by": store.approved_by,
|
|
316
|
+
"summary": case_summary(store),
|
|
317
|
+
"pending_proposals": 0,
|
|
318
|
+
"pending_proposal_paths": [],
|
|
319
|
+
"degraded": False,
|
|
320
|
+
"contract_drift": {"checked": False, "changed": False, "reason": "agent_flow"},
|
|
321
|
+
"requirement_drift": {
|
|
322
|
+
"checked": False,
|
|
323
|
+
"changed": False,
|
|
324
|
+
"changed_docs": [],
|
|
325
|
+
"missing_docs": [],
|
|
326
|
+
},
|
|
327
|
+
"requirement_coverage": requirement_coverage(store),
|
|
328
|
+
"review_log_tail": [
|
|
329
|
+
event.model_dump(mode="json") for event in store.review_log[-10:]
|
|
330
|
+
],
|
|
331
|
+
"gate_blockers": [],
|
|
332
|
+
"gate_warnings": [],
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _execution_config(
|
|
337
|
+
config: FlowConfig, data_plan_path: Path | None = None
|
|
338
|
+
) -> RunConfig:
|
|
339
|
+
return RunConfig(
|
|
340
|
+
project=config.project,
|
|
341
|
+
mode="cases",
|
|
342
|
+
base_url=config.base_url,
|
|
343
|
+
reset_url=config.reset_url,
|
|
344
|
+
dubbo_url=config.dubbo_url,
|
|
345
|
+
dubbo_host=config.dubbo_host,
|
|
346
|
+
dubbo_target=config.dubbo_target,
|
|
347
|
+
dubbo_targets=config.dubbo_targets,
|
|
348
|
+
dubbo_source_sha256=config.dubbo_source_sha256,
|
|
349
|
+
dubbo_source_commit=config.dubbo_source_commit,
|
|
350
|
+
dubbo_source_branch=config.dubbo_source_branch,
|
|
351
|
+
dubbo_artifact=config.dubbo_artifact,
|
|
352
|
+
dubbo_target_override=config.dubbo_target_override,
|
|
353
|
+
openapi=config.openapi,
|
|
354
|
+
timeout=config.timeout,
|
|
355
|
+
retries=config.retries,
|
|
356
|
+
collect_only=config.collect_only,
|
|
357
|
+
skip_execute=config.skip_execute,
|
|
358
|
+
min_pass_rate=config.min_pass_rate,
|
|
359
|
+
allow_unmapped=config.allow_unmapped,
|
|
360
|
+
codegraph="off",
|
|
361
|
+
case_base=config.case_base,
|
|
362
|
+
data_plan=str(data_plan_path) if data_plan_path else None,
|
|
363
|
+
database_url=config.database_url,
|
|
364
|
+
ruleset=config.rule_base or "ruleset.json",
|
|
365
|
+
feedback="off",
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _read_entries(run_dir: RunDir) -> list[dict[str, Any]]:
|
|
370
|
+
path = run_dir.path / "execution.json"
|
|
371
|
+
if not path.is_file():
|
|
372
|
+
return []
|
|
373
|
+
try:
|
|
374
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
375
|
+
except (OSError, ValueError):
|
|
376
|
+
return []
|
|
377
|
+
return list(payload.get("records") or [])
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _read_mock_summary(run_dir: RunDir) -> dict[str, Any] | None:
|
|
381
|
+
path = run_dir.path / "mock_evidence.json"
|
|
382
|
+
if not path.is_file():
|
|
383
|
+
return None
|
|
384
|
+
try:
|
|
385
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
386
|
+
except (OSError, ValueError):
|
|
387
|
+
return None
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _execute_round(
|
|
391
|
+
*,
|
|
392
|
+
project: Path,
|
|
393
|
+
config: FlowConfig,
|
|
394
|
+
run_dir: RunDir,
|
|
395
|
+
run_meta: dict[str, Any],
|
|
396
|
+
impact: dict[str, Any],
|
|
397
|
+
profiles: list[dict],
|
|
398
|
+
cases: list[Any],
|
|
399
|
+
unmapped: dict[str, Any],
|
|
400
|
+
route_audit: dict[str, Any],
|
|
401
|
+
store: Any,
|
|
402
|
+
store_path: Path,
|
|
403
|
+
runtime: Any,
|
|
404
|
+
data_plan_path: Path | None = None,
|
|
405
|
+
) -> dict[str, Any]:
|
|
406
|
+
kwargs = dict(
|
|
407
|
+
project=project,
|
|
408
|
+
config=_execution_config(config, data_plan_path),
|
|
409
|
+
run_dir=run_dir,
|
|
410
|
+
run_meta=run_meta,
|
|
411
|
+
changes={
|
|
412
|
+
"mode": "agent",
|
|
413
|
+
"case_base": str(store_path),
|
|
414
|
+
"store_version": store.store_version,
|
|
415
|
+
},
|
|
416
|
+
impact=impact,
|
|
417
|
+
profiles=profiles,
|
|
418
|
+
cases=cases,
|
|
419
|
+
unmapped=unmapped,
|
|
420
|
+
route_audit=route_audit,
|
|
421
|
+
case_store_state=_store_state(store, store_path),
|
|
422
|
+
codegen_gate={
|
|
423
|
+
"allow_unmapped": config.allow_unmapped,
|
|
424
|
+
"min_pass_rate": config.min_pass_rate,
|
|
425
|
+
},
|
|
426
|
+
)
|
|
427
|
+
if runtime is None:
|
|
428
|
+
return execute_cases(**kwargs)
|
|
429
|
+
return execute_with_runtime(**kwargs, runtime=runtime)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _changed_endpoints(impact: dict[str, Any]) -> set[str]:
|
|
433
|
+
return {
|
|
434
|
+
str(api.get("handler") or "")
|
|
435
|
+
for api in impact.get("changed_apis") or []
|
|
436
|
+
if api.get("handler")
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _diagnose_and_repair(
|
|
441
|
+
*,
|
|
442
|
+
run_dir: RunDir,
|
|
443
|
+
cases: list[Any],
|
|
444
|
+
draft: Any,
|
|
445
|
+
llm: LLMClient,
|
|
446
|
+
impact: dict[str, Any],
|
|
447
|
+
context: dict[str, Any],
|
|
448
|
+
project: Path,
|
|
449
|
+
ruleset: RuleSet | None,
|
|
450
|
+
data_catalog: DataCatalog | None,
|
|
451
|
+
mock_semantic: MockSemantic | None,
|
|
452
|
+
) -> RepairOutcome:
|
|
453
|
+
entries = _read_entries(run_dir)
|
|
454
|
+
try:
|
|
455
|
+
outcome = diagnose_and_repair(
|
|
456
|
+
draft=draft,
|
|
457
|
+
cases=cases,
|
|
458
|
+
entries=entries,
|
|
459
|
+
llm=llm,
|
|
460
|
+
context=context,
|
|
461
|
+
analysis=None,
|
|
462
|
+
project=project,
|
|
463
|
+
mock_semantic=mock_semantic,
|
|
464
|
+
mock_summary=_read_mock_summary(run_dir),
|
|
465
|
+
changed_endpoints=_changed_endpoints(impact),
|
|
466
|
+
case_keys={case.id: case.case_key for case in cases},
|
|
467
|
+
ruleset=ruleset,
|
|
468
|
+
data_catalog=data_catalog,
|
|
469
|
+
)
|
|
470
|
+
except AgentError as exc:
|
|
471
|
+
outcome = RepairOutcome(
|
|
472
|
+
draft=draft.model_copy(deep=True),
|
|
473
|
+
mock_semantic=mock_semantic,
|
|
474
|
+
errors=[f"{exc.code}: {exc.detail}"],
|
|
475
|
+
)
|
|
476
|
+
run_dir.write_json("diagnosis.json", outcome.diagnoses)
|
|
477
|
+
run_dir.write_json(
|
|
478
|
+
"diagnosis_meta.json",
|
|
479
|
+
{
|
|
480
|
+
"eligible_case_ids": sorted(outcome.eligible_case_ids),
|
|
481
|
+
"errors": outcome.errors,
|
|
482
|
+
"warnings": outcome.warnings,
|
|
483
|
+
},
|
|
484
|
+
)
|
|
485
|
+
run_dir.write_json(
|
|
486
|
+
"repair.json",
|
|
487
|
+
{
|
|
488
|
+
"applied": outcome.applied,
|
|
489
|
+
"rejected": outcome.rejected,
|
|
490
|
+
"mock_applied": outcome.mock_applied,
|
|
491
|
+
"mock_rejected": outcome.mock_rejected,
|
|
492
|
+
},
|
|
493
|
+
)
|
|
494
|
+
return outcome
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def _project_path(project: Path, raw: str | None, default: str) -> Path:
|
|
498
|
+
path = Path(raw or default)
|
|
499
|
+
if not path.is_absolute():
|
|
500
|
+
path = project / path
|
|
501
|
+
return path.resolve()
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _project_inputs(project: Path, values: list[str]) -> list[Path]:
|
|
505
|
+
paths: list[Path] = []
|
|
506
|
+
for raw in values:
|
|
507
|
+
path = Path(raw)
|
|
508
|
+
if not path.is_absolute():
|
|
509
|
+
path = project / path
|
|
510
|
+
path = path.resolve()
|
|
511
|
+
if not path.is_relative_to(project):
|
|
512
|
+
raise AgentError("data_ddl_outside_project", str(path))
|
|
513
|
+
if not path.is_file():
|
|
514
|
+
raise AgentError("data_ddl_missing", str(path))
|
|
515
|
+
paths.append(path)
|
|
516
|
+
return paths
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _configured_data_dialect(config: FlowConfig) -> str | None:
|
|
520
|
+
"""显式 --db-dialect 优先,其次从 --db-url 推断;都没有时返回 None。"""
|
|
521
|
+
try:
|
|
522
|
+
if config.data_dialect:
|
|
523
|
+
return normalize_dialect(config.data_dialect)
|
|
524
|
+
if config.database_url:
|
|
525
|
+
return dialect_from_url(config.database_url)
|
|
526
|
+
except ValueError as exc:
|
|
527
|
+
raise AgentError("data_dialect_invalid", str(exc)) from exc
|
|
528
|
+
return None
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _build_data_catalog(
|
|
532
|
+
*,
|
|
533
|
+
project: Path,
|
|
534
|
+
context: dict[str, Any],
|
|
535
|
+
config: FlowConfig,
|
|
536
|
+
) -> DataCatalog | None:
|
|
537
|
+
configured = _configured_data_dialect(config)
|
|
538
|
+
if config.data_catalog:
|
|
539
|
+
path = _project_path(project, config.data_catalog, ".astsight/data/data_catalog.json")
|
|
540
|
+
if not path.is_file():
|
|
541
|
+
raise AgentError("data_catalog_missing", str(path))
|
|
542
|
+
catalog = DataCatalog.model_validate(load_json(path))
|
|
543
|
+
errors = validate_catalog(catalog)
|
|
544
|
+
if errors:
|
|
545
|
+
raise AgentError("data_catalog_invalid", ";".join(errors[:20]))
|
|
546
|
+
if configured and catalog.dialect != configured:
|
|
547
|
+
raise AgentError(
|
|
548
|
+
"data_dialect_mismatch",
|
|
549
|
+
f"data_catalog 为 {catalog.dialect},但目标数据库为 {configured}",
|
|
550
|
+
)
|
|
551
|
+
return catalog
|
|
552
|
+
if not config.data_ddl:
|
|
553
|
+
return None
|
|
554
|
+
dialect = configured or "sqlite"
|
|
555
|
+
ddl_paths = _project_inputs(project, config.data_ddl)
|
|
556
|
+
text = "\n;\n".join(
|
|
557
|
+
path.read_text(encoding="utf-8-sig") for path in ddl_paths
|
|
558
|
+
)
|
|
559
|
+
parsed = parse_ddl(text, dialect=dialect)
|
|
560
|
+
seed_path = (
|
|
561
|
+
_project_path(project, config.data_seed, config.data_seed)
|
|
562
|
+
if config.data_seed
|
|
563
|
+
else None
|
|
564
|
+
)
|
|
565
|
+
seed = load_seed(seed_path, parsed)
|
|
566
|
+
catalog = build_catalog(
|
|
567
|
+
project=project.name,
|
|
568
|
+
ddl=parsed,
|
|
569
|
+
seed=seed,
|
|
570
|
+
context_id=str(context.get("context_id") or ""),
|
|
571
|
+
dialect=dialect,
|
|
572
|
+
sources={
|
|
573
|
+
"ddl": [
|
|
574
|
+
path.relative_to(project).as_posix() for path in ddl_paths
|
|
575
|
+
],
|
|
576
|
+
"seed": (
|
|
577
|
+
seed_path.relative_to(project).as_posix()
|
|
578
|
+
if seed_path is not None and seed_path.is_relative_to(project)
|
|
579
|
+
else str(seed_path) if seed_path else None
|
|
580
|
+
),
|
|
581
|
+
},
|
|
582
|
+
)
|
|
583
|
+
errors = validate_catalog(catalog)
|
|
584
|
+
if errors:
|
|
585
|
+
raise AgentError("data_catalog_invalid", ";".join(errors[:20]))
|
|
586
|
+
return catalog
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def run_flow(
|
|
590
|
+
config: FlowConfig,
|
|
591
|
+
*,
|
|
592
|
+
llm: LLMClient | None = None,
|
|
593
|
+
) -> FlowResult:
|
|
594
|
+
project = Path(config.project).resolve()
|
|
595
|
+
if not project.is_dir():
|
|
596
|
+
raise AgentError("project_missing", f"项目目录不存在: {project}")
|
|
597
|
+
if not config.requirements:
|
|
598
|
+
raise AgentError("requirements_missing", "至少提供一个 --requirements")
|
|
599
|
+
|
|
600
|
+
owned_llm = llm is None
|
|
601
|
+
client = llm or LLMClient(load_config(config_path=config.llm_config))
|
|
602
|
+
|
|
603
|
+
run_id = new_run_id("agent")
|
|
604
|
+
out_root = (
|
|
605
|
+
Path(config.out)
|
|
606
|
+
if Path(config.out).is_absolute()
|
|
607
|
+
else project / config.out
|
|
608
|
+
)
|
|
609
|
+
run_dir = RunDir(out_root, run_id)
|
|
610
|
+
result = FlowResult(run_id=run_id, run_dir=run_dir.path, status="not_run")
|
|
611
|
+
steps: dict[str, Any] = {}
|
|
612
|
+
result.steps = steps
|
|
613
|
+
|
|
614
|
+
runtime = None
|
|
615
|
+
sut = None
|
|
616
|
+
data_plan_file: Path | None = None
|
|
617
|
+
try:
|
|
618
|
+
# ── 1. 路由 + 变更范围 ────────────────────────────────
|
|
619
|
+
# 契约不是流程前置条件:需求先产出规则,接口事实从代码路由补;
|
|
620
|
+
# 有 OpenAPI 时额外获得其契约字段;C1 还会扫描 Spring/gRPC/Dubbo 契约源。
|
|
621
|
+
openapi_source = discover_openapi(project, config.openapi, None)
|
|
622
|
+
operations: list[Any] = []
|
|
623
|
+
if openapi_source:
|
|
624
|
+
operations = parse_operations(load_spec(openapi_source))
|
|
625
|
+
else:
|
|
626
|
+
result.warnings.append(
|
|
627
|
+
"openapi_missing: 未提供/未发现 OpenAPI;画像只使用代码路由。"
|
|
628
|
+
"C1 仍会扫描 Spring/gRPC/Dubbo 契约源,无法证明的字段进入 contract_gaps"
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
routes, route_audit, graph_client, graph_notes = inventory_routes(
|
|
632
|
+
project,
|
|
633
|
+
codegraph=config.codegraph,
|
|
634
|
+
codegraph_module_root=config.codegraph_module_root,
|
|
635
|
+
full_index=config.full_index,
|
|
636
|
+
openapi_source=openapi_source,
|
|
637
|
+
)
|
|
638
|
+
supplement = (route_audit or {}).get("openapi_supplement") or {}
|
|
639
|
+
route_audit = {
|
|
640
|
+
**(route_audit or {}),
|
|
641
|
+
"health": route_inventory_health(
|
|
642
|
+
project, routes, openapi_operations=supplement.get("operations")
|
|
643
|
+
),
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
if config.mode == "delta":
|
|
647
|
+
changed_apis, changes_meta, unsupported = _delta_scope(
|
|
648
|
+
project, config, routes, graph_client
|
|
649
|
+
)
|
|
650
|
+
else:
|
|
651
|
+
changed_apis, changes_meta = _full_scope(routes)
|
|
652
|
+
unsupported = []
|
|
653
|
+
_align_to_openapi(changed_apis, operations)
|
|
654
|
+
impact = {
|
|
655
|
+
"changed_apis": changed_apis,
|
|
656
|
+
"unresolved_symbols": [],
|
|
657
|
+
"traces": [],
|
|
658
|
+
"changed_symbols": [],
|
|
659
|
+
"unsupported_files": unsupported,
|
|
660
|
+
"scope": config.mode,
|
|
661
|
+
}
|
|
662
|
+
run_dir.write_json("routes.json", {"routes": routes, "audit": route_audit})
|
|
663
|
+
run_dir.write_json("changed_apis.json", impact)
|
|
664
|
+
run_dir.write_json("changes.json", changes_meta)
|
|
665
|
+
steps["scope"] = {
|
|
666
|
+
"mode": config.mode,
|
|
667
|
+
"routes": len(routes),
|
|
668
|
+
"changed_apis": [api.get("handler") for api in changed_apis],
|
|
669
|
+
"openapi": openapi_source,
|
|
670
|
+
"interface_evidence": "openapi" if operations else "code_routes_only",
|
|
671
|
+
}
|
|
672
|
+
if not changed_apis and (config.mode != "full" or routes):
|
|
673
|
+
result.warnings.append("本次变更未命中任何接口,流程结束")
|
|
674
|
+
result.status = "not_run"
|
|
675
|
+
return result
|
|
676
|
+
if not routes:
|
|
677
|
+
result.warnings.append(
|
|
678
|
+
"routes_missing: 未从代码或 OpenAPI 发现可用接口;"
|
|
679
|
+
"本轮先完成需求规则抽取,不生成用例"
|
|
680
|
+
)
|
|
681
|
+
|
|
682
|
+
# ── 2. 用例上下文(画像)────────────────────────────
|
|
683
|
+
context = build_context(
|
|
684
|
+
project,
|
|
685
|
+
config.requirements,
|
|
686
|
+
openapi=openapi_source,
|
|
687
|
+
routes=_profile_routes(changed_apis),
|
|
688
|
+
changed_apis=changed_apis,
|
|
689
|
+
codegraph_client=graph_client,
|
|
690
|
+
)
|
|
691
|
+
run_dir.write_json("context.json", context)
|
|
692
|
+
result.warnings.extend(
|
|
693
|
+
f"context:{warning}" for warning in context.get("warnings") or []
|
|
694
|
+
)
|
|
695
|
+
steps["scope"]["profiles"] = len(context.get("profiles") or [])
|
|
696
|
+
steps["scope"]["contract_incomplete"] = sum(
|
|
697
|
+
1
|
|
698
|
+
for profile in context.get("profiles") or []
|
|
699
|
+
if profile.get("contract_incomplete")
|
|
700
|
+
)
|
|
701
|
+
|
|
702
|
+
# ── 3. A1 规则抽取(LLM 候选 + 确定性导入)──────────
|
|
703
|
+
rules_context = build_rules_context(
|
|
704
|
+
project, config.requirements, openapi=openapi_source
|
|
705
|
+
)
|
|
706
|
+
rules_context_dir = write_rules_context(
|
|
707
|
+
rules_context, project=project, out=run_dir.path / "rules"
|
|
708
|
+
)
|
|
709
|
+
rule_base = _project_path(project, config.rule_base, "ruleset.json")
|
|
710
|
+
previous_ruleset = load_rule_set(rule_base) if rule_base.is_file() else None
|
|
711
|
+
rule_draft = generate_rule_draft(rules_context, llm=client)
|
|
712
|
+
run_dir.write_json(
|
|
713
|
+
"rules.draft.json", rule_draft.model_dump(mode="json")
|
|
714
|
+
)
|
|
715
|
+
imported = import_rule_draft_for_flow(
|
|
716
|
+
project=project.name,
|
|
717
|
+
context=rules_context,
|
|
718
|
+
draft=rule_draft,
|
|
719
|
+
previous_path=rule_base if rule_base.is_file() else None,
|
|
720
|
+
prompt=rule_prompt_metadata(rules_context, client),
|
|
721
|
+
)
|
|
722
|
+
save_rule_set(rule_base, imported.ruleset)
|
|
723
|
+
# 人工评审文档随规则库产出:用于和产品方对齐需求缺陷,只读、不参与导入。
|
|
724
|
+
rules_review_path = rule_base.with_suffix(".md")
|
|
725
|
+
rules_review_path.write_text(
|
|
726
|
+
render_rule_set_markdown(imported.ruleset), encoding="utf-8"
|
|
727
|
+
)
|
|
728
|
+
result.warnings.extend(imported.validation.warnings)
|
|
729
|
+
conflicted = [conflict.topic for conflict in imported.ruleset.conflicts]
|
|
730
|
+
if conflicted:
|
|
731
|
+
result.warnings.append(
|
|
732
|
+
f"规则冲突(将在用例审核中确认): {', '.join(conflicted[:5])}"
|
|
733
|
+
)
|
|
734
|
+
steps["rules"] = {
|
|
735
|
+
"ruleset": str(rule_base),
|
|
736
|
+
"review": str(rules_review_path),
|
|
737
|
+
"context_dir": str(rules_context_dir.context_dir),
|
|
738
|
+
"context_id": rules_context_dir.context_id,
|
|
739
|
+
"business_rules": len(imported.ruleset.rules),
|
|
740
|
+
"contract_rules": len(imported.ruleset.contract_rules),
|
|
741
|
+
"diff": imported.diff.as_dict(),
|
|
742
|
+
"questions": len(imported.ruleset.questions),
|
|
743
|
+
"gaps": len(imported.ruleset.gaps),
|
|
744
|
+
"conflicts": conflicted,
|
|
745
|
+
"warnings": imported.validation.warnings,
|
|
746
|
+
}
|
|
747
|
+
ruleset = load_rule_set(rule_base)
|
|
748
|
+
|
|
749
|
+
if not routes:
|
|
750
|
+
# 没有接口事实就不能生成可执行用例;规则库仍然完整产出并落盘。
|
|
751
|
+
result.status = "not_run"
|
|
752
|
+
return result
|
|
753
|
+
|
|
754
|
+
# ── 4. C3.5.1 Mock 语义(契约层 + 规则映射)──────────
|
|
755
|
+
mock_semantic = build_mock_semantic(context, ruleset)
|
|
756
|
+
mock_candidates = generate_mock_semantic_candidates(
|
|
757
|
+
context, mock_semantic, ruleset=ruleset, llm=client
|
|
758
|
+
)
|
|
759
|
+
if mock_candidates is not None:
|
|
760
|
+
result.warnings.extend(mock_candidates.warnings)
|
|
761
|
+
mock_semantic_path = _project_path(
|
|
762
|
+
project, ".astsight/mock_semantics.json", ".astsight/mock_semantics.json"
|
|
763
|
+
)
|
|
764
|
+
save_json_atomic(
|
|
765
|
+
mock_semantic_path, mock_semantic.model_dump(mode="json")
|
|
766
|
+
)
|
|
767
|
+
run_dir.write_json(
|
|
768
|
+
"mock_semantics.json", mock_semantic.model_dump(mode="json")
|
|
769
|
+
)
|
|
770
|
+
if mock_semantic.gaps:
|
|
771
|
+
result.warnings.extend(
|
|
772
|
+
f"mock_semantic_gap:{gap.dep_id or 'global'}:{gap.reason}"
|
|
773
|
+
for gap in mock_semantic.gaps[:20]
|
|
774
|
+
)
|
|
775
|
+
steps["mock_semantics"] = {
|
|
776
|
+
"path": str(mock_semantic_path),
|
|
777
|
+
"deps": len(mock_semantic.deps),
|
|
778
|
+
"branches": sum(len(dep.branches) for dep in mock_semantic.deps),
|
|
779
|
+
"gaps": len(mock_semantic.gaps),
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
# ── 5. C5a 数据目录(DDL + seed + LLM 语义候选)──────
|
|
783
|
+
catalog = _build_data_catalog(
|
|
784
|
+
project=project, context=context, config=config
|
|
785
|
+
)
|
|
786
|
+
if catalog is not None:
|
|
787
|
+
if not config.skip_data and client is not None:
|
|
788
|
+
semantic_draft, applied = generate_data_semantics(
|
|
789
|
+
catalog,
|
|
790
|
+
llm=client,
|
|
791
|
+
ruleset=ruleset,
|
|
792
|
+
context=rules_context,
|
|
793
|
+
)
|
|
794
|
+
catalog = applied.catalog
|
|
795
|
+
result.warnings.extend(applied.warnings)
|
|
796
|
+
run_dir.write_json(
|
|
797
|
+
"data_semantics.draft.json",
|
|
798
|
+
semantic_draft.model_dump(mode="json"),
|
|
799
|
+
)
|
|
800
|
+
catalog_path = _project_path(
|
|
801
|
+
project, ".astsight/data/data_catalog.json", ".astsight/data/data_catalog.json"
|
|
802
|
+
)
|
|
803
|
+
save_json_atomic(catalog_path, catalog.model_dump(mode="json"))
|
|
804
|
+
run_dir.write_json(
|
|
805
|
+
"data_catalog.json", catalog.model_dump(mode="json")
|
|
806
|
+
)
|
|
807
|
+
steps["data_catalog"] = {
|
|
808
|
+
"path": str(catalog_path),
|
|
809
|
+
"catalog_id": catalog.catalog_id,
|
|
810
|
+
"tables": len(catalog.tables),
|
|
811
|
+
"states": len(catalog.states),
|
|
812
|
+
"gaps": len(catalog.gaps),
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
# ── 6. A4 用例设计(规则 + 画像 + 语义 + 造数目录)──
|
|
816
|
+
design = generate_case_design(
|
|
817
|
+
context,
|
|
818
|
+
ruleset=ruleset,
|
|
819
|
+
llm=client,
|
|
820
|
+
project=project,
|
|
821
|
+
mode=config.mode,
|
|
822
|
+
changed_apis=changed_apis,
|
|
823
|
+
mock_semantic=mock_semantic,
|
|
824
|
+
data_catalog=catalog,
|
|
825
|
+
max_cases=config.max_cases,
|
|
826
|
+
)
|
|
827
|
+
draft = design.draft
|
|
828
|
+
validation = design.validation
|
|
829
|
+
draft_path = run_dir.path / "cases.draft.json"
|
|
830
|
+
save_json_atomic(draft_path, draft.model_dump(mode="json"))
|
|
831
|
+
result.warnings.extend(design.warnings)
|
|
832
|
+
steps["case_design"] = {
|
|
833
|
+
"cases": len(draft.cases),
|
|
834
|
+
"business_cases": sum(
|
|
835
|
+
1 for case in draft.cases if case.level.value == "business"
|
|
836
|
+
),
|
|
837
|
+
"code_cases": sum(
|
|
838
|
+
1 for case in draft.cases if case.level.value == "code"
|
|
839
|
+
),
|
|
840
|
+
"warnings": design.warnings,
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
# ── 7. proposal / 审核 ───────────────────────────────
|
|
844
|
+
store_path = resolve_case_base(project, config.case_base)
|
|
845
|
+
store = load_case_set(store_path) or empty_case_set(project, context=context)
|
|
846
|
+
built = build_proposal(
|
|
847
|
+
project=project,
|
|
848
|
+
draft_path=draft_path,
|
|
849
|
+
draft=draft,
|
|
850
|
+
context=context,
|
|
851
|
+
validation=validation,
|
|
852
|
+
store=store,
|
|
853
|
+
store_path=store_path,
|
|
854
|
+
ruleset=ruleset,
|
|
855
|
+
data_catalog=catalog,
|
|
856
|
+
)
|
|
857
|
+
steps["proposal"] = {
|
|
858
|
+
"path": str(built.path) if built.path else None,
|
|
859
|
+
"diff": built.diff.counts(),
|
|
860
|
+
"reused": built.reused,
|
|
861
|
+
}
|
|
862
|
+
if built.path is not None:
|
|
863
|
+
if not config.approve_as:
|
|
864
|
+
result.warnings.append(
|
|
865
|
+
f"存在待审 proposal:{built.path};未提供 --approve-as,流程停在人工审核"
|
|
866
|
+
)
|
|
867
|
+
result.status = "pending_review"
|
|
868
|
+
return result
|
|
869
|
+
decisions = _fill_decisions(
|
|
870
|
+
built.path / "cases.review.json", config.approve_as
|
|
871
|
+
)
|
|
872
|
+
steps["proposal"]["decisions"] = decisions
|
|
873
|
+
approve_proposal(
|
|
874
|
+
proposal_path=built.path,
|
|
875
|
+
project=project,
|
|
876
|
+
case_base=store_path,
|
|
877
|
+
reviewer=config.approve_as,
|
|
878
|
+
)
|
|
879
|
+
store = load_case_set(store_path)
|
|
880
|
+
if store is None:
|
|
881
|
+
raise AgentError("case_store_missing", str(store_path))
|
|
882
|
+
cases = _scope_cases(store, draft)
|
|
883
|
+
if not cases:
|
|
884
|
+
result.warnings.append("审核后没有可执行的用例")
|
|
885
|
+
result.status = "not_run"
|
|
886
|
+
return result
|
|
887
|
+
steps["approved_cases"] = [case.id for case in cases]
|
|
888
|
+
pending = list_pending_proposals(project)
|
|
889
|
+
if pending:
|
|
890
|
+
result.warnings.append(f"仍有 {len(pending)} 个待审 proposal 未应用")
|
|
891
|
+
|
|
892
|
+
# ── 8. C5b 造数计划(批准后,LLM 候选 + 确定性校验)──
|
|
893
|
+
data_bundle: DataPlanBundle | None = None
|
|
894
|
+
if catalog is not None and not config.skip_data:
|
|
895
|
+
if config.data_plan:
|
|
896
|
+
plan_path = _project_path(
|
|
897
|
+
project, config.data_plan, ".astsight/data/data_plan.json"
|
|
898
|
+
)
|
|
899
|
+
if not plan_path.is_file():
|
|
900
|
+
raise AgentError("data_plan_missing", str(plan_path))
|
|
901
|
+
data_bundle = DataPlanBundle.model_validate(load_json(plan_path))
|
|
902
|
+
else:
|
|
903
|
+
plan_draft = generate_data_plans(
|
|
904
|
+
cases,
|
|
905
|
+
catalog=catalog,
|
|
906
|
+
ruleset=ruleset,
|
|
907
|
+
llm=client,
|
|
908
|
+
mock_semantic=mock_semantic,
|
|
909
|
+
)
|
|
910
|
+
run_dir.write_json(
|
|
911
|
+
"data_plan.draft.json", plan_draft.model_dump(mode="json")
|
|
912
|
+
)
|
|
913
|
+
data_bundle = build_data_plan_bundle(
|
|
914
|
+
cases=cases,
|
|
915
|
+
catalog=catalog,
|
|
916
|
+
ruleset=ruleset,
|
|
917
|
+
payloads=plan_draft.plans,
|
|
918
|
+
run_scope=run_id,
|
|
919
|
+
)
|
|
920
|
+
plan_path = _project_path(
|
|
921
|
+
project, ".astsight/data/data_plan.json", ".astsight/data/data_plan.json"
|
|
922
|
+
)
|
|
923
|
+
save_json_atomic(
|
|
924
|
+
plan_path, data_bundle.model_dump(mode="json")
|
|
925
|
+
)
|
|
926
|
+
data_plan_file = plan_path
|
|
927
|
+
run_dir.write_json(
|
|
928
|
+
"data_plan.json", data_bundle.model_dump(mode="json")
|
|
929
|
+
)
|
|
930
|
+
steps["data_plan"] = {
|
|
931
|
+
"path": str(plan_path),
|
|
932
|
+
"run_scope": data_bundle.run_scope,
|
|
933
|
+
"plans": len(data_bundle.plans),
|
|
934
|
+
"rejected": [
|
|
935
|
+
item.model_dump(mode="json") for item in data_bundle.rejected
|
|
936
|
+
],
|
|
937
|
+
}
|
|
938
|
+
result.warnings.extend(data_bundle.warnings)
|
|
939
|
+
if data_bundle.rejected:
|
|
940
|
+
raise AgentError(
|
|
941
|
+
"data_plan_invalid",
|
|
942
|
+
";".join(
|
|
943
|
+
f"{item.case_key}:{item.reason}"
|
|
944
|
+
for item in data_bundle.rejected[:20]
|
|
945
|
+
),
|
|
946
|
+
details={
|
|
947
|
+
"rejected": [
|
|
948
|
+
item.model_dump(mode="json")
|
|
949
|
+
for item in data_bundle.rejected
|
|
950
|
+
]
|
|
951
|
+
},
|
|
952
|
+
)
|
|
953
|
+
elif any(case.preconditions for case in cases):
|
|
954
|
+
result.warnings.append(
|
|
955
|
+
"data_unavailable: 用例含前置状态但未提供 DDL/data catalog,"
|
|
956
|
+
"相关用例应按 blocked 处理"
|
|
957
|
+
)
|
|
958
|
+
|
|
959
|
+
# ── 9. Mock 计划与运行时 ─────────────────────────────
|
|
960
|
+
plan, mock_warnings = build_mock_plan(
|
|
961
|
+
context,
|
|
962
|
+
mock_semantic,
|
|
963
|
+
SimpleNamespace(cases=cases),
|
|
964
|
+
sut_id=_sut_id(project),
|
|
965
|
+
host=config.mock_host,
|
|
966
|
+
port=config.mock_port,
|
|
967
|
+
project_root=project,
|
|
968
|
+
)
|
|
969
|
+
result.warnings.extend(mock_warnings)
|
|
970
|
+
injection_document: dict[str, Any] = {"injections": []}
|
|
971
|
+
if plan is not None:
|
|
972
|
+
plan_path = run_dir.path / "mock_plan.json"
|
|
973
|
+
save_json_atomic(plan_path, plan.model_dump(mode="json"))
|
|
974
|
+
try:
|
|
975
|
+
runtime = start_mock_plan(
|
|
976
|
+
plan_path,
|
|
977
|
+
history_path=run_dir.path / "mock_calls.jsonl",
|
|
978
|
+
gripmock_path=config.gripmock_path,
|
|
979
|
+
)
|
|
980
|
+
except MockPlanError as exc:
|
|
981
|
+
raise AgentError(
|
|
982
|
+
"mock_start_failed", f"{exc.code}: {exc.detail}"
|
|
983
|
+
) from exc
|
|
984
|
+
injection_document = runtime.injection_document()
|
|
985
|
+
run_dir.write_json(
|
|
986
|
+
"run_manifest.json", runtime.manifest(run_id=run_id)
|
|
987
|
+
)
|
|
988
|
+
run_dir.write_json("mock_injection.json", injection_document)
|
|
989
|
+
steps["mock"] = {
|
|
990
|
+
"started": runtime is not None,
|
|
991
|
+
"injections": len(injection_document.get("injections") or []),
|
|
992
|
+
"warnings": mock_warnings,
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
# ── 6. SUT 启动(先 Mock、后 SUT)────────────────────
|
|
996
|
+
if config.sut_command:
|
|
997
|
+
if not config.base_url:
|
|
998
|
+
raise AgentError(
|
|
999
|
+
"sut_base_url_missing",
|
|
1000
|
+
"--sut-command 需要同时提供 --base-url(就绪探测与用例执行使用)",
|
|
1001
|
+
)
|
|
1002
|
+
sut = start_sut(
|
|
1003
|
+
config.sut_command,
|
|
1004
|
+
base_url=config.base_url,
|
|
1005
|
+
log_path=run_dir.path / "sut.log",
|
|
1006
|
+
injection_document=injection_document,
|
|
1007
|
+
extra_env=config.sut_env,
|
|
1008
|
+
agent_token=runtime.token if runtime is not None else None,
|
|
1009
|
+
ready_url=config.sut_ready_url,
|
|
1010
|
+
timeout=config.sut_timeout,
|
|
1011
|
+
cwd=project,
|
|
1012
|
+
)
|
|
1013
|
+
result.warnings.extend(sut.warnings)
|
|
1014
|
+
steps["sut"] = {
|
|
1015
|
+
"started": True,
|
|
1016
|
+
"env_keys": sut.env_keys,
|
|
1017
|
+
"log": str(sut.log_path),
|
|
1018
|
+
}
|
|
1019
|
+
elif runtime is not None and injection_document.get("injections"):
|
|
1020
|
+
result.warnings.append(
|
|
1021
|
+
"Mock 已启动但未提供 --sut-command:注入未应用到 SUT,"
|
|
1022
|
+
"需要外部自行设置环境变量"
|
|
1023
|
+
)
|
|
1024
|
+
|
|
1025
|
+
# ── 10. 造数落地(用例级 fixture)────────────────────
|
|
1026
|
+
# apply/teardown 由生成物中的 data_state fixture 按用例执行,
|
|
1027
|
+
# 不在编排层整批预插;缺 DB 时用例会被标 blocked,而不是静默通过。
|
|
1028
|
+
if data_bundle is not None and data_bundle.plans:
|
|
1029
|
+
steps["data_apply"] = {
|
|
1030
|
+
"mode": "per_case",
|
|
1031
|
+
"plans": len(data_bundle.plans),
|
|
1032
|
+
"database_url_configured": bool(config.database_url),
|
|
1033
|
+
}
|
|
1034
|
+
if not config.database_url:
|
|
1035
|
+
result.warnings.append(
|
|
1036
|
+
"data_unavailable: 已生成 data_plan,但未提供数据库 URL;"
|
|
1037
|
+
"依赖前置状态的用例将标 blocked"
|
|
1038
|
+
)
|
|
1039
|
+
elif any(case.preconditions for case in cases):
|
|
1040
|
+
steps["data_apply"] = {
|
|
1041
|
+
"mode": "blocked",
|
|
1042
|
+
"plans": 0,
|
|
1043
|
+
"database_url_configured": bool(config.database_url),
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
# ── 11. 执行 ────────────────────────────────────────
|
|
1047
|
+
run_meta = {
|
|
1048
|
+
"run_id": run_id,
|
|
1049
|
+
"mode": "agent",
|
|
1050
|
+
"project": str(project),
|
|
1051
|
+
"started_at": utc_now(),
|
|
1052
|
+
"base": config.base if config.mode == "delta" else None,
|
|
1053
|
+
"target": config.target if config.mode == "delta" else None,
|
|
1054
|
+
"base_url": config.base_url,
|
|
1055
|
+
"openapi": openapi_source,
|
|
1056
|
+
"scope": config.mode,
|
|
1057
|
+
"approve_as": config.approve_as,
|
|
1058
|
+
}
|
|
1059
|
+
unmapped = {
|
|
1060
|
+
"symbols": [],
|
|
1061
|
+
"routes": [],
|
|
1062
|
+
"profile_unmapped": [
|
|
1063
|
+
{
|
|
1064
|
+
"endpoint": item.get("endpoint", ""),
|
|
1065
|
+
"handler": item.get("handler", ""),
|
|
1066
|
+
"reason": item.get("reason", ""),
|
|
1067
|
+
"file": item.get("file", ""),
|
|
1068
|
+
}
|
|
1069
|
+
for item in context.get("profile_unmapped") or []
|
|
1070
|
+
],
|
|
1071
|
+
"unsupported_files": unsupported,
|
|
1072
|
+
}
|
|
1073
|
+
report = _execute_round(
|
|
1074
|
+
project=project,
|
|
1075
|
+
config=config,
|
|
1076
|
+
run_dir=run_dir,
|
|
1077
|
+
run_meta=run_meta,
|
|
1078
|
+
impact=impact,
|
|
1079
|
+
profiles=context.get("profiles") or [],
|
|
1080
|
+
cases=cases,
|
|
1081
|
+
unmapped=unmapped,
|
|
1082
|
+
route_audit=route_audit,
|
|
1083
|
+
store=store,
|
|
1084
|
+
store_path=store_path,
|
|
1085
|
+
runtime=runtime,
|
|
1086
|
+
data_plan_path=data_plan_file,
|
|
1087
|
+
)
|
|
1088
|
+
result.report = report
|
|
1089
|
+
result.status = str((report.get("gate") or {}).get("verdict") or "not_run")
|
|
1090
|
+
steps["execution"] = {
|
|
1091
|
+
"run_dir": str(run_dir.path),
|
|
1092
|
+
"report": str(run_dir.path / "report.json"),
|
|
1093
|
+
"verdict": result.status,
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
# ── 8. 诊断 + 有界修复(A5/A6 同一节点)──────────────
|
|
1097
|
+
outcome = _diagnose_and_repair(
|
|
1098
|
+
run_dir=run_dir,
|
|
1099
|
+
cases=cases,
|
|
1100
|
+
draft=draft,
|
|
1101
|
+
llm=client,
|
|
1102
|
+
impact=impact,
|
|
1103
|
+
context=context,
|
|
1104
|
+
project=project,
|
|
1105
|
+
ruleset=ruleset,
|
|
1106
|
+
data_catalog=catalog,
|
|
1107
|
+
mock_semantic=mock_semantic,
|
|
1108
|
+
)
|
|
1109
|
+
result.warnings.extend(outcome.warnings)
|
|
1110
|
+
steps["diagnosis"] = {
|
|
1111
|
+
"cases": len(outcome.diagnoses),
|
|
1112
|
+
"eligible_for_repair": sorted(outcome.eligible_case_ids),
|
|
1113
|
+
"errors": outcome.errors,
|
|
1114
|
+
}
|
|
1115
|
+
if outcome.errors:
|
|
1116
|
+
result.errors.extend(outcome.errors)
|
|
1117
|
+
|
|
1118
|
+
for round_no in range(1, max(0, config.max_repair_rounds) + 1):
|
|
1119
|
+
if not outcome.changed:
|
|
1120
|
+
break
|
|
1121
|
+
round_step: dict[str, Any] = {
|
|
1122
|
+
"applied": outcome.applied,
|
|
1123
|
+
"rejected": outcome.rejected,
|
|
1124
|
+
"mock_applied": outcome.mock_applied,
|
|
1125
|
+
"mock_rejected": outcome.mock_rejected,
|
|
1126
|
+
"diagnosed": sorted(outcome.diagnoses),
|
|
1127
|
+
}
|
|
1128
|
+
steps[f"repair_{round_no}"] = round_step
|
|
1129
|
+
rerun = False
|
|
1130
|
+
|
|
1131
|
+
if outcome.mock_changed and outcome.mock_semantic is not None:
|
|
1132
|
+
mock_semantic = outcome.mock_semantic
|
|
1133
|
+
save_json_atomic(
|
|
1134
|
+
mock_semantic_path,
|
|
1135
|
+
mock_semantic.model_dump(mode="json"),
|
|
1136
|
+
)
|
|
1137
|
+
run_dir.write_json(
|
|
1138
|
+
"mock_semantics.json", mock_semantic.model_dump(mode="json")
|
|
1139
|
+
)
|
|
1140
|
+
save_json_atomic(
|
|
1141
|
+
run_dir.path / f"repair-{round_no}.mock_semantics.json",
|
|
1142
|
+
mock_semantic.model_dump(mode="json"),
|
|
1143
|
+
)
|
|
1144
|
+
if runtime is not None:
|
|
1145
|
+
hot_updated = sync_mock_semantic(runtime, mock_semantic)
|
|
1146
|
+
save_json_atomic(
|
|
1147
|
+
runtime.plan_path, runtime.plan.model_dump(mode="json")
|
|
1148
|
+
)
|
|
1149
|
+
round_step["mock_hot_updated"] = hot_updated
|
|
1150
|
+
rerun = True
|
|
1151
|
+
else:
|
|
1152
|
+
result.warnings.append(
|
|
1153
|
+
"Mock 修复未应用:当前没有运行中的 Mock 服务"
|
|
1154
|
+
)
|
|
1155
|
+
|
|
1156
|
+
if outcome.case_changed:
|
|
1157
|
+
draft = outcome.draft
|
|
1158
|
+
repaired_validation = validate_draft(
|
|
1159
|
+
draft,
|
|
1160
|
+
context,
|
|
1161
|
+
project=project,
|
|
1162
|
+
ruleset=ruleset,
|
|
1163
|
+
data_catalog=catalog,
|
|
1164
|
+
mock_semantic=mock_semantic,
|
|
1165
|
+
require_rules=True,
|
|
1166
|
+
)
|
|
1167
|
+
patch_errors = [
|
|
1168
|
+
issue.message for issue in repaired_validation.errors
|
|
1169
|
+
]
|
|
1170
|
+
if patch_errors:
|
|
1171
|
+
result.warnings.append(
|
|
1172
|
+
"修复草案未通过校验,停止修复:"
|
|
1173
|
+
+ ";".join(patch_errors[:5])
|
|
1174
|
+
)
|
|
1175
|
+
break
|
|
1176
|
+
|
|
1177
|
+
draft_path = run_dir.path / f"repair-{round_no}.draft.json"
|
|
1178
|
+
save_json_atomic(draft_path, draft.model_dump(mode="json"))
|
|
1179
|
+
store = load_case_set(store_path) or empty_case_set(
|
|
1180
|
+
project, context=context
|
|
1181
|
+
)
|
|
1182
|
+
rebuilt = build_proposal(
|
|
1183
|
+
project=project,
|
|
1184
|
+
draft_path=draft_path,
|
|
1185
|
+
draft=draft,
|
|
1186
|
+
context=context,
|
|
1187
|
+
validation=repaired_validation,
|
|
1188
|
+
store=store,
|
|
1189
|
+
store_path=store_path,
|
|
1190
|
+
ruleset=ruleset,
|
|
1191
|
+
data_catalog=catalog,
|
|
1192
|
+
)
|
|
1193
|
+
round_step["proposal"] = str(rebuilt.path) if rebuilt.path else None
|
|
1194
|
+
round_step["diff"] = rebuilt.diff.counts()
|
|
1195
|
+
if rebuilt.path is not None:
|
|
1196
|
+
_fill_decisions(
|
|
1197
|
+
rebuilt.path / "cases.review.json", _REPAIR_REVIEWER
|
|
1198
|
+
)
|
|
1199
|
+
round_step["reviewer"] = _REPAIR_REVIEWER
|
|
1200
|
+
approve_proposal(
|
|
1201
|
+
proposal_path=rebuilt.path,
|
|
1202
|
+
project=project,
|
|
1203
|
+
case_base=store_path,
|
|
1204
|
+
reviewer=_REPAIR_REVIEWER,
|
|
1205
|
+
)
|
|
1206
|
+
store = load_case_set(store_path)
|
|
1207
|
+
if store is None:
|
|
1208
|
+
break
|
|
1209
|
+
cases = _scope_cases(store, draft)
|
|
1210
|
+
if not cases:
|
|
1211
|
+
break
|
|
1212
|
+
rerun = True
|
|
1213
|
+
|
|
1214
|
+
if not rerun:
|
|
1215
|
+
break
|
|
1216
|
+
|
|
1217
|
+
round_id = f"{run_id}-repair{round_no}"
|
|
1218
|
+
round_dir = RunDir(out_root, round_id)
|
|
1219
|
+
round_meta = {**run_meta, "run_id": round_id, "repair_round": round_no}
|
|
1220
|
+
report = _execute_round(
|
|
1221
|
+
project=project,
|
|
1222
|
+
config=config,
|
|
1223
|
+
run_dir=round_dir,
|
|
1224
|
+
run_meta=round_meta,
|
|
1225
|
+
impact=impact,
|
|
1226
|
+
profiles=context.get("profiles") or [],
|
|
1227
|
+
cases=cases,
|
|
1228
|
+
unmapped=unmapped,
|
|
1229
|
+
route_audit=route_audit,
|
|
1230
|
+
store=store,
|
|
1231
|
+
store_path=store_path,
|
|
1232
|
+
runtime=runtime,
|
|
1233
|
+
data_plan_path=data_plan_file,
|
|
1234
|
+
)
|
|
1235
|
+
result.report = report
|
|
1236
|
+
result.status = str(
|
|
1237
|
+
(report.get("gate") or {}).get("verdict") or "not_run"
|
|
1238
|
+
)
|
|
1239
|
+
round_step["run_dir"] = str(round_dir.path)
|
|
1240
|
+
round_step["verdict"] = result.status
|
|
1241
|
+
outcome = _diagnose_and_repair(
|
|
1242
|
+
run_dir=round_dir,
|
|
1243
|
+
cases=cases,
|
|
1244
|
+
draft=draft,
|
|
1245
|
+
llm=client,
|
|
1246
|
+
impact=impact,
|
|
1247
|
+
context=context,
|
|
1248
|
+
project=project,
|
|
1249
|
+
ruleset=ruleset,
|
|
1250
|
+
data_catalog=catalog,
|
|
1251
|
+
mock_semantic=mock_semantic,
|
|
1252
|
+
)
|
|
1253
|
+
result.warnings.extend(outcome.warnings)
|
|
1254
|
+
if outcome.errors:
|
|
1255
|
+
result.errors.extend(outcome.errors)
|
|
1256
|
+
|
|
1257
|
+
return result
|
|
1258
|
+
finally:
|
|
1259
|
+
if sut is not None:
|
|
1260
|
+
sut.stop()
|
|
1261
|
+
if runtime is not None:
|
|
1262
|
+
runtime.stop()
|
|
1263
|
+
result.llm_usage = [usage.as_dict() for usage in client.usage]
|
|
1264
|
+
_attach_token_usage(result, run_dir, client, config.feedback)
|
|
1265
|
+
run_dir.write_json(
|
|
1266
|
+
"flow.json",
|
|
1267
|
+
{
|
|
1268
|
+
**result.as_dict(),
|
|
1269
|
+
"finished_at": utc_now(),
|
|
1270
|
+
"llm": {
|
|
1271
|
+
"config": client.config.redacted(),
|
|
1272
|
+
"usage": result.llm_usage,
|
|
1273
|
+
},
|
|
1274
|
+
},
|
|
1275
|
+
)
|
|
1276
|
+
if owned_llm:
|
|
1277
|
+
client.close()
|
|
1278
|
+
|
|
1279
|
+
|
|
1280
|
+
def _usage_summary(usages: list[dict[str, Any]], model: str) -> dict[str, Any]:
|
|
1281
|
+
input_tokens = sum(int(item.get("input_tokens") or 0) for item in usages)
|
|
1282
|
+
output_tokens = sum(int(item.get("output_tokens") or 0) for item in usages)
|
|
1283
|
+
prompt_chars = sum(int(item.get("prompt_chars") or 0) for item in usages)
|
|
1284
|
+
calls = len(usages)
|
|
1285
|
+
summary: dict[str, Any] = {
|
|
1286
|
+
"calls": calls,
|
|
1287
|
+
"total_prompt_chars": prompt_chars,
|
|
1288
|
+
"total_input_tokens": input_tokens,
|
|
1289
|
+
"total_output_tokens": output_tokens,
|
|
1290
|
+
"total_tokens": input_tokens + output_tokens,
|
|
1291
|
+
"by_model": {},
|
|
1292
|
+
"by_node": {},
|
|
1293
|
+
"by_node_status": "not_available",
|
|
1294
|
+
"note": "LLMUsage 未记录节点标签;按节点统计不可用",
|
|
1295
|
+
}
|
|
1296
|
+
if calls:
|
|
1297
|
+
summary["by_model"] = {
|
|
1298
|
+
model: {
|
|
1299
|
+
"calls": calls,
|
|
1300
|
+
"input_tokens": input_tokens,
|
|
1301
|
+
"output_tokens": output_tokens,
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
return summary
|
|
1305
|
+
|
|
1306
|
+
|
|
1307
|
+
def _attach_token_usage(
|
|
1308
|
+
result: "FlowResult",
|
|
1309
|
+
run_dir: RunDir,
|
|
1310
|
+
client: Any,
|
|
1311
|
+
feedback_mode: str = "auto",
|
|
1312
|
+
) -> None:
|
|
1313
|
+
"""补齐 token 用量与诊断包,再统一重写 report.json/report.md。"""
|
|
1314
|
+
report = result.report
|
|
1315
|
+
if not isinstance(report, dict):
|
|
1316
|
+
return
|
|
1317
|
+
model = str(getattr(client.config, "model", "") or "unknown")
|
|
1318
|
+
usage = _usage_summary(result.llm_usage, model)
|
|
1319
|
+
report["token_usage"] = usage
|
|
1320
|
+
audit = report.setdefault("audit", {})
|
|
1321
|
+
audit["token_usage"] = {
|
|
1322
|
+
"status": "reported" if usage["calls"] else "not_available",
|
|
1323
|
+
"by_node": "not_available",
|
|
1324
|
+
"reason": "LLMUsage 未记录节点标签",
|
|
1325
|
+
}
|
|
1326
|
+
verdict = str((report.get("gate") or {}).get("verdict") or "")
|
|
1327
|
+
if feedback_mode != "off" and (
|
|
1328
|
+
feedback_mode == "always" or verdict == "fail"
|
|
1329
|
+
):
|
|
1330
|
+
try:
|
|
1331
|
+
bundle = collect_feedback(run_dir, report=report)
|
|
1332
|
+
report.setdefault("artifacts", {})["feedback_zip"] = run_dir.rel(
|
|
1333
|
+
Path(bundle["path"])
|
|
1334
|
+
)
|
|
1335
|
+
except Exception as exc:
|
|
1336
|
+
report.setdefault("gate", {}).setdefault("warnings", []).append(
|
|
1337
|
+
f"feedback_bundle_failed: {type(exc).__name__}: {exc}"[:300]
|
|
1338
|
+
)
|
|
1339
|
+
run_dir.write_json("report.json", report)
|
|
1340
|
+
(run_dir.path / "report.md").write_text(
|
|
1341
|
+
render_markdown(report), encoding="utf-8"
|
|
1342
|
+
)
|
|
1343
|
+
|
|
1344
|
+
|
|
1345
|
+
__all__ = ["FlowConfig", "FlowResult", "run_flow"]
|