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/agent/jar.py ADDED
@@ -0,0 +1,235 @@
1
+ """Java agent jar 解析与校验:环境变量 → 安装的 wheel → 源码树构建产物。
2
+
3
+ 只有校验通过的 jar 才会被注入 `JAVA_TOOL_OPTIONS`。安装包(wheel)里的 jar
4
+ 必须带 `manifest.json`(版本、协议号、sha256、大小),引擎逐项比对;源码树
5
+ 里的 `mvn package` 产物没有 sidecar 时按“未校验的开发构建”接受,但版本仍须
6
+ 匹配预期版本。
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import importlib.metadata
12
+ import json
13
+ import os
14
+ import re
15
+ import zipfile
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ AGENT_PROTOCOL = 1
21
+ AGENT_VERSION = "0.1.0.dev0"
22
+ DISTRIBUTION_NAME = "astsight-java-agent"
23
+
24
+ _JAR_ENV = "ASTSIGHT_JAVA_AGENT_JAR"
25
+ _VERSION_ENV = "ASTSIGHT_JAVA_AGENT_REQUIRED_VERSION"
26
+ _IMPORT_NAME = "astsight_java_agent"
27
+ _WHEEL_JAR = f"{_IMPORT_NAME}/agent/astsight-agent.jar"
28
+ _WHEEL_MANIFEST = f"{_IMPORT_NAME}/manifest.json"
29
+ _JAR_DEFAULT = (
30
+ Path(__file__).resolve().parents[3]
31
+ / "java"
32
+ / "astsight-agent"
33
+ / "target"
34
+ / "astsight-agent.jar"
35
+ )
36
+ _SNAPSHOT_RE = re.compile(r"^(.+)-SNAPSHOT$")
37
+
38
+
39
+ class AgentJarError(ValueError):
40
+ """jar 或 manifest 无法解析;`reason` 直接进入注入告警后缀。"""
41
+
42
+ def __init__(self, reason: str) -> None:
43
+ super().__init__(reason)
44
+ self.reason = reason
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class AgentJar:
49
+ path: Path
50
+ version: str
51
+ source: str
52
+ sha256: str | None = None
53
+
54
+
55
+ def normalize_agent_version(raw: str) -> str:
56
+ """把 Maven 版本归一成 PEP 440 可表示的版本号。
57
+
58
+ `0.1.0-SNAPSHOT` → `0.1.0.dev0`;`0.2-SNAPSHOT` → `0.2.0.dev0`。
59
+ """
60
+ text = raw.strip()
61
+ match = _SNAPSHOT_RE.match(text)
62
+ if not match:
63
+ return text
64
+ parts = match.group(1).split(".")
65
+ if all(part.isdigit() for part in parts) and len(parts) < 3:
66
+ parts += ["0"] * (3 - len(parts))
67
+ return ".".join(parts) + ".dev0"
68
+
69
+
70
+ def expected_agent_version() -> str:
71
+ override = os.environ.get(_VERSION_ENV, "").strip()
72
+ return override or AGENT_VERSION
73
+
74
+
75
+ def resolve_agent_jar(*, required_version: str | None = None) -> tuple[AgentJar | None, str | None]:
76
+ """返回 (jar, 失败原因)。失败原因为 None 时 jar 一定可用。"""
77
+ expected = normalize_agent_version(required_version or expected_agent_version())
78
+
79
+ configured = os.environ.get(_JAR_ENV, "").strip()
80
+ if configured:
81
+ # 显式覆盖只认这一个路径,缺失就报错,不静默回退到别的 jar。
82
+ return _load(Path(configured), source="env", expected=expected, require_manifest=False)
83
+
84
+ try:
85
+ wheel = _wheel_paths(importlib.metadata.distribution(DISTRIBUTION_NAME))
86
+ except importlib.metadata.PackageNotFoundError:
87
+ wheel = None
88
+ except AgentJarError as error:
89
+ return None, error.reason
90
+ if wheel is not None:
91
+ jar_path, manifest_path = wheel
92
+ if manifest_path is None:
93
+ return None, "agent_jar_manifest_missing"
94
+ return _load(
95
+ jar_path,
96
+ source="wheel",
97
+ expected=expected,
98
+ require_manifest=True,
99
+ manifest_path=manifest_path,
100
+ )
101
+
102
+ return _load(_JAR_DEFAULT, source="repo", expected=expected, require_manifest=False)
103
+
104
+
105
+ def _wheel_paths(dist: Any) -> tuple[Path, Path | None]:
106
+ """从已安装 distribution 里定位 jar 与 manifest(测试可传 fake dist)。"""
107
+ files = list(getattr(dist, "files", None) or [])
108
+ jar_entry = next((f for f in files if f.as_posix().endswith(_WHEEL_JAR)), None)
109
+ if jar_entry is None:
110
+ raise AgentJarError("agent_jar_missing")
111
+ manifest_entry = next(
112
+ (f for f in files if f.as_posix().endswith(_WHEEL_MANIFEST)), None
113
+ )
114
+ jar = Path(dist.locate_file(jar_entry))
115
+ manifest = Path(dist.locate_file(manifest_entry)) if manifest_entry else None
116
+ return jar, manifest
117
+
118
+
119
+ def _load(
120
+ path: Path,
121
+ *,
122
+ source: str,
123
+ expected: str,
124
+ require_manifest: bool,
125
+ manifest_path: Path | None = None,
126
+ ) -> tuple[AgentJar | None, str | None]:
127
+ if not path.is_file():
128
+ return None, "agent_jar_missing"
129
+ if any(char.isspace() for char in str(path)):
130
+ return None, "agent_jar_path_has_space"
131
+ try:
132
+ entries = _jar_manifest(path)
133
+ except AgentJarError as error:
134
+ return None, error.reason
135
+ jar_version = entries.get("Implementation-Version", "").strip()
136
+ if not jar_version:
137
+ return None, "agent_jar_unreadable"
138
+ if normalize_agent_version(jar_version) != expected:
139
+ return None, "agent_jar_version_mismatch"
140
+
141
+ sidecar = manifest_path or path.with_name(path.name + ".manifest.json")
142
+ if not sidecar.is_file():
143
+ if require_manifest:
144
+ return None, "agent_jar_manifest_missing"
145
+ return AgentJar(path=path, version=expected, source=source), None
146
+ try:
147
+ manifest = _read_manifest(sidecar)
148
+ digest = _sha256(path)
149
+ _check_manifest(
150
+ manifest,
151
+ jar_version=jar_version,
152
+ expected=expected,
153
+ digest=digest,
154
+ size=path.stat().st_size,
155
+ )
156
+ except AgentJarError as error:
157
+ return None, error.reason
158
+ return (
159
+ AgentJar(path=path, version=expected, source=source, sha256=digest),
160
+ None,
161
+ )
162
+
163
+
164
+ def _jar_manifest(path: Path) -> dict[str, str]:
165
+ try:
166
+ with zipfile.ZipFile(path) as archive:
167
+ raw = archive.read("META-INF/MANIFEST.MF")
168
+ except (OSError, KeyError, zipfile.BadZipFile):
169
+ raise AgentJarError("agent_jar_unreadable") from None
170
+ entries: dict[str, str] = {}
171
+ last_key: str | None = None
172
+ for line in raw.decode("utf-8", errors="replace").splitlines():
173
+ if line.startswith(" ") and last_key:
174
+ entries[last_key] += line[1:]
175
+ continue
176
+ if ":" not in line:
177
+ last_key = None
178
+ continue
179
+ key, value = line.split(":", 1)
180
+ last_key = key.strip()
181
+ entries[last_key] = value.strip()
182
+ return entries
183
+
184
+
185
+ def _read_manifest(path: Path) -> dict[str, Any]:
186
+ try:
187
+ parsed = json.loads(path.read_text(encoding="utf-8"))
188
+ except (OSError, ValueError):
189
+ raise AgentJarError("agent_jar_manifest_invalid") from None
190
+ if not isinstance(parsed, dict):
191
+ raise AgentJarError("agent_jar_manifest_invalid")
192
+ return parsed
193
+
194
+
195
+ def _check_manifest(
196
+ manifest: dict[str, Any],
197
+ *,
198
+ jar_version: str,
199
+ expected: str,
200
+ digest: str,
201
+ size: int,
202
+ ) -> None:
203
+ if manifest.get("schema") != 1 or manifest.get("artifact") != DISTRIBUTION_NAME:
204
+ raise AgentJarError("agent_jar_manifest_invalid")
205
+ if str(manifest.get("jar_version") or "").strip() != jar_version:
206
+ raise AgentJarError("agent_jar_version_mismatch")
207
+ if normalize_agent_version(str(manifest.get("version") or "")) != expected:
208
+ raise AgentJarError("agent_jar_version_mismatch")
209
+ if manifest.get("protocol") != AGENT_PROTOCOL:
210
+ raise AgentJarError("agent_jar_protocol_mismatch")
211
+ if str(manifest.get("sha256") or "").lower() != digest:
212
+ raise AgentJarError("agent_jar_checksum_mismatch")
213
+ declared_size = manifest.get("size")
214
+ if isinstance(declared_size, int) and declared_size != size:
215
+ raise AgentJarError("agent_jar_size_mismatch")
216
+
217
+
218
+ def _sha256(path: Path) -> str:
219
+ hasher = hashlib.sha256()
220
+ with path.open("rb") as handle:
221
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
222
+ hasher.update(chunk)
223
+ return hasher.hexdigest()
224
+
225
+
226
+ __all__ = [
227
+ "AGENT_PROTOCOL",
228
+ "AGENT_VERSION",
229
+ "DISTRIBUTION_NAME",
230
+ "AgentJar",
231
+ "AgentJarError",
232
+ "expected_agent_version",
233
+ "normalize_agent_version",
234
+ "resolve_agent_jar",
235
+ ]
@@ -0,0 +1,136 @@
1
+ """C3.5.1 Mock 语义适配器:为契约层无法补全的响应分支提供 LLM 候选。
2
+
3
+ 默认 `success` 与规则映射分支已由 `astsight.mock.semantic` 确定性生成;
4
+ 这里只补响应骨架/语义,候选仍逐项校验,未知 dep/分支/规则一律拒绝。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field
13
+
14
+ from contracts import MockSemantic, RuleSet
15
+
16
+ from ..llm import LLMClient, LLMError
17
+ from ..mock.semantic import (
18
+ MockSemanticApplyResult,
19
+ apply_mock_semantic_candidates,
20
+ )
21
+ from .errors import AgentError
22
+
23
+ _ENGINE_ROOT = Path(__file__).resolve().parents[2]
24
+ _AST_SIGHT_ROOT = _ENGINE_ROOT.parent
25
+ _PROMPT_PATH = _AST_SIGHT_ROOT / "prompts" / "c35_mock_semantics.md"
26
+
27
+
28
+ class MockSemanticDraft(BaseModel):
29
+ model_config = ConfigDict(extra="forbid")
30
+
31
+ deps: list[dict[str, Any]] = Field(default_factory=list, max_length=200)
32
+ gaps: list[dict[str, Any]] = Field(default_factory=list, max_length=200)
33
+ questions: list[dict[str, Any]] = Field(default_factory=list, max_length=100)
34
+
35
+
36
+ def load_mock_semantic_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("mock_semantics_prompt_missing", str(prompt_path))
40
+ return prompt_path.read_text(encoding="utf-8")
41
+
42
+
43
+ def _needs_candidates(semantic: MockSemantic) -> bool:
44
+ for dep in semantic.deps:
45
+ success = next(
46
+ (branch for branch in dep.branches if branch.branch == "success"), None
47
+ )
48
+ if success is None or not success.stub.body:
49
+ return True
50
+ return False
51
+
52
+
53
+ def generate_mock_semantic_candidates(
54
+ context: dict[str, Any],
55
+ semantic: MockSemantic,
56
+ *,
57
+ ruleset: RuleSet | None,
58
+ llm: LLMClient,
59
+ prompt_path: str | Path | None = None,
60
+ ) -> MockSemanticApplyResult | None:
61
+ """只为缺失/空 success body 的下游调用模型;无需要时返回 None。"""
62
+ if not semantic.deps or not _needs_candidates(semantic):
63
+ return None
64
+ system = load_mock_semantic_prompt(prompt_path)
65
+ user = json.dumps(
66
+ {
67
+ "context_id": context.get("context_id"),
68
+ "profiles": context.get("profiles") or [],
69
+ "deps": [
70
+ {
71
+ "dep_id": dep.dep_id,
72
+ "endpoint": dep.endpoint,
73
+ "route_key": dep.route_key,
74
+ "branches": [
75
+ {
76
+ "branch": branch.branch,
77
+ "semantics": branch.semantics,
78
+ "stub": branch.stub.model_dump(mode="json"),
79
+ "source": branch.source.model_dump(mode="json"),
80
+ }
81
+ for branch in dep.branches
82
+ ],
83
+ }
84
+ for dep in semantic.deps
85
+ ],
86
+ "rules": (
87
+ [
88
+ {
89
+ "rule_key": rule.rule_key,
90
+ "rule_id": rule.rule_id,
91
+ "text": rule.text,
92
+ "authority": rule.authority.value,
93
+ }
94
+ for rule in ruleset.rules
95
+ ]
96
+ if ruleset is not None
97
+ else []
98
+ ),
99
+ "schema": MockSemanticDraft.model_json_schema(),
100
+ "notes": [
101
+ "只补充 branches,不新增 dep_id",
102
+ "success 分支可提供响应骨架 stub.body/status",
103
+ "非 success 分支必须有 source.rule_keys,且只能引用输入规则",
104
+ "无法确定时不要生成分支,写 gaps",
105
+ ],
106
+ },
107
+ ensure_ascii=False,
108
+ separators=(",", ":"),
109
+ )
110
+ try:
111
+ payload = llm.complete_json(system=system, user=user)
112
+ except LLMError as exc:
113
+ raise AgentError("mock_semantics_llm_failed", str(exc)) from exc
114
+ if not isinstance(payload, dict):
115
+ raise AgentError("mock_semantics_invalid", "模型输出必须是 JSON object")
116
+ try:
117
+ draft = MockSemanticDraft.model_validate(payload)
118
+ except Exception as exc:
119
+ raise AgentError("mock_semantics_invalid", str(exc)[:2_000]) from exc
120
+ result = apply_mock_semantic_candidates(
121
+ semantic, draft.model_dump(mode="json"), context=context, ruleset=ruleset
122
+ )
123
+ if not result.ok:
124
+ raise AgentError(
125
+ "mock_semantics_candidates_invalid",
126
+ ";".join(result.errors[:20]),
127
+ details={"errors": result.errors, "warnings": result.warnings},
128
+ )
129
+ return result
130
+
131
+
132
+ __all__ = [
133
+ "MockSemanticDraft",
134
+ "generate_mock_semantic_candidates",
135
+ "load_mock_semantic_prompt",
136
+ ]