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
astsight/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """AstSight M1:确定性闭环。
2
+
3
+ 链路 A:git diff → 变更符号 → 影响接口 → 画像 → 模板用例 → pytest 编码
4
+ → 执行 → 确定性归因 → 报告。
5
+ 链路 B:需求/设计文档 + ContractModel → 规则库 → 用例草案 → 人工审核 → 版本化 case store
6
+ → 编码 → 执行 → 审核/需求覆盖报告。
7
+
8
+ 设计基线:`framework-capability-design.md` v4.95(C1/C2/C3/C4/C5/C6/C7)。
9
+ HTTP Mock 首版只支持明文 HTTP;下游 `dep_id` 含 downstream_key,运行期按 route_key 路由
10
+ (见 C3.5.5)。
11
+ 目标支持 HTTP、gRPC(仅 unary)、Dubbo 2.7+(Java sidecar 泛化调用);
12
+ HTTP 客户端(含 Feign)一律按普通出站调用处理,不做客户端框架专用支持;
13
+ v4.3 起 SUT → Dubbo 下游 Mock 走 agent + ByteBuddy + Filter(低侵入)。
14
+ 当前实现覆盖规则层、HTTP/gRPC/Dubbo 契约源、画像、审核用例库、C5 造数、
15
+ pytest codegen、执行归因与统一 Mock 运行时。
16
+ """
17
+
18
+ __version__ = "0.1.0"
astsight/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,44 @@
1
+ """LLM 辅助的 Agent 流程:语义分析、用例生成、诊断与修复。
2
+
3
+ 模型只产出候选;证据校验、用例校验、Mock 计划、审核与执行保持确定性。
4
+ """
5
+ from .case_design import CaseDesignResult, generate_case_design
6
+ from .casegen import generate_case_draft, validate_case_bindings
7
+ from .data_prep import DataPlanDraft, generate_data_plans, generate_data_semantics
8
+ from .errors import AgentError
9
+ from .flow import FlowConfig, FlowResult, run_flow
10
+ from .jar import AGENT_VERSION, AgentJar, resolve_agent_jar
11
+ from .mockplan import build_mock_plan, sync_mock_semantic
12
+ from .repair import RepairOutcome, diagnose_and_repair
13
+ from .rule_analysis import generate_rule_draft, import_rule_draft_for_flow
14
+ from .semantic import SemanticValidation, analyze_semantics, validate_semantics
15
+ from .sut import SutProcess, injection_env, start_sut
16
+
17
+ __all__ = [
18
+ "AGENT_VERSION",
19
+ "AgentError",
20
+ "AgentJar",
21
+ "CaseDesignResult",
22
+ "DataPlanDraft",
23
+ "FlowConfig",
24
+ "FlowResult",
25
+ "RepairOutcome",
26
+ "SemanticValidation",
27
+ "SutProcess",
28
+ "analyze_semantics",
29
+ "build_mock_plan",
30
+ "diagnose_and_repair",
31
+ "generate_case_design",
32
+ "generate_case_draft",
33
+ "generate_data_plans",
34
+ "generate_data_semantics",
35
+ "generate_rule_draft",
36
+ "import_rule_draft_for_flow",
37
+ "injection_env",
38
+ "resolve_agent_jar",
39
+ "run_flow",
40
+ "start_sut",
41
+ "sync_mock_semantic",
42
+ "validate_case_bindings",
43
+ "validate_semantics",
44
+ ]
@@ -0,0 +1,421 @@
1
+ """A4 用例设计适配器:规则 + 画像 + Mock 语义 + 数据目录 → CaseDraft。
2
+
3
+ 模型只做场景联想;接口、字段、规则引用、Mock 分支和前置状态全部逐项
4
+ 对事实源校验。规则库是唯一业务规则来源,草案不得新增规则。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from contracts import DataCatalog, MockSemantic, RuleSet, RuleStatus
14
+
15
+ from ..cases.draft import CaseDraft
16
+ from ..cases.validate import ValidationResult, validate_draft
17
+ from ..llm import LLMClient, LLMError
18
+ from ..rules import rule_set_hash
19
+ from ..rules.relations import relation_step_aliases
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" / "a4_case_design.md"
25
+ MAX_CASES = 200
26
+ MAX_RULES_IN_PROMPT = 300
27
+
28
+
29
+ @dataclass
30
+ class CaseDesignResult:
31
+ draft: CaseDraft
32
+ validation: ValidationResult
33
+ warnings: list[str] = field(default_factory=list)
34
+
35
+
36
+ def load_case_design_prompt(path: str | Path | None = None) -> str:
37
+ prompt_path = Path(path) if path else _PROMPT_PATH
38
+ if not prompt_path.is_file():
39
+ raise AgentError("case_design_prompt_missing", str(prompt_path))
40
+ return prompt_path.read_text(encoding="utf-8")
41
+
42
+
43
+ def _rule_view(ruleset: RuleSet) -> list[dict[str, Any]]:
44
+ items: list[dict[str, Any]] = []
45
+ for rule in ruleset.rules:
46
+ if rule.status is RuleStatus.DEPRECATED:
47
+ continue
48
+ items.append(
49
+ {
50
+ "rule_key": rule.rule_key,
51
+ "rule_id": rule.rule_id,
52
+ "text": rule.text,
53
+ "type": rule.type.value,
54
+ "entities": list(rule.entities),
55
+ "fields": list(rule.fields),
56
+ "relations": [
57
+ {
58
+ "relation_id": relation.relation_id,
59
+ "relation_key": relation.relation_key,
60
+ "assertion_kind": relation.assertion_kind,
61
+ "target": relation.target,
62
+ "op": relation.op,
63
+ "expect": relation.expect,
64
+ "where": relation.where,
65
+ "wait_ms": relation.wait_ms,
66
+ "step_aliases": relation_step_aliases(relation),
67
+ "description": relation.description,
68
+ "evidence": relation.evidence,
69
+ }
70
+ for relation in rule.relations
71
+ ],
72
+ "authority": rule.authority.value,
73
+ "source_kind": rule.source.kind.value,
74
+ "priority": rule.priority.value,
75
+ "status": rule.status.value,
76
+ }
77
+ )
78
+ for rule in ruleset.contract_rules:
79
+ if rule.status is RuleStatus.DEPRECATED:
80
+ continue
81
+ items.append(
82
+ {
83
+ "rule_key": rule.rule_key,
84
+ "rule_id": rule.rule_id,
85
+ "text": f"{rule.endpoint} {rule.field}: {rule.constraint}",
86
+ "type": "contract",
87
+ "transport": rule.transport.value,
88
+ "endpoint": rule.endpoint,
89
+ "field": rule.field,
90
+ "constraint": rule.constraint,
91
+ "authority": rule.authority.value,
92
+ "source_kind": "explicit",
93
+ "priority": "P1",
94
+ "status": rule.status.value,
95
+ }
96
+ )
97
+ return items[:MAX_RULES_IN_PROMPT]
98
+
99
+
100
+ _MAX_BRANCH_BODY_CHARS = 4_000
101
+
102
+
103
+ def _branch_body(branch: Any) -> Any:
104
+ if branch.reply is not None:
105
+ return branch.reply.body
106
+ return branch.stub.body
107
+
108
+
109
+ def _body_view(body: Any) -> Any:
110
+ """限制进入提示词的响应体大小,避免一个巨大桩撑爆上下文。"""
111
+ try:
112
+ text = json.dumps(body, ensure_ascii=False, separators=(",", ":"))
113
+ except (TypeError, ValueError):
114
+ return None
115
+ if len(text) > _MAX_BRANCH_BODY_CHARS:
116
+ return {"truncated": True, "preview": text[:_MAX_BRANCH_BODY_CHARS]}
117
+ return body
118
+
119
+
120
+ def _semantic_view(semantic: MockSemantic | None) -> list[dict[str, Any]]:
121
+ if semantic is None:
122
+ return []
123
+ return [
124
+ {
125
+ "dep_id": dep.dep_id,
126
+ "transport": dep.transport.value,
127
+ "endpoint": dep.endpoint,
128
+ "route_key": dep.route_key,
129
+ "strategy": dep.strategy.value,
130
+ "branches": [
131
+ {
132
+ "branch": branch.branch,
133
+ "outcome": branch.outcome.value,
134
+ "semantics": branch.semantics,
135
+ "source_kind": branch.source.kind,
136
+ "rule_keys": list(branch.source.rule_keys),
137
+ "body": _body_view(_branch_body(branch)),
138
+ }
139
+ for branch in dep.branches
140
+ ],
141
+ "gap_reason": [
142
+ gap.reason for gap in semantic.gaps if gap.dep_id == dep.dep_id
143
+ ],
144
+ }
145
+ for dep in semantic.deps
146
+ ]
147
+
148
+
149
+ def _catalog_view(catalog: DataCatalog | None) -> dict[str, Any] | None:
150
+ if catalog is None:
151
+ return None
152
+ return {
153
+ "catalog_id": catalog.catalog_id,
154
+ "tables": [
155
+ {
156
+ "name": table.name,
157
+ "primary_key": list(table.primary_key),
158
+ "columns": [
159
+ {
160
+ "name": column.name,
161
+ "type": column.type,
162
+ "nullable": column.nullable,
163
+ "enum_values": list(column.enum_values),
164
+ "semantic_type": column.semantic_type.value,
165
+ }
166
+ for column in table.columns
167
+ ],
168
+ }
169
+ for table in catalog.tables
170
+ ],
171
+ "states": [
172
+ {
173
+ "state_key": state.state_key,
174
+ "target_state": state.target_state,
175
+ "table_values": state.table_values,
176
+ "rule_keys": list(state.rule_keys),
177
+ }
178
+ for state in catalog.states
179
+ ],
180
+ "gaps": catalog.gaps,
181
+ }
182
+
183
+
184
+ def _profile_view(profile: dict[str, Any]) -> dict[str, Any]:
185
+ return {
186
+ "endpoint": profile.get("endpoint"),
187
+ "method": profile.get("method"),
188
+ "path": profile.get("path"),
189
+ "transport": profile.get("transport", "http"),
190
+ "coverage_role": profile.get("coverage_role", "primary"),
191
+ "business_key": profile.get("business_key"),
192
+ "contract_incomplete": bool(profile.get("contract_incomplete")),
193
+ "contract_incomplete_reason": profile.get("contract_incomplete_reason"),
194
+ "params": profile.get("params") or [],
195
+ "request_body": profile.get("request_body") or {},
196
+ "body_required": profile.get("body_required") or [],
197
+ "response_fields": profile.get("response_fields") or {},
198
+ "success_codes": profile.get("success_codes") or [],
199
+ "error_codes": profile.get("error_codes") or [],
200
+ "downstream_deps": profile.get("downstream_deps") or [],
201
+ "service": profile.get("service"),
202
+ "parameter_types": profile.get("parameter_types") or [],
203
+ "parameter_schemas": profile.get("parameter_schemas") or [],
204
+ "return_type": profile.get("return_type"),
205
+ "result_schema": profile.get("result_schema"),
206
+ "group": profile.get("group"),
207
+ "version": profile.get("version"),
208
+ "direct_url": profile.get("direct_url"),
209
+ "protocol_port": profile.get("protocol_port"),
210
+ "url_source": profile.get("url_source"),
211
+ "mq_producers": profile.get("mq_producers") or [],
212
+ "mq_warnings": profile.get("mq_warnings") or [],
213
+ }
214
+
215
+
216
+ def _prompt_input(
217
+ context: dict[str, Any],
218
+ *,
219
+ ruleset: RuleSet,
220
+ mode: str,
221
+ changed_apis: list[dict[str, Any]] | None,
222
+ mock_semantic: MockSemantic | None,
223
+ data_catalog: DataCatalog | None,
224
+ ) -> dict[str, Any]:
225
+ profiles = context.get("profiles") or []
226
+ supported_transports = {"http", "dubbo"}
227
+ supported_profiles = [
228
+ item
229
+ for item in profiles
230
+ if str(item.get("transport", "http")).lower() in supported_transports
231
+ ]
232
+ unsupported_profiles = [
233
+ {
234
+ "endpoint": item.get("endpoint"),
235
+ "transport": item.get("transport"),
236
+ "reason": "transport_not_supported_in_case_design",
237
+ }
238
+ for item in profiles
239
+ if str(item.get("transport", "http")).lower() not in supported_transports
240
+ ]
241
+ return {
242
+ "mode": mode,
243
+ "context_id": context.get("context_id"),
244
+ "profiles": [_profile_view(item) for item in supported_profiles],
245
+ "unsupported_profiles": unsupported_profiles,
246
+ "profile_unmapped": context.get("profile_unmapped") or [],
247
+ "documents": context.get("documents") or [],
248
+ "openapi": context.get("openapi") or {},
249
+ "changed_apis": changed_apis or [],
250
+ "ruleset": {
251
+ "ruleset_id": ruleset.ruleset_id,
252
+ "version": ruleset.version,
253
+ "hash": rule_set_hash(ruleset),
254
+ "rules": _rule_view(ruleset),
255
+ "conflicts": [
256
+ {
257
+ "topic": conflict.topic,
258
+ "kind": conflict.kind.value,
259
+ "severity": conflict.severity.value if conflict.severity else "",
260
+ "rule_keys": list(conflict.rule_keys),
261
+ "docs": list(conflict.docs),
262
+ "origin": conflict.origin,
263
+ "reason": conflict.reason,
264
+ }
265
+ for conflict in ruleset.conflicts
266
+ ],
267
+ },
268
+ "mock_semantics": _semantic_view(mock_semantic),
269
+ "data_catalog": _catalog_view(data_catalog),
270
+ "schema": CaseDraft.model_json_schema(),
271
+ }
272
+
273
+
274
+ def _auto_bind_single_dependency(
275
+ draft: CaseDraft, semantic: MockSemantic | None, context: dict[str, Any]
276
+ ) -> list[str]:
277
+ warnings: list[str] = []
278
+ if semantic is None:
279
+ return warnings
280
+ branches = semantic.branch_index()
281
+ profiles = {
282
+ str(profile.get("endpoint") or ""): profile
283
+ for profile in context.get("profiles") or []
284
+ }
285
+ for case in draft.cases:
286
+ if case.mock_bindings:
287
+ continue
288
+ if case.category not in ("positive", "business", "smoke"):
289
+ continue
290
+ profile = profiles.get(case.endpoint)
291
+ if profile is None:
292
+ continue
293
+ deps = [
294
+ str(dep.get("dep_id") or "")
295
+ for dep in profile.get("downstream_deps") or []
296
+ if dep.get("dep_id")
297
+ ]
298
+ if len(deps) != 1:
299
+ continue
300
+ dep_id = deps[0]
301
+ if (dep_id, "success") not in branches:
302
+ continue
303
+ case.mock_bindings = {dep_id: "success"}
304
+ warnings.append(f"default_success_binding:{case.case_key}:{dep_id}")
305
+ return warnings
306
+
307
+
308
+ def _auto_bind_mock_replies(
309
+ draft: CaseDraft, semantic: MockSemantic | None
310
+ ) -> list[str]:
311
+ """模型给了 mock_replies 却漏了 binding 时补 success,并留下告警。"""
312
+ warnings: list[str] = []
313
+ if semantic is None:
314
+ return warnings
315
+ branches = semantic.branch_index()
316
+ for case in draft.cases:
317
+ for dep_id in case.mock_replies:
318
+ if dep_id in case.mock_bindings:
319
+ continue
320
+ if (dep_id, "success") not in branches:
321
+ continue
322
+ case.mock_bindings[dep_id] = "success"
323
+ warnings.append(
324
+ f"default_success_binding:{case.case_key}:{dep_id}"
325
+ )
326
+ return warnings
327
+
328
+
329
+ def generate_case_design(
330
+ context: dict[str, Any],
331
+ *,
332
+ ruleset: RuleSet,
333
+ llm: LLMClient,
334
+ project: str | Path,
335
+ mode: str = "full",
336
+ changed_apis: list[dict[str, Any]] | None = None,
337
+ mock_semantic: MockSemantic | None = None,
338
+ data_catalog: DataCatalog | None = None,
339
+ prompt_path: str | Path | None = None,
340
+ max_cases: int = MAX_CASES,
341
+ ) -> CaseDesignResult:
342
+ if ruleset is None:
343
+ raise AgentError("rules_missing", "A4 需要规则库,禁止无规则生成用例")
344
+ system = load_case_design_prompt(prompt_path)
345
+ user = json.dumps(
346
+ _prompt_input(
347
+ context,
348
+ ruleset=ruleset,
349
+ mode=mode,
350
+ changed_apis=changed_apis,
351
+ mock_semantic=mock_semantic,
352
+ data_catalog=data_catalog,
353
+ ),
354
+ ensure_ascii=False,
355
+ separators=(",", ":"),
356
+ )
357
+ try:
358
+ payload = llm.complete_json(system=system, user=user)
359
+ except LLMError as exc:
360
+ raise AgentError("case_design_llm_failed", str(exc)) from exc
361
+ if not isinstance(payload, dict):
362
+ raise AgentError("case_design_invalid", "模型输出必须是 JSON object")
363
+ try:
364
+ draft = CaseDraft.model_validate(payload)
365
+ except Exception as exc:
366
+ raise AgentError("case_design_invalid", str(exc)[:2_000]) from exc
367
+ if len(draft.cases) > max_cases:
368
+ raise AgentError(
369
+ "case_design_too_many_cases", f"{len(draft.cases)} > {max_cases}"
370
+ )
371
+
372
+ draft.context_id = str(context.get("context_id") or "")
373
+ draft.ruleset_id = ruleset.ruleset_id
374
+ draft.ruleset_hash = rule_set_hash(ruleset)
375
+ draft.generator = {
376
+ **(draft.generator or {}),
377
+ "kind": "llm",
378
+ "name": str((draft.generator or {}).get("name") or "astsight-a4"),
379
+ }
380
+ if not draft.scope_docs:
381
+ draft.scope_docs = sorted(
382
+ {
383
+ ref.doc
384
+ for case in draft.cases
385
+ for ref in case.requirement_refs
386
+ if ref.doc
387
+ }
388
+ )
389
+
390
+ warnings = _auto_bind_single_dependency(draft, mock_semantic, context)
391
+ warnings.extend(_auto_bind_mock_replies(draft, mock_semantic))
392
+ validation = validate_draft(
393
+ draft,
394
+ context,
395
+ project=project,
396
+ ruleset=ruleset,
397
+ data_catalog=data_catalog,
398
+ mock_semantic=mock_semantic,
399
+ require_rules=True,
400
+ )
401
+ errors = [item.message for item in validation.errors]
402
+ warnings.extend(item.message for item in validation.warnings)
403
+ if errors:
404
+ raise AgentError(
405
+ "case_design_validation_failed",
406
+ ";".join(errors[:20]),
407
+ details={
408
+ "errors": errors,
409
+ "warnings": warnings,
410
+ "draft": draft.model_dump(mode="json"),
411
+ },
412
+ )
413
+ return CaseDesignResult(draft=draft, validation=validation, warnings=warnings)
414
+
415
+
416
+ __all__ = [
417
+ "MAX_CASES",
418
+ "CaseDesignResult",
419
+ "generate_case_design",
420
+ "load_case_design_prompt",
421
+ ]
@@ -0,0 +1,196 @@
1
+ """A4 用例草案生成:semantic analysis → CaseDraft。
2
+
3
+ 草案仍走既有的 `validate_draft`(端点/字段/quote/断言组合/资源上限),
4
+ 并额外核对 mock_bindings 的 dep_id 与分支是否来自 context + semantic analysis。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from ..cases.draft import CaseDraft
13
+ from ..cases.validate import ValidationResult, validate_draft
14
+ from ..llm import LLMClient, LLMError
15
+ from .errors import AgentError
16
+ from .models import SemanticAnalysis
17
+
18
+ _ENGINE_ROOT = Path(__file__).resolve().parents[2]
19
+ _AST_SIGHT_ROOT = _ENGINE_ROOT.parent
20
+ # 旧链路提示词:只保留模块兼容,不再被规则驱动主流程调用。
21
+ _PROMPT_PATH = _AST_SIGHT_ROOT / "prompts" / "legacy" / "agent_case_generation.md"
22
+ MAX_CASES = 200
23
+
24
+
25
+ def load_casegen_prompt(path: str | Path | None = None) -> str:
26
+ prompt_path = Path(path) if path else _PROMPT_PATH
27
+ if not prompt_path.is_file():
28
+ raise AgentError("casegen_prompt_missing", str(prompt_path))
29
+ return prompt_path.read_text(encoding="utf-8")
30
+
31
+
32
+ def _profile_index(context: dict[str, Any]) -> dict[str, dict[str, Any]]:
33
+ return {
34
+ str(profile.get("endpoint") or ""): profile
35
+ for profile in context.get("profiles") or []
36
+ }
37
+
38
+
39
+ def _dep_index(profile: dict[str, Any]) -> dict[str, dict[str, Any]]:
40
+ return {
41
+ str(dep.get("dep_id") or ""): dep
42
+ for dep in profile.get("downstream_deps") or []
43
+ if dep.get("dep_id")
44
+ }
45
+
46
+
47
+ def _auto_bind_single_dependency(
48
+ draft: CaseDraft,
49
+ analysis: SemanticAnalysis,
50
+ context: dict[str, Any],
51
+ ) -> list[str]:
52
+ """仅对“恰好一个下游 + 正向/业务 + LLM 未绑定”补 success,且显式告警。"""
53
+ warnings: list[str] = []
54
+ profiles = _profile_index(context)
55
+ branches = analysis.branch_index()
56
+ for case in draft.cases:
57
+ if case.mock_bindings:
58
+ continue
59
+ if case.category not in ("positive", "business"):
60
+ continue
61
+ profile = profiles.get(case.endpoint)
62
+ if profile is None:
63
+ continue
64
+ deps = _dep_index(profile)
65
+ if len(deps) != 1:
66
+ continue
67
+ dep_id = next(iter(deps))
68
+ if (dep_id, "success") not in branches:
69
+ continue
70
+ case.mock_bindings = {dep_id: "success"}
71
+ warnings.append(
72
+ f"default_success_binding:{case.case_key}:{dep_id}"
73
+ )
74
+ return warnings
75
+
76
+
77
+ def validate_case_bindings(
78
+ draft: CaseDraft,
79
+ analysis: SemanticAnalysis,
80
+ context: dict[str, Any],
81
+ ) -> tuple[list[str], list[str]]:
82
+ """返回 (errors, warnings);只核对下游绑定与证据,不改写用例。"""
83
+ errors: list[str] = []
84
+ warnings: list[str] = []
85
+ branches = analysis.branch_index()
86
+ profiles = _profile_index(context)
87
+ for case in draft.cases:
88
+ profile = profiles.get(case.endpoint)
89
+ if profile is None:
90
+ continue
91
+ deps = _dep_index(profile)
92
+ for dep_id, branch in case.mock_bindings.items():
93
+ if dep_id not in deps:
94
+ errors.append(
95
+ f"{case.case_key}: mock dep_id 不属于 {case.endpoint}: {dep_id!r}"
96
+ )
97
+ if (dep_id, branch) not in branches:
98
+ errors.append(
99
+ f"{case.case_key}: 未定义的分支 {dep_id} / {branch}"
100
+ )
101
+ if deps and case.category in ("positive", "business") and not case.mock_bindings:
102
+ warnings.append(
103
+ f"downstream_unbound:{case.case_key}:{case.endpoint}"
104
+ )
105
+ return errors, warnings
106
+
107
+
108
+ def _prompt_input(context: dict[str, Any], analysis: SemanticAnalysis) -> dict[str, Any]:
109
+ return {
110
+ "context": {
111
+ "context_id": context.get("context_id"),
112
+ "documents": context.get("documents") or [],
113
+ "profiles": context.get("profiles") or [],
114
+ "profile_unmapped": context.get("profile_unmapped") or [],
115
+ "openapi": context.get("openapi") or {},
116
+ },
117
+ "semantic_analysis": analysis.model_dump(mode="json"),
118
+ "schema": CaseDraft.model_json_schema(),
119
+ }
120
+
121
+
122
+ def generate_case_draft(
123
+ context: dict[str, Any],
124
+ analysis: SemanticAnalysis,
125
+ *,
126
+ llm: LLMClient,
127
+ project: str | Path,
128
+ prompt_path: str | Path | None = None,
129
+ max_cases: int = MAX_CASES,
130
+ ) -> tuple[CaseDraft, ValidationResult, list[str]]:
131
+ system = load_casegen_prompt(prompt_path)
132
+ user = json.dumps(
133
+ _prompt_input(context, analysis),
134
+ ensure_ascii=False,
135
+ separators=(",", ":"),
136
+ )
137
+ try:
138
+ payload = llm.complete_json(system=system, user=user)
139
+ except LLMError as exc:
140
+ raise AgentError("casegen_llm_failed", str(exc)) from exc
141
+ if not isinstance(payload, dict):
142
+ raise AgentError("casegen_invalid", "模型输出必须是 JSON object")
143
+ try:
144
+ draft = CaseDraft.model_validate(payload)
145
+ except Exception as exc:
146
+ raise AgentError("casegen_invalid", str(exc)[:2_000]) from exc
147
+ if len(draft.cases) > max_cases:
148
+ raise AgentError(
149
+ "casegen_too_many_cases",
150
+ f"{len(draft.cases)} > {max_cases}",
151
+ )
152
+
153
+ draft.context_id = str(context.get("context_id") or "")
154
+ draft.generator = {
155
+ **(draft.generator or {}),
156
+ "kind": "llm",
157
+ "name": str((draft.generator or {}).get("name") or "astsight-a4"),
158
+ }
159
+ if not draft.scope_docs:
160
+ draft.scope_docs = sorted(
161
+ {
162
+ ref.doc
163
+ for case in draft.cases
164
+ for ref in case.requirement_refs
165
+ if ref.doc
166
+ }
167
+ )
168
+
169
+ warnings = _auto_bind_single_dependency(draft, analysis, context)
170
+ validation = validate_draft(draft, context, project=project)
171
+ errors = [item.message for item in validation.errors]
172
+ binding_errors, binding_warnings = validate_case_bindings(
173
+ draft, analysis, context
174
+ )
175
+ errors.extend(binding_errors)
176
+ warnings.extend(binding_warnings)
177
+ warnings.extend(item.message for item in validation.warnings)
178
+ if errors:
179
+ raise AgentError(
180
+ "casegen_validation_failed",
181
+ ";".join(errors[:20]),
182
+ details={
183
+ "errors": errors,
184
+ "warnings": warnings,
185
+ "draft": draft.model_dump(mode="json"),
186
+ },
187
+ )
188
+ return draft, validation, warnings
189
+
190
+
191
+ __all__ = [
192
+ "MAX_CASES",
193
+ "generate_case_draft",
194
+ "load_casegen_prompt",
195
+ "validate_case_bindings",
196
+ ]