argo-search 2.14.0 → 2.14.1

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 (82) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.es.md +18 -8
  3. package/README.ja.md +18 -8
  4. package/README.ko.md +18 -8
  5. package/README.md +511 -608
  6. package/README.zh.md +975 -0
  7. package/SKILL.md +1 -1
  8. package/assets/readme/counts.json +1 -1
  9. package/backends/domain_profiles.json +24 -0
  10. package/backends/engine_registry.yaml +69 -18
  11. package/backends/quota_profiles.json +40 -0
  12. package/config.yaml +23 -3
  13. package/docs/CHANGELOG.md +22 -0
  14. package/docs/ENGINE_CATALOG.md +41 -37
  15. package/docs/MCP_SETUP.md +1 -1
  16. package/docs/RELEASE_NOTES_v2.14.0.md +12 -1
  17. package/docs/RELEASE_NOTES_v2.14.1.md +80 -0
  18. package/docs/RELEASING.md +52 -0
  19. package/engines/specs/artic.yaml +11 -1
  20. package/engines/specs/cleveland.yaml +15 -1
  21. package/engines/specs/clinicaltrials.yaml +16 -1
  22. package/engines/specs/cnii.yaml +15 -4
  23. package/engines/specs/deezer.yaml +12 -1
  24. package/engines/specs/doaj.yaml +14 -1
  25. package/engines/specs/endoflife.yaml +16 -1
  26. package/engines/specs/eu_opendata.yaml +11 -1
  27. package/engines/specs/europeana.yaml +19 -1
  28. package/engines/specs/feed.yaml +62 -0
  29. package/engines/specs/figshare.yaml +12 -1
  30. package/engines/specs/hackernews.yaml +17 -2
  31. package/engines/specs/hal.yaml +19 -1
  32. package/engines/specs/hf_datasets.yaml +59 -0
  33. package/engines/specs/hf_papers.yaml +17 -1
  34. package/engines/specs/jikan.yaml +12 -10
  35. package/engines/specs/kaggle.yaml +5 -3
  36. package/engines/specs/maven.yaml +61 -0
  37. package/engines/specs/nasa_cmr.yaml +12 -1
  38. package/engines/specs/nuget.yaml +57 -0
  39. package/engines/specs/tatoeba.yaml +14 -1
  40. package/engines/specs/tvmaze.yaml +5 -1
  41. package/engines/specs/usda.yaml +14 -1
  42. package/package.json +2 -1
  43. package/packages/dsh-plugin/dsh/native-tools.mjs +61 -113
  44. package/packages/dsh-plugin/dsh/wide-research.js +1 -1
  45. package/packages/dsh-plugin/package.json +1 -1
  46. package/scripts/badcase_ledger.py +49 -5
  47. package/scripts/build_release_assets.sh +43 -15
  48. package/scripts/dormant_ledger.py +225 -0
  49. package/scripts/engine_states.py +6 -1
  50. package/scripts/engine_validate.py +182 -6
  51. package/scripts/engines.py +0 -36
  52. package/scripts/engines_base.py +27 -67
  53. package/scripts/engines_builders.py +0 -36
  54. package/scripts/engines_builders_batch16.py +6 -179
  55. package/scripts/engines_builders_batch9.py +0 -204
  56. package/scripts/engines_builders_feeds.py +148 -30
  57. package/scripts/engines_builders_intl.py +0 -328
  58. package/scripts/engines_builders_science.py +0 -85
  59. package/scripts/engines_builders_tech.py +0 -98
  60. package/scripts/engines_parsers.py +534 -9
  61. package/scripts/evidence_loop.py +91 -4
  62. package/scripts/gen_engine_catalog.py +2 -2
  63. package/scripts/gen_native_tools.py +2 -1
  64. package/scripts/local_intent.py +51 -15
  65. package/scripts/local_seek.py +37 -4
  66. package/scripts/mcp_handlers.py +124 -72
  67. package/scripts/mcp_server.py +1 -1
  68. package/scripts/mcp_tools.py +143 -61
  69. package/scripts/mcp_transport.py +42 -10
  70. package/scripts/pre-commit +25 -1
  71. package/scripts/release.py +20 -11
  72. package/scripts/release_check.py +1 -1
  73. package/scripts/route_policy.py +6 -1
  74. package/scripts/search_cli.py +44 -7
  75. package/scripts/secret_guard.py +106 -0
  76. package/scripts/semantic_evidence.py +230 -15
  77. package/scripts/settings_page.py +80 -8
  78. package/scripts/source_audit.py +77 -0
  79. package/scripts/sync_backends.py +7 -0
  80. package/sub-skills/local-seek/scripts/seek_fts.py +9 -1
  81. package/README.en.md +0 -826
  82. package/scripts/image_vision/vision_probe +0 -0
