bugx-cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (338) hide show
  1. package/README.md +193 -185
  2. package/core/README.md +2 -2
  3. package/core/agent/README.md +2 -1
  4. package/core/agent/agent_artifacts.py +8 -6
  5. package/core/agent/agent_eval.py +136 -54
  6. package/core/agent/agent_execution.py +218 -52
  7. package/core/agent/agent_orchestrator.py +14 -8
  8. package/core/agent/agent_targets.py +8 -2
  9. package/core/agent/feature_baseline.py +150 -0
  10. package/core/assets/README.md +3 -2
  11. package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  12. package/core/assets/axe-core/LICENSE.txt +362 -0
  13. package/core/assets/axe-core/UPSTREAM.md +10 -0
  14. package/core/assets/axe-core/axe.min.js +12 -0
  15. package/core/assets/bugx-hero-en.svg +74 -0
  16. package/core/assets/bugx-hero-zh.svg +74 -0
  17. package/core/assets/bugx-social-preview.svg +71 -0
  18. package/core/assets/bugx-wechat-group.png +0 -0
  19. package/core/assets/codex.png +0 -0
  20. package/core/assets/dsh.png +0 -0
  21. package/core/assets/webui-chatgpt.jpg +0 -0
  22. package/core/assets/webui-session.jpg +0 -0
  23. package/core/assets/webui-skills.jpg +0 -0
  24. package/core/assets/webui-studio.jpg +0 -0
  25. package/core/assets/webui-zcode.jpg +0 -0
  26. package/core/assets/zcode.png +0 -0
  27. package/core/audit_packs/README.md +2 -0
  28. package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
  29. package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
  30. package/core/audit_packs/pitfalls/go_backend.json +66 -0
  31. package/core/audit_packs/pitfalls/java_spring.json +64 -0
  32. package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
  33. package/core/audit_packs/pitfalls/python_web.json +82 -0
  34. package/core/autonomous_cve/SPEC.md +1 -1
  35. package/core/autonomous_cve/attack_graph_store.py +152 -106
  36. package/core/autonomous_cve/behavior_graph.py +8 -2
  37. package/core/autonomous_cve/verifier.py +4 -1
  38. package/core/bugx.md +1 -1
  39. package/core/bugx_paths.py +43 -8
  40. package/core/cli-help.txt +66 -0
  41. package/core/cloud_sync/SPEC.md +1 -1
  42. package/core/cloud_sync/cloud_client.py +81 -11
  43. package/core/cloud_sync/cloud_onboard.py +42 -1
  44. package/core/cloud_sync/consent.py +33 -3
  45. package/core/cloud_sync/flywheel_client.py +186 -15
  46. package/core/cloud_sync/network_transport.py +24 -3
  47. package/core/cloud_sync/sensitive_filter.py +2 -2
  48. package/core/cloud_sync/sync_push.py +12 -10
  49. package/core/contracts/AGENT_GUIDE.md +6 -9
  50. package/core/contracts/README.md +2 -2
  51. package/core/contracts/bugx-runtime-contract.md +1 -1
  52. package/core/contracts/bugx-worker.md +1 -1
  53. package/core/contracts/engine_gap_contracts.py +86 -3
  54. package/core/coverage/coverage_discovery.py +599 -29
  55. package/core/coverage/coverage_evidence.py +47 -0
  56. package/core/coverage/coverage_forensics.py +9 -0
  57. package/core/coverage/coverage_validate.py +6 -1
  58. package/core/dev_harness/SPEC.md +1 -1
  59. package/core/engine-integrity.json +670 -442
  60. package/core/fuzzing/concurrency_fuzzer.py +53 -0
  61. package/core/fuzzing/differential_oracle.py +562 -27
  62. package/core/fuzzing/fuzz_input.py +109 -6
  63. package/core/fuzzing/stateful_fuzzer.py +72 -0
  64. package/core/governance/secret_redactor.py +22 -10
  65. package/core/host_acp/SPEC.md +1 -1
  66. package/core/host_acp/__init__.py +4 -4
  67. package/core/host_acp/claude.py +59 -1
  68. package/core/host_acp/cline.py +64 -1
  69. package/core/host_acp/codex.py +56 -1
  70. package/core/host_acp/dsh.py +59 -1
  71. package/core/host_acp/opencode.py +56 -1
  72. package/core/host_acp/pi.py +59 -1
  73. package/core/host_acp/zcode.py +59 -1
  74. package/core/host_runtime/SPEC.md +1 -1
  75. package/core/host_runtime/adapters.py +1 -1
  76. package/core/host_runtime/cline.py +13 -0
  77. package/core/host_runtime/host_evaluators.py +44 -4
  78. package/core/host_runtime/host_probe.py +1 -1
  79. package/core/host_runtime/host_provider_arbitrator.py +116 -62
  80. package/core/host_runtime/host_registry.py +15 -8
  81. package/core/host_runtime/mcp_registry_gate.py +12 -1
  82. package/core/host_runtime/pi.py +102 -0
  83. package/core/host_runtime/provider_facts.py +66 -0
  84. package/core/hosts/SPEC.md +1 -1
  85. package/core/hosts/__init__.py +6 -2
  86. package/core/hosts/_dsh_usage.py +1 -1
  87. package/core/hosts/base.py +32 -4
  88. package/core/hosts/claude.py +55 -0
  89. package/core/hosts/cline.py +6 -2
  90. package/core/hosts/codex.py +58 -0
  91. package/core/hosts/dsh.py +9 -1
  92. package/core/hosts/opencode.py +6 -6
  93. package/core/hosts/pi.py +159 -2
  94. package/core/infra/README.md +4 -2
  95. package/core/infra/__init__.py +2 -0
  96. package/core/infra/build_info.py +22 -3
  97. package/core/infra/client_metadata.py +1 -1
  98. package/core/infra/json_utils.py +22 -0
  99. package/core/launch_phases/README.md +6 -3
  100. package/core/launch_phases/SPEC.md +1 -1
  101. package/core/launch_phases/common.py +21 -2
  102. package/core/launch_phases/finding_confirm_phase.py +170 -5
  103. package/core/launch_phases/finding_settlement.py +188 -1
  104. package/core/launch_phases/judge_phase.py +69 -12
  105. package/core/launch_phases/orchestrator_controls.py +11 -7
  106. package/core/launch_phases/post_coverage_sync.py +9 -2
  107. package/core/launch_phases/post_phase.py +144 -8
  108. package/core/launch_phases/post_receipt.py +12 -1
  109. package/core/launch_phases/pre_phase.py +3 -3
  110. package/core/launch_phases/pre_recon_scout.py +66 -36
  111. package/core/launch_phases/pre_state_builder.py +23 -176
  112. package/core/launch_phases/report_sharing.py +3 -7
  113. package/core/launch_phases/round_orchestrator.py +129 -58
  114. package/core/launch_phases/semantic_recon.py +545 -0
  115. package/core/launch_phases/session_runtime.py +56 -9
  116. package/core/launch_phases/startup_gates.py +36 -8
  117. package/core/launch_phases/startup_interaction.py +68 -12
  118. package/core/launch_phases/startup_version_gate.py +13 -3
  119. package/core/launch_phases/supervisor_bridge.py +46 -17
  120. package/core/launch_phases/supervisor_coverage.py +8 -2
  121. package/core/launch_phases/supervisor_degraded.py +1 -9
  122. package/core/launch_phases/verify_loop.py +767 -0
  123. package/core/launch_phases/worker_barriers.py +15 -5
  124. package/core/launch_phases/worker_orchestrator.py +105 -25
  125. package/core/launch_phases/worker_prior.py +115 -0
  126. package/core/ledger/README.md +2 -1
  127. package/core/ledger/SPEC.md +1 -1
  128. package/core/ledger/_facade.py +2 -1
  129. package/core/ledger/archive_ops.py +60 -2
  130. package/core/ledger/cli.py +6 -1
  131. package/core/ledger/export_ops.py +6 -1
  132. package/core/ledger/finding_confirmation.py +48 -6
  133. package/core/ledger/finding_lifecycle.py +428 -5
  134. package/core/ledger/finding_verification.py +555 -10
  135. package/core/ledger/fp_ledger.py +255 -0
  136. package/core/ledger/incidents.py +10 -4
  137. package/core/ledger/patterns.py +10 -7
  138. package/core/ledger/receipt_contract.py +17 -1
  139. package/core/ledger/sync_ops.py +21 -16
  140. package/core/ledger/tool_experience.py +2 -1
  141. package/core/ledger/verify_life.py +88 -17
  142. package/core/locales/en-US.json +2 -2
  143. package/core/locales/zh-CN.json +2 -2
  144. package/core/mcp_handlers/SPEC.md +1 -1
  145. package/core/mcp_handlers/base.py +23 -3
  146. package/core/mcp_handlers/channel_lifecycle.py +85 -30
  147. package/core/mcp_handlers/retrieval_handlers.py +11 -1
  148. package/core/mcp_handlers/rpc_server.py +6 -1
  149. package/core/mcp_handlers/supervisor_handlers.py +32 -6
  150. package/core/mcp_handlers/tool_table.py +15 -0
  151. package/core/mcp_runtime_support/environment.py +0 -38
  152. package/core/mcp_runtime_support/verifier.py +0 -52
  153. package/core/metadata.txt +2 -3
  154. package/core/planning/README.md +2 -1
  155. package/core/planning/domain_router.py +4 -2
  156. package/core/planning/dynamic_flow_analyzer.py +219 -14
  157. package/core/planning/judge_pipeline.py +87 -4
  158. package/core/planning/prompt_harness.py +57 -15
  159. package/core/planning/prompt_policy_engine.py +386 -0
  160. package/core/planning/spec_harvester.py +4 -4
  161. package/core/probes/INTERFACE.md +11 -1
  162. package/core/probes/SPEC.md +11 -1
  163. package/core/probes/__init__.py +46 -40
  164. package/core/probes/android_probe.py +177 -9
  165. package/core/probes/codebase_memory_probe.py +57 -0
  166. package/core/probes/desktop_probe.py +104 -0
  167. package/core/probes/differential_probe.py +99 -21
  168. package/core/probes/efficiency_probe.py +64 -0
  169. package/core/probes/ios_binary_probe.py +105 -1
  170. package/core/probes/memory_probe.py +66 -0
  171. package/core/probes/miniprogram_probe.py +75 -13
  172. package/core/probes/mobile_probe.py +215 -30
  173. package/core/probes/native_probe.py +88 -0
  174. package/core/probes/openwiki_probe.py +70 -0
  175. package/core/probes/pattern_probe.py +106 -0
  176. package/core/probes/platform_probe.py +81 -0
  177. package/core/probes/probe_registry.py +108 -7
  178. package/core/probes/sast_fixture_corpus.py +340 -0
  179. package/core/probes/sast_probe.py +553 -52
  180. package/core/probes/sast_rules.py +668 -28
  181. package/core/probes/sca_scanner.py +48 -0
  182. package/core/probes/ui_accessibility.py +149 -0
  183. package/core/probes/ui_audit.py +513 -0
  184. package/core/probes/ui_contract.py +273 -0
  185. package/core/probes/ui_evidence.py +212 -0
  186. package/core/probes/ui_measurements.py +314 -0
  187. package/core/probes/ui_repair.py +250 -0
  188. package/core/probes/ui_review.py +133 -0
  189. package/core/probes/ui_storybook.py +107 -0
  190. package/core/probes/ui_tokens.py +185 -0
  191. package/core/probes/ui_visual_diff.py +131 -0
  192. package/core/probes/web_probe.py +373 -18
  193. package/core/project_profiler/SPEC.md +1 -1
  194. package/core/project_profiler/arbitrator.py +6 -1
  195. package/core/project_profiler/detector.py +8 -1
  196. package/core/project_profiler/strategy.py +51 -15
  197. package/core/prompts/README.md +4 -2
  198. package/core/prompts/command_routing_en.md +2 -2
  199. package/core/prompts/command_routing_zh.md +2 -2
  200. package/core/prompts/policies/prompt_policies.json +101 -0
  201. package/core/prompts/stages/stage_repair.md +1 -1
  202. package/core/prompts/stages/stage_verify.defensive.md +42 -0
  203. package/core/prompts/stages/stage_verify.md +44 -0
  204. package/core/repair/README.md +1 -1
  205. package/core/repair/l7_repair_loop.py +1 -4
  206. package/core/repair/rsi_fixer.py +4 -4
  207. package/core/repair/rsi_loop.py +1 -3
  208. package/core/repair/rsi_repair.py +7 -7
  209. package/core/repair/rsi_scope.py +27 -8
  210. package/core/report_engine/SPEC.md +1 -1
  211. package/core/report_engine/attestation.py +8 -4
  212. package/core/report_engine/finding_report.py +2 -1
  213. package/core/report_engine/models.py +7 -9
  214. package/core/report_engine/report_share.py +0 -8
  215. package/core/report_engine/sast_bridge.py +2 -2
  216. package/core/report_engine/server.py +18 -8
  217. package/core/report_engine/web-conformance.md +123 -18
  218. package/core/report_engine/web_conformance.py +21 -52
  219. package/core/retrieval/README.md +2 -1
  220. package/core/retrieval/SPEC.md +1 -1
  221. package/core/retrieval/code_analyzer.py +50 -14
  222. package/core/retrieval/context_assembler.py +7 -1
  223. package/core/retrieval/knowledge_sync.py +108 -14
  224. package/core/retrieval/pitfall_packs.py +277 -0
  225. package/core/retrieval/symbol_index.py +25 -6
  226. package/core/retrieval/universal_code_matcher.py +234 -49
  227. package/core/runtime/README.md +1 -1
  228. package/core/runtime/bugx_logging.py +78 -7
  229. package/core/runtime/fixture_solidify.py +5 -10
  230. package/core/runtime/global_telemetry.py +20 -0
  231. package/core/runtime/incident_eval.py +1 -1
  232. package/core/runtime/model_runner.py +4 -41
  233. package/core/runtime/platform_adapter.py +2 -2
  234. package/core/runtime/prep_validate.py +4 -2
  235. package/core/runtime/project_settings.py +2 -1
  236. package/core/runtime/scenario_eval.py +50 -8
  237. package/core/skills/bugx_docs_mcp_server.py +3 -1
  238. package/core/skills/bugx_mcp_server.py +29 -2
  239. package/core/skills/tools_kb.py +1 -1
  240. package/core/supervisor/README.md +1 -1
  241. package/core/supervisor/SPEC.md +1 -1
  242. package/core/supervisor/budget_governor.py +503 -9
  243. package/core/supervisor/checkpoint_pipeline.py +248 -6
  244. package/core/supervisor/checkpoint_sync.py +13 -0
  245. package/core/supervisor/claim_events.py +1 -1
  246. package/core/supervisor/finding_workflow.py +22 -5
  247. package/core/supervisor/lease_manager.py +1 -1
  248. package/core/supervisor/lifecycle_blocks.py +6 -1
  249. package/core/supervisor/rejection_remedies.py +52 -5
  250. package/core/supervisor/serial_authorization.py +48 -4
  251. package/core/supervisor/task_scheduler.py +2 -2
  252. package/core/supervisor/worker_checkpoint.py +8 -1
  253. package/core/supervisor/worker_runtime.py +8 -2
  254. package/core/supervisor_types/worker_claim.py +9 -0
  255. package/core/webui/README.md +1 -1
  256. package/core/webui/SPEC.md +2 -1
  257. package/core/webui/adapters/claude.py +5 -1
  258. package/core/webui/adapters/cline.py +10 -2
  259. package/core/webui/adapters/codex.py +5 -1
  260. package/core/webui/adapters/dsh.py +5 -1
  261. package/core/webui/docs_session_service.py +2 -2
  262. package/core/webui/mcp_inspector.py +11 -7
  263. package/core/webui/static/00-base.css +1060 -0
  264. package/core/webui/static/01-monitoring.css +802 -0
  265. package/core/webui/static/02-header-actions.css +321 -0
  266. package/core/webui/static/03-trigger-popover.css +697 -0
  267. package/core/webui/static/04-composer.css +628 -0
  268. package/core/webui/static/05-skills-center.css +878 -0
  269. package/core/webui/static/06-mcp-center.css +623 -0
  270. package/core/webui/static/07-skill-detail.css +265 -0
  271. package/core/webui/static/08-files-management.css +167 -0
  272. package/core/webui/static/09-files-center.css +386 -0
  273. package/core/webui/static/10-icons.css +105 -0
  274. package/core/webui/static/11-project-options.css +185 -0
  275. package/core/webui/static/12-profile-tab.css +383 -0
  276. package/core/webui/static/design-tokens.css +113 -0
  277. package/core/webui/static/index.html +14 -1
  278. package/core/webui/workspace_service.py +1 -1
  279. package/docs/07_distribution/01_README_NPM.md +193 -185
  280. package/ecosystem/integrations/README.md +1 -1
  281. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  282. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  283. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  284. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
  285. package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
  286. package/ecosystem/integrations/opencode/opencode.json +23 -12
  287. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  288. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  289. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  290. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  291. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  292. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  293. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  294. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  295. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  296. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  297. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
  298. package/interfaces/bin/bugx.js +37 -0
  299. package/interfaces/cli/bugx_cli/__init__.py +4 -2
  300. package/interfaces/cli/bugx_cli/cli.py +172 -69
  301. package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
  302. package/interfaces/cli/bugx_cli/commands/agent.py +461 -134
  303. package/interfaces/cli/bugx_cli/commands/audit.py +10 -9
  304. package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
  305. package/interfaces/cli/bugx_cli/commands/cloud.py +31 -22
  306. package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
  307. package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
  308. package/interfaces/cli/bugx_cli/commands/knowledge.py +5 -4
  309. package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
  310. package/interfaces/cli/bugx_cli/commands/plugin.py +58 -23
  311. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
  312. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
  313. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
  314. package/interfaces/cli/bugx_cli/commands/project.py +6 -13
  315. package/interfaces/cli/bugx_cli/commands/report.py +2 -6
  316. package/interfaces/cli/bugx_cli/commands/system.py +524 -169
  317. package/interfaces/cli/bugx_cli/common.py +21 -15
  318. package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
  319. package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
  320. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
  321. package/interfaces/cli/bugx_cli/infra/engine_installer.py +35 -16
  322. package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
  323. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
  324. package/interfaces/cli/bugx_cli/infra/security.py +13 -6
  325. package/package.json +30 -15
  326. package/pyproject.toml +60 -9
  327. package/scripts/ensure-python.mjs +7 -7
  328. package/scripts/sync-version.mjs +10 -21
  329. package/scripts/test-npm-wrapper.mjs +1 -1
  330. package/core/assets/bugx-hero-cn.png +0 -0
  331. package/core/assets/bugx-hero-en.png +0 -0
  332. package/core/webui/static/project-settings.css +0 -6458
  333. package/docs/07_distribution/README.md +0 -16
  334. package/docs/README.md +0 -121
  335. package/interfaces/README.md +0 -143
  336. package/interfaces/bin/README.md +0 -35
  337. package/interfaces/cli/README.md +0 -90
  338. package/scripts/README.md +0 -118
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env python3
2
+ """core/ledger/fp_ledger.py — 负样本误报账本与源码哈希防误杀护栏(P1 / T-005)。
3
+
4
+ 核心安全边界:
5
+ 1. 仅沉淀经引擎确认驳回的误报(允许 ``not_reproducible`` / ``false_positive`` / ``wont_fix``),
6
+ 严禁把 ``timeout`` / ``env_blocked`` / ``source_tampered`` 误记为“代码安全”;
7
+ 2. 每条负样本必须绑定目标文件的 ``source_sha256``;
8
+ 3. 查询时实时重算目标文件 SHA-256:
9
+ - 哈希一致 → ``active_guard``(有效降噪护栏);
10
+ - 哈希漂移或文件消失 → 自动降级为 ``stale_guard`` 并失效,严防修改代码引入新漏洞后被旧误报掩盖!
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import tempfile
19
+ import time
20
+ from pathlib import Path
21
+ from typing import Any, Mapping, Sequence
22
+
23
+ LEDGER_SCHEMA_VERSION = 1
24
+ ALLOWED_FP_REJECTION_CLASSES = frozenset({
25
+ "not_reproducible",
26
+ "false_positive",
27
+ "wont_fix",
28
+ })
29
+
30
+
31
+ class FalsePositiveLedgerError(ValueError):
32
+ """Raised on invalid false-positive ledger path or payload."""
33
+
34
+
35
+ def _sha256_bytes(data: bytes) -> str:
36
+ return hashlib.sha256(data).hexdigest()
37
+
38
+
39
+ def _confined_file(root: Path, rel_path: str) -> tuple[str, Path]:
40
+ if not isinstance(rel_path, str) or not rel_path.strip():
41
+ raise FalsePositiveLedgerError("file_path 必须是非空相对路径")
42
+ candidate = Path(rel_path.replace("\\", "/"))
43
+ if candidate.is_absolute() or ".." in candidate.parts:
44
+ raise FalsePositiveLedgerError(f"file_path 越界或非相对路径: {rel_path}")
45
+ resolved_root = Path(root).resolve()
46
+ cursor = resolved_root
47
+ for part in candidate.parts:
48
+ if part in {"", "."}:
49
+ continue
50
+ cursor = cursor / part
51
+ if cursor.is_symlink():
52
+ raise FalsePositiveLedgerError(f"file_path 禁止穿过符号链接: {rel_path}")
53
+ resolved = (resolved_root / candidate).resolve()
54
+ try:
55
+ rel_norm = resolved.relative_to(resolved_root).as_posix()
56
+ except ValueError as exc:
57
+ raise FalsePositiveLedgerError(f"file_path 越界: {rel_path}") from exc
58
+ return rel_norm, resolved
59
+
60
+
61
+ def _file_sha256(path: Path) -> str | None:
62
+ if not path.is_file() or path.is_symlink():
63
+ return None
64
+ try:
65
+ return _sha256_bytes(path.read_bytes())
66
+ except OSError:
67
+ return None
68
+
69
+
70
+ def ledger_path(root: Path) -> Path:
71
+ return Path(root).resolve() / ".bugx" / "knowledge" / "fp-ledger.json"
72
+
73
+
74
+ def _atomic_write_json(path: Path, payload: Mapping[str, Any]) -> None:
75
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
76
+ raw = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True).encode("utf-8")
77
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
78
+ try:
79
+ os.fchmod(fd, 0o600)
80
+ with os.fdopen(fd, "wb") as handle:
81
+ handle.write(raw)
82
+ handle.flush()
83
+ os.fsync(handle.fileno())
84
+ os.replace(tmp_name, path)
85
+ except BaseException:
86
+ try:
87
+ os.close(fd)
88
+ except OSError:
89
+ pass
90
+ try:
91
+ os.unlink(tmp_name)
92
+ except OSError:
93
+ pass
94
+ raise
95
+
96
+
97
+ def load_fp_ledger(root: Path) -> dict[str, Any]:
98
+ path = ledger_path(root)
99
+ if not path.is_file():
100
+ return {"schema_version": LEDGER_SCHEMA_VERSION, "entries": []}
101
+ try:
102
+ data = json.loads(path.read_text(encoding="utf-8"))
103
+ except (OSError, ValueError):
104
+ return {"schema_version": LEDGER_SCHEMA_VERSION, "entries": []}
105
+ if not isinstance(data, dict) or not isinstance(data.get("entries"), list):
106
+ return {"schema_version": LEDGER_SCHEMA_VERSION, "entries": []}
107
+ return data
108
+
109
+
110
+ def record_false_positive(
111
+ root: Path,
112
+ *,
113
+ file_path: str,
114
+ rejection_class: str,
115
+ guard_evidence: str,
116
+ category: str = "",
117
+ cwe: str = "",
118
+ symbol: str = "",
119
+ fingerprint: str = "",
120
+ languages: Sequence[str] = (),
121
+ frameworks: Sequence[str] = (),
122
+ ) -> dict[str, Any]:
123
+ """Persist a source-hash-bound false-positive guard into .bugx/knowledge/fp-ledger.json."""
124
+ if rejection_class not in ALLOWED_FP_REJECTION_CLASSES:
125
+ raise FalsePositiveLedgerError(
126
+ f"不允许将 rejection_class={rejection_class!r} 写入负样本误报账本(仅允许 {sorted(ALLOWED_FP_REJECTION_CLASSES)})"
127
+ )
128
+ evidence_text = (guard_evidence or "").strip()
129
+ if not evidence_text:
130
+ raise FalsePositiveLedgerError("guard_evidence 不能为空")
131
+
132
+ rel_norm, abs_path = _confined_file(root, file_path)
133
+ src_hash = _file_sha256(abs_path)
134
+ if src_hash is None:
135
+ raise FalsePositiveLedgerError(f"目标文件不存在或不可读,拒绝写入无哈希绑定的误报记录: {rel_norm}")
136
+
137
+ dedup_key = _sha256_bytes(
138
+ f"{rel_norm}|{category.strip().lower()}|{cwe.strip().upper()}|{symbol.strip()}|{src_hash}".encode("utf-8")
139
+ )[:16]
140
+ fp_id = f"FP-{dedup_key}"
141
+ now = time.time()
142
+
143
+ data = load_fp_ledger(root)
144
+ entries: list[dict[str, Any]] = [e for e in data.get("entries", []) if isinstance(e, dict)]
145
+
146
+ existing = next((e for e in entries if e.get("fp_id") == fp_id), None)
147
+ if existing is not None:
148
+ existing["hit_count"] = int(existing.get("hit_count") or 1) + 1
149
+ existing["guard_evidence"] = evidence_text[:500]
150
+ existing["updated_at"] = now
151
+ record = existing
152
+ else:
153
+ record = {
154
+ "fp_id": fp_id,
155
+ "file_path": rel_norm,
156
+ "source_sha256": src_hash,
157
+ "category": category.strip().lower(),
158
+ "cwe": cwe.strip().upper(),
159
+ "symbol": symbol.strip(),
160
+ "fingerprint": fingerprint.strip(),
161
+ "rejection_class": rejection_class,
162
+ "guard_evidence": evidence_text[:500],
163
+ "languages": sorted({s.strip().lower() for s in languages if isinstance(s, str) and s.strip()}),
164
+ "frameworks": sorted({s.strip().lower() for s in frameworks if isinstance(s, str) and s.strip()}),
165
+ "hit_count": 1,
166
+ "created_at": now,
167
+ "updated_at": now,
168
+ }
169
+ entries.append(record)
170
+
171
+ payload = {
172
+ "schema_version": LEDGER_SCHEMA_VERSION,
173
+ "updated_at": now,
174
+ "entries": entries,
175
+ }
176
+ _atomic_write_json(ledger_path(root), payload)
177
+ return record
178
+
179
+
180
+ def match_false_positive_guards(
181
+ root: Path,
182
+ *,
183
+ file_path: str,
184
+ category: str = "",
185
+ cwe: str = "",
186
+ symbol: str = "",
187
+ include_stale: bool = False,
188
+ ) -> list[dict[str, Any]]:
189
+ """Return active (hash-verified) false-positive guards for a file; stale entries auto-invalidate."""
190
+ try:
191
+ rel_norm, abs_path = _confined_file(root, file_path)
192
+ except FalsePositiveLedgerError:
193
+ return []
194
+ current_hash = _file_sha256(abs_path)
195
+ data = load_fp_ledger(root)
196
+ cat_norm = category.strip().lower()
197
+ cwe_norm = cwe.strip().upper()
198
+ sym_norm = symbol.strip()
199
+
200
+ matched: list[dict[str, Any]] = []
201
+ for entry in data.get("entries", []):
202
+ if not isinstance(entry, dict):
203
+ continue
204
+ if entry.get("file_path") != rel_norm:
205
+ continue
206
+ if cat_norm and entry.get("category") and entry.get("category") != cat_norm:
207
+ continue
208
+ if cwe_norm and entry.get("cwe") and entry.get("cwe") != cwe_norm:
209
+ continue
210
+ if sym_norm and entry.get("symbol") and entry.get("symbol") != sym_norm:
211
+ continue
212
+
213
+ is_active = bool(current_hash and entry.get("source_sha256") == current_hash)
214
+ guard_status = "active_guard" if is_active else "stale_guard"
215
+ if not is_active and not include_stale:
216
+ continue
217
+ item = dict(entry)
218
+ item["guard_status"] = guard_status
219
+ matched.append(item)
220
+ return matched
221
+
222
+
223
+ def render_fp_guard_guidance(
224
+ guards: Sequence[Mapping[str, Any]],
225
+ *,
226
+ char_budget: int = 600,
227
+ ) -> str:
228
+ """Render compact active false-positive guard hints for Worker noise reduction."""
229
+ active = [g for g in guards if g.get("guard_status") == "active_guard"]
230
+ if not active or char_budget <= 0:
231
+ return ""
232
+ lines = ["[历史已证伪误报护栏 (Active FP Guards — 源码未变更,避免重复无效验证)]"]
233
+ used = len(lines[0]) + 1
234
+ for g in active:
235
+ block = (
236
+ f"- [{g.get('fp_id')} | {g.get('file_path')} | {g.get('rejection_class')}] "
237
+ f"{g.get('guard_evidence')}"
238
+ )
239
+ if used + len(block) + 1 > char_budget:
240
+ break
241
+ lines.append(block)
242
+ used += len(block) + 1
243
+ return "\n".join(lines) if len(lines) > 1 else ""
244
+
245
+
246
+ __all__ = [
247
+ "LEDGER_SCHEMA_VERSION",
248
+ "ALLOWED_FP_REJECTION_CLASSES",
249
+ "FalsePositiveLedgerError",
250
+ "ledger_path",
251
+ "load_fp_ledger",
252
+ "record_false_positive",
253
+ "match_false_positive_guards",
254
+ "render_fp_guard_guidance",
255
+ ]
@@ -441,10 +441,16 @@ def lookup_incidents(
441
441
  data = canonical_bytes(row)
442
442
  size = len(data)
443
443
  toks, _ = estimate_tokens(data)
444
- if byte_budget is not None and total_b + size > byte_budget:
445
- continue
446
- if token_budget is not None and total_t + toks > token_budget:
447
- continue
444
+ # F-RSI-20261115-127:identity 精确命中是调用方显式 signatures 的
445
+ # 查询意图本体,不得被预算挤掉——context 合法上限 64KB 可超
446
+ # byte_budget 20480,被 continue 跳过后低分 text 行反被塞入,
447
+ # 显式签名查询静默落空。预算只约束文本扫描的加分行;limit 硬顶
448
+ # 对全部行仍生效。
449
+ if not _identity_exact_hit:
450
+ if byte_budget is not None and total_b + size > byte_budget:
451
+ continue
452
+ if token_budget is not None and total_t + toks > token_budget:
453
+ continue
448
454
  result.append(row)
449
455
  total_b += size
450
456
  total_t += toks
@@ -174,16 +174,19 @@ def normalize_pattern(payload: Mapping[str, Any], now: str | None = None) -> dic
174
174
  "created_at": str(payload.get("created_at") or timestamp),
175
175
  "updated_at": str(payload.get("updated_at") or timestamp),
176
176
  "last_used_at": payload.get("last_used_at"),
177
- "use_count": int(payload.get("use_count", 0)), "hit_count": int(payload.get("hit_count", 0)),
178
- "miss_count": int(payload.get("miss_count", 0)),
179
- "false_positive_count": int(payload.get("false_positive_count", 0)),
180
- "rejected_count": int(payload.get("rejected_count", 0)),
181
177
  **extract_card_fields(payload),
182
178
  "routing_tags": extract_routing_tags(payload),
183
179
  }
184
- for field in ("use_count", "hit_count", "miss_count", "false_positive_count", "rejected_count"):
185
- if result[field] < 0:
186
- raise LessonLedgerError(f"{field} 不得小于 0")
180
+ # F-RSI-20261115-130:计数器字段显式校验——int() 隐式转换会把 bool 静默
181
+ # 折成 0/1、小数截断(3.9→3)、非数字裸抛 ValueError(非 LessonLedgerError,
182
+ # 穿过 except LessonLedgerError 调用链)。对齐 incidents.normalize_duration
183
+ # 的显式校验标准(bool 排除 + 整型 + 非负),消除同域两套标准。
184
+ for field in ("use_count", "hit_count", "miss_count",
185
+ "false_positive_count", "rejected_count"):
186
+ value = payload.get(field, 0)
187
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
188
+ raise LessonLedgerError(f"{field} 必须是非负整数(收到 {value!r})")
189
+ result[field] = value
187
190
  return result
188
191
 
189
192
 
@@ -160,7 +160,8 @@ def verify_receipt_coverage_contract(
160
160
  )
161
161
  elif declared is None:
162
162
  warnings.append(
163
- f"收据未声明覆盖债务,密封件声明为 {sealed_debt}(无法交叉校验)"
163
+ f"收据显式声明 coverage_debt_units=null(账本不可读),"
164
+ f"密封件声明为 {sealed_debt}(无法交叉校验)"
164
165
  )
165
166
  elif isinstance(declared, int) and not isinstance(declared, bool):
166
167
  if declared != sealed_debt:
@@ -200,12 +201,27 @@ def verify_receipt_coverage_contract(
200
201
  f"收据声明的 {declared} 无法核实"
201
202
  "(『读不出来』不得被折叠成『没有债务』——修复轮复核 E3-R2-D5)"
202
203
  )
204
+ elif declared is None:
205
+ # F-RSI-20261115-124:收据显式 null + 密封账本重算也 None——
206
+ # 双方均不可读,债务状态完全未知,不得零反馈静默通过
207
+ warnings.append(
208
+ "收据显式声明 coverage_debt_units=null 且密封账本不可读:"
209
+ "双方均无法核实覆盖债务,债务状态未知"
210
+ )
203
211
  elif isinstance(declared, int) and not isinstance(declared, bool):
204
212
  if recomputed != declared:
205
213
  errors.append(
206
214
  f"收据声明的覆盖债务 {declared} 与密封账本按权威口径重算的 "
207
215
  f"{recomputed} 不一致(收据必须由账本算出,不得写死字面量)"
208
216
  )
217
+ elif declared is None:
218
+ # F-RSI-20261115-124:收据宣称「账本不可读」(null)但密封账本
219
+ # 可读且重算出 {recomputed}——声明与事实矛盾,不得静默通过
220
+ # (历史 E2-D1 拦了 999 字面量,null 是绕过债务核实的漏网伪造路径)
221
+ errors.append(
222
+ f"收据显式声明 coverage_debt_units=null(账本不可读)"
223
+ f"但密封账本重算出 {recomputed}:声明与事实矛盾"
224
+ )
209
225
  else:
210
226
  # 密封账本**类型错**(合法 JSON 但不是对象)时,整段重算此前被**静默
211
227
  # 跳过、零告警**——修复轮复核 E2-D1 实测(定级 P0):把
@@ -497,30 +497,35 @@ def apply_synced_tombstone_tx(
497
497
  "tool experience tombstone record_id 必须是 tool_name/category"
498
498
  )
499
499
  tool_name, category = record_id.split("/", 1)
500
+ # F-129: 与 DDL 命名契约绑定,按列名取值,禁止依赖列序位置。
500
501
  row = c.execute(
501
- "SELECT * FROM tool_experience WHERE tool_name=? AND category=?",
502
+ "SELECT tool_name,category,experience_level,record_version,use_count,"
503
+ "hit_count,miss_count,false_positive_count,rejected_count,"
504
+ "independent_lifecycle_count,first_observed_at,last_observed_at,"
505
+ "tool_version,device_id,deleted,deleted_at FROM tool_experience "
506
+ "WHERE tool_name=? AND category=?",
502
507
  (tool_name, category),
503
508
  ).fetchone()
504
509
  if not row:
505
510
  return "missing"
506
- if bool(row[14]):
511
+ if bool(row["deleted"]):
507
512
  return "duplicate"
508
513
  deleted_at = now_iso()
509
514
  content = {
510
- "tool_name": row[0],
511
- "category": row[1],
512
- "experience_level": row[2],
513
- "record_version": int(row[3]),
514
- "use_count": int(row[4]),
515
- "hit_count": int(row[5]),
516
- "miss_count": int(row[6]),
517
- "false_positive_count": int(row[7]),
518
- "rejected_count": int(row[8]),
519
- "independent_lifecycle_count": int(row[9]),
520
- "first_observed_at": row[10],
521
- "last_observed_at": row[11],
522
- "tool_version": row[12],
523
- "device_id": row[13],
515
+ "tool_name": row["tool_name"],
516
+ "category": row["category"],
517
+ "experience_level": row["experience_level"],
518
+ "record_version": int(row["record_version"]),
519
+ "use_count": int(row["use_count"]),
520
+ "hit_count": int(row["hit_count"]),
521
+ "miss_count": int(row["miss_count"]),
522
+ "false_positive_count": int(row["false_positive_count"]),
523
+ "rejected_count": int(row["rejected_count"]),
524
+ "independent_lifecycle_count": int(row["independent_lifecycle_count"]),
525
+ "first_observed_at": row["first_observed_at"],
526
+ "last_observed_at": row["last_observed_at"],
527
+ "tool_version": row["tool_version"],
528
+ "device_id": row["device_id"],
524
529
  "deleted": True,
525
530
  "deleted_at": deleted_at,
526
531
  }
@@ -626,7 +626,8 @@ def activate_tool_experience(
626
626
  raise LessonLedgerError("待激活的工具经验不存在")
627
627
  if row[2] != "candidate":
628
628
  raise LessonLedgerError("只有 candidate 工具经验可以激活")
629
- if bool(row[14]):
629
+ # F-129: 按列名取值,禁止依赖列序位置(row_factory=sqlite3.Row)。
630
+ if bool(row["deleted"]):
630
631
  raise LessonLedgerError("已删除的工具经验不能激活")
631
632
  if int(row[9] or 0) < 2 or int(row[5] or 0) < 2:
632
633
  raise LessonLedgerError("工具经验至少需要两个独立 lifecycle hit")
@@ -35,7 +35,10 @@
35
35
  调用方把该基线保存到 agent 会话之外(如手动记录,或 export 环境变量)。
36
36
  2. bugx 运行结束后:`bugx engine --root . post` —— 优先用
37
37
  `BH_PRE_BASELINE` 环境变量(调用方传入的外部基线)做 diff;
38
- 若未设置则回退读仓库内 snapshot。外部基线是权威,agent 无法篡改。
38
+ 若未设置则回退读仓库内 snapshot。外部基线由 pre 阶段签发
39
+ `baseline_hash` + `baseline_source`,post 先校验来源与完整性再采信;
40
+ agent 篡改基线内容或注入无签名基线将被 fail-closed 拒绝,
41
+ 不再依赖「agent 无法篡改 env」的进程边界假设。
39
42
  3. diff 异常 → restore 回滚到基线,并复核 agent 报告是否真实。
40
43
 
41
44
  不变量(新机制:轮费改在结算时支付,life 只由结算写入):
@@ -68,6 +71,7 @@ for _p in _Path(__file__).resolve().parents:
68
71
  del _p
69
72
 
70
73
  import hashlib
74
+ import hmac
71
75
  import json
72
76
  import os
73
77
  import re
@@ -138,14 +142,14 @@ LIFE_FILE, SNAPSHOT_FILE, AUDIT_LOG, LIFE_LOCK_FILE = _default_life_paths()
138
142
  # 自校验:脚本被 bash/sed/cp 篡改后,所有命令拒绝执行。
139
143
  # 维护方法:改完本脚本后运行 `python3 verify_life.py selfhash`,
140
144
  # 把输出粘贴到下面 SELF_HASH = "..." 即可(哈希会随每次编辑变化)。
141
- SELF_HASH = "56f26ad4a62294f914e98fe771a0cae231fd5790a5b36da7ece4968e3171690d"
145
+ SELF_HASH = "1d29d8cf0342e4ee0f371da3528fd26f29524d0436714e7a86d9163abccbd3f4"
142
146
 
143
147
  # 单轮每项真实发现的加分上限(与 bugx.md「单轮加分上限」一致)。
144
148
  # 防「凑数无限续命」:每轮 life 净增上限 = -1(轮费) + MAX_PER_ROUND。
145
149
  MAX_PER_ROUND = 5
146
- # 本脚本被设计成**可独立复制执行**(tests/ledger/test_verify_life.py 会把它单独
150
+ # 本脚本被设计成**可独立复制执行**(独立平铺副本场景;行为契约以本注释与
147
151
  # 拷进临时目录跑,那里没有 core 包),因此不能 import canonical 常量。字面量必须在
148
- # 此维护,并由 tests/launch/test_orchestrator_controls.py 断言与
152
+ # 上游 docstring 共同维护;与
149
153
  # core.launch_phases.common.FIX_MODES 完全相等——单一事实源靠契约测试守,不靠 import。
150
154
  VALID_MODES = {"auto", "log-only"}
151
155
  SETTLEMENT_WAL_SCHEMA = 1
@@ -478,29 +482,87 @@ def evidence_bad_lines(findings: list[str]) -> list[str]:
478
482
  return bad
479
483
 
480
484
 
485
+ # ---- 外部基线完整性锚(F-184)----
486
+ # 旧实现只做 json.loads/路径读取,docstring 的「agent 无法篡改」是进程边界
487
+ # 假设而非代码校验;具备 env 控制权的进程可注入被篡改基线掩盖历史篡改。
488
+ # 现在由可信宿主在 pre 阶段(snapshot)对基线载荷签发 baseline_hash,
489
+ # post 读取时强制校验来源标识 + 完整性,失败即 fail-closed 拒绝。
490
+ BASELINE_HASH_FIELD = "baseline_hash"
491
+ BASELINE_SOURCE_FIELD = "baseline_source"
492
+ HOST_SIGNED_SOURCE = "host-signed-pre"
493
+ REPO_SNAPSHOT_SOURCE = "repo-snapshot"
494
+
495
+
496
+ def baseline_integrity_hash(payload: dict) -> str:
497
+ """基线载荷的确定性 SHA256——排除锚字段本身,避免自引用死循环。"""
498
+ body = {
499
+ key: value for key, value in payload.items()
500
+ if key not in (BASELINE_HASH_FIELD, BASELINE_SOURCE_FIELD)
501
+ }
502
+ blob = json.dumps(
503
+ body, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False,
504
+ ).encode("utf-8")
505
+ return hashlib.sha256(blob).hexdigest()
506
+
507
+
508
+ def sign_baseline(payload: dict) -> dict:
509
+ """由可信宿主在 pre 阶段调用,为基线载荷签发来源标识与完整性锚。"""
510
+ signed = dict(payload)
511
+ signed[BASELINE_SOURCE_FIELD] = HOST_SIGNED_SOURCE
512
+ signed[BASELINE_HASH_FIELD] = baseline_integrity_hash(signed)
513
+ return signed
514
+
515
+
481
516
  def external_baseline() -> dict | None:
482
- """读取调用方传入的外部基线(修复漏洞 2 的关键)。
517
+ """读取外部基线(pre 签发、post 校验)。
483
518
 
484
- 优先级:环境变量 BH_PRE_BASELINE(调用方 pre 时输出、post 时传回,支持 JSON 字符串或文件路径)
485
- > 仓库内 snapshot 文件。外部基线在 agent 会话之外,agent 无法篡改。
519
+ 优先级:环境变量 BH_PRE_BASELINE(pre 签发、post 传回,JSON 字符串或
520
+ 文件路径)> 仓库内 snapshot 文件。env 基线必须携带合法来源标识与
521
+ baseline_hash,且哈希与载荷逐字节一致,否则 fail-closed 拒绝;
522
+ 快照回退显式标记 baseline_source,不再以进程边界假设代替校验。
486
523
  """
