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.
- package/README.md +54 -29
- package/bin/foxclaw.cjs +51 -0
- package/index.js +4 -10
- package/package.json +46 -38
- package/python/.dockerignore +35 -0
- package/python/.env.example +173 -0
- package/python/.gitattributes +46 -0
- package/python/.github/workflows/ci.yml +167 -0
- package/python/.github/workflows/release.yml +183 -0
- package/python/CHANGELOG.md +57 -0
- package/python/CHANGELOG_CN.md +57 -0
- package/python/Dockerfile +64 -0
- package/python/LICENSE +21 -0
- package/python/MANIFEST.in +14 -0
- package/python/README.md +201 -0
- package/python/README_CN.md +336 -0
- package/python/bench/bm25_audit.py +186 -0
- package/python/bench/bm25_regression.py +177 -0
- package/python/bench/bm25_stress.py +155 -0
- package/python/bench/cd_audit.py +215 -0
- package/python/bench/chaos.py +140 -0
- package/python/bench/concurrency.py +103 -0
- package/python/bench/e2e_real_models.py +94 -0
- package/python/bench/llm_retry_test.py +241 -0
- package/python/bench/load_test.py +193 -0
- package/python/bench/vector_ivf_upgrade.py +128 -0
- package/python/docs/CHANNELS.md +195 -0
- package/python/docs/GOVERNANCE.md +164 -0
- package/python/docs/RELEASE.md +110 -0
- package/python/docs/RUN.md +75 -0
- package/python/docs/RUN_CN.md +121 -0
- package/python/docs//351/205/215/347/275/256/346/214/207/345/215/227.md +152 -0
- package/python/evals/__init__.py +0 -0
- package/python/evals/governance/README.md +61 -0
- package/python/evals/governance/__init__.py +0 -0
- package/python/evals/governance/cases.py +115 -0
- package/python/evals/governance/compare_embeddings.py +94 -0
- package/python/evals/governance/convergence.svg +11 -0
- package/python/evals/governance/report.json +371 -0
- package/python/evals/governance/run_evals.py +368 -0
- package/python/examples/governance_middleware_demo.py +72 -0
- package/python/examples/langgraph_governance_demo.py +104 -0
- package/python/examples/sample_itinerary.csv +6 -0
- package/python/examples/sample_knowledge.csv +9 -0
- package/python/examples/sample_transactions.csv +14 -0
- package/python/foxclaw/__init__.py +408 -0
- package/python/foxclaw/agents/__init__.py +12 -0
- package/python/foxclaw/agents/agents.py +35 -0
- package/python/foxclaw/agents/base.py +794 -0
- package/python/foxclaw/agents/impl/__init__.py +1 -0
- package/python/foxclaw/agents/impl/_helpers.py +70 -0
- package/python/foxclaw/agents/impl/finance.py +231 -0
- package/python/foxclaw/agents/impl/office.py +350 -0
- package/python/foxclaw/agents/impl/supervisor.py +592 -0
- package/python/foxclaw/agents/mixins/_context.py +128 -0
- package/python/foxclaw/agents/mixins/augment.py +143 -0
- package/python/foxclaw/agents/mixins/llm.py +67 -0
- package/python/foxclaw/agents/mixins/memory.py +41 -0
- package/python/foxclaw/agents/mixins/preference.py +131 -0
- package/python/foxclaw/agents/mixins/prompt.py +71 -0
- package/python/foxclaw/agents/mixins/skillbox.py +58 -0
- package/python/foxclaw/agents/mixins/tool_exec.py +417 -0
- package/python/foxclaw/api/__init__.py +224 -0
- package/python/foxclaw/api/_state.py +43 -0
- package/python/foxclaw/api/bootstrap.py +96 -0
- package/python/foxclaw/api/middleware.py +294 -0
- package/python/foxclaw/api/routes/ahs.py +404 -0
- package/python/foxclaw/api/routes/attachments.py +116 -0
- package/python/foxclaw/api/routes/browser.py +35 -0
- package/python/foxclaw/api/routes/domain.py +306 -0
- package/python/foxclaw/api/routes/knowledge.py +145 -0
- package/python/foxclaw/api/routes/llm_admin.py +449 -0
- package/python/foxclaw/api/routes/memory.py +105 -0
- package/python/foxclaw/api/routes/orchestration.py +39 -0
- package/python/foxclaw/api/routes/recovery.py +44 -0
- package/python/foxclaw/api/routes/review.py +266 -0
- package/python/foxclaw/api/routes/search.py +33 -0
- package/python/foxclaw/api/routes/system.py +311 -0
- package/python/foxclaw/api/routes/task.py +263 -0
- package/python/foxclaw/api/routes/ws.py +64 -0
- package/python/foxclaw/api/spine.py +52 -0
- package/python/foxclaw/browser/__init__.py +13 -0
- package/python/foxclaw/browser/action/__init__.py +1 -0
- package/python/foxclaw/browser/action/action_executor.py +50 -0
- package/python/foxclaw/browser/action/action_types.py +44 -0
- package/python/foxclaw/browser/action/action_verifier.py +68 -0
- package/python/foxclaw/browser/action/url_policy.py +143 -0
- package/python/foxclaw/browser/adapter/__init__.py +1 -0
- package/python/foxclaw/browser/adapter/base_adapter.py +23 -0
- package/python/foxclaw/browser/adapter/web_adapter.py +46 -0
- package/python/foxclaw/browser/driver/__init__.py +1 -0
- package/python/foxclaw/browser/driver/base_driver.py +61 -0
- package/python/foxclaw/browser/driver/playwright_driver.py +170 -0
- package/python/foxclaw/browser/perception/__init__.py +1 -0
- package/python/foxclaw/browser/perception/dom_extractor.py +42 -0
- package/python/foxclaw/browser/perception/element_indexer.py +56 -0
- package/python/foxclaw/browser/perception/semantic_reducer.py +33 -0
- package/python/foxclaw/browser/perception/snapshot.py +29 -0
- package/python/foxclaw/browser/service.py +144 -0
- package/python/foxclaw/browser/session/__init__.py +1 -0
- package/python/foxclaw/browser/session/session_manager.py +57 -0
- package/python/foxclaw/capability/__init__.py +12 -0
- package/python/foxclaw/capability/embedding_service.py +65 -0
- package/python/foxclaw/channels/__init__.py +138 -0
- package/python/foxclaw/channels/discord.py +175 -0
- package/python/foxclaw/channels/dispatcher.py +179 -0
- package/python/foxclaw/channels/feishu.py +215 -0
- package/python/foxclaw/channels/openclaw_bridge.py +151 -0
- package/python/foxclaw/channels/signing.py +187 -0
- package/python/foxclaw/channels/telegram.py +120 -0
- package/python/foxclaw/channels/weixin.py +215 -0
- package/python/foxclaw/cli.py +183 -0
- package/python/foxclaw/cognitive/__init__.py +4 -0
- package/python/foxclaw/cognitive/reasoner.py +81 -0
- package/python/foxclaw/cognitive/state.py +141 -0
- package/python/foxclaw/core/__init__.py +9 -0
- package/python/foxclaw/core/audit_chain.py +131 -0
- package/python/foxclaw/core/audit_sink.py +100 -0
- package/python/foxclaw/core/compaction.py +265 -0
- package/python/foxclaw/core/config.py +65 -0
- package/python/foxclaw/core/confirm_nonce.py +151 -0
- package/python/foxclaw/core/dispatch.py +27 -0
- package/python/foxclaw/core/envfile.py +48 -0
- package/python/foxclaw/core/failure_policy.py +142 -0
- package/python/foxclaw/core/gateway.py +81 -0
- package/python/foxclaw/core/governance_audit.py +171 -0
- package/python/foxclaw/core/idempotency.py +282 -0
- package/python/foxclaw/core/injection_guard.py +202 -0
- package/python/foxclaw/core/memory_adapter.py +489 -0
- package/python/foxclaw/core/metrics.py +88 -0
- package/python/foxclaw/core/model_router.py +985 -0
- package/python/foxclaw/core/paths.py +103 -0
- package/python/foxclaw/core/recovery.py +349 -0
- package/python/foxclaw/core/scheduler.py +141 -0
- package/python/foxclaw/core/secrets.py +131 -0
- package/python/foxclaw/core/sessions.py +155 -0
- package/python/foxclaw/core/settings.py +414 -0
- package/python/foxclaw/core/shared_write.py +186 -0
- package/python/foxclaw/core/steering_queue.py +154 -0
- package/python/foxclaw/core/system_bus.py +84 -0
- package/python/foxclaw/core/thought_chain.py +316 -0
- package/python/foxclaw/core/token_meter.py +231 -0
- package/python/foxclaw/core/tools.py +164 -0
- package/python/foxclaw/core/tracing.py +375 -0
- package/python/foxclaw/core/truth_pipeline.py +110 -0
- package/python/foxclaw/core/update_check.py +149 -0
- package/python/foxclaw/core/vec_recall_adapter.py +477 -0
- package/python/foxclaw/core/verify.py +173 -0
- package/python/foxclaw/core/web_search.py +218 -0
- package/python/foxclaw/finance/__init__.py +15 -0
- package/python/foxclaw/finance/evidence.py +149 -0
- package/python/foxclaw/finance/fx.py +98 -0
- package/python/foxclaw/finance/graph.py +179 -0
- package/python/foxclaw/finance/models.py +146 -0
- package/python/foxclaw/finance/nlparse.py +515 -0
- package/python/foxclaw/finance/policy.py +301 -0
- package/python/foxclaw/finance/reasoner.py +121 -0
- package/python/foxclaw/finance/reasoning.py +319 -0
- package/python/foxclaw/finance/reconcile.py +175 -0
- package/python/foxclaw/finance/runtime.py +500 -0
- package/python/foxclaw/governance/__init__.py +24 -0
- package/python/foxclaw/governance/middleware.py +176 -0
- package/python/foxclaw/harness/__init__.py +17 -0
- package/python/foxclaw/harness/_base.py +66 -0
- package/python/foxclaw/harness/_policy.py +340 -0
- package/python/foxclaw/harness/drift.py +77 -0
- package/python/foxclaw/harness/event_bus.py +28 -0
- package/python/foxclaw/harness/harness.py +358 -0
- package/python/foxclaw/harness/loop_detection.py +145 -0
- package/python/foxclaw/itinerary/__init__.py +10 -0
- package/python/foxclaw/itinerary/amap_client.py +114 -0
- package/python/foxclaw/itinerary/models.py +80 -0
- package/python/foxclaw/itinerary/reasoner.py +96 -0
- package/python/foxclaw/itinerary/reasoning.py +168 -0
- package/python/foxclaw/itinerary/runtime.py +144 -0
- package/python/foxclaw/kernel/__init__.py +13 -0
- package/python/foxclaw/kernel/capabilities.py +72 -0
- package/python/foxclaw/kernel/policy_gate.py +108 -0
- package/python/foxclaw/kernel/process_manager.py +186 -0
- package/python/foxclaw/kernel/scheduler.py +125 -0
- package/python/foxclaw/kernel/sentinel.py +443 -0
- package/python/foxclaw/kernel/sentinel_client.py +243 -0
- package/python/foxclaw/kernel/spine.py +97 -0
- package/python/foxclaw/knowledge/__init__.py +360 -0
- package/python/foxclaw/knowledge/truth_crystallizer.py +89 -0
- package/python/foxclaw/learning/__init__.py +12 -0
- package/python/foxclaw/learning/knowledge_graph.py +144 -0
- package/python/foxclaw/learning/models.py +93 -0
- package/python/foxclaw/learning/reasoner.py +67 -0
- package/python/foxclaw/learning/runtime.py +351 -0
- package/python/foxclaw/learning/spaced_repetition.py +91 -0
- package/python/foxclaw/mcp_server.py +188 -0
- package/python/foxclaw/orchestration/__init__.py +167 -0
- package/python/foxclaw/pipeline/__init__.py +23 -0
- package/python/foxclaw/pipeline/cognitive_pipeline.py +429 -0
- package/python/foxclaw/pipeline/stage_meta.py +21 -0
- package/python/foxclaw/pipeline/supervisor_stages.py +201 -0
- package/python/foxclaw/planning/__init__.py +17 -0
- package/python/foxclaw/planning/llm_planner.py +232 -0
- package/python/foxclaw/planning/planner.py +94 -0
- package/python/foxclaw/search/__init__.py +24 -0
- package/python/foxclaw/search/agent_port.py +190 -0
- package/python/foxclaw/search/evidence.py +109 -0
- package/python/foxclaw/search/external_search.py +50 -0
- package/python/foxclaw/search/hkc_read_port.py +60 -0
- package/python/foxclaw/search/internal_search.py +71 -0
- package/python/foxclaw/search/models.py +127 -0
- package/python/foxclaw/search/planner.py +44 -0
- package/python/foxclaw/search/retriever.py +39 -0
- package/python/foxclaw/search/runtime.py +127 -0
- package/python/foxclaw/search/strategy.py +44 -0
- package/python/foxclaw/skills/__init__.py +559 -0
- package/python/foxclaw/skills/archive.py +111 -0
- package/python/foxclaw/skills/fetch.py +226 -0
- package/python/foxclaw/skills/hooks_spec.py +69 -0
- package/python/foxclaw/skills/install_cmd.py +216 -0
- package/python/foxclaw/skills/lifecycle.py +252 -0
- package/python/foxclaw/skills/markdown_skill.py +175 -0
- package/python/foxclaw/skills/markdown_store.py +39 -0
- package/python/foxclaw/skills/mcp_client.py +184 -0
- package/python/foxclaw/skills/mcp_store.py +40 -0
- package/python/foxclaw/skills/permission.py +145 -0
- package/python/foxclaw/skills/pipeline.py +354 -0
- package/python/foxclaw/skills/policy.py +74 -0
- package/python/foxclaw/skills/review.py +72 -0
- package/python/foxclaw/skills/store.py +57 -0
- package/python/frontend/assets/core_bg.jpg +0 -0
- package/python/frontend/deck/auth.js +25 -0
- package/python/frontend/deck/chat_model_picker.js +483 -0
- package/python/frontend/deck/domain.js +276 -0
- package/python/frontend/deck/main.js +1806 -0
- package/python/frontend/deck/markdown.js +44 -0
- package/python/frontend/deck/settings.js +307 -0
- package/python/frontend/deck/state.js +5 -0
- package/python/frontend/deck/util.js +4 -0
- package/python/frontend/deck/visuals.js +190 -0
- package/python/frontend/deck.css +855 -0
- package/python/frontend/deck.html +686 -0
- package/python/frontend/deck_v2.html +341 -0
- package/python/frontend/planet/index.html +266 -0
- package/python/frontend/planet/planet.css +579 -0
- package/python/frontend/planet/planet.js +1436 -0
- package/python/frontend/planet/vendor/three.core.min.js +6 -0
- package/python/frontend/planet/vendor/three.module.min.js +6 -0
- package/python/frontend/v3/assets/index-CQSBdxk4.js +34 -0
- package/python/frontend/v3/assets/index-D5nIsjms.css +1 -0
- package/python/frontend/v3/index.html +15 -0
- package/python/frontend/widget_runtime.js +252 -0
- package/python/frontend/widgets.js +639 -0
- package/python/frontend_src/index.html +14 -0
- package/python/frontend_src/package-lock.json +1376 -0
- package/python/frontend_src/package.json +19 -0
- package/python/frontend_src/src/App.vue +58 -0
- package/python/frontend_src/src/api.js +82 -0
- package/python/frontend_src/src/components/ChatDock.vue +365 -0
- package/python/frontend_src/src/components/ComposerMenu.vue +75 -0
- package/python/frontend_src/src/components/DocViewer.vue +162 -0
- package/python/frontend_src/src/components/Inspector.vue +235 -0
- package/python/frontend_src/src/components/LeftRail.vue +415 -0
- package/python/frontend_src/src/components/MenuPopover.vue +128 -0
- package/python/frontend_src/src/components/MessageStream.vue +389 -0
- package/python/frontend_src/src/components/ModelPicker.vue +350 -0
- package/python/frontend_src/src/components/QuickIngest.vue +112 -0
- package/python/frontend_src/src/components/Stage.vue +272 -0
- package/python/frontend_src/src/components/ToolMenu.vue +141 -0
- package/python/frontend_src/src/components/TopBar.vue +118 -0
- package/python/frontend_src/src/components/panels/ActivityPanel.vue +82 -0
- package/python/frontend_src/src/components/panels/AgentsPanel.vue +83 -0
- package/python/frontend_src/src/components/panels/KnowledgePanel.vue +425 -0
- package/python/frontend_src/src/components/panels/MemoryPanel.vue +117 -0
- package/python/frontend_src/src/components/panels/PanelBox.vue +50 -0
- package/python/frontend_src/src/components/panels/ReviewPanel.vue +292 -0
- package/python/frontend_src/src/components/panels/SettingsPanel.vue +358 -0
- package/python/frontend_src/src/components/panels/TasksPanel.vue +73 -0
- package/python/frontend_src/src/components/panels/ToolsPanel.vue +746 -0
- package/python/frontend_src/src/components/panels/UsagePanel.vue +105 -0
- package/python/frontend_src/src/lib/fmt.js +44 -0
- package/python/frontend_src/src/lib/i18n.js +53 -0
- package/python/frontend_src/src/lib/locales/en.js +173 -0
- package/python/frontend_src/src/lib/locales/zh.js +174 -0
- package/python/frontend_src/src/lib/md.js +190 -0
- package/python/frontend_src/src/main.js +9 -0
- package/python/frontend_src/src/stores/app.js +91 -0
- package/python/frontend_src/src/stores/chat.js +450 -0
- package/python/frontend_src/src/stores/model.js +96 -0
- package/python/frontend_src/src/stores/panels.js +289 -0
- package/python/frontend_src/src/stores/profile.js +31 -0
- package/python/frontend_src/src/stores/system.js +25 -0
- package/python/frontend_src/src/styles/base.css +138 -0
- package/python/frontend_src/src/styles/panel.css +117 -0
- package/python/frontend_src/src/styles/tokens.css +78 -0
- package/python/frontend_src/vite.config.js +39 -0
- package/python/pyproject.toml +268 -0
- package/python/requirements.txt +311 -0
- package/python/skills/README.md +123 -0
- package/python/skills/execution-contract/SKILL.md +30 -0
- package/python/skills/general-assistant/SKILL.md +34 -0
- package/python/skills/planner/SKILL.md +33 -0
- package/python/skills/schedule-itinerary/SKILL.md +35 -0
- package/python/skills/skill-composition/SKILL.md +31 -0
- package/python/skills/skill-guard/SKILL.md +67 -0
- package/python/skills/skill-memory/SKILL.md +50 -0
- package/python/skills/skill-router/SKILL.md +35 -0
- package/python/tests/conftest.py +54 -0
- package/python/tests/run_all.py +200 -0
- package/python/tests/test_agent_lifecycle.py +326 -0
- package/python/tests/test_ahs_p2.py +393 -0
- package/python/tests/test_anthropic_tools.py +192 -0
- package/python/tests/test_api.py +97 -0
- package/python/tests/test_api_auth.py +79 -0
- package/python/tests/test_api_host_guard.py +69 -0
- package/python/tests/test_attachments.py +151 -0
- package/python/tests/test_audit_chain.py +116 -0
- package/python/tests/test_audit_sink.py +130 -0
- package/python/tests/test_browser.py +149 -0
- package/python/tests/test_browser_request_guard.py +180 -0
- package/python/tests/test_capabilities.py +152 -0
- package/python/tests/test_channel_signing.py +185 -0
- package/python/tests/test_channel_trust.py +109 -0
- package/python/tests/test_channels.py +174 -0
- package/python/tests/test_cli.py +46 -0
- package/python/tests/test_compaction_toolpair.py +119 -0
- package/python/tests/test_config_layering.py +61 -0
- package/python/tests/test_confirm_nonce.py +186 -0
- package/python/tests/test_context_compaction_wiring.py +124 -0
- package/python/tests/test_dispatch.py +89 -0
- package/python/tests/test_domain_evals.py +334 -0
- package/python/tests/test_domain_import.py +72 -0
- package/python/tests/test_domain_reasoners.py +134 -0
- package/python/tests/test_e2e.py +161 -0
- package/python/tests/test_emb_cache.py +97 -0
- package/python/tests/test_embedding_singleton.py +87 -0
- package/python/tests/test_envfile.py +83 -0
- package/python/tests/test_evals_smoke.py +90 -0
- package/python/tests/test_event_spine.py +174 -0
- package/python/tests/test_evidence_semantic.py +88 -0
- package/python/tests/test_evidence_sse.py +94 -0
- package/python/tests/test_file_ingest.py +135 -0
- package/python/tests/test_finance.py +144 -0
- package/python/tests/test_finance_ledger.py +245 -0
- package/python/tests/test_finance_persist.py +174 -0
- package/python/tests/test_gateway.py +125 -0
- package/python/tests/test_governance.py +421 -0
- package/python/tests/test_governance_audit.py +324 -0
- package/python/tests/test_governance_middleware.py +137 -0
- package/python/tests/test_hkc.py +268 -0
- package/python/tests/test_hkc_index_build_manager.py +306 -0
- package/python/tests/test_hkc_manifest_reuse.py +294 -0
- package/python/tests/test_hkc_search_event_sync.py +482 -0
- package/python/tests/test_import_path_guard.py +155 -0
- package/python/tests/test_injection_guard.py +193 -0
- package/python/tests/test_integration.py +117 -0
- package/python/tests/test_itinerary.py +100 -0
- package/python/tests/test_kee_semantic.py +84 -0
- package/python/tests/test_kernel.py +212 -0
- package/python/tests/test_learning.py +101 -0
- package/python/tests/test_llm_admin.py +145 -0
- package/python/tests/test_llm_planner.py +344 -0
- package/python/tests/test_markdown_skills.py +62 -0
- package/python/tests/test_markdown_skills_openclaw.py +66 -0
- package/python/tests/test_mcp_connectors.py +97 -0
- package/python/tests/test_mcp_guardian_discovery.py +87 -0
- package/python/tests/test_mcp_no_memory.py +43 -0
- package/python/tests/test_mcp_policy_gate.py +76 -0
- package/python/tests/test_mcp_server.py +92 -0
- package/python/tests/test_memory_recall.py +92 -0
- package/python/tests/test_metrics.py +58 -0
- package/python/tests/test_multi_chain.py +90 -0
- package/python/tests/test_multimodal.py +122 -0
- package/python/tests/test_negotiation.py +136 -0
- package/python/tests/test_orchestration.py +109 -0
- package/python/tests/test_orchestration_decoupled.py +103 -0
- package/python/tests/test_p3_p5_hardening.py +324 -0
- package/python/tests/test_parallel_dispatch.py +207 -0
- package/python/tests/test_pipeline.py +492 -0
- package/python/tests/test_plan_visible.py +86 -0
- package/python/tests/test_planner.py +88 -0
- package/python/tests/test_policy_gate.py +108 -0
- package/python/tests/test_profile.py +67 -0
- package/python/tests/test_readme_claims.py +163 -0
- package/python/tests/test_reasoner.py +170 -0
- package/python/tests/test_release_check.py +252 -0
- package/python/tests/test_resume_checkpoint.py +148 -0
- package/python/tests/test_routing.py +85 -0
- package/python/tests/test_scheduler.py +138 -0
- package/python/tests/test_search.py +194 -0
- package/python/tests/test_secrets.py +153 -0
- package/python/tests/test_semantic.py +69 -0
- package/python/tests/test_sessions.py +90 -0
- package/python/tests/test_settings.py +265 -0
- package/python/tests/test_shadow_learning.py +290 -0
- package/python/tests/test_shared_write.py +200 -0
- package/python/tests/test_skill_taint_gate.py +145 -0
- package/python/tests/test_skills.py +117 -0
- package/python/tests/test_skills_fetch.py +282 -0
- package/python/tests/test_stats_and_events.py +162 -0
- package/python/tests/test_streaming.py +55 -0
- package/python/tests/test_supervisor_pipeline.py +176 -0
- package/python/tests/test_supervisor_triage.py +102 -0
- package/python/tests/test_taint.py +112 -0
- package/python/tests/test_task_stream.py +74 -0
- package/python/tests/test_thinking_sse.py +66 -0
- package/python/tests/test_thinking_stream.py +76 -0
- package/python/tests/test_tool_center.py +113 -0
- package/python/tests/test_tool_parallel.py +113 -0
- package/python/tests/test_tool_params.py +99 -0
- package/python/tests/test_tool_use.py +229 -0
- package/python/tests/test_toplevel_concurrency.py +116 -0
- package/python/tests/test_tracing.py +256 -0
- package/python/tests/test_truth_crystallizer.py +125 -0
- package/python/tests/test_truth_flow.py +88 -0
- package/python/tests/test_update_check.py +95 -0
- package/python/tests/test_url_policy.py +53 -0
- package/python/tests/test_verify_evidence.py +212 -0
- package/python/tests/test_version_sync.py +100 -0
- package/python/tests/test_web_trigger.py +82 -0
- package/python/tools/check_faiss_type.py +30 -0
- package/python/tools/check_log.ps1 +38 -0
- package/python/tools/ivf_status.py +72 -0
- package/python/tools/mypy_baseline.txt +13 -0
- package/python/tools/mypy_ratchet.py +143 -0
- package/python/tools/pack.py +173 -0
- package/python/tools/release_check.py +349 -0
- package/python/tools/restart_foxclaw.ps1 +71 -0
- package/python/tools/shared_write_audit.py +190 -0
- package/python/tools/size_baseline.txt +28 -0
- package/python/tools/size_check.py +102 -0
- package/python/tools/strip_comments.py +228 -0
- package/python/tools/verify_env.bat +2 -0
- package/python/tools/verify_env.py +25 -0
- package/python/vendor/HMR_LICENSE +37 -0
- package/python/vendor/HMR_README.md +65 -0
- package/python/vendor/hkc/LICENSE +37 -0
- package/python/vendor/hkc/hkc_ace/__init__.py +0 -0
- package/python/vendor/hkc/hkc_ace/ace.py +457 -0
- package/python/vendor/hkc/hkc_ace/skill_taxonomy.json +465 -0
- package/python/vendor/hkc/hkc_api/__init__.py +0 -0
- package/python/vendor/hkc/hkc_api/container.py +416 -0
- package/python/vendor/hkc/hkc_api/ingest_jobs.py +103 -0
- package/python/vendor/hkc/hkc_api/main.py +157 -0
- package/python/vendor/hkc/hkc_api/routes/__init__.py +0 -0
- package/python/vendor/hkc/hkc_api/routes/ability.py +151 -0
- package/python/vendor/hkc/hkc_api/routes/config.py +51 -0
- package/python/vendor/hkc/hkc_api/routes/knowledge.py +630 -0
- package/python/vendor/hkc/hkc_api/routes/search.py +88 -0
- package/python/vendor/hkc/hkc_api/schemas.py +153 -0
- package/python/vendor/hkc/hkc_api/synthesis.py +179 -0
- package/python/vendor/hkc/hkc_core/__init__.py +0 -0
- package/python/vendor/hkc/hkc_core/graph/__init__.py +0 -0
- package/python/vendor/hkc/hkc_core/graph/base.py +188 -0
- package/python/vendor/hkc/hkc_core/graph/sqlite_store.py +789 -0
- package/python/vendor/hkc/hkc_core/models/__init__.py +0 -0
- package/python/vendor/hkc/hkc_core/models/enums.py +65 -0
- package/python/vendor/hkc/hkc_core/models/ku.py +307 -0
- package/python/vendor/hkc/hkc_core/utils/__init__.py +0 -0
- package/python/vendor/hkc/hkc_core/utils/id_gen.py +113 -0
- package/python/vendor/hkc/hkc_crystallizer/__init__.py +44 -0
- package/python/vendor/hkc/hkc_crystallizer/adapters.py +94 -0
- package/python/vendor/hkc/hkc_crystallizer/candidate.py +145 -0
- package/python/vendor/hkc/hkc_crystallizer/crystallizer.py +179 -0
- package/python/vendor/hkc/hkc_crystallizer/ingress.py +90 -0
- package/python/vendor/hkc/hkc_kde/__init__.py +0 -0
- package/python/vendor/hkc/hkc_kde/chunker.py +197 -0
- package/python/vendor/hkc/hkc_kde/extractor.py +623 -0
- package/python/vendor/hkc/hkc_kde/kde.py +298 -0
- package/python/vendor/hkc/hkc_kde/loaders/__init__.py +0 -0
- package/python/vendor/hkc/hkc_kde/loaders/ebook_loader.py +153 -0
- package/python/vendor/hkc/hkc_kde/loaders/office_loader.py +194 -0
- package/python/vendor/hkc/hkc_kde/loaders/pdf_loader.py +162 -0
- package/python/vendor/hkc/hkc_kde/loaders/text_loader.py +157 -0
- package/python/vendor/hkc/hkc_kde/loaders/web_loader.py +91 -0
- package/python/vendor/hkc/hkc_kde/models.py +74 -0
- package/python/vendor/hkc/hkc_kde/packager.py +329 -0
- package/python/vendor/hkc/hkc_kde/relation_disc.py +151 -0
- package/python/vendor/hkc/hkc_kee/__init__.py +0 -0
- package/python/vendor/hkc/hkc_kee/dedup.py +227 -0
- package/python/vendor/hkc/hkc_kee/fingerprint.py +106 -0
- package/python/vendor/hkc/hkc_kee/kee.py +541 -0
- package/python/vendor/hkc/hkc_kep/__init__.py +0 -0
- package/python/vendor/hkc/hkc_kep/event_bus.py +205 -0
- package/python/vendor/hkc/hkc_sdk/__init__.py +63 -0
- package/python/vendor/hkc/hkc_sdk/base.py +151 -0
- package/python/vendor/hkc/hkc_sdk/direct_client.py +153 -0
- package/python/vendor/hkc/hkc_sdk/exceptions.py +39 -0
- package/python/vendor/hkc/hkc_sdk/http_client.py +166 -0
- package/python/vendor/hkc/hkc_sdk/models.py +171 -0
- package/python/vendor/hkc/hkc_search/__init__.py +0 -0
- package/python/vendor/hkc/hkc_search/bm25.py +325 -0
- package/python/vendor/hkc/hkc_search/embedding_backends.py +374 -0
- package/python/vendor/hkc/hkc_search/graph_search.py +132 -0
- package/python/vendor/hkc/hkc_search/hybrid.py +331 -0
- package/python/vendor/hkc/hkc_search/index_build_manager.py +378 -0
- package/python/vendor/hkc/hkc_search/vector_search.py +484 -0
- package/python/vendor/hmr/__init__.py +0 -0
- package/python/vendor/hmr/core/__init__.py +0 -0
- package/python/vendor/hmr/core/hmr.py +684 -0
- package/python/vendor/hmr/core/models.py +310 -0
- package/python/vendor/hmr/engines/__init__.py +0 -0
- package/python/vendor/hmr/engines/evolution.py +710 -0
- package/python/vendor/hmr/engines/jit_compiler.py +472 -0
- package/python/vendor/hmr/engines/lifecycle.py +264 -0
- package/python/vendor/hmr/engines/policy.py +625 -0
- package/python/vendor/hmr/engines/recall.py +260 -0
- package/python/vendor/hmr/engines/runtime_state.py +158 -0
- package/python/vendor/hmr/engines/scheduler.py +323 -0
- package/python/vendor/hmr/engines/semantic.py +150 -0
- package/python/vendor/hmr/engines/temporal.py +261 -0
- package/python/vendor/hmr/engines/thought_chain.py +635 -0
- package/python/vendor/hmr/graph/__init__.py +0 -0
- package/python/vendor/hmr/graph/cwg.py +338 -0
- package/python/vendor/hmr/graph/memory_graph.py +530 -0
- package/python/vendor/hmr/storage/__init__.py +0 -0
- package/python/vendor/hmr/storage/memory_fs.py +300 -0
- package/python/vendor/hmr/storage/vector_store.py +520 -0
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Memory Policy Engine - 记忆策略引擎
|
|
3
|
+
HMR v2.0 新增
|
|
4
|
+
|
|
5
|
+
解决的问题:
|
|
6
|
+
v1.x 的存/取/忘策略全部硬编码,无法从经验中学习
|
|
7
|
+
PolicyEngine 让系统从实际使用反馈中学习最优策略:
|
|
8
|
+
- IngestPolicy:什么值得存?存成什么类型?置信度多少?
|
|
9
|
+
- RecallPolicy:什么时候用 JIT?top_k 设多少?
|
|
10
|
+
- ForgetPolicy:什么时候降权?什么时候删除?
|
|
11
|
+
|
|
12
|
+
学习机制:
|
|
13
|
+
使用带动量的梯度更新(类 SGD),无需 GPU/大数据
|
|
14
|
+
反馈信号:
|
|
15
|
+
- recall_hit:召回结果被实际使用 → 正向奖励
|
|
16
|
+
- recall_miss:召回结果无用 → 负向惩罚
|
|
17
|
+
- compress_gain:压缩后召回质量上升 → 正向
|
|
18
|
+
- task_success:任务完成 → 关联记忆正向
|
|
19
|
+
- task_failure:任务失败 → 关联记忆负向
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import re
|
|
24
|
+
import threading
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import List, Dict, Any, Optional
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from datetime import datetime
|
|
29
|
+
from collections import deque
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# ============================================================================
|
|
33
|
+
# 反馈事件
|
|
34
|
+
# ============================================================================
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class FeedbackEvent:
|
|
38
|
+
"""一次策略反馈事件"""
|
|
39
|
+
event_type: str # recall_hit / recall_miss / compress_gain / task_success / task_failure
|
|
40
|
+
memory_ids: List[str] # 相关的记忆 ID
|
|
41
|
+
signal: float # 强度 -1.0~1.0(正=好 负=坏)
|
|
42
|
+
context: Dict[str, Any] = field(default_factory=dict)
|
|
43
|
+
timestamp: datetime = field(default_factory=datetime.utcnow)
|
|
44
|
+
|
|
45
|
+
def to_dict(self) -> dict:
|
|
46
|
+
return {
|
|
47
|
+
"event_type": self.event_type,
|
|
48
|
+
"memory_ids": self.memory_ids,
|
|
49
|
+
"signal": self.signal,
|
|
50
|
+
"context": self.context,
|
|
51
|
+
"timestamp": self.timestamp.isoformat(),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def from_dict(cls, d: dict) -> "FeedbackEvent":
|
|
56
|
+
d = d.copy()
|
|
57
|
+
d["timestamp"] = datetime.fromisoformat(d["timestamp"])
|
|
58
|
+
return cls(**d)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ============================================================================
|
|
62
|
+
# Ingest Policy(存储策略)
|
|
63
|
+
# ============================================================================
|
|
64
|
+
|
|
65
|
+
class IngestPolicy:
|
|
66
|
+
"""
|
|
67
|
+
决定:什么值得存,存成什么类型,置信度设多少。
|
|
68
|
+
|
|
69
|
+
特征向量(12维):
|
|
70
|
+
[0] 内容长度(归一化)
|
|
71
|
+
[1] 包含数字/指标
|
|
72
|
+
[2] 包含失败关键词
|
|
73
|
+
[3] 包含成功关键词
|
|
74
|
+
[4] 包含决策关键词
|
|
75
|
+
[5] 包含原因关键词
|
|
76
|
+
[6] 已有相关记忆数量(归一化)
|
|
77
|
+
[7] 当前时间权重(运行时活跃度)
|
|
78
|
+
[8] tag 数量
|
|
79
|
+
[9] runtime_dependencies 数量
|
|
80
|
+
[10] 内容重复度(与已有摘要的词重叠)
|
|
81
|
+
[11] 标题质量(有标题=1,无=0)
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
TYPE_LABELS = ["concept", "decision", "execution", "reflection", "task"]
|
|
85
|
+
DEFAULT_WEIGHTS = {
|
|
86
|
+
# 特征索引: [长度, 数字, 失败词, 成功词, 决策词, 原因词, 已有记忆数, 活跃度, tag数, dep数, 重复度, 有标题, 概念词]
|
|
87
|
+
"concept": [ 0.0, -0.1, -0.2, 0.1, -0.1, 0.3, -0.1, 0.0, 0.2, 0.1, -0.3, 0.0, 0.6],
|
|
88
|
+
"decision": [-0.1, 0.0, -0.2, 0.2, 0.6, 0.1, 0.0, 0.0, 0.1, 0.3, -0.2, 0.1, -0.3],
|
|
89
|
+
"execution": [ 0.3, 0.4, 0.7, 0.2, -0.1, 0.1, 0.0, 0.1, 0.0, 0.0, -0.2, 0.0, -0.3],
|
|
90
|
+
"reflection": [ 0.1, 0.0, 0.3, 0.0, 0.0, 0.5, 0.1, 0.0, 0.1, 0.0, -0.1, 0.0, -0.3],
|
|
91
|
+
"task": [ 0.1, 0.0, -0.3, -0.1, 0.2, -0.1, 0.0, 0.0, 0.0, 0.2, -0.1, 0.1, -0.3],
|
|
92
|
+
}
|
|
93
|
+
IMPORTANCE_WEIGHTS = [0.1, 0.15, 0.35, 0.1, 0.15, 0.2, 0.0, 0.05, 0.1, 0.1, -0.35, 0.05, 0.1]
|
|
94
|
+
|
|
95
|
+
# 关键词集合
|
|
96
|
+
FAIL_WORDS = {
|
|
97
|
+
"失败","错误","死锁","超时","崩溃","积压","故障","异常","不足","问题","缺陷","阻塞","中断",
|
|
98
|
+
"fail","error","crash","timeout","bug","wrong","issue","broken","blocked","overflow"
|
|
99
|
+
}
|
|
100
|
+
SUCCESS_WORDS = {
|
|
101
|
+
"成功","完成","通过","正常","优化","降低","提升","改善","恢复","解决",
|
|
102
|
+
"success","done","pass","improved","fixed","resolved","optimised","reduced"
|
|
103
|
+
}
|
|
104
|
+
DECISION_WORDS = {
|
|
105
|
+
# 只保留"已做决策"的词,"建议/推荐"是泛化概念词,不放这里
|
|
106
|
+
"决定","选择","采用","决策","选用","确定","批准",
|
|
107
|
+
"decided","chose","selected","adopted","determined","approved"
|
|
108
|
+
}
|
|
109
|
+
CONCEPT_WORDS = {
|
|
110
|
+
"建议","推荐","模式","原则","方式","架构","设计","规范","最佳实践","理念",
|
|
111
|
+
"recommend","pattern","principle","approach","design","architecture","best practice"
|
|
112
|
+
}
|
|
113
|
+
REASON_WORDS = {
|
|
114
|
+
"因为","由于","原因","导致","根因","分析","推断","基于","根据",
|
|
115
|
+
"because","cause","reason","due to","resulted","analysis","therefore","hence"
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
def __init__(self):
|
|
119
|
+
self.weights = {k: list(v) for k, v in self.DEFAULT_WEIGHTS.items()}
|
|
120
|
+
self.importance_weights = list(self.IMPORTANCE_WEIGHTS)
|
|
121
|
+
self._lr = 0.01 # 学习率
|
|
122
|
+
self._momentum = {k: [0.0]*13 for k in self.TYPE_LABELS}
|
|
123
|
+
|
|
124
|
+
def should_store(self, content: str, context: Dict[str, Any]) -> bool:
|
|
125
|
+
"""判断这条内容是否值得存入长期记忆"""
|
|
126
|
+
importance = self._compute_importance(content, context)
|
|
127
|
+
# 基准阈值 0.3,重复内容不存
|
|
128
|
+
return importance >= 0.3
|
|
129
|
+
|
|
130
|
+
def classify_type(self, content: str, context: Dict[str, Any]) -> str:
|
|
131
|
+
"""推断最适合的 memory_type"""
|
|
132
|
+
features = self._extract_features(content, context)
|
|
133
|
+
scores = {}
|
|
134
|
+
for mtype, w in self.weights.items():
|
|
135
|
+
score = sum(f * wi for f, wi in zip(features, w))
|
|
136
|
+
scores[mtype] = score
|
|
137
|
+
return max(scores, key=lambda k: scores[k])
|
|
138
|
+
|
|
139
|
+
def recommend_confidence(self, content: str, context: Dict[str, Any]) -> float:
|
|
140
|
+
"""推荐置信度"""
|
|
141
|
+
importance = self._compute_importance(content, context)
|
|
142
|
+
# 置信度 = 重要性 * 0.6 + 0.4 基线
|
|
143
|
+
return round(min(1.0, importance * 0.6 + 0.4), 2)
|
|
144
|
+
|
|
145
|
+
def update(self, memory_id: str, feedback: float, features: List[float], mtype: str):
|
|
146
|
+
"""基于反馈更新权重(带动量的 SGD)"""
|
|
147
|
+
if mtype not in self.weights:
|
|
148
|
+
return
|
|
149
|
+
w = self.weights[mtype]
|
|
150
|
+
m = self._momentum[mtype]
|
|
151
|
+
for i in range(min(len(features), len(w))):
|
|
152
|
+
grad = -feedback * features[i]
|
|
153
|
+
m[i] = 0.9 * m[i] + self._lr * grad
|
|
154
|
+
w[i] = max(-1.0, min(1.0, w[i] - m[i]))
|
|
155
|
+
|
|
156
|
+
def _extract_features(self, content: str, context: Dict[str, Any]) -> List[float]:
|
|
157
|
+
"""
|
|
158
|
+
中英文兼容的特征提取:
|
|
159
|
+
使用字符级 in 检查(不依赖空格分词),同时兼容中文和英文。
|
|
160
|
+
"""
|
|
161
|
+
text = content.lower()
|
|
162
|
+
# 字符级关键词匹配(对中文无需分词)
|
|
163
|
+
fail_score = min(1.0, sum(1 for w in self.FAIL_WORDS if w in text) / 3)
|
|
164
|
+
success_score = min(1.0, sum(1 for w in self.SUCCESS_WORDS if w in text) / 3)
|
|
165
|
+
decision_score= min(1.0, sum(1 for w in self.DECISION_WORDS if w in text) / 2)
|
|
166
|
+
reason_score = min(1.0, sum(1 for w in self.REASON_WORDS if w in text) / 2)
|
|
167
|
+
concept_score = min(1.0, sum(1 for w in self.CONCEPT_WORDS if w in text) / 2)
|
|
168
|
+
return [
|
|
169
|
+
min(1.0, len(content) / 500),
|
|
170
|
+
1.0 if re.search(r'\d+', content) else 0.0,
|
|
171
|
+
fail_score,
|
|
172
|
+
success_score,
|
|
173
|
+
decision_score,
|
|
174
|
+
reason_score,
|
|
175
|
+
min(1.0, context.get("existing_memory_count", 0) / 100),
|
|
176
|
+
context.get("runtime_activity", 0.5),
|
|
177
|
+
min(1.0, len(context.get("tags", [])) / 5),
|
|
178
|
+
min(1.0, len(context.get("runtime_dependencies", [])) / 5),
|
|
179
|
+
context.get("content_overlap", 0.0),
|
|
180
|
+
1.0 if context.get("title") else 0.0,
|
|
181
|
+
concept_score, # ← 新增第13维:概念词得分
|
|
182
|
+
]
|
|
183
|
+
|
|
184
|
+
def _compute_importance(self, content: str, context: Dict[str, Any]) -> float:
|
|
185
|
+
features = self._extract_features(content, context)
|
|
186
|
+
score = sum(f * w for f, w in zip(features, self.importance_weights))
|
|
187
|
+
return max(0.0, min(1.0, score + 0.5))
|
|
188
|
+
|
|
189
|
+
def to_dict(self) -> dict:
|
|
190
|
+
return {"weights": self.weights, "importance_weights": self.importance_weights}
|
|
191
|
+
|
|
192
|
+
@classmethod
|
|
193
|
+
def from_dict(cls, d: dict) -> "IngestPolicy":
|
|
194
|
+
p = cls()
|
|
195
|
+
p.weights = d.get("weights", p.weights)
|
|
196
|
+
p.importance_weights = d.get("importance_weights", p.importance_weights)
|
|
197
|
+
return p
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# ============================================================================
|
|
201
|
+
# Recall Policy(召回策略)
|
|
202
|
+
# ============================================================================
|
|
203
|
+
|
|
204
|
+
class RecallPolicy:
|
|
205
|
+
"""
|
|
206
|
+
决定:用哪种策略召回,top_k 设多少,是否走 JIT。
|
|
207
|
+
|
|
208
|
+
特征向量(8维):
|
|
209
|
+
[0] 查询长度(归一化)
|
|
210
|
+
[1] 包含推理词(why/cause/因为)
|
|
211
|
+
[2] 包含时间词(recent/last/最近)
|
|
212
|
+
[3] 当前任务复杂度
|
|
213
|
+
[4] 历史召回命中率
|
|
214
|
+
[5] 当前记忆库大小(归一化)
|
|
215
|
+
[6] 是否有活跃 goal
|
|
216
|
+
[7] 上次召回失败标记
|
|
217
|
+
"""
|
|
218
|
+
|
|
219
|
+
STRATEGY_LABELS = ["semantic", "temporal", "jit", "hybrid", "graph"]
|
|
220
|
+
DEFAULT_STRATEGY_WEIGHTS = {
|
|
221
|
+
"semantic": [ 0.0, 0.0, 0.0, 0.0, 0.2, 0.0, 0.0, 0.0],
|
|
222
|
+
"temporal": [ 0.0, -0.2, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0],
|
|
223
|
+
"jit": [ 0.2, 0.5, -0.1, 0.3, 0.0, 0.1, 0.0, 0.3],
|
|
224
|
+
"hybrid": [ 0.1, 0.2, 0.0, 0.2, 0.1, 0.0, 0.5, 0.1],
|
|
225
|
+
"graph": [ 0.0, 0.3, 0.0, 0.3, 0.0, 0.2, 0.1, 0.2],
|
|
226
|
+
}
|
|
227
|
+
TOP_K_WEIGHTS = [0.1, 0.3, 0.0, 0.4, -0.2, 0.2, 0.1, 0.2] # → 调整 top_k
|
|
228
|
+
|
|
229
|
+
REASON_WORDS = {"为什么","原因","因为","why","cause","reason","because","导致"}
|
|
230
|
+
TIME_WORDS = {"最近","上次","昨天","recent","last","yesterday","previously","before"}
|
|
231
|
+
|
|
232
|
+
def __init__(self):
|
|
233
|
+
self.strategy_weights = {k: list(v) for k, v in self.DEFAULT_STRATEGY_WEIGHTS.items()}
|
|
234
|
+
self.top_k_weights = list(self.TOP_K_WEIGHTS)
|
|
235
|
+
self._lr = 0.005
|
|
236
|
+
self._hit_rate_history: deque = deque(maxlen=50)
|
|
237
|
+
|
|
238
|
+
def select_strategy(self, query: str, context: Dict[str, Any]) -> str:
|
|
239
|
+
features = self._extract_features(query, context)
|
|
240
|
+
scores = {}
|
|
241
|
+
for strat, w in self.strategy_weights.items():
|
|
242
|
+
scores[strat] = sum(f * wi for f, wi in zip(features, w))
|
|
243
|
+
return max(scores, key=lambda k: scores[k])
|
|
244
|
+
|
|
245
|
+
def decide_top_k(self, query: str, context: Dict[str, Any], base: int = 5) -> int:
|
|
246
|
+
features = self._extract_features(query, context)
|
|
247
|
+
delta = sum(f * w for f, w in zip(features, self.top_k_weights))
|
|
248
|
+
return max(3, min(12, base + int(delta * 5)))
|
|
249
|
+
|
|
250
|
+
def record_hit(self, used: bool):
|
|
251
|
+
self._hit_rate_history.append(1.0 if used else 0.0)
|
|
252
|
+
|
|
253
|
+
def get_hit_rate(self) -> float:
|
|
254
|
+
if not self._hit_rate_history:
|
|
255
|
+
return 0.5
|
|
256
|
+
return sum(self._hit_rate_history) / len(self._hit_rate_history)
|
|
257
|
+
|
|
258
|
+
def update(self, strategy: str, feedback: float, features: List[float]):
|
|
259
|
+
if strategy not in self.strategy_weights:
|
|
260
|
+
return
|
|
261
|
+
w = self.strategy_weights[strategy]
|
|
262
|
+
for i in range(min(len(features), len(w))):
|
|
263
|
+
grad = -feedback * features[i]
|
|
264
|
+
w[i] = max(-1.0, min(1.0, w[i] - self._lr * grad))
|
|
265
|
+
|
|
266
|
+
def _extract_features(self, query: str, context: Dict[str, Any]) -> List[float]:
|
|
267
|
+
q_lower = (query or "").lower()
|
|
268
|
+
# 字符级匹配(兼容中英文)
|
|
269
|
+
reason_score = min(1.0, sum(1 for w in self.REASON_WORDS if w in q_lower) / 2)
|
|
270
|
+
time_score = min(1.0, sum(1 for w in self.TIME_WORDS if w in q_lower) / 2)
|
|
271
|
+
return [
|
|
272
|
+
min(1.0, len(q_lower) / 100),
|
|
273
|
+
reason_score,
|
|
274
|
+
time_score,
|
|
275
|
+
context.get("task_complexity", 0.5),
|
|
276
|
+
self.get_hit_rate(),
|
|
277
|
+
min(1.0, context.get("memory_count", 0) / 500),
|
|
278
|
+
1.0 if context.get("active_goal") else 0.0,
|
|
279
|
+
1.0 if context.get("last_recall_failed") else 0.0,
|
|
280
|
+
]
|
|
281
|
+
|
|
282
|
+
def to_dict(self) -> dict:
|
|
283
|
+
return {"strategy_weights": self.strategy_weights, "top_k_weights": self.top_k_weights}
|
|
284
|
+
|
|
285
|
+
@classmethod
|
|
286
|
+
def from_dict(cls, d: dict) -> "RecallPolicy":
|
|
287
|
+
p = cls()
|
|
288
|
+
p.strategy_weights = d.get("strategy_weights", p.strategy_weights)
|
|
289
|
+
p.top_k_weights = d.get("top_k_weights", p.top_k_weights)
|
|
290
|
+
return p
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
# ============================================================================
|
|
294
|
+
# Forget Policy(遗忘策略)
|
|
295
|
+
# ============================================================================
|
|
296
|
+
|
|
297
|
+
class ForgetPolicy:
|
|
298
|
+
"""
|
|
299
|
+
决定:记忆应该以多快的速度衰减,什么时候应该删除。
|
|
300
|
+
|
|
301
|
+
对不同类型的记忆采用不同的衰减速率:
|
|
302
|
+
- insight / concept:慢衰减(知识价值持久)
|
|
303
|
+
- execution:中等衰减(经验记录有时效性)
|
|
304
|
+
- task:快衰减(完成后快速过期)
|
|
305
|
+
"""
|
|
306
|
+
|
|
307
|
+
BASE_DECAY_RATES: Dict[str, float] = {
|
|
308
|
+
"concept": 0.02,
|
|
309
|
+
"decision": 0.02,
|
|
310
|
+
"insight": 0.01,
|
|
311
|
+
"reflection": 0.02,
|
|
312
|
+
"project": 0.01,
|
|
313
|
+
"execution": 0.04,
|
|
314
|
+
"agent_memory":0.03,
|
|
315
|
+
"task": 0.06,
|
|
316
|
+
"workflow": 0.02,
|
|
317
|
+
}
|
|
318
|
+
# 反馈修正:召回命中的记忆衰减更慢
|
|
319
|
+
HIT_DECAY_BONUS = 0.005 # 每次命中,衰减率 -0.005(更慢)
|
|
320
|
+
MISS_DECAY_BONUS = -0.003 # 每次未命中,衰减率 +0.003(更快)
|
|
321
|
+
|
|
322
|
+
def __init__(self):
|
|
323
|
+
self.decay_overrides: Dict[str, float] = {} # memory_id → custom decay rate
|
|
324
|
+
|
|
325
|
+
def get_decay_rate(self, memory) -> float:
|
|
326
|
+
"""获取记忆的个性化衰减率"""
|
|
327
|
+
if memory.id in self.decay_overrides:
|
|
328
|
+
return self.decay_overrides[memory.id]
|
|
329
|
+
base = self.BASE_DECAY_RATES.get(memory.type, 0.03)
|
|
330
|
+
# 置信度高的记忆衰减更慢
|
|
331
|
+
confidence_bonus = (memory.confidence - 0.5) * 0.01
|
|
332
|
+
return max(0.005, base - confidence_bonus)
|
|
333
|
+
|
|
334
|
+
def should_delete(self, memory, retrievability: float) -> bool:
|
|
335
|
+
"""是否应该删除这条记忆"""
|
|
336
|
+
# concept/insight 类型除非极低才删
|
|
337
|
+
if memory.type in ("concept", "insight", "decision", "reflection"):
|
|
338
|
+
return retrievability < 0.02 and memory.access_count == 0
|
|
339
|
+
return retrievability < 0.05 and memory.access_count == 0
|
|
340
|
+
|
|
341
|
+
def update_from_feedback(self, memory_id: str, mtype: str, was_useful: bool):
|
|
342
|
+
"""根据使用情况调整个性化衰减率"""
|
|
343
|
+
base = self.BASE_DECAY_RATES.get(mtype, 0.03)
|
|
344
|
+
current = self.decay_overrides.get(memory_id, base)
|
|
345
|
+
if was_useful:
|
|
346
|
+
# 有用的记忆衰减更慢
|
|
347
|
+
self.decay_overrides[memory_id] = max(0.005, current + self.HIT_DECAY_BONUS)
|
|
348
|
+
else:
|
|
349
|
+
# 无用的记忆衰减更快
|
|
350
|
+
self.decay_overrides[memory_id] = min(0.15, current - self.MISS_DECAY_BONUS)
|
|
351
|
+
|
|
352
|
+
def to_dict(self) -> dict:
|
|
353
|
+
return {"decay_overrides": self.decay_overrides}
|
|
354
|
+
|
|
355
|
+
@classmethod
|
|
356
|
+
def from_dict(cls, d: dict) -> "ForgetPolicy":
|
|
357
|
+
p = cls()
|
|
358
|
+
p.decay_overrides = d.get("decay_overrides", {})
|
|
359
|
+
return p
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
# ============================================================================
|
|
363
|
+
# Memory Policy Engine(主类)
|
|
364
|
+
# ============================================================================
|
|
365
|
+
|
|
366
|
+
class MemoryPolicyEngine:
|
|
367
|
+
"""
|
|
368
|
+
记忆策略引擎(三个子策略的协调者)
|
|
369
|
+
|
|
370
|
+
使用方式:
|
|
371
|
+
policy = MemoryPolicyEngine("./hmr_data/policy")
|
|
372
|
+
|
|
373
|
+
# 存储决策
|
|
374
|
+
if policy.ingest.should_store(content, ctx):
|
|
375
|
+
mtype = policy.ingest.classify_type(content, ctx)
|
|
376
|
+
conf = policy.ingest.recommend_confidence(content, ctx)
|
|
377
|
+
hmr.ingest(content, memory_type=mtype, metadata={"confidence": conf})
|
|
378
|
+
|
|
379
|
+
# 召回决策
|
|
380
|
+
strategy = policy.recall.select_strategy(query, ctx)
|
|
381
|
+
top_k = policy.recall.decide_top_k(query, ctx)
|
|
382
|
+
result = hmr.recall(query, strategy=strategy, top_k=top_k)
|
|
383
|
+
|
|
384
|
+
# 遗忘决策
|
|
385
|
+
decay_rate = policy.forget.get_decay_rate(memory)
|
|
386
|
+
|
|
387
|
+
# 反馈(让策略从结果中学习)
|
|
388
|
+
policy.record_feedback(
|
|
389
|
+
event_type="recall_hit",
|
|
390
|
+
memory_ids=[mem.id for mem in used_memories],
|
|
391
|
+
signal=0.8
|
|
392
|
+
)
|
|
393
|
+
"""
|
|
394
|
+
|
|
395
|
+
def __init__(self, storage_path: Optional[str] = None):
|
|
396
|
+
self.storage_path = Path(storage_path) if storage_path else None
|
|
397
|
+
self._lock = threading.Lock()
|
|
398
|
+
|
|
399
|
+
self.ingest = IngestPolicy()
|
|
400
|
+
self.recall = RecallPolicy()
|
|
401
|
+
self.forget = ForgetPolicy()
|
|
402
|
+
|
|
403
|
+
# 反馈历史(最近 200 条)
|
|
404
|
+
self._feedback_history: deque = deque(maxlen=200)
|
|
405
|
+
|
|
406
|
+
# 统计
|
|
407
|
+
self._stats = {
|
|
408
|
+
"total_feedback": 0,
|
|
409
|
+
"positive_feedback": 0,
|
|
410
|
+
"negative_feedback": 0,
|
|
411
|
+
"policy_updates": 0,
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
if self.storage_path:
|
|
415
|
+
self.storage_path.mkdir(parents=True, exist_ok=True)
|
|
416
|
+
self._load()
|
|
417
|
+
|
|
418
|
+
# ── 反馈接口 ───────────────────────────────────────────────────────────
|
|
419
|
+
|
|
420
|
+
def record_feedback(
|
|
421
|
+
self,
|
|
422
|
+
event_type: str,
|
|
423
|
+
memory_ids: List[str],
|
|
424
|
+
signal: float,
|
|
425
|
+
context: Optional[Dict[str, Any]] = None,
|
|
426
|
+
query: Optional[str] = None,
|
|
427
|
+
strategy: Optional[str] = None,
|
|
428
|
+
):
|
|
429
|
+
"""
|
|
430
|
+
记录一次策略反馈,并更新权重。
|
|
431
|
+
|
|
432
|
+
event_type:
|
|
433
|
+
recall_hit - 召回结果被实际使用(signal > 0)
|
|
434
|
+
recall_miss - 召回结果完全没用到(signal < 0)
|
|
435
|
+
compress_gain - 压缩后召回质量提升(signal > 0)
|
|
436
|
+
task_success - 完整任务成功(signal = 0.5~1.0)
|
|
437
|
+
task_failure - 任务失败(signal = -0.5~-1.0)
|
|
438
|
+
"""
|
|
439
|
+
event = FeedbackEvent(
|
|
440
|
+
event_type=event_type,
|
|
441
|
+
memory_ids=memory_ids,
|
|
442
|
+
signal=signal,
|
|
443
|
+
context=context or {}
|
|
444
|
+
)
|
|
445
|
+
|
|
446
|
+
with self._lock:
|
|
447
|
+
self._feedback_history.append(event)
|
|
448
|
+
self._stats["total_feedback"] += 1
|
|
449
|
+
if signal > 0:
|
|
450
|
+
self._stats["positive_feedback"] += 1
|
|
451
|
+
else:
|
|
452
|
+
self._stats["negative_feedback"] += 1
|
|
453
|
+
|
|
454
|
+
# 更新各子策略的权重
|
|
455
|
+
self._update_policies(event, query, strategy)
|
|
456
|
+
|
|
457
|
+
# 每次有反馈都保存(确保重启后数据不丢失)
|
|
458
|
+
if self.storage_path:
|
|
459
|
+
self._save()
|
|
460
|
+
|
|
461
|
+
def _update_policies(
|
|
462
|
+
self, event: FeedbackEvent,
|
|
463
|
+
query: Optional[str], strategy: Optional[str]
|
|
464
|
+
):
|
|
465
|
+
ctx = event.context
|
|
466
|
+
signal = event.signal
|
|
467
|
+
|
|
468
|
+
# 更新召回策略
|
|
469
|
+
if event.event_type in ("recall_hit", "recall_miss") and query and strategy:
|
|
470
|
+
features = self.recall._extract_features(query, ctx)
|
|
471
|
+
self.recall.update(strategy, signal, features)
|
|
472
|
+
self.recall.record_hit(signal > 0)
|
|
473
|
+
# 更新遗忘策略
|
|
474
|
+
for mid in event.memory_ids:
|
|
475
|
+
self.forget.update_from_feedback(mid, ctx.get("memory_type", "concept"), signal > 0)
|
|
476
|
+
|
|
477
|
+
# 任务成功/失败 → 更新存储策略
|
|
478
|
+
if event.event_type in ("task_success", "task_failure"):
|
|
479
|
+
for mid in event.memory_ids:
|
|
480
|
+
mtype = ctx.get("memory_type", "concept")
|
|
481
|
+
content = ctx.get("content", "")
|
|
482
|
+
if content:
|
|
483
|
+
features = self.ingest._extract_features(content, ctx)
|
|
484
|
+
self.ingest.update(mid, signal, features, mtype)
|
|
485
|
+
self.forget.update_from_feedback(mid, mtype, signal > 0)
|
|
486
|
+
|
|
487
|
+
self._stats["policy_updates"] += 1
|
|
488
|
+
|
|
489
|
+
# ── 便捷方法(完整存储决策流程)─────────────────────────────────────────
|
|
490
|
+
|
|
491
|
+
def decide_ingest(
|
|
492
|
+
self,
|
|
493
|
+
content: str,
|
|
494
|
+
title: Optional[str] = None,
|
|
495
|
+
tags: Optional[List[str]] = None,
|
|
496
|
+
runtime_dependencies: Optional[List[str]] = None,
|
|
497
|
+
existing_memory_count: int = 0,
|
|
498
|
+
) -> Dict[str, Any]:
|
|
499
|
+
"""
|
|
500
|
+
返回完整的存储决策:是否存、用什么类型、置信度多少
|
|
501
|
+
|
|
502
|
+
返回:
|
|
503
|
+
{
|
|
504
|
+
"should_store": bool,
|
|
505
|
+
"memory_type": str,
|
|
506
|
+
"confidence": float,
|
|
507
|
+
"reasoning": str
|
|
508
|
+
}
|
|
509
|
+
"""
|
|
510
|
+
ctx = {
|
|
511
|
+
"title": title,
|
|
512
|
+
"tags": tags or [],
|
|
513
|
+
"runtime_dependencies": runtime_dependencies or [],
|
|
514
|
+
"existing_memory_count": existing_memory_count,
|
|
515
|
+
"runtime_activity": 0.7,
|
|
516
|
+
"content_overlap": 0.0,
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
should = self.ingest.should_store(content, ctx)
|
|
520
|
+
mtype = self.ingest.classify_type(content, ctx)
|
|
521
|
+
conf = self.ingest.recommend_confidence(content, ctx)
|
|
522
|
+
|
|
523
|
+
type_reasons = {
|
|
524
|
+
"execution": "包含失败/结果记录",
|
|
525
|
+
"decision": "包含决策关键词",
|
|
526
|
+
"reflection": "包含原因分析",
|
|
527
|
+
"concept": "抽象知识内容",
|
|
528
|
+
"task": "任务描述",
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
return {
|
|
532
|
+
"should_store": should,
|
|
533
|
+
"memory_type": mtype,
|
|
534
|
+
"confidence": conf,
|
|
535
|
+
"reasoning": f"{'值得存储' if should else '重复或价值低,跳过'} | "
|
|
536
|
+
f"分类={mtype}({type_reasons.get(mtype, '')})| "
|
|
537
|
+
f"置信度={conf}"
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
def decide_recall(
|
|
541
|
+
self,
|
|
542
|
+
query: str,
|
|
543
|
+
context: Dict[str, Any],
|
|
544
|
+
base_top_k: int = 5
|
|
545
|
+
) -> Dict[str, Any]:
|
|
546
|
+
"""
|
|
547
|
+
返回完整的召回决策:策略和 top_k
|
|
548
|
+
"""
|
|
549
|
+
ctx = dict(context)
|
|
550
|
+
ctx["memory_count"] = ctx.get("total_memories", 0)
|
|
551
|
+
ctx["task_complexity"] = min(1.0, len(ctx.get("pending_tasks", [])) / 5)
|
|
552
|
+
|
|
553
|
+
strategy = self.recall.select_strategy(query, ctx)
|
|
554
|
+
top_k = self.recall.decide_top_k(query, ctx, base_top_k)
|
|
555
|
+
hit_rate = self.recall.get_hit_rate()
|
|
556
|
+
|
|
557
|
+
return {
|
|
558
|
+
"strategy": strategy,
|
|
559
|
+
"top_k": top_k,
|
|
560
|
+
"hit_rate": round(hit_rate, 3),
|
|
561
|
+
"reasoning": f"策略={strategy},top_k={top_k},历史命中率={hit_rate:.0%}"
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
# ── 统计和持久化 ───────────────────────────────────────────────────────
|
|
565
|
+
|
|
566
|
+
def get_stats(self) -> Dict[str, Any]:
|
|
567
|
+
positive_ratio = (
|
|
568
|
+
self._stats["positive_feedback"] /
|
|
569
|
+
max(self._stats["total_feedback"], 1)
|
|
570
|
+
)
|
|
571
|
+
return {
|
|
572
|
+
**self._stats,
|
|
573
|
+
"positive_ratio": round(positive_ratio, 3),
|
|
574
|
+
"recall_hit_rate": round(self.recall.get_hit_rate(), 3),
|
|
575
|
+
"feedback_history_size": len(self._feedback_history),
|
|
576
|
+
"custom_decay_rules": len(self.forget.decay_overrides),
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
def get_policy_weights_summary(self) -> Dict[str, Any]:
|
|
580
|
+
"""返回当前策略权重(用于调试和可视化)"""
|
|
581
|
+
return {
|
|
582
|
+
"ingest_type_bias": {
|
|
583
|
+
mtype: round(sum(w) / len(w), 3)
|
|
584
|
+
for mtype, w in self.ingest.weights.items()
|
|
585
|
+
},
|
|
586
|
+
"recall_strategy_bias": {
|
|
587
|
+
strat: round(sum(w) / len(w), 3)
|
|
588
|
+
for strat, w in self.recall.strategy_weights.items()
|
|
589
|
+
},
|
|
590
|
+
"forget_custom_rules": len(self.forget.decay_overrides),
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
def _save(self):
|
|
594
|
+
if not self.storage_path:
|
|
595
|
+
return
|
|
596
|
+
data = {
|
|
597
|
+
"ingest": self.ingest.to_dict(),
|
|
598
|
+
"recall": self.recall.to_dict(),
|
|
599
|
+
"forget": self.forget.to_dict(),
|
|
600
|
+
"stats": self._stats,
|
|
601
|
+
"feedback_history": [e.to_dict() for e in self._feedback_history],
|
|
602
|
+
"saved_at": datetime.utcnow().isoformat(),
|
|
603
|
+
}
|
|
604
|
+
tmp = self.storage_path / "policy.tmp"
|
|
605
|
+
target = self.storage_path / "policy.json"
|
|
606
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
607
|
+
json.dump(data, f, ensure_ascii=False, indent=2, default=str)
|
|
608
|
+
tmp.replace(target)
|
|
609
|
+
|
|
610
|
+
def _load(self):
|
|
611
|
+
target = self.storage_path / "policy.json"
|
|
612
|
+
if not target.exists():
|
|
613
|
+
return
|
|
614
|
+
try:
|
|
615
|
+
with open(target, "r", encoding="utf-8") as f:
|
|
616
|
+
data = json.load(f)
|
|
617
|
+
self.ingest = IngestPolicy.from_dict(data.get("ingest", {}))
|
|
618
|
+
self.recall = RecallPolicy.from_dict(data.get("recall", {}))
|
|
619
|
+
self.forget = ForgetPolicy.from_dict(data.get("forget", {}))
|
|
620
|
+
self._stats = data.get("stats", self._stats)
|
|
621
|
+
for ev in data.get("feedback_history", []):
|
|
622
|
+
self._feedback_history.append(FeedbackEvent.from_dict(ev))
|
|
623
|
+
print(f"[PolicyEngine] 加载策略,历史反馈 {len(self._feedback_history)} 条")
|
|
624
|
+
except Exception as e:
|
|
625
|
+
print(f"[PolicyEngine] 策略加载失败: {e}")
|