argo-search 2.17.0 → 2.18.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 (70) hide show
  1. package/AGENTS.md +3 -3
  2. package/README.es.md +10 -5
  3. package/README.ja.md +10 -5
  4. package/README.ko.md +10 -5
  5. package/README.md +11 -6
  6. package/README.zh.md +11 -6
  7. package/SKILL.md +12 -11
  8. package/assets/readme/counts.json +1 -1
  9. package/assets/readme/hero.svg +3 -3
  10. package/backends/domain_profiles.json +6 -0
  11. package/backends/engine_registry.yaml +12 -0
  12. package/backends/quota_profiles.json +10 -0
  13. package/bin/argo +78 -12
  14. package/docs/CHANGELOG.md +19 -1
  15. package/docs/COMMIT_STANDARD.md +2 -2
  16. package/docs/ENGINE_CATALOG.md +7 -6
  17. package/docs/RELEASE_NOTES_v2.17.0.md +4 -2
  18. package/docs/RELEASE_NOTES_v2.18.0.md +87 -0
  19. package/docs/RELEASING.md +1 -1
  20. package/engines/specs/twitter_cli.yaml +17 -0
  21. package/engines/specs/twitter_syndication.yaml +2 -3
  22. package/package.json +2 -1
  23. package/packages/dsh-plugin/dsh/native-tools.mjs +10 -0
  24. package/packages/dsh-plugin/dsh/workbench-io.js +34 -15
  25. package/packages/dsh-plugin/dsh/workbench-search.js +66 -6
  26. package/packages/dsh-plugin/dsh/workbench.js +43 -0
  27. package/packages/dsh-plugin/package.json +1 -1
  28. package/packages/dsh-plugin/test/workbench-concurrency.test.js +9 -11
  29. package/packages/dsh-plugin/test/workbench.test.js +85 -0
  30. package/scripts/affected_tests.py +324 -0
  31. package/scripts/badcase_ledger.py +93 -2
  32. package/scripts/check_commit_report.py +13 -9
  33. package/scripts/cli_io.py +8 -3
  34. package/scripts/engine_families.py +1 -0
  35. package/scripts/engine_states.py +4 -4
  36. package/scripts/engines.py +2 -0
  37. package/scripts/engines_base.py +12 -28
  38. package/scripts/engines_builders_intl.py +20 -94
  39. package/scripts/engines_twitter_cli.py +182 -0
  40. package/scripts/fetch_cli_output.py +75 -0
  41. package/scripts/fetch_dispatch.py +248 -0
  42. package/scripts/fetch_quality.py +11 -0
  43. package/scripts/fetch_v3.py +48 -114
  44. package/scripts/intent_router.py +224 -0
  45. package/scripts/mcp_compact.py +3 -0
  46. package/scripts/mcp_handlers.py +24 -4
  47. package/scripts/mcp_tools.py +2 -0
  48. package/scripts/mcp_transport.py +1 -1
  49. package/scripts/mcp_warm.py +15 -11
  50. package/scripts/output_transparency.py +10 -0
  51. package/scripts/pre-commit +9 -1
  52. package/scripts/release_check.py +1 -2
  53. package/scripts/research_notes.py +52 -5
  54. package/scripts/retry_policy.py +17 -3
  55. package/scripts/route_combo.py +8 -3
  56. package/scripts/search.py +29 -29
  57. package/scripts/search_cli.py +104 -8
  58. package/scripts/search_output.py +4 -1
  59. package/scripts/social_research.py +8 -6
  60. package/scripts/time_utils.py +28 -0
  61. package/scripts/twitter_single_read.py +107 -0
  62. package/scripts/x_keyword_route.py +138 -0
  63. package/scripts/x_search.py +24 -33
  64. package/scripts/zhihu_answer_body.py +96 -0
  65. package/scripts/zhihu_answer_fetch.py +66 -0
  66. package/scripts/zhihu_answer_lookup.py +138 -0
  67. package/sub-skills/local-seek/SKILL.md +3 -1
  68. package/sub-skills/local-seek/scripts/seek.py +80 -109
  69. package/sub-skills/local-seek/scripts/seek_git.py +65 -0
  70. package/sub-skills/local-seek/scripts/seek_inspect.py +242 -0
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env python3
2
+ """intent_router.py — 高层意图路由(--intent)。
3
+
4
+ 把「调用方记忆 explicit_only 引擎名」转为「声明查询意图」:
5
+ - news 时事/动态:有密钥且未超预算(且非 fast 模式)走 deepseek_search,
6
+ 否则透明降级到自动路由 + domain=news 并附降级说明;
7
+ - academic 学术多源:depth 至少为 deep + domain=academic;
8
+ - social 社交与社区:domain=social;
9
+ - image-reverse 反搜图:自动从 animetrace/tracemoe/saucenao/google_lens 选取可用源;
10
+ - calc 精确计算/换算:wolframalpha 可用时自动启用,否则降级 auto 并提示。
11
+
12
+ 设计约束:
13
+ - 仅在显式传入 --intent 时由 search_cli.py 懒加载,默认路径零启动开销;
14
+ - 所有环境/配额/配置探测器均支持依赖注入,便于离线单测与回退验证。
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any, Callable
20
+
21
+ SUPPORTED_INTENTS: tuple[str, ...] = (
22
+ "news",
23
+ "academic",
24
+ "social",
25
+ "image-reverse",
26
+ "calc",
27
+ )
28
+
29
+ _REVERSE_IMAGE_CANDIDATES: tuple[str, ...] = (
30
+ "animetrace",
31
+ "tracemoe",
32
+ "saucenao",
33
+ "google_lens",
34
+ )
35
+
36
+ # 垂直意图引擎前置表(传给 super_search.engines_boost,真正驱动选源而不仅改缓存键)
37
+ _INTENT_BOOST: dict[str, list[str]] = {
38
+ "academic": ["arxiv", "openalex", "semantic_scholar", "local_pubmed"],
39
+ "social": ["anysearch", "reddit", "zhihu", "hackernews"],
40
+ "news_fallback": ["anysearch", "google_news", "em_global_news", "cn_ai_news"],
41
+ }
42
+
43
+
44
+ def _default_get_engines() -> dict[str, dict[str, Any]]:
45
+ from config import get_engines
46
+ return get_engines()
47
+
48
+
49
+ def _default_missing_env(engine_id: str, spec: dict[str, Any] | None) -> list[str]:
50
+ from engine_env import missing_env_for
51
+ return missing_env_for(engine_id, spec)
52
+
53
+
54
+ def _default_quota_available(engine_id: str, mode: str) -> bool:
55
+ from quota import get_quota_manager
56
+ return get_quota_manager().is_available(engine_id, mode=mode)
57
+
58
+
59
+ def _engine_ready(
60
+ engine_id: str,
61
+ engines_cfg: dict[str, dict[str, Any]],
62
+ mode: str,
63
+ check_env: Callable[[str, dict[str, Any] | None], list[str]],
64
+ check_quota: Callable[[str, str], bool],
65
+ ) -> tuple[bool, str]:
66
+ """检查单个目标引擎是否可用,返回 (ready, unavailable_reason)。"""
67
+ spec = engines_cfg.get(engine_id)
68
+ if not isinstance(spec, dict) or not spec.get("enabled", True):
69
+ return False, f"{engine_id} 未启用"
70
+ missing = check_env(engine_id, spec)
71
+ if missing:
72
+ return False, f"{engine_id} 缺少环境变量 {', '.join(missing)}"
73
+ if not check_quota(engine_id, mode):
74
+ return False, f"{engine_id} 配额或月度预算已耗尽"
75
+ return True, ""
76
+
77
+
78
+ def resolve_intent(
79
+ intent: str,
80
+ *,
81
+ engine: str = "auto",
82
+ domain: str | None = None,
83
+ depth: str = "fast",
84
+ mode: str = "auto",
85
+ get_engines_fn: Callable[[], dict[str, dict[str, Any]]] | None = None,
86
+ check_env_fn: Callable[[str, dict[str, Any] | None], list[str]] | None = None,
87
+ check_quota_fn: Callable[[str, str], bool] | None = None,
88
+ ) -> dict[str, Any]:
89
+ """将高层意图解析为 (engine, domain, depth) 与可审计的降级说明。"""
90
+ if intent not in SUPPORTED_INTENTS:
91
+ raise ValueError(
92
+ f"不支持的意图 {intent!r},可选: {', '.join(SUPPORTED_INTENTS)}"
93
+ )
94
+
95
+ explicit_engine = bool(engine and engine != "auto")
96
+ resolved_engine = engine or "auto"
97
+ resolved_domain = domain or None
98
+ resolved_depth = depth or "fast"
99
+ degraded = False
100
+ reason = ""
101
+ warnings: list[str] = []
102
+
103
+ if intent == "academic":
104
+ if not resolved_domain:
105
+ resolved_domain = "academic"
106
+ if resolved_depth == "fast":
107
+ resolved_depth = "deep"
108
+ boost = None if explicit_engine else list(_INTENT_BOOST["academic"])
109
+ reason = ("学术多源模式(depth=deep,引擎前置 arxiv/openalex/"
110
+ "semantic_scholar/local_pubmed)")
111
+ if explicit_engine:
112
+ warnings.append(f"--engine {engine} 覆盖了 --intent {intent} 的默认多源路由")
113
+ return _pack(
114
+ intent, resolved_engine, resolved_domain, resolved_depth,
115
+ degraded, reason, explicit_engine, warnings, engines_boost=boost,
116
+ )
117
+
118
+ if intent == "social":
119
+ if not resolved_domain:
120
+ resolved_domain = "social"
121
+ boost = None if explicit_engine else list(_INTENT_BOOST["social"])
122
+ # reason 只说真实发生的事:本意图靠 engines_boost 把社交源前置,
123
+ # `domain=social` 只是缓存键隔离标记,不参与选源(route_query 从不读
124
+ # engine_domain)。旧措辞「社交与社区垂直域」会让调用方以为结果已被
125
+ # 限定在社区域内——实测同一 query 带不带该 domain,路由逐位相同。
126
+ reason = ("社交意图(引擎前置 anysearch/reddit/zhihu/hackernews;"
127
+ "domain 不参与选源,仅隔离缓存键)")
128
+ if explicit_engine:
129
+ warnings.append(f"--engine {engine} 覆盖了 --intent {intent} 的默认多源路由")
130
+ return _pack(
131
+ intent, resolved_engine, resolved_domain, resolved_depth,
132
+ degraded, reason, explicit_engine, warnings, engines_boost=boost,
133
+ )
134
+
135
+ if explicit_engine:
136
+ warnings.append(f"--engine {engine} 覆盖了 --intent {intent} 的默认引擎选择")
137
+ if intent == "news" and not resolved_domain:
138
+ resolved_domain = "news"
139
+ return _pack(
140
+ intent, resolved_engine, resolved_domain, resolved_depth,
141
+ False, f"已由显式 --engine {engine} 覆盖", True, warnings,
142
+ )
143
+
144
+ engines_cfg = (get_engines_fn or _default_get_engines)()
145
+ check_env = check_env_fn or _default_missing_env
146
+ check_quota = check_quota_fn or _default_quota_available
147
+
148
+ engines_boost: list[str] | None = None
149
+ if intent == "news":
150
+ if mode == "fast":
151
+ degraded = True
152
+ resolved_domain = resolved_domain or "news"
153
+ engines_boost = list(_INTENT_BOOST["news_fallback"])
154
+ reason = "mode=fast 跳过付费时事源 deepseek_search,已降级为免费新闻优先路由"
155
+ warnings.append(f"[intent:news] {reason}")
156
+ else:
157
+ ok, why = _engine_ready("deepseek_search", engines_cfg, mode, check_env, check_quota)
158
+ if ok:
159
+ resolved_engine = "deepseek_search"
160
+ reason = "时事意图自动命中 deepseek_search(密钥与预算均可用)"
161
+ else:
162
+ degraded = True
163
+ resolved_domain = resolved_domain or "news"
164
+ engines_boost = list(_INTENT_BOOST["news_fallback"])
165
+ reason = f"{why},已降级为新闻优先自动路由(domain=news)"
166
+ warnings.append(f"[intent:news] {reason}")
167
+
168
+ elif intent == "image-reverse":
169
+ usable: list[str] = []
170
+ block_reasons: list[str] = []
171
+ for cand in _REVERSE_IMAGE_CANDIDATES:
172
+ ok, why = _engine_ready(cand, engines_cfg, mode, check_env, check_quota)
173
+ if ok:
174
+ usable.append(cand)
175
+ elif why:
176
+ block_reasons.append(why)
177
+ if usable:
178
+ chosen = usable[:2]
179
+ resolved_engine = ",".join(chosen)
180
+ reason = f"反搜图自动选取可用源: {resolved_engine}"
181
+ else:
182
+ degraded = True
183
+ reason = f"反搜图候选源均不可用({'; '.join(block_reasons[:3])}),已降级为自动路由"
184
+ warnings.append(f"[intent:image-reverse] {reason}")
185
+
186
+ elif intent == "calc":
187
+ ok, why = _engine_ready("wolframalpha", engines_cfg, mode, check_env, check_quota)
188
+ if ok:
189
+ resolved_engine = "wolframalpha"
190
+ reason = "计算意图自动命中 wolframalpha"
191
+ else:
192
+ degraded = True
193
+ reason = f"{why},已降级为自动路由"
194
+ warnings.append(f"[intent:calc] {reason}")
195
+
196
+ return _pack(
197
+ intent, resolved_engine, resolved_domain, resolved_depth,
198
+ degraded, reason, False, warnings, engines_boost=engines_boost,
199
+ )
200
+
201
+
202
+ def _pack(
203
+ intent: str,
204
+ engine: str,
205
+ domain: str | None,
206
+ depth: str,
207
+ degraded: bool,
208
+ reason: str,
209
+ overridden: bool,
210
+ warnings: list[str],
211
+ *,
212
+ engines_boost: list[str] | None = None,
213
+ ) -> dict[str, Any]:
214
+ return {
215
+ "intent": intent,
216
+ "engine": engine,
217
+ "domain": domain,
218
+ "depth": depth,
219
+ "engines_boost": engines_boost,
220
+ "degraded": degraded,
221
+ "reason": reason,
222
+ "overridden_by_engine": overridden,
223
+ "warnings": warnings,
224
+ }
@@ -35,6 +35,8 @@ def _compact_search_result(result: dict[str, Any], summary: bool = False) -> dic
35
35
  "input_kind": result.get("input_kind"),
36
36
  "login_hint": result.get("login_hint"),
37
37
  }
38
+ if result.get("errors"):
39
+ out["errors"] = result["errors"][:12]
38
40
  results = []
39
41
  for r in result.get("results") or []:
40
42
  if not isinstance(r, dict):
@@ -95,6 +97,7 @@ def _compact_search_result(result: dict[str, Any], summary: bool = False) -> dic
95
97
  "status": o.get("status"),
96
98
  "latency_ms": o.get("latency_ms"),
97
99
  "results_count": o.get("results_count"),
100
+ **({"error_kind": o["error_kind"]} if o.get("error_kind") else {}),
98
101
  }
99
102
  for o in outcomes
100
103
  if isinstance(o, dict)
@@ -132,10 +132,10 @@ def _resolve_research_profile(arguments: dict[str, Any]) -> tuple[dict[str, Any]
132
132
 
133
133
 
134
134
  def _search_social_platforms(
135
- platforms: list[str], query: str, n: int, timeout: float = 20.0,
135
+ platforms: list[str], query: str, n: int, timeout: float = 20.0, **kwargs,
136
136
  ) -> tuple[dict[str, list], list[str], list[str]]:
137
137
  """并行抓取多社交平台(MCP 热路径)。"""
138
- return _warm_search_social_platforms(platforms, query, n, timeout=timeout, lazy_cached_fn=_lazy_cached)
138
+ return _warm_search_social_platforms(platforms, query, n, timeout=timeout, lazy_cached_fn=_lazy_cached, **kwargs)
139
139
 
140
140
 
141
141
  def _env_bool(name: str, default: bool = False) -> bool:
@@ -260,7 +260,14 @@ def execute_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
260
260
  query = arguments["query"]
261
261
  n = _clamp_int(
262
262
  arguments.get("max_results", arguments.get("num", 5)), 5, 1, 20)
263
- platform_results, engines_used, errors = _search_social_platforms(platforms, query, n)
263
+ from x_keyword_route import X_ENGINES
264
+ engine = arguments.get("engine", "auto")
265
+ if engine in X_ENGINES:
266
+ platforms = ["twitter"]
267
+ outcomes = []
268
+ platform_results, engines_used, errors = _search_social_platforms(
269
+ platforms, query, n, x_engine=engine if engine in X_ENGINES else "auto",
270
+ since=arguments.get("since"), until=arguments.get("until"), outcomes=outcomes)
264
271
  if str(arguments.get("mode", "text")).strip().lower() in (
265
272
  "sentiment", "social-sentiment"):
266
273
  research_mod = _lazy_cached("research")
@@ -278,6 +285,9 @@ def execute_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
278
285
  "count": len(all_results),
279
286
  "engines_used": engines_used,
280
287
  }
288
+ if outcomes:
289
+ output["engine_outcomes"] = outcomes
290
+ output["engines_used"] = engines_used
281
291
  if errors:
282
292
  output["errors"] = errors
283
293
  return _ok(output, pretty=pretty)
@@ -431,6 +441,13 @@ def execute_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
431
441
  url = arguments["url"]
432
442
  mode = arguments.get("mode", "text")
433
443
 
444
+ if "answer_offset" in arguments and (mode != "text" or type(arguments["answer_offset"]) is not int or arguments["answer_offset"] < 0):
445
+ raise ValueError("answer_offset 仅用于 text 模式,须为非负整数。")
446
+ if "answer_offset" in arguments:
447
+ from zhihu_answer_fetch import match_answer
448
+ if not match_answer(url):
449
+ raise ValueError("answer_offset 需要精确的知乎回答 URL。")
450
+
434
451
  # 微信公众号文章原生自适应
435
452
  if "mp.weixin.qq.com" in url or mode == "article":
436
453
  article_mod = _lazy_cached("article")
@@ -497,14 +514,17 @@ def execute_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
497
514
  timeout=_env_int("ARGO_MCP_TIMEOUT_FETCH", _int_param(arguments, "timeout", 15)),
498
515
  use_browser_fallback=True,
499
516
  force_browser=arguments.get("use_browser", False),
517
+ answer_offset=arguments.get("answer_offset"),
500
518
  )
501
519
  if focus_query and result.get("success"):
502
520
  focus_mod = _lazy_cached("focus_extract")
503
521
  focus_mod.apply_focus(result, focus_query,
504
522
  max_chars=_clamp_int(
505
523
  _int_param(arguments, "max_chars", 8000), 8000, 500, 50000))
524
+ from zhihu_answer_fetch import finish_focus
525
+ finish_focus(result, _clamp_int(_int_param(arguments, "max_chars", 8000), 8000, 500, 50000))
506
526
  if not result.get("focus_applied"):
507
- result["focus_note"] = "内容未达聚焦阈值,返回全文"
527
+ result["focus_note"] = "内容未达聚焦阈值,按字符上限返回"
508
528
  if arguments.get("summary", True) and isinstance(result.get("content"), str):
509
529
  max_c = _clamp_int(_int_param(arguments, "max_chars", 8000), 8000, 500, 50000)
510
530
  if len(result["content"]) > max_c:
@@ -117,6 +117,7 @@ TOOLS = [
117
117
  "properties": {
118
118
  "query": {"type": "string", "description": "搜索查询词"},
119
119
  "domain": {"type": "string", "enum": ["web", "social", "job", "local"], "description": "搜索领域:web 统一网络搜索(默认),social 社交媒体/论坛讨论,job 招聘岗位聚合,local 本机文件搜索"},
120
+ "platforms": {"type": "string", "description": "domain=social 的平台名,逗号分隔。twitter 表示 X 关键词自动选路;固定通道用 engine=fxtwitter/twitter_cli/twitter。"},
120
121
  "engine": {"type": "string", "description": "指定搜索引擎(auto 自动选择;可选 octen/anysearch/exa/zhihu/eastmoney/arxiv/byted/bocha/tavily/deepseek_search/github/wikipedia/semantic_scholar/local_search 等,默认 auto;deepseek_search 为按次计费的官方 DeepSeek 搜索,结果带权威分级与发布时间,新闻时事类查询优先考虑)"},
121
122
  "max_results": {"type": "integer", "description": "返回结果条数(1-20,默认 5)"},
122
123
  "depth": {"type": "string", "enum": ["fast", "balanced", "deep"], "description": "搜索深度:fast 快、deep 全(慢),默认 fast"},
@@ -245,6 +246,7 @@ TOOLS = [
245
246
  "extract_mode": {"type": "string", "enum": ["tables", "metadata", "jsonld", "all"], "description": "mode=extract 时的提取子模式,默认 all"},
246
247
  "focus": {"type": "string", "description": "BM25 聚焦查询词:只返回相关段落,省 token(仅 mode=text)"},
247
248
  "max_chars": {"type": "integer", "description": "返回正文最大字符数(500-50000,默认 8000)"},
249
+ "answer_offset": {"type": "integer", "description": "知乎回答摘要查询偏移:首轮省略;仅在用户明确要求续查时传上次的 next_offset"},
248
250
  "use_browser": {"type": "boolean", "description": "强制用反检测浏览器(HTTP 失败时已自动升级,默认关)"},
249
251
  "include_links": {"type": "boolean", "description": "附带正文内链接(最多 30 条;默认只回 links_count,省 token,默认关)"},
250
252
  },
@@ -39,7 +39,7 @@ except Exception: # pragma: no cover
39
39
 
40
40
  # 版本来源:与 package.json / SKILL.md 保持一致(发布时统一升版;
41
41
  # tests/test_consistency_gates.py 会四端对账,漂移即红)
42
- ARGO_MCP_VERSION = "2.17.0"
42
+ ARGO_MCP_VERSION = "2.18.0"
43
43
 
44
44
  _response_format = "content-length" # 根据客户端请求自动切换
45
45
 
@@ -87,22 +87,26 @@ def _resolve_research_profile(arguments: dict[str, Any], lazy_cached_fn) -> tupl
87
87
 
88
88
  def _search_social_platforms(
89
89
  platforms: list[str], query: str, n: int, timeout: float = 20.0,
90
- lazy_cached_fn=None,
90
+ lazy_cached_fn=None, *, x_engine="auto", since=None, until=None, outcomes=None,
91
91
  ) -> tuple[dict[str, list], list[str], list[str]]:
92
92
  """并行抓取多社交平台(MCP 热路径)。"""
93
93
  platform_results: dict[str, list] = {}
94
94
  errors: list[str] = []
95
95
  engines_used: list[str] = []
96
96
 
97
- def _one(platform: str) -> tuple[str, list, str | None]:
97
+ def _one(platform: str):
98
+ if platform in ("twitter", "x"):
99
+ from x_keyword_route import search_x_keywords
100
+ result = search_x_keywords(query, n, engine=x_engine, since=since, until=until, timeout=timeout)
101
+ return result["results"], result["errors"], result["engines_used"], result["engine_outcomes"]
98
102
  module_name = platform.replace("-", "_") + "_engine"
99
103
  try:
100
104
  mod = lazy_cached_fn(f"social_engines.{module_name}")
101
- return platform, mod.search(query, n=n), None
105
+ return mod.search(query, n=n), [], [platform], []
102
106
  except ImportError:
103
- return platform, [], f"Platform {platform} not available (module social_engines.{module_name})"
107
+ return [], [f"Platform {platform} not available (module social_engines.{module_name})"], [], []
104
108
  except Exception as e:
105
- return platform, [], f"{platform}: {str(e)[:100]}"
109
+ return [], [f"{platform}: {str(e)[:100]}"], [], []
106
110
 
107
111
  workers = min(max(len(platforms), 1), 4)
108
112
  import concurrent.futures
@@ -110,12 +114,12 @@ def _search_social_platforms(
110
114
  futs = {ex.submit(_one, p): p for p in platforms}
111
115
  try:
112
116
  for fut in concurrent.futures.as_completed(futs, timeout=timeout):
113
- platform, results, err = fut.result()
114
- platform_results[platform] = results
115
- if err:
116
- errors.append(err)
117
- elif results is not None:
118
- engines_used.append(platform)
117
+ results, issues, used, attempts = fut.result()
118
+ platform_results[futs[fut]] = results
119
+ errors.extend(issues)
120
+ engines_used.extend(used)
121
+ if outcomes is not None:
122
+ outcomes.extend(attempts)
119
123
  except concurrent.futures.TimeoutError:
120
124
  for fut, platform in futs.items():
121
125
  if not fut.done():
@@ -101,6 +101,16 @@ def build_failures(result: dict[str, Any], limit: int = 6) -> list[dict[str, Any
101
101
  seen.add(key)
102
102
  category, action, retryable = _FAILURE_META.get(
103
103
  status, ("unknown", "源端异常;可重试或换源", True))
104
+ # 当 status 落入通用 error/unknown 但携带原始 HTTP 状态码时,按状态码兜底
105
+ # 归因,避免 429/401/403/5xx 被降级成 failure_kinds=unknown 污染坏例账本。
106
+ http_st = o.get("http_status")
107
+ if category == "unknown" and isinstance(http_st, int):
108
+ if http_st == 429:
109
+ category, action, retryable = _FAILURE_META[engine_states.OUTCOME_RATE_LIMITED]
110
+ elif http_st in (401, 403):
111
+ category, action, retryable = _FAILURE_META[engine_states.OUTCOME_AUTH_FAILED]
112
+ elif 500 <= http_st < 600:
113
+ category, action, retryable = ("transient", f"源端 HTTP {http_st} 临时故障;可重试或换源", True)
104
114
  item: dict[str, Any] = {
105
115
  "engine": engine,
106
116
  "status": status,
@@ -117,7 +117,6 @@ if [ -z "$PY" ]; then
117
117
  exit 1
118
118
  fi
119
119
 
120
- printf "[pre-commit] argo 快门禁(74 条 4 片并行,实测 ~8s,解释器 %s;全量回归请手动跑 tests/)...\n" "$PY"
121
120
  # 测试清单单真源:tests/gate_manifest.txt(2026-11-14 收口)。
122
121
  # 清单曾在此手工枚举 42 个文件,每轮新门禁「漏一道加一道」(头注释史
123
122
  # 至少 6 轮),env/config 对账门三道长期漏册——现由 tests/test_gate_manifest.py
@@ -130,6 +129,11 @@ if [ ! -f "$MANIFEST" ]; then
130
129
  echo "[pre-commit] 缺 $MANIFEST,快门禁清单无真源,门禁视为失败" >&2
131
130
  exit 1
132
131
  fi
132
+ # 条数从清单真源现算(2026-11-24):这里是手抄数字的第三个副本,manifest 从
133
+ # 74 涨到 76 时不会变红——AGENTS.md 有 test_agents_md_precommit_file_count_matches
134
+ # 对拍,本行没有。打印值与实际跑的分片内容不一致会误导「跑了多少道门」的判断。
135
+ GATE_COUNT=$(grep -Ev '(^[[:space:]]*#|^[[:space:]]*$)' "$MANIFEST" | wc -l | tr -d ' ')
136
+ printf "[pre-commit] argo 快门禁(%s 条 4 片并行,实测 ~8s,解释器 %s;全量回归请手动跑 tests/)...\n" "$GATE_COUNT" "$PY"
133
137
  # 新增测试文件当场归类(2026-11-21 审计):test_gate_manifest.py 的词根
134
138
  # 反向断言拦不住命名不带 gate/… 的 <1s 文件(两个漏册实证),本检查把
135
139
  # 拦截点前移到 commit 时刻——staged 新增 tests/test_*.py 必须入册;存量
@@ -169,6 +173,10 @@ else
169
173
  fi
170
174
  fi
171
175
 
176
+ # L2 变更感知增量选测(2026-11-24 方案三):按 staged 改动反查未入册的 343 个
177
+ # 存量单测并在 8s 预算内精准执行,补齐「本地绿、全量红」盲区;无命中 <0.25s。
178
+ "$PY" scripts/affected_tests.py --staged --run --budget 8
179
+
172
180
  # 派生件一致性门禁(P0-2):写完 spec 不跑 sync 就提交,派生件会过期。
173
181
  # 实测 0.13s,进 pre-commit 不触发 --no-verify 绕过。
174
182
  echo "[pre-commit] 派生件一致性校验与自愈同步..."
@@ -38,8 +38,7 @@ import re
38
38
  import sys
39
39
  from pathlib import Path
40
40
 
41
- # 八处机器声明的相对路径(顺序即报错输出顺序;2026-11-13 ZCode 插件随
42
- # packages/argo-zcode 剥离,插件清单/面板 UI/插件市场三处声明同步退出)
41
+ # 八处机器声明的相对路径(顺序即报错输出顺序)
43
42
  JSON_DECLS = (
44
43
  "package.json",
45
44
  "packages/dsh-plugin/package.json",
@@ -299,22 +299,64 @@ def create_explore_bundle(
299
299
  )
300
300
 
301
301
 
302
+ def _parse_study_stdin(raw: str, pick: int = 0) -> dict[str, str]:
303
+ """从 stdin JSON(argo fetch --json 或 argo search --agent)提取 study 参数。"""
304
+ payload = json.loads(raw)
305
+ if not isinstance(payload, dict):
306
+ raise ValueError("stdin JSON 必须是对象(来自 argo fetch --json 或 argo search --agent)")
307
+ # 形态 1:argo fetch --json
308
+ if payload.get("url") and ("content" in payload or "fetch_method" in payload):
309
+ return {
310
+ "url": str(payload.get("url") or "").strip(),
311
+ "title": str(payload.get("title") or "").strip(),
312
+ "archive_text": str(payload.get("content") or ""),
313
+ "related": "",
314
+ }
315
+ # 形态 2:argo search --agent / --json
316
+ results = payload.get("results")
317
+ if isinstance(results, list) and results:
318
+ idx = max(0, min(pick, len(results) - 1))
319
+ chosen = results[idx] if isinstance(results[idx], dict) else {}
320
+ others = [
321
+ str(r.get("url")) for i, r in enumerate(results)
322
+ if i != idx and isinstance(r, dict) and r.get("url")
323
+ ]
324
+ return {
325
+ "url": str(chosen.get("url") or "").strip(),
326
+ "title": str(chosen.get("title") or "").strip(),
327
+ "archive_text": str(chosen.get("snippet") or ""),
328
+ "related": ", ".join(others[:5]),
329
+ }
330
+ raise ValueError("无法识别的 stdin JSON 结构:缺少 url/content 或 results[]")
331
+
332
+
302
333
  def _cmd_create(args: argparse.Namespace) -> int:
303
334
  kind = args.command
304
- target = args.url if kind == "study" else args.problem
335
+ piped: dict[str, str] = {}
336
+ if kind == "study" and (not args.url or getattr(args, "from_json", False)):
337
+ from cli_io import stdin_is_memory_stream, stdin_is_piped
338
+ should_read = getattr(args, "from_json", False) or stdin_is_piped() or stdin_is_memory_stream()
339
+ raw = sys.stdin.read().strip() if should_read else ""
340
+ if raw:
341
+ piped = _parse_study_stdin(raw, pick=int(getattr(args, "pick", 0) or 0))
342
+ target = (args.url or piped.get("url") or "") if kind == "study" else args.problem
343
+ if not target:
344
+ raise SystemExit("study 需要提供 <url>,或通过管道传入 `argo fetch --json` / `argo search --agent` 输出")
305
345
  slug = args.slug or slugify(target)
306
346
  out_path = Path(args.output).expanduser().resolve() if args.output else None
307
347
  archive_text = ""
308
348
  if kind == "study":
309
- archive_text = args.archive_text or ""
349
+ archive_text = args.archive_text or piped.get("archive_text") or ""
310
350
  if not archive_text and args.archive and Path(args.archive).is_file():
311
351
  try:
312
352
  archive_text = Path(args.archive).read_text(encoding="utf-8", errors="replace")
313
353
  except OSError:
314
354
  pass
355
+ title = args.title or piped.get("title") or slug
356
+ related = args.related or piped.get("related") or "无"
315
357
  res = _create_note_bundle(
316
- kind, root=resolve_root(args.root), slug=slug, title=args.title or slug,
317
- target=target, related=args.related or "无",
358
+ kind, root=resolve_root(args.root), slug=slug, title=title,
359
+ target=target, related=related,
318
360
  archive_text=archive_text, output=out_path,
319
361
  )
320
362
  print(dumps(res))
@@ -339,7 +381,12 @@ def build_parser() -> argparse.ArgumentParser:
339
381
  ("explore", "problem", "探索问题或主题", "生成方向探索研报(标准 Markdown + Frontmatter)"),
340
382
  ):
341
383
  sp = sub.add_parser(name, help=desc)
342
- sp.add_argument(arg_name, help=arg_help)
384
+ if name == "study":
385
+ sp.add_argument(arg_name, nargs="?", default="", help=f"{arg_help}(省略时从 stdin JSON 读取)")
386
+ sp.add_argument("--from-json", action="store_true", help="显式从 stdin 读取 fetch/search JSON 管道")
387
+ sp.add_argument("--pick", type=int, default=0, help="从 search JSON 的 results[] 中选取第 N 条(默认 0)")
388
+ else:
389
+ sp.add_argument(arg_name, help=arg_help)
343
390
  sp.add_argument("--title", help="标题(缺省用 slug)")
344
391
  sp.add_argument("--slug", help="标识符(缺省从对象推导)")
345
392
  sp.add_argument("-o", "--output", help="直接指定研报输出文件路径")
@@ -28,6 +28,18 @@ _BLOCKED_ERROR_KEYWORDS = (
28
28
  "just a moment", "checking your browser", "cf-browser-verification",
29
29
  "challenge", "ddos-guard", "perimeterx", "access denied",
30
30
  "handshake failure", "unable to handshake", "安全验证", "滑动验证",
31
+ "captcha", "cloudflare", "verify you are human",
32
+ )
33
+
34
+ # 瞬时网络 / 连接 / DNS / TLS / 服务端 5xx 错误(与超时同属 transient/network,可重试)
35
+ _TRANSIENT_ERROR_KEYWORDS = (
36
+ "timeout", "timed out", "connection reset", "connection refused",
37
+ "connection aborted", "remote disconnected", "eof occurred",
38
+ "broken pipe", "urlopen error", "getaddrinfo", "name or service not known",
39
+ "nodename nor servname", "network is unreachable", "temporary failure",
40
+ "ssl:", "certificate verify failed", "bad gateway", "service unavailable",
41
+ "gateway timeout", "internal server error", "http 500", "http 502",
42
+ "http 503", "http 504", " 500 ", " 502 ", " 503 ", " 504 ",
31
43
  )
32
44
 
33
45
  # 确定性失败:源端状态,不是网络抖动。重试只是多烧一次调用并推迟切备选
@@ -55,15 +67,17 @@ def classify_error_status(message: Any) -> str:
55
67
  拦截是源端状态,鉴权最后(401/403 也可能来自拦截页)。
56
68
  """