@@ -38,6 +38,8 @@ image_url / upstream(均为可选,缺省由下游补)。
38
38
  from __future__ import annotations
39
39
 
40
40
  import html as _htmllib
41
+ import re
42
+ from pathlib import Path
41
43
  from typing import Any, Callable
42
44
 
43
45
  # 解析器签名:(原始数据, spec) -> 标准结果行列表
@@ -98,6 +100,164 @@ def resolve(spec: dict) -> list[Parser]:
98
100
  return [get(n) for n in names]
99
101
 
100
102
 
103
+ # ─────────────────────────────────────────────────────────────────────────────
104
+ # 声明式字段映射(output_map 的通用实现)
105
+ # ─────────────────────────────────────────────────────────────────────────────
106
+ #
107
+ # 为什么放在这里:2026-11-10 归一 13 个专用 builder 时发现,原 builder 常把
108
+ # 多个上游字段拼进 snippet(cleveland 的 `tombstone · 授权 CC0`、deezer 的
109
+ # `Deezer 音乐人 · 专辑 N · 粉丝 M`),而 output_map 只能取单个字段——归一后
110
+ # 这类信息会静默丢失。把「拼接」变成声明式能力,属于解析层职责,故与
111
+ # `parse_*` 解析器同文件维护;engines_base 只做委托调用。
112
+
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
+ def _render_field_template(template: str, item: dict) -> str:
148
+ """模板插值:`{field}` 取条目字段(支持点分路径),空值置空并折叠分隔符。
149
+
150
+ 与 URL 模板的区别:URL 模板任一占位为空则整体落空(否则拼出半截链接),
151
+ 而文本模板把空占位折叠掉——少一段仍是有效文本。
152
+ 连续/首尾的 `·`/`⇄`/`|` 分隔符会折叠,避免缺字段留下 `a · · b` 残渣。
153
+ """
154
+ def _repl(m: re.Match) -> str:
155
+ return _coerce_field(_dig(item, m.group(1)))
156
+
157
+ out = re.sub(r"\{([^}]+)\}", _repl, template)
158
+ out = re.sub(r"(?:\s*[·⇄|]\s*)+", lambda m: " " + next(
159
+ (ch for ch in m.group(0) if ch in "·⇄|"), "·") + " ", out)
160
+ out = out.strip()
161
+ out = re.sub(r"(?:^\s*[·⇄|]\s*|\s*[·⇄|]\s*$)", "", out)
162
+ return out.strip()
163
+
164
+
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
+ def make_field_parser(path: str, fields: dict[str, str], url_template: str | None = None,
193
+ max_items: int = 10, templates: dict[str, str] | None = None,
194
+ url_item_template: str | None = None) -> Callable:
195
+ """构造声明式 parser。支持点分路径字段、url_template(含嵌套占位)与模板拼接。
196
+
197
+ `templates` 是可选的模板字段映射(`{item_title, item_summary}`),声明后
198
+ 覆盖同名 `fields` 条目——用于需要多字段拼接的源(见 `_render_field_template`)。
199
+
200
+ `url_item_template` 是**逐条目**的 URL 拼接模板(如 eu_opendata 的
201
+ `landing_page.0.resource` 数组取首项)。与 `url_template` 的区别:后者用
202
+ `_format_url_template` 且任一占位为空即整体落空;前者在取不到值时保持
203
+ 「不声明 URL」,交给通用推断或下游补。
204
+ """
205
+ templates = templates or {}
206
+
207
+ def parser(data: Any) -> list[dict[str, Any]]:
208
+ if isinstance(data, list) and path in ("", ".", "$", "[]"):
209
+ items = data
210
+ elif isinstance(data, dict):
211
+ items = extract_items(data, path)
212
+ else:
213
+ items = []
214
+ results = []
215
+ for item in items:
216
+ if not isinstance(item, dict):
217
+ continue
218
+ r: dict[str, Any] = {}
219
+ for ok, ik in fields.items():
220
+ if not ik:
221
+ continue
222
+ raw = _dig(item, ik) if "." in str(ik) else item.get(ik, "")
223
+ if raw in ("", None) and "." not in str(ik):
224
+ raw = item.get(ik, "")
225
+ coerced = _coerce_field(raw, max_len=300 if ok == "snippet" else 500)
226
+ if coerced:
227
+ r[ok] = coerced
228
+ # 模板字段优先于同名单字段映射(声明式拼接覆盖单字段取值)。
229
+ # 键名是 output_map 的声明名(item_title_template),落到标准行字段
230
+ # 名(title/snippet)——不转换会把结果写进 `item_summary_template` 键。
231
+ # 模板渲染为空时**回落**到单字段映射(如 tatoeba 无译文时用 lang),
232
+ # 而不是把已取到的值覆盖成空。
233
+ for ok, tmpl in templates.items():
234
+ if not tmpl:
235
+ continue
236
+ std = {"item_title_template": "title",
237
+ "item_summary_template": "snippet"}.get(ok, ok)
238
+ rendered = _render_field_template(tmpl, item)
239
+ if rendered:
240
+ r[std] = rendered[:300 if std == "snippet" else 500]
241
+ if url_template and (not r.get("url") or not str(r["url"]).startswith(("http://", "https://"))):
242
+ built = _format_url_template(url_template, item)
243
+ if built.startswith(("http://", "https://")):
244
+ r["url"] = built
245
+ else:
246
+ r.pop("url", None)
247
+ # 逐条目 URL 模板:占位取自条目自身(如 landing_page.0.resource),
248
+ # 取不到就保持无 URL(不造半截链接)。
249
+ if url_item_template and (not r.get("url") or not str(r["url"]).startswith(("http://", "https://"))):
250
+ built = _format_url_template(url_item_template, item)
251
+ if built.startswith(("http://", "https://")):
252
+ r["url"] = built
253
+ if isinstance(r.get("url"), str) and r["url"].startswith("//"):
254
+ r["url"] = "https:" + r["url"]
255
+ if r.get("title") or r.get("url"):
256
+ results.append(r)
257
+ return results[:max_items]
258
+ return parser
259
+
260
+
101
261
  # ─────────────────────────────────────────────────────────────────────────────
