argo-search 2.13.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 (129) hide show
  1. package/AGENTS.md +93 -0
  2. package/README.es.md +30 -8
  3. package/README.ja.md +30 -8
  4. package/README.ko.md +30 -8
  5. package/README.md +511 -596
  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 +90 -6
  10. package/backends/engine_registry.yaml +222 -32
  11. package/backends/env_passthrough.txt +2 -0
  12. package/backends/quota_profiles.json +151 -11
  13. package/bin/argo +3 -0
  14. package/config.yaml +50 -4
  15. package/docs/CHANGELOG.md +45 -0
  16. package/docs/COMMIT_STANDARD.md +98 -0
  17. package/docs/ENGINE_CATALOG.md +100 -81
  18. package/docs/MCP_SETUP.md +1 -1
  19. package/docs/RELEASE_NOTES_v2.14.0.md +88 -0
  20. package/docs/RELEASE_NOTES_v2.14.1.md +80 -0
  21. package/docs/RELEASING.md +52 -0
  22. package/engines/specs/artic.yaml +11 -1
  23. package/engines/specs/cleveland.yaml +15 -1
  24. package/engines/specs/clinicaltrials.yaml +24 -1
  25. package/engines/specs/cnii.yaml +17 -1
  26. package/engines/specs/coingecko.yaml +10 -2
  27. package/engines/specs/dbpedia.yaml +32 -0
  28. package/engines/specs/deezer.yaml +12 -1
  29. package/engines/specs/doaj.yaml +14 -1
  30. package/engines/specs/endoflife.yaml +16 -1
  31. package/engines/specs/eu_opendata.yaml +11 -1
  32. package/engines/specs/europeana.yaml +19 -1
  33. package/engines/specs/feed.yaml +62 -0
  34. package/engines/specs/figshare.yaml +12 -1
  35. package/engines/specs/fourget.yaml +23 -0
  36. package/engines/specs/grep_app.yaml +19 -0
  37. package/engines/specs/hackernews.yaml +17 -1
  38. package/engines/specs/hal.yaml +19 -1
  39. package/engines/specs/hf_datasets.yaml +59 -0
  40. package/engines/specs/hf_papers.yaml +42 -0
  41. package/engines/specs/jikan.yaml +12 -10
  42. package/engines/specs/kaggle.yaml +46 -0
  43. package/engines/specs/local_baidu.yaml +5 -0
  44. package/engines/specs/local_seek.yaml +34 -0
  45. package/engines/specs/local_yandex.yaml +37 -0
  46. package/engines/specs/maven.yaml +61 -0
  47. package/engines/specs/mojeek.yaml +31 -0
  48. package/engines/specs/mwmbl.yaml +39 -0
  49. package/engines/specs/nasa_cmr.yaml +12 -1
  50. package/engines/specs/nuget.yaml +57 -0
  51. package/engines/specs/openaire.yaml +34 -0
  52. package/engines/specs/repology.yaml +18 -0
  53. package/engines/specs/tatoeba.yaml +14 -1
  54. package/engines/specs/tvmaze.yaml +5 -1
  55. package/engines/specs/usda.yaml +14 -1
  56. package/package.json +14 -10
  57. package/packages/dsh-plugin/dsh/client.js +1 -0
  58. package/packages/dsh-plugin/dsh/native-tools.mjs +85 -116
  59. package/packages/dsh-plugin/dsh/runner.js +35 -1
  60. package/packages/dsh-plugin/dsh/specs.js +3 -1
  61. package/packages/dsh-plugin/dsh/wide-research.js +5 -3
  62. package/packages/dsh-plugin/package.json +1 -1
  63. package/packages/dsh-plugin/test/client.test.js +6 -0
  64. package/packages/dsh-plugin/test/config.test.js +5 -1
  65. package/packages/dsh-plugin/test/index.test.js +3 -1
  66. package/packages/dsh-plugin/test/size-gate.test.js +2 -2
  67. package/scripts/badcase_causes.py +81 -0
  68. package/scripts/badcase_ledger.py +336 -19
  69. package/scripts/build_release_assets.sh +43 -15
  70. package/scripts/cache.py +3 -3
  71. package/scripts/check_commit_report.py +168 -0
  72. package/scripts/dormant_ledger.py +225 -0
  73. package/scripts/engine_admission.py +9 -5
  74. package/scripts/engine_families.py +13 -2
  75. package/scripts/engine_policy.py +1 -1
  76. package/scripts/engine_states.py +398 -8
  77. package/scripts/engine_status.py +31 -0
  78. package/scripts/engine_validate.py +224 -40
  79. package/scripts/engines.py +4 -34
  80. package/scripts/engines_base.py +53 -147
  81. package/scripts/engines_builders.py +2 -33
  82. package/scripts/engines_builders_batch12.py +168 -0
  83. package/scripts/engines_builders_batch16.py +13 -0
  84. package/scripts/engines_builders_batch9.py +0 -204
  85. package/scripts/engines_builders_feeds.py +148 -30
  86. package/scripts/engines_builders_intl.py +0 -328
  87. package/scripts/engines_builders_science.py +0 -85
  88. package/scripts/engines_builders_tech.py +0 -98
  89. package/scripts/engines_parsers.py +924 -0
  90. package/scripts/evidence_loop.py +91 -4
  91. package/scripts/fetch_browser.py +4 -2
  92. package/scripts/fetch_jsrun.py +2 -1
  93. package/scripts/fetch_v3.py +22 -22
  94. package/scripts/gen_engine_catalog.py +2 -2
  95. package/scripts/gen_native_tools.py +46 -18
  96. package/scripts/local_intent.py +175 -0
  97. package/scripts/local_seek.py +256 -91
  98. package/scripts/local_seek_adapter.py +87 -0
  99. package/scripts/mcp_handlers.py +124 -72
  100. package/scripts/mcp_server.py +1 -1
  101. package/scripts/mcp_tools.py +143 -61
  102. package/scripts/mcp_transport.py +42 -10
  103. package/scripts/pre-commit +68 -1
  104. package/scripts/recovery.py +14 -5
  105. package/scripts/recovery_l0.py +5 -3
  106. package/scripts/release.py +20 -11
  107. package/scripts/release_check.py +1 -1
  108. package/scripts/research.py +1 -1
  109. package/scripts/research_gates.py +3 -3
  110. package/scripts/route_lang.py +6 -1
  111. package/scripts/route_policy.py +26 -14
  112. package/scripts/search.py +33 -25
  113. package/scripts/search_cli.py +52 -6
  114. package/scripts/search_output.py +83 -16
  115. package/scripts/secret_guard.py +106 -0
  116. package/scripts/semantic_evidence.py +230 -15
  117. package/scripts/settings_page.py +80 -8
  118. package/scripts/source_audit.py +408 -0
  119. package/scripts/sync_backends.py +38 -1
  120. package/scripts/wechat_article.py +5 -3
  121. package/scripts/wide_research.py +4 -1
  122. package/scripts/x_article_fetch.py +2 -1
  123. package/sub-skills/local-search/parsers.py +6 -1
  124. package/sub-skills/local-seek/scripts/seek.py +390 -24
  125. package/sub-skills/local-seek/scripts/seek_fts.py +28 -9
  126. package/sub-skills/local-seek/scripts/seek_rank.py +64 -1
  127. package/README.en.md +0 -814
  128. package/engines/specs/cinii.yaml +0 -44
  129. package/scripts/image_vision/vision_probe +0 -0