57
69
  m = str(message or "").lower()
58
- if "timeout" in m or "timed out" in m:
70
+ padded = f" {m} "
71
+ if any(k in padded for k in _TRANSIENT_ERROR_KEYWORDS):
59
72
  return engine_states.OUTCOME_TIMEOUT
60
73
  if any(k in m for k in _QUOTA_ERROR_KEYWORDS):
61
74
  return engine_states.OUTCOME_QUOTA_EXHAUSTED
62
- if "rate" in m or "429" in m:
75
+ if "rate" in m or "429" in m or "too many requests" in m or "throttl" in m:
63
76
  return engine_states.OUTCOME_RATE_LIMITED
64
77
  if any(k in m for k in _BLOCKED_ERROR_KEYWORDS):
65
78
  return engine_states.OUTCOME_BLOCKED
66
- if "auth" in m or "401" in m or "403" in m:
79
+ if ("auth" in m or "401" in m or "403" in m
80
+ or "unauthorized" in m or "invalid api key" in m or "invalid key" in m):
67
81
  return engine_states.OUTCOME_AUTH_FAILED
68
82
  return engine_states.OUTCOME_ERROR
69
83
 
@@ -598,10 +598,15 @@ def _get_engines_combo(domain: dict[str, Any], enabled: set[str], mode: str = "a
598
598
  except Exception:
599
599
  pass
600
600
 
601
- # fast/budget 模式过滤付费引擎
602
- if mode in ("fast", "budget"):
601
+ # 全模式配额/预算前置预检(2026-11-24 方案 B):
602
+ # 旧实现只在 fast/budget 模式检查 is_available,导致 auto/deep 模式下配额已耗尽
603
+ # 的源(如 bocha/octen)仍被派发并反复撞 quota_exhausted。现全模式前置跳过
604
+ # (内存查表零额外 IO);fail-open 保护:若全被排除则保留原列表交执行层报清原因。
605
+ if filtered:
603
606
  quota_mgr = get_quota_manager()
604
- filtered = [e for e in filtered if quota_mgr.is_available(e, mode=mode)]
607
+ _avail = [e for e in filtered if quota_mgr.is_available(e, mode=mode)]
608
+ if _avail or mode in ("fast", "budget"):
609
+ filtered = _avail
605
610
 
606
611
  # fast/budget 模式优先前置零成本子引擎
607
612
  if mode in ("fast", "budget"):