argo-search 2.13.0 → 2.14.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 (89) hide show
  1. package/AGENTS.md +93 -0
  2. package/README.en.md +16 -4
  3. package/README.es.md +16 -4
  4. package/README.ja.md +16 -4
  5. package/README.ko.md +16 -4
  6. package/README.md +16 -4
  7. package/SKILL.md +1 -1
  8. package/assets/readme/counts.json +1 -1
  9. package/backends/domain_profiles.json +66 -6
  10. package/backends/engine_registry.yaml +154 -15
  11. package/backends/env_passthrough.txt +2 -0
  12. package/backends/quota_profiles.json +111 -11
  13. package/bin/argo +3 -0
  14. package/config.yaml +27 -1
  15. package/docs/CHANGELOG.md +23 -0
  16. package/docs/COMMIT_STANDARD.md +98 -0
  17. package/docs/ENGINE_CATALOG.md +94 -79
  18. package/docs/RELEASE_NOTES_v2.14.0.md +77 -0
  19. package/engines/specs/clinicaltrials.yaml +8 -0
  20. package/engines/specs/cnii.yaml +5 -0
  21. package/engines/specs/coingecko.yaml +10 -2
  22. package/engines/specs/dbpedia.yaml +32 -0
  23. package/engines/specs/fourget.yaml +23 -0
  24. package/engines/specs/grep_app.yaml +19 -0
  25. package/engines/specs/hackernews.yaml +1 -0
  26. package/engines/specs/hf_papers.yaml +26 -0
  27. package/engines/specs/kaggle.yaml +44 -0
  28. package/engines/specs/local_baidu.yaml +5 -0
  29. package/engines/specs/local_seek.yaml +34 -0
  30. package/engines/specs/local_yandex.yaml +37 -0
  31. package/engines/specs/mojeek.yaml +31 -0
  32. package/engines/specs/mwmbl.yaml +39 -0
  33. package/engines/specs/openaire.yaml +34 -0
  34. package/engines/specs/repology.yaml +18 -0
  35. package/package.json +13 -10
  36. package/packages/dsh-plugin/dsh/client.js +1 -0
  37. package/packages/dsh-plugin/dsh/native-tools.mjs +24 -3
  38. package/packages/dsh-plugin/dsh/runner.js +35 -1
  39. package/packages/dsh-plugin/dsh/specs.js +3 -1
  40. package/packages/dsh-plugin/dsh/wide-research.js +4 -2
  41. package/packages/dsh-plugin/package.json +1 -1
  42. package/packages/dsh-plugin/test/client.test.js +6 -0
  43. package/packages/dsh-plugin/test/config.test.js +5 -1
  44. package/packages/dsh-plugin/test/index.test.js +3 -1
  45. package/packages/dsh-plugin/test/size-gate.test.js +2 -2
  46. package/scripts/badcase_causes.py +81 -0
  47. package/scripts/badcase_ledger.py +287 -14
  48. package/scripts/cache.py +3 -3
  49. package/scripts/check_commit_report.py +168 -0
  50. package/scripts/engine_admission.py +9 -5
  51. package/scripts/engine_families.py +13 -2
  52. package/scripts/engine_policy.py +1 -1
  53. package/scripts/engine_states.py +393 -8
  54. package/scripts/engine_status.py +31 -0
  55. package/scripts/engine_validate.py +47 -39
  56. package/scripts/engines.py +6 -0
  57. package/scripts/engines_base.py +26 -80
  58. package/scripts/engines_builders.py +5 -0
  59. package/scripts/engines_builders_batch12.py +168 -0
  60. package/scripts/engines_builders_batch16.py +186 -0
  61. package/scripts/engines_parsers.py +399 -0
  62. package/scripts/fetch_browser.py +4 -2
  63. package/scripts/fetch_jsrun.py +2 -1
  64. package/scripts/fetch_v3.py +22 -22
  65. package/scripts/gen_native_tools.py +44 -17
  66. package/scripts/local_intent.py +139 -0
  67. package/scripts/local_seek.py +223 -91
  68. package/scripts/local_seek_adapter.py +87 -0
  69. package/scripts/mcp_transport.py +1 -1
  70. package/scripts/pre-commit +44 -1
  71. package/scripts/recovery.py +14 -5
  72. package/scripts/recovery_l0.py +5 -3
  73. package/scripts/research.py +1 -1
  74. package/scripts/research_gates.py +3 -3
  75. package/scripts/route_lang.py +6 -1
  76. package/scripts/route_policy.py +21 -14
  77. package/scripts/search.py +33 -25
  78. package/scripts/search_cli.py +10 -1
  79. package/scripts/search_output.py +83 -16
  80. package/scripts/source_audit.py +331 -0
  81. package/scripts/sync_backends.py +31 -1
  82. package/scripts/wechat_article.py +5 -3
  83. package/scripts/wide_research.py +4 -1
  84. package/scripts/x_article_fetch.py +2 -1
  85. package/sub-skills/local-search/parsers.py +6 -1
  86. package/sub-skills/local-seek/scripts/seek.py +390 -24
  87. package/sub-skills/local-seek/scripts/seek_fts.py +20 -9
  88. package/sub-skills/local-seek/scripts/seek_rank.py +64 -1
  89. package/engines/specs/cinii.yaml +0 -44