102
262
  # 内置解析器
103
263
  # ─────────────────────────────────────────────────────────────────────────────
@@ -231,11 +391,55 @@ def parse_mwmbl(data: Any, spec: dict) -> list[dict]:
231
391
  return results
232
392
 
233
393
 
394
+ def parse_artic(data: Any, spec: dict) -> list[dict]:
395
+ """Art Institute of Chicago 响应解析(L2:IIIF 图片需响应级 config 拼接)。
396
+
397
+ 上游把 IIIF 基础地址放在响应的 `config.iiif_url`(不在条目里),图片直链
398
+ 是 `{iiif_url}/{image_id}/full/843,/0/default.jpg`。这类「拼接依赖响应级
399
+ 配置」的解析无法用 output_map 声明,故注册专用解析器——协议标准、解析变体。
400
+
401
+ image_id 为空时**不产出** image_url(不得凭空造链接,见 test_image_sources)。
402
+ """
403
+ if not isinstance(data, dict):
404
+ return []
405
+ source = spec.get("engine_id", "artic")
406
+ iiif = str(((data.get("config") or {}).get("iiif_url") or "")).rstrip("/")
407
+ rows = data.get("data") if isinstance(data.get("data"), list) else []
408
+ results = []
409
+ for _rk, it in enumerate(rows):
410
+ if not isinstance(it, dict):
411
+ continue
412
+ title = str(it.get("title") or "").strip()
413
+ art_id = it.get("id")
414
+ url_ = f"https://www.artic.edu/artworks/{art_id}" if art_id else ""
415
+ if not title and not url_:
416
+ continue
417
+ row = {
418
+ "title": title[:200],
419
+ "url": url_,
420
+ "snippet": str(it.get("artist_display") or "")[:300],
421
+ "source": source,
422
+ "score": max(0.0, 0.7 - _rk * 0.05),
423
+ }
424
+ image_id = str(it.get("image_id") or "").strip()
425
+ if iiif and image_id:
426
+ row["image_url"] = f"{iiif}/{image_id}/full/843,/0/default.jpg"
427
+ # AIC 是 CC0 开放图像;授权缺失时按无授权处理,不凭空标注
428
+ lic = str(it.get("copyright_notice") or "").strip()
429
+ if lic:
430
+ row["image_license"] = lic
431
+ else:
432
+ row["image_license"] = "CC0(芝加哥艺术博物馆开放图像)"
433
+ results.append(row)
434
+ return results
435
+
436
+
234
437
  # 注册通用解析器
235
438
  register("array_at", parse_array_at)
236
439
  register("object_root", parse_object_root)
237
440
  register("strip_fields", parse_strip_fields)
238
441
  register("mwmbl", parse_mwmbl)
442
+ register("artic", parse_artic)
239
443
 
240
444
 
