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/repair.py
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
"""A5/A6 合并节点:一次 LLM 调用完成失败归因与有界修复。
|
|
2
|
+
|
|
3
|
+
确定性归因先跑;只有高/中置信度的 `case_error` / `mock_error` 才允许修复。
|
|
4
|
+
修复对象包括用例请求/断言/绑定,以及用例实际使用的 Mock 语义分支。
|
|
5
|
+
修复不等于“让失败变绿”:断言条数与推导强度不得下降,身份字段不可改,
|
|
6
|
+
修改后的草案和 Mock 语义都必须重新通过确定性校验。
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import copy
|
|
11
|
+
import json
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from contracts import DataCatalog, MockSemantic, MockStub, RuleSet
|
|
17
|
+
|
|
18
|
+
from ..cases.context import find_profile
|
|
19
|
+
from ..cases.draft import CaseDraft
|
|
20
|
+
from ..cases.strength import derive_assert_strength
|
|
21
|
+
from ..cases.validate import validate_draft
|
|
22
|
+
from ..llm import LLMClient, LLMError
|
|
23
|
+
from ..mock.server import FORBIDDEN_RESPONSE_HEADERS
|
|
24
|
+
from .casegen import validate_case_bindings
|
|
25
|
+
from .diagnosis import (
|
|
26
|
+
ACTION_BY_ROOT,
|
|
27
|
+
diagnosis_payload,
|
|
28
|
+
is_repairable,
|
|
29
|
+
select_failures,
|
|
30
|
+
)
|
|
31
|
+
from .errors import AgentError
|
|
32
|
+
from .models import (
|
|
33
|
+
CasePatch,
|
|
34
|
+
MockBranchPatch,
|
|
35
|
+
RepairPlan,
|
|
36
|
+
SemanticAnalysis,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
_ENGINE_ROOT = Path(__file__).resolve().parents[2]
|
|
40
|
+
_AST_SIGHT_ROOT = _ENGINE_ROOT.parent
|
|
41
|
+
_PROMPT_PATH = _AST_SIGHT_ROOT / "prompts" / "a5_diagnose_repair.md"
|
|
42
|
+
MAX_REPAIRS = 20
|
|
43
|
+
_STRENGTH_RANK = {"L1": 1, "L2": 2, "L3": 3, "L4": 4}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class RepairOutcome:
|
|
48
|
+
draft: CaseDraft
|
|
49
|
+
mock_semantic: MockSemantic | None = None
|
|
50
|
+
diagnoses: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
51
|
+
eligible_case_ids: set[str] = field(default_factory=set)
|
|
52
|
+
applied: list[dict[str, Any]] = field(default_factory=list)
|
|
53
|
+
rejected: list[dict[str, Any]] = field(default_factory=list)
|
|
54
|
+
mock_applied: list[dict[str, Any]] = field(default_factory=list)
|
|
55
|
+
mock_rejected: list[dict[str, Any]] = field(default_factory=list)
|
|
56
|
+
errors: list[str] = field(default_factory=list)
|
|
57
|
+
warnings: list[str] = field(default_factory=list)
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def case_changed(self) -> bool:
|
|
61
|
+
return bool(self.applied)
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def mock_changed(self) -> bool:
|
|
65
|
+
return bool(self.mock_applied)
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def changed(self) -> bool:
|
|
69
|
+
return self.case_changed or self.mock_changed
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def load_repair_prompt(path: str | Path | None = None) -> str:
|
|
73
|
+
prompt_path = Path(path) if path else _PROMPT_PATH
|
|
74
|
+
if not prompt_path.is_file():
|
|
75
|
+
raise AgentError("repair_prompt_missing", str(prompt_path))
|
|
76
|
+
return prompt_path.read_text(encoding="utf-8")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _profile_view(profile: dict[str, Any]) -> dict[str, Any]:
|
|
80
|
+
return {
|
|
81
|
+
"endpoint": profile.get("endpoint"),
|
|
82
|
+
"transport": profile.get("transport", "http"),
|
|
83
|
+
"method": profile.get("method"),
|
|
84
|
+
"path": profile.get("path"),
|
|
85
|
+
"service": profile.get("service"),
|
|
86
|
+
"parameter_types": profile.get("parameter_types") or [],
|
|
87
|
+
"parameter_schemas": profile.get("parameter_schemas") or [],
|
|
88
|
+
"result_schema": profile.get("result_schema"),
|
|
89
|
+
"group": profile.get("group"),
|
|
90
|
+
"version": profile.get("version"),
|
|
91
|
+
"request_fields": profile.get("request_fields") or [],
|
|
92
|
+
"response_fields": profile.get("response_fields") or [],
|
|
93
|
+
"success_codes": profile.get("success_codes") or [],
|
|
94
|
+
"error_codes": profile.get("error_codes") or [],
|
|
95
|
+
"downstream_deps": [
|
|
96
|
+
{
|
|
97
|
+
"dep_id": dep.get("dep_id"),
|
|
98
|
+
"path": dep.get("path_key"),
|
|
99
|
+
"method": dep.get("method"),
|
|
100
|
+
}
|
|
101
|
+
for dep in profile.get("downstream_deps") or []
|
|
102
|
+
],
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _apply_case_patch(case: Any, patch: CasePatch) -> str | None:
|
|
107
|
+
"""应用顶层与步骤级修补;步骤名不存在时整条 patch 拒绝。"""
|
|
108
|
+
step_patches = patch.steps or []
|
|
109
|
+
steps = {
|
|
110
|
+
str(getattr(step, "name", "")): step
|
|
111
|
+
for step in (getattr(case, "steps", []) or [])
|
|
112
|
+
}
|
|
113
|
+
missing = [item.name for item in step_patches if item.name not in steps]
|
|
114
|
+
if missing:
|
|
115
|
+
return "step_unknown:" + ",".join(missing)
|
|
116
|
+
for name in patch.changed_fields():
|
|
117
|
+
if name == "steps":
|
|
118
|
+
continue
|
|
119
|
+
setattr(case, name, copy.deepcopy(getattr(patch, name)))
|
|
120
|
+
for step_patch in step_patches:
|
|
121
|
+
target = steps[step_patch.name]
|
|
122
|
+
for field in step_patch.changed_fields():
|
|
123
|
+
setattr(target, field, copy.deepcopy(getattr(step_patch, field)))
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _all_assertions(case: Any) -> list[Any]:
|
|
128
|
+
values = list(getattr(case, "asserts", []) or [])
|
|
129
|
+
for step in getattr(case, "steps", []) or []:
|
|
130
|
+
values.extend(getattr(step, "asserts", []) or [])
|
|
131
|
+
return values
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _assertion_weakening(case: Any, patch: CasePatch) -> str | None:
|
|
135
|
+
"""断言条数或推导强度下降即拒绝;避免“删断言式修复”。"""
|
|
136
|
+
steps_by_name = {
|
|
137
|
+
str(getattr(step, "name", "")): step
|
|
138
|
+
for step in (getattr(case, "steps", []) or [])
|
|
139
|
+
}
|
|
140
|
+
for step_patch in patch.steps or []:
|
|
141
|
+
if "asserts" not in step_patch.changed_fields():
|
|
142
|
+
continue
|
|
143
|
+
target = steps_by_name.get(step_patch.name)
|
|
144
|
+
if target is None:
|
|
145
|
+
return f"step_unknown:{step_patch.name}"
|
|
146
|
+
before_values = list(getattr(target, "asserts", []) or [])
|
|
147
|
+
after_values = list(step_patch.asserts or [])
|
|
148
|
+
if len(after_values) < len(before_values):
|
|
149
|
+
return f"step_assertion_count_decreased:{step_patch.name}"
|
|
150
|
+
before = str(derive_assert_strength(before_values, steps=1))
|
|
151
|
+
after = str(derive_assert_strength(after_values, steps=1))
|
|
152
|
+
if _STRENGTH_RANK.get(after, 1) < _STRENGTH_RANK.get(before, 1):
|
|
153
|
+
return (
|
|
154
|
+
f"step_assert_strength_decreased:{step_patch.name}:"
|
|
155
|
+
f"{before}->{after}"
|
|
156
|
+
)
|
|
157
|
+
transport = str(getattr(getattr(target, "transport", None), "value", ""))
|
|
158
|
+
is_dubbo = transport == "dubbo" or getattr(target, "dubbo", None) is not None
|
|
159
|
+
required = "rpc_status" if is_dubbo else "status_code"
|
|
160
|
+
if not any(
|
|
161
|
+
assertion.kind == required for assertion in after_values
|
|
162
|
+
):
|
|
163
|
+
return f"step_{required}_missing:{step_patch.name}"
|
|
164
|
+
|
|
165
|
+
if "asserts" not in patch.changed_fields():
|
|
166
|
+
return None
|
|
167
|
+
before_values = _all_assertions(case)
|
|
168
|
+
after_values = list(patch.asserts or [])
|
|
169
|
+
for step in getattr(case, "steps", []) or []:
|
|
170
|
+
after_values.extend(getattr(step, "asserts", []) or [])
|
|
171
|
+
if len(after_values) < len(before_values):
|
|
172
|
+
return "assertion_count_decreased"
|
|
173
|
+
steps = max(1, len(getattr(case, "steps", []) or []))
|
|
174
|
+
before = str(derive_assert_strength(before_values, steps=steps))
|
|
175
|
+
after = str(derive_assert_strength(after_values, steps=steps))
|
|
176
|
+
if _STRENGTH_RANK.get(after, 1) < _STRENGTH_RANK.get(before, 1):
|
|
177
|
+
return f"assert_strength_decreased:{before}->{after}"
|
|
178
|
+
return None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _validate_after(
|
|
182
|
+
draft: CaseDraft,
|
|
183
|
+
*,
|
|
184
|
+
context: dict[str, Any],
|
|
185
|
+
analysis: SemanticAnalysis | None,
|
|
186
|
+
project: str | Path,
|
|
187
|
+
ruleset: RuleSet | None = None,
|
|
188
|
+
data_catalog: DataCatalog | None = None,
|
|
189
|
+
mock_semantic: MockSemantic | None = None,
|
|
190
|
+
) -> list[str]:
|
|
191
|
+
validation = validate_draft(
|
|
192
|
+
draft,
|
|
193
|
+
context,
|
|
194
|
+
project=project,
|
|
195
|
+
ruleset=ruleset,
|
|
196
|
+
data_catalog=data_catalog,
|
|
197
|
+
mock_semantic=mock_semantic,
|
|
198
|
+
require_rules=ruleset is not None,
|
|
199
|
+
)
|
|
200
|
+
errors = [item.message for item in validation.errors]
|
|
201
|
+
if analysis is not None:
|
|
202
|
+
binding_errors, _ = validate_case_bindings(draft, analysis, context)
|
|
203
|
+
errors.extend(binding_errors)
|
|
204
|
+
return errors
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _branch_snapshot(
|
|
208
|
+
semantic: MockSemantic, dep_id: str, branch_name: str
|
|
209
|
+
) -> Any | None:
|
|
210
|
+
dep = semantic.dep_index().get(dep_id)
|
|
211
|
+
if dep is None:
|
|
212
|
+
return None
|
|
213
|
+
return next((item for item in dep.branches if item.branch == branch_name), None)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _restore_branch(
|
|
217
|
+
semantic: MockSemantic, dep_id: str, branch_name: str, snapshot: Any
|
|
218
|
+
) -> None:
|
|
219
|
+
dep = semantic.dep_index().get(dep_id)
|
|
220
|
+
if dep is None:
|
|
221
|
+
return
|
|
222
|
+
for index, item in enumerate(dep.branches):
|
|
223
|
+
if item.branch == branch_name:
|
|
224
|
+
dep.branches[index] = snapshot
|
|
225
|
+
return
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _mock_patch_allowed(case: Any, patch: MockBranchPatch) -> bool:
|
|
229
|
+
bindings = getattr(case, "mock_bindings", {}) or {}
|
|
230
|
+
return str(bindings.get(patch.dep_id) or "") == patch.branch
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _apply_mock_patch(
|
|
234
|
+
semantic: MockSemantic, patch: MockBranchPatch
|
|
235
|
+
) -> tuple[dict[str, Any] | None, str | None]:
|
|
236
|
+
changed = patch.changed_fields()
|
|
237
|
+
if not changed:
|
|
238
|
+
return None, "no_change"
|
|
239
|
+
dep = semantic.dep_index().get(patch.dep_id)
|
|
240
|
+
if dep is None:
|
|
241
|
+
return None, "mock_dep_unknown"
|
|
242
|
+
branch = next((item for item in dep.branches if item.branch == patch.branch), None)
|
|
243
|
+
if branch is None:
|
|
244
|
+
return None, "mock_branch_unknown"
|
|
245
|
+
if "headers" in changed:
|
|
246
|
+
forbidden = sorted(
|
|
247
|
+
key
|
|
248
|
+
for key in (patch.headers or {})
|
|
249
|
+
if key.lower() in FORBIDDEN_RESPONSE_HEADERS
|
|
250
|
+
)
|
|
251
|
+
if forbidden:
|
|
252
|
+
return None, f"mock_header_forbidden:{','.join(forbidden)}"
|
|
253
|
+
stub_data = branch.stub.model_dump()
|
|
254
|
+
if "status" in changed:
|
|
255
|
+
stub_data["status"] = patch.status
|
|
256
|
+
if "headers" in changed:
|
|
257
|
+
stub_data["headers"] = dict(patch.headers or {})
|
|
258
|
+
if "body" in changed:
|
|
259
|
+
stub_data["body"] = copy.deepcopy(patch.body)
|
|
260
|
+
try:
|
|
261
|
+
branch.stub = MockStub.model_validate(stub_data)
|
|
262
|
+
except Exception as exc:
|
|
263
|
+
return None, f"mock_stub_invalid:{str(exc)[:200]}"
|
|
264
|
+
if "semantics" in changed:
|
|
265
|
+
branch.semantics = str(patch.semantics)
|
|
266
|
+
return {
|
|
267
|
+
"dep_id": patch.dep_id,
|
|
268
|
+
"branch": patch.branch,
|
|
269
|
+
"fields": changed,
|
|
270
|
+
"reason": patch.reason,
|
|
271
|
+
}, None
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _parse_plan(payload: Any) -> RepairPlan:
|
|
275
|
+
if isinstance(payload, list):
|
|
276
|
+
payload = {"schema_version": 2, "diagnoses": payload}
|
|
277
|
+
return RepairPlan.model_validate(payload)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def diagnose_and_repair(
|
|
281
|
+
draft: CaseDraft,
|
|
282
|
+
*,
|
|
283
|
+
cases: list[Any],
|
|
284
|
+
entries: list[dict[str, Any]],
|
|
285
|
+
llm: LLMClient,
|
|
286
|
+
context: dict[str, Any],
|
|
287
|
+
analysis: SemanticAnalysis | None,
|
|
288
|
+
project: str | Path,
|
|
289
|
+
mock_semantic: MockSemantic | None = None,
|
|
290
|
+
mock_summary: dict[str, Any] | None = None,
|
|
291
|
+
changed_endpoints: set[str] | None = None,
|
|
292
|
+
case_keys: dict[str, str] | None = None,
|
|
293
|
+
max_failures: int = 20,
|
|
294
|
+
max_repairs: int = MAX_REPAIRS,
|
|
295
|
+
prompt_path: str | Path | None = None,
|
|
296
|
+
ruleset: RuleSet | None = None,
|
|
297
|
+
data_catalog: DataCatalog | None = None,
|
|
298
|
+
) -> RepairOutcome:
|
|
299
|
+
"""一次 LLM 调用:诊断疑难失败,并在护栏内直接给草案/Mock 打补丁。"""
|
|
300
|
+
key_by_case_id = case_keys or {}
|
|
301
|
+
outcome = RepairOutcome(
|
|
302
|
+
draft=draft.model_copy(deep=True),
|
|
303
|
+
mock_semantic=(
|
|
304
|
+
mock_semantic.model_copy(deep=True) if mock_semantic is not None else None
|
|
305
|
+
),
|
|
306
|
+
)
|
|
307
|
+
cases_by_id = {str(getattr(case, "id", "")): case for case in cases}
|
|
308
|
+
selected = [
|
|
309
|
+
entry
|
|
310
|
+
for entry in select_failures(entries, max_failures)
|
|
311
|
+
if str(entry.get("case_id") or "") in cases_by_id
|
|
312
|
+
]
|
|
313
|
+
if not selected:
|
|
314
|
+
return outcome
|
|
315
|
+
|
|
316
|
+
changed = changed_endpoints or set()
|
|
317
|
+
packages: list[dict[str, Any]] = []
|
|
318
|
+
for entry in selected:
|
|
319
|
+
case_id = str(entry.get("case_id") or "")
|
|
320
|
+
case = cases_by_id[case_id]
|
|
321
|
+
package = diagnosis_payload(
|
|
322
|
+
entry,
|
|
323
|
+
case,
|
|
324
|
+
mock_summary,
|
|
325
|
+
changed,
|
|
326
|
+
case_key=key_by_case_id.get(case_id),
|
|
327
|
+
mock_semantic=outcome.mock_semantic,
|
|
328
|
+
)
|
|
329
|
+
profile, _ = find_profile(context, case.endpoint)
|
|
330
|
+
package["profile"] = _profile_view(profile) if profile else {}
|
|
331
|
+
packages.append(package)
|
|
332
|
+
|
|
333
|
+
system = load_repair_prompt(prompt_path)
|
|
334
|
+
user = json.dumps(
|
|
335
|
+
{
|
|
336
|
+
"failures": packages,
|
|
337
|
+
"schema": RepairPlan.model_json_schema(),
|
|
338
|
+
"note": (
|
|
339
|
+
"确定性归因已先行。请对每个失败给出归因;"
|
|
340
|
+
"只有在证据支持时才对同一个 case 附带 patch。"
|
|
341
|
+
),
|
|
342
|
+
},
|
|
343
|
+
ensure_ascii=False,
|
|
344
|
+
separators=(",", ":"),
|
|
345
|
+
)
|
|
346
|
+
try:
|
|
347
|
+
payload = llm.complete_json(system=system, user=user)
|
|
348
|
+
except LLMError as exc:
|
|
349
|
+
raise AgentError("repair_llm_failed", str(exc)) from exc
|
|
350
|
+
try:
|
|
351
|
+
plan = _parse_plan(payload)
|
|
352
|
+
except Exception as exc:
|
|
353
|
+
raise AgentError("repair_invalid", str(exc)[:2_000]) from exc
|
|
354
|
+
|
|
355
|
+
requested = {str(entry.get("case_id") or "") for entry in selected}
|
|
356
|
+
entry_by_id = {str(entry.get("case_id") or ""): entry for entry in selected}
|
|
357
|
+
seen_cases: set[str] = set()
|
|
358
|
+
seen_mock_pairs: set[tuple[str, str]] = set()
|
|
359
|
+
for decision in plan.diagnoses:
|
|
360
|
+
if decision.case_id not in requested:
|
|
361
|
+
outcome.errors.append(f"diagnosis_unknown_case:{decision.case_id}")
|
|
362
|
+
continue
|
|
363
|
+
if decision.case_id in seen_cases:
|
|
364
|
+
outcome.warnings.append(f"diagnosis_duplicate_case:{decision.case_id}")
|
|
365
|
+
continue
|
|
366
|
+
seen_cases.add(decision.case_id)
|
|
367
|
+
|
|
368
|
+
expected_target = ACTION_BY_ROOT[decision.root_cause]
|
|
369
|
+
if decision.action_target != expected_target:
|
|
370
|
+
outcome.warnings.append(
|
|
371
|
+
f"diagnosis_action_target_corrected:{decision.case_id}:"
|
|
372
|
+
f"{decision.action_target}->{expected_target}"
|
|
373
|
+
)
|
|
374
|
+
decision = decision.model_copy(
|
|
375
|
+
update={"action_target": expected_target}
|
|
376
|
+
)
|
|
377
|
+
entry = entry_by_id[decision.case_id]
|
|
378
|
+
case = cases_by_id[decision.case_id]
|
|
379
|
+
case_key = key_by_case_id.get(decision.case_id)
|
|
380
|
+
target = next(
|
|
381
|
+
(item for item in outcome.draft.cases if item.case_key == case_key),
|
|
382
|
+
None,
|
|
383
|
+
)
|
|
384
|
+
record = decision.model_dump(mode="json")
|
|
385
|
+
record["eligible_for_repair"] = is_repairable(
|
|
386
|
+
decision, entry, target or case
|
|
387
|
+
)
|
|
388
|
+
outcome.diagnoses[decision.case_id] = record
|
|
389
|
+
if record["eligible_for_repair"]:
|
|
390
|
+
outcome.eligible_case_ids.add(decision.case_id)
|
|
391
|
+
|
|
392
|
+
patch = decision.patch
|
|
393
|
+
if patch is None:
|
|
394
|
+
continue
|
|
395
|
+
if not record["eligible_for_repair"]:
|
|
396
|
+
outcome.rejected.append(
|
|
397
|
+
{"case_key": patch.case_key, "reason": "case_not_eligible"}
|
|
398
|
+
)
|
|
399
|
+
continue
|
|
400
|
+
if not case_key or patch.case_key != case_key:
|
|
401
|
+
outcome.rejected.append(
|
|
402
|
+
{"case_key": patch.case_key, "reason": "case_key_mismatch"}
|
|
403
|
+
)
|
|
404
|
+
continue
|
|
405
|
+
if target is None:
|
|
406
|
+
outcome.rejected.append(
|
|
407
|
+
{"case_key": case_key, "reason": "case_unknown"}
|
|
408
|
+
)
|
|
409
|
+
continue
|
|
410
|
+
fields = patch.changed_fields()
|
|
411
|
+
if not fields and not patch.mock_branches:
|
|
412
|
+
outcome.rejected.append({"case_key": case_key, "reason": "no_change"})
|
|
413
|
+
continue
|
|
414
|
+
if len(outcome.applied) >= max_repairs:
|
|
415
|
+
outcome.rejected.append(
|
|
416
|
+
{"case_key": case_key, "reason": "repair_limit_reached"}
|
|
417
|
+
)
|
|
418
|
+
continue
|
|
419
|
+
|
|
420
|
+
before = {
|
|
421
|
+
name: copy.deepcopy(getattr(target, name))
|
|
422
|
+
for name in fields
|
|
423
|
+
}
|
|
424
|
+
weakness = _assertion_weakening(target, patch)
|
|
425
|
+
if weakness is not None:
|
|
426
|
+
outcome.rejected.append(
|
|
427
|
+
{"case_key": case_key, "reason": weakness}
|
|
428
|
+
)
|
|
429
|
+
continue
|
|
430
|
+
|
|
431
|
+
branch_snapshots: dict[tuple[str, str], Any] = {}
|
|
432
|
+
applied_mock: list[dict[str, Any]] = []
|
|
433
|
+
reject_reason: str | None = _apply_case_patch(target, patch)
|
|
434
|
+
for mock_patch in patch.mock_branches:
|
|
435
|
+
if reject_reason is not None:
|
|
436
|
+
break
|
|
437
|
+
pair = (mock_patch.dep_id, mock_patch.branch)
|
|
438
|
+
if pair in seen_mock_pairs:
|
|
439
|
+
reject_reason = f"mock_branch_duplicate:{pair[0]}/{pair[1]}"
|
|
440
|
+
break
|
|
441
|
+
if not _mock_patch_allowed(target, mock_patch):
|
|
442
|
+
reject_reason = f"mock_branch_not_bound:{pair[0]}/{pair[1]}"
|
|
443
|
+
break
|
|
444
|
+
if outcome.mock_semantic is None:
|
|
445
|
+
reject_reason = "mock_semantic_missing"
|
|
446
|
+
break
|
|
447
|
+
branch_snapshots.setdefault(
|
|
448
|
+
pair,
|
|
449
|
+
copy.deepcopy(
|
|
450
|
+
_branch_snapshot(
|
|
451
|
+
outcome.mock_semantic, mock_patch.dep_id, mock_patch.branch
|
|
452
|
+
)
|
|
453
|
+
),
|
|
454
|
+
)
|
|
455
|
+
result, error = _apply_mock_patch(outcome.mock_semantic, mock_patch)
|
|
456
|
+
if error is not None:
|
|
457
|
+
reject_reason = error
|
|
458
|
+
break
|
|
459
|
+
assert result is not None
|
|
460
|
+
applied_mock.append(result)
|
|
461
|
+
|
|
462
|
+
if reject_reason is None:
|
|
463
|
+
errors = _validate_after(
|
|
464
|
+
outcome.draft,
|
|
465
|
+
context=context,
|
|
466
|
+
analysis=analysis,
|
|
467
|
+
project=project,
|
|
468
|
+
ruleset=ruleset,
|
|
469
|
+
data_catalog=data_catalog,
|
|
470
|
+
mock_semantic=outcome.mock_semantic,
|
|
471
|
+
)
|
|
472
|
+
if errors:
|
|
473
|
+
reject_reason = "validation_failed"
|
|
474
|
+
for name, value in before.items():
|
|
475
|
+
setattr(target, name, value)
|
|
476
|
+
if outcome.mock_semantic is not None:
|
|
477
|
+
for (dep_id, branch_name), snapshot in branch_snapshots.items():
|
|
478
|
+
if snapshot is not None:
|
|
479
|
+
_restore_branch(
|
|
480
|
+
outcome.mock_semantic, dep_id, branch_name, snapshot
|
|
481
|
+
)
|
|
482
|
+
outcome.rejected.append(
|
|
483
|
+
{
|
|
484
|
+
"case_key": case_key,
|
|
485
|
+
"reason": reject_reason,
|
|
486
|
+
"errors": errors[:10],
|
|
487
|
+
}
|
|
488
|
+
)
|
|
489
|
+
continue
|
|
490
|
+
|
|
491
|
+
if reject_reason is not None:
|
|
492
|
+
for name, value in before.items():
|
|
493
|
+
setattr(target, name, value)
|
|
494
|
+
if outcome.mock_semantic is not None:
|
|
495
|
+
for (dep_id, branch_name), snapshot in branch_snapshots.items():
|
|
496
|
+
if snapshot is not None:
|
|
497
|
+
_restore_branch(
|
|
498
|
+
outcome.mock_semantic, dep_id, branch_name, snapshot
|
|
499
|
+
)
|
|
500
|
+
outcome.rejected.append(
|
|
501
|
+
{"case_key": case_key, "reason": reject_reason}
|
|
502
|
+
)
|
|
503
|
+
if reject_reason.startswith("mock_"):
|
|
504
|
+
outcome.mock_rejected.append(
|
|
505
|
+
{"case_key": case_key, "reason": reject_reason}
|
|
506
|
+
)
|
|
507
|
+
continue
|
|
508
|
+
|
|
509
|
+
if fields:
|
|
510
|
+
outcome.applied.append(
|
|
511
|
+
{
|
|
512
|
+
"case_key": case_key,
|
|
513
|
+
"fields": fields,
|
|
514
|
+
"reason": patch.reason,
|
|
515
|
+
"before": before,
|
|
516
|
+
"after": {
|
|
517
|
+
name: copy.deepcopy(getattr(target, name))
|
|
518
|
+
for name in fields
|
|
519
|
+
},
|
|
520
|
+
}
|
|
521
|
+
)
|
|
522
|
+
for item in applied_mock:
|
|
523
|
+
seen_mock_pairs.add((item["dep_id"], item["branch"]))
|
|
524
|
+
item["case_key"] = case_key
|
|
525
|
+
outcome.mock_applied.append(item)
|
|
526
|
+
|
|
527
|
+
missing = requested - seen_cases
|
|
528
|
+
for case_id in sorted(missing):
|
|
529
|
+
outcome.warnings.append(f"diagnosis_missing:{case_id}")
|
|
530
|
+
return outcome
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
__all__ = [
|
|
534
|
+
"MAX_REPAIRS",
|
|
535
|
+
"RepairOutcome",
|
|
536
|
+
"diagnose_and_repair",
|
|
537
|
+
"load_repair_prompt",
|
|
538
|
+
]
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""A1 规则抽取适配器:规则 context → LLM → RuleDraft → 确定性导入。
|
|
2
|
+
|
|
3
|
+
模型只提出候选;rule_key、fingerprint、A 级落地、CR 契约规则都由
|
|
4
|
+
`astsight.rules` 重算。校验不通过时不产生可写规则库。
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from ..llm import LLMClient, LLMError
|
|
13
|
+
from ..rules import (
|
|
14
|
+
RuleDraft,
|
|
15
|
+
RuleImportResult,
|
|
16
|
+
import_rule_draft,
|
|
17
|
+
load_rule_set,
|
|
18
|
+
)
|
|
19
|
+
from ..rules.store import RuleStoreError
|
|
20
|
+
from .errors import AgentError
|
|
21
|
+
|
|
22
|
+
_ENGINE_ROOT = Path(__file__).resolve().parents[2]
|
|
23
|
+
_AST_SIGHT_ROOT = _ENGINE_ROOT.parent
|
|
24
|
+
_PROMPT_PATH = _AST_SIGHT_ROOT / "prompts" / "a1_requirement_analysis.md"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def load_rule_prompt(path: str | Path | None = None) -> str:
|
|
28
|
+
prompt_path = Path(path) if path else _PROMPT_PATH
|
|
29
|
+
if not prompt_path.is_file():
|
|
30
|
+
raise AgentError("rules_prompt_missing", str(prompt_path))
|
|
31
|
+
return prompt_path.read_text(encoding="utf-8")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _context_view(context: dict[str, Any]) -> dict[str, Any]:
|
|
35
|
+
return {
|
|
36
|
+
"context_id": context.get("context_id"),
|
|
37
|
+
"documents": context.get("documents") or [],
|
|
38
|
+
"openapi": context.get("openapi") or {},
|
|
39
|
+
"operations": context.get("operations") or [],
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def generate_rule_draft(
|
|
44
|
+
context: dict[str, Any],
|
|
45
|
+
*,
|
|
46
|
+
llm: LLMClient,
|
|
47
|
+
prompt_path: str | Path | None = None,
|
|
48
|
+
max_rules: int = 500,
|
|
49
|
+
) -> RuleDraft:
|
|
50
|
+
system = load_rule_prompt(prompt_path)
|
|
51
|
+
user = json.dumps(
|
|
52
|
+
{
|
|
53
|
+
"context": _context_view(context),
|
|
54
|
+
"schema": RuleDraft.model_json_schema(),
|
|
55
|
+
"output_mode": "json",
|
|
56
|
+
"notes": [
|
|
57
|
+
"source.section 必须取自 context.documents[].sections[].path 或 number",
|
|
58
|
+
"source.quote 必须是该 section 原文的连续子串",
|
|
59
|
+
"规则 text 和 constraints 中的数字/枚举/错误码必须出现在 quote 中",
|
|
60
|
+
"同一字段尽量输出结构化 constraints,供框架做冲突检测",
|
|
61
|
+
"按四分流输出:文档内部可判定的矛盾进 conflicts,文档没写的进 gaps,"
|
|
62
|
+
"需要业务决策或外部事实的进 questions;不得把内部矛盾降级为 questions",
|
|
63
|
+
"conflicts 填 kind/severity;gaps 填 check_dimension;"
|
|
64
|
+
"questions 填 source 与 related_rule_ids",
|
|
65
|
+
"questions/gaps/conflicts 是本次抽取的完整结果,不沿用上一版",
|
|
66
|
+
"gaps 每项必须包含 reason",
|
|
67
|
+
"不要输出 ContractRule;CR 规则由框架从 ContractModel 的各源能力子集确定性生成",
|
|
68
|
+
],
|
|
69
|
+
},
|
|
70
|
+
ensure_ascii=False,
|
|
71
|
+
separators=(",", ":"),
|
|
72
|
+
)
|
|
73
|
+
try:
|
|
74
|
+
payload = llm.complete_json(system=system, user=user)
|
|
75
|
+
except LLMError as exc:
|
|
76
|
+
raise AgentError("rules_llm_failed", str(exc)) from exc
|
|
77
|
+
if not isinstance(payload, dict):
|
|
78
|
+
raise AgentError("rules_invalid", "模型输出必须是 JSON object")
|
|
79
|
+
try:
|
|
80
|
+
draft = RuleDraft.model_validate(payload)
|
|
81
|
+
except Exception as exc:
|
|
82
|
+
raise AgentError("rules_invalid", str(exc)[:2_000]) from exc
|
|
83
|
+
if len(draft.rules) > max_rules:
|
|
84
|
+
raise AgentError("rules_too_many", f"{len(draft.rules)} > {max_rules}")
|
|
85
|
+
# context_id 由框架回填,其余来源证据仍逐项校验。
|
|
86
|
+
draft.context_id = str(context.get("context_id") or "")
|
|
87
|
+
return draft
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def rule_prompt_metadata(
|
|
91
|
+
context: dict[str, Any], llm: LLMClient | None = None
|
|
92
|
+
) -> dict[str, Any]:
|
|
93
|
+
"""规则库要记录的抽取口径:提示词版本/hash + 模型(若可得)。
|
|
94
|
+
|
|
95
|
+
模型在框架外运行时拿不到 llm,就只记录 context 里的提示词信息。
|
|
96
|
+
"""
|
|
97
|
+
info = dict(context.get("prompt") or {})
|
|
98
|
+
info.setdefault("name", "a1_requirement_analysis")
|
|
99
|
+
info.setdefault("version", "11")
|
|
100
|
+
config = getattr(llm, "config", None)
|
|
101
|
+
redacted = (
|
|
102
|
+
config.redacted() if callable(getattr(config, "redacted", None)) else {}
|
|
103
|
+
)
|
|
104
|
+
for key in ("provider", "model"):
|
|
105
|
+
if redacted.get(key):
|
|
106
|
+
info[key] = redacted[key]
|
|
107
|
+
return info
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def import_rule_draft_for_flow(
|
|
111
|
+
*,
|
|
112
|
+
project: str,
|
|
113
|
+
context: dict[str, Any],
|
|
114
|
+
draft: RuleDraft,
|
|
115
|
+
previous_path: str | Path | None = None,
|
|
116
|
+
prompt: dict[str, Any] | None = None,
|
|
117
|
+
) -> RuleImportResult:
|
|
118
|
+
previous = None
|
|
119
|
+
if previous_path is not None:
|
|
120
|
+
try:
|
|
121
|
+
previous = load_rule_set(previous_path)
|
|
122
|
+
except RuleStoreError as exc:
|
|
123
|
+
raise AgentError("rules_base_invalid", str(exc)) from exc
|
|
124
|
+
result = import_rule_draft(
|
|
125
|
+
project=project,
|
|
126
|
+
context=context,
|
|
127
|
+
draft=draft,
|
|
128
|
+
previous=previous,
|
|
129
|
+
prompt=prompt or rule_prompt_metadata(context),
|
|
130
|
+
dry_run=True,
|
|
131
|
+
)
|
|
132
|
+
if result.validation.errors:
|
|
133
|
+
raise AgentError(
|
|
134
|
+
"rules_validation_failed",
|
|
135
|
+
";".join(result.validation.errors[:20]),
|
|
136
|
+
details={
|
|
137
|
+
"errors": result.validation.errors,
|
|
138
|
+
"warnings": result.validation.warnings,
|
|
139
|
+
"draft": draft.model_dump(mode="json"),
|
|
140
|
+
},
|
|
141
|
+
)
|
|
142
|
+
return result
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
__all__ = [
|
|
146
|
+
"generate_rule_draft",
|
|
147
|
+
"import_rule_draft_for_flow",
|
|
148
|
+
"load_rule_prompt",
|
|
149
|
+
"rule_prompt_metadata",
|
|
150
|
+
]
|