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,176 @@
|
|
|
1
|
+
"""
|
|
2
|
+
框架无关治理中间件的实现。
|
|
3
|
+
|
|
4
|
+
只依赖治理内核(Harness + ThoughtChain + ToolLoopDetector),不碰 Foxclaw 其余部分。
|
|
5
|
+
对外只暴露两个概念:
|
|
6
|
+
· GovernanceSession —— 一次带目标基线的治理会话:observe(每步) + audit(取审计链)+ 循环检测;
|
|
7
|
+
· governed —— 把某个工具函数包成"调用前先过 Harness"的装饰器(同步/异步都支持)。
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import functools
|
|
13
|
+
import tempfile
|
|
14
|
+
import uuid
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Optional, cast
|
|
17
|
+
|
|
18
|
+
from ..harness.harness import Harness
|
|
19
|
+
from ..harness.loop_detection import ToolLoopDetector
|
|
20
|
+
from ..core.thought_chain import NodeType, ThoughtChain, ThoughtNode
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class GovResult:
|
|
25
|
+
"""一步治理判定的结果(框架无关,不泄露 Foxclaw 内部类型)。"""
|
|
26
|
+
status: str
|
|
27
|
+
blocked: bool
|
|
28
|
+
warned: bool
|
|
29
|
+
delta: float
|
|
30
|
+
dimension: str
|
|
31
|
+
reason: Optional[str]
|
|
32
|
+
node_id: str
|
|
33
|
+
scores: dict = field(default_factory=dict)
|
|
34
|
+
loop: Optional[dict] = None
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def tool_violation(self) -> bool:
|
|
38
|
+
"""工具越权(与语言/语义无关的确定性信号)。"""
|
|
39
|
+
return self.scores.get("tool", 0) >= 1.0
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def scope_violation(self) -> bool:
|
|
43
|
+
"""范围蔓延越上限(确定性信号)。"""
|
|
44
|
+
return self.scores.get("scope", 0) >= 1.0
|
|
45
|
+
|
|
46
|
+
def to_dict(self) -> dict:
|
|
47
|
+
return {"status": self.status, "blocked": self.blocked, "warned": self.warned,
|
|
48
|
+
"delta": round(self.delta, 4), "dimension": self.dimension,
|
|
49
|
+
"reason": self.reason, "node_id": self.node_id,
|
|
50
|
+
"scores": {k: round(v, 4) for k, v in self.scores.items()},
|
|
51
|
+
"loop": self.loop}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class GovernanceBlocked(Exception):
|
|
55
|
+
"""被治理层拦截时抛出(供 governed 装饰器/框架回调使用)。"""
|
|
56
|
+
def __init__(self, result: GovResult):
|
|
57
|
+
self.result = result
|
|
58
|
+
super().__init__(f"governance blocked: {result.reason}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class GovernanceSession:
|
|
62
|
+
"""一次治理会话:注册目标基线,之后每步 observe 都过三维漂移 + 循环检测,并落审计链。
|
|
63
|
+
|
|
64
|
+
参数:
|
|
65
|
+
goal —— 任务目标(语义漂移的基线);
|
|
66
|
+
allowed_tools —— 允许的工具类别集合(如 {"read","finance"});越类别即工具越权;
|
|
67
|
+
entities —— 基线实体集(范围蔓延的参照);
|
|
68
|
+
agent_id —— 审计归属标识;
|
|
69
|
+
shadow_rounds —— 观测期轮数(前 N 步只观测不拦截,用真实分布校准阈值);默认 0=即时判定;
|
|
70
|
+
db_path —— 审计链落盘路径;默认临时文件(会话级)。
|
|
71
|
+
|
|
72
|
+
线程/进程无关:不启动任何后台线程,不联网;语义向量用本地缓存模型,缺失自动降级哈希嵌入。
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def __init__(self, goal: str, allowed_tools=None, entities=None,
|
|
76
|
+
agent_id: str = "agent", shadow_rounds: int = 0,
|
|
77
|
+
db_path: str | None = None, policy_path: str | None = None,
|
|
78
|
+
embedding_model: str | None = None):
|
|
79
|
+
self.agent_id = agent_id
|
|
80
|
+
self._session_id = f"gov_{uuid.uuid4().hex[:10]}"
|
|
81
|
+
self.thought_chain = ThoughtChain(
|
|
82
|
+
db_path=db_path or tempfile.mktemp(suffix=".gov.db"))
|
|
83
|
+
self.harness = Harness(
|
|
84
|
+
agent_id=agent_id, thought_chain=self.thought_chain,
|
|
85
|
+
policy_path=policy_path or tempfile.mktemp(suffix=".gov.yaml"),
|
|
86
|
+
shadow_rounds=shadow_rounds, embedding_model=embedding_model)
|
|
87
|
+
self.harness.register_goal(
|
|
88
|
+
goal_text=goal,
|
|
89
|
+
allowed_tool_categories=set(allowed_tools or {"read"}),
|
|
90
|
+
baseline_entities=set(entities or []))
|
|
91
|
+
if shadow_rounds <= 0:
|
|
92
|
+
self.harness._shadow_mode = False
|
|
93
|
+
self._loop = ToolLoopDetector()
|
|
94
|
+
self._blocked_count = 0
|
|
95
|
+
|
|
96
|
+
def observe(self, content: str, tool: str | None = None, entities=None,
|
|
97
|
+
node_type: str | None = None, conf: float = 0.9,
|
|
98
|
+
semantic: bool = True) -> GovResult:
|
|
99
|
+
"""观测一个推理/工具步骤,返回治理判定。不抛异常(判定在结果里)。
|
|
100
|
+
|
|
101
|
+
semantic=False:只按工具/范围维度判定(语义置 0)。用于纯"工具授权"检查——
|
|
102
|
+
工具调用串对目标的语义距离是噪声。"""
|
|
103
|
+
node = ThoughtNode.create(
|
|
104
|
+
session_id=self._session_id, agent_id=self.agent_id,
|
|
105
|
+
type=cast(NodeType, node_type or ("tool_intent" if tool else "reasoning")),
|
|
106
|
+
content=content, conf=conf, tool_name=tool, entities=entities or [])
|
|
107
|
+
self.thought_chain.add_node(node)
|
|
108
|
+
r = self.harness.check(node, ignore_semantic=not semantic)
|
|
109
|
+
loop_warn = None
|
|
110
|
+
if tool:
|
|
111
|
+
lv = self._loop.record(tool, {"content": content})
|
|
112
|
+
if lv.stuck:
|
|
113
|
+
loop_warn = lv.to_dict()
|
|
114
|
+
if r.is_blocked:
|
|
115
|
+
self._blocked_count += 1
|
|
116
|
+
return GovResult(status=r.status, blocked=r.is_blocked, warned=r.is_warned,
|
|
117
|
+
delta=r.delta, dimension=r.dominant_dim, reason=r.reason,
|
|
118
|
+
node_id=node.id, scores=dict(r.scores), loop=loop_warn)
|
|
119
|
+
|
|
120
|
+
def guard(self, content: str, tool: str | None = None, entities=None) -> GovResult:
|
|
121
|
+
"""与 observe 相同,但被 BLOCK 时**抛 GovernanceBlocked**(fail-closed 风格)。"""
|
|
122
|
+
r = self.observe(content, tool=tool, entities=entities)
|
|
123
|
+
if r.blocked:
|
|
124
|
+
raise GovernanceBlocked(r)
|
|
125
|
+
return r
|
|
126
|
+
|
|
127
|
+
def audit(self) -> list[dict]:
|
|
128
|
+
"""取回本会话的完整可审计推理链(带每步 Harness 判定)。"""
|
|
129
|
+
return [n.to_dict() for n in
|
|
130
|
+
self.thought_chain.get_chain(self._session_id, self.agent_id)]
|
|
131
|
+
|
|
132
|
+
def summary(self) -> dict:
|
|
133
|
+
"""治理摘要:总步数/拦截数/漂移趋势(供框架侧上报)。"""
|
|
134
|
+
s = self.thought_chain.get_summary(self.agent_id)
|
|
135
|
+
s["blocked_this_session"] = self._blocked_count
|
|
136
|
+
s["shadow_mode"] = self.harness.is_shadow_mode
|
|
137
|
+
return s
|
|
138
|
+
|
|
139
|
+
def __enter__(self):
|
|
140
|
+
return self
|
|
141
|
+
|
|
142
|
+
def __exit__(self, *exc):
|
|
143
|
+
return False
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def governed(session: GovernanceSession, tool_name: str | None = None, entities=None):
|
|
147
|
+
"""装饰器:把一个工具函数包成"调用前先过 Harness"。
|
|
148
|
+
|
|
149
|
+
命中越权/跑题/范围蔓延 → 抛 GovernanceBlocked,函数不执行。同步/异步函数都支持。
|
|
150
|
+
|
|
151
|
+
gov = GovernanceSession(goal=..., allowed_tools={"read"})
|
|
152
|
+
@governed(gov)
|
|
153
|
+
def delete_row(...): ... # 调用即被拦(delete 不在 read 允许集)
|
|
154
|
+
"""
|
|
155
|
+
def _check(name):
|
|
156
|
+
r = session.observe(f"tool call: {name}", tool=name, entities=entities,
|
|
157
|
+
semantic=False)
|
|
158
|
+
if r.blocked or r.tool_violation or r.scope_violation:
|
|
159
|
+
raise GovernanceBlocked(r)
|
|
160
|
+
|
|
161
|
+
def deco(fn):
|
|
162
|
+
name = tool_name or getattr(fn, "__name__", "tool")
|
|
163
|
+
|
|
164
|
+
if asyncio.iscoroutinefunction(fn):
|
|
165
|
+
@functools.wraps(fn)
|
|
166
|
+
async def awrapper(*a, **kw):
|
|
167
|
+
_check(name)
|
|
168
|
+
return await fn(*a, **kw)
|
|
169
|
+
return awrapper
|
|
170
|
+
|
|
171
|
+
@functools.wraps(fn)
|
|
172
|
+
def wrapper(*a, **kw):
|
|
173
|
+
_check(name)
|
|
174
|
+
return fn(*a, **kw)
|
|
175
|
+
return wrapper
|
|
176
|
+
return deco
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Foxclaw — Harness: 跨层约束-校准机制"""
|
|
2
|
+
from .harness import (
|
|
3
|
+
Harness,
|
|
4
|
+
HarnessResult,
|
|
5
|
+
GoalBaseline,
|
|
6
|
+
SemanticDrift,
|
|
7
|
+
ToolIntentDrift,
|
|
8
|
+
ScopeCreepDrift,
|
|
9
|
+
HarnessEventBus,
|
|
10
|
+
TOOL_CATEGORIES,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"Harness", "HarnessResult", "GoalBaseline",
|
|
15
|
+
"SemanticDrift", "ToolIntentDrift", "ScopeCreepDrift",
|
|
16
|
+
"HarnessEventBus", "TOOL_CATEGORIES",
|
|
17
|
+
]
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Harness 基础设施:contextvar 分槽 + 工具类别白名单 + 结果/基线数据类。"""
|
|
2
|
+
import contextvars
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from ..core.thought_chain import HarnessStatus
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
_harness_ctx: contextvars.ContextVar = contextvars.ContextVar(
|
|
12
|
+
"foxclaw_harness_ctx", default=None)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _harness_ctx_get(token: str):
|
|
16
|
+
return (_harness_ctx.get() or {}).get(token)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _harness_ctx_set(token: str, baseline):
|
|
20
|
+
d = dict(_harness_ctx.get() or {})
|
|
21
|
+
d[token] = baseline
|
|
22
|
+
_harness_ctx.set(d)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
TOOL_CATEGORIES: dict[str, set[str]] = {
|
|
26
|
+
"read": {"read_file", "search", "fetch", "list", "get", "query"},
|
|
27
|
+
"write": {"write_file", "create", "update", "save", "append"},
|
|
28
|
+
"delete": {"delete", "remove", "drop", "clear", "reset"},
|
|
29
|
+
"exec": {"run_code", "shell", "subprocess", "execute"},
|
|
30
|
+
"network": {"http_get", "http_post", "scrape", "download"},
|
|
31
|
+
"calendar": {"add_event", "get_schedule", "update_event"},
|
|
32
|
+
"finance": {"get_balance", "add_transaction", "generate_report"},
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class HarnessResult:
|
|
38
|
+
status: HarnessStatus
|
|
39
|
+
delta: float
|
|
40
|
+
dominant_dim: str
|
|
41
|
+
scores: dict
|
|
42
|
+
reason: Optional[str] = None
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def is_blocked(self) -> bool:
|
|
46
|
+
return self.status == "BLOCK"
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def is_warned(self) -> bool:
|
|
50
|
+
return self.status == "WARN"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class GoalBaseline:
|
|
55
|
+
"""目标基线 — 在接口层注册,后续所有层的校验参照此基线"""
|
|
56
|
+
goal_text: str
|
|
57
|
+
allowed_tool_categories: set[str]
|
|
58
|
+
baseline_entities: set[str]
|
|
59
|
+
goal_embedding: Optional[np.ndarray] = None
|
|
60
|
+
|
|
61
|
+
def to_dict(self) -> dict:
|
|
62
|
+
return {
|
|
63
|
+
"goal_text": self.goal_text,
|
|
64
|
+
"allowed_tool_categories": list(self.allowed_tool_categories),
|
|
65
|
+
"baseline_entities": list(self.baseline_entities),
|
|
66
|
+
}
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""Harness Policy 学习 + 影子观察 + 阈值校准 + 持久化(mixin)。
|
|
2
|
+
|
|
3
|
+
拆分自 harness.py:`Harness` 主类继承本 mixin,通过 `self.weights/_policy/_lock`
|
|
4
|
+
等实例状态协同工作。纯搬移、零行为变更。
|
|
5
|
+
"""
|
|
6
|
+
import os
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, TYPE_CHECKING
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import yaml
|
|
13
|
+
|
|
14
|
+
from ..core.thought_chain import ThoughtNode
|
|
15
|
+
from ._base import HarnessResult
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from .event_bus import HarnessEventBus
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PolicyMixin:
|
|
22
|
+
agent_id: str
|
|
23
|
+
bus: "HarnessEventBus"
|
|
24
|
+
policy_path: Path
|
|
25
|
+
weights: dict[str, float]
|
|
26
|
+
promote_min_obs: int
|
|
27
|
+
_policy: dict
|
|
28
|
+
_baseline: Any
|
|
29
|
+
_delta_history: list[float]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _reindex_learned_actions(self):
|
|
33
|
+
"""把 self._policy['rules'] 里已学习的 action 编译成 check() 用得上的结构。
|
|
34
|
+
|
|
35
|
+
使自学习从「权重级」升级到「规则级」:BLOCK 时 _generate_policy_action 生成的
|
|
36
|
+
penalize_tool / restrict_scope 不再只是躺在 YAML 里的意图,而是被这里编译、
|
|
37
|
+
并在 check() 里真正改变判定。加载 policy 时 + 每次新学到规则后都会重建。
|
|
38
|
+
"""
|
|
39
|
+
penalized: set[str] = set()
|
|
40
|
+
scope_limit: int | None = None
|
|
41
|
+
for rule in self._policy.get("rules", []):
|
|
42
|
+
action = rule.get("action") or {}
|
|
43
|
+
atype = action.get("type")
|
|
44
|
+
if atype == "penalize_tool":
|
|
45
|
+
pat = action.get("tool_pattern")
|
|
46
|
+
if pat:
|
|
47
|
+
penalized.add(pat)
|
|
48
|
+
elif atype == "restrict_scope":
|
|
49
|
+
lim = action.get("entity_expansion_limit")
|
|
50
|
+
if isinstance(lim, int):
|
|
51
|
+
scope_limit = lim if scope_limit is None else min(scope_limit, lim)
|
|
52
|
+
self._penalized_tools = penalized
|
|
53
|
+
self._scope_limit = scope_limit
|
|
54
|
+
|
|
55
|
+
def _is_penalized_tool(self, tool_name: str) -> bool:
|
|
56
|
+
"""工具名是否命中已学习的 penalize_tool 规则(与 ToolIntentDrift 一致的子串匹配)。"""
|
|
57
|
+
if not tool_name or not self._penalized_tools:
|
|
58
|
+
return False
|
|
59
|
+
return any(tool_name == p or p in tool_name for p in self._penalized_tools)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
_LEARNABLE_RULE_DIMS = frozenset({"tool", "scope"})
|
|
63
|
+
|
|
64
|
+
def _trigger_policy_learning(self, node: ThoughtNode, result: HarnessResult):
|
|
65
|
+
"""BLOCK 事件 → 规则候选进 **shadow_rules(不生效)** → 影子观察 → promote/discard。
|
|
66
|
+
|
|
67
|
+
【P0-1】原为「BLOCK → 规则直接写 rules + reindex → 下次 check 立即生效」——
|
|
68
|
+
在线无验证学习是真实风险(一次偶发 BLOCK 就永久改变判定)。改后:
|
|
69
|
+
· 规则级:候选进 shadow_rules,观察 N 次达标才 promote(生效)/discard;
|
|
70
|
+
· 权重级:保持现状(触发维度 +0.05 归一化)——文稿只影子化规则级,权重微调风险低;
|
|
71
|
+
· 边界:semantic 仅权重级不生成规则;未知维度连权重都不学,只记录。
|
|
72
|
+
"""
|
|
73
|
+
dim = result.dominant_dim
|
|
74
|
+
|
|
75
|
+
if dim not in self.weights:
|
|
76
|
+
self._record_history("skip", "",
|
|
77
|
+
note=f"未知维度 '{dim}' 禁止自学习(fail-closed)")
|
|
78
|
+
self._save_policy()
|
|
79
|
+
return
|
|
80
|
+
|
|
81
|
+
if dim in self._LEARNABLE_RULE_DIMS:
|
|
82
|
+
new_rule: dict[str, Any] = {
|
|
83
|
+
"id": f"rule_{node.id}",
|
|
84
|
+
"trigger": {
|
|
85
|
+
"harness_status": "BLOCK",
|
|
86
|
+
"dominant_dim": dim,
|
|
87
|
+
"delta_threshold": round(result.delta, 3),
|
|
88
|
+
},
|
|
89
|
+
"action": self._generate_policy_action(node, result),
|
|
90
|
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
91
|
+
"source": "harness_learned",
|
|
92
|
+
"agent_id": self.agent_id,
|
|
93
|
+
"shadow": {
|
|
94
|
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
95
|
+
"observations": 0, "would_block": 0, "would_pass": 0,
|
|
96
|
+
"status": "observing",
|
|
97
|
+
},
|
|
98
|
+
}
|
|
99
|
+
self._policy.setdefault("shadow_rules", []).append(new_rule)
|
|
100
|
+
self._record_history("propose", new_rule["id"],
|
|
101
|
+
note=f"{dim} 维度 BLOCK → 影子观察")
|
|
102
|
+
self.bus.emit("shadow_rule_proposed", {
|
|
103
|
+
"agent_id": self.agent_id, "rule_id": new_rule["id"],
|
|
104
|
+
"dominant_dim": dim,
|
|
105
|
+
"action_type": new_rule["action"].get("type", ""),
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
bumped = dict(self.weights)
|
|
109
|
+
bumped[dim] = min(bumped[dim] + 0.05, 0.8)
|
|
110
|
+
total = sum(bumped.values())
|
|
111
|
+
self.weights = {k: v / total for k, v in bumped.items()}
|
|
112
|
+
|
|
113
|
+
self._save_policy()
|
|
114
|
+
self.bus.emit("policy_updated", {
|
|
115
|
+
"agent_id": self.agent_id,
|
|
116
|
+
"rule_id": "",
|
|
117
|
+
"dominant_dim": dim,
|
|
118
|
+
"new_weights": dict(self.weights),
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _observe_shadow_rules(self, node: ThoughtNode, result: HarnessResult,
|
|
123
|
+
real_scores: dict):
|
|
124
|
+
"""对观察中的影子规则做双轨计数,达标后 promote/discard。锁内调用。
|
|
125
|
+
|
|
126
|
+
适用性:当前场景的 dominant_dim 与规则 trigger.dominant_dim 相同。
|
|
127
|
+
(trigger.delta_threshold 仅记录生成时的漂移强度,不作匹配条件——否则
|
|
128
|
+
observations 几乎无法积累,影子机制会失去意义。)
|
|
129
|
+
|
|
130
|
+
落盘节流:promote/discard 立即 save;普通计数每 10 次 save 一次(进程崩溃
|
|
131
|
+
最多丢 9 次观察计数,可接受)——否则「有影子规则时每次 check 都写 YAML」,
|
|
132
|
+
一次任务几十次 check 就是几十次磁盘写。
|
|
133
|
+
"""
|
|
134
|
+
need_save = False
|
|
135
|
+
for rule in list(self._policy.get("shadow_rules", [])):
|
|
136
|
+
sh = rule.get("shadow") or {}
|
|
137
|
+
if sh.get("status") != "observing":
|
|
138
|
+
continue
|
|
139
|
+
trig = rule.get("trigger") or {}
|
|
140
|
+
if trig.get("dominant_dim") != result.dominant_dim:
|
|
141
|
+
continue
|
|
142
|
+
|
|
143
|
+
sh["observations"] = sh.get("observations", 0) + 1
|
|
144
|
+
|
|
145
|
+
shadow_status = self._status_with_action(rule, node, real_scores)
|
|
146
|
+
real_blocked = result.is_blocked
|
|
147
|
+
shadow_blocked = shadow_status == "BLOCK"
|
|
148
|
+
if shadow_blocked and not real_blocked:
|
|
149
|
+
sh["would_block"] = sh.get("would_block", 0) + 1
|
|
150
|
+
elif not shadow_blocked and real_blocked:
|
|
151
|
+
sh["would_pass"] = sh.get("would_pass", 0) + 1
|
|
152
|
+
|
|
153
|
+
verdict = self._should_promote(sh)
|
|
154
|
+
if verdict is True:
|
|
155
|
+
self._promote_rule(rule)
|
|
156
|
+
need_save = True
|
|
157
|
+
elif verdict is False:
|
|
158
|
+
self._discard_rule(rule, "影子证据不达标")
|
|
159
|
+
need_save = True
|
|
160
|
+
elif sh["observations"] % 10 == 0:
|
|
161
|
+
need_save = True
|
|
162
|
+
if need_save:
|
|
163
|
+
self._save_policy()
|
|
164
|
+
|
|
165
|
+
def _status_with_action(self, rule: dict, node: ThoughtNode,
|
|
166
|
+
real_scores: dict) -> str:
|
|
167
|
+
"""模拟应用单条影子规则的 action,给出「若它生效」的判定(复用同一权重/阈值)。"""
|
|
168
|
+
scores = dict(real_scores)
|
|
169
|
+
action = rule.get("action") or {}
|
|
170
|
+
atype = action.get("type")
|
|
171
|
+
if atype == "penalize_tool":
|
|
172
|
+
pat = action.get("tool_pattern", "")
|
|
173
|
+
tool_name = getattr(node, "tool_name", "") or ""
|
|
174
|
+
if pat and tool_name and (tool_name == pat or pat in tool_name):
|
|
175
|
+
scores["tool"] = 1.0
|
|
176
|
+
elif atype == "restrict_scope":
|
|
177
|
+
lim = action.get("entity_expansion_limit")
|
|
178
|
+
baseline = self._baseline
|
|
179
|
+
if isinstance(lim, int) and baseline is not None and baseline.baseline_entities:
|
|
180
|
+
new_entities = set(node.entities) - baseline.baseline_entities
|
|
181
|
+
if len(new_entities) > lim:
|
|
182
|
+
scores["scope"] = 1.0
|
|
183
|
+
delta = sum(self.weights[k] * v for k, v in scores.items())
|
|
184
|
+
if delta > self._block_threshold:
|
|
185
|
+
return "BLOCK"
|
|
186
|
+
if delta > self._warn_threshold:
|
|
187
|
+
return "WARN"
|
|
188
|
+
return "PASS"
|
|
189
|
+
|
|
190
|
+
def _should_promote(self, sh: dict):
|
|
191
|
+
"""影子证据判定(文稿第四步):True=promote / False=discard / None=继续观察。"""
|
|
192
|
+
obs = sh.get("observations", 0)
|
|
193
|
+
if obs < self.promote_min_obs:
|
|
194
|
+
return None
|
|
195
|
+
wb, wp = sh.get("would_block", 0), sh.get("would_pass", 0)
|
|
196
|
+
if wb / max(obs, 1) > 0.3:
|
|
197
|
+
return False
|
|
198
|
+
if wb == 0 and wp == 0:
|
|
199
|
+
return False
|
|
200
|
+
return True
|
|
201
|
+
|
|
202
|
+
def _promote_rule(self, rule: dict):
|
|
203
|
+
"""影子 → 生效:移入 rules、重建索引、记 history、发事件。"""
|
|
204
|
+
rule.get("shadow", {})["status"] = "promoted"
|
|
205
|
+
self._policy.setdefault("shadow_rules", []).remove(rule)
|
|
206
|
+
rule.pop("shadow", None)
|
|
207
|
+
self._policy.setdefault("rules", []).append(rule)
|
|
208
|
+
self._reindex_learned_actions()
|
|
209
|
+
self._record_history("promote", rule["id"],
|
|
210
|
+
note=f"观察达标升迁(维度 {rule.get('trigger', {}).get('dominant_dim', '?')})")
|
|
211
|
+
self.bus.emit("shadow_rule_promoted", {
|
|
212
|
+
"agent_id": self.agent_id, "rule_id": rule["id"],
|
|
213
|
+
"dominant_dim": rule.get("trigger", {}).get("dominant_dim", ""),
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
def _discard_rule(self, rule: dict, why: str):
|
|
217
|
+
"""影子证据不达标:标记 discarded(保留供审计回放,不再参与双轨评估)。"""
|
|
218
|
+
sh = rule.get("shadow") or {}
|
|
219
|
+
sh["status"] = "discarded"
|
|
220
|
+
self._record_history("discard", rule.get("id", ""), note=why)
|
|
221
|
+
self.bus.emit("shadow_rule_discarded", {
|
|
222
|
+
"agent_id": self.agent_id, "rule_id": rule.get("id", ""),
|
|
223
|
+
"reason": why,
|
|
224
|
+
"observations": sh.get("observations", 0),
|
|
225
|
+
"would_block": sh.get("would_block", 0),
|
|
226
|
+
"would_pass": sh.get("would_pass", 0),
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
def rollback(self, rule_id: str) -> bool:
|
|
230
|
+
"""【P0-1 回滚】把一条已生效规则撤出生效集(误 promote 的后悔药)。
|
|
231
|
+
|
|
232
|
+
规则从 rules 移回 shadow_rules 并标记 rolled_back(不再生效、保留可审计),
|
|
233
|
+
重建索引 + 记 history + 发事件。找不到返回 False。"""
|
|
234
|
+
for rule in list(self._policy.get("rules", [])):
|
|
235
|
+
if rule.get("id") != rule_id:
|
|
236
|
+
continue
|
|
237
|
+
self._policy["rules"].remove(rule)
|
|
238
|
+
rule["shadow"] = {
|
|
239
|
+
"created_at": rule.get("created_at", ""),
|
|
240
|
+
"observations": 0, "would_block": 0, "would_pass": 0,
|
|
241
|
+
"status": "rolled_back",
|
|
242
|
+
}
|
|
243
|
+
self._policy.setdefault("shadow_rules", []).append(rule)
|
|
244
|
+
self._reindex_learned_actions()
|
|
245
|
+
self._record_history("rollback", rule_id, note="人工/自动回滚")
|
|
246
|
+
self._save_policy()
|
|
247
|
+
self.bus.emit("shadow_rule_rolled_back", {
|
|
248
|
+
"agent_id": self.agent_id, "rule_id": rule_id,
|
|
249
|
+
})
|
|
250
|
+
return True
|
|
251
|
+
return False
|
|
252
|
+
|
|
253
|
+
def _record_history(self, event: str, rule_id: str, note: str = ""):
|
|
254
|
+
"""policy YAML 的 history 段(文稿第六步):propose/promote/discard/rollback/skip 全轨迹。
|
|
255
|
+
有界保留最近 500 条(与库内有界日志惯例一致)。"""
|
|
256
|
+
hist = self._policy.setdefault("history", [])
|
|
257
|
+
hist.append({
|
|
258
|
+
"ts": datetime.now(timezone.utc).isoformat(),
|
|
259
|
+
"event": event, "rule_id": rule_id,
|
|
260
|
+
"version": self._policy.get("version", 1),
|
|
261
|
+
"note": note[:200],
|
|
262
|
+
})
|
|
263
|
+
if len(hist) > 500:
|
|
264
|
+
del hist[:-500]
|
|
265
|
+
|
|
266
|
+
def _generate_policy_action(self, node: ThoughtNode, result: HarnessResult) -> dict:
|
|
267
|
+
"""生成结构化策略动作,随 learned rule 持久化到 policy 文件。
|
|
268
|
+
|
|
269
|
+
自学习现在**两级都生效**:
|
|
270
|
+
· 权重级 —— _trigger_policy_learning 里对触发维度 +0.05 并归一化,影响后续 delta;
|
|
271
|
+
· 规则级 —— 本函数生成的 action 由 _reindex_learned_actions 编译,并在 check() 里应用:
|
|
272
|
+
- penalize_tool → 命中工具的 tool 分被抬到 1.0(即便类别本在允许集里);
|
|
273
|
+
- restrict_scope → 新增实体数超过 entity_expansion_limit 时 scope 分抬到 1.0。
|
|
274
|
+
(increase_semantic_threshold 仍主要靠权重级体现,未单列规则应用。)
|
|
275
|
+
因此这些 action 不再只是"意图记录"——penalize_tool / restrict_scope 会真正改变判定。
|
|
276
|
+
"""
|
|
277
|
+
dim = result.dominant_dim
|
|
278
|
+
if dim == "tool" and node.tool_name:
|
|
279
|
+
return {
|
|
280
|
+
"type": "penalize_tool",
|
|
281
|
+
"tool_pattern": node.tool_name,
|
|
282
|
+
"weight_delta": -0.3,
|
|
283
|
+
}
|
|
284
|
+
elif dim == "scope":
|
|
285
|
+
return {
|
|
286
|
+
"type": "restrict_scope",
|
|
287
|
+
"entity_expansion_limit": 2,
|
|
288
|
+
}
|
|
289
|
+
else:
|
|
290
|
+
return {
|
|
291
|
+
"type": "increase_semantic_threshold",
|
|
292
|
+
"delta": -0.05,
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _calibrate_thresholds(self):
|
|
297
|
+
"""Shadow mode 结束 — 用真实 Δ 分布校准阈值。
|
|
298
|
+
关键:阈值要设在"正常任务分布"之上,这样正常任务通过,
|
|
299
|
+
只有真正离群的(如完全跑题)才被拦截。
|
|
300
|
+
否则用中位数附近的分位数会拦掉一半正常流量。
|
|
301
|
+
"""
|
|
302
|
+
arr = np.array(sorted(self._delta_history), dtype=np.float64)
|
|
303
|
+
if arr.size == 0:
|
|
304
|
+
self._shadow_mode = False
|
|
305
|
+
return
|
|
306
|
+
mean = float(arr.mean())
|
|
307
|
+
std = float(arr.std())
|
|
308
|
+
p90 = float(np.percentile(arr, 90))
|
|
309
|
+
block = max(p90, mean + 1.5 * std) * 1.10
|
|
310
|
+
warn = block * 0.8
|
|
311
|
+
self._block_threshold = max(block, 0.25)
|
|
312
|
+
self._warn_threshold = max(warn, 0.18)
|
|
313
|
+
self._shadow_mode = False
|
|
314
|
+
self.bus.emit("shadow_calibrated", {
|
|
315
|
+
"agent_id": self.agent_id,
|
|
316
|
+
"warn_threshold": self._warn_threshold,
|
|
317
|
+
"block_threshold": self._block_threshold,
|
|
318
|
+
"sample_size": len(arr),
|
|
319
|
+
"mean": round(mean, 3),
|
|
320
|
+
"std": round(std, 3),
|
|
321
|
+
})
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _load_policy(self) -> dict:
|
|
325
|
+
if self.policy_path.exists():
|
|
326
|
+
with open(self.policy_path, encoding="utf-8") as f:
|
|
327
|
+
return yaml.safe_load(f) or {}
|
|
328
|
+
return {
|
|
329
|
+
"version": 1,
|
|
330
|
+
"agent_id": self.agent_id,
|
|
331
|
+
"rules": [],
|
|
332
|
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
def _save_policy(self):
|
|
336
|
+
os.makedirs(self.policy_path.parent, exist_ok=True)
|
|
337
|
+
self._policy["version"] = self._policy.get("version", 1) + 1
|
|
338
|
+
self._policy["updated_at"] = datetime.now(timezone.utc).isoformat()
|
|
339
|
+
with open(self.policy_path, "w", encoding="utf-8") as f:
|
|
340
|
+
yaml.dump(self._policy, f, allow_unicode=True, sort_keys=False)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Harness 三个检测维度:语义距离 / 工具意图 / 范围蔓延。"""
|
|
2
|
+
import hashlib
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
from sklearn.metrics.pairwise import cosine_similarity
|
|
6
|
+
|
|
7
|
+
from ._base import TOOL_CATEGORIES
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SemanticDrift:
|
|
11
|
+
"""维度一:语义距离。优先 sentence-transformers,不可用则降级 n-gram 哈希嵌入。"""
|
|
12
|
+
|
|
13
|
+
DIM = 256
|
|
14
|
+
|
|
15
|
+
def __init__(self, model_name: str = "all-MiniLM-L6-v2"):
|
|
16
|
+
from ..capability.embedding_service import get_text_embedder
|
|
17
|
+
self._model = get_text_embedder(model_name)
|
|
18
|
+
self._mode = "transformer" if self._model is not None else "hash"
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def mode(self) -> str:
|
|
22
|
+
return self._mode
|
|
23
|
+
|
|
24
|
+
def _encode(self, text: str) -> np.ndarray:
|
|
25
|
+
if self._mode == "transformer":
|
|
26
|
+
return self._model.encode(text)
|
|
27
|
+
return self._hash_embed(text)
|
|
28
|
+
|
|
29
|
+
def _hash_embed(self, text: str) -> np.ndarray:
|
|
30
|
+
"""字符 3-gram 哈希到固定维向量。余弦相似度数学真实,只是不带语义模型。"""
|
|
31
|
+
vec = np.zeros(self.DIM, dtype=np.float32)
|
|
32
|
+
text = (text or "").lower().strip()
|
|
33
|
+
if not text:
|
|
34
|
+
return vec
|
|
35
|
+
grams = [text[i:i+3] for i in range(max(len(text) - 2, 1))]
|
|
36
|
+
for g in grams:
|
|
37
|
+
h = int(hashlib.md5(g.encode("utf-8")).hexdigest(), 16)
|
|
38
|
+
idx = h % self.DIM
|
|
39
|
+
sign = 1.0 if (h // self.DIM) % 2 == 0 else -1.0
|
|
40
|
+
vec[idx] += sign
|
|
41
|
+
norm = np.linalg.norm(vec)
|
|
42
|
+
return vec / norm if norm > 0 else vec
|
|
43
|
+
|
|
44
|
+
def encode(self, text: str) -> np.ndarray:
|
|
45
|
+
"""把文本编码成向量(纯函数,无副作用)。每任务基线自持此向量,并发安全。"""
|
|
46
|
+
return self._encode(text)
|
|
47
|
+
|
|
48
|
+
def score(self, content: str, baseline_vec: np.ndarray) -> float:
|
|
49
|
+
"""内容相对**每任务基线向量**的语义漂移。baseline_vec 由调用方(check)显式传入,
|
|
50
|
+
不再用共享的实例级基线 → 并发顶层任务的语义基线互不覆盖。"""
|
|
51
|
+
if baseline_vec is None:
|
|
52
|
+
return 0.0
|
|
53
|
+
node_vec = self._encode(content)
|
|
54
|
+
sim = cosine_similarity([baseline_vec], [node_vec])[0][0]
|
|
55
|
+
return float(min(1.0, max(0.0, 1.0 - sim)))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ToolIntentDrift:
|
|
59
|
+
"""维度二:工具意图"""
|
|
60
|
+
|
|
61
|
+
def score(self, tool_name: str, allowed_categories: set[str]) -> float:
|
|
62
|
+
if not tool_name:
|
|
63
|
+
return 0.0
|
|
64
|
+
for cat, patterns in TOOL_CATEGORIES.items():
|
|
65
|
+
if any(tool_name.startswith(p) or p in tool_name for p in patterns):
|
|
66
|
+
return 0.0 if cat in allowed_categories else 1.0
|
|
67
|
+
return 0.3
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ScopeCreepDrift:
|
|
71
|
+
"""维度三:范围蔓延"""
|
|
72
|
+
|
|
73
|
+
def score(self, node_entities: set[str], baseline_entities: set[str]) -> float:
|
|
74
|
+
if not baseline_entities:
|
|
75
|
+
return 0.0
|
|
76
|
+
new_entities = node_entities - baseline_entities
|
|
77
|
+
return min(len(new_entities) / max(len(baseline_entities), 1), 1.0)
|