argo-search 2.14.0 → 2.15.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.
Files changed (207) hide show
  1. package/AGENTS.md +8 -6
  2. package/README.es.md +56 -824
  3. package/README.ja.md +55 -825
  4. package/README.ko.md +55 -823
  5. package/README.md +128 -868
  6. package/README.zh.md +206 -0
  7. package/SKILL.md +17 -18
  8. package/assets/readme/counts.json +1 -1
  9. package/assets/readme/hero.svg +23 -23
  10. package/backends/concept_vectors.bin +0 -0
  11. package/backends/domain_profiles.json +66 -0
  12. package/backends/engine_concept_vectors.json +1525 -1525
  13. package/backends/engine_registry.yaml +193 -46
  14. package/backends/quota_profiles.json +110 -0
  15. package/bin/argo +30 -17
  16. package/config.yaml +196 -36
  17. package/docs/ADDING_NEW_ENGINE.md +10 -0
  18. package/docs/ARGO_INTRO.md +1 -1
  19. package/docs/CHANGELOG.md +45 -0
  20. package/docs/ENGINE_CATALOG.md +128 -112
  21. package/docs/MCP_SETUP.md +2 -2
  22. package/docs/RELEASE_NOTES_v2.14.0.md +12 -1
  23. package/docs/RELEASE_NOTES_v2.14.1.md +80 -0
  24. package/docs/RELEASE_NOTES_v2.15.0.md +50 -0
  25. package/docs/RELEASING.md +53 -1
  26. package/engines/specs/ai_labs.yaml +89 -0
  27. package/engines/specs/artic.yaml +11 -1
  28. package/engines/specs/bilibili_hot.yaml +11 -1
  29. package/engines/specs/brave.yaml +3 -3
  30. package/engines/specs/cisa_alerts.yaml +40 -0
  31. package/engines/specs/cleveland.yaml +15 -1
  32. package/engines/specs/clinicaltrials.yaml +16 -1
  33. package/engines/specs/cn_ai_news.yaml +10 -8
  34. package/engines/specs/cnii.yaml +15 -4
  35. package/engines/specs/deezer.yaml +12 -1
  36. package/engines/specs/digup.yaml +11 -6
  37. package/engines/specs/doaj.yaml +14 -1
  38. package/engines/specs/douyin_hot.yaml +11 -1
  39. package/engines/specs/dw_news.yaml +4 -2
  40. package/engines/specs/endoflife.yaml +16 -1
  41. package/engines/specs/eng_blogs.yaml +63 -0
  42. package/engines/specs/eu_opendata.yaml +11 -1
  43. package/engines/specs/europeana.yaml +22 -5
  44. package/engines/specs/feed.yaml +62 -0
  45. package/engines/specs/felo.yaml +3 -3
  46. package/engines/specs/figshare.yaml +12 -1
  47. package/engines/specs/firecrawl.yaml +3 -0
  48. package/engines/specs/fourget.yaml +5 -2
  49. package/engines/specs/france24.yaml +6 -4
  50. package/engines/specs/fxtwitter.yaml +29 -6
  51. package/engines/specs/grepapp_mcp.yaml +62 -0
  52. package/engines/specs/guardian_rss.yaml +6 -4
  53. package/engines/specs/hackernews.yaml +17 -2
  54. package/engines/specs/hal.yaml +19 -1
  55. package/engines/specs/hf_datasets.yaml +59 -0
  56. package/engines/specs/hf_papers.yaml +17 -1
  57. package/engines/specs/itotii.yaml +13 -1
  58. package/engines/specs/jikan.yaml +12 -10
  59. package/engines/specs/kaggle.yaml +5 -3
  60. package/engines/specs/lobsters.yaml +41 -0
  61. package/engines/specs/local_seek.yaml +6 -0
  62. package/engines/specs/maven.yaml +61 -0
  63. package/engines/specs/nasa_cmr.yaml +12 -1
  64. package/engines/specs/nuget.yaml +57 -0
  65. package/engines/specs/open_meteo.yaml +1 -1
  66. package/engines/specs/redskill.yaml +2 -0
  67. package/engines/specs/searxng.yaml +4 -2
  68. package/engines/specs/sec_edgar.yaml +8 -3
  69. package/engines/specs/tatoeba.yaml +14 -1
  70. package/engines/specs/tinyfish.yaml +2 -0
  71. package/engines/specs/tinyfish_news.yaml +2 -0
  72. package/engines/specs/tinyfish_paper.yaml +2 -0
  73. package/engines/specs/toutiao_hot.yaml +11 -1
  74. package/engines/specs/train.yaml +3 -0
  75. package/engines/specs/tvmaze.yaml +5 -1
  76. package/engines/specs/twitter.yaml +4 -0
  77. package/engines/specs/unpaywall.yaml +6 -0
  78. package/engines/specs/usda.yaml +14 -1
  79. package/engines/specs/vam.yaml +17 -3
  80. package/engines/specs/weibo_hot.yaml +11 -1
  81. package/engines/specs/wolframalpha.yaml +3 -3
  82. package/engines/specs/xiaohongshu.yaml +2 -0
  83. package/engines/specs/zhihu.yaml +3 -18
  84. package/engines/specs/zhihu_kb.yaml +18 -0
  85. package/engines/specs/zhihu_questions.yaml +19 -0
  86. package/package.json +4 -2
  87. package/packages/dsh-plugin/README.md +9 -14
  88. package/packages/dsh-plugin/dsh/client.js +467 -1024
  89. package/packages/dsh-plugin/dsh/diagnostics.js +71 -20
  90. package/packages/dsh-plugin/dsh/native-tools.mjs +61 -113
  91. package/packages/dsh-plugin/dsh/runner.js +2 -0
  92. package/packages/dsh-plugin/dsh/wide-research.js +1 -1
  93. package/packages/dsh-plugin/package.json +8 -3
  94. package/packages/dsh-plugin/scripts/sync-local.mjs +87 -0
  95. package/packages/dsh-plugin/scripts/sync-local.sh +13 -1
  96. package/packages/dsh-plugin/test/diagnostics.test.js +38 -1
  97. package/packages/dsh-plugin/test/size-gate.test.js +2 -9
  98. package/scripts/adaptive.py +7 -1
  99. package/scripts/archive_run.py +112 -53
  100. package/scripts/argo_paths.py +40 -3
  101. package/scripts/badcase_ledger.py +153 -10
  102. package/scripts/build_concept_table.py +112 -55
  103. package/scripts/build_release_assets.sh +43 -15
  104. package/scripts/cache.py +5 -1
  105. package/scripts/caliber_isolation.py +60 -23
  106. package/scripts/circuit_breaker.py +56 -8
  107. package/scripts/cli_io.py +20 -2
  108. package/scripts/config_cache.py +31 -0
  109. package/scripts/daemon.py +146 -51
  110. package/scripts/dormant_ledger.py +239 -0
  111. package/scripts/engine_dispatch.py +3 -3
  112. package/scripts/engine_env.py +182 -1
  113. package/scripts/engine_families.py +50 -7
  114. package/scripts/engine_states.py +9 -51
  115. package/scripts/engine_validate.py +150 -6
  116. package/scripts/engines.py +15 -67
  117. package/scripts/engines_base.py +68 -124
  118. package/scripts/engines_builders.py +0 -51
  119. package/scripts/engines_builders_batch10.py +346 -100
  120. package/scripts/engines_builders_batch11.py +2 -75
  121. package/scripts/engines_builders_batch9.py +15 -228
  122. package/scripts/engines_builders_cn.py +0 -194
  123. package/scripts/engines_builders_feeds.py +203 -35
  124. package/scripts/engines_builders_intl.py +15 -443
  125. package/scripts/engines_builders_pixiv.py +2 -16
  126. package/scripts/engines_builders_science.py +0 -85
  127. package/scripts/engines_builders_search.py +7 -14
  128. package/scripts/engines_builders_tech.py +5 -112
  129. package/scripts/engines_builders_weather.py +236 -0
  130. package/scripts/engines_fields.py +91 -0
  131. package/scripts/engines_http.py +135 -0
  132. package/scripts/engines_mcp.py +383 -0
  133. package/scripts/engines_parsers.py +196 -27
  134. package/scripts/engines_schema_drift.py +260 -0
  135. package/scripts/evidence.py +13 -0
  136. package/scripts/evidence_loop.py +93 -5
  137. package/scripts/fetch_jsrun.py +15 -11
  138. package/scripts/fetch_v3.py +28 -28
  139. package/scripts/fulltext_store.py +42 -1
  140. package/scripts/fxtwitter_api.py +8 -7
  141. package/scripts/gen_engine_catalog.py +4 -4
  142. package/scripts/gen_native_tools.py +2 -1
  143. package/scripts/general_pool.py +15 -4
  144. package/scripts/health_check.py +1 -1
  145. package/scripts/link_source.py +65 -24
  146. package/scripts/local_intent.py +51 -15
  147. package/scripts/local_seek.py +37 -4
  148. package/scripts/local_seek_adapter.py +57 -17
  149. package/scripts/mcp_handlers.py +173 -99
  150. package/scripts/mcp_handlers_surface.py +6 -18
  151. package/scripts/mcp_server.py +1 -1
  152. package/scripts/mcp_tools.py +143 -61
  153. package/scripts/mcp_transport.py +42 -10
  154. package/scripts/min_version_scan.py +7 -3
  155. package/scripts/network_aware.py +7 -13
  156. package/scripts/pre-commit +57 -31
  157. package/scripts/query_understanding.py +30 -6
  158. package/scripts/quota.py +6 -1
  159. package/scripts/rank_signals.py +9 -0
  160. package/scripts/recompute.py +15 -5
  161. package/scripts/recovery.py +21 -15
  162. package/scripts/release.py +29 -32
  163. package/scripts/release_check.py +6 -26
  164. package/scripts/replay_eval.py +2 -2
  165. package/scripts/research_cli.py +40 -0
  166. package/scripts/research_notes.py +368 -0
  167. package/scripts/route.py +32 -70
  168. package/scripts/route_audit.py +259 -0
  169. package/scripts/route_combo.py +10 -4
  170. package/scripts/route_domains.py +150 -23
  171. package/scripts/route_lang.py +20 -7
  172. package/scripts/route_log.py +26 -9
  173. package/scripts/route_policy.py +91 -7
  174. package/scripts/route_telemetry_export.py +199 -0
  175. package/scripts/rrf_classic.py +5 -22
  176. package/scripts/search.py +2 -1
  177. package/scripts/search_attribution.py +33 -10
  178. package/scripts/search_cli.py +44 -7
  179. package/scripts/search_entry.py +5 -1
  180. package/scripts/search_output.py +5 -4
  181. package/scripts/search_pipeline.py +12 -0
  182. package/scripts/search_rank.py +21 -11
  183. package/scripts/secret_guard.py +106 -0
  184. package/scripts/semantic_evidence.py +539 -117
  185. package/scripts/settings_page.py +83 -11
  186. package/scripts/social_engines/xiaohongshu_engine.py +2 -1
  187. package/scripts/social_engines/zhihu_engine.py +251 -43
  188. package/scripts/sogou_weixin_browser.py +5 -6
  189. package/scripts/source_audit.py +77 -0
  190. package/scripts/source_ledger.py +2 -15
  191. package/scripts/source_selection.py +45 -20
  192. package/scripts/straggler_policy.py +1 -2
  193. package/scripts/sync_backends.py +24 -0
  194. package/scripts/tfidf_router.py +23 -11
  195. package/scripts/time_utils.py +54 -1
  196. package/scripts/train.py +68 -2
  197. package/scripts/usage_log.py +26 -1
  198. package/sub-skills/argo-wide-research/SKILL.md +68 -0
  199. package/sub-skills/ego-search/SKILL.md +1 -1
  200. package/sub-skills/local-seek/scripts/seek_fts.py +67 -4
  201. package/README.en.md +0 -826
  202. package/scripts/caliber_dedupe.py +0 -66
  203. package/scripts/engines_builders_batch16.py +0 -186
  204. package/scripts/health_probe.py +0 -253
  205. package/scripts/image_vision/vision_probe +0 -0
  206. package/scripts/social_engines/twitter_engine.py +0 -514
  207. package/scripts/sync_installs.py +0 -29
