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
package/scripts/cache.py CHANGED
@@ -101,7 +101,11 @@ DOMAIN_TIER_MAP = {
101
101
  "wechat_search": "news",
102
102
  "shopping": "general",
103
103
  "reference": "evergreen",
104
- "social": "general",
104
+ # 2026-11-15:social 原为 general=3600s,但社交 UGC 结果漂移极快——实测
105
+ # X 搜索同查询间隔 0s 重合 0/5、5s 重合 0/5、15s 才重合 4/5。1 小时缓存
106
+ # 会把旧帖当新结果返回(实测复现:no-cache 拿到的 5 条与缓存命中完全不同)。
107
+ # 改 realtime=900s,与社交平台时效语义一致(同 zhihu_hot_list/hot_trending)。
108
+ "social": "realtime",
105
109
  "local_chinese": "general",
106
110
  "local_news": "news",
107
111
  "local_academic": "research",
@@ -92,6 +92,63 @@ def group_by_caliber(ranked_lists: list[list[dict[str, Any]]]) -> dict[str, list
92
92
  return caliber_groups
93
93
 
94
94
 
95
+ def _dedupe_key(r: dict[str, Any], canonical_url, fallback: str) -> str:
96
+ """按归一 URL -> 标题 -> 卡片类型 -> 兜底唯一键 生成融合/去重主键。"""
97
+ return (
98
+ canonical_url(r.get("url", ""))
99
+ or (f"__title__:{r.get('title', '')}" if r.get("title") else "")
100
+ or (f"__card__:{r.get('card_type', '')}" if r.get("card_type") else "")
101
+ or fallback
102
+ )
103
+
104
+
105
+ def _merge_evidence(
106
+ cur: dict[str, Any], r: dict[str, Any], extra_eng: str | None = None,
107
+ ) -> None:
108
+ """保留更长的标题/摘要,合并 source 与去重后的 consensus_engines。"""
109
+ new_txt = f"{r.get('title', '')} {r.get('snippet', '')}"
110
+ cur_txt = f"{cur.get('title', '')} {cur.get('snippet', '')}"
111
+ if len(new_txt) > len(cur_txt):
112
+ cur["title"] = r.get("title", cur.get("title"))
113
+ cur["snippet"] = r.get("snippet", cur.get("snippet"))
114
+ sources = {cur.get("source", ""), r.get("source", "")}
115
+ cur["source"] = "/".join(s for s in sources if s)
116
+ cons = list(cur.get("consensus_engines") or [])
117
+ incoming = [extra_eng] if extra_eng is not None else list(r.get("consensus_engines") or [])
118
+ for eng in incoming:
119
+ if eng and eng not in cons:
120
+ cons.append(eng)
121
+ cur["consensus_engines"] = cons
122
+
123
+
124
+ def merge_cross_caliber_duplicates(
125
+ rows: list[dict[str, Any]],
126
+ canonical_url=None,
127
+ ) -> list[dict[str, Any]]:
128
+ """按归一 URL 合并跨口径重复条;保留共识证据并叠加跨口径边际共振增益。"""
129
+ if not rows or len(rows) <= 1:
130
+ return rows
131
+ if canonical_url is None:
132
+ from url_canon import canonical_url
133
+ index: dict[str, dict[str, Any]] = {}
134
+ out: list[dict[str, Any]] = []
135
+ for r in rows:
136
+ if not isinstance(r, dict):
137
+ continue
138
+ key = _dedupe_key(r, canonical_url, f"__idx__:{id(r)}")
139
+ cur = index.get(key)
140
+ if cur is None:
141
+ index[key] = r
142
+ out.append(r)
143
+ continue
144
+ s_cur = float(cur.get("_rrf_score") or 0.0)
145
+ s_new = float(r.get("_rrf_score") or 0.0)
146
+ # IASF 跨口径独立共振:不同口径独立命中同一 URL 时叠加次口径 0.35 边际共振增益
147
+ cur["_rrf_score"] = round(max(s_cur, s_new) + 0.35 * min(s_cur, s_new), 6)
148
+ _merge_evidence(cur, r)
149
+ return out
150
+
151
+
95
152
  def merge_within_caliber(
96
153
  groups: list[list[dict[str, Any]]],
97
154
  k: int = 60,
@@ -113,12 +170,7 @@ def merge_within_caliber(
113
170
 
114
171
  for group in groups:
115
172
  for i, r in enumerate(group):
116
- key = (
117
- _canonical_url(r.get("url", ""))
118
- or (f"__title__:{r.get('title', '')}" if r.get("title") else "")
119
- or (f"__card__:{r.get('card_type', '')}" if r.get("card_type") else "")
120
- or f"__idx__:{id(r)}"
121
- )
173
+ key = _dedupe_key(r, _canonical_url, f"__idx__:{id(r)}")
122
174
  eng = r.get("_engine") or r.get("source", "") or ""
123
175
  w = _engine_weight(eng, lang=lang) if weighted else 1.0
124
176
  m = len(items[key].get("consensus_engines") or []) if key in items else 0
@@ -127,24 +179,10 @@ def merge_within_caliber(
127
179
  if key not in items:
128
180
  item = dict(r)
129
181
  item["_rrf_score"] = 0.0
130
- cons: list[str] = []
131
- if eng:
132
- cons.append(eng)
133
- item["consensus_engines"] = cons
182
+ item["consensus_engines"] = [eng] if eng else []
134
183
  items[key] = item
135
184
  else:
136
- cur = items[key]
137
- new_txt = f"{r.get('title', '')} {r.get('snippet', '')}"
138
- cur_txt = f"{cur.get('title', '')} {cur.get('snippet', '')}"
139
- if len(new_txt) > len(cur_txt):
140
- cur["title"] = r.get("title", cur.get("title"))
141
- cur["snippet"] = r.get("snippet", cur.get("snippet"))
142
- sources = {cur.get("source", ""), r.get("source", "")}
143
- cur["source"] = "/".join(s for s in sources if s)
144
- cons = list(cur.get("consensus_engines") or [])
145
- if eng and eng not in cons:
146
- cons.append(eng)
147
- cur["consensus_engines"] = cons
185
+ _merge_evidence(items[key], r, extra_eng=eng)
148
186
 
149
187
  ranked = sorted(scores.items(), key=lambda x: -x[1])
150
188
  out = []
@@ -193,5 +231,4 @@ def merge_by_caliber(
193
231
  for cal in sorted(merged_by_caliber.keys(),
194
232
  key=lambda c: _CALIBER_PRIORITY.get(c, 8)):
195
233
  out.extend(merged_by_caliber[cal])
196
- from caliber_dedupe import merge_cross_caliber_duplicates
197
234
  return merge_cross_caliber_duplicates(out, _canonical_url)
@@ -13,6 +13,7 @@ from __future__ import annotations
13
13
  import hashlib
14
14
  import json
15
15
  import os
16
+ import re
16
17
  import threading
17
18
  import time
18
19
  from pathlib import Path
@@ -54,6 +55,13 @@ OPEN_SECONDS = 60 # 熔断冷却
54
55
  EMPTY_NEGATIVE_TTL = 45 # 空结果负缓存(秒)
55
56
  ERROR_NEGATIVE_TTL = 30 # 错误负缓存(秒)
56
57
  HALF_OPEN_PROBE = True # 冷却后允许一次探测
58
+ # 限流/封锁类源站行为的指数冷却阶梯(秒):不改变 closed 态、不累计 opens、不触发 auto_disabled,
59
+ # 仅通过 cooldown_until 阻止同类 429/WAF 引擎每 60s 内无效空转。
60
+ RATE_LIMIT_COOLDOWNS = (60, 300, 900)
61
+ _COOLDOWN_KINDS = frozenset({
62
+ engine_states.BREAKER_KIND_RATE_LIMITED,
63
+ engine_states.BREAKER_KIND_BLOCKED,
64
+ })
57
65
 
58
66
  # 自适应禁用(v2.7)
59
67
  DISABLE_AFTER_OPENS = 3 # 连续 open 达此次数 → 自动禁用(持久跳过)
@@ -182,11 +190,15 @@ class CircuitBreaker:
182
190
  "suspected_stale": self._suspected_stale_locked(st),
183
191
  "auth_disabled": bool(st.get("auth_disabled")),
184
192
  "auth_streak": int(st.get("auth_streak") or 0),
193
+ "cooldown_streak": int(st.get("cooldown_streak") or 0),
185
194
  # 用 time.time()(墙钟)而非 time.monotonic():熔断状态持久化到文件,
186
195
  # 跨进程恢复时 opened_at 必须可比较。monotonic 在不同进程间基准不同,
187
196
  # 换用会导致跨进程冷却判断错误。时钟回拨风险可控(只会让冷却提前结束)。
188
- "cooldown_remain": max(0, int(OPEN_SECONDS - (time.time() - opened_at)))
189
- if state == engine_states.BREAKER_OPEN else 0,
197
+ "cooldown_remain": max(
198
+ max(0, int(OPEN_SECONDS - (time.time() - opened_at)))
199
+ if state == engine_states.BREAKER_OPEN else 0,
200
+ max(0, int(float(st.get("cooldown_until") or 0) - time.time())),
201
+ ),
190
202
  }
191
203
 
192
204
  @staticmethod
@@ -277,6 +289,10 @@ class CircuitBreaker:
277
289
  return True, "half_open_probe"
278
290
  remain = int(OPEN_SECONDS - (time.time() - opened_at))
279
291
  return False, f"circuit_open:{remain}s"
292
+ cooldown_until = float(st.get("cooldown_until") or 0)
293
+ soft_remain = cooldown_until - time.time()
294
+ if soft_remain > 0:
295
+ return False, f"rate_limit_cooldown:{max(1, int(soft_remain))}s"
280
296
  return True, engine_states.BREAKER_CLOSED
281
297
 
282
298
  def _mutate_locked(self, mutator) -> None:
@@ -340,6 +356,8 @@ class CircuitBreaker:
340
356
  and not st.get("empty_streak")
341
357
  and not st.get("empty_recent")
342
358
  and not st.get("auth_streak")
359
+ and not st.get("cooldown_streak")
360
+ and not st.get("cooldown_until")
343
361
  and st.get("ever_nonempty")):
344
362
  # 已健康且无任何待清理状态:内存短路,零写盘。
345
363
  # ever_nonempty 必须参与短路判定:升级前落盘的存量干净条目没有
@@ -380,15 +398,16 @@ class CircuitBreaker:
380
398
  「跨 ≥2 个不同查询」的去重(同一查询反复空不构成引擎失效证据)。
381
399
 
382
400
  empty 语义是「该查询无结果」——查询级信号,不是引擎级故障。
383
- 它仍可触发 60s 短冷却(防止重复打无效源),但不累计 opens,
384
- 因此永远不会驱动 auto-disable(否则聚合引擎/local 源等易空
385
- 引擎会被误判为持续故障而静默禁用)。
401
+ 它只进 45s 负缓存(EMPTY_NEGATIVE_TTL,防止重复打无效源),
402
+ 不设 cooldown、不累计 opens,因此永远不会驱动 auto-disable
403
+ (否则聚合引擎/local 源等易空引擎会被误判为持续故障而静默禁用)。
386
404
 
387
405
  blocked / rate-limited 语义是「源站行为,不是引擎坏了」——前者是
388
406
  请求在到达内容前被拦截(反爬/指纹/挑战页),后者是源端限流。
389
- 同样只做 60s 短冷却、不累计 opens:把封锁/限流当引擎故障累计到
390
- auto-disable 是封错人——引擎实现没有问题,换客户端形态、
391
- 等冷却或等源站策略变化即可恢复。
407
+ 走指数冷却阶梯(RATE_LIMIT_COOLDOWNS,60/300/900s,经 cooldown_until
408
+ 拒绝探测)、不累计 opens:把封锁/限流当引擎故障累计到 auto-disable
409
+ 是封错人——引擎实现没有问题,换客户端形态、等冷却或等源站策略
410
+ 变化即可恢复。
392
411
  """
393
412
  self._mutate_locked(
394
413
  lambda: self._mutate_failure(engine, kind, attribution, query))
@@ -447,11 +466,17 @@ class CircuitBreaker:
447
466
  st["last_kind"] = kind
448
467
  if attribution:
449
468
  st["last_attribution"] = dict(attribution)
469
+ self._apply_flat_observation(st, attribution)
450
470
  # empty(无结果)与 blocked(被拦截)都是查询级/源站级信号,不驱动
451
471
  # open 熔断:否则「空结果→open 60s→half_open→再 open」无效 churn,
452
472
  # 还占主位阻塞 6s。仅 error/timeout 驱动稳定 state 切换(空结果由
453
473
  # 负缓存短 TTL 保底)。2026-08 修复;blocked 2026-09 并入同语义。
454
474
  # 已因 auth 直达 disabled 的不再被 opens 块盖回 open(禁用优先)。
475
+ if kind in _COOLDOWN_KINDS:
476
+ streak = int(st.get("cooldown_streak") or 0) + 1
477
+ st["cooldown_streak"] = streak
478
+ dur = RATE_LIMIT_COOLDOWNS[min(streak - 1, len(RATE_LIMIT_COOLDOWNS) - 1)]
479
+ st["cooldown_until"] = time.time() + dur
455
480
  if (drives_opens and st.get("state") != engine_states.BREAKER_DISABLED
456
481
  and (st["failures"] >= FAILURE_THRESHOLD
457
482
  or st.get("state") == engine_states.BREAKER_HALF_OPEN)):
@@ -525,10 +550,33 @@ class CircuitBreaker:
525
550
  def _m() -> None:
526
551
  st = self._engines.get(engine) or {"failures": 0, "state": engine_states.BREAKER_CLOSED}
527
552
  st["last_attribution"] = dict(attribution)
553
+ self._apply_flat_observation(st, attribution)
528
554
  self._engines[engine] = st
529
555
 
530
556
  self._mutate_locked(_m)
531
557
 
558
+ @staticmethod
559
+ def _apply_flat_observation(st: dict[str, Any],
560
+ attribution: dict[str, Any] | None) -> None:
561
+ """把归因平铺成状态文件里可直接读的 last_http/last_error。
562
+
563
+ HTTP 码在 engine_failure.classify 的输出里编在 reason/evidence 字符串
564
+ (http-403 形态),诊断时得解析嵌套 dict——平铺后 403/401/402 一眼可见
565
+ (2026-11-14 运行时审计 C 类:bocha 欠费 403 只能碰巧从 quota.json
566
+ 看到,熔断台账自己答不了「为什么」)。缺码或无归因时不写字段。
567
+ """
568
+ if not attribution:
569
+ return
570
+ blob = " ".join(str(attribution.get(k) or "")
571
+ for k in ("reason", "evidence"))
572
+ m = re.search(r"http-(\d{3})", blob)
573
+ if m:
574
+ st["last_http"] = int(m.group(1))
575
+ err = (str(attribution.get("reason") or "")
576
+ or str(attribution.get("evidence") or "")).strip()
577
+ if err:
578
+ st["last_error"] = err[:120]
579
+
532
580
  def auto_disabled(self) -> list[str]:
533
581
  """返回所有处于自动禁用状态的引擎。"""
534
582
  with self._lock:
package/scripts/cli_io.py CHANGED
@@ -55,8 +55,8 @@ import sys
55
55
  import time
56
56
  from typing import Any
57
57
 
58
- __all__ = ["stdin_is_piped", "read_stdin_if_piped", "dumps", "dumps_pretty",
59
- "ensure_utf8_stdio"]
58
+ __all__ = ["stdin_is_piped", "stdin_is_memory_stream", "read_stdin_if_piped",
59
+ "dumps", "dumps_pretty", "ensure_utf8_stdio"]
60
60
 
61
61
  # stdout 的紧凑分隔符(无冗余空格):与 mcp_handlers._dumps 的默认计算方式一致。
62
62
  _COMPACT = (",", ":")
@@ -143,6 +143,24 @@ def stdin_is_piped() -> bool:
143
143
  return mode is not None and (stat.S_ISFIFO(mode) or stat.S_ISREG(mode))
144
144
 
145
145
 
146
+ def stdin_is_memory_stream() -> bool:
147
+ """stdin 是否为无 OS fd 但仍打开的非 TTY 文本流(如单测 io.StringIO)。
148
+
149
+ ``stdin_is_piped()`` 依 ``fstat(fileno())`` 判定,对 ``io.StringIO`` 返回 False;
150
+ 调用方如需在无真实 fd 的单测里同样走读流路径而非打开 ``/dev/tty``(如
151
+ ``getpass.getpass``),可叠加本判据。"""
152
+ import io
153
+
154
+ stdin = getattr(sys, "stdin", None)
155
+ if not isinstance(stdin, io.TextIOBase) or getattr(stdin, "closed", False):
156
+ return False
157
+ try:
158
+ stdin.fileno()
159
+ return False
160
+ except (OSError, ValueError, AttributeError):
161
+ return not stdin.isatty()
162
+
163
+
146
164
  def _stdin_mode() -> int | None:
147
165
  """stdin 的 st_mode;取不到(已关闭 / 非法 fd)返回 None。
148
166
 
@@ -23,6 +23,7 @@ from __future__ import annotations
23
23
  import hashlib
24
24
  import json
25
25
  import os
26
+ import time
26
27
  from pathlib import Path
27
28
  from typing import Any
28
29
 
@@ -366,6 +367,10 @@ def _save_config_disk_cache(st: os.stat_result, scan: tuple[float, int, int, str
366
367
  _sweep_orphan_cache_slots(path)
367
368
 
368
369
 
370
+ # 存活但陈旧 checkout 槽的回收阈值:槽 mtime = 该 checkout 最后一次加载配置。
371
+ _SLOT_STALE_S = 7 * 86400
372
+
373
+
369
374
  def _sweep_orphan_cache_slots(keep: Path) -> None:
370
375
  """回收「config_path 已不存在」的缓存槽;任何失败静默。
371
376
 
@@ -377,6 +382,12 @@ def _sweep_orphan_cache_slots(keep: Path) -> None:
377
382
  config 的旧摘要」来删——那会误删另一个 checkout 正在用的槽。只删 config_path
378
383
  在盘上已消失的槽,既不误伤活着的 checkout,又能自愈任何来源的临时副本。
379
384
 
385
+ 2026-11-14 补第三条:槽 7 天未写即回收。自愈机制曾被「还活着的 checkout」
386
+ 绕过——~/tmp 评测 checkout 与 argo-history 归档的 config.yaml 永久存在,
387
+ 它们的槽按旧判据永远够不着(生产库实测 6 槽约 1.4MB,4 槽属此类)。槽的
388
+ mtime 就是那个 checkout 最后一次加载配置的时刻,一周没写 = 一周没跑过
389
+ 搜索;缓存本可再生(重建一次 16-50ms),陈槽无保留价值。
390
+
380
391
  时机:只在写缓存时顺带扫(缓存未命中才写,属低频)。临时 checkout 自己写槽
381
392
  时就会回收上一批的遗留,所以污染源活跃时回收也随之发生。
382
393
  """
@@ -386,6 +397,12 @@ def _sweep_orphan_cache_slots(keep: Path) -> None:
386
397
  siblings = list(keep.parent.glob("config-cache-*.json"))
387
398
  except OSError:
388
399
  return
400
+ keep_cfg = ""
401
+ try:
402
+ keep_payload = json.loads(keep.read_text(encoding="utf-8"))
403
+ keep_cfg = str(((keep_payload.get("key") or {}).get("config_path")) or "").strip()
404
+ except Exception:
405
+ pass
389
406
  for path in siblings:
390
407
  if path == keep:
391
408
  continue
@@ -400,3 +417,17 @@ def _sweep_orphan_cache_slots(keep: Path) -> None:
400
417
  path.unlink()
401
418
  except OSError:
402
419
  continue
420
+ elif cfg_path and keep_cfg and cfg_path == keep_cfg:
421
+ # 同一 checkout 历史指纹槽且已超 2 小时未动:安全回收,防多轮改配置无界泄漏
422
+ try:
423
+ if (time.time() - path.stat().st_mtime) > 7200:
424
+ path.unlink()
425
+ except OSError:
426
+ pass
427
+ elif cfg_path:
428
+ # 存活但陈旧的 checkout 槽(第三条判据,见 docstring)
429
+ try:
430
+ if (time.time() - path.stat().st_mtime) > _SLOT_STALE_S:
431
+ path.unlink()
432
+ except OSError:
433
+ pass
package/scripts/daemon.py CHANGED
@@ -207,29 +207,43 @@ def _pid_path() -> str:
207
207
  return str(state_path(PID_NAME + "-" + _tree_tag()))
208
208
 
209
209
 
210
- def _pid_is_daemon(pid: int) -> bool:
211
- """核实 pid 的命令行确实是本 daemon(macOS/Linux ps,Windows 视为不是)。
212
-
213
- 误杀的代价不对称:漏杀只是留一个下次 start 时 ping 不到、自己会空闲退出的
214
- 进程;错杀是 SIGTERM 一个无关进程。所以判据从紧——单独出现 "daemon.py"
215
- 子串不够(编辑器/别仓同名脚本都会中)。
216
-
217
- 必须识别两种启动形态(2026-10-13 实测发现第二种此前漏判):
218
- A. `python <本仓>/scripts/daemon.py start`——直接调用与 autostart 派生;
219
- B. `./bin/argo daemon start`——bin/argo 经 runpy 原地执行时,Python 层的
220
- sys.argv 被改写但**内核记录的 argv 不变**,ps 里始终是 bin/argo 形态。
221
- 此前只认 A,B 形态下 stop 的 pid 兜底补刀会漏判,留孤儿进程。
222
- """
210
+ def _pid_alive(pid: int) -> bool:
223
211
  if os.name == "nt":
224
- return False
225
- import subprocess
212
+ import subprocess
213
+ try:
214
+ r = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH", "/FO", "CSV"],
215
+ capture_output=True, text=True, timeout=5,
216
+ encoding="utf-8", errors="replace")
217
+ return f'"{pid}"' in (r.stdout or "")
218
+ except OSError:
219
+ return False
226
220
  try:
227
- r = subprocess.run(["ps", "-p", str(pid), "-o", "command="],
228
- capture_output=True, text=True, timeout=5,
229
- encoding="utf-8", errors="replace")
230
- cmd = (r.stdout or "").strip()
231
- except Exception:
221
+ os.kill(pid, 0)
222
+ return True
223
+ except OSError:
232
224
  return False
225
+
226
+
227
+ def _pid_is_daemon(pid: int) -> bool:
228
+ """核实 pid 的命令行确实是本 daemon(POSIX ps / Windows PowerShell CIM)。"""
229
+ import subprocess
230
+ if os.name == "nt":
231
+ try:
232
+ ps_cmd = f"(Get-CimInstance Win32_Process -Filter 'ProcessId={pid}').CommandLine"
233
+ r = subprocess.run(["powershell", "-NoProfile", "-Command", ps_cmd],
234
+ capture_output=True, text=True, timeout=5,
235
+ encoding="utf-8", errors="replace")
236
+ cmd = (r.stdout or "").strip()
237
+ except OSError:
238
+ return False
239
+ else:
240
+ try:
241
+ r = subprocess.run(["ps", "-p", str(pid), "-o", "command="],
242
+ capture_output=True, text=True, timeout=5,
243
+ encoding="utf-8", errors="replace")
244
+ cmd = (r.stdout or "").strip()
245
+ except OSError:
246
+ return False
233
247
  if not cmd:
234
248
  return False
235
249
  toks = cmd.split()
@@ -247,6 +261,54 @@ def _log_path() -> str:
247
261
  return str(state_path(LOG_NAME + "-" + _tree_tag()))
248
262
 
249
263
 
264
+ # 日志轮转:daemon 生命周期短(空闲自杀),增长慢,启动时检查一次足够。
265
+ # 曾完全无轮转(只靠空闲自杀间接限速),18 天积 405 行属侥幸而非机制。
266
+ _LOG_MAX_BYTES = 1 * 1024 * 1024
267
+
268
+
269
+ def _rotate_log_if_needed() -> None:
270
+ """日志超 1MB 时轮转为 .1(旧的 .1 直接淘汰,不保多代)。
271
+
272
+ 轮转失败不拦启动:日志是观测件,写不进去也比起不来强。
273
+ """
274
+ p = _log_path()
275
+ try:
276
+ if os.path.exists(p) and os.path.getsize(p) > _LOG_MAX_BYTES:
277
+ old = p + ".1"
278
+ if os.path.exists(old):
279
+ os.unlink(old)
280
+ os.replace(p, old)
281
+ except OSError:
282
+ pass
283
+
284
+
285
+ class _TimestampedStdout:
286
+ """行级时间戳包装:daemon.log 曾零时间戳,重启频率与崩溃间隔无法回答
287
+ (2026-11-14 运行时审计 C 类实锤)。服务输出统一加 [ISO-8601] 前缀。
288
+
289
+ 只包装文本流;fd 重定向(dup2)不走这里,外部轮转不受影响。
290
+ """
291
+
292
+ def __init__(self, raw):
293
+ self._raw = raw
294
+ self._at_line_start = True
295
+
296
+ def write(self, s):
297
+ if not s:
298
+ return 0
299
+ now = time.strftime("%Y-%m-%dT%H:%M:%S")
300
+ out = []
301
+ for chunk in s.splitlines(keepends=True):
302
+ if self._at_line_start and chunk.strip():
303
+ out.append(f"[{now}] ")
304
+ out.append(chunk)
305
+ self._at_line_start = chunk.endswith("\n")
306
+ return self._raw.write("".join(out))
307
+
308
+ def flush(self):
309
+ self._raw.flush()
310
+
311
+
250
312
  def _atomic_write(path: str, text: str) -> None:
251
313
  d = os.path.dirname(path)
252
314
  if d:
@@ -640,6 +702,56 @@ def _quiet_stop(sp: str) -> bool:
640
702
  return False
641
703
 
642
704
 
705
+ def _terminate_pid(pid: int) -> None:
706
+ if os.name == "nt":
707
+ import subprocess
708
+ subprocess.run(["taskkill", "/PID", str(pid), "/F"],
709
+ capture_output=True, timeout=5)
710
+ return
711
+ os.kill(pid, signal.SIGTERM)
712
+
713
+
714
+ def _redirect_stdio_to_log() -> None:
715
+ log_dir = os.path.dirname(_log_path())
716
+ if log_dir:
717
+ os.makedirs(log_dir, exist_ok=True)
718
+ _rotate_log_if_needed()
719
+ log = open(_log_path(), "ab", buffering=0)
720
+ os.dup2(log.fileno(), 0)
721
+ os.dup2(log.fileno(), 1)
722
+ os.dup2(log.fileno(), 2)
723
+ with contextlib.suppress(OSError):
724
+ log.close()
725
+
726
+
727
+ def _wait_ready_and_report(args: argparse.Namespace) -> int:
728
+ deadline = time.time() + 10
729
+ while time.time() < deadline:
730
+ try:
731
+ info = ping(_sock_path(), 0.5)
732
+ msg = {"ok": True, "pid": info.get("pid")}
733
+ print(json.dumps(msg, ensure_ascii=False) if args.json
734
+ else f"argo daemon 已启动 pid={info.get('pid')} socket={_sock_path()}")
735
+ return 0
736
+ except Exception:
737
+ time.sleep(0.05)
738
+ print(json.dumps({"ok": False, "error": "启动超时", "log": _log_path()},
739
+ ensure_ascii=False) if args.json
740
+ else f"argo daemon 启动超时,看日志:{_log_path()}", file=sys.stderr)
741
+ return 1
742
+
743
+
744
+ def _start_detached_windows(args: argparse.Namespace) -> int:
745
+ import subprocess
746
+ flags = getattr(subprocess, "DETACHED_PROCESS", 0x00000008) | getattr(
747
+ subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)
748
+ cmd = [sys.executable, os.path.abspath(__file__), "start",
749
+ "--foreground", "--detached-log", "--idle-exit", str(args.idle_exit)]
750
+ subprocess.Popen(cmd, creationflags=flags, close_fds=True,
751
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
752
+ return _wait_ready_and_report(args)
753
+
754
+
643
755
  def _start(args: argparse.Namespace) -> int:
644
756
  alive = _alive()
645
757
  if alive:
@@ -728,38 +840,18 @@ def _start(args: argparse.Namespace) -> int:
728
840
  except Exception:
729
841
  pass
730
842
 
731
- if args.foreground or os.name == "nt": # Windows 无 fork:只支持前台
843
+ if args.foreground:
844
+ if getattr(args, "detached_log", False):
845
+ _redirect_stdio_to_log()
732
846
  _serve_child(args)
733
847
  return 0
734
-
848
+ if os.name == "nt":
849
+ return _start_detached_windows(args)
735
850
  pid = os.fork()
736
851
  if pid > 0:
737
- # 父进程:等 socket 就绪后报告(子进程 bind 完成即视为成功)
738
- deadline = time.time() + 10
739
- while time.time() < deadline:
740
- try:
741
- info = ping(_sock_path(), 0.5)
742
- msg = {"ok": True, "pid": info.get("pid")}
743
- print(json.dumps(msg, ensure_ascii=False) if args.json
744
- else f"argo daemon 已启动 pid={info.get('pid')} socket={_sock_path()}")
745
- return 0
746
- except Exception:
747
- time.sleep(0.05)
748
- print(json.dumps({"ok": False, "error": "启动超时", "log": _log_path()},
749
- ensure_ascii=False) if args.json
750
- else f"argo daemon 启动超时,看日志:{_log_path()}", file=sys.stderr)
751
- return 1
852
+ return _wait_ready_and_report(args)
752
853
  os.setsid()
753
- # 重定向 stdio 到日志:daemon 不再依赖终端(日志目录同样可能还不存在)
754
- log_dir = os.path.dirname(_log_path())
755
- if log_dir:
756
- os.makedirs(log_dir, exist_ok=True)
757
- log = open(_log_path(), "ab", buffering=0)
758
- os.dup2(log.fileno(), 0)
759
- os.dup2(log.fileno(), 1)
760
- os.dup2(log.fileno(), 2)
761
- with contextlib.suppress(OSError):
762
- log.close()
854
+ _redirect_stdio_to_log()
763
855
  _serve_child(args)
764
856
  return 0
765
857
  finally:
@@ -768,6 +860,10 @@ def _start(args: argparse.Namespace) -> int:
768
860
 
769
861
 
770
862
  def _serve_child(args: argparse.Namespace) -> None:
863
+ # stdio 已 dup2 到日志文件;文本流再包一层时间戳,所有 print 落日志带
864
+ # [ISO-8601] 前缀(观测缺失收口:无时间戳的日志无法回答重启频率)。
865
+ sys.stdout = _TimestampedStdout(sys.stdout)
866
+ sys.stderr = _TimestampedStdout(sys.stderr)
771
867
  try:
772
868
  from engine_env import sync_envfile_to_environ
773
869
  sync_envfile_to_environ()
@@ -807,9 +903,7 @@ def _stop(args: argparse.Namespace) -> int:
807
903
  if pid:
808
904
  grace = time.time() + _STOP_GRACE_S
809
905
  while time.time() < grace:
810
- try:
811
- os.kill(pid, 0)
812
- except OSError:
906
+ if not _pid_alive(pid):
813
907
  break # 进程已退出:真停
814
908
  time.sleep(0.1)
815
909
  with contextlib.suppress(OSError):
@@ -826,7 +920,7 @@ def _stop(args: argparse.Namespace) -> int:
826
920
  with open(_pid_path(), encoding="utf-8") as f:
827
921
  pid = int(f.read().strip())
828
922
  if _pid_is_daemon(pid):
829
- os.kill(pid, signal.SIGTERM)
923
+ _terminate_pid(pid)
830
924
  killed = pid
831
925
  except (OSError, ValueError):
832
926
  pass
@@ -859,6 +953,7 @@ def _cli() -> int:
859
953
  sub = ap.add_subparsers(dest="cmd", required=True)
860
954
  p_start = sub.add_parser("start", help="启动 daemon(默认后台化)")
861
955
  p_start.add_argument("--foreground", action="store_true", help="前台运行(调试用)")
956
+ p_start.add_argument("--detached-log", action="store_true", help=argparse.SUPPRESS)
862
957
  p_start.add_argument("--idle-exit", type=float, default=1800.0,
863
958
  help="空闲 N 秒后自杀退出;0=常驻不退(默认 1800)")
864
959
  for p in (p_start, sub.add_parser("status"), sub.add_parser("stop")):