foxclaw 0.1.0 → 0.1.3

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 (514) hide show
  1. package/README.md +54 -29
  2. package/bin/foxclaw.cjs +51 -0
  3. package/index.js +4 -10
  4. package/package.json +46 -38
  5. package/python/.dockerignore +35 -0
  6. package/python/.env.example +173 -0
  7. package/python/.gitattributes +46 -0
  8. package/python/.github/workflows/ci.yml +167 -0
  9. package/python/.github/workflows/release.yml +183 -0
  10. package/python/CHANGELOG.md +57 -0
  11. package/python/CHANGELOG_CN.md +57 -0
  12. package/python/Dockerfile +64 -0
  13. package/python/LICENSE +21 -0
  14. package/python/MANIFEST.in +14 -0
  15. package/python/README.md +201 -0
  16. package/python/README_CN.md +336 -0
  17. package/python/bench/bm25_audit.py +186 -0
  18. package/python/bench/bm25_regression.py +177 -0
  19. package/python/bench/bm25_stress.py +155 -0
  20. package/python/bench/cd_audit.py +215 -0
  21. package/python/bench/chaos.py +140 -0
  22. package/python/bench/concurrency.py +103 -0
  23. package/python/bench/e2e_real_models.py +94 -0
  24. package/python/bench/llm_retry_test.py +241 -0
  25. package/python/bench/load_test.py +193 -0
  26. package/python/bench/vector_ivf_upgrade.py +128 -0
  27. package/python/docs/CHANNELS.md +195 -0
  28. package/python/docs/GOVERNANCE.md +164 -0
  29. package/python/docs/RELEASE.md +110 -0
  30. package/python/docs/RUN.md +75 -0
  31. package/python/docs/RUN_CN.md +121 -0
  32. package/python/docs//351/205/215/347/275/256/346/214/207/345/215/227.md +152 -0
  33. package/python/evals/__init__.py +0 -0
  34. package/python/evals/governance/README.md +61 -0
  35. package/python/evals/governance/__init__.py +0 -0
  36. package/python/evals/governance/cases.py +115 -0
  37. package/python/evals/governance/compare_embeddings.py +94 -0
  38. package/python/evals/governance/convergence.svg +11 -0
  39. package/python/evals/governance/report.json +371 -0
  40. package/python/evals/governance/run_evals.py +368 -0
  41. package/python/examples/governance_middleware_demo.py +72 -0
  42. package/python/examples/langgraph_governance_demo.py +104 -0
  43. package/python/examples/sample_itinerary.csv +6 -0
  44. package/python/examples/sample_knowledge.csv +9 -0
  45. package/python/examples/sample_transactions.csv +14 -0
  46. package/python/foxclaw/__init__.py +408 -0
  47. package/python/foxclaw/agents/__init__.py +12 -0
  48. package/python/foxclaw/agents/agents.py +35 -0
  49. package/python/foxclaw/agents/base.py +794 -0
  50. package/python/foxclaw/agents/impl/__init__.py +1 -0
  51. package/python/foxclaw/agents/impl/_helpers.py +70 -0
  52. package/python/foxclaw/agents/impl/finance.py +231 -0
  53. package/python/foxclaw/agents/impl/office.py +350 -0
  54. package/python/foxclaw/agents/impl/supervisor.py +592 -0
  55. package/python/foxclaw/agents/mixins/_context.py +128 -0
  56. package/python/foxclaw/agents/mixins/augment.py +143 -0
  57. package/python/foxclaw/agents/mixins/llm.py +67 -0
  58. package/python/foxclaw/agents/mixins/memory.py +41 -0
  59. package/python/foxclaw/agents/mixins/preference.py +131 -0
  60. package/python/foxclaw/agents/mixins/prompt.py +71 -0
  61. package/python/foxclaw/agents/mixins/skillbox.py +58 -0
  62. package/python/foxclaw/agents/mixins/tool_exec.py +417 -0
  63. package/python/foxclaw/api/__init__.py +224 -0
  64. package/python/foxclaw/api/_state.py +43 -0
  65. package/python/foxclaw/api/bootstrap.py +96 -0
  66. package/python/foxclaw/api/middleware.py +294 -0
  67. package/python/foxclaw/api/routes/ahs.py +404 -0
  68. package/python/foxclaw/api/routes/attachments.py +116 -0
  69. package/python/foxclaw/api/routes/browser.py +35 -0
  70. package/python/foxclaw/api/routes/domain.py +306 -0
  71. package/python/foxclaw/api/routes/knowledge.py +145 -0
  72. package/python/foxclaw/api/routes/llm_admin.py +449 -0
  73. package/python/foxclaw/api/routes/memory.py +105 -0
  74. package/python/foxclaw/api/routes/orchestration.py +39 -0
  75. package/python/foxclaw/api/routes/recovery.py +44 -0
  76. package/python/foxclaw/api/routes/review.py +266 -0
  77. package/python/foxclaw/api/routes/search.py +33 -0
  78. package/python/foxclaw/api/routes/system.py +311 -0
  79. package/python/foxclaw/api/routes/task.py +263 -0
  80. package/python/foxclaw/api/routes/ws.py +64 -0
  81. package/python/foxclaw/api/spine.py +52 -0
  82. package/python/foxclaw/browser/__init__.py +13 -0
  83. package/python/foxclaw/browser/action/__init__.py +1 -0
  84. package/python/foxclaw/browser/action/action_executor.py +50 -0
  85. package/python/foxclaw/browser/action/action_types.py +44 -0
  86. package/python/foxclaw/browser/action/action_verifier.py +68 -0
  87. package/python/foxclaw/browser/action/url_policy.py +143 -0
  88. package/python/foxclaw/browser/adapter/__init__.py +1 -0
  89. package/python/foxclaw/browser/adapter/base_adapter.py +23 -0
  90. package/python/foxclaw/browser/adapter/web_adapter.py +46 -0
  91. package/python/foxclaw/browser/driver/__init__.py +1 -0
  92. package/python/foxclaw/browser/driver/base_driver.py +61 -0
  93. package/python/foxclaw/browser/driver/playwright_driver.py +170 -0
  94. package/python/foxclaw/browser/perception/__init__.py +1 -0
  95. package/python/foxclaw/browser/perception/dom_extractor.py +42 -0
  96. package/python/foxclaw/browser/perception/element_indexer.py +56 -0
  97. package/python/foxclaw/browser/perception/semantic_reducer.py +33 -0
  98. package/python/foxclaw/browser/perception/snapshot.py +29 -0
  99. package/python/foxclaw/browser/service.py +144 -0
  100. package/python/foxclaw/browser/session/__init__.py +1 -0
  101. package/python/foxclaw/browser/session/session_manager.py +57 -0
  102. package/python/foxclaw/capability/__init__.py +12 -0
  103. package/python/foxclaw/capability/embedding_service.py +65 -0
  104. package/python/foxclaw/channels/__init__.py +138 -0
  105. package/python/foxclaw/channels/discord.py +175 -0
  106. package/python/foxclaw/channels/dispatcher.py +179 -0
  107. package/python/foxclaw/channels/feishu.py +215 -0
  108. package/python/foxclaw/channels/openclaw_bridge.py +151 -0
  109. package/python/foxclaw/channels/signing.py +187 -0
  110. package/python/foxclaw/channels/telegram.py +120 -0
  111. package/python/foxclaw/channels/weixin.py +215 -0
  112. package/python/foxclaw/cli.py +183 -0
  113. package/python/foxclaw/cognitive/__init__.py +4 -0
  114. package/python/foxclaw/cognitive/reasoner.py +81 -0
  115. package/python/foxclaw/cognitive/state.py +141 -0
  116. package/python/foxclaw/core/__init__.py +9 -0
  117. package/python/foxclaw/core/audit_chain.py +131 -0
  118. package/python/foxclaw/core/audit_sink.py +100 -0
  119. package/python/foxclaw/core/compaction.py +265 -0
  120. package/python/foxclaw/core/config.py +65 -0
  121. package/python/foxclaw/core/confirm_nonce.py +151 -0
  122. package/python/foxclaw/core/dispatch.py +27 -0
  123. package/python/foxclaw/core/envfile.py +48 -0
  124. package/python/foxclaw/core/failure_policy.py +142 -0
  125. package/python/foxclaw/core/gateway.py +81 -0
  126. package/python/foxclaw/core/governance_audit.py +171 -0
  127. package/python/foxclaw/core/idempotency.py +282 -0
  128. package/python/foxclaw/core/injection_guard.py +202 -0
  129. package/python/foxclaw/core/memory_adapter.py +489 -0
  130. package/python/foxclaw/core/metrics.py +88 -0
  131. package/python/foxclaw/core/model_router.py +985 -0
  132. package/python/foxclaw/core/paths.py +103 -0
  133. package/python/foxclaw/core/recovery.py +349 -0
  134. package/python/foxclaw/core/scheduler.py +141 -0
  135. package/python/foxclaw/core/secrets.py +131 -0
  136. package/python/foxclaw/core/sessions.py +155 -0
  137. package/python/foxclaw/core/settings.py +414 -0
  138. package/python/foxclaw/core/shared_write.py +186 -0
  139. package/python/foxclaw/core/steering_queue.py +154 -0
  140. package/python/foxclaw/core/system_bus.py +84 -0
  141. package/python/foxclaw/core/thought_chain.py +316 -0
  142. package/python/foxclaw/core/token_meter.py +231 -0
  143. package/python/foxclaw/core/tools.py +164 -0
  144. package/python/foxclaw/core/tracing.py +375 -0
  145. package/python/foxclaw/core/truth_pipeline.py +110 -0
  146. package/python/foxclaw/core/update_check.py +149 -0
  147. package/python/foxclaw/core/vec_recall_adapter.py +477 -0
  148. package/python/foxclaw/core/verify.py +173 -0
  149. package/python/foxclaw/core/web_search.py +218 -0
  150. package/python/foxclaw/finance/__init__.py +15 -0
  151. package/python/foxclaw/finance/evidence.py +149 -0
  152. package/python/foxclaw/finance/fx.py +98 -0
  153. package/python/foxclaw/finance/graph.py +179 -0
  154. package/python/foxclaw/finance/models.py +146 -0
  155. package/python/foxclaw/finance/nlparse.py +515 -0
  156. package/python/foxclaw/finance/policy.py +301 -0
  157. package/python/foxclaw/finance/reasoner.py +121 -0
  158. package/python/foxclaw/finance/reasoning.py +319 -0
  159. package/python/foxclaw/finance/reconcile.py +175 -0
  160. package/python/foxclaw/finance/runtime.py +500 -0
  161. package/python/foxclaw/governance/__init__.py +24 -0
  162. package/python/foxclaw/governance/middleware.py +176 -0
  163. package/python/foxclaw/harness/__init__.py +17 -0
  164. package/python/foxclaw/harness/_base.py +66 -0
  165. package/python/foxclaw/harness/_policy.py +340 -0
  166. package/python/foxclaw/harness/drift.py +77 -0
  167. package/python/foxclaw/harness/event_bus.py +28 -0
  168. package/python/foxclaw/harness/harness.py +358 -0
  169. package/python/foxclaw/harness/loop_detection.py +145 -0
  170. package/python/foxclaw/itinerary/__init__.py +10 -0
  171. package/python/foxclaw/itinerary/amap_client.py +114 -0
  172. package/python/foxclaw/itinerary/models.py +80 -0
  173. package/python/foxclaw/itinerary/reasoner.py +96 -0
  174. package/python/foxclaw/itinerary/reasoning.py +168 -0
  175. package/python/foxclaw/itinerary/runtime.py +144 -0
  176. package/python/foxclaw/kernel/__init__.py +13 -0
  177. package/python/foxclaw/kernel/capabilities.py +72 -0
  178. package/python/foxclaw/kernel/policy_gate.py +108 -0
  179. package/python/foxclaw/kernel/process_manager.py +186 -0
  180. package/python/foxclaw/kernel/scheduler.py +125 -0
  181. package/python/foxclaw/kernel/sentinel.py +443 -0
  182. package/python/foxclaw/kernel/sentinel_client.py +243 -0
  183. package/python/foxclaw/kernel/spine.py +97 -0
  184. package/python/foxclaw/knowledge/__init__.py +360 -0
  185. package/python/foxclaw/knowledge/truth_crystallizer.py +89 -0
  186. package/python/foxclaw/learning/__init__.py +12 -0
  187. package/python/foxclaw/learning/knowledge_graph.py +144 -0
  188. package/python/foxclaw/learning/models.py +93 -0
  189. package/python/foxclaw/learning/reasoner.py +67 -0
  190. package/python/foxclaw/learning/runtime.py +351 -0
  191. package/python/foxclaw/learning/spaced_repetition.py +91 -0
  192. package/python/foxclaw/mcp_server.py +188 -0
  193. package/python/foxclaw/orchestration/__init__.py +167 -0
  194. package/python/foxclaw/pipeline/__init__.py +23 -0
  195. package/python/foxclaw/pipeline/cognitive_pipeline.py +429 -0
  196. package/python/foxclaw/pipeline/stage_meta.py +21 -0
  197. package/python/foxclaw/pipeline/supervisor_stages.py +201 -0
  198. package/python/foxclaw/planning/__init__.py +17 -0
  199. package/python/foxclaw/planning/llm_planner.py +232 -0
  200. package/python/foxclaw/planning/planner.py +94 -0
  201. package/python/foxclaw/search/__init__.py +24 -0
  202. package/python/foxclaw/search/agent_port.py +190 -0
  203. package/python/foxclaw/search/evidence.py +109 -0
  204. package/python/foxclaw/search/external_search.py +50 -0
  205. package/python/foxclaw/search/hkc_read_port.py +60 -0
  206. package/python/foxclaw/search/internal_search.py +71 -0
  207. package/python/foxclaw/search/models.py +127 -0
  208. package/python/foxclaw/search/planner.py +44 -0
  209. package/python/foxclaw/search/retriever.py +39 -0
  210. package/python/foxclaw/search/runtime.py +127 -0
  211. package/python/foxclaw/search/strategy.py +44 -0
  212. package/python/foxclaw/skills/__init__.py +559 -0
  213. package/python/foxclaw/skills/archive.py +111 -0
  214. package/python/foxclaw/skills/fetch.py +226 -0
  215. package/python/foxclaw/skills/hooks_spec.py +69 -0
  216. package/python/foxclaw/skills/install_cmd.py +216 -0
  217. package/python/foxclaw/skills/lifecycle.py +252 -0
  218. package/python/foxclaw/skills/markdown_skill.py +175 -0
  219. package/python/foxclaw/skills/markdown_store.py +39 -0
  220. package/python/foxclaw/skills/mcp_client.py +184 -0
  221. package/python/foxclaw/skills/mcp_store.py +40 -0
  222. package/python/foxclaw/skills/permission.py +145 -0
  223. package/python/foxclaw/skills/pipeline.py +354 -0
  224. package/python/foxclaw/skills/policy.py +74 -0
  225. package/python/foxclaw/skills/review.py +72 -0
  226. package/python/foxclaw/skills/store.py +57 -0
  227. package/python/frontend/assets/core_bg.jpg +0 -0
  228. package/python/frontend/deck/auth.js +25 -0
  229. package/python/frontend/deck/chat_model_picker.js +483 -0
  230. package/python/frontend/deck/domain.js +276 -0
  231. package/python/frontend/deck/main.js +1806 -0
  232. package/python/frontend/deck/markdown.js +44 -0
  233. package/python/frontend/deck/settings.js +307 -0
  234. package/python/frontend/deck/state.js +5 -0
  235. package/python/frontend/deck/util.js +4 -0
  236. package/python/frontend/deck/visuals.js +190 -0
  237. package/python/frontend/deck.css +855 -0
  238. package/python/frontend/deck.html +686 -0
  239. package/python/frontend/deck_v2.html +341 -0
  240. package/python/frontend/planet/index.html +266 -0
  241. package/python/frontend/planet/planet.css +579 -0
  242. package/python/frontend/planet/planet.js +1436 -0
  243. package/python/frontend/planet/vendor/three.core.min.js +6 -0
  244. package/python/frontend/planet/vendor/three.module.min.js +6 -0
  245. package/python/frontend/v3/assets/index-CQSBdxk4.js +34 -0
  246. package/python/frontend/v3/assets/index-D5nIsjms.css +1 -0
  247. package/python/frontend/v3/index.html +15 -0
  248. package/python/frontend/widget_runtime.js +252 -0
  249. package/python/frontend/widgets.js +639 -0
  250. package/python/frontend_src/index.html +14 -0
  251. package/python/frontend_src/package-lock.json +1376 -0
  252. package/python/frontend_src/package.json +19 -0
  253. package/python/frontend_src/src/App.vue +58 -0
  254. package/python/frontend_src/src/api.js +82 -0
  255. package/python/frontend_src/src/components/ChatDock.vue +365 -0
  256. package/python/frontend_src/src/components/ComposerMenu.vue +75 -0
  257. package/python/frontend_src/src/components/DocViewer.vue +162 -0
  258. package/python/frontend_src/src/components/Inspector.vue +235 -0
  259. package/python/frontend_src/src/components/LeftRail.vue +415 -0
  260. package/python/frontend_src/src/components/MenuPopover.vue +128 -0
  261. package/python/frontend_src/src/components/MessageStream.vue +389 -0
  262. package/python/frontend_src/src/components/ModelPicker.vue +350 -0
  263. package/python/frontend_src/src/components/QuickIngest.vue +112 -0
  264. package/python/frontend_src/src/components/Stage.vue +272 -0
  265. package/python/frontend_src/src/components/ToolMenu.vue +141 -0
  266. package/python/frontend_src/src/components/TopBar.vue +118 -0
  267. package/python/frontend_src/src/components/panels/ActivityPanel.vue +82 -0
  268. package/python/frontend_src/src/components/panels/AgentsPanel.vue +83 -0
  269. package/python/frontend_src/src/components/panels/KnowledgePanel.vue +425 -0
  270. package/python/frontend_src/src/components/panels/MemoryPanel.vue +117 -0
  271. package/python/frontend_src/src/components/panels/PanelBox.vue +50 -0
  272. package/python/frontend_src/src/components/panels/ReviewPanel.vue +292 -0
  273. package/python/frontend_src/src/components/panels/SettingsPanel.vue +358 -0
  274. package/python/frontend_src/src/components/panels/TasksPanel.vue +73 -0
  275. package/python/frontend_src/src/components/panels/ToolsPanel.vue +746 -0
  276. package/python/frontend_src/src/components/panels/UsagePanel.vue +105 -0
  277. package/python/frontend_src/src/lib/fmt.js +44 -0
  278. package/python/frontend_src/src/lib/i18n.js +53 -0
  279. package/python/frontend_src/src/lib/locales/en.js +173 -0
  280. package/python/frontend_src/src/lib/locales/zh.js +174 -0
  281. package/python/frontend_src/src/lib/md.js +190 -0
  282. package/python/frontend_src/src/main.js +9 -0
  283. package/python/frontend_src/src/stores/app.js +91 -0
  284. package/python/frontend_src/src/stores/chat.js +450 -0
  285. package/python/frontend_src/src/stores/model.js +96 -0
  286. package/python/frontend_src/src/stores/panels.js +289 -0
  287. package/python/frontend_src/src/stores/profile.js +31 -0
  288. package/python/frontend_src/src/stores/system.js +25 -0
  289. package/python/frontend_src/src/styles/base.css +138 -0
  290. package/python/frontend_src/src/styles/panel.css +117 -0
  291. package/python/frontend_src/src/styles/tokens.css +78 -0
  292. package/python/frontend_src/vite.config.js +39 -0
  293. package/python/pyproject.toml +268 -0
  294. package/python/requirements.txt +311 -0
  295. package/python/skills/README.md +123 -0
  296. package/python/skills/execution-contract/SKILL.md +30 -0
  297. package/python/skills/general-assistant/SKILL.md +34 -0
  298. package/python/skills/planner/SKILL.md +33 -0
  299. package/python/skills/schedule-itinerary/SKILL.md +35 -0
  300. package/python/skills/skill-composition/SKILL.md +31 -0
  301. package/python/skills/skill-guard/SKILL.md +67 -0
  302. package/python/skills/skill-memory/SKILL.md +50 -0
  303. package/python/skills/skill-router/SKILL.md +35 -0
  304. package/python/tests/conftest.py +54 -0
  305. package/python/tests/run_all.py +200 -0
  306. package/python/tests/test_agent_lifecycle.py +326 -0
  307. package/python/tests/test_ahs_p2.py +393 -0
  308. package/python/tests/test_anthropic_tools.py +192 -0
  309. package/python/tests/test_api.py +97 -0
  310. package/python/tests/test_api_auth.py +79 -0
  311. package/python/tests/test_api_host_guard.py +69 -0
  312. package/python/tests/test_attachments.py +151 -0
  313. package/python/tests/test_audit_chain.py +116 -0
  314. package/python/tests/test_audit_sink.py +130 -0
  315. package/python/tests/test_browser.py +149 -0
  316. package/python/tests/test_browser_request_guard.py +180 -0
  317. package/python/tests/test_capabilities.py +152 -0
  318. package/python/tests/test_channel_signing.py +185 -0
  319. package/python/tests/test_channel_trust.py +109 -0
  320. package/python/tests/test_channels.py +174 -0
  321. package/python/tests/test_cli.py +46 -0
  322. package/python/tests/test_compaction_toolpair.py +119 -0
  323. package/python/tests/test_config_layering.py +61 -0
  324. package/python/tests/test_confirm_nonce.py +186 -0
  325. package/python/tests/test_context_compaction_wiring.py +124 -0
  326. package/python/tests/test_dispatch.py +89 -0
  327. package/python/tests/test_domain_evals.py +334 -0
  328. package/python/tests/test_domain_import.py +72 -0
  329. package/python/tests/test_domain_reasoners.py +134 -0
  330. package/python/tests/test_e2e.py +161 -0
  331. package/python/tests/test_emb_cache.py +97 -0
  332. package/python/tests/test_embedding_singleton.py +87 -0
  333. package/python/tests/test_envfile.py +83 -0
  334. package/python/tests/test_evals_smoke.py +90 -0
  335. package/python/tests/test_event_spine.py +174 -0
  336. package/python/tests/test_evidence_semantic.py +88 -0
  337. package/python/tests/test_evidence_sse.py +94 -0
  338. package/python/tests/test_file_ingest.py +135 -0
  339. package/python/tests/test_finance.py +144 -0
  340. package/python/tests/test_finance_ledger.py +245 -0
  341. package/python/tests/test_finance_persist.py +174 -0
  342. package/python/tests/test_gateway.py +125 -0
  343. package/python/tests/test_governance.py +421 -0
  344. package/python/tests/test_governance_audit.py +324 -0
  345. package/python/tests/test_governance_middleware.py +137 -0
  346. package/python/tests/test_hkc.py +268 -0
  347. package/python/tests/test_hkc_index_build_manager.py +306 -0
  348. package/python/tests/test_hkc_manifest_reuse.py +294 -0
  349. package/python/tests/test_hkc_search_event_sync.py +482 -0
  350. package/python/tests/test_import_path_guard.py +155 -0
  351. package/python/tests/test_injection_guard.py +193 -0
  352. package/python/tests/test_integration.py +117 -0
  353. package/python/tests/test_itinerary.py +100 -0
  354. package/python/tests/test_kee_semantic.py +84 -0
  355. package/python/tests/test_kernel.py +212 -0
  356. package/python/tests/test_learning.py +101 -0
  357. package/python/tests/test_llm_admin.py +145 -0
  358. package/python/tests/test_llm_planner.py +344 -0
  359. package/python/tests/test_markdown_skills.py +62 -0
  360. package/python/tests/test_markdown_skills_openclaw.py +66 -0
  361. package/python/tests/test_mcp_connectors.py +97 -0
  362. package/python/tests/test_mcp_guardian_discovery.py +87 -0
  363. package/python/tests/test_mcp_no_memory.py +43 -0
  364. package/python/tests/test_mcp_policy_gate.py +76 -0
  365. package/python/tests/test_mcp_server.py +92 -0
  366. package/python/tests/test_memory_recall.py +92 -0
  367. package/python/tests/test_metrics.py +58 -0
  368. package/python/tests/test_multi_chain.py +90 -0
  369. package/python/tests/test_multimodal.py +122 -0
  370. package/python/tests/test_negotiation.py +136 -0
  371. package/python/tests/test_orchestration.py +109 -0
  372. package/python/tests/test_orchestration_decoupled.py +103 -0
  373. package/python/tests/test_p3_p5_hardening.py +324 -0
  374. package/python/tests/test_parallel_dispatch.py +207 -0
  375. package/python/tests/test_pipeline.py +492 -0
  376. package/python/tests/test_plan_visible.py +86 -0
  377. package/python/tests/test_planner.py +88 -0
  378. package/python/tests/test_policy_gate.py +108 -0
  379. package/python/tests/test_profile.py +67 -0
  380. package/python/tests/test_readme_claims.py +163 -0
  381. package/python/tests/test_reasoner.py +170 -0
  382. package/python/tests/test_release_check.py +252 -0
  383. package/python/tests/test_resume_checkpoint.py +148 -0
  384. package/python/tests/test_routing.py +85 -0
  385. package/python/tests/test_scheduler.py +138 -0
  386. package/python/tests/test_search.py +194 -0
  387. package/python/tests/test_secrets.py +153 -0
  388. package/python/tests/test_semantic.py +69 -0
  389. package/python/tests/test_sessions.py +90 -0
  390. package/python/tests/test_settings.py +265 -0
  391. package/python/tests/test_shadow_learning.py +290 -0
  392. package/python/tests/test_shared_write.py +200 -0
  393. package/python/tests/test_skill_taint_gate.py +145 -0
  394. package/python/tests/test_skills.py +117 -0
  395. package/python/tests/test_skills_fetch.py +282 -0
  396. package/python/tests/test_stats_and_events.py +162 -0
  397. package/python/tests/test_streaming.py +55 -0
  398. package/python/tests/test_supervisor_pipeline.py +176 -0
  399. package/python/tests/test_supervisor_triage.py +102 -0
  400. package/python/tests/test_taint.py +112 -0
  401. package/python/tests/test_task_stream.py +74 -0
  402. package/python/tests/test_thinking_sse.py +66 -0
  403. package/python/tests/test_thinking_stream.py +76 -0
  404. package/python/tests/test_tool_center.py +113 -0
  405. package/python/tests/test_tool_parallel.py +113 -0
  406. package/python/tests/test_tool_params.py +99 -0
  407. package/python/tests/test_tool_use.py +229 -0
  408. package/python/tests/test_toplevel_concurrency.py +116 -0
  409. package/python/tests/test_tracing.py +256 -0
  410. package/python/tests/test_truth_crystallizer.py +125 -0
  411. package/python/tests/test_truth_flow.py +88 -0
  412. package/python/tests/test_update_check.py +95 -0
  413. package/python/tests/test_url_policy.py +53 -0
  414. package/python/tests/test_verify_evidence.py +212 -0
  415. package/python/tests/test_version_sync.py +100 -0
  416. package/python/tests/test_web_trigger.py +82 -0
  417. package/python/tools/check_faiss_type.py +30 -0
  418. package/python/tools/check_log.ps1 +38 -0
  419. package/python/tools/ivf_status.py +72 -0
  420. package/python/tools/mypy_baseline.txt +13 -0
  421. package/python/tools/mypy_ratchet.py +143 -0
  422. package/python/tools/pack.py +173 -0
  423. package/python/tools/release_check.py +349 -0
  424. package/python/tools/restart_foxclaw.ps1 +71 -0
  425. package/python/tools/shared_write_audit.py +190 -0
  426. package/python/tools/size_baseline.txt +28 -0
  427. package/python/tools/size_check.py +102 -0
  428. package/python/tools/strip_comments.py +228 -0
  429. package/python/tools/verify_env.bat +2 -0
  430. package/python/tools/verify_env.py +25 -0
  431. package/python/vendor/HMR_LICENSE +37 -0
  432. package/python/vendor/HMR_README.md +65 -0
  433. package/python/vendor/hkc/LICENSE +37 -0
  434. package/python/vendor/hkc/hkc_ace/__init__.py +0 -0
  435. package/python/vendor/hkc/hkc_ace/ace.py +457 -0
  436. package/python/vendor/hkc/hkc_ace/skill_taxonomy.json +465 -0
  437. package/python/vendor/hkc/hkc_api/__init__.py +0 -0
  438. package/python/vendor/hkc/hkc_api/container.py +416 -0
  439. package/python/vendor/hkc/hkc_api/ingest_jobs.py +103 -0
  440. package/python/vendor/hkc/hkc_api/main.py +157 -0
  441. package/python/vendor/hkc/hkc_api/routes/__init__.py +0 -0
  442. package/python/vendor/hkc/hkc_api/routes/ability.py +151 -0
  443. package/python/vendor/hkc/hkc_api/routes/config.py +51 -0
  444. package/python/vendor/hkc/hkc_api/routes/knowledge.py +630 -0
  445. package/python/vendor/hkc/hkc_api/routes/search.py +88 -0
  446. package/python/vendor/hkc/hkc_api/schemas.py +153 -0
  447. package/python/vendor/hkc/hkc_api/synthesis.py +179 -0
  448. package/python/vendor/hkc/hkc_core/__init__.py +0 -0
  449. package/python/vendor/hkc/hkc_core/graph/__init__.py +0 -0
  450. package/python/vendor/hkc/hkc_core/graph/base.py +188 -0
  451. package/python/vendor/hkc/hkc_core/graph/sqlite_store.py +789 -0
  452. package/python/vendor/hkc/hkc_core/models/__init__.py +0 -0
  453. package/python/vendor/hkc/hkc_core/models/enums.py +65 -0
  454. package/python/vendor/hkc/hkc_core/models/ku.py +307 -0
  455. package/python/vendor/hkc/hkc_core/utils/__init__.py +0 -0
  456. package/python/vendor/hkc/hkc_core/utils/id_gen.py +113 -0
  457. package/python/vendor/hkc/hkc_crystallizer/__init__.py +44 -0
  458. package/python/vendor/hkc/hkc_crystallizer/adapters.py +94 -0
  459. package/python/vendor/hkc/hkc_crystallizer/candidate.py +145 -0
  460. package/python/vendor/hkc/hkc_crystallizer/crystallizer.py +179 -0
  461. package/python/vendor/hkc/hkc_crystallizer/ingress.py +90 -0
  462. package/python/vendor/hkc/hkc_kde/__init__.py +0 -0
  463. package/python/vendor/hkc/hkc_kde/chunker.py +197 -0
  464. package/python/vendor/hkc/hkc_kde/extractor.py +623 -0
  465. package/python/vendor/hkc/hkc_kde/kde.py +298 -0
  466. package/python/vendor/hkc/hkc_kde/loaders/__init__.py +0 -0
  467. package/python/vendor/hkc/hkc_kde/loaders/ebook_loader.py +153 -0
  468. package/python/vendor/hkc/hkc_kde/loaders/office_loader.py +194 -0
  469. package/python/vendor/hkc/hkc_kde/loaders/pdf_loader.py +162 -0
  470. package/python/vendor/hkc/hkc_kde/loaders/text_loader.py +157 -0
  471. package/python/vendor/hkc/hkc_kde/loaders/web_loader.py +91 -0
  472. package/python/vendor/hkc/hkc_kde/models.py +74 -0
  473. package/python/vendor/hkc/hkc_kde/packager.py +329 -0
  474. package/python/vendor/hkc/hkc_kde/relation_disc.py +151 -0
  475. package/python/vendor/hkc/hkc_kee/__init__.py +0 -0
  476. package/python/vendor/hkc/hkc_kee/dedup.py +227 -0
  477. package/python/vendor/hkc/hkc_kee/fingerprint.py +106 -0
  478. package/python/vendor/hkc/hkc_kee/kee.py +541 -0
  479. package/python/vendor/hkc/hkc_kep/__init__.py +0 -0
  480. package/python/vendor/hkc/hkc_kep/event_bus.py +205 -0
  481. package/python/vendor/hkc/hkc_sdk/__init__.py +63 -0
  482. package/python/vendor/hkc/hkc_sdk/base.py +151 -0
  483. package/python/vendor/hkc/hkc_sdk/direct_client.py +153 -0
  484. package/python/vendor/hkc/hkc_sdk/exceptions.py +39 -0
  485. package/python/vendor/hkc/hkc_sdk/http_client.py +166 -0
  486. package/python/vendor/hkc/hkc_sdk/models.py +171 -0
  487. package/python/vendor/hkc/hkc_search/__init__.py +0 -0
  488. package/python/vendor/hkc/hkc_search/bm25.py +325 -0
  489. package/python/vendor/hkc/hkc_search/embedding_backends.py +374 -0
  490. package/python/vendor/hkc/hkc_search/graph_search.py +132 -0
  491. package/python/vendor/hkc/hkc_search/hybrid.py +331 -0
  492. package/python/vendor/hkc/hkc_search/index_build_manager.py +378 -0
  493. package/python/vendor/hkc/hkc_search/vector_search.py +484 -0
  494. package/python/vendor/hmr/__init__.py +0 -0
  495. package/python/vendor/hmr/core/__init__.py +0 -0
  496. package/python/vendor/hmr/core/hmr.py +684 -0
  497. package/python/vendor/hmr/core/models.py +310 -0
  498. package/python/vendor/hmr/engines/__init__.py +0 -0
  499. package/python/vendor/hmr/engines/evolution.py +710 -0
  500. package/python/vendor/hmr/engines/jit_compiler.py +472 -0
  501. package/python/vendor/hmr/engines/lifecycle.py +264 -0
  502. package/python/vendor/hmr/engines/policy.py +625 -0
  503. package/python/vendor/hmr/engines/recall.py +260 -0
  504. package/python/vendor/hmr/engines/runtime_state.py +158 -0
  505. package/python/vendor/hmr/engines/scheduler.py +323 -0
  506. package/python/vendor/hmr/engines/semantic.py +150 -0
  507. package/python/vendor/hmr/engines/temporal.py +261 -0
  508. package/python/vendor/hmr/engines/thought_chain.py +635 -0
  509. package/python/vendor/hmr/graph/__init__.py +0 -0
  510. package/python/vendor/hmr/graph/cwg.py +338 -0
  511. package/python/vendor/hmr/graph/memory_graph.py +530 -0
  512. package/python/vendor/hmr/storage/__init__.py +0 -0
  513. package/python/vendor/hmr/storage/memory_fs.py +300 -0
  514. package/python/vendor/hmr/storage/vector_store.py +520 -0
