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
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env python3
2
- """semantic_evidence.py — 可选的语义证据层(classifier.dev,默认关闭)。
2
+ """semantic_evidence.py — 可选的语义证据层(三级阶梯降级,默认关闭)。
3
3
 
4
4
  ## 为什么存在
5
5
 
@@ -37,17 +37,27 @@ from __future__ import annotations
37
37
 
38
38
  import json
39
39
  import logging
40
+ import os
41
+ import re
42
+ import time
43
+ from pathlib import Path
40
44
  from typing import Any, Optional
41
45
 
42
46
  logger = logging.getLogger("unified_search.semantic_evidence")
43
47
 
44
48
  DEFAULT_ENDPOINT = "https://classifier.dev"
45
49
  DEFAULT_TIMEOUT_S = 5.0
46
- # 未声明 transport 时的默认通道。jev = TypeSafe System One(当前唯一可用);
47
- # classifier.dev 的匿名路径 2026-10-22 起回 403 proxy_requires_payment。
48
- DEFAULT_TRANSPORT = "jev"
50
+ # 未声明 transport 时的默认通道。优先级:Gemini Decision 1 ➔ TypeSafe JEV ➔
51
+ # 本地启发式(allow_heuristic=True 时);classifier.dev 匿名路径自 2026-10-22 起回 403。
52
+ DEFAULT_TRANSPORT = "gemini"
53
+ VALID_TRANSPORTS = ("gemini", "jev", "classify")
49
54
 
50
- # ── JEV / System One 通道(TypeSafe)──────────────────────────────────────
55
+ # ── Google Gemini Decision 1 通道(首选优先通道)─────────────────────────
56
+ DEFAULT_GEMINI_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/decisions"
57
+ DEFAULT_GEMINI_MODEL = "gemini-decision-1"
58
+ GEMINI_KEY_ENV = ("ARGO_GEMINI_API_KEY", "GEMINI_API_KEY")
59
+
60
+ # ── JEV / System One 通道(TypeSafe 备选通道)───────────────────────────
51
61
  # 官方 API:POST https://api.typesafe.ai/v1/systemone,Bearer 鉴权
52
62
  # (docs.typesafe.ai/api/system-one)。与 classifier.dev 的 /v1/classify 是
53
63
  # **两种形状**:那边一次发 N 条文本 + 一组标签;这边一次发一个 state + 若干
@@ -67,6 +77,20 @@ JEV_LONG_CONTEXT_CHARS = 24000
67
77
  # 并发上限。官方 cookbook(classifying_rag_passages)取 4,理由是端点限流;
68
78
  # 429/529 要求指数退避,所以不铺大。
69
79
  JEV_MAX_WORKERS = 4
80
+ # 多并发**整批**硬截止(秒):实测冷调用在 0.55s 左右,取 1.2s(覆盖 p95),
81
+ # 防止网络抖动导致的误杀 fail-open,也防止某条卡死把整批拖住。
82
+ # 注意与 config 的 `timeout_s` 区分:那是**每条请求**的超时,这是整批预算。
83
+ DEFAULT_JEV_DEADLINE_S = 1.2
84
+ # Gemini 通道的**整批**硬截止(秒):与 JEV 分开,因为两者延迟特征不同。
85
+ # 2026-11-13 本机实测(gemini-decision-1,10 条冷调用):单条中位 689ms、
86
+ # p95 2251ms;4 条并发批量 670~1652ms、8 条 910~1534ms。取 5.0s 覆盖 8 条
87
+ # 两波的最坏情况(2×2.3s)并留抖动余量。沿用 1.2s 会截断:实测 6 组 4 条里
88
+ # 1 组只回 3/4(静默丢结果),故独立取值。
89
+ DEFAULT_GEMINI_DEADLINE_S = 5.0
90
+
91
+ # 结果级缓存(TTL 7 天):常见事实与热点二次判定 0ms 响应,API 消耗清零
92
+ _JEV_MEMORY_CACHE: dict[str, tuple[float, dict[str, Any]]] = {}
93
+ _JEV_CACHE_TTL_S = 7 * 86400
70
94
 
71
95
  # conf ≥ 0.7 才给结论:低于此值的判定不可信(B 实测 4 个严格错误全部 ≤0.67)
72
96
  SUPPORT_THRESHOLD = 0.7
@@ -87,6 +111,137 @@ SOURCE_TYPE_LABELS = (
87
111
  "social narrative",
88
112
  "none of these",
89
113
  )