@@ -62,6 +62,8 @@ def _warn(message: str) -> None:
62
62
  _AGENT_RESULT_FIELDS = (
63
63
  "title", "url", "snippet", "source", "score", "ref",
64
64
  "published_at", "fetch_suggested", "full_text_url",
65
+ # 本地命中标记:明确区分本地文件与联网结果,供 Agent 分面过滤
66
+ "is_local",
65
67
  # 离散权威等级(0-4,≥3 极权威):Agent 的廉价可信闸门——连续 authority
66
68
  # 分不知道该在哪切,等级才能直接当门用(DeepSeek Search 同款语义)。
67
69
  # 整数字段约 6 字节,剥掉它等于把「先信谁」重新推回给调用方猜。
@@ -227,6 +229,8 @@ def _strip_for_agent(payload: dict[str, Any]) -> dict[str, Any]:
227
229
  # 信任级别:网页文本一律是不可信外部数据,随答案一起到达,
228
230
  # 避免调用方把摘要里的指令当任务执行(输出层声明,非提示词)。
229
231
  "content_trust",
232
+ # 本地与公网分面契约(方案三):通道隔离,避免本地命中与联网结果在同一列表里混淆
233
+ "local_results", "web_results", "local_seek_skipped", "local_seek_skip_reason", "facets",
230
234
  # 核验产出:verify/evidence_reorder 是**花了墙钟换来的**,且是
231
235
  # 「该不该引用这批结果」的直接依据。此前被整块剥掉,调用方付了
232
236
  # 几秒核验却只看到 verified_count 一个数(2026-10-22 实测)。
@@ -256,6 +260,18 @@ def _strip_for_agent(payload: dict[str, Any]) -> dict[str, Any]:
256
260
  slim_results.append(slim)
257
261
  out["results"] = slim_results
258
262
  out["count"] = len(slim_results)
263
+
264
+ # 分面通道:对 local_results 与 web_results 按同一字段白名单瘦身
265
+ if "local_results" in payload:
266
+ out["local_results"] = [
267
+ {k: r[k] for k in _AGENT_RESULT_FIELDS if r.get(k) is not None}
268
+ for r in (payload.get("local_results") or []) if isinstance(r, dict)
269
+ ]
270
+ if "web_results" in payload:
271
+ out["web_results"] = [
272
+ {k: r[k] for k in _AGENT_RESULT_FIELDS if r.get(k) is not None}
273
+ for r in (payload.get("web_results") or []) if isinstance(r, dict)
274
+ ]
259
275
  return out
260
276
 
261
277
 
@@ -424,7 +440,7 @@ def format_text_output(results: dict[str, Any]) -> str:
424
440
  for err in results.get("errors", [])[:3]:
425
441
  lines.append(f" [ERROR] {err}")
426
442
 
427
- # 正文区:编号 + 标题 + 摘要(链接沉底,避免噪声)
443
+ # 正文区:分桶呈现【本地搜索】与【联网搜索】,避免来源混淆
428
444
  sources = results.get("sources")
429
445
  if not isinstance(sources, list) or not sources:
430
446
  sources = build_sources(results.get("results") or [])
@@ -432,15 +448,19 @@ def format_text_output(results: dict[str, Any]) -> str:
432
448
  # 用 URL 保持一致 ref
433
449
  url_to_ref = {s.get("url"): s.get("ref") for s in sources if isinstance(s, dict)}
434
450
  body_items = [r for r in (results.get("results") or []) if isinstance(r, dict)]
435
- for r in body_items:
451
+
452
+ def _is_local_item(it: dict[str, Any]) -> bool:
453
+ return bool(it.get("is_local") or it.get("source") == "local_files"
454
+ or str(it.get("url", "")).startswith("file://")
455
+ or str(it.get("source", "")).startswith("local_"))
456
+
457
+ local_items = [r for r in body_items if _is_local_item(r)]
458
+ web_items = [r for r in body_items if not _is_local_item(r)]
459
+
460
+ def _render_item(r: dict[str, Any], is_local_sec: bool = False) -> None:
436
461
  url = (r.get("url") or "").strip()
437
462
  ref = url_to_ref.get(url)
438
463
  if ref is None:
439
- # 未进 sources 时临时编号。分两种:有 URL 但没被收进 sources
440
- # (编号未知,用 ?);以及**本就没有 URL** 的条目——天气/行情/
441
- # 宏观这类结构化快照走的就是这条。此前两种情况共用一个分支,
442
- # 且分支条件是 `and url`,于是无 URL 的条目 ref 保持 None,
443
- # 正文里直接打成 `[None]`(2026-09-19 实测「北京天气」复现)。
444
464
  ref = "?" if url else "—"
445
465
  score = r.get("score", 0)
446
466
  title = (r.get("title") or "?")[:80]
@@ -451,21 +471,33 @@ def format_text_output(results: dict[str, Any]) -> str:
451
471
  lines.append(f" {snippet[:140]}")
452
472
  elif score:
453
473
  lines.append(f" (score={score_s})")
474
+ if is_local_sec and url.startswith("file://"):
475
+ lines.append(f" {url}")
454
476
 
455
- # 底部相关信源(传统搜索引擎形态)
456
- # sources 只保留 ref/url/engine(A2 引用式),title 从 results 回查
457
- if sources:
477
+ if local_items:
478
+ lines.append("")
479
+ lines.append(f"【本地搜索】({len(local_items)} 项命中)")
480
+ for r in local_items:
481
+ _render_item(r, is_local_sec=True)
482
+
483
+ if web_items:
484
+ lines.append("")
485
+ lines.append(f"【联网搜索】({len(web_items)} 项命中)")
486
+ for r in web_items:
487
+ _render_item(r, is_local_sec=False)
488
+
489
+ # 底部相关信源(仅呈现联网 URL)
490
+ web_sources = [s for s in sources if isinstance(s, dict)
491
+ and not str(s.get("url", "")).startswith("file://")]
492
+ if web_sources:
458
493
  lines.append("")
459
- lines.append("── 相关信源 ──")
494
+ lines.append("── 联网信源 ──")
460
495
  _results_list = results.get("results") or []
461
- for s in sources:
462
- if not isinstance(s, dict):
463
- continue
496
+ for s in web_sources:
464
497
  ref = s.get("ref", "?")
465
498
  eng = s.get("engine") or ""
466
499
  url = s.get("url") or ""
467
500
  eng_s = f" · {eng}" if eng else ""
468
- # 通过 ref 回查 results 获取 title(A2:sources 不再重复 title)
469
501
  _title = ""
470
502
  if isinstance(ref, int) and 1 <= ref <= len(_results_list):
471
503
  _title = (_results_list[ref - 1].get("title") or "")[:60]
@@ -711,12 +743,33 @@ def shape_response(ctx: _ShapeContext, result: dict[str, Any]) -> dict[str, Any]
711
743
  #(宽根守卫 + 3s 超时兜底),--include-local / MCP include_local 显式开,
712
744
  # --no-local / include_local=false 关。按 URL 去重后并入,防止与既有
713
745
  # 结果(或未来评分变化)产生双份条目。
746
+ # 内容形态约束优先于双轨并发:--video / --min-duration 是用户对「结果形态」
747
+ # 的硬要求,本机文件(.md/.py/.txt…)永远不满足。此前不判形态直接并入,
748
+ # 实测 --video 的 3 条视频会被 3 条本机 markdown 挤成 6 条混合结果。
749
+ # 判据与 search_pipeline 的视频过滤同源(decision 的 video_only/min/max_duration)。
750
+ _video_scope = bool((decision or {}).get("video_only")) \
751
+ or (decision or {}).get("min_duration") is not None \
752
+ or (decision or {}).get("max_duration") is not None
753
+ if include_local and _video_scope:
754
+ result["local_seek_skipped"] = True
755
+ result["local_seek_skip_reason"] = "content_shape_video"
756
+ include_local = False
757
+
714
758
  if include_local:
715
759
  try:
716
760
  local_hits = _run_local_seek(query, n)
717
761
  except Exception as e:
718
762
  local_hits = []
719
763
  _log(f"[include-local] {type(e).__name__}: {e}")
764
+ # 本地轨意图预判跳过了(公域答案型查询 + 无本地信号):显式标记,
765
+ # 让调用方看到「本地轨没跑」而不是误以为「本地没有匹配」。
766
+ # 与 local_seek_skipped 的另两个来源(宽根守卫 / seek.py 缺失)同义。
767
+ try:
768
+ from local_seek import local_seek_last_skipped
769
+ if local_seek_last_skipped():
770
+ result["local_seek_skipped"] = True
771
+ except Exception:
772
+ pass
720
773
  if local_hits:
721
774
  _seen_urls = {r.get("url") for r in (result.get("results") or [])
722
775
  if isinstance(r, dict)}
@@ -724,8 +777,22 @@ def shape_response(ctx: _ShapeContext, result: dict[str, Any]) -> dict[str, Any]
724
777
  if isinstance(h, dict) and h.get("url") not in _seen_urls]
