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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""CLI 子命令的 service 实现。"""
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""CLI 命令共用的路径与可选输入加载。"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from contracts import DataCatalog, RuleSet
|
|
7
|
+
|
|
8
|
+
from ..persistence import load_json
|
|
9
|
+
from ..rules import load_rule_set
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _resolve_under_project(project: Path, raw: str | None) -> Path | None:
|
|
13
|
+
if not raw:
|
|
14
|
+
return None
|
|
15
|
+
path = Path(raw)
|
|
16
|
+
if not path.is_absolute():
|
|
17
|
+
cwd_candidate = (Path.cwd() / path).resolve()
|
|
18
|
+
path = cwd_candidate if cwd_candidate.exists() else (project / path).resolve()
|
|
19
|
+
return path.resolve()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _load_optional_ruleset(project: Path, raw: str | None) -> RuleSet | None:
|
|
23
|
+
path = _resolve_under_project(project, raw)
|
|
24
|
+
if path is None or not path.is_file():
|
|
25
|
+
return None
|
|
26
|
+
return load_rule_set(path)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _load_optional_catalog(project: Path, raw: str | None) -> DataCatalog | None:
|
|
30
|
+
path = _resolve_under_project(project, raw)
|
|
31
|
+
if path is None or not path.is_file():
|
|
32
|
+
return None
|
|
33
|
+
return DataCatalog.model_validate(load_json(path))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _load_optional_mock_semantic(project: Path, raw: str | None):
|
|
37
|
+
from contracts import MockSemantic
|
|
38
|
+
|
|
39
|
+
path = _resolve_under_project(project, raw)
|
|
40
|
+
if path is None or not path.is_file():
|
|
41
|
+
return None
|
|
42
|
+
return MockSemantic.model_validate(load_json(path))
|
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
"""CLI data 命令的 service 实现。"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import shlex
|
|
7
|
+
import sys
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
from codegraph import (
|
|
12
|
+
CODEGRAPH_VERSION,
|
|
13
|
+
install as install_codegraph_runtime,
|
|
14
|
+
status as codegraph_runtime_status,
|
|
15
|
+
)
|
|
16
|
+
from contracts import DataCatalog, DataPlanBundle, MockPlan, RuleSet
|
|
17
|
+
from ..cases.context import load_context, prepare_context
|
|
18
|
+
from ..cases.draft import load_draft
|
|
19
|
+
from ..cases.proposal import (
|
|
20
|
+
ProposalError,
|
|
21
|
+
approve_proposal,
|
|
22
|
+
build_proposal,
|
|
23
|
+
classify,
|
|
24
|
+
interactive_review,
|
|
25
|
+
list_pending_proposals,
|
|
26
|
+
)
|
|
27
|
+
from ..cases.store import (
|
|
28
|
+
case_summary,
|
|
29
|
+
empty_case_set,
|
|
30
|
+
load_case_set,
|
|
31
|
+
requirement_coverage,
|
|
32
|
+
resolve_case_base,
|
|
33
|
+
)
|
|
34
|
+
from ..cases.validate import validate_draft
|
|
35
|
+
from ..data import (
|
|
36
|
+
SeedData,
|
|
37
|
+
apply_bundle,
|
|
38
|
+
apply_semantics,
|
|
39
|
+
build_catalog,
|
|
40
|
+
build_data_plan_bundle,
|
|
41
|
+
load_seed,
|
|
42
|
+
parse_dbml,
|
|
43
|
+
parse_ddl,
|
|
44
|
+
reflect_database,
|
|
45
|
+
validate_catalog,
|
|
46
|
+
validate_plan_fixtures,
|
|
47
|
+
)
|
|
48
|
+
from ..data.semantics import SemanticDraft
|
|
49
|
+
from ..inventory import discover_openapi, inventory_routes
|
|
50
|
+
from ..mock import MockPlanError, validate_mock_plan
|
|
51
|
+
from ..mock.semantic import (
|
|
52
|
+
apply_mock_semantic_candidates,
|
|
53
|
+
build_mock_semantic,
|
|
54
|
+
validate_mock_semantic,
|
|
55
|
+
)
|
|
56
|
+
from ..persistence import load_json, save_json_atomic
|
|
57
|
+
from ..feedback import collect_feedback, open_issue
|
|
58
|
+
from ..pipeline import RunConfig, run
|
|
59
|
+
from ..profile import build_plan_from_profiles, build_profiles, load_spec, parse_operations
|
|
60
|
+
from ..rules import (
|
|
61
|
+
RuleDraft,
|
|
62
|
+
RuleStoreError,
|
|
63
|
+
build_rules_context,
|
|
64
|
+
import_rule_draft,
|
|
65
|
+
load_rule_set,
|
|
66
|
+
load_rules_context,
|
|
67
|
+
load_rule_draft,
|
|
68
|
+
prepare_rules_context,
|
|
69
|
+
render_rule_set_markdown,
|
|
70
|
+
rule_coverage,
|
|
71
|
+
rule_set_hash,
|
|
72
|
+
rule_set_snapshot,
|
|
73
|
+
save_rule_set,
|
|
74
|
+
write_rules_context,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
from ._shared import (
|
|
78
|
+
_load_optional_ruleset,
|
|
79
|
+
_resolve_under_project,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _data_path(project: Path, raw: str | None, default_name: str) -> Path:
|
|
84
|
+
path = Path(raw) if raw else project / ".astsight" / "data" / default_name
|
|
85
|
+
if not path.is_absolute():
|
|
86
|
+
path = project / path
|
|
87
|
+
if path.suffix.lower() != ".json":
|
|
88
|
+
path = path / default_name
|
|
89
|
+
return path.resolve()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _data_catalog(args) -> int:
|
|
93
|
+
project = Path(args.project).resolve()
|
|
94
|
+
try:
|
|
95
|
+
if args.db_url:
|
|
96
|
+
dialect = _catalog_dialect(args.db_url, args.dialect)
|
|
97
|
+
schemas = [
|
|
98
|
+
item.strip()
|
|
99
|
+
for item in str(args.schema or "").split(",")
|
|
100
|
+
if item.strip()
|
|
101
|
+
]
|
|
102
|
+
reflection = reflect_database(
|
|
103
|
+
args.db_url,
|
|
104
|
+
schemas=schemas,
|
|
105
|
+
include=args.include,
|
|
106
|
+
exclude=args.exclude,
|
|
107
|
+
)
|
|
108
|
+
parsed = reflection.ddl
|
|
109
|
+
sources = reflection.sources
|
|
110
|
+
elif args.dbml:
|
|
111
|
+
_catalog_reject_reflect_only(args)
|
|
112
|
+
dialect = args.dialect or "sqlite"
|
|
113
|
+
path = Path(_resolve_under_project(project, args.dbml) or args.dbml)
|
|
114
|
+
parsed = parse_dbml(path.read_text(encoding="utf-8-sig"))
|
|
115
|
+
sources = {
|
|
116
|
+
"kind": "dbml",
|
|
117
|
+
"file": _project_relative(project, path),
|
|
118
|
+
}
|
|
119
|
+
else:
|
|
120
|
+
_catalog_reject_reflect_only(args)
|
|
121
|
+
dialect = args.dialect or "sqlite"
|
|
122
|
+
text = "\n;\n".join(
|
|
123
|
+
Path(_resolve_under_project(project, raw) or raw).read_text(
|
|
124
|
+
encoding="utf-8-sig"
|
|
125
|
+
)
|
|
126
|
+
for raw in args.ddl
|
|
127
|
+
)
|
|
128
|
+
parsed = parse_ddl(text, dialect=dialect)
|
|
129
|
+
sources = {"kind": "ddl", "files": list(args.ddl)}
|
|
130
|
+
seed = load_seed(_resolve_under_project(project, args.seed), parsed)
|
|
131
|
+
context_id = None
|
|
132
|
+
if args.context:
|
|
133
|
+
context = load_rules_context(args.context)
|
|
134
|
+
context_id = str(context.get("context_id") or "")
|
|
135
|
+
ruleset = _load_optional_ruleset(project, args.ruleset)
|
|
136
|
+
if args.ruleset and ruleset is None:
|
|
137
|
+
raise ValueError(f"规则库不存在: {args.ruleset}")
|
|
138
|
+
if args.rule_states and ruleset is None:
|
|
139
|
+
raise ValueError("--rule-states 需要 --ruleset")
|
|
140
|
+
scan = None
|
|
141
|
+
if args.code:
|
|
142
|
+
from ..data import scan_code_enums
|
|
143
|
+
|
|
144
|
+
scan = scan_code_enums(project, args.code)
|
|
145
|
+
catalog = build_catalog(
|
|
146
|
+
project=project.name,
|
|
147
|
+
ddl=parsed,
|
|
148
|
+
seed=seed,
|
|
149
|
+
context_id=context_id,
|
|
150
|
+
dialect=dialect,
|
|
151
|
+
sources=sources,
|
|
152
|
+
ruleset=ruleset,
|
|
153
|
+
code_enums=list(scan.enums) if scan else None,
|
|
154
|
+
rule_states=args.rule_states,
|
|
155
|
+
)
|
|
156
|
+
if scan and scan.warnings:
|
|
157
|
+
catalog.warnings.extend(scan.warnings)
|
|
158
|
+
errors = validate_catalog(catalog)
|
|
159
|
+
if errors:
|
|
160
|
+
print(json.dumps({"ok": False, "errors": errors}, ensure_ascii=False, indent=2))
|
|
161
|
+
return 1
|
|
162
|
+
out = _data_path(project, args.out, "data_catalog.json")
|
|
163
|
+
save_json_atomic(out, catalog.model_dump(mode="json"))
|
|
164
|
+
except Exception as exc:
|
|
165
|
+
print(f"data catalog 失败: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
166
|
+
return 1
|
|
167
|
+
print(
|
|
168
|
+
json.dumps(
|
|
169
|
+
{
|
|
170
|
+
"ok": True,
|
|
171
|
+
"catalog": str(out),
|
|
172
|
+
"catalog_id": catalog.catalog_id,
|
|
173
|
+
"source": sources.get("kind"),
|
|
174
|
+
"dialect": dialect,
|
|
175
|
+
"schemas": sources.get("schemas") or [],
|
|
176
|
+
"tables": len(catalog.tables),
|
|
177
|
+
"foreign_keys": len(catalog.foreign_keys),
|
|
178
|
+
"tables_order": catalog.tables_order,
|
|
179
|
+
"semantic_values": sum(
|
|
180
|
+
len(column.value_semantics)
|
|
181
|
+
for table in catalog.tables
|
|
182
|
+
for column in table.columns
|
|
183
|
+
),
|
|
184
|
+
"code_enums": len(scan.enums) if scan else 0,
|
|
185
|
+
"code_files": len(scan.files) if scan else 0,
|
|
186
|
+
"rule_states": int(
|
|
187
|
+
(catalog.sources.get("rule_states") or {}).get(
|
|
188
|
+
"proposed", 0
|
|
189
|
+
)
|
|
190
|
+
),
|
|
191
|
+
"gaps": len(catalog.gaps),
|
|
192
|
+
"warnings": catalog.warnings,
|
|
193
|
+
},
|
|
194
|
+
ensure_ascii=False,
|
|
195
|
+
indent=2,
|
|
196
|
+
)
|
|
197
|
+
)
|
|
198
|
+
return 0
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _catalog_dialect(db_url: str, requested: str | None) -> str:
|
|
202
|
+
from ..data import dialect_from_url
|
|
203
|
+
|
|
204
|
+
inferred = dialect_from_url(db_url)
|
|
205
|
+
if requested and requested != inferred:
|
|
206
|
+
raise ValueError(
|
|
207
|
+
f"--dialect {requested} 与 --db-url 推断的 {inferred} 不一致"
|
|
208
|
+
)
|
|
209
|
+
return inferred
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _catalog_reject_reflect_only(args) -> None:
|
|
213
|
+
if args.schema or args.include or args.exclude:
|
|
214
|
+
raise ValueError("--schema/--include/--exclude 仅用于 --db-url")
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _project_relative(project: Path, path: Path) -> str:
|
|
218
|
+
try:
|
|
219
|
+
return path.resolve().relative_to(project).as_posix()
|
|
220
|
+
except ValueError:
|
|
221
|
+
return path.name
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _data_semantics(args) -> int:
|
|
225
|
+
project = Path(args.project).resolve()
|
|
226
|
+
if args.draft and args.llm:
|
|
227
|
+
print("--draft 与 --llm 只能二选一", file=sys.stderr)
|
|
228
|
+
return 1
|
|
229
|
+
if not args.draft and not args.llm:
|
|
230
|
+
print(
|
|
231
|
+
"需要 --draft(框架外模型输出)或 --llm(框架内调用模型)",
|
|
232
|
+
file=sys.stderr,
|
|
233
|
+
)
|
|
234
|
+
return 1
|
|
235
|
+
try:
|
|
236
|
+
catalog = DataCatalog.model_validate(load_json(args.catalog))
|
|
237
|
+
ruleset = _load_optional_ruleset(project, args.ruleset)
|
|
238
|
+
if args.llm:
|
|
239
|
+
from ..agent.data_prep import generate_data_semantics
|
|
240
|
+
from ..llm import LLMClient, load_config
|
|
241
|
+
|
|
242
|
+
context = None
|
|
243
|
+
if args.context:
|
|
244
|
+
context_path = _resolve_under_project(project, args.context)
|
|
245
|
+
context = load_json(context_path)
|
|
246
|
+
_draft, result = generate_data_semantics(
|
|
247
|
+
catalog,
|
|
248
|
+
llm=LLMClient(load_config(config_path=args.llm_config)),
|
|
249
|
+
ruleset=ruleset,
|
|
250
|
+
context=context if isinstance(context, dict) else None,
|
|
251
|
+
prompt_path=args.prompt,
|
|
252
|
+
)
|
|
253
|
+
catalog = result.catalog
|
|
254
|
+
else:
|
|
255
|
+
draft_path = _resolve_under_project(project, args.draft)
|
|
256
|
+
draft = SemanticDraft.model_validate(load_json(draft_path))
|
|
257
|
+
result = apply_semantics(catalog, draft, ruleset=ruleset)
|
|
258
|
+
if not result.ok:
|
|
259
|
+
print(
|
|
260
|
+
json.dumps(
|
|
261
|
+
{"ok": False, "errors": result.errors, "warnings": result.warnings},
|
|
262
|
+
ensure_ascii=False,
|
|
263
|
+
indent=2,
|
|
264
|
+
)
|
|
265
|
+
)
|
|
266
|
+
return 1
|
|
267
|
+
out = _data_path(project, args.out, "data_catalog.json")
|
|
268
|
+
save_json_atomic(out, catalog.model_dump(mode="json"))
|
|
269
|
+
except Exception as exc:
|
|
270
|
+
print(f"data semantics 失败: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
271
|
+
return 1
|
|
272
|
+
print(
|
|
273
|
+
json.dumps(
|
|
274
|
+
{
|
|
275
|
+
"ok": True,
|
|
276
|
+
"catalog": str(out),
|
|
277
|
+
"fields": result.applied_fields,
|
|
278
|
+
"states": result.applied_states,
|
|
279
|
+
"warnings": result.warnings,
|
|
280
|
+
},
|
|
281
|
+
ensure_ascii=False,
|
|
282
|
+
indent=2,
|
|
283
|
+
)
|
|
284
|
+
)
|
|
285
|
+
return 0
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _data_states(args) -> int:
|
|
289
|
+
project = Path(args.project).resolve()
|
|
290
|
+
try:
|
|
291
|
+
catalog = DataCatalog.model_validate(load_json(args.catalog))
|
|
292
|
+
errors = validate_catalog(catalog)
|
|
293
|
+
if errors:
|
|
294
|
+
print(
|
|
295
|
+
json.dumps({"ok": False, "errors": errors}, ensure_ascii=False, indent=2)
|
|
296
|
+
)
|
|
297
|
+
return 1
|
|
298
|
+
states = catalog.states
|
|
299
|
+
if args.state:
|
|
300
|
+
states = [
|
|
301
|
+
state for state in states if state.state_key == args.state
|
|
302
|
+
]
|
|
303
|
+
if not states:
|
|
304
|
+
print(f"state 不存在: {args.state}", file=sys.stderr)
|
|
305
|
+
return 1
|
|
306
|
+
gaps_by_state: dict[str, list[dict[str, Any]]] = {}
|
|
307
|
+
for gap in catalog.gaps:
|
|
308
|
+
key = str(gap.get("state_key") or "")
|
|
309
|
+
if key:
|
|
310
|
+
gaps_by_state.setdefault(key, []).append(gap)
|
|
311
|
+
payload: list[dict[str, Any]] = []
|
|
312
|
+
for state in states:
|
|
313
|
+
payload.append(
|
|
314
|
+
{
|
|
315
|
+
"state_key": state.state_key,
|
|
316
|
+
"rule_keys": list(state.rule_keys),
|
|
317
|
+
"tables": {
|
|
318
|
+
table: len(rows)
|
|
319
|
+
for table, rows in state.table_values.items()
|
|
320
|
+
},
|
|
321
|
+
"target_state": state.target_state,
|
|
322
|
+
"gaps": gaps_by_state.get(state.state_key, []),
|
|
323
|
+
"errors": validate_plan_fixtures(
|
|
324
|
+
catalog, state.table_values
|
|
325
|
+
),
|
|
326
|
+
"evidence": state.evidence.value,
|
|
327
|
+
}
|
|
328
|
+
)
|
|
329
|
+
summary = {
|
|
330
|
+
"states": len(catalog.states),
|
|
331
|
+
"paths": len(catalog.state_paths),
|
|
332
|
+
"shown": len(payload),
|
|
333
|
+
"rule_states": sum(
|
|
334
|
+
1
|
|
335
|
+
for state in catalog.states
|
|
336
|
+
if state.state_key.startswith("rule_")
|
|
337
|
+
),
|
|
338
|
+
"transition_states": sum(
|
|
339
|
+
1
|
|
340
|
+
for state in catalog.states
|
|
341
|
+
if state.state_key.startswith("transition_")
|
|
342
|
+
),
|
|
343
|
+
"seed_states": sum(
|
|
344
|
+
1
|
|
345
|
+
for state in catalog.states
|
|
346
|
+
if state.state_key.startswith("seed_")
|
|
347
|
+
),
|
|
348
|
+
}
|
|
349
|
+
except Exception as exc:
|
|
350
|
+
print(f"data states 失败: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
351
|
+
return 1
|
|
352
|
+
|
|
353
|
+
if args.json:
|
|
354
|
+
print(
|
|
355
|
+
json.dumps(
|
|
356
|
+
{
|
|
357
|
+
"ok": True,
|
|
358
|
+
"summary": summary,
|
|
359
|
+
"states": payload,
|
|
360
|
+
"paths": [
|
|
361
|
+
path.model_dump(mode="json")
|
|
362
|
+
for path in catalog.state_paths
|
|
363
|
+
],
|
|
364
|
+
},
|
|
365
|
+
ensure_ascii=False,
|
|
366
|
+
indent=2,
|
|
367
|
+
)
|
|
368
|
+
)
|
|
369
|
+
return 0
|
|
370
|
+
print(
|
|
371
|
+
f"states: {summary['states']} "
|
|
372
|
+
f"(rule={summary['rule_states']}, "
|
|
373
|
+
f"transition={summary['transition_states']}, "
|
|
374
|
+
f"seed={summary['seed_states']}); shown={summary['shown']}; "
|
|
375
|
+
f"paths={summary['paths']}"
|
|
376
|
+
)
|
|
377
|
+
for item in payload:
|
|
378
|
+
tables = ", ".join(
|
|
379
|
+
f"{table}:{rows}" for table, rows in item["tables"].items()
|
|
380
|
+
)
|
|
381
|
+
target = (
|
|
382
|
+
json.dumps(item["target_state"], ensure_ascii=False)
|
|
383
|
+
if item["target_state"]
|
|
384
|
+
else "-"
|
|
385
|
+
)
|
|
386
|
+
print(f"- {item['state_key']} tables={tables} target={target}")
|
|
387
|
+
for gap in item["gaps"]:
|
|
388
|
+
column = ".".join(
|
|
389
|
+
part
|
|
390
|
+
for part in (gap.get("table"), gap.get("column"))
|
|
391
|
+
if part
|
|
392
|
+
)
|
|
393
|
+
print(
|
|
394
|
+
f" gap {gap.get('kind')}: {column} — {gap.get('reason', '')}"
|
|
395
|
+
)
|
|
396
|
+
for error in item["errors"]:
|
|
397
|
+
print(f" invalid: {error}")
|
|
398
|
+
if catalog.state_paths:
|
|
399
|
+
print(f"paths: {len(catalog.state_paths)}")
|
|
400
|
+
for path in catalog.state_paths:
|
|
401
|
+
print(f"- {path.path_key} table={path.table} column={path.column}")
|
|
402
|
+
values = [str(path.steps[0].from_value)] + [
|
|
403
|
+
str(step.to_value) for step in path.steps
|
|
404
|
+
]
|
|
405
|
+
print(" " + " → ".join(values))
|
|
406
|
+
for step in path.steps:
|
|
407
|
+
print(
|
|
408
|
+
f" {step.from_value} → {step.to_value}"
|
|
409
|
+
f" ({step.rule_key}, {step.condition})"
|
|
410
|
+
)
|
|
411
|
+
return 0
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _data_plan(args) -> int:
|
|
415
|
+
project = Path(args.project).resolve()
|
|
416
|
+
try:
|
|
417
|
+
catalog = DataCatalog.model_validate(load_json(args.catalog))
|
|
418
|
+
errors = validate_catalog(catalog)
|
|
419
|
+
if errors:
|
|
420
|
+
print(json.dumps({"ok": False, "errors": errors}, ensure_ascii=False, indent=2))
|
|
421
|
+
return 1
|
|
422
|
+
case_base = _resolve_under_project(project, args.cases) or project / "caseset.json"
|
|
423
|
+
caseset = load_case_set(case_base)
|
|
424
|
+
if caseset is None:
|
|
425
|
+
print(f"用例库不存在: {case_base}", file=sys.stderr)
|
|
426
|
+
return 1
|
|
427
|
+
from ..cases.store import approved_cases
|
|
428
|
+
|
|
429
|
+
ruleset = _load_optional_ruleset(project, args.ruleset)
|
|
430
|
+
payloads: dict[str, Any] = {}
|
|
431
|
+
if args.fixtures:
|
|
432
|
+
raw = load_json(args.fixtures)
|
|
433
|
+
if isinstance(raw, dict) and "plans" in raw:
|
|
434
|
+
payloads = dict(raw.get("plans") or {})
|
|
435
|
+
elif isinstance(raw, dict):
|
|
436
|
+
payloads = dict(raw)
|
|
437
|
+
bundle = build_data_plan_bundle(
|
|
438
|
+
cases=approved_cases(caseset),
|
|
439
|
+
catalog=catalog,
|
|
440
|
+
ruleset=ruleset,
|
|
441
|
+
payloads=payloads,
|
|
442
|
+
run_scope=args.run_scope or "",
|
|
443
|
+
)
|
|
444
|
+
out = _data_path(project, args.out, "data_plan.json")
|
|
445
|
+
save_json_atomic(out, bundle.model_dump(mode="json"))
|
|
446
|
+
except Exception as exc:
|
|
447
|
+
print(f"data plan 失败: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
448
|
+
return 1
|
|
449
|
+
print(
|
|
450
|
+
json.dumps(
|
|
451
|
+
{
|
|
452
|
+
"ok": not bundle.rejected,
|
|
453
|
+
"plan": str(out),
|
|
454
|
+
"run_scope": bundle.run_scope,
|
|
455
|
+
"plans": len(bundle.plans),
|
|
456
|
+
"post_assertions": sum(
|
|
457
|
+
len(plan.post_assertions) for plan in bundle.plans
|
|
458
|
+
),
|
|
459
|
+
"rejected": [
|
|
460
|
+
item.model_dump(mode="json") for item in bundle.rejected
|
|
461
|
+
],
|
|
462
|
+
"warnings": bundle.warnings,
|
|
463
|
+
},
|
|
464
|
+
ensure_ascii=False,
|
|
465
|
+
indent=2,
|
|
466
|
+
)
|
|
467
|
+
)
|
|
468
|
+
return 1 if bundle.rejected else 0
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _data_apply(args) -> int:
|
|
472
|
+
try:
|
|
473
|
+
data = load_json(args.plan)
|
|
474
|
+
if isinstance(data, dict) and "plans" in data:
|
|
475
|
+
bundle = DataPlanBundle.model_validate(data)
|
|
476
|
+
else:
|
|
477
|
+
bundle = DataPlanBundle.model_validate(
|
|
478
|
+
{"schema_version": 1, "run_scope": "", "plans": [data]}
|
|
479
|
+
)
|
|
480
|
+
result = apply_bundle(
|
|
481
|
+
db_url=args.db_url,
|
|
482
|
+
bundle=bundle,
|
|
483
|
+
run_scope=args.run_scope,
|
|
484
|
+
keep=args.keep_data,
|
|
485
|
+
)
|
|
486
|
+
except Exception as exc:
|
|
487
|
+
print(f"data apply 失败: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
488
|
+
return 1
|
|
489
|
+
print(json.dumps(result.as_dict(), ensure_ascii=False, indent=2))
|
|
490
|
+
return 0
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""`astsight init`:生成默认模型配置。
|
|
2
|
+
|
|
3
|
+
产品默认路径是“装好即可配置模型”:不要求用户复制示例文件或理解所有字段。
|
|
4
|
+
配置文件只保存 provider/model/base_url 与 key 的环境变量名,不写入明文 key。
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Mapping
|
|
13
|
+
|
|
14
|
+
DEFAULT_PROVIDER = "anthropic"
|
|
15
|
+
DEFAULT_MODEL = "claude-sonnet-5-5"
|
|
16
|
+
DEFAULT_OPENAI_MODEL = "gpt-4.1"
|
|
17
|
+
DEFAULT_KEY_ENV = "ASTSIGHT_LLM_API_KEY"
|
|
18
|
+
DEFAULT_TIMEOUT = 120
|
|
19
|
+
DEFAULT_MAX_TOKENS = 16384
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def default_config_path(*, local: bool = False, home: Path | None = None) -> Path:
|
|
23
|
+
if local:
|
|
24
|
+
return Path.cwd() / "llm.json"
|
|
25
|
+
base = Path.home() if home is None else home
|
|
26
|
+
return base / ".astsight" / "llm.json"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def detect_defaults(env: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
30
|
+
"""从现有环境变量推断最省事的默认值。"""
|
|
31
|
+
values = os.environ if env is None else env
|
|
32
|
+
if values.get("ANTHROPIC_AUTH_TOKEN"):
|
|
33
|
+
return {
|
|
34
|
+
"provider": "anthropic",
|
|
35
|
+
"model": values.get("ANTHROPIC_MODEL") or DEFAULT_MODEL,
|
|
36
|
+
"base_url": values.get("ANTHROPIC_BASE_URL") or "",
|
|
37
|
+
"auth_style": "bearer",
|
|
38
|
+
"api_key_env": "ANTHROPIC_AUTH_TOKEN",
|
|
39
|
+
}
|
|
40
|
+
if values.get("ANTHROPIC_API_KEY"):
|
|
41
|
+
return {
|
|
42
|
+
"provider": "anthropic",
|
|
43
|
+
"model": values.get("ANTHROPIC_MODEL") or DEFAULT_MODEL,
|
|
44
|
+
"base_url": values.get("ANTHROPIC_BASE_URL") or "",
|
|
45
|
+
"auth_style": "x-api-key",
|
|
46
|
+
"api_key_env": "ANTHROPIC_API_KEY",
|
|
47
|
+
}
|
|
48
|
+
if values.get("OPENAI_API_KEY"):
|
|
49
|
+
return {
|
|
50
|
+
"provider": "openai",
|
|
51
|
+
"model": values.get("OPENAI_MODEL") or DEFAULT_OPENAI_MODEL,
|
|
52
|
+
"base_url": values.get("OPENAI_BASE_URL") or "",
|
|
53
|
+
"auth_style": "bearer",
|
|
54
|
+
"api_key_env": "OPENAI_API_KEY",
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
"provider": DEFAULT_PROVIDER,
|
|
58
|
+
"model": DEFAULT_MODEL,
|
|
59
|
+
"base_url": "",
|
|
60
|
+
"auth_style": "x-api-key",
|
|
61
|
+
"api_key_env": DEFAULT_KEY_ENV,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _ask(label: str, default: str) -> str:
|
|
66
|
+
prompt = f"{label} [{default}]: " if default else f"{label}: "
|
|
67
|
+
try:
|
|
68
|
+
answer = input(prompt).strip()
|
|
69
|
+
except EOFError:
|
|
70
|
+
return default
|
|
71
|
+
return answer or default
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def initialize(
|
|
75
|
+
*,
|
|
76
|
+
out: Path | None = None,
|
|
77
|
+
local: bool = False,
|
|
78
|
+
provider: str | None = None,
|
|
79
|
+
model: str | None = None,
|
|
80
|
+
base_url: str | None = None,
|
|
81
|
+
auth_style: str | None = None,
|
|
82
|
+
api_key_env: str | None = None,
|
|
83
|
+
force: bool = False,
|
|
84
|
+
interactive: bool = True,
|
|
85
|
+
env: Mapping[str, str] | None = None,
|
|
86
|
+
home: Path | None = None,
|
|
87
|
+
) -> dict[str, Any]:
|
|
88
|
+
values = os.environ if env is None else env
|
|
89
|
+
detected = detect_defaults(values)
|
|
90
|
+
provider = (provider or detected["provider"]).strip().lower()
|
|
91
|
+
model = (model or detected["model"]).strip()
|
|
92
|
+
base_url = (base_url if base_url is not None else detected["base_url"]).strip()
|
|
93
|
+
auth_style = (auth_style or detected["auth_style"]).strip().lower()
|
|
94
|
+
api_key_env = (api_key_env or detected["api_key_env"]).strip()
|
|
95
|
+
|
|
96
|
+
if interactive and sys.stdin.isatty() and not values.get("CI"):
|
|
97
|
+
provider = _ask("模型协议 provider (anthropic/openai)", provider).lower()
|
|
98
|
+
model = _ask("模型名称", model)
|
|
99
|
+
base_url = _ask("API 地址(可空,使用默认)", base_url)
|
|
100
|
+
api_key_env = _ask("API key 的环境变量名", api_key_env)
|
|
101
|
+
if provider == "anthropic":
|
|
102
|
+
auth_style = "bearer" if api_key_env == "ANTHROPIC_AUTH_TOKEN" else "x-api-key"
|
|
103
|
+
else:
|
|
104
|
+
auth_style = "bearer"
|
|
105
|
+
|
|
106
|
+
if provider not in {"anthropic", "openai"}:
|
|
107
|
+
raise ValueError(f"provider 必须是 anthropic 或 openai,实际为 {provider!r}")
|
|
108
|
+
if auth_style not in {"x-api-key", "bearer"}:
|
|
109
|
+
raise ValueError(f"auth_style 必须是 x-api-key 或 bearer,实际为 {auth_style!r}")
|
|
110
|
+
if not model:
|
|
111
|
+
raise ValueError("模型名称不能为空")
|
|
112
|
+
if not api_key_env:
|
|
113
|
+
raise ValueError("API key 环境变量名不能为空")
|
|
114
|
+
|
|
115
|
+
path = Path(out) if out else default_config_path(local=local, home=home)
|
|
116
|
+
if path.exists() and not force:
|
|
117
|
+
raise FileExistsError(
|
|
118
|
+
f"配置文件已存在: {path};如需覆盖请加 --force"
|
|
119
|
+
)
|
|
120
|
+
payload = {
|
|
121
|
+
"schema_version": 1,
|
|
122
|
+
"provider": provider,
|
|
123
|
+
"model": model,
|
|
124
|
+
"base_url": base_url,
|
|
125
|
+
"auth_style": auth_style,
|
|
126
|
+
"api_key": "",
|
|
127
|
+
"api_key_env": api_key_env,
|
|
128
|
+
"timeout": DEFAULT_TIMEOUT,
|
|
129
|
+
"max_tokens": DEFAULT_MAX_TOKENS,
|
|
130
|
+
"temperature": 0.0,
|
|
131
|
+
"max_retries": 1,
|
|
132
|
+
}
|
|
133
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
134
|
+
path.write_text(
|
|
135
|
+
json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
|
|
136
|
+
encoding="utf-8",
|
|
137
|
+
)
|
|
138
|
+
try:
|
|
139
|
+
path.chmod(0o600)
|
|
140
|
+
except OSError:
|
|
141
|
+
pass
|
|
142
|
+
key_present = bool(values.get(api_key_env))
|
|
143
|
+
return {
|
|
144
|
+
"path": str(path),
|
|
145
|
+
"provider": provider,
|
|
146
|
+
"model": model,
|
|
147
|
+
"base_url": base_url,
|
|
148
|
+
"auth_style": auth_style,
|
|
149
|
+
"api_key_env": api_key_env,
|
|
150
|
+
"key_present": key_present,
|
|
151
|
+
"next_steps": _next_steps(path, api_key_env, key_present),
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _next_steps(path: Path, api_key_env: str, key_present: bool) -> list[str]:
|
|
156
|
+
steps = []
|
|
157
|
+
if not key_present:
|
|
158
|
+
steps.append(f"export {api_key_env}=<你的 key>")
|
|
159
|
+
steps.append("astsight codegraph status # 确认变更追溯运行时可用")
|
|
160
|
+
steps.append(
|
|
161
|
+
"astsight agent run --project <项目> --requirements <需求文档>"
|
|
162
|
+
)
|
|
163
|
+
return steps
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
__all__ = [
|
|
167
|
+
"DEFAULT_KEY_ENV",
|
|
168
|
+
"DEFAULT_MODEL",
|
|
169
|
+
"default_config_path",
|
|
170
|
+
"detect_defaults",
|
|
171
|
+
"initialize",
|
|
172
|
+
]
|