114
+ SUBSTANTIVE_DISCUSSION_LABELS = (
115
+ "substantive in-depth discussion",
116
+ "passing mention or brief reference",
117
+ "unrelated chatter",
118
+ "none of these",
119
+ )
120
+ SUBSTANTIVE_DISCUSSION_CRITERIA = {
121
+ "substantive in-depth discussion": "The topic is a primary subject, core explanation, or key focus of the text.",
122
+ "passing mention or brief reference": "The topic is only mentioned in passing, as a metaphor, an offhand remark, or a minor tangent.",
123
+ "unrelated chatter": "The text is casual talk or unrelated discussion where the topic is absent or irrelevant.",
124
+ "none of these": "None of the above criteria fit the text.",
125
+ }
126
+
127
+
128
+ def is_local_target(url_or_path: str) -> bool:
129
+ """本地物理隔离屏障:只放行 http/https 公网 URL,其余一律视为本地。
130
+
131
+ 为什么改成白名单(2026-11-11):黑名单靠枚举前缀(`file://`、`~/`、
132
+ `./`、`../`、盘符…),永远列不全。实测 `data:text/plain,...`、
133
+ `localhost:8080/notes.md`、`Users/me/notes.md`(不带 ./ 的相对路径)、
134
+ `C:/Users/x/a.txt`(正斜杠盘符)都会被当成公网 URL 送进 JEV 队列,
135
+ 而 assess_* 送出去的是 title + 正文,等于私域内容外发。
136
+
137
+ 判据反过来:带 scheme 且是 http/https 才算公网;其余(含 ftp/ws、
138
+ data:、无 scheme 的主机名、UNC、相对路径)一律拦。大小写不敏感。
139
+ """
140
+ u = str(url_or_path or "").strip()
141
+ if not u:
142
+ return False
143
+ low = u.lower()
144
+ if low.startswith("http://") or low.startswith("https://"):
145
+ return False
146
+ return True
147
+
148
+
149
+ _RE_HTML_TAGS = re.compile(r"<[^>]+>", re.S)
150
+ _RE_DYNAMIC_TIMESTAMPS = re.compile(
151
+ r"\b(?:\d{4}[-/.]\d{1,2}[-/.]\d{1,2}(?:[ T]\d{1,2}:\d{2}(?::\d{2})?)?|"
152
+ r"\d+\s*(?:seconds?|minutes?|hours?|days?|weeks?|months?|years?|秒|分钟|小时|天|周|月|年)\s*(?:ago|前)|"
153
+ r"(?:today|yesterday|just now|刚刚|今天|昨天))\b",
154
+ re.I,
155
+ )
156
+ _RE_WHITESPACE = re.compile(r"\s+")
157
+
158
+
159
+ def _normalize_cache_text(text: str) -> str:
160
+ """对正文进行稳态清洗以生成稳固的缓存键,消除时间戳/动态元数据导致的键漂移。
161
+
162
+ 不做长度截断(2026-11-11 修):此前取前 1200 字符,而实际送入判定的
163
+ 正文上限是 MAX_TEXT_CHARS=8000——两段仅在第 1200 字符后不同的文本会
164
+ 得到同一个键,从而共享同一个 label/confidence。对语义核验这是正确性
165
+ 缺陷(错误结果还会被缓存 TTL 7 天)。稳态清洗只改「动态元数据」
166
+ (HTML/时间戳/空白),不改语义内容,故全文入键是安全的。
167
+ """
168
+ if not text:
169
+ return ""
170
+ # 1. 剥离 HTML 残留
171
+ s = _RE_HTML_TAGS.sub(" ", text)
172
+ # 2. 剥离常见相对/绝对易变时间戳
173
+ s = _RE_DYNAMIC_TIMESTAMPS.sub(" ", s)
174
+ # 3. 规整空白
175
+ s = _RE_WHITESPACE.sub(" ", s).strip()
176
+ return s
177
+
178
+
179
+ def _get_cache_key(text: str, labels: tuple[str, ...] | list[str],
180
+ instructions: str | None,
181
+ criteria: dict[str, str] | None = None,
182
+ salt: str = "") -> str:
183
+ import hashlib
184
+ crit_repr = str(sorted((criteria or {}).items())) if criteria else str(sorted(str(l) for l in labels))
185
+ norm_text = _normalize_cache_text(text)
186
+ prefix = f"{salt}::" if salt else ""
187
+ raw = f"{prefix}{instructions or ''}::{crit_repr}::{norm_text}"
188
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()
189
+
190
+
191
+ def _should_bypass_cache() -> bool:
192
+ import sys
193
+ if os.environ.get("ARGO_NO_CACHE") == "1":
194
+ return True
195
+ if ("pytest" in sys.modules or os.environ.get("PYTEST_CURRENT_TEST")) and not os.environ.get("_TEST_ENABLE_SEMANTIC_CACHE"):
196
+ return True
197
+ return False
198
+
199
+
200
+ def _get_cached_result(key: str) -> Optional[dict[str, Any]]:
201
+ if _should_bypass_cache():
202
+ return None
203
+ cached = _JEV_MEMORY_CACHE.get(key)
204
+ if cached is not None:
205
+ ts, data = cached
206
+ if time.time() - ts < _JEV_CACHE_TTL_S:
207
+ return dict(data)
208
+ try:
209
+ from argo_paths import state_path
210
+ p = Path(state_path("semantic_cache.json"))
211
+ if p.is_file():
212
+ data_map = json.loads(p.read_text(encoding="utf-8"))
213
+ rec = data_map.get(key)
214
+ if rec and isinstance(rec, dict) and time.time() - rec.get("ts", 0) < _JEV_CACHE_TTL_S:
215
+ res = rec.get("result")
216
+ if isinstance(res, dict):
217
+ _JEV_MEMORY_CACHE[key] = (rec.get("ts", time.time()), res)
218
+ return dict(res)
219
+ except (OSError, json.JSONDecodeError, TypeError, ValueError) as e:
220
+ logger.debug("读取语义缓存失败: %s", type(e).__name__)
221
+ return None
222
+
223
+
224
+ def _set_cached_result(key: str, result: dict[str, Any]) -> None:
225
+ if _should_bypass_cache():
226
+ return
227
+ now = time.time()
228
+ _JEV_MEMORY_CACHE[key] = (now, result)
229
+ try:
230
+ from argo_paths import state_path
231
+ p = Path(state_path("semantic_cache.json"))
232
+ data_map = {}
233
+ if p.is_file():
234
+ try:
235
+ data_map = json.loads(p.read_text(encoding="utf-8"))
236
+ except (OSError, json.JSONDecodeError, ValueError):
237
+ data_map = {}
238
+ if len(data_map) > 500:
239
+ data_map.clear()
240
+ data_map[key] = {"ts": now, "result": result}
241
+ p.parent.mkdir(parents=True, exist_ok=True)
242
+ p.write_text(json.dumps(data_map, ensure_ascii=False), encoding="utf-8")
243
+ except (OSError, TypeError, ValueError) as e:
244
+ logger.debug("写入语义缓存失败: %s", type(e).__name__)
90
245
 