487
524
  import os
488
525
 
489
526
  raw = os.environ.get("BH_PRE_BASELINE", "").strip()
490
527
  if raw:
528
+ payload: dict | None = None
491
529
  try:
492
530
  p = Path(raw)
493
531
  if p.is_file():
494
- return _load_json(p, "外部基线文件")
532
+ payload = _load_json(p, "外部基线文件")
495
533
  except (OSError, ValueError):
496
534
  pass
497
- try:
498
- return json.loads(raw)
499
- except json.JSONDecodeError as e:
500
- print(f"[verify_life] BH_PRE_BASELINE 无法解析: {e}")
535
+ if payload is None:
536
+ try:
537
+ parsed = json.loads(raw)
538
+ payload = parsed if isinstance(parsed, dict) else None
539
+ except json.JSONDecodeError as e:
540
+ print(f"[verify_life] BH_PRE_BASELINE 无法解析: {e}")
541
+ return None
542
+ if not isinstance(payload, dict):
543
+ print("[verify_life] 外部基线必须是 JSON 对象,拒绝。")
544
+ return None
545
+ source = payload.get(BASELINE_SOURCE_FIELD)
546
+ if source != HOST_SIGNED_SOURCE:
547
+ print(f"[verify_life] 外部基线来源标识缺失或不合法"
548
+ f"(要求 {HOST_SIGNED_SOURCE!r},实际 {source!r}),拒绝。")
549
+ return None
550
+ expected = payload.get(BASELINE_HASH_FIELD)
551
+ if not isinstance(expected, str) or not expected:
552
+ print("[verify_life] 外部基线缺 baseline_hash(新格式强制校验),拒绝。")
501
553
  return None