725
778
  if _fresh_local:
726
779
  result.setdefault("results", []).extend(_fresh_local)
727
- result["local_results"] = _fresh_local
728
780
  result["include_local"] = True
781
+
782
+ # ── 来源分桶:构建独立的 local_results 与 web_results,杜绝来源混淆 ──────────
783
+ _all_res = [r for r in (result.get("results") or []) if isinstance(r, dict)]
784
+ _loc_b = [r for r in _all_res if r.get("is_local") or r.get("source") == "local_files"
785
+ or str(r.get("url", "")).startswith("file://") or str(r.get("source", "")).startswith("local_")]
786
+ _web_b = [r for r in _all_res if r not in _loc_b]
787
+ for _lr in _loc_b:
788
+ _lr["is_local"] = True
789
+ result["local_results"] = _loc_b
790
+ result["web_results"] = _web_b
791
+ result["facets"] = {
792
+ "web_count": len(_web_b),
793
+ "local_count": len(_loc_b),
794
+ "total_count": len(_all_res),
795
+ }
729
796
  # ── 收口:重算一切「由 results 派生」的字段 ────────────────────────────────
730
797
  #
731
798
  # why:本函数**后置**改 results 的地方不止一处(域过滤裁剪、本地命中并入),
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env python3
2
+ """secret_guard.py — 输出流自动脱敏拦截器(防止真实凭据反射/外泄给 Agent 与 LLM)。
3
+
4
+ 第一性原理:
5
+ 任何流向终端、JSON 或 MCP 工具返回的文本/结构化数据,都必须经过
6
+ 脱敏拦截,杜绝三类泄露:
7
+ 1. 已配置的真实凭据(从 os.environ 与 envfile 收集的所有有效 API Key/Token);
8
+ 2. URL 参数中的敏感认证(?key=..., &token=..., &secret=...);
9
+ 3. 通用高熵 API 凭据签名模式(sk-..., tvly-..., ghp_..., Bearer ...)。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import re
16
+ from typing import Any
17
+
18
+ # 通用高熵 API Key 签名正则
19
+ _GENERIC_KEY_PATTERNS = [
20
+ # OpenAI / DeepSeek / 通用 sk- 开头
21
+ re.compile(r"\b(sk-[a-zA-Z0-9_\-]{20,})\b"),
22
+ # Tavily tvly- 开头
23
+ re.compile(r"\b(tvly-[a-zA-Z0-9_\-]{20,})\b"),
24
+ # GitHub Token (ghp_, github_pat_)
25
+ re.compile(r"\b(ghp_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9_]{40,})\b"),
26
+ # HTTP Bearer 认证头残留
27
+ re.compile(r"(?i)\bBearer\s+([a-zA-Z0-9_\-\.]{24,})\b"),
28
+ # 典型键值对形式
29
+ re.compile(r"(?i)(?:api_key|access_token|secret_key|api_secret)\s*[:=]\s*['\"]?([a-zA-Z0-9_\-]{24,})['\"]?"),
30
+ ]
31
+
32
+ # URL query 敏感参数脱敏
33
+ _URL_PARAM_PATTERN = re.compile(
34
+ r"([?&](?:api_?key|access_?token|token|key|secret|password|auth)=)[^& \t\r\n\"'>]+",
35
+ re.I,
36
+ )
37
+
38
+ # 避免误杀的非密钥常见词
39
+ _WHITELIST = {
40
+ "undefined", "null", "false", "true", "none", "password", "secret", "bearer",
41
+ "http_proxy", "https_proxy", "all_proxy", "no_proxy",
42
+ }
43
+
44
+
45
+ def get_active_secrets() -> set[str]:
46
+ """收集当前环境中加载的真实有效长密钥字符串集合(去重、过滤短串)。"""
47
+ secrets: set[str] = set()
48
+ # 1. 进程环境变量
49
+ for k, v in os.environ.items():
50
+ if not v or len(v) < 8:
51
+ continue
52
+ k_upper = k.upper()
53
+ if (k_upper.startswith("ARGO_") or
54
+ k_upper.endswith(("_KEY", "_TOKEN", "_SECRET", "_PASSWORD", "_APIKEY")) or
55
+ "API_KEY" in k_upper or "ACCESS_KEY" in k_upper):
56
+ if v.lower() not in _WHITELIST:
57
+ secrets.add(v.strip())
58
+
59
+ # 2. envfile 存储的密钥
60
+ try:
61
+ from engine_env import _envfile_load
62
+ file_env = _envfile_load()
63
+ for _k, v in file_env.items():
64
+ if v and len(v) >= 8 and v.lower() not in _WHITELIST:
65
+ secrets.add(v.strip())
66
+ except Exception:
67
+ pass
68
+
69
+ return secrets
70
+
71
+
72
+ def redact_text(text: str, extra_secrets: set[str] | None = None) -> str:
73
+ """对单段文本执行深度脱敏替换。"""
74
+ if not text or not isinstance(text, str):
75
+ return text
76
+
77
+ out = text
78
+
79
+ # 1. 替换已知真实有效凭据
80
+ active_secrets = get_active_secrets()
81
+ if extra_secrets:
82
+ active_secrets.update(extra_secrets)
83
+
84
+ for sec in sorted(active_secrets, key=len, reverse=True):
85
+ if sec in out:
86
+ out = out.replace(sec, "[REDACTED_API_KEY]")
87
+
88
+ # 2. 替换通用高熵 API Key 签名
89
+ for pat in _GENERIC_KEY_PATTERNS:
90
+ out = pat.sub("[REDACTED_SECRET]", out)
91
+
92
+ # 3. 替换 URL query 参数中的敏感参数
93
+ out = _URL_PARAM_PATTERN.sub(r"\1[REDACTED]", out)
94
+
95
+ return out
96
+
97
+
98
+ def redact_data(data: Any, extra_secrets: set[str] | None = None) -> Any:
99
+ """递归对复杂数据结构(dict / list / str)进行全量脱敏。"""
100
+ if isinstance(data, str):
101
+ return redact_text(data, extra_secrets=extra_secrets)
102
+ if isinstance(data, list):
103
+ return [redact_data(item, extra_secrets=extra_secrets) for item in data]
104
+ if isinstance(data, dict):
105
+ return {k: redact_data(v, extra_secrets=extra_secrets) for k, v in data.items()}
106
+ return data
@@ -37,6 +37,10 @@ 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")
@@ -67,6 +71,12 @@ JEV_LONG_CONTEXT_CHARS = 24000
67
71
  # 并发上限。官方 cookbook(classifying_rag_passages)取 4,理由是端点限流;
68
72
  # 429/529 要求指数退避,所以不铺大。
69
73
  JEV_MAX_WORKERS = 4
74
+ # 多并发整体截止时间(秒):实测冷调用在 0.55s 左右,提高到 1.2s(覆盖 p95),防止网络抖动导致的误杀 fail-open
75
+ DEFAULT_JEV_DEADLINE_S = 1.2
76
+
77
+ # 结果级缓存(TTL 7 天):常见事实与热点二次判定 0ms 响应,API 消耗清零
78
+ _JEV_MEMORY_CACHE: dict[str, tuple[float, dict[str, Any]]] = {}
79
+ _JEV_CACHE_TTL_S = 7 * 86400
70
80
 
71
81
  # conf ≥ 0.7 才给结论:低于此值的判定不可信(B 实测 4 个严格错误全部 ≤0.67)
72
82
  SUPPORT_THRESHOLD = 0.7
@@ -87,6 +97,135 @@ SOURCE_TYPE_LABELS = (
87
97
  "social narrative",
88
98
  "none of these",
89
99
  )
100
+ SUBSTANTIVE_DISCUSSION_LABELS = (
101
+ "substantive in-depth discussion",
102
+ "passing mention or brief reference",
103
+ "unrelated chatter",
104
+ "none of these",
105
+ )
106
+ SUBSTANTIVE_DISCUSSION_CRITERIA = {
107
+ "substantive in-depth discussion": "The topic is a primary subject, core explanation, or key focus of the text.",
108
+ "passing mention or brief reference": "The topic is only mentioned in passing, as a metaphor, an offhand remark, or a minor tangent.",
109
+ "unrelated chatter": "The text is casual talk or unrelated discussion where the topic is absent or irrelevant.",
110
+ "none of these": "None of the above criteria fit the text.",
111
+ }
112
+
113
+
114
+ def is_local_target(url_or_path: str) -> bool:
115
+ """本地物理隔离屏障:只放行 http/https 公网 URL,其余一律视为本地。
116
+
117
+ 为什么改成白名单(2026-11-11):黑名单靠枚举前缀(`file://`、`~/`、
118
+ `./`、`../`、盘符…),永远列不全。实测 `data:text/plain,...`、
119
+ `localhost:8080/notes.md`、`Users/me/notes.md`(不带 ./ 的相对路径)、
120
+ `C:/Users/x/a.txt`(正斜杠盘符)都会被当成公网 URL 送进 JEV 队列,
121
+ 而 assess_* 送出去的是 title + 正文,等于私域内容外发。
122
+
123
+ 判据反过来:带 scheme 且是 http/https 才算公网;其余(含 ftp/ws、
124
+ data:、无 scheme 的主机名、UNC、相对路径)一律拦。大小写不敏感。
125
+ """
126
+ u = str(url_or_path or "").strip()
127
+ if not u:
128
+ return False
129
+ low = u.lower()
130
+ if low.startswith("http://") or low.startswith("https://"):
131
+ return False
132
+ return True
133
+
134
+
135
+ _RE_HTML_TAGS = re.compile(r"<[^>]+>", re.S)
136
+ _RE_DYNAMIC_TIMESTAMPS = re.compile(
137
+ r"\b(?:\d{4}[-/.]\d{1,2}[-/.]\d{1,2}(?:[ T]\d{1,2}:\d{2}(?::\d{2})?)?|"
138
+ r"\d+\s*(?:seconds?|minutes?|hours?|days?|weeks?|months?|years?|秒|分钟|小时|天|周|月|年)\s*(?:ago|前)|"
139
+ r"(?:today|yesterday|just now|刚刚|今天|昨天))\b",
140
+ re.I,
141
+ )
142
+ _RE_WHITESPACE = re.compile(r"\s+")
143
+
144
+
145
+ def _normalize_cache_text(text: str) -> str:
146
+ """对正文进行稳态清洗以生成稳固的缓存键,消除时间戳/动态元数据导致的键漂移。
147
+
148
+ 不做长度截断(2026-11-11 修):此前取前 1200 字符,而实际送入判定的
149
+ 正文上限是 MAX_TEXT_CHARS=8000——两段仅在第 1200 字符后不同的文本会
150
+ 得到同一个键,从而共享同一个 label/confidence。对语义核验这是正确性
151
+ 缺陷(错误结果还会被缓存 TTL 7 天)。稳态清洗只改「动态元数据」
152
+ (HTML/时间戳/空白),不改语义内容,故全文入键是安全的。
153
+ """
154
+ if not text:
155
+ return ""
156
+ # 1. 剥离 HTML 残留
157
+ s = _RE_HTML_TAGS.sub(" ", text)
158
+ # 2. 剥离常见相对/绝对易变时间戳
159
+ s = _RE_DYNAMIC_TIMESTAMPS.sub(" ", s)
160
+ # 3. 规整空白
161
+ s = _RE_WHITESPACE.sub(" ", s).strip()
162
+ return s
163
+
164
+
165
+ def _get_cache_key(text: str, labels: tuple[str, ...] | list[str],
166
+ instructions: str | None,
167
+ criteria: dict[str, str] | None = None) -> str:
168
+ import hashlib
169
+ crit_repr = str(sorted((criteria or {}).items())) if criteria else str(sorted(str(l) for l in labels))
170
+ norm_text = _normalize_cache_text(text)
171
+ raw = f"{instructions or ''}::{crit_repr}::{norm_text}"
172
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()
173
+
174
+
175
+ def _should_bypass_cache() -> bool:
176
+ import sys
177
+ if os.environ.get("ARGO_NO_CACHE") == "1":
178
+ return True
179
+ if ("pytest" in sys.modules or os.environ.get("PYTEST_CURRENT_TEST")) and not os.environ.get("_TEST_ENABLE_SEMANTIC_CACHE"):
180
+ return True
181
+ return False
182
+
183
+
184
+ def _get_cached_result(key: str) -> Optional[dict[str, Any]]:
185
+ if _should_bypass_cache():
186
+ return None
187
+ cached = _JEV_MEMORY_CACHE.get(key)
188
+ if cached is not None:
189
+ ts, data = cached
190
+ if time.time() - ts < _JEV_CACHE_TTL_S:
191
+ return dict(data)
192
+ try:
193
+ from argo_paths import state_path
194
+ p = Path(state_path("semantic_cache.json"))
195
+ if p.is_file():
196
+ data_map = json.loads(p.read_text(encoding="utf-8"))
197
+ rec = data_map.get(key)
198
+ if rec and isinstance(rec, dict) and time.time() - rec.get("ts", 0) < _JEV_CACHE_TTL_S:
199
+ res = rec.get("result")
200
+ if isinstance(res, dict):
201
+ _JEV_MEMORY_CACHE[key] = (rec.get("ts", time.time()), res)
202
+ return dict(res)
203
+ except Exception:
204
+ pass
205
+ return None
206
+
207
+
208
+ def _set_cached_result(key: str, result: dict[str, Any]) -> None:
209
+ if _should_bypass_cache():
210
+ return
211
+ now = time.time()
212
+ _JEV_MEMORY_CACHE[key] = (now, result)
213
+ try:
214
+ from argo_paths import state_path
215
+ p = Path(state_path("semantic_cache.json"))
216
+ data_map = {}
217
+ if p.is_file():
218
+ try:
219
+ data_map = json.loads(p.read_text(encoding="utf-8"))
220
+ except Exception:
221
+ data_map = {}
222
+ if len(data_map) > 500:
223
+ data_map.clear()
224
+ data_map[key] = {"ts": now, "result": result}
225
+ p.parent.mkdir(parents=True, exist_ok=True)
226
+ p.write_text(json.dumps(data_map, ensure_ascii=False), encoding="utf-8")
227
+ except Exception:
228
+ pass
90
229
 
91
230
 
92
231
  def _config() -> dict[str, Any]:
@@ -209,9 +348,10 @@ def _jev_post(path_state: Any, questions: dict[str, Any], *,
209
348
 
210
349
 
211
350
  def _jev_choice(text: str, labels: tuple[str, ...] | list[str],
212
- instructions: str | None, timeout: float
351
+ instructions: str | None, timeout: float,
352
+ criteria: dict[str, str] | None = None
213
353
  ) -> Optional[dict[str, Any]]:
214
- """单条文本 → 一个 Choice 问题。
354
+ """单条文本 → 一个 Choice 问题(带本地结果级 Hash 缓存,命中 0ms)。
215
355
 
216
356
  **每条一个请求**,不是「多段一个 state、每段一问」。理由在官方文档里:
217
357
  jaggedness 那篇明写「state 里塞与决策无关的细节会降低准确率(context
@@ -219,13 +359,19 @@ def _jev_choice(text: str, labels: tuple[str, ...] | list[str],
219
359
  classifying_rag_passages 也是「One request per passage」。(我们试过 3 段
220
360
  合一,结果全对,但样本太小,不拿它赌准确率。)
221
361
  """
