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.
Files changed (158) hide show
  1. astsight/__init__.py +18 -0
  2. astsight/__main__.py +4 -0
  3. astsight/agent/__init__.py +44 -0
  4. astsight/agent/case_design.py +421 -0
  5. astsight/agent/casegen.py +196 -0
  6. astsight/agent/data_prep.py +265 -0
  7. astsight/agent/diagnosis.py +221 -0
  8. astsight/agent/errors.py +15 -0
  9. astsight/agent/flow.py +1345 -0
  10. astsight/agent/jar.py +235 -0
  11. astsight/agent/mock_semantics.py +136 -0
  12. astsight/agent/mockplan.py +481 -0
  13. astsight/agent/models.py +285 -0
  14. astsight/agent/repair.py +538 -0
  15. astsight/agent/rule_analysis.py +150 -0
  16. astsight/agent/semantic.py +250 -0
  17. astsight/agent/sut.py +442 -0
  18. astsight/artifacts.py +73 -0
  19. astsight/cases/__init__.py +5 -0
  20. astsight/cases/adapters.py +79 -0
  21. astsight/cases/context.py +764 -0
  22. astsight/cases/data_refs.py +167 -0
  23. astsight/cases/deleted_cleanup.py +121 -0
  24. astsight/cases/draft.py +575 -0
  25. astsight/cases/expressions.py +256 -0
  26. astsight/cases/proposal.py +1500 -0
  27. astsight/cases/regexsample.py +242 -0
  28. astsight/cases/relations.py +193 -0
  29. astsight/cases/requirements.py +269 -0
  30. astsight/cases/store.py +362 -0
  31. astsight/cases/strength.py +77 -0
  32. astsight/cases/templates.py +613 -0
  33. astsight/cases/validate.py +738 -0
  34. astsight/cases/validate_assertions.py +733 -0
  35. astsight/cases/validate_base.py +418 -0
  36. astsight/cases/validate_coverage.py +288 -0
  37. astsight/cases/validate_data.py +227 -0
  38. astsight/cases/validate_dubbo.py +300 -0
  39. astsight/cases/validate_mqmock.py +349 -0
  40. astsight/cases/validate_profile.py +168 -0
  41. astsight/cases/validate_rules.py +280 -0
  42. astsight/cases/validate_semantics.py +199 -0
  43. astsight/cases/validate_steps.py +510 -0
  44. astsight/changes/__init__.py +13 -0
  45. astsight/changes/contract_diff.py +310 -0
  46. astsight/changes/deleted.py +161 -0
  47. astsight/changes/git_diff.py +182 -0
  48. astsight/changes/impact.py +464 -0
  49. astsight/changes/symbol_diff.py +431 -0
  50. astsight/changes/transport_contracts.py +385 -0
  51. astsight/cli.py +1537 -0
  52. astsight/codegen/__init__.py +5 -0
  53. astsight/codegen/pytest_gen.py +1814 -0
  54. astsight/commands/__init__.py +1 -0
  55. astsight/commands/_shared.py +42 -0
  56. astsight/commands/data.py +490 -0
  57. astsight/commands/init.py +172 -0
  58. astsight/commands/mock.py +333 -0
  59. astsight/commands/rules.py +360 -0
  60. astsight/data/__init__.py +124 -0
  61. astsight/data/annotations.py +458 -0
  62. astsight/data/apply.py +310 -0
  63. astsight/data/catalog.py +402 -0
  64. astsight/data/codeconst.py +1281 -0
  65. astsight/data/connection.py +74 -0
  66. astsight/data/dbml.py +727 -0
  67. astsight/data/ddl.py +642 -0
  68. astsight/data/dialects.py +156 -0
  69. astsight/data/fixtures.py +193 -0
  70. astsight/data/plan.py +444 -0
  71. astsight/data/reflect.py +667 -0
  72. astsight/data/render.py +133 -0
  73. astsight/data/seed.py +142 -0
  74. astsight/data/semantics.py +211 -0
  75. astsight/data/states.py +1214 -0
  76. astsight/data/validate.py +234 -0
  77. astsight/evaluation.py +205 -0
  78. astsight/execute/__init__.py +6 -0
  79. astsight/execute/diagnose.py +192 -0
  80. astsight/execute/dubbo_targets.py +734 -0
  81. astsight/execute/runner.py +357 -0
  82. astsight/feedback.py +573 -0
  83. astsight/inventory.py +406 -0
  84. astsight/llm/__init__.py +28 -0
  85. astsight/llm/client.py +634 -0
  86. astsight/mock/__init__.py +122 -0
  87. astsight/mock/evidence.py +388 -0
  88. astsight/mock/gripmock_binary.py +246 -0
  89. astsight/mock/grpc_descriptor.py +299 -0
  90. astsight/mock/grpc_runtime.py +423 -0
  91. astsight/mock/identity.py +482 -0
  92. astsight/mock/matching.py +75 -0
  93. astsight/mock/plan.py +1246 -0
  94. astsight/mock/replies.py +84 -0
  95. astsight/mock/routes.py +231 -0
  96. astsight/mock/runtime.py +225 -0
  97. astsight/mock/semantic.py +539 -0
  98. astsight/mock/server.py +1481 -0
  99. astsight/mock/sessions.py +222 -0
  100. astsight/mq/__init__.py +1 -0
  101. astsight/mq/inject/capture.py +337 -0
  102. astsight/mq/inject/sitecustomize.py +14 -0
  103. astsight/persistence.py +86 -0
  104. astsight/pipeline.py +1733 -0
  105. astsight/profile/__init__.py +36 -0
  106. astsight/profile/builder.py +297 -0
  107. astsight/profile/callsite.py +46 -0
  108. astsight/profile/downstream.py +1967 -0
  109. astsight/profile/dubbo.py +2141 -0
  110. astsight/profile/grpc_downstream.py +758 -0
  111. astsight/profile/javaclass.py +431 -0
  112. astsight/profile/javadeps.py +277 -0
  113. astsight/profile/javatypes.py +1037 -0
  114. astsight/profile/langroutes.py +1051 -0
  115. astsight/profile/langscan.py +1363 -0
  116. astsight/profile/mq.py +804 -0
  117. astsight/profile/openapi.py +288 -0
  118. astsight/report/__init__.py +5 -0
  119. astsight/report/merge.py +1098 -0
  120. astsight/rules/__init__.py +102 -0
  121. astsight/rules/conflicts.py +269 -0
  122. astsight/rules/context.py +552 -0
  123. astsight/rules/contract.py +233 -0
  124. astsight/rules/contract_model.py +1361 -0
  125. astsight/rules/coverage.py +127 -0
  126. astsight/rules/diff.py +143 -0
  127. astsight/rules/draft.py +152 -0
  128. astsight/rules/grounding.py +110 -0
  129. astsight/rules/relations.py +319 -0
  130. astsight/rules/render.py +413 -0
  131. astsight/rules/store.py +547 -0
  132. astsight/rules/validate.py +399 -0
  133. astsight/sidecar/__init__.py +37 -0
  134. astsight/sidecar/dubbo.py +449 -0
  135. astsight/sidecar/package.py +251 -0
  136. astsight/sidecar/triple.py +258 -0
  137. astsight-0.1.0.dist-info/METADATA +1348 -0
  138. astsight-0.1.0.dist-info/RECORD +158 -0
  139. astsight-0.1.0.dist-info/WHEEL +5 -0
  140. astsight-0.1.0.dist-info/entry_points.txt +2 -0
  141. astsight-0.1.0.dist-info/top_level.txt +3 -0
  142. codegraph/__init__.py +55 -0
  143. codegraph/bridge/codegraph_worker.mjs +548 -0
  144. codegraph/client.py +158 -0
  145. codegraph/embedded.py +561 -0
  146. codegraph/memory.py +89 -0
  147. codegraph/route_repair.py +1680 -0
  148. codegraph/runtime.py +270 -0
  149. contracts/__init__.py +245 -0
  150. contracts/base.py +37 -0
  151. contracts/cases.py +100 -0
  152. contracts/data.py +209 -0
  153. contracts/entities.py +436 -0
  154. contracts/enums.py +355 -0
  155. contracts/mock.py +350 -0
  156. contracts/mock_plan.py +209 -0
  157. contracts/mock_semantic.py +89 -0
  158. contracts/rules.py +340 -0