@@ -55,6 +55,9 @@ PASSTHROUGH_PATH = BACKENDS_DIR / "env_passthrough.txt"
55
55
  DSH_CLIENT_PATH = SKILL_DIR / "packages" / "dsh-plugin" / "dsh" / "client.js"
56
56
  _KEYS_BEGIN = " // <generated:keys> 由 scripts/sync_backends.py 从引擎声明生成,勿手改\n"
57
57
  _KEYS_END = " // </generated:keys>\n"
58
+ DSH_RUNNER_PATH = SKILL_DIR / "packages" / "dsh-plugin" / "dsh" / "runner.js"
59
+ _KEYREFS_BEGIN = " // <generated:keyrefs> 由 scripts/sync_backends.py 从引擎声明生成,勿手改\n"
60
+ _KEYREFS_END = " // </generated:keyrefs>\n"
58
61
  # 面板常用组:首屏直接显示的那几把 key(其余在「显示全部」里)
59
62
  # 旧面板手写名单里与候选链规则不一致的 ref(候选链里确实有这个名字,运行时
60
63
  # get_env 能读到):保留旧名,否则 DSH 凭证库里已存的 key 改名后面板显示未配置
@@ -337,6 +340,27 @@ def write_dsh_keys_block(block: str) -> None:
337
340
  atomic_write_text(DSH_CLIENT_PATH, s[:i] + block + s[j + len(_KEYS_END):], mode=0o644)
338
341
 
339
342
 
343
+ def render_keyrefs(rows: list[dict[str, Any]]) -> str:
344
+ body = "".join(" '%s',\n" % r["ref"] for r in rows)
345
+ return _KEYREFS_BEGIN + " keyRefs: [\n" + body + " ],\n" + _KEYREFS_END
346
+
347
+
348
+ def read_keyrefs_block() -> str:
349
+ if not DSH_RUNNER_PATH.exists():
350
+ return ""
351
+ s = DSH_RUNNER_PATH.read_text(encoding="utf-8")
352
+ i, j = s.find(_KEYREFS_BEGIN), s.find(_KEYREFS_END)
353
+ return s[i:j + len(_KEYREFS_END)] if i >= 0 and j > i else ""
354
+
355
+
356
+ def write_keyrefs_block(block: str) -> None:
357
+ s = DSH_RUNNER_PATH.read_text(encoding="utf-8")
358
+ i, j = s.find(_KEYREFS_BEGIN), s.find(_KEYREFS_END)
359
+ if i < 0 or j < i:
360
+ raise SystemExit(f"{DSH_RUNNER_PATH} 缺 <generated:keyrefs> 标记区")
361
+ atomic_write_text(DSH_RUNNER_PATH, s[:i] + block + s[j + len(_KEYREFS_END):], mode=0o644)
362
+
363
+
340
364
  # ── 校验/补全:domain_profiles.json ─────────────────────────────────────────
341
365
 
342
366
  def check_domain_profiles(engines: dict[str, dict[str, Any]], profiles: dict[str, Any]) -> list[str]:
@@ -432,8 +456,11 @@ def collect_issues(engines: dict[str, dict[str, Any]],
432
456
  miss = sorted(set(want_pt) - set(cur_pt))
433
457
  extra = sorted(set(cur_pt) - set(want_pt))
434
458
  issues.append(f"env_passthrough.txt 与声明不一致: 缺 {miss} 多 {extra}")
435
- if DSH_CLIENT_PATH.exists() and read_dsh_keys_block() != render_dsh_keys(derive_dsh_keys(engines)):
459
+ dsh_rows = derive_dsh_keys(engines)
460
+ if DSH_CLIENT_PATH.exists() and read_dsh_keys_block() != render_dsh_keys(dsh_rows):
436
461
  issues.append("packages/dsh-plugin/dsh/client.js 的 KEYS 标记区与引擎声明不一致")
462
+ if DSH_RUNNER_PATH.exists() and read_keyrefs_block() != render_keyrefs(dsh_rows):
463
+ issues.append("packages/dsh-plugin/dsh/runner.js 的 keyRefs 标记区与引擎声明不一致")
437
464
  return issues
438
465
 
439
466
 
@@ -533,6 +560,9 @@ def main() -> int:
533
560
  if DSH_CLIENT_PATH.exists():
534
561
  keys_new = derive_dsh_keys(engines)
535
562
  write_dsh_keys_block(render_dsh_keys(keys_new))
563
+ if DSH_RUNNER_PATH.exists():
564
+ write_keyrefs_block(render_keyrefs(keys_new))
565
+ print(f" dsh runner.js keyRefs {len(keys_new)} 个转发名")
536
566
  print(f" dsh client.js KEYS {len(keys_new)} 把 key")
537
567
  print(f" quota_profiles.json {len(quota_new) - 1} 条")
538
568
  print(f" engine_registry.yaml {len(registry_new['engines'])} 条")
@@ -14,6 +14,8 @@
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
+ import engine_states
18
+
17
19
  import argparse
18
20
  import json
19
21
  import os
@@ -84,7 +86,7 @@ def _cdp_fetch(url: str, timeout: int = 15) -> dict:
84
86
  "image_count": len(imgs),
85
87
  "images": imgs,
86
88
  "content": content,
87
- "fetch_method": "chrome_cdp",
89
+ "fetch_method": engine_states.FETCH_CHROME_CDP,
88
90
  }