241
445
  def parse_smart_generic(data: Any, engine_name: str = "?",
@@ -297,34 +501,66 @@ def parse_smart_generic(data: Any, engine_name: str = "?",
297
501
  if not isinstance(i, dict):
298
502
  continue
299
503
  flat = dict(i)
300
- for nested_k in ("paper", "item", "data", "node", "article", "entry"):
504
+ for nested_k in ("paper", "item", "data", "node", "article", "entry", "show", "bibjson"):
301
505
  if isinstance(i.get(nested_k), dict):
302
506
  for k, v in i[nested_k].items():
303
507
  flat.setdefault(k, v)
304
508
 
305
509
  title = (
306
510
  flat.get("title") or flat.get("name") or flat.get("heading")
307
- or flat.get("Title") or flat.get("titleNullable")
308
- or flat.get("headline") or flat.get("subject") or flat.get("topic") or ""
511
+ or flat.get("Title") or flat.get("titleNullable") or flat.get("title_s")
512
+ or flat.get("headline") or flat.get("subject") or flat.get("topic")
513
+ or flat.get("text") or flat.get("cycle") or ""
309
514
  )
310
- if isinstance(title, list):
515
+ if isinstance(title, dict):
516
+ # 多语言字典(如 EU Open Data):优先取 en/zh/fr/de,否则取首个
517
+ for lang in ("en", "zh", "fr", "de"):
518
+ if title.get(lang):
519
+ title = title[lang]
520
+ break
521
+ if isinstance(title, dict) and title:
522
+ title = next(iter(title.values()))
523
+ elif isinstance(title, list):
311
524
  title = title[0] if title else ""
312
525
  raw_id = flat.get("id") or flat.get("objectID") or flat.get("ID") or ""
313
526
  url = (
314
527
  flat.get("url") or flat.get("URL") or flat.get("html_url")
315
528
  or flat.get("link") or flat.get("href") or flat.get("urlNullable")
316
- or flat.get("web_url") or flat.get("canonical_url") or ""
529
+ or flat.get("web_url") or flat.get("canonical_url") or flat.get("guid")
530
+ or flat.get("uri_s") or flat.get("url_public_html")
531
+ or flat.get("resource") or flat.get("landing_page") or ""
317
532
  )
318
- if not url and url_template and raw_id:
533
+ if isinstance(url, list) and url:
534
+ if isinstance(url[0], dict):
535
+ url = url[0].get("url") or url[0].get("href") or url[0].get("resource") or ""
536
+ else:
537
+ url = str(url[0])
538
+ if not url and url_template:
319
539
  url = url_template.replace("{id}", str(raw_id))
540
+ for _k, _v in flat.items():
541
+ if f"{{{_k}}}" in url:
542
+ url = url.replace(f"{{{_k}}}", str(_v))
320
543
 
321
544
  snippet = (
322
545
  flat.get("snippet") or flat.get("summary") or flat.get("content")
323
- or flat.get("description") or flat.get("abstract")
546
+ or flat.get("description") or flat.get("abstract") or flat.get("abstract_s")
324
547
  or flat.get("subtitleNullable") or flat.get("subtitle")
325
548
  or flat.get("extract") or flat.get("details") or flat.get("text") or ""
326
549
  )
327
- if isinstance(snippet, list):
550
+ if not snippet and (flat.get("eol") or flat.get("latest")):
551
+ _sp = [f"最新 {flat['latest']}" if flat.get("latest") else "",
552
+ f"发布 {flat['releaseDate']}" if flat.get("releaseDate") else "",
553
+ f"支持至 {flat['support']}" if flat.get("support") else "",
554
+ f"EOL {flat['eol']}" if flat.get("eol") else ""]
555
+ snippet = " · ".join(x for x in _sp if x)
556
+ if isinstance(snippet, dict):
557
+ for lang in ("en", "zh", "fr", "de"):
558
+ if snippet.get(lang):
559
+ snippet = snippet[lang]
560
+ break
561
+ if isinstance(snippet, dict) and snippet:
562
+ snippet = next(iter(snippet.values()))
563
+ elif isinstance(snippet, list):
328
564
  snippet = snippet[0] if snippet else ""
329
565
 
330
566
  # 文本标签剥离与 HTML 实体反转义
@@ -339,7 +575,8 @@ def parse_smart_generic(data: Any, engine_name: str = "?",
339
575
 
340
576
  published_at = (
341
577
  flat.get("published_at") or flat.get("publishedAt")
342
- or flat.get("created_at") or flat.get("pubdate") or flat.get("date") or ""
578
+ or flat.get("created_at") or flat.get("pubdate") or flat.get("date")
579
+ or flat.get("premiered") or flat.get("first_air_date") or ""
343
580
  )
344
581
  if published_at:
345
582
  try:
@@ -397,3 +634,291 @@ def _migrate_builtin() -> None:
397
634
 
398
635
 
399
636
  _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
+