@@ -0,0 +1,265 @@
1
+ """C5 LLM 适配器:字段业务语义(C5a)与逐用例造数候选(C5b)。
2
+
3
+ 模型只产出语义/取值候选,不产出 SQL。表/列/枚举、类型、FK 闭包、
4
+ preconditions 覆盖和 SQL 渲染全部由 `astsight.data` 确定性校验。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from pathlib import Path
10
+ from typing import Any, Iterable
11
+
12
+ from contracts import DataCatalog, MockSemantic, RuleSet, TestCase
13
+ from pydantic import BaseModel, ConfigDict, Field
14
+
15
+ from ..cases.data_refs import resolve_case_data
16
+ from ..data.semantics import SemanticApplyResult, SemanticDraft, apply_semantics
17
+ from ..llm import LLMClient, LLMError
18
+ from .errors import AgentError
19
+
20
+ _ENGINE_ROOT = Path(__file__).resolve().parents[2]
21
+ _AST_SIGHT_ROOT = _ENGINE_ROOT.parent
22
+ _CATALOG_PROMPT = _AST_SIGHT_ROOT / "prompts" / "c5_data_catalog.md"
23
+ _PLAN_PROMPT = _AST_SIGHT_ROOT / "prompts" / "c5_data_plan.md"
24
+ MAX_CASES_IN_PROMPT = 200
25
+
26
+
27
+ class DataPlanDraft(BaseModel):
28
+ """C5b 模型输出;SQL 不在契约内。"""
29
+
30
+ model_config = ConfigDict(extra="forbid")
31
+
32
+ plans: dict[str, dict[str, Any]] = Field(default_factory=dict)
33
+ gaps: list[str] = Field(default_factory=list, max_length=200)
34
+ questions: list[str] = Field(default_factory=list, max_length=100)
35
+
36
+
37
+ def _load_prompt(path: str | Path | None, default: Path, code: str) -> str:
38
+ prompt_path = Path(path) if path else default
39
+ if not prompt_path.is_file():
40
+ raise AgentError(code, str(prompt_path))
41
+ return prompt_path.read_text(encoding="utf-8")
42
+
43
+
44
+ def _catalog_payload(catalog: DataCatalog) -> dict[str, Any]:
45
+ return {
46
+ "catalog_id": catalog.catalog_id,
47
+ "context_id": catalog.context_id,
48
+ "dialect": catalog.dialect,
49
+ "tables": [
50
+ {
51
+ "name": table.name,
52
+ "comment": table.comment,
53
+ "purpose": table.purpose,
54
+ "primary_key": list(table.primary_key),
55
+ "columns": [
56
+ {
57
+ "name": column.name,
58
+ "type": column.type,
59
+ "nullable": column.nullable,
60
+ "default": column.default,
61
+ "enum_values": list(column.enum_values),
62
+ "comment": column.comment,
63
+ "semantic_type": column.semantic_type.value,
64
+ "value_semantics": [
65
+ {
66
+ "value": value.value,
67
+ "meaning": value.meaning,
68
+ "rule_keys": list(value.rule_keys),
69
+ "source": value.source,
70
+ }
71
+ for value in column.value_semantics
72
+ ],
73
+ }
74
+ for column in table.columns
75
+ ],
76
+ }
77
+ for table in catalog.tables
78
+ ],
79
+ "foreign_keys": [
80
+ {
81
+ "child_table": fk.child_table,
82
+ "child_columns": list(fk.child_columns),
83
+ "parent_table": fk.parent_table,
84
+ "parent_columns": list(fk.parent_columns),
85
+ }
86
+ for fk in catalog.foreign_keys
87
+ ],
88
+ "seed_states": [
89
+ {
90
+ "state_key": state.state_key,
91
+ "table_values": state.table_values,
92
+ "target_state": state.target_state,
93
+ }
94
+ for state in catalog.states
95
+ ],
96
+ "state_paths": [
97
+ {
98
+ "path_key": path.path_key,
99
+ "table": path.table,
100
+ "column": path.column,
101
+ "steps": [step.model_dump(mode="json") for step in path.steps],
102
+ }
103
+ for path in catalog.state_paths
104
+ ],
105
+ "gaps": catalog.gaps,
106
+ }
107
+
108
+
109
+ def _rule_payload(ruleset: RuleSet | None) -> list[dict[str, Any]]:
110
+ if ruleset is None:
111
+ return []
112
+ return [
113
+ {
114
+ "rule_key": rule.rule_key,
115
+ "rule_id": rule.rule_id,
116
+ "text": rule.text,
117
+ "fields": list(rule.fields),
118
+ "authority": rule.authority.value,
119
+ }
120
+ for rule in ruleset.rules
121
+ ]
122
+
123
+
124
+ def _docs_payload(context: dict[str, Any] | None) -> list[dict[str, Any]]:
125
+ if not context:
126
+ return []
127
+ return [
128
+ {
129
+ "doc": document.get("doc"),
130
+ "sections": [
131
+ {
132
+ "section": section.get("section"),
133
+ "number": section.get("number"),
134
+ "text": str(section.get("text") or "")[:8_000],
135
+ }
136
+ for section in document.get("sections") or []
137
+ ],
138
+ }
139
+ for document in context.get("documents") or []
140
+ ]
141
+
142
+
143
+ def generate_data_semantics(
144
+ catalog: DataCatalog,
145
+ *,
146
+ llm: LLMClient,
147
+ ruleset: RuleSet | None = None,
148
+ context: dict[str, Any] | None = None,
149
+ prompt_path: str | Path | None = None,
150
+ ) -> tuple[SemanticDraft, SemanticApplyResult]:
151
+ system = _load_prompt(prompt_path, _CATALOG_PROMPT, "data_catalog_prompt_missing")
152
+ user = json.dumps(
153
+ {
154
+ "catalog": _catalog_payload(catalog),
155
+ "rules": _rule_payload(ruleset),
156
+ "documents": _docs_payload(context),
157
+ "schema": SemanticDraft.model_json_schema(),
158
+ },
159
+ ensure_ascii=False,
160
+ separators=(",", ":"),
161
+ )
162
+ try:
163
+ payload = llm.complete_json(system=system, user=user)
164
+ except LLMError as exc:
165
+ raise AgentError("data_catalog_llm_failed", str(exc)) from exc
166
+ if not isinstance(payload, dict):
167
+ raise AgentError("data_catalog_invalid", "模型输出必须是 JSON object")
168
+ try:
169
+ draft = SemanticDraft.model_validate(payload)
170
+ except Exception as exc:
171
+ raise AgentError("data_catalog_invalid", str(exc)[:2_000]) from exc
172
+ probe = catalog.model_copy(deep=True)
173
+ applied = apply_semantics(probe, draft, ruleset=ruleset)
174
+ if not applied.ok:
175
+ raise AgentError(
176
+ "data_catalog_candidates_invalid",
177
+ ";".join(applied.errors[:20]),
178
+ details={"errors": applied.errors, "warnings": applied.warnings},
179
+ )
180
+ return draft, applied
181
+
182
+
183
+ def _case_payload(case: TestCase) -> dict[str, Any]:
184
+ # 造数要用用例实际发出的值:先把 $data 换成实体字面量。
185
+ resolved = resolve_case_data(case)
186
+ return {
187
+ "case_id": resolved.id,
188
+ "case_key": getattr(resolved, "case_key", ""),
189
+ "title": resolved.title,
190
+ "endpoint": resolved.endpoint,
191
+ "rule_keys": [ref.rule_key for ref in resolved.rule_refs],
192
+ "preconditions": [
193
+ item.model_dump(mode="json")
194
+ for item in resolved.preconditions
195
+ ],
196
+ "data": resolved.data,
197
+ "request": {
198
+ "path_params": resolved.path_params,
199
+ "query": resolved.query,
200
+ "headers": resolved.headers,
201
+ "body": resolved.body,
202
+ },
203
+ "steps": [
204
+ {
205
+ "name": step.name,
206
+ "endpoint": step.endpoint,
207
+ "request": {
208
+ "path_params": step.path_params,
209
+ "query": step.query,
210
+ "headers": step.headers,
211
+ "body": step.body,
212
+ },
213
+ }
214
+ for step in resolved.steps
215
+ ],
216
+ "mock_bindings": dict(resolved.mock_bindings),
217
+ "mock_replies": resolved.mock_replies,
218
+ }
219
+
220
+
221
+ def generate_data_plans(
222
+ cases: Iterable[TestCase],
223
+ *,
224
+ catalog: DataCatalog,
225
+ ruleset: RuleSet | None,
226
+ llm: LLMClient,
227
+ mock_semantic: MockSemantic | None = None,
228
+ prompt_path: str | Path | None = None,
229
+ ) -> DataPlanDraft:
230
+ case_list = list(cases)[:MAX_CASES_IN_PROMPT]
231
+ system = _load_prompt(prompt_path, _PLAN_PROMPT, "data_plan_prompt_missing")
232
+ user = json.dumps(
233
+ {
234
+ "catalog": _catalog_payload(catalog),
235
+ "rules": _rule_payload(ruleset),
236
+ "cases": [_case_payload(case) for case in case_list],
237
+ "mock_semantics": [
238
+ {
239
+ "dep_id": dep.dep_id,
240
+ "branches": [branch.branch for branch in dep.branches],
241
+ }
242
+ for dep in (mock_semantic.deps if mock_semantic else [])
243
+ ],
244
+ "schema": DataPlanDraft.model_json_schema(),
245
+ },
246
+ ensure_ascii=False,
247
+ separators=(",", ":"),
248
+ )
249
+ try:
250
+ payload = llm.complete_json(system=system, user=user)
251
+ except LLMError as exc:
252
+ raise AgentError("data_plan_llm_failed", str(exc)) from exc
253
+ if not isinstance(payload, dict):
254
+ raise AgentError("data_plan_invalid", "模型输出必须是 JSON object")
255
+ try:
256
+ return DataPlanDraft.model_validate(payload)
257
+ except Exception as exc:
258
+ raise AgentError("data_plan_invalid", str(exc)[:2_000]) from exc
259
+
260
+
261
+ __all__ = [
262
+ "DataPlanDraft",
263
+ "generate_data_plans",
264
+ "generate_data_semantics",
265
+ ]
@@ -0,0 +1,221 @@
1
+ """A5/A6 失败现场打包:确定性归因之后,把疑难失败整理成 LLM 可消费的输入。
2
+
3
+ 本模块只做选择与裁剪,不调用模型、不改草案;真正的诊断 + 修复合并节点在
4
+ `repair.py`。确定性归因保持原样,LLM 结论单独存放,修复前仍需过确定性护栏。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from typing import Any
10
+
11
+ from contracts import MockSemantic
12
+
13
+ MAX_FAILURES = 20
14
+ MAX_MESSAGE_CHARS = 8_000
15
+ _SECRET_HEADERS = ("authorization", "cookie", "token", "secret", "api-key", "x-api-key")
16
+ _5XX_RE = re.compile(r"\b5\d{2}\b")
17
+ ACTION_BY_ROOT = {
18
+ "code_defect": "user",
19
+ "case_error": "user",
20
+ "change_induced": "user",
21
+ "data_error": "framework",
22
+ "mock_error": "framework",
23
+ "adapter_error": "framework",
24
+ "env_error": "framework",
25
+ }
26
+ REPAIRABLE_ROOTS = {"case_error", "mock_error"}
27
+
28
+
29
+ def _safe_headers(headers: dict[str, str]) -> dict[str, str]:
30
+ safe: dict[str, str] = {}
31
+ for key, value in (headers or {}).items():
32
+ if any(token in str(key).lower() for token in _SECRET_HEADERS):
33
+ safe[str(key)] = "***"
34
+ else:
35
+ safe[str(key)] = str(value)[:500]
36
+ return safe
37
+
38
+
39
+ def case_payload(case: Any, *, case_key: str | None = None) -> dict[str, Any]:
40
+ refs = [
41
+ {
42
+ "doc": ref.doc,
43
+ "section": ref.section,
44
+ "quote": (ref.quote or "")[:500],
45
+ }
46
+ for ref in (getattr(case, "requirement_refs", None) or [])
47
+ ]
48
+ return {
49
+ "id": getattr(case, "id", ""),
50
+ "endpoint": getattr(case, "endpoint", ""),
51
+ "case_key": case_key or getattr(case, "id", ""),
52
+ "category": getattr(case, "category", ""),
53
+ "title": getattr(case, "title", ""),
54
+ "transport": getattr(
55
+ getattr(case, "transport", None), "value", None
56
+ )
57
+ or str(getattr(case, "transport", "http")),
58
+ "method": getattr(case, "method", ""),
59
+ "path": getattr(case, "path", ""),
60
+ "dubbo": (
61
+ getattr(case, "dubbo").model_dump(mode="json")
62
+ if getattr(case, "dubbo", None) is not None
63
+ else None
64
+ ),
65
+ "path_params": getattr(case, "path_params", {}) or {},
66
+ "query": getattr(case, "query", {}) or {},
67
+ "headers": _safe_headers(getattr(case, "headers", {}) or {}),
68
+ "body": getattr(case, "body", None),
69
+ "asserts": [
70
+ assertion.model_dump(mode="json")
71
+ for assertion in (getattr(case, "asserts", None) or [])
72
+ ],
73
+ "steps": [
74
+ step.model_dump(mode="json")
75
+ for step in (getattr(case, "steps", None) or [])
76
+ ],
77
+ "assert_strength": str(getattr(case, "assert_strength", "")),
78
+ "requirement_refs": refs,
79
+ "mock_bindings": dict(getattr(case, "mock_bindings", {}) or {}),
80
+ "source": getattr(case, "source", ""),
81
+ }
82
+
83
+
84
+ def mock_payload(case_id: str, mock_summary: dict[str, Any] | None) -> dict[str, Any]:
85
+ summary = mock_summary or {}
86
+ by_case = (summary.get("by_case") or {}).get(case_id) or {}
87
+ unused = [
88
+ item for item in (summary.get("unused_bindings") or [])
89
+ if str(item.get("case_id") or "") == case_id
90
+ ]
91
+ return {
92
+ "checked": bool(summary.get("checked")),
93
+ "session_checked": bool(summary.get("sessions_checked")),
94
+ "case_calls": by_case,
95
+ "unused_bindings": unused[:10],
96
+ "late_calls": [
97
+ item for item in (summary.get("late_calls") or [])
98
+ if str(item.get("case_id") or "") == case_id
99
+ ][:10],
100
+ "errors": [
101
+ item for item in (summary.get("errors") or [])
102
+ if str(item.get("case_id") or "") == case_id
103
+ ][:10],
104
+ }
105
+
106
+
107
+ def mock_semantics_payload(
108
+ case: Any, mock_semantic: MockSemantic | None
109
+ ) -> dict[str, Any]:
110
+ """只回传该用例绑定到的下游分支,避免把整份语义库塞进提示词。"""
111
+ if mock_semantic is None:
112
+ return {}
113
+ dep_index = mock_semantic.dep_index()
114
+ payload: dict[str, Any] = {}
115
+ for dep_id, bound_branch in (getattr(case, "mock_bindings", {}) or {}).items():
116
+ dep = dep_index.get(str(dep_id))
117
+ if dep is None:
118
+ continue
119
+ payload[str(dep_id)] = {
120
+ "endpoint": dep.endpoint,
121
+ "route_key": dep.route_key,
122
+ "bound_branch": str(bound_branch),
123
+ "branches": [
124
+ {
125
+ "branch": branch.branch,
126
+ "semantics": branch.semantics,
127
+ "stub": branch.stub.model_dump(mode="json"),
128
+ }
129
+ for branch in dep.branches
130
+ ],
131
+ }
132
+ return payload
133
+
134
+
135
+ def select_failures(
136
+ entries: list[dict[str, Any]], max_failures: int = MAX_FAILURES
137
+ ) -> list[dict[str, Any]]:
138
+ """确定性归因已能定案的失败不再交给 LLM,节省一次调用。"""
139
+ selected: list[dict[str, Any]] = []
140
+ for entry in entries:
141
+ if entry.get("outcome") not in ("failed", "error"):
142
+ continue
143
+ reason = str((entry.get("diagnosis") or {}).get("reason") or "")
144
+ if reason not in ("unknown", "case_error", "change_induced", "sut_bug"):
145
+ continue
146
+ selected.append(entry)
147
+ if len(selected) >= max_failures:
148
+ break
149
+ return selected
150
+
151
+
152
+ def diagnosis_payload(
153
+ entry: dict[str, Any],
154
+ case: Any,
155
+ mock_summary: dict[str, Any] | None,
156
+ changed_endpoints: set[str],
157
+ *,
158
+ case_key: str | None = None,
159
+ mock_semantic: MockSemantic | None = None,
160
+ ) -> dict[str, Any]:
161
+ case_payload_value = case_payload(case, case_key=case_key)
162
+ message = str(entry.get("message") or "")[:MAX_MESSAGE_CHARS]
163
+ return {
164
+ "case": case_payload_value,
165
+ "execution": {
166
+ "status": entry.get("outcome"),
167
+ "message": message,
168
+ "duration": entry.get("duration"),
169
+ "attempts": entry.get("attempts") or [],
170
+ "deterministic_diagnosis": entry.get("diagnosis") or {},
171
+ "endpoint_changed": case_payload_value["endpoint"] in changed_endpoints,
172
+ },
173
+ "mock_evidence": mock_payload(str(entry.get("case_id") or ""), mock_summary),
174
+ "mock_semantics": mock_semantics_payload(case, mock_semantic),
175
+ "change_set": {
176
+ "endpoint_changed": case_payload_value["endpoint"] in changed_endpoints,
177
+ },
178
+ }
179
+
180
+
181
+ def is_repairable(
182
+ diagnosis: Any,
183
+ entry: dict[str, Any],
184
+ case: Any,
185
+ ) -> bool:
186
+ """只有高/中置信度、非 5xx、非正向超时的用例/ Mock 归因才允许自动修复。"""
187
+ if str(getattr(diagnosis, "root_cause", "")) not in REPAIRABLE_ROOTS:
188
+ return False
189
+ if str(getattr(diagnosis, "action_target", "")) != ACTION_BY_ROOT[
190
+ str(getattr(diagnosis, "root_cause", ""))
191
+ ]:
192
+ return False
193
+ if str(getattr(diagnosis, "confidence", "")) not in ("high", "medium"):
194
+ return False
195
+ root = str(getattr(diagnosis, "root_cause", ""))
196
+ reason = str((entry.get("diagnosis") or {}).get("reason") or "")
197
+ if reason not in ("unknown", "case_error", "sut_bug"):
198
+ return False
199
+ message = str(entry.get("message") or "")
200
+ # 5xx 只能由 Mock 语义错误解释:若把 5xx 当作用例错误去改断言,
201
+ # 等于把真实代码缺陷“修绿”,必须拒绝。
202
+ if _5XX_RE.search(message) and root != "mock_error":
203
+ return False
204
+ if root == "mock_error" and not (getattr(case, "mock_bindings", {}) or {}):
205
+ return False
206
+ if str(getattr(case, "category", "")) == "positive" and "timeout" in message.lower():
207
+ return False
208
+ return True
209
+
210
+
211
+ __all__ = [
212
+ "ACTION_BY_ROOT",
213
+ "MAX_FAILURES",
214
+ "REPAIRABLE_ROOTS",
215
+ "case_payload",
216
+ "diagnosis_payload",
217
+ "is_repairable",
218
+ "mock_payload",
219
+ "mock_semantics_payload",
220
+ "select_failures",
221
+ ]
@@ -0,0 +1,15 @@
1
+ """Agent 流程错误:错误码稳定,detail 供 CLI/报告展示。"""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+
7
+ class AgentError(RuntimeError):
8
+ def __init__(self, code: str, detail: str = "", *, details: Any = None):
9
+ self.code = code
10
+ self.detail = detail
11
+ self.details = details
12
+ super().__init__(f"{code}: {detail}" if detail else code)
13
+
14
+
15
+ __all__ = ["AgentError"]