argo-search 2.14.1 → 2.16.0
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.
- package/AGENTS.md +8 -6
- package/README.es.md +57 -813
- package/README.ja.md +56 -814
- package/README.ko.md +56 -812
- package/README.md +160 -754
- package/README.zh.md +152 -872
- package/SKILL.md +22 -23
- package/assets/readme/counts.json +1 -1
- package/assets/readme/hero.svg +23 -23
- package/backends/concept_vectors.bin +0 -0
- package/backends/domain_profiles.json +149 -6
- package/backends/engine_concept_vectors.json +1525 -1525
- package/backends/engine_registry.yaml +139 -30
- package/backends/quota_profiles.json +83 -3
- package/bin/argo +33 -17
- package/config.yaml +189 -33
- package/docs/ADDING_NEW_ENGINE.md +10 -0
- package/docs/ARGO_INTRO.md +1 -1
- package/docs/CHANGELOG.md +38 -0
- package/docs/ENGINE_CATALOG.md +102 -89
- package/docs/MCP_SETUP.md +10 -1
- package/docs/RELEASE_NOTES_v2.14.1.md +4 -4
- package/docs/RELEASE_NOTES_v2.15.0.md +50 -0
- package/docs/RELEASE_NOTES_v2.16.0.md +58 -0
- package/docs/RELEASING.md +1 -1
- package/engines/specs/ai_labs.yaml +89 -0
- package/engines/specs/archive_org.yaml +1 -1
- package/engines/specs/bilibili_hot.yaml +11 -1
- package/engines/specs/brave.yaml +3 -3
- package/engines/specs/carbon_intensity.yaml +1 -1
- package/engines/specs/cisa_alerts.yaml +40 -0
- package/engines/specs/cn_ai_news.yaml +10 -8
- package/engines/specs/crates.yaml +1 -1
- package/engines/specs/crossref.yaml +4 -2
- package/engines/specs/crt_sh.yaml +1 -1
- package/engines/specs/dblp.yaml +1 -1
- package/engines/specs/devto.yaml +1 -1
- package/engines/specs/digup.yaml +11 -6
- package/engines/specs/docker_hub.yaml +1 -1
- package/engines/specs/douyin_hot.yaml +11 -1
- package/engines/specs/dw_news.yaml +4 -2
- package/engines/specs/eng_blogs.yaml +63 -0
- package/engines/specs/europeana.yaml +3 -4
- package/engines/specs/europepmc.yaml +1 -1
- package/engines/specs/felo.yaml +3 -3
- package/engines/specs/firecrawl.yaml +3 -0
- package/engines/specs/fourget.yaml +5 -2
- package/engines/specs/france24.yaml +6 -4
- package/engines/specs/fxtwitter.yaml +30 -7
- package/engines/specs/gbfs_nyc.yaml +1 -1
- package/engines/specs/gleif.yaml +1 -1
- package/engines/specs/gov_regulations.yaml +1 -1
- package/engines/specs/grepapp_mcp.yaml +62 -0
- package/engines/specs/guardian_rss.yaml +6 -4
- package/engines/specs/hf_datasets.yaml +1 -1
- package/engines/specs/huggingface.yaml +1 -1
- package/engines/specs/itotii.yaml +13 -1
- package/engines/specs/keenable.yaml +7 -1
- package/engines/specs/linux_do.yaml +63 -0
- package/engines/specs/lobsters.yaml +41 -0
- package/engines/specs/local_crossref.yaml +3 -1
- package/engines/specs/local_github.yaml +1 -1
- package/engines/specs/local_npm.yaml +6 -0
- package/engines/specs/local_openstreetmap.yaml +1 -1
- package/engines/specs/local_seek.yaml +6 -0
- package/engines/specs/maven.yaml +1 -1
- package/engines/specs/mdn.yaml +1 -1
- package/engines/specs/musicbrainz.yaml +1 -1
- package/engines/specs/nasa_images.yaml +1 -1
- package/engines/specs/nhtsa_vpic.yaml +6 -3
- package/engines/specs/npm.yaml +1 -1
- package/engines/specs/nuget.yaml +1 -1
- package/engines/specs/nvd.yaml +1 -1
- package/engines/specs/open_meteo.yaml +1 -1
- package/engines/specs/openalex.yaml +4 -2
- package/engines/specs/openreview.yaml +1 -1
- package/engines/specs/polymarket.yaml +1 -1
- package/engines/specs/redskill.yaml +2 -0
- package/engines/specs/searxng.yaml +4 -2
- package/engines/specs/sec_edgar.yaml +9 -4
- package/engines/specs/steam.yaml +1 -1
- package/engines/specs/tinyfish.yaml +2 -0
- package/engines/specs/tinyfish_news.yaml +2 -0
- package/engines/specs/tinyfish_paper.yaml +2 -0
- package/engines/specs/toutiao_hot.yaml +11 -1
- package/engines/specs/train.yaml +3 -0
- package/engines/specs/twitter.yaml +4 -0
- package/engines/specs/unpaywall.yaml +6 -0
- package/engines/specs/vam.yaml +17 -3
- package/engines/specs/weibo_hot.yaml +11 -1
- package/engines/specs/wikidata.yaml +1 -1
- package/engines/specs/wikipedia.yaml +1 -1
- package/engines/specs/wolframalpha.yaml +3 -3
- package/engines/specs/xiaohongshu.yaml +2 -0
- package/engines/specs/zhihu.yaml +3 -18
- package/engines/specs/zhihu_hot_app.yaml +1 -1
- package/engines/specs/zhihu_kb.yaml +18 -0
- package/engines/specs/zhihu_questions.yaml +19 -0
- package/package.json +4 -2
- package/packages/dsh-plugin/README.md +9 -14
- package/packages/dsh-plugin/dsh/client.js +481 -1037
- package/packages/dsh-plugin/dsh/diagnostics.js +71 -20
- package/packages/dsh-plugin/dsh/index.js +6 -0
- package/packages/dsh-plugin/dsh/runner.js +3 -1
- package/packages/dsh-plugin/dsh/workbench-client.js +796 -0
- package/packages/dsh-plugin/dsh/workbench-md.js +386 -0
- package/packages/dsh-plugin/dsh/workbench-suggestions.js +148 -0
- package/packages/dsh-plugin/dsh/workbench.js +966 -0
- package/packages/dsh-plugin/icon.svg +23 -0
- package/packages/dsh-plugin/package.json +10 -3
- package/packages/dsh-plugin/scripts/sync-local.mjs +87 -0
- package/packages/dsh-plugin/scripts/sync-local.sh +13 -1
- package/packages/dsh-plugin/test/diagnostics.test.js +38 -1
- package/packages/dsh-plugin/test/size-gate.test.js +2 -9
- package/packages/dsh-plugin/test/workbench.test.js +92 -0
- package/scripts/adaptive.py +7 -1
- package/scripts/archive_run.py +112 -53
- package/scripts/argo_paths.py +42 -5
- package/scripts/badcase_ledger.py +117 -9
- package/scripts/build_concept_table.py +112 -55
- package/scripts/cache.py +6 -2
- package/scripts/caliber_isolation.py +60 -23
- package/scripts/circuit_breaker.py +72 -11
- package/scripts/cli_io.py +20 -2
- package/scripts/config_cache.py +44 -1
- package/scripts/daemon.py +151 -51
- package/scripts/dormant_ledger.py +23 -9
- package/scripts/engine_dispatch.py +8 -5
- package/scripts/engine_env.py +191 -1
- package/scripts/engine_families.py +50 -7
- package/scripts/engine_states.py +3 -50
- package/scripts/engine_validate.py +13 -45
- package/scripts/engines.py +15 -31
- package/scripts/engines_base.py +66 -61
- package/scripts/engines_builders.py +0 -15
- package/scripts/engines_builders_archive.py +4 -3
- package/scripts/engines_builders_batch10.py +346 -100
- package/scripts/engines_builders_batch11.py +4 -76
- package/scripts/engines_builders_batch13.py +4 -3
- package/scripts/engines_builders_batch14.py +2 -1
- package/scripts/engines_builders_batch15.py +2 -1
- package/scripts/engines_builders_batch9.py +16 -25
- package/scripts/engines_builders_cn.py +7 -201
- package/scripts/engines_builders_data.py +12 -11
- package/scripts/engines_builders_data_macro.py +5 -4
- package/scripts/engines_builders_dsh.py +2 -1
- package/scripts/engines_builders_feeds.py +76 -11
- package/scripts/engines_builders_finance.py +2 -1
- package/scripts/engines_builders_intl.py +18 -117
- package/scripts/engines_builders_media.py +59 -12
- package/scripts/engines_builders_pixiv.py +2 -16
- package/scripts/engines_builders_science.py +8 -7
- package/scripts/engines_builders_search.py +7 -14
- package/scripts/engines_builders_skill.py +2 -1
- package/scripts/engines_builders_tech.py +8 -17
- package/scripts/engines_builders_weather.py +241 -0
- package/scripts/engines_fields.py +91 -0
- package/scripts/engines_http.py +184 -0
- package/scripts/engines_mcp.py +405 -0
- package/scripts/engines_parsers.py +13 -369
- package/scripts/engines_schema_drift.py +260 -0
- package/scripts/evidence.py +13 -0
- package/scripts/evidence_loop.py +19 -4
- package/scripts/extend_route_labels.py +6 -0
- package/scripts/fetch_jina.py +98 -0
- package/scripts/fetch_jsrun.py +15 -11
- package/scripts/fetch_v3.py +79 -120
- package/scripts/fulltext_store.py +42 -1
- package/scripts/fxtwitter_api.py +8 -7
- package/scripts/gen_engine_catalog.py +2 -2
- package/scripts/general_pool.py +15 -4
- package/scripts/health_check.py +1 -1
- package/scripts/image_vision/vision_probe +0 -0
- package/scripts/install.sh +2 -0
- package/scripts/link_source.py +65 -24
- package/scripts/local_seek_adapter.py +57 -17
- package/scripts/matrix_search_eval.py +8 -10
- package/scripts/mcp_handlers.py +53 -31
- package/scripts/mcp_handlers_surface.py +6 -18
- package/scripts/mcp_transport.py +10 -5
- package/scripts/min_version_scan.py +7 -3
- package/scripts/network_aware.py +7 -13
- package/scripts/numeric_verify.py +3 -2
- package/scripts/output_transparency.py +3 -0
- package/scripts/pre-commit +45 -43
- package/scripts/query_understanding.py +30 -6
- package/scripts/quota.py +36 -30
- package/scripts/rank_signals.py +9 -0
- package/scripts/recompute.py +15 -5
- package/scripts/recovery.py +38 -29
- package/scripts/recovery_runner.py +29 -10
- package/scripts/redskill/redskill_engine.py +2 -1
- package/scripts/release.py +14 -26
- package/scripts/release_check.py +5 -25
- package/scripts/replay_eval.py +2 -2
- package/scripts/research_cli.py +40 -0
- package/scripts/research_notes.py +368 -0
- package/scripts/route.py +40 -70
- package/scripts/route_audit.py +259 -0
- package/scripts/route_combo.py +21 -6
- package/scripts/route_domains.py +150 -23
- package/scripts/route_lang.py +20 -7
- package/scripts/route_log.py +26 -9
- package/scripts/route_policy.py +85 -6
- package/scripts/route_telemetry_export.py +199 -0
- package/scripts/rrf_classic.py +5 -22
- package/scripts/search.py +2 -1
- package/scripts/search_attribution.py +53 -10
- package/scripts/search_entry.py +32 -1
- package/scripts/search_output.py +23 -11
- package/scripts/search_pipeline.py +15 -3
- package/scripts/search_rank.py +21 -11
- package/scripts/semantic_evidence.py +394 -178
- package/scripts/serp_guard.py +13 -1
- package/scripts/settings_page.py +4 -3
- package/scripts/single_flight.py +1 -1
- package/scripts/social_engines/hackernews_engine.py +2 -1
- package/scripts/social_engines/reddit_engine.py +2 -1
- package/scripts/social_engines/xiaohongshu_engine.py +2 -1
- package/scripts/social_engines/zhihu_engine.py +252 -43
- package/scripts/sogou_weixin_browser.py +5 -6
- package/scripts/source_audit.py +44 -9
- package/scripts/source_ledger.py +2 -15
- package/scripts/source_selection.py +45 -20
- package/scripts/straggler_policy.py +1 -2
- package/scripts/sync_backends.py +17 -0
- package/scripts/tfidf_router.py +23 -11
- package/scripts/time_utils.py +54 -1
- package/scripts/train.py +68 -2
- package/scripts/usage_log.py +50 -10
- package/scripts/watch.py +3 -3
- package/scripts/zhihu_quota.py +2 -1
- package/sub-skills/argo-wide-research/SKILL.md +70 -0
- package/sub-skills/ego-search/{SKILL.md → README.md} +15 -47
- package/sub-skills/ego-search/scripts/ego_search.py +13 -4
- package/sub-skills/js-run/{SKILL.md → README.md} +3 -20
- package/sub-skills/local-search/{SKILL.md → README.md} +3 -8
- package/sub-skills/local-search/engine_registry.py +32 -7
- package/sub-skills/local-seek/SKILL.md +20 -22
- package/sub-skills/local-seek/scripts/seek_fts.py +58 -3
- package/scripts/caliber_dedupe.py +0 -66
- package/scripts/engines_builders_batch16.py +0 -13
- package/scripts/health_probe.py +0 -253
- package/scripts/social_engines/twitter_engine.py +0 -514
- package/scripts/sync_installs.py +0 -29
|
@@ -42,6 +42,15 @@ import re
|
|
|
42
42
|
from pathlib import Path
|
|
43
43
|
from typing import Any, Callable
|
|
44
44
|
|
|
45
|
+
# 字段取值与模板渲染下沉到 engines_fields(无反向依赖),供本模块与
|
|
46
|
+
# engines_schema_drift 共用,消除 parsers ↔ drift 的循环导入。
|
|
47
|
+
from engines_fields import (
|
|
48
|
+
_coerce_field,
|
|
49
|
+
_dig,
|
|
50
|
+
_format_url_template,
|
|
51
|
+
extract_items,
|
|
52
|
+
)
|
|
53
|
+
|
|
45
54
|
# 解析器签名:(原始数据, spec) -> 标准结果行列表
|
|
46
55
|
Parser = Callable[[Any, dict], list[dict]]
|
|
47
56
|
|
|
@@ -110,40 +119,6 @@ def resolve(spec: dict) -> list[Parser]:
|
|
|
110
119
|
# 这类信息会静默丢失。把「拼接」变成声明式能力,属于解析层职责,故与
|
|
111
120
|
# `parse_*` 解析器同文件维护;engines_base 只做委托调用。
|
|
112
121
|
|
|
113
|
-
def _dig(obj: Any, path: str) -> Any:
|
|
114
|
-
"""按点分路径取嵌套值;路径段为数字时按数组索引。"""
|
|
115
|
-
if not path:
|
|
116
|
-
return obj
|
|
117
|
-
cur = obj
|
|
118
|
-
for seg in path.split("."):
|
|
119
|
-
if isinstance(cur, list):
|
|
120
|
-
try:
|
|
121
|
-
cur = cur[int(seg)]
|
|
122
|
-
except (ValueError, IndexError):
|
|
123
|
-
return None
|
|
124
|
-
elif isinstance(cur, dict):
|
|
125
|
-
cur = cur.get(seg)
|
|
126
|
-
else:
|
|
127
|
-
return None
|
|
128
|
-
return cur
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
def _coerce_field(val: Any, *, max_len: int | None = None) -> str:
|
|
132
|
-
"""把 API 字段压成字符串:list 取首项、dict 丢弃、其余 str。"""
|
|
133
|
-
if val is None:
|
|
134
|
-
return ""
|
|
135
|
-
if isinstance(val, list):
|
|
136
|
-
if not val:
|
|
137
|
-
return ""
|
|
138
|
-
val = val[0]
|
|
139
|
-
if isinstance(val, dict):
|
|
140
|
-
return ""
|
|
141
|
-
s = str(val).strip()
|
|
142
|
-
if max_len is not None and len(s) > max_len:
|
|
143
|
-
return s[:max_len]
|
|
144
|
-
return s
|
|
145
|
-
|
|
146
|
-
|
|
147
122
|
def _render_field_template(template: str, item: dict) -> str:
|
|
148
123
|
"""模板插值:`{field}` 取条目字段(支持点分路径),空值置空并折叠分隔符。
|
|
149
124
|
|
|
@@ -162,33 +137,6 @@ def _render_field_template(template: str, item: dict) -> str:
|
|
|
162
137
|
return out.strip()
|
|
163
138
|
|
|
164
139
|
|
|
165
|
-
def _format_url_template(template: str, item: dict) -> str:
|
|
166
|
-
"""支持 {field} 与 {a.b.c} 点分路径的 URL 模板;任一占位为空则返回空串。"""
|
|
167
|
-
vals = {m.group(1): _coerce_field(_dig(item, m.group(1)))
|
|
168
|
-
for m in re.finditer(r"\{([^}]+)\}", template)}
|
|
169
|
-
if any(not v for v in vals.values()):
|
|
170
|
-
return ""
|
|
171
|
-
try:
|
|
172
|
-
return re.sub(r"\{([^}]+)\}", lambda m: vals[m.group(1)], template)
|
|
173
|
-
except Exception:
|
|
174
|
-
return ""
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
def extract_items(data: Any, path: str) -> list:
|
|
178
|
-
"""从 JSON 按路径提取列表。path 为 . / $ / [] / 空 且 data 为 list 时直接返回。"""
|
|
179
|
-
if path in ("", ".", "$", "[]"):
|
|
180
|
-
return data if isinstance(data, list) else []
|
|
181
|
-
if not isinstance(data, dict):
|
|
182
|
-
return []
|
|
183
|
-
obj = _dig(data, path)
|
|
184
|
-
if isinstance(obj, list):
|
|
185
|
-
return obj
|
|
186
|
-
# DBLP 等 API 在 h=1 时把 hit 收成对象而非数组
|
|
187
|
-
if isinstance(obj, dict):
|
|
188
|
-
return [obj]
|
|
189
|
-
return []
|
|
190
|
-
|
|
191
|
-
|
|
192
140
|
def make_field_parser(path: str, fields: dict[str, str], url_template: str | None = None,
|
|
193
141
|
max_items: int = 10, templates: dict[str, str] | None = None,
|
|
194
142
|
url_item_template: str | None = None) -> Callable:
|
|
@@ -234,8 +182,10 @@ def make_field_parser(path: str, fields: dict[str, str], url_template: str | Non
|
|
|
234
182
|
if not tmpl:
|
|
235
183
|
continue
|
|
236
184
|
std = {"item_title_template": "title",
|
|
237
|
-
"item_summary_template": "snippet"
|
|
238
|
-
|
|
185
|
+
"item_summary_template": "snippet",
|
|
186
|
+
"item_image_template": "image_url"}.get(ok, ok)
|
|
187
|
+
rendered = (_format_url_template(tmpl, item) if std == "image_url"
|
|
188
|
+
else _render_field_template(tmpl, item))
|
|
239
189
|
if rendered:
|
|
240
190
|
r[std] = rendered[:300 if std == "snippet" else 500]
|
|
241
191
|
if url_template and (not r.get("url") or not str(r["url"]).startswith(("http://", "https://"))):
|
|
@@ -327,24 +277,6 @@ def _strip_tags(text: str) -> str:
|
|
|
327
277
|
return _TAG_RE.sub("", text)
|
|
328
278
|
|
|
329
279
|
|
|
330
|
-
def _dig(obj: Any, path: str) -> Any:
|
|
331
|
-
"""按点分路径取嵌套值;路径段为数字时按数组索引。"""
|
|
332
|
-
if not path:
|
|
333
|
-
return obj
|
|
334
|
-
cur = obj
|
|
335
|
-
for seg in path.split("."):
|
|
336
|
-
if isinstance(cur, list):
|
|
337
|
-
try:
|
|
338
|
-
cur = cur[int(seg)]
|
|
339
|
-
except (ValueError, IndexError):
|
|
340
|
-
return None
|
|
341
|
-
elif isinstance(cur, dict):
|
|
342
|
-
cur = cur.get(seg)
|
|
343
|
-
else:
|
|
344
|
-
return None
|
|
345
|
-
return cur
|
|
346
|
-
|
|
347
|
-
|
|
348
280
|
def _flatten_segments(val: Any) -> str:
|
|
349
281
|
"""把 [{value, is_bold}, ...] 数组展平成纯文本。
|
|
350
282
|
|
|
@@ -634,291 +566,3 @@ def _migrate_builtin() -> None:
|
|
|
634
566
|
|
|
635
567
|
|
|
636
568
|
_migrate_builtin()
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
# ─────────────────────────────────────────────────────────────────────────────
|
|
640
|
-
# 声明式架构自省与结构漂移诊断(第一性原理 + MECE 原则)
|
|
641
|
-
# ─────────────────────────────────────────────────────────────────────────────
|
|
642
|
-
|
|
643
|
-
_TITLE_SYNONYMS = (
|
|
644
|
-
"title", "name", "headline", "subject", "text", "label",
|
|
645
|
-
"caption", "item_title", "artwork_title", "track_name", "display_name",
|
|
646
|
-
)
|
|
647
|
-
_URL_SYNONYMS = (
|
|
648
|
-
"url", "link", "web_url", "html_url", "href", "uri",
|
|
649
|
-
"source_url", "landing_page", "target_url", "permalink", "page_url", "site_url",
|
|
650
|
-
)
|
|
651
|
-
_SUMMARY_SYNONYMS = (
|
|
652
|
-
"snippet", "summary", "description", "abstract", "body",
|
|
653
|
-
"content", "desc", "overview", "intro", "tombstone", "details", "comment",
|
|
654
|
-
)
|
|
655
|
-
_PUB_SYNONYMS = (
|
|
656
|
-
"published_at", "created_at", "pubdate", "pub_date", "date",
|
|
657
|
-
"time", "timestamp", "premiered", "first_air_date", "release_date",
|
|
658
|
-
)
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
def _flatten_item(item: Any, prefix: str = "", depth: int = 0, max_depth: int = 3) -> dict[str, Any]:
|
|
662
|
-
"""将嵌套字典/列表展平为点分路径键值字典(深度受控,列表展开前 2 条)。"""
|
|
663
|
-
flat: dict[str, Any] = {}
|
|
664
|
-
if depth > max_depth or not isinstance(item, (dict, list)):
|
|
665
|
-
return flat
|
|
666
|
-
if isinstance(item, dict):
|
|
667
|
-
for k, v in item.items():
|
|
668
|
-
path = f"{prefix}.{k}" if prefix else str(k)
|
|
669
|
-
if isinstance(v, (dict, list)) and depth < max_depth:
|
|
670
|
-
flat.update(_flatten_item(v, path, depth + 1, max_depth))
|
|
671
|
-
else:
|
|
672
|
-
flat[path] = v
|
|
673
|
-
elif isinstance(item, list):
|
|
674
|
-
for i, v in enumerate(item[:2]):
|
|
675
|
-
path = f"{prefix}.{i}" if prefix else str(i)
|
|
676
|
-
if isinstance(v, (dict, list)) and depth < max_depth:
|
|
677
|
-
flat.update(_flatten_item(v, path, depth + 1, max_depth))
|
|
678
|
-
else:
|
|
679
|
-
flat[path] = v
|
|
680
|
-
return flat
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
def _find_candidate_containers(data: Any, prefix: str = "", depth: int = 0, max_depth: int = 4) -> list[tuple[str, list, float]]:
|
|
684
|
-
"""递归搜索全部字典列表,并按结构质量评分。"""
|
|
685
|
-
candidates: list[tuple[str, list, float]] = []
|
|
686
|
-
if depth > max_depth:
|
|
687
|
-
return candidates
|
|
688
|
-
if isinstance(data, list):
|
|
689
|
-
if data and isinstance(data[0], dict):
|
|
690
|
-
sample = data[0]
|
|
691
|
-
score = 0.5 + min(0.3, len(data) * 0.02)
|
|
692
|
-
keys = {str(k).lower() for k in sample.keys()}
|
|
693
|
-
if any(k in keys for k in ("title", "name", "id", "url", "link")):
|
|
694
|
-
score += 0.2
|
|
695
|
-
candidates.append((prefix or ".", data, score))
|
|
696
|
-
return candidates
|
|
697
|
-
if isinstance(data, dict):
|
|
698
|
-
for k, v in data.items():
|
|
699
|
-
path = f"{prefix}.{k}" if prefix else str(k)
|
|
700
|
-
if isinstance(v, list) and v and isinstance(v[0], dict):
|
|
701
|
-
sample = v[0]
|
|
702
|
-
score = 0.5 + min(0.3, len(v) * 0.02)
|
|
703
|
-
keys = {str(k).lower() for k in sample.keys()}
|
|
704
|
-
if any(syn in keys for syn in ("title", "name", "id", "url", "link")):
|
|
705
|
-
score += 0.2
|
|
706
|
-
candidates.append((path, v, score))
|
|
707
|
-
elif isinstance(v, dict) and depth < max_depth:
|
|
708
|
-
candidates.extend(_find_candidate_containers(v, path, depth + 1, max_depth))
|
|
709
|
-
candidates.sort(key=lambda x: x[2], reverse=True)
|
|
710
|
-
return candidates
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
def _match_best_field(target_kind: str, flat: dict[str, Any]) -> tuple[str | None, Any, float]:
|
|
714
|
-
"""根据目标类型和扁平键树,启发式匹配最优路径。"""
|
|
715
|
-
if target_kind == "title":
|
|
716
|
-
for path, val in flat.items():
|
|
717
|
-
if not isinstance(val, (str, int)) or not str(val).strip():
|
|
718
|
-
continue
|
|
719
|
-
seg = path.split(".")[-1].lower()
|
|
720
|
-
if seg in ("title", "name", "headline", "artwork_title"):
|
|
721
|
-
return path, val, 0.95
|
|
722
|
-
if seg in _TITLE_SYNONYMS:
|
|
723
|
-
return path, val, 0.85
|
|
724
|
-
elif target_kind == "url":
|
|
725
|
-
url_candidates: list[tuple[str, Any, float]] = []
|
|
726
|
-
for path, val in flat.items():
|
|
727
|
-
s = str(val or "").strip()
|
|
728
|
-
if not (s.startswith("http://") or s.startswith("https://") or s.startswith("/")):
|
|
729
|
-
continue
|
|
730
|
-
seg = path.split(".")[-1].lower()
|
|
731
|
-
score = 0.6
|
|
732
|
-
if seg in _URL_SYNONYMS:
|
|
733
|
-
score += 0.3
|
|
734
|
-
if any(s.lower().endswith(ext) for ext in (".jpg", ".jpeg", ".png", ".gif", ".webp")):
|
|
735
|
-
score -= 0.4
|
|
736
|
-
url_candidates.append((path, val, score))
|
|
737
|
-
if url_candidates:
|
|
738
|
-
url_candidates.sort(key=lambda x: x[2], reverse=True)
|
|
739
|
-
best = url_candidates[0]
|
|
740
|
-
if best[2] >= 0.5:
|
|
741
|
-
return best[0], best[1], best[2]
|
|
742
|
-
for path, val in flat.items():
|
|
743
|
-
seg = path.split(".")[-1].lower()
|
|
744
|
-
if seg in _URL_SYNONYMS and val:
|
|
745
|
-
return path, val, 0.75
|
|
746
|
-
elif target_kind == "summary":
|
|
747
|
-
for path, val in flat.items():
|
|
748
|
-
s = str(val or "").strip()
|
|
749
|
-
if not s or len(s) < 5:
|
|
750
|
-
continue
|
|
751
|
-
seg = path.split(".")[-1].lower()
|
|
752
|
-
if seg in ("snippet", "summary", "description", "abstract"):
|
|
753
|
-
return path, val, 0.90
|
|
754
|
-
if seg in _SUMMARY_SYNONYMS:
|
|
755
|
-
return path, val, 0.80
|
|
756
|
-
return None, None, 0.0
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
def diagnose_schema_drift(raw_data: Any, spec_or_output_map: dict[str, Any]) -> dict[str, Any]:
|
|
760
|
-
"""上游数据源结构漂移自省对拍诊断(第一性原理 + MECE 原则)。
|
|
761
|
-
|
|
762
|
-
层级覆盖:
|
|
763
|
-
1. Envelope: 业务错误封套、非结构化数据判定
|
|
764
|
-
2. Container: items 容器路径位移对拍与自动推荐
|
|
765
|
-
3. Field: item_title / item_url / item_summary 字段更名、层级下沉同义与特征对拍
|
|
766
|
-
"""
|
|
767
|
-
omap = spec_or_output_map.get("output_map") if isinstance(spec_or_output_map.get("output_map"), dict) else spec_or_output_map
|
|
768
|
-
if not isinstance(omap, dict):
|
|
769
|
-
omap = {}
|
|
770
|
-
|
|
771
|
-
current_items_path = omap.get("items", "")
|
|
772
|
-
current_title = omap.get("item_title", "title")
|
|
773
|
-
current_url = omap.get("item_url", "url")
|
|
774
|
-
current_summary = omap.get("item_summary", "snippet")
|
|
775
|
-
|
|
776
|
-
issues: list[str] = []
|
|
777
|
-
container_drift: dict[str, Any] | None = None
|
|
778
|
-
field_drifts: dict[str, Any] = {}
|
|
779
|
-
suggested_patch: dict[str, str] = {}
|
|
780
|
-
|
|
781
|
-
# 1. Envelope 层
|
|
782
|
-
if not isinstance(raw_data, (dict, list)):
|
|
783
|
-
return {
|
|
784
|
-
"ok": False,
|
|
785
|
-
"drift_detected": False,
|
|
786
|
-
"stage": "envelope",
|
|
787
|
-
"issues": [f"响应非 JSON 结构 (类型: {type(raw_data).__name__})"],
|
|
788
|
-
"confidence": 0.0,
|
|
789
|
-
"suggested_patch": {},
|
|
790
|
-
}
|
|
791
|
-
if isinstance(raw_data, dict):
|
|
792
|
-
err_val = raw_data.get("error") or raw_data.get("err_msg") or raw_data.get("message")
|
|
793
|
-
if err_val and not raw_data.get("data") and not raw_data.get("results") and not raw_data.get("items"):
|
|
794
|
-
return {
|
|
795
|
-
"ok": False,
|
|
796
|
-
"drift_detected": False,
|
|
797
|
-
"stage": "envelope",
|
|
798
|
-
"issues": [f"上游返回业务错误封套: {err_val}"],
|
|
799
|
-
"confidence": 0.0,
|
|
800
|
-
"suggested_patch": {},
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
# 2. Container 层
|
|
804
|
-
items = extract_items(raw_data, current_items_path)
|
|
805
|
-
if not items or not isinstance(items[0], dict):
|
|
806
|
-
candidates = _find_candidate_containers(raw_data)
|
|
807
|
-
if candidates:
|
|
808
|
-
best_path, best_items, score = candidates[0]
|
|
809
|
-
container_drift = {
|
|
810
|
-
"from": current_items_path,
|
|
811
|
-
"to": best_path,
|
|
812
|
-
"count": len(best_items),
|
|
813
|
-
"score": score,
|
|
814
|
-
}
|
|
815
|
-
issues.append(f"容器路径失效: '{current_items_path}' 未提取到条目,候选路径 '{best_path}' (包含 {len(best_items)} 条)")
|
|
816
|
-
suggested_patch["items"] = best_path
|
|
817
|
-
items = best_items
|
|
818
|
-
else:
|
|
819
|
-
return {
|
|
820
|
-
"ok": False,
|
|
821
|
-
"drift_detected": False,
|
|
822
|
-
"stage": "container",
|
|
823
|
-
"issues": [f"未在响应中发现任何字典列表容器 (当前 items='{current_items_path}')"],
|
|
824
|
-
"confidence": 0.0,
|
|
825
|
-
"suggested_patch": {},
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
# 3. Field 层
|
|
829
|
-
sample = items[0]
|
|
830
|
-
flat = _flatten_item(sample, max_depth=3)
|
|
831
|
-
|
|
832
|
-
# 校验与对拍 title
|
|
833
|
-
val_title = _dig(sample, current_title) if current_title else None
|
|
834
|
-
if not val_title:
|
|
835
|
-
cand_p, cand_v, cand_s = _match_best_field("title", flat)
|
|
836
|
-
if cand_p and cand_p != current_title:
|
|
837
|
-
field_drifts["item_title"] = {"from": current_title, "to": cand_p, "sample": str(cand_v)[:50], "score": cand_s}
|
|
838
|
-
issues.append(f"标题字段失效: '{current_title}' 为空 -> 候选 '{cand_p}' (值: {cand_v!r})")
|
|
839
|
-
suggested_patch["item_title"] = cand_p
|
|
840
|
-
|
|
841
|
-
# 校验与对拍 url
|
|
842
|
-
val_url = _dig(sample, current_url) if current_url else None
|
|
843
|
-
if not val_url:
|
|
844
|
-
cand_p, cand_v, cand_s = _match_best_field("url", flat)
|
|
845
|
-
if cand_p and cand_p != current_url:
|
|
846
|
-
field_drifts["item_url"] = {"from": current_url, "to": cand_p, "sample": str(cand_v)[:50], "score": cand_s}
|
|
847
|
-
issues.append(f"链接字段失效: '{current_url}' 为空 -> 候选 '{cand_p}' (值: {cand_v!r})")
|
|
848
|
-
suggested_patch["item_url"] = cand_p
|
|
849
|
-
|
|
850
|
-
# 校验与对拍 summary
|
|
851
|
-
if current_summary:
|
|
852
|
-
val_sum = _dig(sample, current_summary)
|
|
853
|
-
if not val_sum:
|
|
854
|
-
cand_p, cand_v, cand_s = _match_best_field("summary", flat)
|
|
855
|
-
if cand_p and cand_p != current_summary:
|
|
856
|
-
field_drifts["item_summary"] = {"from": current_summary, "to": cand_p, "sample": str(cand_v)[:50], "score": cand_s}
|
|
857
|
-
issues.append(f"摘要字段失效: '{current_summary}' 为空 -> 候选 '{cand_p}'")
|
|
858
|
-
suggested_patch["item_summary"] = cand_p
|
|
859
|
-
|
|
860
|
-
drift_detected = bool(container_drift or field_drifts)
|
|
861
|
-
stage = "field" if field_drifts else ("container" if container_drift else "ok")
|
|
862
|
-
confidence = 0.0
|
|
863
|
-
if drift_detected:
|
|
864
|
-
confidence = 0.95 if (suggested_patch.get("items") or ("item_title" in suggested_patch and "item_url" in suggested_patch)) else 0.80
|
|
865
|
-
|
|
866
|
-
return {
|
|
867
|
-
"ok": not drift_detected,
|
|
868
|
-
"drift_detected": drift_detected,
|
|
869
|
-
"stage": stage,
|
|
870
|
-
"issues": issues,
|
|
871
|
-
"container_drift": container_drift,
|
|
872
|
-
"field_drifts": field_drifts,
|
|
873
|
-
"suggested_patch": suggested_patch,
|
|
874
|
-
"confidence": confidence,
|
|
875
|
-
}
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
def render_drift_report(diagnosis: dict[str, Any], engine_id: str = "") -> str:
|
|
879
|
-
"""渲染终端格式化的结构漂移诊断报告。"""
|
|
880
|
-
lines: list[str] = []
|
|
881
|
-
prefix = f"[{engine_id}] " if engine_id else ""
|
|
882
|
-
if not diagnosis.get("drift_detected"):
|
|
883
|
-
if diagnosis.get("issues"):
|
|
884
|
-
lines.append(f"{prefix}诊断发现异常 (Stage: {diagnosis.get('stage')}):")
|
|
885
|
-
for iss in diagnosis["issues"]:
|
|
886
|
-
lines.append(f" • {iss}")
|
|
887
|
-
else:
|
|
888
|
-
lines.append(f"{prefix}结构正常,未检测到漂移。")
|
|
889
|
-
return "\n".join(lines)
|
|
890
|
-
|
|
891
|
-
lines.append(f"{prefix}检测到上游响应结构漂移 (Stage: {diagnosis.get('stage')}, 置信度: {diagnosis.get('confidence', 0):.0%}):")
|
|
892
|
-
for iss in diagnosis.get("issues", []):
|
|
893
|
-
lines.append(f" • {iss}")
|
|
894
|
-
|
|
895
|
-
patch = diagnosis.get("suggested_patch") or {}
|
|
896
|
-
if patch:
|
|
897
|
-
lines.append(" 建议 Spec 补丁 (output_map):")
|
|
898
|
-
for k, v in patch.items():
|
|
899
|
-
lines.append(f" {k}: {v}")
|
|
900
|
-
return "\n".join(lines)
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
def apply_schema_patch(spec_file: str | Path, patch: dict[str, str]) -> tuple[bool, str]:
|
|
904
|
-
"""安全原子应用 Spec 补丁:保留所有注释和格式,仅改写 output_map 对应键。"""
|
|
905
|
-
import re as _re
|
|
906
|
-
p = Path(spec_file)
|
|
907
|
-
if not p.is_file():
|
|
908
|
-
return False, f"Spec 文件不存在: {p}"
|
|
909
|
-
|
|
910
|
-
text = p.read_text(encoding="utf-8")
|
|
911
|
-
if "output_map:" not in text:
|
|
912
|
-
return False, "Spec 中无 output_map 节点,不支持就地修改"
|
|
913
|
-
|
|
914
|
-
for k, v in patch.items():
|
|
915
|
-
pattern = _re.compile(rf"^([ \t]+){_re.escape(k)}:\s*.*$", _re.M)
|
|
916
|
-
if pattern.search(text):
|
|
917
|
-
text = pattern.sub(rf"\g<1>{k}: {v}", text)
|
|
918
|
-
else:
|
|
919
|
-
# 补在 output_map 之后
|
|
920
|
-
text = _re.sub(r"^(output_map:.*)$", rf"\1\n {k}: {v}", text, count=1, flags=_re.M)
|
|
921
|
-
|
|
922
|
-
p.write_text(text, encoding="utf-8")
|
|
923
|
-
return True, f"已安全更新 {p.name} 中的 {len(patch)} 个字段"
|
|
924
|
-
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""engines_schema_drift.py — 声明式引擎 Spec 结构漂移只读诊断。
|
|
3
|
+
|
|
4
|
+
职责:
|
|
5
|
+
- 检测三层契约漂移:Envelope (业务错误封套)、Container (items 列表)、Field (title/url/snippet)
|
|
6
|
+
- 启发式推荐 output_map 补丁与样本密钥快照(仅预览,不自动改写 YAML 真源)
|
|
7
|
+
- 内存影子验证建议补丁是否能成功提取 title 与 url
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from engines_fields import _dig, _format_url_template, extract_items
|
|
15
|
+
|
|
16
|
+
_TITLE_SYNONYMS = (
|
|
17
|
+
"title", "name", "headline", "subject", "text", "label",
|
|
18
|
+
"caption", "item_title", "artwork_title", "track_name", "display_name",
|
|
19
|
+
)
|
|
20
|
+
_URL_SYNONYMS = (
|
|
21
|
+
"url", "link", "web_url", "html_url", "href", "uri",
|
|
22
|
+
"source_url", "landing_page", "target_url", "permalink", "page_url", "site_url",
|
|
23
|
+
)
|
|
24
|
+
_SUMMARY_SYNONYMS = (
|
|
25
|
+
"snippet", "summary", "description", "abstract", "body",
|
|
26
|
+
"content", "desc", "overview", "intro", "tombstone", "details", "comment",
|
|
27
|
+
)
|
|
28
|
+
_PUB_SYNONYMS = (
|
|
29
|
+
"published_at", "created_at", "pubdate", "pub_date", "date",
|
|
30
|
+
"time", "timestamp", "premiered", "first_air_date", "release_date",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _flatten_item(item: Any, prefix: str = "", depth: int = 0, max_depth: int = 3) -> dict[str, Any]:
|
|
35
|
+
"""将嵌套字典/列表展平为点分路径键值字典(列表只展开前 2 条)。"""
|
|
36
|
+
flat: dict[str, Any] = {}
|
|
37
|
+
if depth > max_depth or not isinstance(item, (dict, list)):
|
|
38
|
+
return flat
|
|
39
|
+
pairs = item.items() if isinstance(item, dict) else enumerate(item[:2])
|
|
40
|
+
for k, v in pairs:
|
|
41
|
+
path = f"{prefix}.{k}" if prefix else str(k)
|
|
42
|
+
if isinstance(v, (dict, list)) and depth < max_depth:
|
|
43
|
+
flat.update(_flatten_item(v, path, depth + 1, max_depth))
|
|
44
|
+
else:
|
|
45
|
+
flat[path] = v
|
|
46
|
+
return flat
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _score_container(data: list) -> float:
|
|
50
|
+
score = 0.5 + min(0.3, len(data) * 0.02)
|
|
51
|
+
keys = {str(k).lower() for k in data[0].keys()}
|
|
52
|
+
if any(k in keys for k in ("title", "name", "id", "url", "link")):
|
|
53
|
+
score += 0.2
|
|
54
|
+
return score
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _find_candidate_containers(data: Any, prefix: str = "", depth: int = 0, max_depth: int = 4) -> list[tuple[str, list, float]]:
|
|
58
|
+
"""递归搜索全部字典列表,并按结构质量降序返回。"""
|
|
59
|
+
candidates: list[tuple[str, list, float]] = []
|
|
60
|
+
if depth > max_depth:
|
|
61
|
+
return candidates
|
|
62
|
+
if isinstance(data, list):
|
|
63
|
+
if data and isinstance(data[0], dict):
|
|
64
|
+
candidates.append((prefix or ".", data, _score_container(data)))
|
|
65
|
+
return candidates
|
|
66
|
+
if isinstance(data, dict):
|
|
67
|
+
for k, v in data.items():
|
|
68
|
+
path = f"{prefix}.{k}" if prefix else str(k)
|
|
69
|
+
if isinstance(v, list) and v and isinstance(v[0], dict):
|
|
70
|
+
candidates.append((path, v, _score_container(v)))
|
|
71
|
+
elif isinstance(v, dict) and depth < max_depth:
|
|
72
|
+
candidates.extend(_find_candidate_containers(v, path, depth + 1, max_depth))
|
|
73
|
+
candidates.sort(key=lambda x: x[2], reverse=True)
|
|
74
|
+
return candidates
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _match_text_field(flat: dict[str, Any], primary: tuple[str, ...], synonyms: tuple[str, ...],
|
|
78
|
+
*, high: float, mid: float, min_len: int = 1) -> tuple[str | None, Any, float]:
|
|
79
|
+
for path, val in flat.items():
|
|
80
|
+
if not isinstance(val, (str, int)):
|
|
81
|
+
continue
|
|
82
|
+
s = str(val).strip()
|
|
83
|
+
if len(s) < min_len:
|
|
84
|
+
continue
|
|
85
|
+
seg = path.split(".")[-1].lower()
|
|
86
|
+
if seg in primary:
|
|
87
|
+
return path, val, high
|
|
88
|
+
if seg in synonyms:
|
|
89
|
+
return path, val, mid
|
|
90
|
+
return None, None, 0.0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _match_best_field(target_kind: str, flat: dict[str, Any]) -> tuple[str | None, Any, float]:
|
|
94
|
+
"""根据目标类型和扁平键树,启发式匹配最优路径。"""
|
|
95
|
+
if target_kind == "title":
|
|
96
|
+
return _match_text_field(
|
|
97
|
+
flat, ("title", "name", "headline", "artwork_title"), _TITLE_SYNONYMS, high=0.95, mid=0.85,
|
|
98
|
+
)
|
|
99
|
+
if target_kind == "summary":
|
|
100
|
+
return _match_text_field(
|
|
101
|
+
flat, ("snippet", "summary", "description", "abstract"), _SUMMARY_SYNONYMS, high=0.90, mid=0.80, min_len=5,
|
|
102
|
+
)
|
|
103
|
+
if target_kind == "url":
|
|
104
|
+
cands: list[tuple[str, Any, float]] = []
|
|
105
|
+
for path, val in flat.items():
|
|
106
|
+
s = str(val or "").strip()
|
|
107
|
+
if not s.startswith(("http://", "https://", "/")):
|
|
108
|
+
continue
|
|
109
|
+
seg = path.split(".")[-1].lower()
|
|
110
|
+
score = 0.6 + (0.3 if seg in _URL_SYNONYMS else 0.0)
|
|
111
|
+
if s.lower().endswith((".jpg", ".jpeg", ".png", ".gif", ".webp")):
|
|
112
|
+
score -= 0.4
|
|
113
|
+
cands.append((path, val, score))
|
|
114
|
+
cands.sort(key=lambda x: x[2], reverse=True)
|
|
115
|
+
if cands and cands[0][2] >= 0.5:
|
|
116
|
+
return cands[0]
|
|
117
|
+
for path, val in flat.items():
|
|
118
|
+
if path.split(".")[-1].lower() in _URL_SYNONYMS and val:
|
|
119
|
+
return path, val, 0.75
|
|
120
|
+
return None, None, 0.0
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _shadow_check(raw_data: Any, spec_or_omap: dict[str, Any], patch: dict[str, str]) -> tuple[bool, str]:
|
|
124
|
+
omap = spec_or_omap.get("output_map") if isinstance(spec_or_omap.get("output_map"), dict) else spec_or_omap
|
|
125
|
+
merged = {**(omap or {}), **patch}
|
|
126
|
+
items = extract_items(raw_data, merged.get("items", ""))
|
|
127
|
+
if not items or not isinstance(items[0], dict):
|
|
128
|
+
return False, f"容器路径 '{merged.get('items', '')}' 未提取到字典条目"
|
|
129
|
+
title_k = merged.get("item_title", "title")
|
|
130
|
+
url_k = merged.get("item_url", "url")
|
|
131
|
+
url_tmpl = spec_or_omap.get("url_template") if isinstance(spec_or_omap, dict) else None
|
|
132
|
+
checked = 0
|
|
133
|
+
for it in items[:5]:
|
|
134
|
+
if not isinstance(it, dict):
|
|
135
|
+
continue
|
|
136
|
+
t = _dig(it, title_k) if title_k else None
|
|
137
|
+
u = (_dig(it, url_k) if url_k else None) or (_format_url_template(url_tmpl, it) if url_tmpl else None)
|
|
138
|
+
if not t or not str(t).strip():
|
|
139
|
+
return False, f"样本标题为空 (字段 '{title_k}')"
|
|
140
|
+
if not u or not str(u).strip():
|
|
141
|
+
return False, f"样本 URL 为空 (字段 '{url_k}')"
|
|
142
|
+
checked += 1
|
|
143
|
+
return (True, f"成功对 {checked} 条样本完成 title 与 url 提取验证") if checked else (False, "无有效样本条目")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def diagnose_schema_drift(raw_data: Any, spec_or_output_map: dict[str, Any]) -> dict[str, Any]:
|
|
147
|
+
"""上游数据源结构漂移只读诊断(Envelope / Container / Field 三层对拍)。"""
|
|
148
|
+
omap = spec_or_output_map.get("output_map") if isinstance(spec_or_output_map.get("output_map"), dict) else spec_or_output_map
|
|
149
|
+
if not isinstance(omap, dict):
|
|
150
|
+
omap = {}
|
|
151
|
+
|
|
152
|
+
cur_items = omap.get("items", "")
|
|
153
|
+
cur_fields = {
|
|
154
|
+
"item_title": (omap.get("item_title", "title"), "title", "标题"),
|
|
155
|
+
"item_url": (omap.get("item_url", "url"), "url", "链接"),
|
|
156
|
+
"item_summary": (omap.get("item_summary", "snippet"), "summary", "摘要"),
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if not isinstance(raw_data, (dict, list)):
|
|
160
|
+
return {
|
|
161
|
+
"ok": False, "drift_detected": False, "stage": "envelope", "confidence": 0.0,
|
|
162
|
+
"issues": [f"响应非 JSON 结构 (类型: {type(raw_data).__name__})"], "suggested_patch": {},
|
|
163
|
+
}
|
|
164
|
+
if isinstance(raw_data, dict):
|
|
165
|
+
err_val = raw_data.get("error") or raw_data.get("err_msg") or raw_data.get("message")
|
|
166
|
+
if (err_val and not any(raw_data.get(k) for k in ("data", "results", "items"))
|
|
167
|
+
and not _find_candidate_containers(raw_data)):
|
|
168
|
+
return {
|
|
169
|
+
"ok": False, "drift_detected": False, "stage": "envelope", "confidence": 0.0,
|
|
170
|
+
"issues": [f"上游返回业务错误封套: {err_val}"], "suggested_patch": {},
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
issues: list[str] = []
|
|
174
|
+
container_drift: dict[str, Any] | None = None
|
|
175
|
+
field_drifts: dict[str, Any] = {}
|
|
176
|
+
suggested_patch: dict[str, str] = {}
|
|
177
|
+
|
|
178
|
+
items = extract_items(raw_data, cur_items)
|
|
179
|
+
if not items or not isinstance(items[0], dict):
|
|
180
|
+
candidates = _find_candidate_containers(raw_data)
|
|
181
|
+
if not candidates:
|
|
182
|
+
return {
|
|
183
|
+
"ok": False, "drift_detected": False, "stage": "container", "confidence": 0.0,
|
|
184
|
+
"issues": [f"未在响应中发现任何字典列表容器 (当前 items='{cur_items}')"], "suggested_patch": {},
|
|
185
|
+
}
|
|
186
|
+
best_path, items, score = candidates[0]
|
|
187
|
+
container_drift = {"from": cur_items, "to": best_path, "count": len(items), "score": score}
|
|
188
|
+
issues.append(f"容器路径失效: '{cur_items}' 未提取到条目,候选路径 '{best_path}' (包含 {len(items)} 条)")
|
|
189
|
+
suggested_patch["items"] = best_path
|
|
190
|
+
|
|
191
|
+
sample = items[0]
|
|
192
|
+
flat = _flatten_item(sample, max_depth=3)
|
|
193
|
+
for map_key, (cur_key, kind, label) in cur_fields.items():
|
|
194
|
+
if not cur_key or _dig(sample, cur_key):
|
|
195
|
+
continue
|
|
196
|
+
cand_p, cand_v, cand_s = _match_best_field(kind, flat)
|
|
197
|
+
if cand_p and cand_p != cur_key:
|
|
198
|
+
field_drifts[map_key] = {"from": cur_key, "to": cand_p, "sample": str(cand_v)[:50], "score": cand_s}
|
|
199
|
+
issues.append(f"{label}字段失效: '{cur_key}' 为空 -> 候选 '{cand_p}' (值: {cand_v!r})")
|
|
200
|
+
suggested_patch[map_key] = cand_p
|
|
201
|
+
|
|
202
|
+
drift_detected = bool(container_drift or field_drifts)
|
|
203
|
+
stage = "field" if field_drifts else ("container" if container_drift else "ok")
|
|
204
|
+
confidence, shadow_verified, shadow_msg = 0.0, False, ""
|
|
205
|
+
|
|
206
|
+
if drift_detected and suggested_patch:
|
|
207
|
+
shadow_verified, shadow_msg = _shadow_check(raw_data, spec_or_output_map, suggested_patch)
|
|
208
|
+
if shadow_verified:
|
|
209
|
+
if container_drift:
|
|
210
|
+
confidence = 0.95
|
|
211
|
+
else:
|
|
212
|
+
min_cand = min(info.get("score", 0.0) for info in field_drifts.values())
|
|
213
|
+
anchor_ok = all(
|
|
214
|
+
k in suggested_patch or bool(_dig(sample, cur_fields[k][0]))
|
|
215
|
+
for k in ("item_title", "item_url")
|
|
216
|
+
)
|
|
217
|
+
confidence = 0.95 if (
|
|
218
|
+
(min_cand >= 0.90 and anchor_ok)
|
|
219
|
+
or (min_cand >= 0.85 and "item_title" in suggested_patch and "item_url" in suggested_patch)
|
|
220
|
+
) else (min_cand if min_cand < 0.95 else 0.80)
|
|
221
|
+
else:
|
|
222
|
+
confidence = 0.60
|
|
223
|
+
issues.append(f"影子试跑未通过: {shadow_msg}")
|
|
224
|
+
|
|
225
|
+
return {
|
|
226
|
+
"ok": not drift_detected,
|
|
227
|
+
"drift_detected": drift_detected,
|
|
228
|
+
"stage": stage,
|
|
229
|
+
"issues": issues,
|
|
230
|
+
"container_drift": container_drift,
|
|
231
|
+
"field_drifts": field_drifts,
|
|
232
|
+
"suggested_patch": suggested_patch,
|
|
233
|
+
"sample_keys": list(flat.keys())[:12],
|
|
234
|
+
"confidence": confidence,
|
|
235
|
+
"shadow_verified": shadow_verified,
|
|
236
|
+
"shadow_msg": shadow_msg,
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def render_drift_report(diagnosis: dict[str, Any], engine_id: str = "") -> str:
|
|
241
|
+
"""渲染终端格式化的结构漂移诊断报告(只读预览)。"""
|
|
242
|
+
prefix = f"[{engine_id}] " if engine_id else ""
|
|
243
|
+
if not diagnosis.get("drift_detected"):
|
|
244
|
+
if diagnosis.get("issues"):
|
|
245
|
+
lines = [f"{prefix}诊断发现异常 (Stage: {diagnosis.get('stage')}):"]
|
|
246
|
+
lines.extend(f" • {iss}" for iss in diagnosis["issues"])
|
|
247
|
+
return "\n".join(lines)
|
|
248
|
+
return f"{prefix}结构正常,未检测到漂移。"
|
|
249
|
+
|
|
250
|
+
lines = [
|
|
251
|
+
f"{prefix}检测到上游响应结构漂移 (Stage: {diagnosis.get('stage')}, 置信度: {diagnosis.get('confidence', 0):.0%}):"
|
|
252
|
+
]
|
|
253
|
+
lines.extend(f" • {iss}" for iss in diagnosis.get("issues", []))
|
|
254
|
+
patch = diagnosis.get("suggested_patch") or {}
|
|
255
|
+
if patch:
|
|
256
|
+
lines.append(" 建议 Spec 补丁 (output_map):")
|
|
257
|
+
lines.extend(f" {k}: {v}" for k, v in patch.items())
|
|
258
|
+
if diagnosis.get("sample_keys"):
|
|
259
|
+
lines.append(f" 样本键路径: {', '.join(diagnosis['sample_keys'])}")
|
|
260
|
+
return "\n".join(lines)
|