89
91
  except Exception as e:
90
92
  return {"ok": False, "error": f"CDP 通道异常: {e}"}
@@ -141,7 +143,7 @@ def _sogou_fallback(url: str) -> dict:
141
143
  "image_count": 0,
142
144
  "images": [],
143
145
  "content": best.get("snippet", ""),
144
- "fetch_method": "sogou_fallback",
146
+ "fetch_method": engine_states.FETCH_SOGOU_FALLBACK,
145
147
  "note": "通过搜狗搜索间接获取,内容可能不完整",
146
148
  }
147
149
  except Exception as e:
@@ -198,7 +200,7 @@ def fetch_wechat_article(url: str) -> dict:
198
200
  # 通道1: HTTP 直取(快速失败)
199
201
  result = _http_fetch(url, timeout=5)
200
202
  if _has_content(result):
201
- result["fetch_method"] = "http_direct"
203
+ result["fetch_method"] = engine_states.FETCH_HTTP_DIRECT
202
204
  result.setdefault("char_count", len(result.get("content") or ""))
203
205
  return result
204
206
 
@@ -40,6 +40,7 @@ from urllib.parse import urlparse
40
40
  sys.path.insert(0, str(Path(__file__).resolve().parent))
41
41
 
42
42
  from cli_io import dumps # noqa: E402
43
+ import engine_states # noqa: E402
43
44
  from research_work_packages import stage_work_packages # noqa: E402
44
45
 
45
46
  MAX_SOURCES_PER_TRACK = 8
@@ -300,7 +301,9 @@ def evaluate_gates(
300
301
  "detail": f"{len(farm_hits)} sources originate from content farms or SEO scraper mirrors; evidence quality severely degraded.",
301
302
  })
302
303
 
303
- cap = "low" if failures else ("medium" if warnings else "high")
304
+ cap = (engine_states.CONCLUSION_CAP_LOW if failures
305
+ else (engine_states.CONCLUSION_CAP_MEDIUM if warnings
306
+ else engine_states.CONCLUSION_CAP_HIGH))
304
307
  return {"passed": not failures, "conclusion_cap": cap, "failures": failures, "warnings": warnings}
305
308
 
306
309
 
@@ -11,6 +11,7 @@ entityMap 里 MEDIA/MARKDOWN 原子块还原为带内嵌图片 Markdown。
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
+ import engine_states
14
15
  import json
15
16
  import os
16
17
  import re
@@ -124,7 +125,7 @@ def fetch_x_article(url: str, max_chars: int = 8000,
124
125
  "length": min(len(content), max_chars),
125
126
  "success": True,
126
127
  "error": None,
127
- "fetch_method": "x_article",
128
+ "fetch_method": engine_states.FETCH_X_ARTICLE,
128
129
  }
129
130
  except Exception:
130
131
  return None
