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
@@ -1,6 +1,7 @@
1
1
  import test from 'node:test'
2
2
  import assert from 'node:assert/strict'
3
3
  import { EventEmitter } from 'node:events'
4
+ import { join } from 'node:path'
4
5
  import { Readable } from 'node:stream'
5
6
  import { buildSearchCliArgs, createWorkbenchHandler } from '../dsh/workbench.js'
6
7
 
@@ -188,9 +189,93 @@ test('workbench CLI args keep every flag before `--` so dash-leading queries sta
188
189
  assert.equal(args[args.length - 1], '--list-engines')
189
190
  assert.ok(args.slice(0, sep).includes('--json'), 'flag 必须全部前置到 -- 之前')
190
191
  assert.ok(args.slice(0, sep).includes('--no-cache'), 'refresh 的 --no-cache 也须前置')
192
+ assert.ok(!args.slice(0, sep).includes('--envelope'), '默认不附冗余 --envelope')
191
193
  assert.ok(!args.slice(0, sep).includes('--list-engines'), 'query 不得混入 flag 区')
192
194
  })
193
195
 
196
+ test('workbench modes map to --intent for real vertical engine boost', () => {
197
+ const acad = buildSearchCliArgs('transformer', 'academic')
198
+ assert.ok(acad.includes('--intent') && acad[acad.indexOf('--intent') + 1] === 'academic')
199
+ const hot = buildSearchCliArgs('AI 政策', 'hotspot')
200
+ assert.ok(hot.includes('--intent') && hot[hot.indexOf('--intent') + 1] === 'news')
201
+ const soc = buildSearchCliArgs('Claude Code', 'general', false, { intent: 'social' })
202
+ assert.ok(soc.includes('--intent') && soc[soc.indexOf('--intent') + 1] === 'social')
203
+ })
204
+
205
+ test('workbench /argo/api/local-inspect and /argo/api/note-study bridge local-seek and note study', async () => {
206
+ const calls = []
207
+ const handler = createWorkbenchHandler(
208
+ { get: () => null },
209
+ { localSearchPath: process.cwd() },
210
+ null,
211
+ {
212
+ runInspectCli: async (cliArgs) => {
213
+ calls.push(cliArgs)
214
+ return { ok: true, symbol: 'resolve_intent', start: 78, end: 193, content: '78: def resolve_intent(' }
215
+ },
216
+ runNoteCli: async (cliArgs, opts) => {
217
+ calls.push({ cliArgs, hasStdin: Boolean(opts?.stdin) })
218
+ return { kind: 'study', note: '/tmp/demo-note.md' }
219
+ },
220
+ },
221
+ )
222
+
223
+ const allowedFile = join(process.cwd(), 'scripts', 'intent_router.py')
224
+ const res1 = mockRes()
225
+ await handler(mockReq('POST', '/argo/api/local-inspect', {
226
+ path: `file://${allowedFile}`,
227
+ symbol: 'resolve_intent',
228
+ }), res1)
229
+ assert.equal(res1.statusCode, 200)
230
+ const b1 = res1.json()
231
+ assert.equal(b1.ok, true)
232
+ assert.equal(b1.symbol, 'resolve_intent')
233
+ assert.deepEqual(calls[0], ['seek', '--json', '--symbol-body', 'resolve_intent', '--', allowedFile])
234
+
235
+ // 路径边界防护:越界绝对路径与 ../ 穿越均返回 403 且绝不触发 CLI
236
+ const resEscapeAbs = mockRes()
237
+ await handler(mockReq('POST', '/argo/api/local-inspect', {
238
+ path: '/etc/passwd',
239
+ lines: '1-5',
240
+ }), resEscapeAbs)
241
+ assert.equal(resEscapeAbs.statusCode, 403)
242
+ assert.equal(resEscapeAbs.json().error, 'path_outside_root')
243
+
244
+ const resEscapeRel = mockRes()
245
+ await handler(mockReq('POST', '/argo/api/local-inspect', {
246
+ path: '../../../etc/passwd',
247
+ lines: '1-5',
248
+ }), resEscapeRel)
249
+ assert.equal(resEscapeRel.statusCode, 403)
250
+ assert.equal(resEscapeRel.json().error, 'path_outside_root')
251
+ assert.equal(calls.length, 1)
252
+
253
+ const res2 = mockRes()
254
+ await handler(mockReq('POST', '/argo/api/note-study', {
255
+ title: 'Test Note',
256
+ payload: { query: 'q', results: [{ title: 'T', url: 'https://example.org/1', snippet: 'S' }] },
257
+ }), res2)
258
+ assert.equal(res2.statusCode, 200)
259
+ const b2 = res2.json()
260
+ assert.equal(b2.ok, true)
261
+ assert.equal(b2.note, '/tmp/demo-note.md')
262
+ assert.equal(calls[1].hasStdin, true)
263
+ assert.ok(calls[1].cliArgs.includes('--from-json'))
264
+ })
265
+
266
+ test('workbench-io cross-platform helpers handle win32 PATH and shebang wrapping', async () => {
267
+ const { mergedLaunchdPath, resolveSpawnCommand } = await import('../dsh/workbench-io.js')
268
+ const winPath = mergedLaunchdPath({ Path: 'C:\\Windows\\System32;C:\\Python312' }, 'win32')
269
+ assert.equal(winPath, 'C:\\Windows\\System32;C:\\Python312')
270
+ assert.ok(!winPath.includes('/opt/homebrew/bin:'))
271
+
272
+ const wrapped = resolveSpawnCommand('C:\\repo\\bin\\argo', ['search', '--json'], { ARGO_PYTHON: 'py' }, 'win32')
273
+ assert.deepEqual(wrapped, { cmd: 'py', argv: ['C:\\repo\\bin\\argo', 'search', '--json'] })
274
+
275
+ const posix = resolveSpawnCommand('/repo/bin/argo', ['search', '--json'], {}, 'darwin')
276
+ assert.deepEqual(posix, { cmd: '/repo/bin/argo', argv: ['search', '--json'] })
277
+ })
278
+
194
279
  test('workbench research gate passes when stats are supplied alongside valid citations', async () => {
195
280
  const { evaluateGates } = await import('../dsh/wide-research.js')
196
281
  const gate = evaluateGates({
@@ -0,0 +1,324 @@
1
+ #!/usr/bin/env python3
2
+ """affected_tests.py — L2 变更感知增量选测引擎。
3
+
4
+ 定位(MECE 三层测试分流):
5
+ - L1 全局硬契约门:tests/gate_manifest.txt(每次 commit 必全跑);
6
+ - L2 变更感知选测:本脚本按 git 改动模块反查 343 个未入册单测中的受影响子集,
7
+ 在严格时间预算内随 pre-commit 自动执行,补齐「本地绿、全量红」盲区;
8
+ - L3 全量回归:pytest tests/ -q(发版前或 CI 运行)。
9
+
10
+ 判定规则(纯标准库 AST,无外部依赖):
11
+ 1. 扫描 scripts/ 与 tests/test_*.py 的静态 import / from-import 关系;
12
+ 2. 对改动模块沿反向依赖图做最多 2 跳传递展开,找出导入它们的未入册测试;
13
+ 3. 叠加文件名 stem 启发式召回(如 scripts/foo.py → tests/test_foo*.py),
14
+ 覆盖通过 importlib 动态加载的测试;
15
+ 4. 排除已在 gate_manifest.txt 中的 L1 测试(避免重复执行),按
16
+ tests/.test_durations 历史耗时升序挑选,单文件超阈值或超总预算的慢测
17
+ 显式跳过并打印提示,留给 L3 全量回归。
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import ast
24
+ import json
25
+ import subprocess
26
+ import sys
27
+ from collections import defaultdict, deque
28
+ from pathlib import Path
29
+ from typing import Iterable
30
+
31
+ ROOT = Path(__file__).resolve().parent.parent
32
+ SCRIPTS_DIR = ROOT / "scripts"
33
+ TESTS_DIR = ROOT / "tests"
34
+ MANIFEST_PATH = TESTS_DIR / "gate_manifest.txt"
35
+ DURATIONS_PATH = TESTS_DIR / ".test_durations"
36
+
37
+
38
+ def extract_imported_modules(path: Path) -> set[str]:
39
+ """用 AST 提取 Python 文件中直接导入的顶层/子模块名。"""
40
+ try:
41
+ tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"), filename=str(path))
42
+ except (OSError, SyntaxError, ValueError):
43
+ return set()
44
+ mods: set[str] = set()
45
+ for node in ast.walk(tree):
46
+ if isinstance(node, ast.Import):
47
+ for alias in node.names:
48
+ name = alias.name
49
+ mods.add(name)
50
+ mods.add(name.split(".", 1)[0])
51
+ elif isinstance(node, ast.ImportFrom) and node.module:
52
+ mods.add(node.module)
53
+ mods.add(node.module.split(".", 1)[0])
54
+ for alias in node.names:
55
+ if alias.name != "*":
56
+ mods.add(f"{node.module}.{alias.name}")
57
+ return mods
58
+
59
+
60
+ def load_manifest_entries(manifest_path: Path = MANIFEST_PATH) -> set[str]:
61
+ """读取 L1 gate_manifest.txt 中已登记的测试相对路径集合。"""
62
+ if not manifest_path.is_file():
63
+ return set()
64
+ entries: set[str] = set()
65
+ for raw in manifest_path.read_text(encoding="utf-8").splitlines():
66
+ line = raw.strip()
67
+ if line and not line.startswith("#"):
68
+ entries.add(line)
69
+ return entries
70
+
71
+
72
+ def load_file_durations(durations_path: Path = DURATIONS_PATH) -> dict[str, float]:
73
+ """将 tests/.test_durations 按测试文件聚合为 {rel_path: total_seconds}。"""
74
+ if not durations_path.is_file():
75
+ return {}
76
+ try:
77
+ raw = json.loads(durations_path.read_text(encoding="utf-8"))
78
+ except (OSError, json.JSONDecodeError, ValueError):
79
+ return {}
80
+ totals: dict[str, float] = defaultdict(float)
81
+ if isinstance(raw, dict):
82
+ for nodeid, secs in raw.items():
83
+ if not isinstance(nodeid, str) or not isinstance(secs, (int, float)):
84
+ continue
85
+ rel = nodeid.split("::", 1)[0]
86
+ totals[rel] += float(secs)
87
+ return dict(totals)
88
+
89
+
90
+ def _path_to_module_names(rel_path: str) -> set[str]:
91
+ """将仓内脚本路径转为可能的 import 模块名集合。"""
92
+ p = Path(rel_path)
93
+ if p.suffix != ".py":
94
+ return set()
95
+ parts = p.parts
96
+ names: set[str] = set()
97
+ if len(parts) >= 2 and parts[0] == "scripts":
98
+ sub = parts[1:]
99
+ stem_parts = list(sub[:-1]) + [p.stem]
100
+ if p.stem == "__init__" and len(stem_parts) >= 2:
101
+ stem_parts = stem_parts[:-1]
102
+ dotted = ".".join(stem_parts)
103
+ if dotted:
104
+ names.add(dotted)
105
+ names.add(stem_parts[-1])
106
+ names.add(f"scripts.{dotted}")
107
+ else:
108
+ names.add(p.stem)
109
+ return names
110
+
111
+
112
+ def build_reverse_script_graph(scripts_dir: Path = SCRIPTS_DIR) -> dict[str, set[str]]:
113
+ """构建 scripts/ 内部的反向依赖图:{被导入模块: {导入它的模块, ...}}。"""
114
+ rev: dict[str, set[str]] = defaultdict(set)
115
+ if not scripts_dir.is_dir():
116
+ return rev
117
+ for py in sorted(scripts_dir.rglob("*.py")):
118
+ rel = py.relative_to(scripts_dir.parent).as_posix()
119
+ mod_names = _path_to_module_names(rel)
120
+ if not mod_names:
121
+ continue
122
+ imported = extract_imported_modules(py)
123
+ for dep in imported:
124
+ rev[dep].update(mod_names)
125
+ return rev
126
+
127
+
128
+ def expand_affected_modules(
129
+ changed_files: Iterable[str],
130
+ reverse_graph: dict[str, set[str]],
131
+ *,
132
+ max_hops: int = 2,
133
+ ) -> tuple[set[str], set[str]]:
134
+ """展开改动文件对应的模块集合及直接改动测试集合。
135
+
136
+ 返回 (受影响模块名集合, 直接改动的测试文件相对路径集合)。
137
+ """
138
+ seeds: set[str] = set()
139
+ direct_tests: set[str] = set()
140
+ for raw in changed_files:
141
+ norm = Path(raw).as_posix().lstrip("./")
142
+ if norm.startswith("tests/test_") and norm.endswith(".py"):
143
+ direct_tests.add(norm)
144
+ elif norm.startswith("scripts/") and norm.endswith(".py"):
145
+ seeds.update(_path_to_module_names(norm))
146
+
147
+ visited = set(seeds)
148
+ queue: deque[tuple[str, int]] = deque((m, 0) for m in seeds)
149
+ while queue:
150
+ mod, hop = queue.popleft()
151
+ if hop >= max_hops:
152
+ continue
153
+ for dependent in reverse_graph.get(mod, ()):
154
+ if dependent not in visited:
155
+ visited.add(dependent)
156
+ queue.append((dependent, hop + 1))
157
+ return visited, direct_tests
158
+
159
+
160
+ def select_affected_tests(
161
+ changed_files: Iterable[str],
162
+ *,
163
+ root: Path = ROOT,
164
+ manifest_entries: set[str] | None = None,
165
+ file_durations: dict[str, float] | None = None,
166
+ budget_seconds: float = 8.0,
167
+ max_single_seconds: float = 3.0,
168
+ max_files: int = 12,
169
+ max_hops: int = 2,
170
+ ) -> dict[str, object]:
171
+ """根据改动文件列表,筛选应执行的 L2 未入册测试。"""
172
+ scripts_dir = root / "scripts"
173
+ tests_dir = root / "tests"
174
+ manifest = load_manifest_entries(tests_dir / "gate_manifest.txt") if manifest_entries is None else manifest_entries
175
+ durations = load_file_durations(tests_dir / ".test_durations") if file_durations is None else file_durations
176
+
177
+ rev_graph = build_reverse_script_graph(scripts_dir)
178
+ affected_mods, direct_tests = expand_affected_modules(
179
+ changed_files, rev_graph, max_hops=max_hops,
180
+ )
181
+
182
+ # 改动脚本的原始模块名与 stem(优先于间接传递依赖进入预算)
183
+ direct_mods: set[str] = set()
184
+ changed_stems: set[str] = set()
185
+ for f in changed_files:
186
+ norm = Path(f).as_posix().lstrip("./")
187
+ if norm.startswith("scripts/") and norm.endswith(".py"):
188
+ direct_mods.update(_path_to_module_names(norm))
189
+ if Path(norm).stem != "__init__":
190
+ changed_stems.add(Path(norm).stem)
191
+
192
+ direct_candidates: set[str] = set()
193
+ transitive_candidates: set[str] = set()
194
+ for rel in direct_tests:
195
+ if rel not in manifest and (root / rel).is_file():
196
+ direct_candidates.add(rel)
197
+
198
+ if (affected_mods or changed_stems) and tests_dir.is_dir():
199
+ for test_file in sorted(tests_dir.glob("test_*.py")):
200
+ rel = f"tests/{test_file.name}"
201
+ if rel in manifest or rel in direct_candidates:
202
+ continue
203
+ stem_hit = any(
204
+ test_file.stem == f"test_{s}" or test_file.stem.startswith(f"test_{s}_")
205
+ for s in changed_stems
206
+ )
207
+ if stem_hit:
208
+ direct_candidates.add(rel)
209
+ continue
210
+ imported = extract_imported_modules(test_file)
211
+ if direct_mods and (imported & direct_mods):
212
+ direct_candidates.add(rel)
213
+ elif affected_mods and (imported & affected_mods):
214
+ transitive_candidates.add(rel)
215
+
216
+ # 直接相关测试优先,同层内按历史耗时升序(无历史记录默认估 0.5s)
217
+ scored = sorted(
218
+ direct_candidates | transitive_candidates,
219
+ key=lambda r: (0 if r in direct_candidates else 1, durations.get(r, 0.5), r),
220
+ )
221
+ selected: list[str] = []
222
+ skipped_slow: list[dict[str, object]] = []
223
+ est_total = 0.0
224
+
225
+ for rel in scored:
226
+ est = round(durations.get(rel, 0.5), 3)
227
+ if est > max_single_seconds:
228
+ skipped_slow.append({"file": rel, "est_seconds": est, "reason": "single_file_slow"})
229
+ continue
230
+ if len(selected) >= max_files or (selected and est_total + est > budget_seconds):
231
+ skipped_slow.append({"file": rel, "est_seconds": est, "reason": "budget_exceeded"})
232
+ continue
233
+ selected.append(rel)
234
+ est_total += est
235
+
236
+ return {
237
+ "selected": selected,
238
+ "skipped": skipped_slow,
239
+ "estimated_seconds": round(est_total, 3),
240
+ "affected_modules_count": len(affected_mods),
241
+ }
242
+
243
+
244
+ def git_changed_files(*, staged: bool = False, diff_ref: str | None = None, root: Path = ROOT) -> list[str]:
245
+ """获取 git 暂存区或相对 ref 的改动文件列表。"""
246
+ if staged:
247
+ cmd = ["git", "diff", "--cached", "--name-only", "--diff-filter=ACMR"]
248
+ elif diff_ref:
249
+ cmd = ["git", "diff", "--name-only", "--diff-filter=ACMR", diff_ref]
250
+ else:
251
+ cmd = ["git", "status", "--porcelain"]
252
+ proc = subprocess.run(
253
+ cmd, cwd=str(root), capture_output=True, text=True,
254
+ encoding="utf-8", errors="replace", check=False,
255
+ )
256
+ if proc.returncode != 0:
257
+ return []
258
+ files: list[str] = []
259
+ for line in proc.stdout.splitlines():
260
+ s = line.strip()
261
+ if not s:
262
+ continue
263
+ if not staged and not diff_ref:
264
+ s = s[3:].strip()
265
+ files.append(s)
266
+ return files
267
+
268
+
269
+ def main(argv: list[str] | None = None) -> int:
270
+ ap = argparse.ArgumentParser(description="L2 变更感知增量选测(补齐未入册单测盲区)")
271
+ ap.add_argument("--staged", action="store_true", help="读取 git staged 改动文件")
272
+ ap.add_argument("--diff-ref", default=None, help="对比指定 git ref 的改动文件(如 HEAD~1)")
273
+ ap.add_argument("--files", nargs="*", default=None, help="显式指定改动文件列表")
274
+ ap.add_argument("--budget", type=float, default=8.0, help="L2 选测总耗时预算(秒,默认 8.0)")
275
+ ap.add_argument("--max-single", type=float, default=3.0, help="单文件最大允许预估耗时(秒)")
276
+ ap.add_argument("--max-files", type=int, default=12, help="单次最多执行的 L2 文件数")
277
+ ap.add_argument("--json", action="store_true", dest="as_json", help="JSON 格式输出")
278
+ ap.add_argument("--run", action="store_true", help="直接用当前解释器执行选中的 L2 测试")
279
+ args = ap.parse_args(argv)
280
+
281
+ if args.files is not None:
282
+ changed = list(args.files)
283
+ else:
284
+ changed = git_changed_files(staged=args.staged, diff_ref=args.diff_ref)
285
+
286
+ plan = select_affected_tests(
287
+ changed,
288
+ budget_seconds=args.budget,
289
+ max_single_seconds=args.max_single,
290
+ max_files=args.max_files,
291
+ )
292
+
293
+ if args.as_json and not args.run:
294
+ print(json.dumps(plan, ensure_ascii=False))
295
+ return 0
296
+
297
+ selected: list[str] = plan["selected"] # type: ignore[assignment]
298
+ skipped: list[dict[str, object]] = plan["skipped"] # type: ignore[assignment]
299
+
300
+ if not args.run:
301
+ for rel in selected:
302
+ print(rel)
303
+ return 0
304
+
305
+ if not selected:
306
+ if skipped:
307
+ print(f"[L2-affected] 无预算内增量单测(跳过 {len(skipped)} 个慢测,留给 L3 全量回归)")
308
+ return 0
309
+
310
+ print(
311
+ f"[L2-affected] 变更命中 {len(selected)} 个未入册单测"
312
+ f"(预估 {plan['estimated_seconds']}s,跳过 {len(skipped)} 个慢测): "
313
+ + ", ".join(selected)
314
+ )
315
+ proc = subprocess.run(
316
+ [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", *selected],
317
+ cwd=str(ROOT),
318
+ check=False,
319
+ )
320
+ return proc.returncode
321
+
322
+
323
+ if __name__ == "__main__":
324
+ sys.exit(main())
@@ -470,10 +470,23 @@ def stats() -> dict:
470
470
  "SELECT engine, COUNT(*) FROM badcases WHERE engine != ''"
471
471
  " GROUP BY engine ORDER BY COUNT(*) DESC LIMIT 8").fetchall())
472
472
  total = con.execute("SELECT COUNT(*) FROM badcases").fetchone()[0]
473
+ rec_no_strategy = con.execute(
474
+ "SELECT COUNT(*) FROM badcases WHERE kind = 'recovery' "
475
+ "AND detail LIKE 'level=None strategy=None%'"
476
+ ).fetchone()[0]
473
477
  finally:
474
478
  con.close()
475
- return {"total": total, "by_kind": by_kind, "top_engines": by_engine,
476
- "by_root_cause": root_cause_stats()}
479
+ rec_total = int(by_kind.get("recovery", 0))
480
+ return {
481
+ "total": total,
482
+ "by_kind": by_kind,
483
+ "recovery_breakdown": {
484
+ "no_strategy": rec_no_strategy,
485
+ "strategy_failed": max(0, rec_total - rec_no_strategy),
486
+ },
487
+ "top_engines": by_engine,
488
+ "by_root_cause": root_cause_stats(),
489
+ }
477
490
 
478
491
 
479
492
  # ── LESSONS.md 导出 ─────────────────────────────────────────────────────────
@@ -625,6 +638,76 @@ def overview() -> dict[str, Any]:
625
638
  return out
626
639
 
627
640
 
641
+ def propose_actions(
642
+ *,
643
+ min_count: int = 5,
644
+ min_days: int = 3,
645
+ rows: list[dict[str, Any]] | None = None,
646
+ engines_cfg: dict[str, dict[str, Any]] | None = None,
647
+ ) -> dict[str, Any]:
648
+ """将坏例账本转化为可审阅的自动降级/治理提案(只读,不自动改配置)。
649
+
650
+ 聚焦「仍在自动路由池(非 explicit_only)且跨多日高频失败」的单引擎:
651
+ - unattributed 占比最高 → fix_attribution(补齐异常归因)
652
+ - quota_exhausted / rate_limited / auth_expired → demote_to_explicit_only
653
+ - 其余持续网络/故障 → review_or_demote
654
+ """
655
+ if rows is None:
656
+ rows = [dict(r) for r in _fetch(None, None, 10000)]
657
+ if engines_cfg is None:
658
+ try:
659
+ from config import get_engines
660
+ engines_cfg = get_engines()
661
+ except (ImportError, OSError, ValueError):
662
+ engines_cfg = {}
663
+
664
+ per_engine: dict[str, dict[str, Any]] = {}
665
+ for r in rows:
666
+ eng_raw = str(r.get("engine") or "").strip()
667
+ if not eng_raw or "," in eng_raw:
668
+ continue
669
+ rc = str(r.get("root_cause") or "unattributed")
670
+ day = str(r.get("ts") or "")[:10]
671
+ bucket = per_engine.setdefault(eng_raw, {"count": 0, "days": set(), "causes": {}})
672
+ bucket["count"] += 1
673
+ if len(day) == 10:
674
+ bucket["days"].add(day)
675
+ bucket["causes"][rc] = bucket["causes"].get(rc, 0) + 1
676
+
677
+ proposals: list[dict[str, Any]] = []
678
+ for eng, info in sorted(per_engine.items(), key=lambda kv: (-kv[1]["count"], kv[0])):
679
+ cnt = info["count"]
680
+ day_cnt = len(info["days"])
681
+ if cnt < min_count or day_cnt < min_days:
682
+ continue
683
+ spec = engines_cfg.get(eng) if isinstance(engines_cfg, dict) else None
684
+ if isinstance(spec, dict) and spec.get("explicit_only"):
685
+ continue
686
+ top_cause = max(info["causes"].items(), key=lambda kv: kv[1])[0]
687
+ if top_cause == "unattributed":
688
+ action = "fix_attribution"
689
+ elif top_cause in ("quota_exhausted", "rate_limited", "auth_expired"):
690
+ action = "demote_to_explicit_only"
691
+ else:
692
+ action = "review_or_demote"
693
+ proposals.append({
694
+ "engine": eng,
695
+ "count": cnt,
696
+ "seen_days": day_cnt,
697
+ "top_root_cause": top_cause,
698
+ "causes": info["causes"],
699
+ "recommended_action": action,
700
+ "in_registry": isinstance(spec, dict),
701
+ })
702
+
703
+ return {
704
+ "min_count": min_count,
705
+ "min_days": min_days,
706
+ "proposal_count": len(proposals),
707
+ "proposals": proposals,
708
+ }
709
+
710
+
628
711
  def main(argv: list[str] | None = None) -> int:
629
712
  ap = argparse.ArgumentParser(description="坏例账本(badcase 管理)")
630
713
  sub = ap.add_subparsers(dest="cmd", required=True)
@@ -636,6 +719,9 @@ def main(argv: list[str] | None = None) -> int:
636
719
  p_list.add_argument("--limit", type=int, default=10)
637
720
  sub.add_parser("stats")
638
721
  sub.add_parser("overview")
722
+ p_propose = sub.add_parser("propose")
723
+ p_propose.add_argument("--min-count", type=int, default=5)
724
+ p_propose.add_argument("--min-days", type=int, default=3)
639
725
  p_check = sub.add_parser("check")
640
726
  p_check.add_argument("--since", default="7d")
641
727
  p_check.add_argument("--max", type=int, default=50)
@@ -661,6 +747,11 @@ def main(argv: list[str] | None = None) -> int:
661
747
  print("[overview] dormant_sources 取数失败(见输出 error 字段)",
662
748
  file=sys.stderr)
663
749
  return 1
750
+ elif args.cmd == "propose":
751
+ print(json.dumps(
752
+ propose_actions(min_count=args.min_count, min_days=args.min_days),
753
+ ensure_ascii=False,
754
+ ))
664
755
  elif args.cmd == "check":
665
756
  report = check(args.since, args.max, args.promote_days)
666
757
  print(json.dumps(report, ensure_ascii=False))
@@ -50,7 +50,7 @@ ROOT = Path(__file__).resolve().parent.parent
50
50
  # 改动里更新 docs/COMMIT_STANDARD.md。tests/test_check_commit_report.py
51
51
  # 的 test_standard_doc_lists_the_same_high_risk_patterns 会机械对拍两者。
52
52
  _HIGH_RISK_SCOPES = frozenset({
53
- "engines", "engine", "route", "search", "rank", "states", "state",
53
+ "engines", "engine", "route", "search", "fetch", "rank", "states", "state",
54
54
  "agents", "agent", "release", "deps",
55
55
  })
56
56
  _HIGH_RISK = (
@@ -61,11 +61,12 @@ _HIGH_RISK = (
61
61
  re.compile(r"^build\(deps\)"),
62
62
  )
63
63
 
64
- # 检查清单三段。`在 commit` 允许写成 `在 commit:` 或 `在commit:`。
64
+ # 检查清单三段。`在 commit` 允许写成 `在 commit:` 或 `在commit:`,
65
+ # 且值必须为 6–40 位十六进制 SHA(拒绝 `<待填>` 等未填占位符)。
65
66
  _SEGMENTS = {
66
- "跑了": re.compile(r"^\s*[-*]?\s*跑了\s*[::]", re.M),
67
- "在 commit": re.compile(r"^\s*[-*]?\s*在\s*commit\s*[::]", re.M),
68
- "未跑": re.compile(r"^\s*[-*]?\s*未跑\s*[::]", re.M),
67
+ "跑了": re.compile(r"^\s*[-*]?\s*跑了\s*[::]\s*\S+", re.M),
68
+ "在 commit": re.compile(r"^\s*[-*]?\s*在\s*commit\s*[::]\s*[0-9a-fA-F]{6,40}\b", re.M),
69
+ "未跑": re.compile(r"^\s*[-*]?\s*未跑\s*[::]\s*\S+", re.M),
69
70
  }
70
71
 
71
72
  # 标题与正文的分界:第一个空行。标题不进正文检查。
@@ -79,12 +80,15 @@ def is_high_risk(title: str) -> bool:
79
80
  """标题是否命中高风险模式。
80
81
 
81
82
  判据有两条,命中任一即高风险:
82
- 1. scope 在 `_HIGH_RISK_SCOPES` 白名单里(带 scope 的常规提交)
83
- 2. 命中 `_HIGH_RISK` 里的特殊模式(无 scope 的 perf/build 等)
83
+ 1. scope(支持 `fetch+cli` / `search,route` 等复合写法按 `[+,/]` 拆分)
84
+ 中任一子项命中 `_HIGH_RISK_SCOPES` 白名单;
85
+ 2. 命中 `_HIGH_RISK` 里的特殊模式(无 scope 的 perf/build 等)。
84
86
  """
85
87
  m = _SCOPE_RE.match(title.strip())
86
- if m and m.group(2) and m.group(2).strip() in _HIGH_RISK_SCOPES:
87
- return True
88
+ if m and m.group(2):
89
+ parts = [p.strip() for p in re.split(r"[+,/]", m.group(2)) if p.strip()]
90
+ if any(p in _HIGH_RISK_SCOPES for p in parts):
91
+ return True
88
92
  return any(p.search(title.strip()) for p in _HIGH_RISK)
89
93
 
90
94
 
package/scripts/cli_io.py CHANGED
@@ -137,10 +137,15 @@ def stdout_is_tty() -> bool:
137
137
  return True # fail-safe:取不到就当终端,不瘦身
138
138
 
139
139
 
140
+ def _is_stream_mode(mode: int) -> bool:
141
+ """是否为流式管道 fd(FIFO 管道或 Node.js libuv 在 macOS 上创建的 socketpair)。"""
142
+ return stat.S_ISFIFO(mode) or stat.S_ISSOCK(mode)
143
+
144
+
140
145
  def stdin_is_piped() -> bool:
141
- """stdin 是否接了管道或文件重定向(而非终端 / /dev/null / 未打开)。"""
146
+ """stdin 是否接了管道、文件重定向或 socketpair(Node.js libuv spawn 在 macOS 上用 socketpair)。"""
142
147
  mode = _stdin_mode()
143
- return mode is not None and (stat.S_ISFIFO(mode) or stat.S_ISREG(mode))
148
+ return mode is not None and (stat.S_ISREG(mode) or _is_stream_mode(mode))
144
149
 
145
150
 
146
151
  def stdin_is_memory_stream() -> bool:
@@ -185,7 +190,7 @@ def read_stdin_if_piped() -> str:
185
190
  if stat.S_ISREG(mode):
186
191
  # 文件重定向:read() 到 EOF 立即返回,本来就不会挂,无需期限
187
192
  return _read_all_text()
188
- if not stat.S_ISFIFO(mode):
193
+ if not _is_stream_mode(mode):
189
194
  return "" # 终端 / /dev/null / 其它字符设备:没有数据
190
195
  return _read_pipe_with_deadline()
191
196
 
@@ -145,6 +145,7 @@ _ENGINE_FAMILY_OVERRIDES: dict[str, str] = {
145
145
  "juejin": "social",
146
146
  "reddit": "social",
147
147
  "twitter": "social",
148
+ "twitter_cli": "social",
148
149
  "fxtwitter": "social",
149
150
  "xiaohongshu": "social",
150
151
  "bilibili": "social",
@@ -371,6 +371,7 @@ FETCH_WECHAT_FAILED = "wechat_failed" # 公众号分支失败
371
371
  FETCH_FULLTEXT = "fulltext" # 从本地 fulltext 存档读全文
372
372
  FETCH_X_ARTICLE = "x_article" # X 文章打包
373
373
  FETCH_BLOCKED = "blocked" # SSRF/安全拦截
374
+ FETCH_PDF_FAILED = "pdf_failed" # PDF 专用提取失败(含解析依赖缺失)
374
375
 
375
376
  FETCH_METHODS = frozenset({
376
377
  FETCH_HTTP_MD, FETCH_HTTP, FETCH_TLS, FETCH_JINA, FETCH_WAYBACK,
@@ -397,7 +398,7 @@ FETCH_FULL = "full"
397
398
  FETCH_METHODS_ALL = FETCH_METHODS | frozenset({
398
399
  FETCH_HTTP_MOBILE, FETCH_TLS_SPOOF, FETCH_JINA_READER, FETCH_MD_VARIANT,
399
400
  FETCH_LLMS_TXT, FETCH_TINYFISH, FETCH_PARALLEL, FETCH_ROBOTS_BLOCKED,
400
- FETCH_HTTP_DIRECT, FETCH_FULL,
401
+ FETCH_HTTP_DIRECT, FETCH_FULL, FETCH_PDF_FAILED,
401
402
  })
402
403
 
403
404
  # 已产出 Markdown 的抓取方式:内容已由站点或阅读器转好,没有 HTML 壳可言。
@@ -431,9 +432,8 @@ def is_degraded_fetch_method(method: str) -> bool:
431
432
  # ── 10. 平台/运行时状态(dsh-plugin / daemon)──────────────────────────────
432
433
  # 生产端已收口:`scripts/daemon.py` 的 ping 响应与 `status` 子命令都带
433
434
  # machine-readable 的 `state` 字段,值取自本表;进程停止时 status 报
434
- # DAEMON_STOPPED(此时没有 ping 可回)。ZCode 面板桥(py_bridge.py)此前直接
435
- # 读这个字段,不再从中文文案反推 pid、也不再用布尔冒充三态——桥随 2026-11-13
436
- # packages/argo-zcode 剥离退出,字段契约由 daemon.py 侧继续履行。
435
+ # DAEMON_STOPPED(此时没有 ping 可回),不再从中文文案反推 pid、也不再用
436
+ # 布尔冒充三态。
437
437
  #
438
438
  # 未收口的部分(JS 侧,本文件当前不是 JS 真源):
439
439
  # - DSH 插件 `packages/dsh-plugin/dsh/client.js` 的 ready/loading/unavailable
@@ -48,6 +48,7 @@ from engines_base import (
48
48
  _CUSTOM_JSON_PARSERS,
49
49
  )
50
50
  from engines_mcp import _build_mcp_engine
51
+ from engines_twitter_cli import _build_twitter_cli_engine
51
52
  from recovery import strip_structured
52
53
  from cli_io import dumps
53
54
 
@@ -428,6 +429,7 @@ _BUILDERS = {
428
429
  "ths_hot": _build_ths_hot_engine,
429
430
  "cls_telegraph": _build_cls_telegraph_engine,
430
431
  "twitter_syndication": _build_twitter_syndication_engine,
432
+ "twitter_cli": _build_twitter_cli_engine,
431
433
  "deps_dev": _build_deps_dev_engine,
432
434
  "biorxiv": _build_biorxiv_engine,
433
435
  "un_comtrade": _build_un_comtrade_engine,