@@ -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)
@@ -696,6 +696,17 @@ def compute_credibility(
696
696
  snippet = r.get("snippet", "") or ""
697
697
 
698
698
  auth = score_authority(url, source, query)
699
+ # 方案C(upstream_authority 只透传不赋权):排序层已拿到的上游权威档
700
+ # (zhihu builder 解析 AuthorityLevel / spec output_map 的
701
+ # item_upstream_authority)原样挂到 credibility.authority.upstream_level,
702
+ # 供取证侧与研报引用;不参与 selection/final 计算——上游档只补充
703
+ # 上下文,不替代本仓基于 URL/域名的评分。无上游档则不加键(不编造)。
704
+ _upstream = r.get("upstream_authority")
705
+ if _upstream is None or _upstream == "":
706
+ _upstream = r.get("authority_level")
707
+ if _upstream is not None and _upstream != "":
708
+ auth = dict(auth)
709
+ auth["upstream_level"] = _upstream
699
710
  fresh = score_freshness(r, query_time)
700
711
  density = score_evidence_density(snippet, title)
701
712
 
@@ -838,6 +849,8 @@ def main():
838
849
  flag_s = ",".join(flags) if flags else "-"
839
850
  print(f"{level} [{c['final']:.2f}] sel={c['selection']:.2f} abs={c['absorption']:.2f} [{flag_s}] {r['title'][:48]}")
840
851
  print(f" 权威:{c['authority']['score']:.2f} ({c['authority']['reason']})")
852
+ if c["authority"].get("upstream_level") is not None:
853
+ print(f" 上游档:{c['authority']['upstream_level']}(upstream_authority 只透传)")
841
854
  print(f" 时效:{c['freshness']['score']:.2f} ({c['freshness']['reason']})")
842
855
  print()
843
856
 
@@ -583,9 +583,38 @@ def verify_results(results: list[dict[str, Any]],
583
583
  semantic_meta: dict[str, Any] | None = None
584
584
  if scored_inputs:
585
585
  try:
586
- from semantic_evidence import assess_support, enabled as _semantic_enabled
586
+ from semantic_evidence import (
587
+ assess_support, assess_source_types,
588
+ assess_substantive_discussion, enabled as _semantic_enabled,
589
+ )
587
590
  if _semantic_enabled():
588
- support = assess_support(query, scored_inputs)
591
+ # 三级阶梯兜底:Gemini 默认 → JEV 备用 → 本地启发式最终兜底
592
+ support = assess_support(query, scored_inputs, allow_heuristic=True)
593
+ source_types = assess_source_types(scored_inputs, allow_heuristic=True)
594
+ substantive_map = assess_substantive_discussion(query, scored_inputs, allow_heuristic=True)
595
+ primary_count = 0
596
+ substantive_count = 0
597
+ passing_count = 0
598
+ # 加权必须同时写回 results 原始行:verified 是 _record_verify
599
+ # 新建的展示副本,而下游 reorder_by_evidence 读的是
600
+ # r["post_fetch_absorption"](原始行),只读副本的 +0.20/+0.15
601
+ # 不会改变任何排序分(2026-11-11 审计)。按 URL 定位,避免
602
+ # 再引入第二份顺序假设。
603
+ result_by_url = {r.get("url") or "": r for r in results}
604
+
605
+ def _apply_adjustment(url: str, delta: float) -> None:
606
+ row = result_by_url.get(url)
607
+ if row is None:
608
+ return
609
+ base = row.get("post_fetch_absorption")
610
+ if base is None:
611
+ base = row.get("absorption") or 0.0
612
+ try:
613
+ adjusted = max(0.0, min(1.0, float(base) + delta))
614
+ except (TypeError, ValueError):
615
+ return
616
+ row["post_fetch_absorption"] = round(adjusted, 3)
617
+
589
618
  if support:
590
619
  for item in verified:
591
620
  info = support.get(item.get("url") or "")
@@ -595,11 +624,70 @@ def verify_results(results: list[dict[str, Any]],
595
624
  info = support.get(r.get("url") or "")
596
625
  if info:
597
626
  r["semantic_support"] = info
627
+ if source_types:
628
+ for item in verified:
629
+ st = source_types.get(item.get("url") or "")
630
+ if st:
631
+ item["source_type"] = st
632
+ if st.get("is_primary"):
633
+ primary_count += 1
634
+ # 官方一手源加权置顶:absorption 基础分提权 0.20
635
+ item["post_absorption"] = min(1.0, (item.get("post_absorption") or 0.0) + 0.20)
636
+ if "delta" in item:
637
+ item["delta"] = round(item["post_absorption"] - (item.get("pre_absorption") or 0.0), 3)
638
+ _apply_adjustment(item.get("url") or "", 0.20)
639
+ for r in results:
640
+ st = source_types.get(r.get("url") or "")
641
+ if st:
642
+ r["source_type"] = st
643
+ if substantive_map:
644
+ for item in verified:
645
+ sub = substantive_map.get(item.get("url") or "")
646
+ if sub:
647
+ item["discussion_depth"] = sub
648
+ if sub.get("is_substantive"):
649
+ substantive_count += 1
650
+ item["substantive_discussion"] = True
651
+ # 深度实质探讨加权提权:+0.15
652
+ item["post_absorption"] = min(1.0, (item.get("post_absorption") or 0.0) + 0.15)
653
+ if "delta" in item:
654
+ item["delta"] = round(item["post_absorption"] - (item.get("pre_absorption") or 0.0), 3)
655
+ _apply_adjustment(item.get("url") or "", 0.15)
656
+ elif sub.get("is_passing_mention"):
657
+ passing_count += 1
658
+ item["passing_mention"] = True
659
+ # 仅顺带提及闲聊降权去噪:-0.10
660
+ item["post_absorption"] = max(0.0, (item.get("post_absorption") or 0.0) - 0.10)
661
+ if "delta" in item:
662
+ item["delta"] = round(item["post_absorption"] - (item.get("pre_absorption") or 0.0), 3)
663
+ _apply_adjustment(item.get("url") or "", -0.10)
664
+ for r in results:
665
+ sub = substantive_map.get(r.get("url") or "")
666
+ if sub:
667
+ r["discussion_depth"] = sub
668
+ if sub.get("is_substantive"):
669
+ r["substantive_discussion"] = True
670
+ elif sub.get("is_passing_mention"):
671
+ r["passing_mention"] = True
672
+
673
+ if any((primary_count, substantive_count, passing_count)):
674
+ revisions = [v["delta"] for v in verified if "delta" in v]
675
+
676
+ if support or source_types or substantive_map:
677
+ c_count = sum(1 for x in (support or {}).values() if x.get("contradicts"))
598
678
  semantic_meta = {
599
- "scored": len(support),
600
- "supports": sum(1 for x in support.values() if x["supports"]),
601
- "contradicts": sum(1 for x in support.values() if x["contradicts"]),
679
+ "scored": len(support or source_types or substantive_map or {}),
680
+ "supports": sum(1 for x in (support or {}).values() if x.get("supports")),
681
+ "contradicts": c_count,
682
+ "primary_sources": primary_count,
683
+ "substantive_discussions": substantive_count,
684
+ "passing_mentions": passing_count,
602
685
  }
686
+ if c_count > 0:
687
+ semantic_meta["contradiction_alert"] = True
688
+ semantic_meta["contradiction_warning"] = (
689
+ f"检测到权威信源反驳当前查询前提({c_count} 条条目与主张冲突)"
690
+ )
603
691
  except Exception as e: # fail-open:语义层不阻断核验
604
692
  _log(f"语义证据层失败: {type(e).__name__}")
605
693
 
@@ -21,20 +21,24 @@ def _jsrun_enabled() -> bool:
21
21
  return env_flag("ARGO_FETCH_JSRUN")
22
22
 
23
23
 
24
+ _MINI_RACER_OK: bool | None = None
25
+
26
+
27
+ def _mini_racer_available() -> bool:
28
+ """一次性探测 py_mini_racer 是否就绪,缺依赖时 O(1) 短路。"""
29
+ global _MINI_RACER_OK
30
+ if _MINI_RACER_OK is None:
31
+ import importlib.util
32
+ _MINI_RACER_OK = importlib.util.find_spec("py_mini_racer") is not None
33
+ return _MINI_RACER_OK
34
+
35
+
24
36
  def _jsrun_challenge_fetch(url: str, html: str, max_chars: int = 8000,
25
37
  timeout: float = 8.0,
26
38
  backoff_budget_s: float | None = None) -> dict:
27
- """用 js-run 执行挑战页 JS,尝试获取 clearance cookie 后重试请求。
28
-
29
- 只处理「环境探测 + 纯计算」型挑战脚本(v0 面)。失败时返回空结果,
30
- 由调用方降级到 tinyfish/CDP。
31
-
32
- 重试请求用 curl_cffi Chrome 指纹 impersonate(站点按 TLS 指纹风控,
33
- 裸 Python 指纹被静默拦截)。退避重试 3 次(间隔 5s/10s)。
34
- `backoff_budget_s`(秒)给整段重试设墙钟上界:传入时退避睡眠与后续
35
- 尝试都不得越过它——此前 sleep(5)+sleep(10) 不受链级预算约束,cookie
36
- 拿到而三连败时可在 fetch 链内部多耗 ~30s(2026-10-06 审查定位)。
37
- """
39
+ """用 js-run 执行挑战页 JS,尝试获取 clearance cookie 后重试请求。"""
40
+ if not html or not _mini_racer_available():
41
+ return {}
38
42
  import re as _re
39
43
  import time as _time
40
44
 
@@ -55,6 +55,7 @@ if SCRIPT_DIR not in sys.path:
55
55
  # engine_states 是状态词表唯一真源(2026-11-09 收口)
56
56
  import fetch_render_tinyfish as _render_tinyfish
57
57
  import engine_states
58
+ from except_sets import IO_BENIGN, OPT_IMPORT, SHAPE_BENIGN # 收窄词汇表(2026-11-13 裸吞收口)
58
59
 
59
60
  # 解码统一入口(2026-10-26,charset 是只依赖 re 的叶子模块,顶层导入无负担):
60
61
  # urllib 兜底车道与主链共享「头声明 > meta 嗅探 > 猜测链」,GBK 老站不再满屏 U+FFFD
@@ -134,12 +135,12 @@ def extract_content(html: str, max_chars: int = 8000) -> tuple[str, str]:
134
135
  content, title = extract_readability(html, max_chars=max_chars)
135
136
  if content.strip():
136
137
  return _cut(content, max_chars), title.strip()
137
- except Exception:
138
+ except OPT_IMPORT + SHAPE_BENIGN:
138
139
  pass
139
140
  ext = ContentExtractor()
140
141
  try:
141
142
  ext.feed(html)
142
- except Exception:
143
+ except SHAPE_BENIGN:
143
144
  pass
144
145
  ext._blocks.sort(key=lambda x: x[0], reverse=True)
145
146
  content = "\n\n".join(text for _, text in ext._blocks[:10])
@@ -499,7 +500,7 @@ def _md_variant_fetch(url: str, max_chars: int = 8000,
499
500
  "User-Agent": "argo-fetch-v3/1.0 (+local-research; md-variant)",
500
501
  "Accept": "text/markdown, text/plain;q=0.9, */*;q=0.8",
501
502
  })
502
- except Exception:
503
+ except OPT_IMPORT + IO_BENIGN:
503
504
  continue
504
505
  if resp.get("status", 0) != 200 or not resp.get("text"):
505
506
  continue
@@ -625,7 +626,7 @@ def _identity_remember_mobile(host: str) -> None:
625
626
  # 并发抓取进程会互相搬走临时文件,身份记忆静默丢失。
626
627
  _paths.atomic_write_json(Path(_identity_path()), _identity_mem, indent=None)
627
628
  _identity_dirty = False
628
- except Exception:
629
+ except IO_BENIGN:
629
630
  pass
630
631
 
631
632
 
@@ -858,7 +859,7 @@ def _archive_truncated(url: str, text: str, delivered: str, kind: str,
858
859
  extra[f"full_{kind}_path"] = path
859
860
  if primary:
860
861
  extra["full_text_path"] = path
861
- except Exception:
862
+ except OPT_IMPORT + IO_BENIGN:
862
863
  pass
863
864
 
864
865
 
@@ -899,7 +900,7 @@ def _make_result(url: str, html: str, max_chars: int,
899
900
  try:
900
901
  from article_meta import extract_article_meta
901
902
  result.update(extract_article_meta(html, url))
902
- except Exception:
903
+ except OPT_IMPORT + SHAPE_BENIGN:
903
904
  pass
904
905
  result.update(extra)
905
906
  return result
@@ -1306,7 +1307,7 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1306
1307
  _declared_ok = _video.get("content_ok")
1307
1308
  try:
1308
1309
  _video = _assess_quality(_video)
1309
- except Exception:
1310
+ except SHAPE_BENIGN:
1310
1311
  pass
1311
1312
  _video["content_ok"] = bool(_declared_ok)
1312
1313
  _video["page_type"] = "video"
@@ -1314,22 +1315,9 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1314
1315
  _video["cached"] = False
1315
1316
  return _strip_html_unless_needed(_video, need_html)
1316
1317
 
1317
- # robots.txt 尊重(合规检查):被禁路径直接拒绝,抓取失败放行
1318
- try:
1319
- from robots_guard import robots_blocked
1320
- if robots_blocked(url, timeout=min(timeout, 5.0)):
1321
- result = _make_result(url, "", 0, engine_states.FETCH_ROBOTS_BLOCKED, ok=False,
1322
- error="robots.txt 禁止抓取")
1323
- result = _assess_quality(result)
1324
- result["cached"] = False
1325
- return _strip_html_unless_needed(result, need_html)
1326
- except ImportError:
1327
- pass
1328
-
1329
- # 微信公众号文章走专用降级链(HTTP→CDP→搜狗,唯一来源 wechat_article.py,
1330
- # 即 `argo wx` 同一实现):通用 HTML 链对 mp.weixin 只能拿到 JS 骨架,
1331
- # 正文全空(2026-11-01 实测缺口:fetch 对 mp.weixin 零处理)。robots 已在
1332
- # 上方拦截,这里只做域名分流;need_html/actions/force_browser 同视频分支让路。
1318
+ # 微信专用降级链(HTTP→CDP→搜狗,wechat_article.py,`argo wx` 同实现——用户
1319
+ # 显式取文不走匿名爬虫 robots 口径)【必须在 robots 闸前】mp.weixin/robots.txt
1320
+ # 是 Disallow: /(11-15 实测),闸先跑分支永不可达(6ebb625 实跑复现)。让路同前。
1333
1321
  if (_is_wechat_article_url(url) and not need_html and not actions
1334
1322
  and not force_browser):
1335
1323
  try:
@@ -1352,7 +1340,7 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1352
1340
  }
1353
1341
  try:
1354
1342
  _wx_result = _assess_quality(_wx_result)
1355
- except Exception:
1343
+ except SHAPE_BENIGN:
1356
1344
  pass
1357
1345
  _wx_result["cached"] = False
1358
1346
  return _strip_html_unless_needed(_wx_result, need_html)
@@ -1368,6 +1356,18 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1368
1356
  "cached": False,
1369
1357
  }, need_html)
1370
1358
 
1359
+ # robots.txt 尊重(合规检查):被禁路径直接拒绝,抓取失败放行
1360
+ try:
1361
+ from robots_guard import robots_blocked
1362
+ if robots_blocked(url, timeout=min(timeout, 5.0)):
1363
+ result = _make_result(url, "", 0, engine_states.FETCH_ROBOTS_BLOCKED, ok=False,
1364
+ error="robots.txt 禁止抓取")
1365
+ result = _assess_quality(result)
1366
+ result["cached"] = False
1367
+ return _strip_html_unless_needed(result, need_html)
1368
+ except ImportError:
1369
+ pass
1370
+
1371
1371
  # 登录态车道(A2):站点有 argo auth 持久 profile → 跳过匿名链直进浏览器。
1372
1372
  # 匿名 HTTP 对已登录站只会拿到「登出态」内容——那是成功的假象,比失败更糟。
1373
1373
  # 判断本体在 browser_auth(含开关与 use_browser_fallback=False 让路);
@@ -1419,7 +1419,7 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1419
1419
  if (out.get("quality_breakdown") or {}).get("version") != _v:
1420
1420
  out = _quality.assess(out)
1421
1421
  out["quality_basis"] = "rescored"
1422
- except Exception:
1422
+ except SHAPE_BENIGN:
1423
1423
  pass
1424
1424
  out["cached"] = True
1425
1425
  out["cache_level"] = hit.get("_cache_level", engine_states.CACHE_LEVEL_UNKNOWN)
@@ -1624,7 +1624,7 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1624
1624
  result = tf
1625
1625
  # tinyfish 未命中(关闭/缺 key/失败/短内容)才起本地 Chrome——
1626
1626
  # 内容过短的成功响应与失败同样需要继续降级
1627
- if result.get("fetch_method") != _render_tinyfish.TINYFISH_METHOD:
1627
+ if result.get("fetch_method") not in (_render_tinyfish.TINYFISH_METHOD, engine_states.FETCH_JSRUN_CHALLENGE):
1628
1628
  browser_result = _browser_fetch(
1629
1629
  url, max_chars, timeout=_level_timeout(15.0))
1630
1630
  if browser_result.get("success") or not result.get("success"):
@@ -1645,7 +1645,7 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1645
1645
  from article_meta import extract_article_meta
1646
1646
  for _mk, _mv in extract_article_meta(result["html"], url).items():
1647
1647
  result.setdefault(_mk, _mv)
1648
- except Exception:
1648
+ except OPT_IMPORT + SHAPE_BENIGN:
1649
1649
  pass
1650
1650
 
1651
1651
  # 写 URL 缓存(不存大块 html,省空间)
@@ -1677,7 +1677,7 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1677
1677
  if ev:
1678
1678
  to_store[FETCH_EVIDENCE_KEY] = {
1679
1679
  k: v for k, v in ev.items() if k != "url"}
1680
- except Exception:
1680
+ except OPT_IMPORT + SHAPE_BENIGN:
1681
1681
  pass
1682
1682
  SearchCache().set_fetch(url, to_store, ttl=ttl)
1683
1683
  except Exception:
@@ -153,13 +153,15 @@ def _evict() -> None:
153
153
  """
154
154
  items = entries()
155
155
  total = sum(e["bytes"] for e in items)
156
+ dropped = 0
156
157
 
157
158
  def _drop(seq: list) -> int:
158
- removed = 0
159
+ nonlocal dropped
159
160
  try:
160
161
  os.unlink(seq["path"])
161
162
  except Exception:
162
163
  return 0
164
+ dropped += 1
163
165
  return seq["bytes"]
164
166
 
165
167
  while len(items) > MAX_FILES:
@@ -167,3 +169,42 @@ def _evict() -> None:
167
169
  while items and total > MAX_TOTAL_BYTES:
168
170
  total -= _drop(items.pop())
169
171
 
172
+ # 淘汰发生了才对账:台账与正文同生命周期。追加式台账曾只写不截断,
173
+ # 正文有 MAX_FILES/MAX_TOTAL 淘汰而台账没有——生产库实测 688 行里
174
+ # 386 行(56%)指向已淘汰文件,纯死行。
175
+ if dropped:
176
+ _reconcile_index()
177
+
178
+
179
+ def _reconcile_index() -> None:
180
+ """把 index.jsonl 重写为与现存正文对齐的最小台账;失败不影响主流程。
181
+
182
+ 回读只按 URL 哈希定位(见模块头),台账只是给人看的列举台账——重写
183
+ 坏了最多丢列举能力,不丢回读能力。同一文件多次存档的记录保留最后一条
184
+ (追加序里最后出现的行元数据最新)。
185
+ """
186
+ try:
187
+ d = store_dir()
188
+ idx = d / "index.jsonl"
189
+ if not idx.is_file():
190
+ return
191
+ alive = {e["path"] for e in entries()}
192
+ last: dict[str, str] = {}
193
+ with idx.open(encoding="utf-8") as f:
194
+ for raw in f:
195
+ line = raw.strip()
196
+ if not line:
197
+ continue
198
+ try:
199
+ rec = json.loads(line)
200
+ except Exception:
201
+ continue # 坏行丢弃,不让一行脏数据卡住整个台账
202
+ p = rec.get("path")
203
+ if isinstance(p, str):
204
+ last[p] = line
205
+ kept = [last[p] for p in last if p in alive]
206
+ import argo_paths
207
+ argo_paths.atomic_write_text(idx, "".join(l + "\n" for l in kept))
208
+ except Exception:
209
+ pass
210
+