@@ -132,8 +132,13 @@ def _parse_html(engine_name: str, html: str, spec: dict[str, Any],
132
132
  return []
133
133
 
134
134
  try:
135
- from bs4 import BeautifulSoup
135
+ from bs4 import BeautifulSoup, Comment
136
136
  soup = BeautifulSoup(html, "html.parser")
137
+ # 搜狗等站把内部标记写成 HTML 注释(实测 <!--awbg0--> 混进结果
138
+ # 标题前缀 awbg0awbg0):get_text 会拼入 Comment 节点,全页统一
139
+ # 剥离,一处修复所有 parse_maps HTML 引擎。
140
+ for c in soup.find_all(string=lambda t: isinstance(t, Comment)):
141
+ c.extract()
137
142
  containers = _select_with_bs4(soup, container_sel)
138
143
  except Exception:
139
144
  return []
@@ -52,6 +52,18 @@ import time
52
52
  from datetime import datetime
53
53
  from pathlib import Path
54
54
 
55
+ # Windows 控制台与多语言环境编码保护(避免 UTF-8 输出在 GBK 等控制台下抛 UnicodeEncodeError)
56
+ if hasattr(sys.stdout, "reconfigure"):
57
+ try:
58
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
59
+ except Exception:
60
+ pass
61
+ if hasattr(sys.stderr, "reconfigure"):
62
+ try:
63
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
64
+ except Exception:
65
+ pass
66
+
55
67
  from seek_rank import _ZH_EN_ALIASES # 中英工程词对齐(词源单点在 seek_rank)
56
68
 
57
69
  CONFIG_DIR = Path(__file__).resolve().parent.parent / "config"
@@ -88,6 +100,8 @@ NOISE_TIER = [
88
100
  _NOISE_SET = frozenset(n for n in NOISE_TIER if not n.endswith("*"))
89
101
  DOC_EXTS = {"pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "md", "txt",
90
102
  "rtf", "html", "htm", "epub", "csv", "json", "yaml", "yml", "log"}
103
+ OFFICE_ZIP_EXTS = {"docx", "pptx", "xlsx"}
104
+ CONFIG_EXTS = {"yaml", "yml", "json", "toml", "ini", "env", "conf", "xml", "properties"}
91
105
  CODE_EXTS = {"py", "js", "ts", "tsx", "jsx", "go", "rs", "java", "c", "h",
92
106
  "cpp", "hpp", "cs", "rb", "php", "swift", "kt", "sh", "bash",
93
107
  "zsh", "sql", "vue", "svelte", "lua", "r", "scala", "dart", "ex"}
@@ -618,6 +632,154 @@ def rg_search(patterns, path, excludes, exts, context, count, max_results,
618
632
  path, max_results, drop_noise), None
619
633
 
620
634
 
635
+ # ── Office 办公文档解包透视(纯 Python 标准库,零第三方依赖)──────────────
636
+
637
+ def _extract_office_items(file_path: Path) -> list[tuple[int, str]]:
638
+ """从 docx/pptx/xlsx 等 Office zip 容器中免依赖流式提取 (序号, 文本)。"""
639
+ ext = file_path.suffix.lower().lstrip(".")
640
+ if ext not in OFFICE_ZIP_EXTS:
641
+ return []
642
+ import zipfile
643
+ import xml.etree.ElementTree as ET
644
+ items: list[tuple[int, str]] = []
645
+ try:
646
+ with zipfile.ZipFile(file_path, "r") as z:
647
+ namelist = set(z.namelist())
648
+ if ext == "docx" and "word/document.xml" in namelist:
649
+ tree = ET.fromstring(z.read("word/document.xml"))
650
+ p_count = 0
651
+ for p in tree.iter():
652
+ if p.tag.endswith("}p"):
653
+ texts = [node.text for node in p.iter() if node.tag.endswith("}t") and node.text]
654
+ if texts:
655
+ p_text = "".join(texts).strip()
656
+ if p_text:
657
+ p_count += 1
658
+ items.append((p_count, f"[段落{p_count}] {p_text}"))
659
+ elif ext == "pptx":
660
+ slide_names = sorted(
661
+ [n for n in namelist if n.startswith("ppt/slides/slide") and n.endswith(".xml")],
662
+ key=lambda x: [int(c) if c.isdigit() else c for c in re.split(r'(\d+)', x)]
663
+ )
664
+ for s_idx, s_name in enumerate(slide_names):
665
+ tree = ET.fromstring(z.read(s_name))
666
+ texts = [node.text for node in tree.iter() if node.tag.endswith("}t") and node.text]
667
+ if texts:
668
+ s_text = " ".join(texts).strip()
669
+ if s_text:
670
+ items.append((s_idx + 1, f"[幻灯片{s_idx + 1}] {s_text}"))
671
+ elif ext == "xlsx":
672
+ shared_strings: list[str] = []
673
+ if "xl/sharedStrings.xml" in namelist:
674
+ tree = ET.fromstring(z.read("xl/sharedStrings.xml"))
675
+ for si in tree.iter():
676
+ if si.tag.endswith("}si"):
677
+ texts = [node.text for node in si.iter() if node.tag.endswith("}t") and node.text]
678
+ shared_strings.append("".join(texts))
679
+ sheet_names = sorted(
680
+ [n for n in namelist if n.startswith("xl/worksheets/sheet") and n.endswith(".xml")],
681
+ key=lambda x: [int(c) if c.isdigit() else c for c in re.split(r'(\d+)', x)]
682
+ )
683
+ item_idx = 0
684
+ for s_idx, s_name in enumerate(sheet_names):
685
+ tree = ET.fromstring(z.read(s_name))
686
+ for c in tree.iter():
687
+ if c.tag.endswith("}c"):
688
+ cell_ref = c.attrib.get("r", "")
689
+ cell_type = c.attrib.get("t", "")
690
+ v_node = [node.text for node in c.iter() if node.tag.endswith("}v") and node.text]
691
+ val = ""
692
+ if v_node:
693
+ v_str = v_node[0]
694
+ if cell_type == "s" and v_str.isdigit() and int(v_str) < len(shared_strings):
695
+ val = shared_strings[int(v_str)]
696
+ else:
697
+ val = v_str
698
+ if val and val.strip():
699
+ item_idx += 1
700
+ r_match = re.search(r'\d+', cell_ref)
701
+ row_num = int(r_match.group(0)) if r_match else item_idx
702
+ items.append((row_num, f"[Sheet{s_idx + 1}:{cell_ref}] {val.strip()}"))
703
+ except Exception:
704
+ return []
705
+ return items
706
+
707
+
708
+ def office_search(patterns: list[str], path: Path, excludes: list[str],
709
+ exts: list[str], count: bool, max_results: int,
710
+ fixed: bool, raw_query: str = "", dots: bool = False,
711
+ drop_noise: bool = True, since_ts: float | None = None,
712
+ until_ts: float | None = None) -> list[tuple[str, int, str]]:
713
+ """扫描目标路径下的 Office 容器文件并提取匹配文本。"""
714
+ active_exts = (set(exts) & OFFICE_ZIP_EXTS) if exts else OFFICE_ZIP_EXTS
715
+ if not active_exts:
716
+ return []
717
+
718
+ compiled = []
719
+ for p in patterns:
720
+ try:
721
+ pattern_str = re.escape(p) if fixed else p
722
+ compiled.append(re.compile(pattern_str, re.IGNORECASE))
723
+ except re.error:
724
+ pass
725
+ if not compiled:
726
+ return []
727
+
728
+ candidates = []
729
+ counts = []
730
+
731
+ if path.is_file():
732
+ files_to_scan = [path] if path.suffix.lower().lstrip(".") in active_exts else []
733
+ else:
734
+ files_to_scan = []
735
+ for root, dirs, files in os.walk(path):
736
+ if not dots:
737
+ dirs[:] = [d for d in dirs if not d.startswith(".")]
738
+ if any(exc in root for exc in excludes if exc):
739
+ continue
740
+ for f in files:
741
+ ext = f.rsplit(".", 1)[-1].lower() if "." in f else ""
742
+ if ext in active_exts:
743
+ fp = Path(root) / f
744
+ if _in_time_window(str(fp), since_ts, until_ts):
745
+ files_to_scan.append(fp)
746
+
747
+ for fp in files_to_scan:
748
+ fp_str = str(fp)
749
+ items = _extract_office_items(fp)
750
+ matched_in_file = 0
751
+ for line_num, txt in items:
752
+ if any(c.search(txt) for c in compiled):
753
+ matched_in_file += 1
754
+ if not count:
755
+ candidates.append((fp_str, line_num, truncate(txt)))
756
+ if count and matched_in_file > 0:
757
+ counts.append((fp_str, matched_in_file, ""))
758
+
759
+ if count:
760
+ counts.sort(key=lambda t: (-t[1], t[0]))
761
+ return counts[:max_results]
762
+
763
+ if not candidates:
764
+ return []
765
+
766
+ return _finish_content(iter(candidates), raw_query, 0, count, fixed,
767
+ path, max_results, drop_noise)
768
+
769
+
770
+ def _merge_content_dedup(a: list, b: list, limit: int) -> list:
771
+ """按 (文件路径, 行号) 去重合并两组正文搜索结果。"""
772
+ seen, out = set(), []
773
+ for it in list(a) + list(b):
774
+ key = (it[0], it[1]) if isinstance(it, (list, tuple)) and len(it) >= 2 else str(it)
775
+ if key not in seen:
776
+ seen.add(key)
777
+ out.append(it)
778
+ if len(out) >= limit:
779
+ break
780
+ return out
781
+
782
+
621
783
  # ── fzf FuzzyMatchV2 评分 + 拼音首字母(pypinyin 优先,GB2312 表保底)──────────
622
784
  # 评分常数与对齐算法按 junegunn/fzf src/algo/algo.go 的 FuzzyMatchV2 口径实现
623
785
  # (2026-10-07 方案甲:原手搓版只有「边界+4/连续+3/全等+5」三档,无 gap 惩罚、
@@ -967,6 +1129,149 @@ def mdfind_search(query, path, max_results, timeout=None,
967
1129
  return [(p, 0, "") for p in lines[:max_results]], None
968
1130
 
969
1131
 
1132
+ _BINARY_EXTS = frozenset({
1133
+ "exe", "dll", "so", "dylib", "bin", "o", "a", "lib",
1134
+ "png", "jpg", "jpeg", "gif", "ico", "webp", "bmp", "psd",
1135
+ "mp3", "mp4", "mov", "avi", "mkv", "flv", "wav",
1136
+ "zip", "tar", "gz", "7z", "bz2", "xz", "rar",
1137
+ "pyc", "pyo", "pyd", "class", "db", "sqlite", "sqlite3"
1138
+ })
1139
+
1140
+
1141
+ def py_walk_filename(query: str, path: Path, exts: list[str], max_results: int,
1142
+ dots: bool = False, timeout: float | None = None,
1143
+ since_ts: float | None = None, until_ts: float | None = None) -> tuple[list, str | None]:
1144
+ """纯 Python 标准库文件名检索(无 fd 时的全平台保底,零外部依赖)。"""
1145
+ timeout = _RUN_DEFAULT_TIMEOUT_S if timeout is None else timeout
1146
+ deadline = (time.time() + timeout) if timeout else None
1147
+ q_low = query.lower()
1148
+ matches = []
1149
+ excludes = set(load_excludes())
1150
+ root_str = str(Path(path).expanduser())
1151
+
1152
+ for root, dirs, files in os.walk(root_str):
1153
+ if deadline and time.time() > deadline:
1154
+ break
1155
+ if not dots:
1156
+ dirs[:] = [d for d in dirs if not d.startswith(".")]
1157
+ dirs[:] = [d for d in dirs if d not in excludes and not any(ex in d for ex in excludes if "*" in ex)]
1158
+
1159
+ for f in files:
1160
+ if not dots and f.startswith("."):
1161
+ continue
1162
+ if exts:
1163
+ suffix = f.rsplit(".", 1)[-1].lower() if "." in f else ""
1164
+ if suffix not in exts:
1165
+ continue
1166
+ if not query or q_low in f.lower():
1167
+ fp = os.path.join(root, f)
1168
+ if _in_time_window(fp, since_ts, until_ts):
1169
+ matches.append((fp, 0, ""))
1170
+ if len(matches) >= max_results * 4:
1171
+ break
1172
+ if len(matches) >= max_results * 4:
1173
+ break
1174
+
1175
+ ranked = _rank_path_results(matches, query) if matches else []
1176
+ return ranked[:max_results], None
1177
+
1178
+
1179
+ def py_walk_search(patterns: list[str], path: Path, excludes: list[str], exts: list[str],
1180
+ context: int, count: bool, max_results: int, fixed: bool,
1181
+ raw_query: str = "", dots: bool = False, timeout: float | None = None,
1182
+ since_ts: float | None = None, until_ts: float | None = None) -> tuple[list, str | None]:
1183
+ """纯 Python 标准库文件内容检索(无 rg 与 grep 时的全平台保底,零外部依赖)。"""
1184
+ timeout = _RUN_DEFAULT_TIMEOUT_S if timeout is None else timeout
1185
+ deadline = (time.time() + timeout) if timeout else None
1186
+ ex_set = set(excludes)
1187
+ pats = patterns or ([raw_query] if raw_query else [])
1188
+ if not pats:
1189
+ return [], None
1190
+
1191
+ regexes = None
1192
+ if not fixed:
1193
+ regexes = []
1194
+ for p in pats:
1195
+ try:
1196
+ regexes.append(re.compile(p, re.IGNORECASE))
1197
+ except re.error:
1198
+ regexes.append(re.compile(re.escape(p), re.IGNORECASE))
1199
+ pats_lower = [p.lower() for p in pats]
1200
+
1201
+ counts = []
1202
+ candidates = []
1203
+ root_str = str(Path(path).expanduser())
1204
+
1205
+ for root, dirs, files in os.walk(root_str):
1206
+ if deadline and time.time() > deadline:
1207
+ break
1208
+ if not dots:
1209
+ dirs[:] = [d for d in dirs if not d.startswith(".")]
1210
+ dirs[:] = [d for d in dirs if d not in ex_set]
1211
+
1212
+ for f in files:
1213
+ if deadline and time.time() > deadline:
1214
+ break
1215
+ if not dots and f.startswith("."):
1216
+ continue
1217
+ suffix = f.rsplit(".", 1)[-1].lower() if "." in f else ""
1218
+ if exts:
1219
+ if suffix not in exts:
1220
+ continue
1221
+ elif suffix in _BINARY_EXTS:
1222
+ continue
1223
+
1224
+ fp = os.path.join(root, f)
1225
+ try:
1226
+ st = os.stat(fp)
1227
+ if st.st_size > 5 * 1024 * 1024 or st.st_size == 0:
1228
+ continue
1229
+ except OSError:
1230
+ continue
1231
+
1232
+ if not _in_time_window(fp, since_ts, until_ts):
1233
+ continue
1234
+
1235
+ file_matched_lines = 0
1236
+ try:
1237
+ with open(fp, "r", encoding="utf-8", errors="replace") as fh:
1238
+ for line_idx, line in enumerate(fh, start=1):
1239
+ matched = False
1240
+ if fixed:
1241
+ line_low = line.lower()
1242
+ matched = any(p in line_low for p in pats_lower)
1243
+ elif regexes:
1244
+ matched = any(rgx.search(line) for rgx in regexes)
1245
+
1246
+ if matched:
1247
+ file_matched_lines += 1
1248
+ if not count:
1249
+ candidates.append((fp, line_idx, truncate(line)))
1250
+ if len(candidates) >= _POOL_CAP_MAX:
1251
+ break
1252
+ except (OSError, UnicodeError):
1253
+ continue
1254
+
1255
+ if count and file_matched_lines > 0:
1256
+ counts.append((fp, file_matched_lines, ""))
1257
+ if len(counts) >= max_results * 2:
1258
+ break
1259
+ if (count and len(counts) >= max_results * 2) or (not count and len(candidates) >= _POOL_CAP_MAX):
1260
+ break
1261
+
1262
+ if count:
1263
+ counts.sort(key=lambda t: (-t[1], t[0]))
1264
+ return counts[:max_results], None
1265
+
1266
+ if not candidates:
1267
+ return [], None
1268
+
1269
+ return _finish_content(
1270
+ iter(candidates), raw_query, context, count, fixed,
1271
+ root_str, max_results, drop_noise=True
1272
+ ), None
1273
+
1274
+
970
1275
  def format_output(results, engine, mode, path, elapsed_ms, query, total):
971
1276
  lines = [f"local-seek: {total} 处命中({engine} · {path} · {elapsed_ms}ms · 模式 {mode})"]
972
1277
  base = os.path.abspath(os.path.expanduser(path))
@@ -984,7 +1289,27 @@ def format_output(results, engine, mode, path, elapsed_ms, query, total):
984
1289
  return "\n".join(lines)
985
1290
 
986
1291
 
1292
+ def _cluster_results(results):
1293
+ """为同一文件紧邻(行号差 <= 4)的命中分配逻辑聚簇 ID。"""
1294
+ if not results:
1295
+ return []
1296
+ clusters = []
1297
+ cid = 1
1298
+ for i, (fp, ln, _txt) in enumerate(results):
1299
+ assigned = None
1300
+ if i > 0 and ln and ln > 0:
1301
+ prev_fp, prev_ln, _ = results[i - 1]
1302
+ if prev_fp == fp and prev_ln and prev_ln > 0 and abs(ln - prev_ln) <= 4:
1303
+ assigned = clusters[i - 1]
1304
+ if assigned is None:
1305
+ assigned = cid
1306
+ cid += 1
1307
+ clusters.append(assigned)
1308
+ return clusters
1309
+
1310
+
987
1311
  def to_json(results, engine, mode, scope, path, elapsed_ms, query, since=None, until=None):
1312
+ clusters = _cluster_results(results)
988
1313
  return json.dumps({
989
1314
  "query": query,
990
1315
  "engine": engine,
@@ -996,8 +1321,8 @@ def to_json(results, engine, mode, scope, path, elapsed_ms, query, since=None, u
996
1321
  "since": since,
997
1322
  "until": until,
998
1323
  "results": [
999
- {"path": fp, "line": ln, "snippet": txt, "mtime": _file_mtime(fp)}
1000
- for fp, ln, txt in results
1324
+ {"path": fp, "line": ln, "snippet": txt, "mtime": _file_mtime(fp), "cluster": cid}
1325
+ for (fp, ln, txt), cid in zip(results, clusters)
1001
1326
  ],
1002
1327
  }, ensure_ascii=False, indent=2)
1003
1328
 
@@ -1290,7 +1615,15 @@ def _run_grep_fallback(args, patterns, fixed, path, excludes, exts, max_results,
1290
1615
  ), None, "fts"
1291
1616
  grep_exe = resolve_grep()
1292
1617
  if not grep_exe:
1293
- return None, "本机无 rg 与 grep 可用,请安装 ripgrep", ""
1618
+ # 纯 Python 标准库保底(Windows / Linux 裸机环境开箱即用,零外部工具依赖)
1619
+ results, err = py_walk_search(
1620
+ patterns, path, excludes, exts, args.context, args.count,
1621
+ max_results, fixed, raw_query=args.query, dots=dots,
1622
+ timeout=timeout, since_ts=since_ts, until_ts=until_ts
1623
+ )
1624
+ if results:
1625
+ return results, None, "py-walk"
1626
+ return None, "本机无 rg 与 grep 可用(纯 Python 保底亦无匹配),请安装 ripgrep", ""
1294
1627
  mode = "fast"
1295
1628
  if not args.exact and len(patterns) > 1:
1296
1629
  results, err = grep_search(grep_exe, [args.query], path, excludes, exts,
@@ -1325,8 +1658,8 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
1325
1658
  ap = argparse.ArgumentParser(prog="seek", description="本地高效搜索统一入口")
1326
1659
  ap.add_argument("query", nargs="?", help="搜索查询词")
1327
1660
  ap.add_argument("--path", default=".", help="搜索目录(默认当前目录)")
1328
- ap.add_argument("--scope", choices=["code", "doc", "all"], default="code",
1329
- help="code=正文+代码;doc=文档类;all=Spotlight 兜底")
1661
+ ap.add_argument("--scope", choices=["code", "doc", "office", "config", "all"], default="code",
1662
+ help="code=正文+代码;doc/office=办公与文档;config=配置文件;all=Spotlight 兜底")
1330
1663
  ap.add_argument("--filename", action="store_true", help="按文件名查找(fd)")
1331
1664
  ap.add_argument("--spotlight", action="store_true", help="Spotlight 全盘兜底")
1332
1665
  ap.add_argument("--dot", action="store_true",
@@ -1412,13 +1745,14 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
1412
1745
  scope = args.scope
1413
1746
  if args.spotlight:
1414
1747
  scope = "all"
1415
- # doc 场景补充文档扩展名
1416
- if scope == "doc" and not exts:
1417
- # 文本档(md/txt/html…)rg 直接搜全文;pdf/docx 等二进制 rg 搜不出
1418
- # 内容,那是 --spotlight(Spotlight 内容索引)的职责。此前把 md/txt
1419
- # 从 exts 里减掉,恰好漏掉最常搜的笔记(2026-10-03 实测:--scope doc
1420
- # 搜 md 零命中,doc 场景等于虚设)。
1421
- exts = sorted(DOC_EXTS)
1748
+ # doc / office 场景补充文档与办公扩展名
1749
+ if scope in ("doc", "office") and not exts:
1750
+ exts = sorted(DOC_EXTS | OFFICE_ZIP_EXTS)
1751
+ scope = "code"
1752
+ if not tool_exists("rg"):
1753
+ scope = "all"
1754
+ elif scope == "config" and not exts:
1755
+ exts = sorted(CONFIG_EXTS)
1422
1756
  scope = "code"
1423
1757
  if not tool_exists("rg"):
1424
1758
  scope = "all"
@@ -1455,17 +1789,6 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
1455
1789
  engine, mode = "none", "fast"
1456
1790
  else:
1457
1791
  engine, mode = "grep", gmode
1458
- elif not tool_exists("rg"):
1459
- # 目录内搜索缺 rg 必须落 grep,不能落 mdfind:Spotlight 不索引
1460
- # 源码内容,会把「工具缺失」伪装成「搜索结论」(实测搜 argo 自身
1461
- # 符号返回 24 条外部陈旧副本、漏掉正主,还报「未找到匹配」)。
1462
- results, err, gmode = _run_grep_fallback(
1463
- args, patterns, fixed, path, excludes, exts, max_results,
1464
- timeout=time_budget, since_ts=since_ts, until_ts=until_ts)
1465
- if results is None:
1466
- engine, mode = "none", "fast"
1467
- else:
1468
- engine, mode = "grep", gmode
1469
1792
  elif args.filename:
1470
1793
  engine, mode = "fd", "fast"
1471
1794
  if tool_exists("fd"):
@@ -1493,7 +1816,39 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
1493
1816
  if py_hits:
1494
1817
  results = _merge_dedup(results or [], py_hits, max_results)
1495
1818
  else:
1496
- err = "fd 未安装:按文件名搜索需要 fd(内容搜索走 rg/grep)"
1819
+ # 纯 Python 标准库保底:系统未安装 fd 时(Windows/Linux 裸机环境),通过 os.walk 查找文件名
1820
+ results, err = py_walk_filename(
1821
+ args.query, path, exts, max_results, dots=args.dot,
1822
+ timeout=time_budget, since_ts=since_ts, until_ts=until_ts
1823
+ )
1824
+ engine = "py-walk"
1825
+ if not err and len(results or []) < 3:
1826
+ _cjk_len = sum(1 for c in args.query if "\u4e00" <= c <= "\u9fff")
1827
+ q_py = pinyin_initials(args.query)
1828
+ if _cjk_len >= 2 and q_py and q_py.lower() != args.query.strip().lower():
1829
+ py_res, py_err = py_walk_filename(
1830
+ q_py, path, exts, max_results, dots=args.dot,
1831
+ timeout=time_budget, since_ts=since_ts, until_ts=until_ts
1832
+ )
1833
+ if not py_err and py_res:
1834
+ results = _merge_dedup(results or [], py_res, max_results)
1835
+ if not results and not err:
1836
+ err = "fd 未安装(纯 Python 扫描亦无匹配):按文件名搜索建议安装 fd"
1837
+ elif not tool_exists("rg"):
1838
+ # 目录内搜索缺 rg 必须落 grep,不能落 mdfind:Spotlight 不索引
1839
+ # 源码内容,会把「工具缺失」伪装成「搜索结论」(实测搜 argo 自身
1840
+ # 符号返回 24 条外部陈旧副本、漏掉正主,还报「未找到匹配」)。
1841
+ results, err, gmode = _run_grep_fallback(
1842
+ args, patterns, fixed, path, excludes, exts, max_results,
1843
+ timeout=time_budget, since_ts=since_ts, until_ts=until_ts)
1844
+ if results is None:
1845
+ engine, mode = "none", "fast"
1846
+ elif gmode == "fts":
1847
+ engine, mode = "fts", gmode
1848
+ elif gmode.startswith("py-walk"):
1849
+ engine, mode = "py-walk", gmode
1850
+ else:
1851
+ engine, mode = "grep", gmode
1497
1852
  else:
1498
1853
  mode = "deep" if (args.context > 0 or args.count) else "fast"
1499
1854
  # FTS 快路资格:带扩展名过滤、自定义排除或符号搜索时关闭(快路不做 rg 侧 glob 与 -w 过滤)。
@@ -1548,6 +1903,17 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
1548
1903
  # 早先版本用 rg 的 -g glob 排除,那会连搜索根自己叫 tests/ 的情况一起打死
1549
1904
  # (实测整棵树被判空、且回落也不触发),故改成 Python 层排序。
1550
1905
 
1906
+ # 融合 Office 办公文档解包透视(DOCX/PPTX/XLSX,纯标准库免依赖)
1907
+ if not args.filename and (args.scope in ("doc", "office") or (exts and any(e in OFFICE_ZIP_EXTS for e in exts))):
1908
+ office_res = office_search(patterns, path, excludes, exts, args.count,
1909
+ max_results, fixed, args.query, args.dot,
1910
+ drop_noise=not args.include_noise,
1911
+ since_ts=since_ts, until_ts=until_ts)
1912
+ if office_res:
1913
+ results = _merge_content_dedup(results or [], office_res, max_results)
1914
+ if "office" not in engine:
1915
+ engine = f"{engine}+office"
1916
+
1551
1917
  elapsed = int((time.time() - start) * 1000)
1552
1918
  # 时间窗:统一出口按文件 mtime 过滤(rg/fd/mdfind 共用)
1553
1919
  results = filter_by_mtime(results, args.since, args.until)