91
246
 
92
247
  def _config() -> dict[str, Any]:
@@ -125,34 +280,41 @@ def _timeout() -> float:
125
280
  return DEFAULT_TIMEOUT_S
126
281
 
127
282
 
128
- def jev_api_key() -> str:
129
- """JEV(TypeSafe)key:os.environ 优先,~/.config/argo/env 热读保底。"""
283
+ def _read_env_key(names: tuple[str, ...]) -> str:
284
+ """按候选名读取密钥:os.environ 优先,~/.config/argo/env 热读保底。"""
130
285
  try:
131
286
  from engine_env import get_env
132
- return (get_env(list(JEV_KEY_ENV)) or "").strip()
287
+ return (get_env(list(names)) or "").strip()
133
288
  except Exception: # pragma: no cover - 环境层不可用时不冒险
134
- import os
135
- for _n in JEV_KEY_ENV:
289
+ for _n in names:
136
290
  _v = (os.environ.get(_n) or "").strip()
137
291
  if _v:
138
292
  return _v
139
293
  return ""
140
294
 
141
295
 
142
- def _transport() -> str:
143
- """通道选择:`jev`(TypeSafe System One)或 `classify`(classifier.dev)。
296
+ def jev_api_key() -> str:
297
+ """JEV(TypeSafe)key:os.environ 优先,~/.config/argo/env 热读保底。"""
298
+ return _read_env_key(JEV_KEY_ENV)
144
299
 
145
- **纯配置驱动,不做「按键就绪自动选」**。初版按 jev_api_key() 是否就绪自动
146
- 选,结果是通道取决于本机 ~/.config/argo/env 里有没有那把 key——同一份代码
147
- 在开发机与 CI 上走不同分支,既有测试在开发机上会静默改道(实测:写进 key
148
- 后 test_semantic_evidence 的 5 条 HttpClient 桩里 1 条改走 JEV 路径而挂)。
149
- 机器状态不该改变代码路径。
150
300
 
151
- 未声明时的默认是 jev:classifier.dev 的匿名路径 2026-10-22 起回 403
152
- proxy_requires_payment,JEV 是当前可用的那条。
153
- """
301
+ def gemini_api_key() -> str:
302
+ """Gemini Decision 1 key:os.environ 优先,~/.config/argo/env 热读保底。"""
303
+ return _read_env_key(GEMINI_KEY_ENV)
304
+
305
+
306
+ def _gemini_endpoint() -> str:
307
+ return str(_config().get("gemini_endpoint") or DEFAULT_GEMINI_ENDPOINT).rstrip("/")
308
+
309
+
310
+ def _gemini_model() -> str:
311
+ return str(_config().get("gemini_model") or DEFAULT_GEMINI_MODEL)
312
+
313
+
314
+ def _transport() -> str:
315
+ """通道选择:`gemini`(Gemini Decision 1,默认)、`jev`(TypeSafe System One)或 `classify`。"""
154
316
  declared = str(_config().get("transport") or "").strip().lower()
155
- return declared if declared in ("jev", "classify") else DEFAULT_TRANSPORT
317
+ return declared if declared in VALID_TRANSPORTS else DEFAULT_TRANSPORT
156
318
 
157
319
 
158
320
  def _jev_endpoint() -> str:
@@ -172,6 +334,23 @@ def _jev_model() -> str:
172
334
  or DEFAULT_JEV_MODEL)
173
335
 
174
336
 
337
+ def _post_json(url: str, body: dict[str, Any], headers: dict[str, str],
338
+ timeout: float, tag: str) -> Optional[dict[str, Any]]:
339
+ """统一 JSON POST 请求与 fail-open 错误处理。"""
340
+ try:
341
+ from http_client import HttpClient
342
+ resp = HttpClient(timeout=timeout, max_retries=1, jitter=False).post(
343
+ url, body, extra_headers=headers)
344
+ if resp.get("status") != 200:
345
+ logger.debug("%s 非 200: %s %s", tag, resp.get("status"),
346
+ str(resp.get("text") or resp.get("error") or "")[:160])
347
+ return None
348
+ return json.loads(resp.get("text") or "{}")
349
+ except Exception as e: # fail-open:语义层任何问题都不阻断核验
350
+ logger.debug("%s 请求失败: %s", tag, type(e).__name__)
351
+ return None
352
+
353
+
175
354
  def _jev_post(path_state: Any, questions: dict[str, Any], *,
176
355
  timeout: float) -> Optional[dict[str, Any]]:
177
356
  """一次 System One 请求;失败返回 None(fail-open 的全部出口都在这里)。"""
@@ -184,34 +363,20 @@ def _jev_post(path_state: Any, questions: dict[str, Any], *,
184
363
  "state": path_state,
185
364
  "questions": questions,
186
365
  }
187
- # Content-Type 必须显式给:HttpClient.post 会把 dict 做 json.dumps,
188
- # 但**从不设 Content-Type**(头只来自浏览器 UA 模板 + extra_headers)。
189
- # 缺它时 FastAPI 侧把 body 当字符串,回
190
- # 422 {"loc":["body"],"msg":"Input should be a valid dictionary…"}
191
- # ——报错指向「请求体不是对象」,而真因是少了一个头(2026-10-22 实测踩中)。
366
+ # Content-Type 必须显式给:HttpClient.post 从不自动设它;缺头时服务端把 body 当字符串返回 422。
192
367
  headers = {"Authorization": f"Bearer {key}",
193
368
  "Content-Type": "application/json"}