554
+ actual = baseline_integrity_hash(payload)
555
+ if not hmac.compare_digest(actual, expected):
556
+ print(f"[verify_life] 外部基线完整性校验失败"
557
+ f"(签发 {expected},实算 {actual}),拒绝。")
558
+ return None
559
+ return payload
502
560
  if SNAPSHOT_FILE.is_file():
503
- return _load_json(SNAPSHOT_FILE, "快照基线")
561
+ snap = _load_json(SNAPSHOT_FILE, "快照基线")
562
+ if isinstance(snap, dict):
563
+ snap = dict(snap)
564
+ snap[BASELINE_SOURCE_FIELD] = REPO_SNAPSHOT_SOURCE
565
+ return snap
504
566
  return None
505
567
 
506
568
 
@@ -802,11 +864,20 @@ def _cmd_snapshot_unlocked() -> int:
802
864
  print(f"[verify_life] 拒绝写入符号链接快照路径: {SNAPSHOT_FILE}")
803
865
  return 1
804
866
  try:
867
+ # F-184:pre 的可信宿主在此签发外部基线锚。baseline_json() 读的就是
868
+ # LIFE_FILE,因此把锚写回寿命文件后,pre 导出的 BH_PRE_BASELINE 天然
869
+ # 携带来源标识与 hash;post 的 external_baseline() 据此强制校验。
870
+ current = load()
871
+ if not isinstance(current, dict):
872
+ print("[verify_life] 寿命状态根节点必须是 JSON 对象,拒绝快照。")
873
+ return 1
874
+ signed = sign_baseline(current)
875
+ _write_json_durable(LIFE_FILE, signed, prefix=".life-")
805
876
  _copy_atomic(LIFE_FILE, SNAPSHOT_FILE)