362
+ cache_key = _get_cache_key(text, labels, instructions, criteria=criteria)
363
+ cached = _get_cached_result(cache_key)
364
+ if cached is not None:
365
+ return cached
366
+
367
+ crit_map = criteria or {str(lab): str(lab) for lab in labels}
222
368
  out = _jev_post(text, {
223
369
  "cls": {
224
370
  "type": "choice",
225
371
  "instructions": instructions or "Classify the state into one of the criteria.",
226
372
  # criteria 的**值**是描述:jaggedness 说 instructions 与 criteria
227
- # 不一致时模型会困惑,所以两边用同一句话,不给它两个版本。
228
- "criteria": {str(lab): str(lab) for lab in labels},
373
+ # 不一致时模型会困惑,所以未显式给描述时两边用同一句话。
374
+ "criteria": crit_map,
229
375
  },
230
376
  }, timeout=timeout)
231
377
  if not isinstance(out, dict):
@@ -235,27 +381,51 @@ def _jev_choice(text: str, labels: tuple[str, ...] | list[str],
235
381
  if isinstance(ans, dict):
236
382
  logger.debug("JEV 答案缺 choice: %s", str(ans)[:120])
237
383
  return None
238
- return {
384
+ res = {
239
385
  "label": str(ans.get("choice")),
240
386
  "confidence": ans.get("confidence"),
241
387
  "scores": ans.get("probabilities"),
242
388
  }
389
+ _set_cached_result(cache_key, res)
390
+ return res
243
391
 
244
392
 
245
393
  def _classify_jev(texts: list[str], labels: tuple[str, ...] | list[str], *,
246
- instructions: str | None, keep: list[tuple[int, str]],
394
+ instructions: str | None, criteria: dict[str, str] | None = None,
395
+ keep: list[tuple[int, str]],
247
396
  timeout: float) -> Optional[list[dict[str, Any]]]:
248
- """JEV 通道:每条文本一个请求,并发 4。
397
+ """JEV 通道:每条文本一个请求,并发 4,带总体时间硬截止预算。
249
398
 
250
399
  任一条失败就在该位留 None(与 classifier.dev 通道「整批失败即 None」
251
400
  不同):一次核验有几条正文,坏一条不该把其余判定的价值也丢掉。全部失败
252
401
  时仍返回 None,调用方行为与未开启时一致。
253
402
  """
254
- from concurrent.futures import ThreadPoolExecutor
403
+ from concurrent.futures import ThreadPoolExecutor, as_completed
255
404
  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))
405
+ deadline_s = DEFAULT_JEV_DEADLINE_S
406
+ results: list[Optional[dict[str, Any]]] = [None] * len(texts_kept)
407
+
408
+ # 不能用 `with ThreadPoolExecutor(...)`:with 退出时 shutdown(wait=True)
409
+ # 会把 as_completed 超时后仍在跑的请求全部 join 完,硬截止形同虚设
410
+ # (实测 sleep 3s 的任务让整轮耗时 3.01s)。这里显式建池、超时后
411
+ # shutdown(wait=False, cancel_futures=True),只保留已完成的结果就返回。
412
+ # 未完成的任务内部仍由 HttpClient 的 timeout 兜底,不阻塞调用方。
413
+ pool = ThreadPoolExecutor(max_workers=min(JEV_MAX_WORKERS, len(texts_kept)))
414
+ try:
415
+ futures = {pool.submit(_jev_choice, t, labels, instructions, timeout, criteria): idx
416
+ for idx, t in enumerate(texts_kept)}
417
+ try:
418
+ for fut in as_completed(futures, timeout=max(0.1, deadline_s)):
419
+ orig_idx = futures[fut]
420
+ try:
421
+ results[orig_idx] = fut.result()
422
+ except Exception:
423
+ results[orig_idx] = None
424
+ except TimeoutError:
425
+ pass
426
+ finally:
427
+ pool.shutdown(wait=False, cancel_futures=True)
428
+
259
429
  if not any(r for r in results):
260
430
  return None
261
431
  out: list[Optional[dict[str, Any]]] = [None] * len(texts)
@@ -267,6 +437,7 @@ def _classify_jev(texts: list[str], labels: tuple[str, ...] | list[str], *,
267
437
 
268
438
  def classify(texts: list[str], labels: tuple[str, ...] | list[str], *,
269
439
  instructions: str | None = None,
440
+ criteria: dict[str, str] | None = None,
270
441
  timeout: float | None = None,
271
442
  tier: str | None = None) -> Optional[list[dict[str, Any]]]:
272
443
  """一次批量分类。任何异常/非 200/条数不匹配 → None。
@@ -285,7 +456,7 @@ def classify(texts: list[str], labels: tuple[str, ...] | list[str], *,
285
456
  to = timeout or _timeout()
286
457
  if _transport() == "jev":
287
458
  return _classify_jev(texts, labels, instructions=instructions,
288
- keep=keep, timeout=to)
459
+ criteria=criteria, keep=keep, timeout=to)
289
460
  body: dict[str, Any] = {
290
461
  "labels": [str(x) for x in labels],
291
462
  "inputs": [t[:MAX_TEXT_CHARS] for _i, t in keep],
@@ -326,8 +497,10 @@ def assess_support(query: str, items: list[dict[str, Any]]) -> Optional[dict[str
326
497
  返回 {url: {label, confidence, supports, contradicts}};未达阈值时
327
498
  supports/contradicts 均为 False(原始 label 与 confidence 仍原样保留,
328
499
  调用方可自行换阈值)。失败返回 None。
500
+ 自动剔除本地文件(is_local_target),严格物理阻断私域外发。
329
501
  """
330
- usable = [it for it in items if (it.get("text") or "").strip() and it.get("url")]
502
+ usable = [it for it in items if (it.get("text") or "").strip() and it.get("url")
503
+ and not is_local_target(it.get("url", ""))]
331
504
  if not usable:
332
505
  return None
333
506
  texts = [f"{it.get('title') or ''}\n{(it.get('text') or '')[:MAX_TEXT_CHARS]}"
@@ -362,9 +535,11 @@ def assess_source_types(items: list[dict[str, Any]]) -> Optional[dict[str, dict]
362
535
  """来源类型分级(研究取证链路用):一手数据 / 二手报道 / 分析观点 / 社交叙事。
363
536
 
364
537
  items: [{"url": str, "title": str, "text": str}](text 可为摘要)
538
+ 自动剔除本地文件(is_local_target),严格物理阻断私域外发。
365
539
  """
366
540
  usable = [it for it in items if it.get("url") and
367
- ((it.get("text") or "").strip() or (it.get("title") or "").strip())]
541
+ ((it.get("text") or "").strip() or (it.get("title") or "").strip())
542
+ and not is_local_target(it.get("url", ""))]
368
543
  if not usable:
369
544
  return None
370
545
  texts = [f"{it.get('title') or ''}\n{(it.get('text') or '')[:MAX_TEXT_CHARS]}"
@@ -384,8 +559,48 @@ def assess_source_types(items: list[dict[str, Any]]) -> Optional[dict[str, dict]
384
559
  continue
385
560
  label = str(r.get("label") or "")
386
561
  conf = r.get("confidence")
562
+ conf_f = float(conf) if isinstance(conf, (int, float)) else 0.0
387
563
  out[str(it["url"])] = {
388
564
  "label": label,
389
- "confidence": float(conf) if isinstance(conf, (int, float)) else 0.0,
565
+ "confidence": conf_f,
566
+ "is_primary": (label == "primary data or official announcement" and conf_f >= SUPPORT_THRESHOLD),
567
+ }
568
+ return out or None
569
+
570
+
571
+ def assess_substantive_discussion(topic: str, items: list[dict[str, Any]]) -> Optional[dict[str, dict]]:
572
+ """对正文/播客单集转录/长篇段落批量判定「是否对主题进行了实质性深入探讨」。
573
+
574
+ 用于复杂需求与播客/音视频长文本场景,区分:
575
+ - substantive in-depth discussion: 深入、实质性探讨或核心讲解
576
+ - passing mention or brief reference: 顺带提及、比喻借用或偏题带过
577
+ - unrelated chatter: 闲聊或偏离主题
578
+ 自动剔除本地文件(is_local_target),严格物理阻断私域外发。
579
+ """
580
+ usable = [it for it in items if (it.get("text") or "").strip() and it.get("url")
581
+ and not is_local_target(it.get("url", ""))]
582
+ if not usable:
583
+ return None
584
+ texts = [f"{it.get('title') or ''}\n{(it.get('text') or '')[:MAX_TEXT_CHARS]}"
585
+ for it in usable]
586
+ instructions = f"Determine the depth of discussion regarding the topic {topic!r} in the text."
587
+ results = classify(texts, SUBSTANTIVE_DISCUSSION_LABELS,
588
+ instructions=instructions,
589
+ criteria=SUBSTANTIVE_DISCUSSION_CRITERIA)
590
+ if results is None:
591
+ return None
592
+ out: dict[str, dict] = {}
593
+ for it, r in zip(usable, results):
594
+ if not r:
595
+ continue
596
+ label = str(r.get("label") or "")
597
+ conf = r.get("confidence")
598
+ conf_f = float(conf) if isinstance(conf, (int, float)) else 0.0
599
+ out[str(it["url"])] = {
600
+ "label": label,
601
+ "confidence": conf_f,
602
+ "is_substantive": (label == "substantive in-depth discussion" and conf_f >= SUPPORT_THRESHOLD),
603
+ "is_passing_mention": (label == "passing mention or brief reference" and conf_f >= SUPPORT_THRESHOLD),
390
604
  }
391
605
  return out or None
606
+