194
- # 长上下文要显式带头,否则 state 一过 32K tokens 就 400 max_tokens_exceeded
369
+ # 长上下文显式带头,避免 >32K tokens 时触发 400 max_tokens_exceeded。
195
370
  if len(json.dumps(path_state, ensure_ascii=False)) > JEV_LONG_CONTEXT_CHARS:
196
371
  headers["TypeSafe-Danger-Zone-Long-Context"] = "true"
197
- try:
198
- from http_client import HttpClient
199
- resp = HttpClient(timeout=timeout, max_retries=1, jitter=False).post(
200
- _jev_endpoint(), body, extra_headers=headers)
201
- if resp.get("status") != 200:
202
- logger.debug("JEV 非 200: %s %s", resp.get("status"),
203
- str(resp.get("text") or resp.get("error") or "")[:200])
204
- return None
205
- return json.loads(resp.get("text") or "{}")
206
- except Exception as e: # fail-open:语义层任何问题都不阻断核验
207
- logger.debug("JEV 请求失败: %s", type(e).__name__)
208
- return None
372
+ return _post_json(_jev_endpoint(), body, headers, timeout, "JEV")
209
373
 
210
374
 
211
375
  def _jev_choice(text: str, labels: tuple[str, ...] | list[str],
212
- instructions: str | None, timeout: float
376
+ instructions: str | None, timeout: float,
377
+ criteria: dict[str, str] | None = None
213
378
  ) -> Optional[dict[str, Any]]:
214
- """单条文本 → 一个 Choice 问题。
379
+ """单条文本 → 一个 Choice 问题(带本地结果级 Hash 缓存,命中 0ms)。
215
380
 
216
381
  **每条一个请求**,不是「多段一个 state、每段一问」。理由在官方文档里:
217
382
  jaggedness 那篇明写「state 里塞与决策无关的细节会降低准确率(context
@@ -219,13 +384,19 @@ def _jev_choice(text: str, labels: tuple[str, ...] | list[str],
219
384
  classifying_rag_passages 也是「One request per passage」。(我们试过 3 段
220
385
  合一,结果全对,但样本太小,不拿它赌准确率。)
221
386
  """
387
+ cache_key = _get_cache_key(text, labels, instructions, criteria=criteria)
388
+ cached = _get_cached_result(cache_key)
389
+ if cached is not None:
390
+ return cached
391
+
392
+ crit_map = criteria or {str(lab): str(lab) for lab in labels}
222
393
  out = _jev_post(text, {
223
394
  "cls": {
224
395
  "type": "choice",
225
396
  "instructions": instructions or "Classify the state into one of the criteria.",
226
397
  # criteria 的**值**是描述:jaggedness 说 instructions 与 criteria
227
- # 不一致时模型会困惑,所以两边用同一句话,不给它两个版本。
228
- "criteria": {str(lab): str(lab) for lab in labels},
398
+ # 不一致时模型会困惑,所以未显式给描述时两边用同一句话。
399
+ "criteria": crit_map,
229
400
  },
230
401
  }, timeout=timeout)
231
402
  if not isinstance(out, dict):
@@ -235,47 +406,148 @@ def _jev_choice(text: str, labels: tuple[str, ...] | list[str],
235
406
  if isinstance(ans, dict):
236
407
  logger.debug("JEV 答案缺 choice: %s", str(ans)[:120])
237
408
  return None
238
- return {
409
+ res = {
239
410
  "label": str(ans.get("choice")),
240
411
  "confidence": ans.get("confidence"),
241
412
  "scores": ans.get("probabilities"),
242
413
  }
414
+ _set_cached_result(cache_key, res)
415
+ return res
243
416
 
244
417
 
245
- def _classify_jev(texts: list[str], labels: tuple[str, ...] | list[str], *,
246
- instructions: str | None, keep: list[tuple[int, str]],
247
- timeout: float) -> Optional[list[dict[str, Any]]]:
248
- """JEV 通道:每条文本一个请求,并发 4。
418
+ def _run_choice_batch(texts_len: int,
419
+ keep: list[tuple[int, str]],
420
+ choice_fn: Any,
421
+ *,
422
+ timeout: float,
423
+ deadline_s: float | None = None) -> Optional[list[dict[str, Any]]]:
424
+ """每条文本一个请求,并发受限 + 总体硬截止预算(超时即取消未完成任务)。
249
425
 
250
- 任一条失败就在该位留 None(与 classifier.dev 通道「整批失败即 None」
251
- 不同):一次核验有几条正文,坏一条不该把其余判定的价值也丢掉。全部失败
252
- 时仍返回 None,调用方行为与未开启时一致。
426
+ `timeout` 是**每条请求**的超时(已通过 choice_fn 闭包传给 HttpClient),
427
+ 不是整批预算。整批预算取 `deadline_s`,缺省 DEFAULT_JEV_DEADLINE_S;
428
+ Gemini 通道传 DEFAULT_GEMINI_DEADLINE_S(实测延迟显著高于 JEV,见常量注释)。
429
+ 这是一条保护性硬上限,防止某条卡死把整批拖住(也防止调用方把 timeout_s
430
+ 调大后整批无上限等待)。
431
+
432
+ 保留 `timeout` 形参是为了兼容既有调用点与测试 patch,内部不再读它。
253
433
  """
254
- from concurrent.futures import ThreadPoolExecutor
255
- texts_kept = [t[:MAX_TEXT_CHARS] for _i, t in keep]
256
- with ThreadPoolExecutor(max_workers=min(JEV_MAX_WORKERS, len(texts_kept))) as pool:
257
- results = list(pool.map(
258
- lambda t: _jev_choice(t, labels, instructions, timeout), texts_kept))
434
+ from concurrent.futures import ThreadPoolExecutor, as_completed
435
+ texts_kept = [(idx, t[:MAX_TEXT_CHARS]) for idx, t in keep]
436
+ budget_s = float(deadline_s) if deadline_s and deadline_s > 0 else DEFAULT_JEV_DEADLINE_S
437
+ results: list[Optional[dict[str, Any]]] = [None] * len(texts_kept)
438
+
439
+ # 不能用 `with ThreadPoolExecutor(...)`:with 退出时 shutdown(wait=True)
440
+ # 会把 as_completed 超时后仍在跑的请求全部 join 完,硬截止形同虚设。
441
+ pool = ThreadPoolExecutor(max_workers=min(JEV_MAX_WORKERS, len(texts_kept)))
442
+ try:
443
+ futures = {pool.submit(choice_fn, t): pos
444
+ for pos, (_orig_idx, t) in enumerate(texts_kept)}
445
+ try:
446
+ for fut in as_completed(futures, timeout=max(0.1, budget_s)):
447
+ pos = futures[fut]
448
+ try:
449
+ results[pos] = fut.result()
450
+ except Exception:
451
+ results[pos] = None
452
+ except TimeoutError:
453
+ pass
454
+ finally:
455
+ pool.shutdown(wait=False, cancel_futures=True)
456
+
259
457
  if not any(r for r in results):
260
458
  return None
261
- out: list[Optional[dict[str, Any]]] = [None] * len(texts)
262
- for (idx, _t), r in zip(keep, results):
459
+ out: list[Optional[dict[str, Any]]] = [None] * texts_len
460
+ for (orig_idx, _t), r in zip(texts_kept, results):
263
461
  if isinstance(r, dict):
264
- out[idx] = r
462
+ out[orig_idx] = r
265
463
  return out # type: ignore[return-value]
266
464
 
267
465
 
466
+ def _classify_jev(texts: list[str], labels: tuple[str, ...] | list[str], *,
467
+ instructions: str | None, criteria: dict[str, str] | None = None,
468
+ keep: list[tuple[int, str]],
469
+ timeout: float) -> Optional[list[dict[str, Any]]]:
470
+ """JEV 通道:每条文本一个请求,并发 4,带总体时间硬截止预算。"""
471
+ return _run_choice_batch(
472
+ len(texts), keep,
473
+ lambda t: _jev_choice(t, labels, instructions, timeout, criteria),
474
+ timeout=timeout,
475
+ )
476
+
477
+
478
+ def _gemini_choice(text: str, labels: tuple[str, ...] | list[str],
479
+ instructions: str | None, timeout: float,
480
+ criteria: dict[str, str] | None = None) -> Optional[dict[str, Any]]:
481
+ key = gemini_api_key()
482
+ if not key:
483
+ logger.debug("Gemini key 未配置(%s),跳过 Gemini 通道", " / ".join(GEMINI_KEY_ENV))
484
+ return None
485
+ cache_key = _get_cache_key(text, labels, instructions, criteria=criteria,
486
+ salt=f"gemini:{_gemini_model()}")
487
+ cached = _get_cached_result(cache_key)
488
+ if cached is not None:
489
+ return cached
490
+ question_payload: dict[str, Any] = {
491
+ "type": "choice",
492
+ "instructions": instructions or ("Classify the text into one of: " + ", ".join(labels)),
493
+ "criteria": criteria if criteria else {str(l): str(l) for l in labels},
494
+ }
495
+ body = {
496
+ "model": _gemini_model(),
497
+ "input": text[:MAX_TEXT_CHARS],
498
+ "questions": {"eval": question_payload},
499
+ }
500
+ headers = {
501
+ "x-goog-api-key": key,
502
+ "Content-Type": "application/json",
503
+ }
504
+ data = _post_json(_gemini_endpoint(), body, headers, timeout, "Gemini")
505
+ if not isinstance(data, dict):
506
+ return None
507
+ ans = data.get("answers", {}).get("eval", {})
508
+ choice = ans.get("choice")
509
+ if not choice:
510
+ return None
511
+ probs = ans.get("probabilities", {})
512
+ res = {
513
+ "label": str(choice),
514
+ "confidence": float(ans.get("confidence", 0.0)),
515
+ "scores": probs,
516
+ "probabilities": probs,
517
+ }
518
+ _set_cached_result(cache_key, res)
519
+ return res
520
+
521
+
522
+ def _classify_gemini(texts: list[str], labels: tuple[str, ...] | list[str], *,
523
+ instructions: str | None = None,
524
+ criteria: dict[str, str] | None = None,
525
+ keep: list[tuple[int, str]],
526
+ timeout: float = 5.0) -> Optional[list[Optional[dict[str, Any]]]]:
527
+ """Gemini 通道:每条文本一个请求,并发 4,整批硬截止取 DEFAULT_GEMINI_DEADLINE_S。
528
+
529
+ 与 JEV 的 1.2s 分开取值:Gemini 单条 p95 实测 2251ms(见常量注释),
530
+ 沿用 1.2s 会在批量里静默截断(实测 6 组 4 条里 1 组只回 3/4)。
531
+ """
532
+ if not gemini_api_key():
533
+ return None
534
+ return _run_choice_batch(
535
+ len(texts), keep,
536
+ lambda t: _gemini_choice(t, labels, instructions, timeout, criteria),
537
+ timeout=timeout,
538
+ deadline_s=DEFAULT_GEMINI_DEADLINE_S,
539
+ )
540
+
541
+
268
542
  def classify(texts: list[str], labels: tuple[str, ...] | list[str], *,
269
543
  instructions: str | None = None,
544
+ criteria: dict[str, str] | None = None,
270
545
  timeout: float | None = None,
271
546
  tier: str | None = None) -> Optional[list[dict[str, Any]]]:
272
- """一次批量分类。任何异常/非 200/条数不匹配 → None。
273
-
274
- 返回按输入顺序排列的 [{label, confidence, scores}];调用方负责判定阈值。
275
- 空文本会被过滤后再发(空串会让整批 400),返回列表与输入等长、空缺位为 None。
547
+ """一次批量远程语义分类。任何异常/非 200/条数不匹配 → None。
276
548
 
277
- 两个通道的实现分居 _classify_jev(TypeSafe,每条一请求)与下方内联的
278
- classifier.dev 路径(一次发 N 条);开关判定见 _transport。
549
+ 远程通道按优先级自适应:Gemini Decision 1 ➔ TypeSafe JEV(互为备选),
550
+ 或显式走 classify。本地启发式兜底由上层 assess_*(allow_heuristic=True)承担。
279
551
  """
280
552
  if not texts or len(labels) < 2:
281
553
  return None
@@ -283,9 +555,25 @@ def classify(texts: list[str], labels: tuple[str, ...] | list[str], *,
283
555
  if not keep:
284
556
  return None
285
557
  to = timeout or _timeout()
286
- if _transport() == "jev":
558
+
559
+ tp = _transport()
560
+ if tp == "gemini":
561
+ res = _classify_gemini(texts, labels, instructions=instructions,
562
+ criteria=criteria, keep=keep, timeout=to)
563
+ if res is not None:
564
+ return res
565
+ # 降级至 JEV 备用通道
287
566
  return _classify_jev(texts, labels, instructions=instructions,
288
- keep=keep, timeout=to)
567
+ criteria=criteria, keep=keep, timeout=to)
568
+
569
+ if tp == "jev":
570
+ res = _classify_jev(texts, labels, instructions=instructions,
571
+ criteria=criteria, keep=keep, timeout=to)
572
+ if res is not None:
573
+ return res
574
+ # 降级至 Gemini 备用通道
575
+ return _classify_gemini(texts, labels, instructions=instructions,
576
+ criteria=criteria, keep=keep, timeout=to)
289
577
  body: dict[str, Any] = {
290
578
  "labels": [str(x) for x in labels],
291
579
  "inputs": [t[:MAX_TEXT_CHARS] for _i, t in keep],
@@ -319,29 +607,46 @@ def classify(texts: list[str], labels: tuple[str, ...] | list[str], *,
319
607
  return out # type: ignore[return-value]
320
608
 
321
609
 
322
- def assess_support(query: str, items: list[dict[str, Any]]) -> Optional[dict[str, dict]]:
323
- """对已抓取的正文批量判定「是否支持查询隐含的主张」。
324
-
325
- items: [{"url": str, "title": str, "text": str}]
326
- 返回 {url: {label, confidence, supports, contradicts}};未达阈值时
327
- supports/contradicts 均为 False(原始 label 与 confidence 仍原样保留,
328
- 调用方可自行换阈值)。失败返回 None。
329
- """
330
- usable = [it for it in items if (it.get("text") or "").strip() and it.get("url")]
610
+ def _prepare_usable_texts(
611
+ items: list[dict[str, Any]], *, require_text: bool = True
612
+ ) -> tuple[list[dict[str, Any]], list[str]]:
613
+ """过滤非本地目标并拼装截断文本,统一三路语义评估的前置隔离逻辑。"""
614
+ usable = []
615
+ for it in items:
616
+ url = it.get("url")
617
+ if not url or is_local_target(url):
618
+ continue
619
+ has_text = bool((it.get("text") or "").strip())
620
+ has_title = bool((it.get("title") or "").strip())
621
+ if has_text or (not require_text and has_title):
622
+ usable.append(it)
623
+ texts = [
624
+ f"{it.get('title') or ''}\n{(it.get('text') or '')[:MAX_TEXT_CHARS]}"
625
+ for it in usable
626
+ ]
627
+ return usable, texts
628
+
629
+
630
+ def _assess_batch(
631
+ items: list[dict[str, Any]],
632
+ *,
633
+ require_text: bool,
634
+ labels: tuple[str, ...],
635
+ instructions: str,
636
+ criteria: dict[str, str] | None = None,
637
+ heuristic_fn: Any,
638
+ allow_heuristic: bool,
639
+ build_extra: Any,
640
+ ) -> Optional[dict[str, dict]]:
641
+ """三路语义评估的统一批处理框架:隔离本地目标、调用远程分类、按需启发式兜底与阈值判定。"""
642
+ usable, texts = _prepare_usable_texts(items, require_text=require_text)
331
643
  if not usable:
332
644
  return None
333
- texts = [f"{it.get('title') or ''}\n{(it.get('text') or '')[:MAX_TEXT_CHARS]}"
334
- for it in usable]
335
- instructions = (
336
- f"Judge whether each passage supports the claim implied by this query: {query!r}. "
337
- "Answer 'supports the query' when the passage backs the claim, "
338
- "'contradicts the query' when it states the opposite or a conflicting figure, "
339
- "'neutral' when it is on-topic but neither supports nor contradicts, "
340
- "and 'none of these' when it is unrelated to the query."
341
- )
342
- results = classify(texts, SUPPORT_LABELS, instructions=instructions)
645
+ results = classify(texts, labels, instructions=instructions, criteria=criteria)
343
646
  if results is None:
344
- return None
647
+ if not allow_heuristic:
648
+ return None
649
+ results = [heuristic_fn(it) for it in usable]
345
650
  out: dict[str, dict] = {}
346
651
  for it, r in zip(usable, results):
347
652
  if not r:
@@ -349,43 +654,160 @@ def assess_support(query: str, items: list[dict[str, Any]]) -> Optional[dict[str
349
654
  label = str(r.get("label") or "")
350
655
  conf = r.get("confidence")
351
656
  conf_f = float(conf) if isinstance(conf, (int, float)) else 0.0
352
- out[str(it["url"])] = {
353
- "label": label,
354
- "confidence": conf_f,
355
- "supports": label == "supports the query" and conf_f >= SUPPORT_THRESHOLD,
356
- "contradicts": label == "contradicts the query" and conf_f >= SUPPORT_THRESHOLD,
357
- }
657
+ entry: dict[str, Any] = {"label": label, "confidence": conf_f}
658
+ entry.update(build_extra(label, conf_f))
659
+ out[str(it["url"])] = entry
358
660
  return out or None
359
661
 
360
662
 
361
- def assess_source_types(items: list[dict[str, Any]]) -> Optional[dict[str, dict]]:
362
- """来源类型分级(研究取证链路用):一手数据 / 二手报道 / 分析观点 / 社交叙事。
663
+ def assess_support(query: str, items: list[dict[str, Any]], *, allow_heuristic: bool = False) -> Optional[dict[str, dict]]:
664
+ """对已抓取的正文批量判定「是否支持查询隐含的主张」。"""
665
+ instructions = (
666
+ f"Judge whether each passage supports the claim implied by this query: {query!r}. "
667
+ "Answer 'supports the query' when the passage backs the claim, "
668
+ "'contradicts the query' when it states the opposite or a conflicting figure, "
669
+ "'neutral' when it is on-topic but neither supports nor contradicts, "
670
+ "and 'none of these' when it is unrelated to the query."
671
+ )
672
+ return _assess_batch(
673
+ items,
674
+ require_text=True,
675
+ labels=SUPPORT_LABELS,
676
+ instructions=instructions,
677
+ heuristic_fn=lambda it: heuristic_support(query, it.get("text") or "", it.get("title") or ""),
678
+ allow_heuristic=allow_heuristic,
679
+ build_extra=lambda label, conf_f: {
680
+ "supports": label == "supports the query" and conf_f >= SUPPORT_THRESHOLD,
681
+ "contradicts": label == "contradicts the query" and conf_f >= SUPPORT_THRESHOLD,
682
+ },
683
+ )
684
+
363
685
 
364
- items: [{"url": str, "title": str, "text": str}](text 可为摘要)
365
- """
366
- usable = [it for it in items if it.get("url") and
367
- ((it.get("text") or "").strip() or (it.get("title") or "").strip())]
368
- if not usable:
369
- return None
370
- texts = [f"{it.get('title') or ''}\n{(it.get('text') or '')[:MAX_TEXT_CHARS]}"
371
- for it in usable]
686
+ _NON_CJK_EAST_ASIAN_RE = re.compile(r"[\u3040-\u30ff]{2,}|[\uac00-\ud7af]{2,}")
687
+ _SENTENCE_SPLIT_RE = re.compile(r"[。!?.!?\n]+")
688
+
689
+
690
+ def _heuristic_tokens(text: str) -> list[str]:
691
+ """复用 cjk_tokens 切分中英信号,并扩展日文假名/韩文音节重叠 2-gram。"""
692
+ from cjk_tokens import cjk_ngrams, signal_tokens
693
+ tokens = signal_tokens(text)
694
+ for run in _NON_CJK_EAST_ASIAN_RE.findall(text or ""):
695
+ tokens.extend(cjk_ngrams(run))
696
+ deduped = list(dict.fromkeys(t for t in tokens if len(t) >= 2))
697
+ if not deduped and (text or "").strip():
698
+ return [(text or "").strip().lower()]
699
+ return deduped
700
+
701
+
702
+ def heuristic_substantive_discussion(topic: str, text: str, title: str = "") -> dict[str, Any]:
703
+ """本地高精度启发式深度判定:区分实质深入探讨 vs 顺带提及(零网络、零外部 Key 依赖)。"""
704
+ t_clean = (topic or "").strip().lower()
705
+ full_text = f"{title}\n{text}".lower()
706
+ if not t_clean or not full_text.strip():
707
+ return {"label": "none of these", "confidence": 0.5}
708
+
709
+ tokens = _heuristic_tokens(topic)
710
+ title_low = (title or "").lower()
711
+ title_hit = any(tok in title_low for tok in tokens)
712
+ sentences = [s.strip() for s in _SENTENCE_SPLIT_RE.split(text.lower()) if s.strip()]
713
+ sent_hits = sum(1 for s in sentences if any(tok in s for tok in tokens))
714
+ token_hits = sum(1 for tok in tokens if tok in full_text)
715
+ text_len = len(text.strip())
716
+
717
+ # 实质探讨:(标题明确命中且正文 >= 30 字) 或 (至少 2 个独立句命中主题且篇幅 >= 60 字)
718
+ if (title_hit and text_len >= 30) or (sent_hits >= 2 and text_len >= 60):
719
+ return {"label": "substantive in-depth discussion", "confidence": 0.88}
720
+ # 顺带提及:单句提及或篇幅不足
721
+ if token_hits >= 1 or sent_hits >= 1 or text_len >= 40:
722
+ return {"label": "passing mention or brief reference", "confidence": 0.78}
723
+ return {"label": "unrelated chatter", "confidence": 0.72}
724
+
725
+
726
+ def heuristic_source_type(url: str, title: str = "", text: str = "") -> dict[str, Any]:
727
+ """本地高精度启发式来源类型分级(零网络、零外部依赖)。"""
728
+ u_low = (url or "").lower()
729
+ full_text = f"{title}\n{text}".lower()
730
+
731
+ primary_domains = (
732
+ ".gov", ".edu", "sec.gov", "arxiv.org", "biorxiv.org", "github.com",
733
+ "rfc-editor.org", "federalregister.gov", "w3.org", "nature.com"
734
+ )
735
+ primary_keywords = ("official announcement", "press release", "filing", "whitepaper", "documentation", "公报", "公告", "官方发布")
736
+ if any(d in u_low for d in primary_domains) or any(k in full_text for k in primary_keywords):
737
+ return {"label": "primary data or official announcement", "confidence": 0.86}
738
+
739
+ social_domains = ("x.com", "twitter.com", "reddit.com", "weibo.com", "zhihu.com", "v2ex.com", "news.ycombinator.com")
740
+ if any(d in u_low for d in social_domains):
741
+ return {"label": "social narrative", "confidence": 0.82}
742
+
743
+ opinion_keywords = ("analysis", "opinion", "commentary", "review", "perspective", "评论", "专栏", "深度分析")
744
+ if any(k in full_text for k in opinion_keywords):
745
+ return {"label": "analysis or opinion", "confidence": 0.76}
746
+
747
+ return {"label": "secondary reporting", "confidence": 0.75}
748
+
749
+
750
+ def heuristic_support(query: str, text: str, title: str = "") -> dict[str, Any]:
751
+ """本地高精度启发式证据支持度初筛(零网络、零外部依赖,支持 CJK/多语 2-gram 与同句极性窗口)。"""
752
+ full_text = f"{title}\n{text}".lower()
753
+ tokens = _heuristic_tokens(query)
754
+ if not tokens:
755
+ return {"label": "neutral", "confidence": 0.70}
756
+ hits = sum(1 for tok in tokens if tok in full_text)
757
+ contra_words = (
758
+ "keep unchanged", "remain unchanged", "defying", "opposite", "denied", "contrary",
759
+ "未降息", "维持不变", "并未", "未如", "反驳", "并非", "否认",
760
+ )
761
+ sentences = [s.strip() for s in _SENTENCE_SPLIT_RE.split(full_text) if s.strip()]
762
+ has_contra = any(
763
+ any(w in s for w in contra_words) and any(tok in s for tok in tokens)
764
+ for s in sentences
765
+ )
766
+ if has_contra:
767
+ return {"label": "contradicts the query", "confidence": 0.85}
768
+ ratio = hits / len(tokens)
769
+ has_cjk = any(ord(c) > 0x2E80 for c in query)
770
+ min_hits = 2 if (has_cjk and len(tokens) > 2) else 1
771
+ threshold = 0.25 if has_cjk else 0.65
772
+ if ratio >= threshold and hits >= min_hits:
773
+ return {"label": "supports the query", "confidence": 0.80}
774
+ return {"label": "neutral", "confidence": 0.70}
775
+
776
+
777
+ def assess_source_types(items: list[dict[str, Any]], *, allow_heuristic: bool = False) -> Optional[dict[str, dict]]:
778
+ """来源类型分级(研究取证链路用):一手数据 / 二手报道 / 分析观点 / 社交叙事。"""
372
779
  instructions = (
373
780
  "Classify each source by its nature: 'primary data or official announcement' "
374
781
  "for original datasets, filings, official releases; 'secondary reporting' for "
375
782
  "news coverage of someone else's work; 'analysis or opinion' for commentary; "
376
783
  "'social narrative' for forum/social posts."
377
784
  )
378
- results = classify(texts, SOURCE_TYPE_LABELS, instructions=instructions)
379
- if results is None:
380
- return None
381
- out: dict[str, dict] = {}
382
- for it, r in zip(usable, results):
383
- if not r:
384
- continue
385
- label = str(r.get("label") or "")
386
- conf = r.get("confidence")
387
- out[str(it["url"])] = {
388
- "label": label,
389
- "confidence": float(conf) if isinstance(conf, (int, float)) else 0.0,
390
- }
391
- return out or None
785
+ return _assess_batch(
786
+ items,
787
+ require_text=False,
788
+ labels=SOURCE_TYPE_LABELS,
789
+ instructions=instructions,
790
+ heuristic_fn=lambda it: heuristic_source_type(it.get("url") or "", it.get("title") or "", it.get("text") or ""),
791
+ allow_heuristic=allow_heuristic,
792
+ build_extra=lambda label, conf_f: {
793
+ "is_primary": label == "primary data or official announcement" and conf_f >= SUPPORT_THRESHOLD,
794
+ },
795
+ )
796
+
797
+
798
+ def assess_substantive_discussion(topic: str, items: list[dict[str, Any]], *, allow_heuristic: bool = False) -> Optional[dict[str, dict]]:
799
+ """批量判定正文对主题是否进行了实质性深入探讨(或顺带提及 / 闲聊)。"""
800
+ return _assess_batch(
801
+ items,
802
+ require_text=True,
803
+ labels=SUBSTANTIVE_DISCUSSION_LABELS,
804
+ instructions=f"Determine the depth of discussion regarding the topic {topic!r} in the text.",
805
+ criteria=SUBSTANTIVE_DISCUSSION_CRITERIA,
806
+ heuristic_fn=lambda it: heuristic_substantive_discussion(topic, it.get("text") or "", it.get("title") or ""),
807
+ allow_heuristic=allow_heuristic,
808
+ build_extra=lambda label, conf_f: {
809
+ "is_substantive": label == "substantive in-depth discussion" and conf_f >= SUPPORT_THRESHOLD,
810
+ "is_passing_mention": label == "passing mention or brief reference" and conf_f >= SUPPORT_THRESHOLD,
811
+ },
812
+ )
813
+