806
877
  except OSError as e:
807
878
  print(f"[verify_life] 快照建立失败: {e}")
808
879
  return 1
809
- print(f"[verify_life] 已备份当前状态到 {SNAPSHOT_FILE.name}")
880
+ print(f"[verify_life] 已备份当前状态到 {SNAPSHOT_FILE.name}(已签发基线完整性锚)")
810
881
  return 0
811
882
 
812
883
 
@@ -819,8 +890,8 @@ def _cmd_diff_unlocked() -> int:
819
890
  检出「自洽撒谎」/超范围涨命/历史篡改。修复漏洞 2。"""
820
891
  snap = external_baseline()
821
892
  if snap is None:
822
- print("[verify_life] 无可用基线——外部基线未设置且无快照文件,"
823
- "先运行 snapshot 再跑 diff")
893
+ print("[verify_life] 无可用基线——外部基线校验失败/未设置且无快照文件,"
894
+ "先修复基线来源或运行 snapshot 再跑 diff")
824
895
  return 2
825
896
  baseline_errors = check_errors(snap)
826
897
  if baseline_errors:
@@ -828,7 +899,7 @@ def _cmd_diff_unlocked() -> int:
828
899
  for error in baseline_errors:
829
900
  print(f" ✗ {error}")
830
901
  return 2
831
- src = "外部基线(BH_PRE_BASELINE)" if os.environ.get("BH_PRE_BASELINE") else "快照文件"
902
+ src = snap.get(BASELINE_SOURCE_FIELD, "未知来源")
832
903
  cur = load()
833
904
  current_errors = check_errors(cur)
834
905
  if current_errors:
@@ -48,7 +48,7 @@
48
48
  "exception.agent.zcode_bundle_missing_result": "Failed to generate zcode plugin bundle: missing plugin install result, refusing to record in hosts",
49
49
  "exception.cli.unhandled": "[bugx] ✗ Unhandled exception: {exc_type}: {exc}",
50
50
  "exception.cloud.auth_set_key_api_key_required": "auth set-key requires --api-key",
51
- "exception.common.agent_asset_missing": "BugX Agent resources not found; reinstall bugx-agent or set BUGX_ASSET_ROOT to a complete resource directory. For source-checkout development only, explicitly set BUGX_DEV_ASSET_ROOT=1.",
51
+ "exception.common.agent_asset_missing": "BugX Agent resources not found; reinstall bugx-cli or set BUGX_ASSET_ROOT to a complete resource directory. For source-checkout development only, explicitly set BUGX_DEV_ASSET_ROOT=1.",
52
52
  "exception.common.config_template_missing": "Cannot find {name} template; please reinstall BugX",
53
53
  "exception.common.engine_dir_contains_symlink": "Engine directory must not contain symlinks: {path}",
54
54
  "exception.common.engine_file_persist_failed": "Failed to persist engine file: {path}: {exc}",
@@ -454,7 +454,7 @@
454
454
  "host.entry.body.qoder_worker": "\n# BugX Worker — Qoder concurrent worker sub-agent\n\nYou are BugX's concurrent worker sub-agent, dispatched in parallel within a Round by the main agent through Qoder's subagent capability (`subagent_type=bugx-worker`). First read and obey the following global engine protocols via `bugx engine path --name <file>`; they are the only authoritative entities and this entry does not copy their content:\n\n- `bugx engine path --name bugx-worker.md`: worker unit-level execution rules (four start-up steps, mining discipline, case-filing oracle, hard evidence gate, checkpoint submission);\n- `bugx engine path --name bugx-runtime-contract.md` and `bugx engine path --name bugx-quick.md`: lifetime, Supervisor, evidence, and reporting protocols.\n\nThese files are provided by the global engine; do not inspect the project's `.bugx/core`. If the project lacks `.bugx/manifest.json`, stop immediately and report this to the dispatcher. The dispatcher must first run the read-only command `bugx engine --root <ROOT> status --json`; only a result of `UNINITIALIZED` permits `bugx engine --root <ROOT> pre` to safely prepare a fresh project. If the result is `FATAL_BLOCKED`, another blocked state, or the status check fails, preserve project data and stop; never bypass the gate with `bugx init`, `bugx reset`, or `--force`. After the project layout is safely prepared, the dispatcher may refresh host Worker integration from the main session if needed. A Worker never runs host-control initialization or installation commands and never executes protocol steps while the layout is missing.\n\n## Worker role boundary (mandatory)\n\n- Handle only the coverage units or affinity task bundles the Supervisor assigns to you: `claim` (skip when the host has pre-reserved) → `worker-start` → mine and produce evidence → `checkpoint`; `life_delta` must be 0, and you never write lifetime, settle accounts, produce the final report, or take units outside the list.\n- Use only the worker channel: the Supervisor MCP's `bugx-supervisor-worker` tools (claim/worker_start/tool_call/heartbeat/checkpoint), or the same-named subcommands of `audit_supervisor.py` in the global engine; never call host-control tools (start/bootstrap/next_round/bind_context/finish/fail/recover) and never run the host-control entries' `pre|post|settle`.\n- Evidence may only be written into the `artifact_root` returned by the claim; out-of-bounds paths are rejected by the Supervisor. Unless the dispatcher explicitly provides an independent git worktree, never modify shared worktree source — fixes are performed serially by the host.\n- During long commands send a heartbeat every 5 minutes; on a non-zero return or `CONTROL_PAUSED`/`CONTROL_ABORTED`, stop at a safe boundary and report the state to the dispatcher.\n\n## Qoder Worker interaction adaptation (mandatory)\n\nA worker is a sub-agent: it presents no startup gate and must not call `AskUserQuestion` — a regular start is decided automatically by project configuration and raises no serial startup questionnaire. When a user decision is truly required, end directly and report the raw `BUGX_INTERACTION_REQUEST <json>` to the dispatcher; never answer on your own or guess options. Treat the worker itself as non-TTY: forward only the current single-choice request and continue once the dispatcher returns the answer.\n",
455
455
  "plugin.zcode_plugin_boundary": "## User-level plugin boundary (plugin form only)\n\nThis entry is registered as a ZCode plugin (agent name `{agent_ref}`) and can be used across projects. Before operating on a project, run the read-only command `bugx engine --root . status --json`: only a result of `UNINITIALIZED` permits `bugx engine --root . pre` to safely prepare a fresh project. If the result is `FATAL_BLOCKED`, another blocked state, or the status check fails, preserve project data and stop; never bypass the gate with `bugx init`, `bugx reset`, or `--force`. This entry is not a substitute for the global engine payload.\n",
456
456
  "plugin.chatgpt_skill_banner": "This is the BugX ChatGPT Skill mirror. Before executing, read the global protocol via `bugx engine path --name AGENT_GUIDE.md` and `bugx engine path --name bugx.md`; the global engine is the only authoritative source for protocol and runtime.\n\nProtocol Mirror Version: {version}\n",
457
- "host.entry.section.commands": "## Host Route (before intent triage)\n\n- **ZCode host**: prefer loading the sibling `bugx-zcode` skill (ZCode-specific handbook: direct-drive path, rpc fallback, field-tested remedies). If it is not registered in the current session (newly installed skills need a host-session restart to appear), apply its core conclusions directly: after `workers` pre-claim, **drive the protocol channel from the host session** (worker MCP tools or `bugx supervisor rpc --role worker`, caller_role=worker); do not default to wrapping the worker in a subagent; `run_sandboxed_probe` must carry the current Task's lease_id/execution_id.\n- All other hosts follow the sections below.\n\n\n\n## How to Use This Skill (AI Meta-Guidance and Intent Decision Tree)\n\nWhen you (the AI) trigger and read this Skill, strictly follow this cognitive model and execution order:\n\n### 1. Intent Decision Tree\nIn the first second of receiving a task, classify which branch it belongs to:\n- **Branch A: Focused Quick Triage / Specific Function / Diff / Error Stack**\n - **Indicators**: Single-file inspection, reproducing a specific function, analyzing an exception stack trace.\n - **Action**: Write a lightweight reproduction test (PoC) or run targeted tests locally using `bugx view`, `bugx test-generate`, `bugx test-verify`; **strictly forbid starting heavy full-lifecycle gates!**\n- **Branch B: Full-Repository Vulnerability Hunting / Deep Mutation / Parallel Worker Audit**\n - **Indicators**: User explicitly triggers `/bugx`, requests \"full codebase audit\", or \"hunt deep vulnerabilities\".\n - **Action**: Follow the canonical lifecycle progression (`engine pre` -> gate confirmation -> Explore -> Mutate -> Repair -> post settlement).\n- **Branch C: Environment Diagnosis / Dependency Repair / Host Inspection**\n - **Action**: Run `bugx doctor --root <ROOT> --json` and `bugx engine --root <ROOT> status --json`; never use `init` or `--force` blindly.\n\n### 2. Standard 5-Step Execution Loop\n1. **Target Root**: Confirm the target repository's absolute path `<ROOT>`; strictly restrict operations within `<ROOT>`, and forbid broad filesystem scans.\n2. **Inspect State**: Run read-only commands to check runtime state first (`bugx engine --root <ROOT> status --json` or `bugx doctor`).\n3. **Select Route**: Pick commands based on intent; if parameters are needed, run `bugx help <top-level-cmd>` (e.g. `bugx help cloud`) to read live syntax dynamically; never guess.\n4. **Handle Gates**: If `engine pre` exits with code `2`, it signals waiting for host structured gate interaction; present options via the host's native control and execute the controlled action selected by the user. Do not fabricate choices or spin-loop. Exit code `0` confirms gate passage only, not audit completion.\n5. **Close the Loop**: Defects require standalone reproduction scripts (PoC) and call-stack evidence; report truthfully using the 6 standard status terms (read-only inspection, project ready, gate ready, test execution, mining launched, mining completed).\n\n### 3. Core Action Matrix (High-Frequency Commands Covering 90% of Calls)\n- **Environment Diagnosis**: `bugx doctor --root <ROOT> --json` (`--repair-assets` for repair)\n- **Startup and Gates**: Run `bugx engine --root <ROOT> status --json` first. Only when the status is `UNINITIALIZED`, run `bugx engine --root <ROOT> pre` to prepare a fresh project; do not run `bugx init` first when starting mining through a host plugin; it is a separate explicit CLI operation and does not replace the status/pre state machine. If the status is `FATAL_BLOCKED`, another blocked state, or the status check fails, preserve the state and stop; never use `init`, `reset`, or `--force` to bypass the gate.\n- **Reproduction and Mutation**: `bugx test-generate --root <ROOT> --scope <PATH::SYM> --out <FILE>` / `bugx test-verify verify --scope <SCOPE>`\n- **Supervisor and Concurrency**: `bugx supervisor status --root <ROOT>`\n- **Telemetry and Logs**: `bugx telemetry inspect` / `bugx log --root <ROOT> --errors`\n- **Dual Reports and Preview**: `bugx report both --eval-dir evals/oss --out evals/oss` / `bugx report serve --port 18991`\n\n### 4. Compact Command Radar (41 Top-level Commands Classified Index)\nTo invoke any command below, inspect exact parameters dynamically via `bugx help <cmd>`; never guess:\n- **Diagnostics and Inspection (9)**: `help`, `doctor`, `hosts`, `completion`, `log`, `stats`, `view`, `project`, `self-audit`\n- **Core Lifecycle and Hosts (14)**: `init`, `engine`, `supervisor`, `daemon`, `config`, `reset`, `install`, `uninstall`, `dsh`, `plugin`, `mcp`, `mcp-runtime`, `capability`, `logic-analysis`\n- **Deep Audit and Verification (10)**: `audit`, `probe`, `test-generate`, `test-audit`, `test-verify`, `patch-forge`, `test-strategy`, `fuzz-input`, `differential-probe`, `mining-audit`\n- **Knowledge Flywheel and Delivery (8)**: `report`, `lesson`, `knowledge`, `skill`, `cloud`, `auth`, `telemetry`, `advisory`\n\n### 5. Mandatory Rules and Deprecated Command Redirection\n- **Gate Blockage Forbids Destructive Repairs**: `FATAL_BLOCKED` must never be bypassed using `init`, `reset`, or `--force`; preserve logs and state first.\n- **Deprecated Command Redirections**: `matrix` -> `bugx audit`; `console` -> `bugx report serve`; `watch` -> `bugx log --watch`; `test` is an internal script, use `scripts/test_selector.py` instead.\n",
457
+ "host.entry.section.commands": "## Host Route (before intent triage)\n\n- **ZCode host**: prefer loading the sibling `bugx-zcode` skill (ZCode-specific handbook: direct-drive path, rpc fallback, field-tested remedies). If it is not registered in the current session (newly installed skills need a host-session restart to appear), apply its core conclusions directly: after `workers` pre-claim, **drive the protocol channel from the host session** (worker MCP tools or `bugx supervisor rpc --role worker`, caller_role=worker); do not default to wrapping the worker in a subagent; `run_sandboxed_probe` must carry the current Task's lease_id/execution_id.\n- All other hosts follow the sections below.\n\n\n\n## How to Use This Skill (AI Meta-Guidance and Intent Decision Tree)\n\nWhen you (the AI) trigger and read this Skill, strictly follow this cognitive model and execution order:\n\n### 1. Intent Decision Tree\nIn the first second of receiving a task, classify which branch it belongs to:\n- **Branch A: Focused Quick Triage / Specific Function / Diff / Error Stack**\n - **Indicators**: Single-file inspection, reproducing a specific function, analyzing an exception stack trace.\n - **Action**: Write a lightweight reproduction test (PoC) or run targeted tests locally using `bugx view`, `bugx test-generate`, `bugx test-verify`; **strictly forbid starting heavy full-lifecycle gates!**\n- **Branch B: Full-Repository Vulnerability Hunting / Deep Mutation / Parallel Worker Audit**\n - **Indicators**: User explicitly triggers `/bugx`, requests \"full codebase audit\", or \"hunt deep vulnerabilities\".\n - **Action**: Follow the canonical lifecycle progression (`engine pre` -> gate confirmation -> Explore -> Mutate -> Repair -> post settlement).\n- **Branch C: Environment Diagnosis / Dependency Repair / Host Inspection**\n - **Action**: Run `bugx doctor --root <ROOT> --json` and `bugx engine --root <ROOT> status --json`; never use `init` or `--force` blindly.\n\n### 2. Standard 5-Step Execution Loop\n1. **Target Root**: Confirm the target repository's absolute path `<ROOT>`; strictly restrict operations within `<ROOT>`, and forbid broad filesystem scans.\n2. **Inspect State**: Run read-only commands to check runtime state first (`bugx engine --root <ROOT> status --json` or `bugx doctor`).\n3. **Select Route**: Pick commands based on intent; if parameters are needed, run `bugx help <top-level-cmd>` (e.g. `bugx help cloud`) to read live syntax dynamically; never guess.\n4. **Handle Gates**: If `engine pre` exits with code `2`, it signals waiting for host structured gate interaction; present options via the host's native control and execute the controlled action selected by the user. Do not fabricate choices or spin-loop. Exit code `0` confirms gate passage only, not audit completion.\n5. **Close the Loop**: Defects require standalone reproduction scripts (PoC) and call-stack evidence; report truthfully using the 6 standard status terms (read-only inspection, project ready, gate ready, test execution, mining launched, mining completed).\n\n### 3. Core Action Matrix (High-Frequency Commands Covering 90% of Calls)\n- **Environment Diagnosis**: `bugx doctor --root <ROOT> --json` (`--repair-assets` for repair)\n- **Startup and Gates**: Run `bugx engine --root <ROOT> status --json` first. Only when the status is `UNINITIALIZED`, run `bugx engine --root <ROOT> pre` to prepare a fresh project; do not run `bugx init` first when starting mining through a host plugin; it is a separate explicit CLI operation and does not replace the status/pre state machine. If the status is `FATAL_BLOCKED`, another blocked state, or the status check fails, preserve the state and stop; never use `init`, `reset`, or `--force` to bypass the gate.\n- **Reproduction and Mutation**: `bugx test-generate --root <ROOT> --scope <PATH::SYM> --out <FILE>` / `bugx test-verify verify --scope <SCOPE>`\n- **Supervisor and Concurrency**: `bugx supervisor status --root <ROOT>`\n- **Telemetry and Logs**: `bugx telemetry inspect` / `bugx log --root <ROOT> --errors`\n- **Dual Reports and Preview**: `bugx report both --eval-dir verification/evals/oss --out verification/evals/oss` / `bugx report serve --port 18991`\n\n### 4. Compact Command Radar (41 Top-level Commands Classified Index)\nTo invoke any command below, inspect exact parameters dynamically via `bugx help <cmd>`; never guess:\n- **Diagnostics and Inspection (9)**: `help`, `doctor`, `hosts`, `completion`, `log`, `stats`, `view`, `project`, `self-audit`\n- **Core Lifecycle and Hosts (14)**: `init`, `engine`, `supervisor`, `daemon`, `config`, `reset`, `install`, `uninstall`, `dsh`, `plugin`, `mcp`, `mcp-runtime`, `capability`, `logic-analysis`\n- **Deep Audit and Verification (10)**: `audit`, `probe`, `test-generate`, `test-audit`, `test-verify`, `patch-forge`, `test-strategy`, `fuzz-input`, `differential-probe`, `mining-audit`\n- **Knowledge Flywheel and Delivery (8)**: `report`, `lesson`, `knowledge`, `skill`, `cloud`, `auth`, `telemetry`, `advisory`\n\n### 5. Mandatory Rules and Deprecated Command Redirection\n- **Gate Blockage Forbids Destructive Repairs**: `FATAL_BLOCKED` must never be bypassed using `init`, `reset`, or `--force`; preserve logs and state first.\n- **Deprecated Command Redirections**: `matrix` -> `bugx audit`; `console` -> `bugx report serve`; `watch` -> `bugx log --watch`; `test` is not a public command. For development checks, create a minimal temporary verification script outside the repository or run tests owned by the target project, then delete the process file.\n",
458
458
  "host.entry.description.codex": "Codex-specific BugX operation Skill for starting, resuming and diagnosing BugX audits and reviewing local model and token usage. Preserve the complete Agent workflow, native user gates and evidence validation while dispatching native Workers for the actual project scope.",
459
459
  "prompt.plugin.chatgpt_shared_skill_write_failed": "Shared global Skill write failed (plugin registration unaffected): {error}",
460
460
  "exception.plugin.claude_usage_skill_missing": "Claude host manual skill is missing; installation cannot complete: {path}\nThis file is a mandatory load listed in bugx/SKILL.md, not an optional add-on.\nFix: ensure ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md is tracked by git, then rebuild the wheel."