@@ -0,0 +1,166 @@
1
+ """
2
+ hkc_sdk / http_client.py
3
+ HTTP 客户端:通过 REST 调用 hkc-api。
4
+
5
+ 用于 HKC 作为独立服务部署、调用方在另一进程/机器的场景。
6
+ """
7
+ from __future__ import annotations
8
+ import logging
9
+
10
+ from .base import BaseClient
11
+ from .models import (
12
+ KU, SearchHit, Ability, CoverageReport, Conflict, IngestResult,
13
+ )
14
+ from .exceptions import (
15
+ HKCNotFoundError, HKCInsufficientCoverage,
16
+ HKCBadRequest, HKCServerError,
17
+ )
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class HTTPClient(BaseClient):
23
+
24
+ def __init__(self, base_url: str = "http://localhost:8000", timeout: int = 60):
25
+ self._base_url = base_url.rstrip("/")
26
+ self._timeout = timeout
27
+
28
+ # ── 内部请求封装 ─────────────────────────────────────────
29
+
30
+ def _request(self, method: str, path: str, **kwargs):
31
+ try:
32
+ import requests
33
+ except ImportError:
34
+ raise ImportError("requests 未安装: pip install requests")
35
+
36
+ url = f"{self._base_url}{path}"
37
+ try:
38
+ resp = requests.request(
39
+ method, url, timeout=self._timeout, **kwargs
40
+ )
41
+ except requests.RequestException as e:
42
+ raise HKCServerError(f"连接失败: {e}")
43
+
44
+ return self._handle_response(resp)
45
+
46
+ def _handle_response(self, resp):
47
+ # 解析错误 detail(可能是 dict 或字符串)
48
+ if resp.status_code == 200:
49
+ return resp.json()
50
+
51
+ try:
52
+ detail = resp.json().get("detail")
53
+ except Exception:
54
+ detail = resp.text
55
+
56
+ if resp.status_code == 404:
57
+ raise HKCNotFoundError(str(detail), detail)
58
+ if resp.status_code == 422:
59
+ msg = detail.get("message") if isinstance(detail, dict) else str(detail)
60
+ raise HKCInsufficientCoverage(msg or "覆盖度不足", detail)
61
+ if resp.status_code in (400, 413):
62
+ raise HKCBadRequest(str(detail), detail)
63
+ raise HKCServerError(f"HTTP {resp.status_code}: {detail}", detail)
64
+
65
+ # ── 知识摄入 ─────────────────────────────────────────────
66
+
67
+ def ingest_text(self, text, source_title="", domain="",
68
+ source="inline", source_year=0) -> IngestResult:
69
+ data = self._request("POST", "/knowledge/ingest/text", json={
70
+ "text": text, "source": source, "source_title": source_title,
71
+ "source_year": source_year, "domain": domain,
72
+ })
73
+ return IngestResult.from_dict(data)
74
+
75
+ def ingest_url(self, url, source_title="", domain="", source_year=0) -> IngestResult:
76
+ data = self._request("POST", "/knowledge/ingest/url", json={
77
+ "url": url, "source_title": source_title,
78
+ "source_year": source_year, "domain": domain,
79
+ })
80
+ return IngestResult.from_dict(data)
81
+
82
+ # ── KU 查询 ──────────────────────────────────────────────
83
+
84
+ def get_ku(self, ku_id) -> KU:
85
+ data = self._request("GET", f"/knowledge/ku/{ku_id}")
86
+ return KU.from_dict(data)
87
+
88
+ def list_by_domain(self, domain, limit=50) -> list[KU]:
89
+ data = self._request("GET", f"/knowledge/domain/{domain}",
90
+ params={"limit": limit})
91
+ return [KU.from_dict(k) for k in data.get("kus", [])]
92
+
93
+ def neighbors(self, ku_id, max_depth=2, top_k=20) -> list[SearchHit]:
94
+ data = self._request("GET", f"/knowledge/ku/{ku_id}/neighbors",
95
+ params={"max_depth": max_depth, "top_k": top_k})
96
+ hits = []
97
+ for h in data.get("neighbors", []):
98
+ h.setdefault("mode", "graph") # 与 DirectClient 一致
99
+ hits.append(SearchHit.from_dict(h))
100
+ return hits
101
+
102
+ # ── 搜索 ─────────────────────────────────────────────────
103
+
104
+ def search(self, query, mode="hybrid", top_k=10, domain="",
105
+ ku_types=None) -> list[SearchHit]:
106
+ data = self._request("POST", "/search", json={
107
+ "query": query, "mode": mode, "top_k": top_k,
108
+ "domain": domain, "ku_types": ku_types,
109
+ })
110
+ return [SearchHit.from_dict(h) for h in data.get("hits", [])]
111
+
112
+ def find_path(self, from_id, to_id) -> list[str]:
113
+ data = self._request("GET", "/search/path",
114
+ params={"from_id": from_id, "to_id": to_id})
115
+ return data.get("path", [])
116
+
117
+ # ── 能力 ─────────────────────────────────────────────────
118
+
119
+ def list_abilities(self) -> list[str]:
120
+ data = self._request("GET", "/abilities")
121
+ return data.get("abilities", [])
122
+
123
+ def coverage_report(self, ability_key) -> CoverageReport:
124
+ data = self._request("GET", f"/abilities/{ability_key}/coverage")
125
+ return CoverageReport.from_dict(data)
126
+
127
+ def compile_ability(self, ability_key) -> Ability:
128
+ data = self._request("POST", f"/abilities/{ability_key}/compile")
129
+ return Ability.from_dict(data)
130
+
131
+ def get_ability(self, ability_key) -> Ability:
132
+ data = self._request("GET", f"/abilities/{ability_key}")
133
+ return Ability.from_dict(data)
134
+
135
+ # ── 冲突 ─────────────────────────────────────────────────
136
+
137
+ def list_conflicts(self, status="open", domain="") -> list[Conflict]:
138
+ data = self._request("GET", "/conflicts",
139
+ params={"status": status, "domain": domain})
140
+ return [Conflict.from_dict(c) for c in data.get("conflicts", [])]
141
+
142
+ def resolve_conflict(self, conflict_id, winner_id, note="",
143
+ resolved_by="sdk") -> bool:
144
+ # 裁决失败(冲突不存在/已解决/winner 无效)API 返回 400,
145
+ # SDK 统一为返回 False(与 DirectClient 行为一致),而非抛异常。
146
+ from .exceptions import HKCBadRequest
147
+ try:
148
+ data = self._request("POST", f"/conflicts/{conflict_id}/resolve", json={
149
+ "winner_id": winner_id, "note": note, "resolved_by": resolved_by,
150
+ })
151
+ return data.get("resolved", False)
152
+ except HKCBadRequest:
153
+ return False
154
+
155
+ # ── 系统 ─────────────────────────────────────────────────
156
+
157
+ def stats(self) -> dict:
158
+ return self._request("GET", "/stats")
159
+
160
+ def health(self) -> bool:
161
+ from .exceptions import HKCError
162
+ try:
163
+ self._request("GET", "/health")
164
+ return True
165
+ except HKCError:
166
+ return False
@@ -0,0 +1,171 @@
1
+ """
2
+ hkc_sdk / models.py
3
+ SDK 对外数据模型。
4
+
5
+ 这是给 SDK 用户的"门面"类型,刻意与内部 KU dataclass 解耦:
6
+ - 内部 KU 字段多、有枚举、随版本演进
7
+ - SDK 模型字段少而稳定,用户代码不会因内部重构而崩
8
+
9
+ 所有模型都能从 dict(HTTP JSON / 直连 to_dict)构造,用 from_dict。
10
+ """
11
+ from __future__ import annotations
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+
16
+ @dataclass
17
+ class KU:
18
+ """知识单元的对外视图。"""
19
+ ku_id: str
20
+ ku_type: str
21
+ name: str
22
+ summary: str = ""
23
+ domain: str = ""
24
+ confidence: float = 1.0
25
+ status: str = "active"
26
+ tags: list[str] = field(default_factory=list)
27
+ extra: dict[str, Any] = field(default_factory=dict)
28
+
29
+ @classmethod
30
+ def from_dict(cls, d: dict) -> "KU":
31
+ return cls(
32
+ ku_id = d["ku_id"],
33
+ ku_type = d["ku_type"],
34
+ name = d["name"],
35
+ summary = d.get("summary", ""),
36
+ domain = d.get("domain", ""),
37
+ confidence = d.get("confidence", 1.0),
38
+ status = d.get("status", "active"),
39
+ tags = d.get("tags", []),
40
+ extra = d.get("extra", {}),
41
+ )
42
+
43
+ @property
44
+ def statement(self) -> str:
45
+ """Claim / Fact 的陈述内容(如果有)。"""
46
+ return self.extra.get("statement", "")
47
+
48
+
49
+ @dataclass
50
+ class SearchHit:
51
+ ku_id: str
52
+ score: float
53
+ name: str
54
+ summary: str = ""
55
+ mode: str = ""
56
+ ku_type: str = ""
57
+
58
+ @classmethod
59
+ def from_dict(cls, d: dict) -> "SearchHit":
60
+ return cls(
61
+ ku_id = d["ku_id"],
62
+ score = d.get("score", 0.0),
63
+ name = d.get("name", ""),
64
+ summary = d.get("summary", ""),
65
+ mode = d.get("mode", ""),
66
+ ku_type = d.get("ku_type", ""),
67
+ )
68
+
69
+
70
+ @dataclass
71
+ class Skill:
72
+ skill_key: str
73
+ display_name: str
74
+ coverage: float = 0.0
75
+ concept_hits: list[str] = field(default_factory=list)
76
+
77
+ @classmethod
78
+ def from_dict(cls, d: dict) -> "Skill":
79
+ return cls(
80
+ skill_key = d.get("skill_key", ""),
81
+ display_name = d.get("display_name", ""),
82
+ coverage = d.get("coverage", 0.0),
83
+ concept_hits = d.get("concept_hits", []),
84
+ )
85
+
86
+
87
+ @dataclass
88
+ class Ability:
89
+ ability_key: str
90
+ display_name: str
91
+ domain: str
92
+ coverage: dict[str, float] = field(default_factory=dict)
93
+ skills: list[Skill] = field(default_factory=list)
94
+ workflows: list[dict] = field(default_factory=list)
95
+ version: str = "1.0.0"
96
+
97
+ @classmethod
98
+ def from_dict(cls, d: dict) -> "Ability":
99
+ return cls(
100
+ ability_key = d["ability_key"],
101
+ display_name = d.get("display_name", ""),
102
+ domain = d.get("domain", ""),
103
+ coverage = d.get("coverage", {}),
104
+ skills = [Skill.from_dict(s) for s in d.get("skills", [])],
105
+ workflows = d.get("workflows", []),
106
+ version = d.get("version", "1.0.0"),
107
+ )
108
+
109
+ def skill_context(self, skill_key: str) -> Skill | None:
110
+ """获取某个 Skill 的上下文,Agent 用。"""
111
+ for s in self.skills:
112
+ if s.skill_key == skill_key:
113
+ return s
114
+ return None
115
+
116
+
117
+ @dataclass
118
+ class CoverageReport:
119
+ ability_key: str
120
+ can_compile: bool
121
+ coverage: dict[str, float] = field(default_factory=dict)
122
+ missing_skills: list[str] = field(default_factory=list)
123
+ ku_count: int = 0
124
+
125
+ @classmethod
126
+ def from_dict(cls, d: dict) -> "CoverageReport":
127
+ return cls(
128
+ ability_key = d["ability_key"],
129
+ can_compile = d.get("can_compile", False),
130
+ coverage = d.get("coverage", {}),
131
+ missing_skills = d.get("missing_skills", []),
132
+ ku_count = d.get("ku_count", 0),
133
+ )
134
+
135
+
136
+ @dataclass
137
+ class Conflict:
138
+ conflict_id: str
139
+ claim_a_id: str
140
+ claim_b_id: str
141
+ domain: str = ""
142
+ status: str = "open"
143
+ resolution_strategy: str = ""
144
+ resolution_note: str = ""
145
+
146
+ @classmethod
147
+ def from_dict(cls, d: dict) -> "Conflict":
148
+ return cls(
149
+ conflict_id = d["conflict_id"],
150
+ claim_a_id = d["claim_a_id"],
151
+ claim_b_id = d["claim_b_id"],
152
+ domain = d.get("domain", ""),
153
+ status = d.get("status", "open"),
154
+ resolution_strategy = d.get("resolution_strategy", ""),
155
+ resolution_note = d.get("resolution_note", ""),
156
+ )
157
+
158
+
159
+ @dataclass
160
+ class IngestResult:
161
+ ku_count: int
162
+ ku_ids: list[str] = field(default_factory=list)
163
+ counts: dict[str, int] = field(default_factory=dict)
164
+
165
+ @classmethod
166
+ def from_dict(cls, d: dict) -> "IngestResult":
167
+ return cls(
168
+ ku_count = d.get("ku_count", 0),
169
+ ku_ids = d.get("ku_ids", []),
170
+ counts = d.get("counts", {}),
171
+ )
File without changes
@@ -0,0 +1,325 @@
1
+ """
2
+ hkc-search / bm25.py
3
+ 关键词检索(Cold 层),自实现 BM25Okapi 倒排索引。
4
+
5
+ 阶段 B 改造(10万 KU 规模):从 rank-bm25 切换到自实现。
6
+ - 倒排索引:term -> {doc_id: tf} + df 字典
7
+ - append_ku / append_batch 真正 O(terms) 增量,无全量重建
8
+ - save / load 用 pickle,启动可免 tokenize
9
+ - 公式与 rank_bm25.BM25Okapi 完全一致(k1=1.5, b=0.75,
10
+ IDF = log((N - df + 0.5) / (df + 0.5) + 1))
11
+ """
12
+ from __future__ import annotations
13
+ import logging
14
+ import math
15
+ import os
16
+ import pickle
17
+ import re
18
+ from collections import defaultdict
19
+ from dataclasses import dataclass
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ @dataclass
25
+ class BM25Result:
26
+ ku_id: str
27
+ score: float
28
+ name: str
29
+ summary: str
30
+
31
+
32
+ # 简单分词(沿用现状)
33
+ _TOKEN_RE_NONWORD = re.compile(r'[^\w\s\u4e00-\u9fff]', re.UNICODE)
34
+ _TOKEN_RE_LATIN = re.compile(r'^[a-z0-9_-]+$')
35
+
36
+
37
+ def _tokenize(text: str) -> list[str]:
38
+ """英文按空格切+小写+去标点;中文按字切(unigram + bigram)。"""
39
+ text = text.lower()
40
+ text = _TOKEN_RE_NONWORD.sub(' ', text)
41
+ tokens: list[str] = []
42
+ for word in text.split():
43
+ if _TOKEN_RE_LATIN.match(word):
44
+ if len(word) >= 2:
45
+ tokens.append(word)
46
+ else:
47
+ chars = [c for c in word if '\u4e00' <= c <= '\u9fff']
48
+ tokens.extend(chars)
49
+ for i in range(len(chars) - 1):
50
+ tokens.append(chars[i] + chars[i + 1])
51
+ return tokens
52
+
53
+
54
+ class BM25Index:
55
+ """
56
+ 自实现 BM25Okapi 倒排索引。
57
+
58
+ 数据结构:
59
+ _doc_ids: list[str] 文档 id 列表(插入顺序)
60
+ _doc_lens: list[int] 每篇 doc 的 token 数
61
+ _doc_idx: dict[str, int] doc_id → _doc_ids 里的 idx
62
+ _meta: dict[str, tuple[str, str]] doc_id → (name, summary)
63
+ _N: int 总 doc 数
64
+ _avgdl: float 平均 doc 长度(在线更新)
65
+ _df: dict[str, int] term → 含该 term 的 doc 数
66
+ _tf: dict[str, dict[str, int]] term → {doc_id: term freq}
67
+ _k1, _b: float BM25Okapi 超参
68
+
69
+ 时间复杂度:
70
+ - append_ku: O(terms in ku)
71
+ - append_batch: O(total terms in batch)
72
+ - remove_ku: O(distinct terms in doc)
73
+ - search: O(|query| * avg postings)
74
+ - build: O(total tokens) 一次性
75
+
76
+ 公式(BM25Okapi,与 rank_bm25 一致):
77
+ IDF(t) = log((N - df + 0.5) / (df + 0.5) + 1)
78
+ tf_norm(t,d) = (tf * (k1+1)) / (tf + k1 * (1 - b + b * |d| / avgdl))
79
+ score(t,d) = IDF(t) * tf_norm(t,d)
80
+ """
81
+
82
+ def __init__(self, k1: float = 1.5, b: float = 0.75, epsilon: float = 0.25):
83
+ self._k1 = k1
84
+ self._b = b
85
+ # ATIRE BM25 变体:对 negative IDF 做 floor,避免高频词得分为负
86
+ # rank_bm25.BM25Okapi 默认 epsilon=0.25, floor = eps * average_idf
87
+ # 为与 rank_bm25 完全一致,保留这个 floor
88
+ self._epsilon = epsilon
89
+ self._reset_state()
90
+
91
+ def _reset_state(self) -> None:
92
+ self._doc_ids: list[str] = []
93
+ self._doc_lens: list[int] = []
94
+ self._doc_idx: dict[str, int] = {}
95
+ self._meta: dict[str, tuple[str, str]] = {}
96
+ self._N: int = 0
97
+ self._avgdl: float = 0.0
98
+ self._df: dict[str, int] = defaultdict(int)
99
+ self._tf: dict[str, dict[str, int]] = defaultdict(dict)
100
+ # ATIRE floor:维护 idf_sum 用于 average_idf(floor = eps * average_idf)
101
+ # 与 rank_bm25._calc_idf 完全一致
102
+ self._idf_sum: float = 0.0
103
+
104
+ # ── 公共接口 ───────────────────────────────────────────
105
+
106
+ def build(self, kus) -> None:
107
+ """全量构建。kus 为空时清空索引。"""
108
+ self._reset_state()
109
+ self.append_batch(kus)
110
+ logger.info("BM25 索引构建完成,共 %d 条", self._N)
111
+
112
+ def append_ku(self, ku) -> None:
113
+ """单条增量。O(terms in ku)。"""
114
+ self._add_doc(ku)
115
+
116
+ def append_batch(self, kus) -> None:
117
+ """批量增量(冷构建期调)。O(total terms in batch),比旧版 'append + 全量重建' 快 100x+。"""
118
+ if not kus:
119
+ return
120
+ for ku in kus:
121
+ self._add_doc(ku)
122
+
123
+ def remove_ku(self, ku_id: str) -> bool:
124
+ """单条删除。O(distinct terms in doc)。不存在返 False。"""
125
+ if ku_id not in self._doc_idx:
126
+ return False
127
+
128
+ # 从 _tf 反查该 doc 涉及的所有 term
129
+ terms_touched: list[str] = []
130
+ for term, postings in self._tf.items():
131
+ if ku_id in postings:
132
+ del postings[ku_id]
133
+ terms_touched.append(term)
134
+
135
+ # 清理空 postings + 同步更新 df / idf_sum
136
+ for term in terms_touched:
137
+ if not self._tf[term]:
138
+ # postings 全空,term 从 _df 移除
139
+ old_df = self._df[term]
140
+ old_idf = self._compute_idf_raw(self._N, old_df)
141
+ self._idf_sum -= old_idf
142
+ del self._df[term]
143
+ del self._tf[term]
144
+ else:
145
+ # postings 还有内容,df 减 1(old_df >= 2,因 _tf[term] 不空)
146
+ old_df = self._df[term]
147
+ new_df = old_df - 1
148
+ old_idf = self._compute_idf_raw(self._N, old_df)
149
+ new_idf = self._compute_idf_raw(self._N, new_df)
150
+ self._idf_sum += (new_idf - old_idf)
151
+ self._df[term] = new_df
152
+
153
+ # 移除 doc 本身
154
+ idx = self._doc_idx.pop(ku_id)
155
+ del self._doc_ids[idx]
156
+ del self._doc_lens[idx]
157
+ del self._meta[ku_id]
158
+
159
+ # idx 之后的 _doc_idx 都要 -1
160
+ for i in range(idx, len(self._doc_ids)):
161
+ self._doc_idx[self._doc_ids[i]] = i
162
+
163
+ # 更新 N, avgdl
164
+ self._N -= 1
165
+ if self._N > 0:
166
+ self._avgdl = sum(self._doc_lens) / self._N
167
+ else:
168
+ self._avgdl = 0.0
169
+
170
+ return True
171
+
172
+ def search(self, query: str, top_k: int = 10) -> list[BM25Result]:
173
+ if not self._N:
174
+ return []
175
+ query_tokens = _tokenize(query)
176
+ if not query_tokens:
177
+ return []
178
+ # 不去重:与 rank_bm25 行为一致(query 重复 term 累加 IDF*tf_norm)
179
+
180
+ scores: dict[str, float] = defaultdict(float)
181
+ for term in query_tokens:
182
+ if term not in self._df:
183
+ continue
184
+ idf = self._idf(term)
185
+ for doc_id, tf in self._tf[term].items():
186
+ doc_idx = self._doc_idx[doc_id]
187
+ doc_len = self._doc_lens[doc_idx]
188
+ scores[doc_id] += idf * self._tf_norm(tf, doc_len)
189
+
190
+ sorted_docs = sorted(scores.items(), key=lambda x: x[1], reverse=True)[:top_k]
191
+ results: list[BM25Result] = []
192
+ for doc_id, score in sorted_docs:
193
+ if score <= 0:
194
+ continue
195
+ name, summary = self._meta[doc_id]
196
+ results.append(BM25Result(
197
+ ku_id=doc_id, score=float(score), name=name, summary=summary,
198
+ ))
199
+ return results
200
+
201
+ def size(self) -> int:
202
+ return self._N
203
+
204
+ def clear(self) -> None:
205
+ """清空索引(替换旧版直接改 _ku_ids 等私有状态)。"""
206
+ self._reset_state()
207
+
208
+ def save(self, path: str) -> None:
209
+ """pickle 落盘(启动可 load 避免 10万 KU 重复 tokenize)。
210
+ 落盘时机留给调用方决定(vector flush 钩子 / 独立 fsync 线程)。"""
211
+ data = {
212
+ 'k1': self._k1,
213
+ 'b': self._b,
214
+ 'doc_ids': self._doc_ids,
215
+ 'doc_lens': self._doc_lens,
216
+ 'doc_idx': self._doc_idx,
217
+ 'meta': self._meta,
218
+ 'N': self._N,
219
+ 'avgdl': self._avgdl,
220
+ 'df': dict(self._df),
221
+ 'tf': {term: dict(postings) for term, postings in self._tf.items()},
222
+ }
223
+ os.makedirs(os.path.dirname(path) or '.', exist_ok=True)
224
+ tmp = path + '.tmp'
225
+ with open(tmp, 'wb') as f:
226
+ pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL)
227
+ os.replace(tmp, path)
228
+
229
+ def load(self, path: str) -> bool:
230
+ """从 pickle 加载。文件不存在或 schema 不匹配返 False。"""
231
+ if not os.path.exists(path):
232
+ return False
233
+ try:
234
+ with open(path, 'rb') as f:
235
+ data = pickle.load(f)
236
+ except Exception as e:
237
+ logger.warning("BM25 索引加载失败,fallback 到空索引: %s", e)
238
+ self._reset_state()
239
+ return False
240
+
241
+ required = {'k1', 'b', 'doc_ids', 'doc_lens', 'doc_idx',
242
+ 'meta', 'N', 'avgdl', 'df', 'tf'}
243
+ if not required.issubset(data.keys()):
244
+ logger.warning("BM25 索引 schema 不匹配,fallback 到空索引")
245
+ self._reset_state()
246
+ return False
247
+
248
+ self._k1 = data['k1']
249
+ self._b = data['b']
250
+ self._doc_ids = data['doc_ids']
251
+ self._doc_lens = data['doc_lens']
252
+ self._doc_idx = data['doc_idx']
253
+ self._meta = data['meta']
254
+ self._N = data['N']
255
+ self._avgdl = data['avgdl']
256
+ self._df = defaultdict(int, data['df'])
257
+ self._tf = defaultdict(dict, {term: dict(postings) for term, postings in data['tf'].items()})
258
+ return True
259
+
260
+ # ── 内部方法 ───────────────────────────────────────────
261
+
262
+ @staticmethod
263
+ def _compute_idf_raw(N: int, df: int) -> float:
264
+ """BM25Okapi 原始 idf(rank_bm25._calc_idf 一致)。
265
+ 允许负值(当 df > N 时,numerator <= 0 → 负 idf,后续 ATIRE floor 兜底)。
266
+ """
267
+ if df == 0:
268
+ return 0.0
269
+ num = N - df + 0.5
270
+ den = df + 0.5
271
+ if num <= 0:
272
+ # log(负) 不存在,但数学上 idf = -log(|num|) + log(den) = -(log(|num|) - log(den))
273
+ return -(math.log(-num) - math.log(den))
274
+ return math.log(num) - math.log(den)
275
+
276
+ def _add_doc(self, ku) -> None:
277
+ text = f"{ku.name} {ku.summary} {' '.join(ku.tags)}"
278
+ tokens = _tokenize(text)
279
+ ku_id = ku.ku_id
280
+ doc_len = len(tokens)
281
+
282
+ self._doc_ids.append(ku_id)
283
+ self._doc_lens.append(doc_len)
284
+ self._doc_idx[ku_id] = self._N
285
+ self._meta[ku_id] = (ku.name, ku.summary[:100])
286
+
287
+ if doc_len > 0:
288
+ term_counts: dict[str, int] = defaultdict(int)
289
+ for t in tokens:
290
+ term_counts[t] += 1
291
+ for term, count in term_counts.items():
292
+ if term not in self._tf:
293
+ self._tf[term] = {}
294
+ self._tf[term][ku_id] = count
295
+ # 增量更新 _idf_sum:N 不变,只 df 变
296
+ if self._df[term] == 0:
297
+ # 新 term (df: 0 → 1)
298
+ self._idf_sum += self._compute_idf_raw(self._N, 1)
299
+ else:
300
+ # 旧 term (df: old → old+1)
301
+ old_df = self._df[term]
302
+ old_idf = self._compute_idf_raw(self._N, old_df)
303
+ new_idf = self._compute_idf_raw(self._N, old_df + 1)
304
+ self._idf_sum += (new_idf - old_idf)
305
+ self._df[term] += 1
306
+
307
+ prev_total = self._avgdl * self._N
308
+ self._N += 1
309
+ self._avgdl = (prev_total + doc_len) / self._N
310
+
311
+ def _idf(self, term: str) -> float:
312
+ df = self._df.get(term, 0)
313
+ if df == 0:
314
+ return 0.0
315
+ # BM25Okapi 公式(rank_bm25 风格):log((N - df + 0.5) / (df + 0.5))
316
+ # 注意:无 +1,负 idf 由 ATIRE floor 兜底
317
+ idf = self._compute_idf_raw(self._N, df)
318
+ if idf < 0:
319
+ # ATIRE floor:eps * average_idf
320
+ avg_idf = (self._idf_sum / len(self._df)) if self._df else 0.0
321
+ return self._epsilon * avg_idf
322
+ return idf
323
+
324
+ def _tf_norm(self, tf: int, doc_len: int) -> float:
325
+ return (tf * (self._k1 + 1)) / (tf + self._k1 * (1 - self._b + self._b * doc_len / self._avgdl))