bugx-cli 0.1.0 → 0.1.1

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 (311) hide show
  1. package/README.md +190 -186
  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/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  11. package/core/assets/axe-core/LICENSE.txt +362 -0
  12. package/core/assets/axe-core/UPSTREAM.md +10 -0
  13. package/core/assets/axe-core/axe.min.js +12 -0
  14. package/core/assets/bugx-hero-en.svg +74 -0
  15. package/core/assets/bugx-hero-zh.svg +74 -0
  16. package/core/assets/codex.png +0 -0
  17. package/core/assets/dsh.png +0 -0
  18. package/core/assets/webui-chatgpt.jpg +0 -0
  19. package/core/assets/webui-session.jpg +0 -0
  20. package/core/assets/webui-skills.jpg +0 -0
  21. package/core/assets/webui-studio.jpg +0 -0
  22. package/core/assets/webui-zcode.jpg +0 -0
  23. package/core/assets/zcode.png +0 -0
  24. package/core/autonomous_cve/SPEC.md +1 -1
  25. package/core/autonomous_cve/attack_graph_store.py +152 -106
  26. package/core/autonomous_cve/behavior_graph.py +8 -2
  27. package/core/autonomous_cve/verifier.py +4 -1
  28. package/core/bugx.md +1 -1
  29. package/core/bugx_paths.py +43 -8
  30. package/core/cli-help.txt +66 -0
  31. package/core/cloud_sync/SPEC.md +1 -1
  32. package/core/cloud_sync/cloud_client.py +25 -6
  33. package/core/cloud_sync/cloud_onboard.py +42 -1
  34. package/core/cloud_sync/flywheel_client.py +16 -7
  35. package/core/cloud_sync/network_transport.py +24 -3
  36. package/core/cloud_sync/sensitive_filter.py +2 -2
  37. package/core/cloud_sync/sync_push.py +12 -10
  38. package/core/contracts/AGENT_GUIDE.md +6 -9
  39. package/core/contracts/README.md +2 -2
  40. package/core/contracts/bugx-runtime-contract.md +1 -1
  41. package/core/contracts/bugx-worker.md +1 -1
  42. package/core/contracts/engine_gap_contracts.py +86 -3
  43. package/core/coverage/coverage_discovery.py +599 -29
  44. package/core/coverage/coverage_evidence.py +47 -0
  45. package/core/coverage/coverage_forensics.py +9 -0
  46. package/core/coverage/coverage_validate.py +6 -1
  47. package/core/dev_harness/SPEC.md +1 -1
  48. package/core/engine-integrity.json +591 -419
  49. package/core/fuzzing/concurrency_fuzzer.py +53 -0
  50. package/core/fuzzing/differential_oracle.py +562 -27
  51. package/core/fuzzing/fuzz_input.py +109 -6
  52. package/core/fuzzing/stateful_fuzzer.py +72 -0
  53. package/core/governance/secret_redactor.py +22 -10
  54. package/core/host_acp/SPEC.md +1 -1
  55. package/core/host_acp/__init__.py +4 -4
  56. package/core/host_acp/claude.py +59 -1
  57. package/core/host_acp/cline.py +64 -1
  58. package/core/host_acp/codex.py +56 -1
  59. package/core/host_acp/dsh.py +59 -1
  60. package/core/host_acp/opencode.py +56 -1
  61. package/core/host_acp/pi.py +59 -1
  62. package/core/host_acp/zcode.py +59 -1
  63. package/core/host_runtime/SPEC.md +1 -1
  64. package/core/host_runtime/adapters.py +1 -1
  65. package/core/host_runtime/cline.py +13 -0
  66. package/core/host_runtime/host_evaluators.py +44 -4
  67. package/core/host_runtime/host_probe.py +1 -1
  68. package/core/host_runtime/host_provider_arbitrator.py +116 -62
  69. package/core/host_runtime/host_registry.py +15 -8
  70. package/core/host_runtime/mcp_registry_gate.py +12 -1
  71. package/core/host_runtime/pi.py +102 -0
  72. package/core/host_runtime/provider_facts.py +66 -0
  73. package/core/hosts/SPEC.md +1 -1
  74. package/core/hosts/__init__.py +6 -2
  75. package/core/hosts/_dsh_usage.py +1 -1
  76. package/core/hosts/base.py +32 -4
  77. package/core/hosts/claude.py +55 -0
  78. package/core/hosts/cline.py +6 -2
  79. package/core/hosts/codex.py +58 -0
  80. package/core/hosts/dsh.py +9 -1
  81. package/core/hosts/opencode.py +6 -6
  82. package/core/hosts/pi.py +159 -2
  83. package/core/infra/README.md +4 -2
  84. package/core/infra/__init__.py +2 -0
  85. package/core/infra/build_info.py +22 -3
  86. package/core/infra/client_metadata.py +1 -1
  87. package/core/infra/json_utils.py +22 -0
  88. package/core/launch_phases/README.md +2 -2
  89. package/core/launch_phases/SPEC.md +1 -1
  90. package/core/launch_phases/common.py +21 -2
  91. package/core/launch_phases/finding_confirm_phase.py +5 -1
  92. package/core/launch_phases/finding_settlement.py +188 -1
  93. package/core/launch_phases/judge_phase.py +69 -12
  94. package/core/launch_phases/orchestrator_controls.py +11 -7
  95. package/core/launch_phases/post_coverage_sync.py +9 -2
  96. package/core/launch_phases/post_phase.py +139 -3
  97. package/core/launch_phases/post_receipt.py +12 -1
  98. package/core/launch_phases/pre_phase.py +3 -3
  99. package/core/launch_phases/pre_recon_scout.py +53 -36
  100. package/core/launch_phases/pre_state_builder.py +23 -176
  101. package/core/launch_phases/round_orchestrator.py +15 -32
  102. package/core/launch_phases/session_runtime.py +56 -9
  103. package/core/launch_phases/startup_gates.py +36 -8
  104. package/core/launch_phases/startup_interaction.py +68 -12
  105. package/core/launch_phases/startup_version_gate.py +9 -3
  106. package/core/launch_phases/supervisor_bridge.py +46 -17
  107. package/core/launch_phases/supervisor_coverage.py +8 -2
  108. package/core/launch_phases/supervisor_degraded.py +1 -9
  109. package/core/launch_phases/worker_barriers.py +15 -5
  110. package/core/launch_phases/worker_orchestrator.py +105 -25
  111. package/core/ledger/README.md +1 -1
  112. package/core/ledger/SPEC.md +1 -1
  113. package/core/ledger/_facade.py +2 -1
  114. package/core/ledger/archive_ops.py +60 -2
  115. package/core/ledger/cli.py +6 -1
  116. package/core/ledger/export_ops.py +6 -1
  117. package/core/ledger/finding_confirmation.py +48 -6
  118. package/core/ledger/finding_lifecycle.py +428 -5
  119. package/core/ledger/finding_verification.py +44 -8
  120. package/core/ledger/incidents.py +10 -4
  121. package/core/ledger/patterns.py +10 -7
  122. package/core/ledger/receipt_contract.py +17 -1
  123. package/core/ledger/sync_ops.py +21 -16
  124. package/core/ledger/tool_experience.py +2 -1
  125. package/core/ledger/verify_life.py +88 -17
  126. package/core/locales/en-US.json +2 -2
  127. package/core/locales/zh-CN.json +2 -2
  128. package/core/mcp_handlers/SPEC.md +1 -1
  129. package/core/mcp_handlers/base.py +23 -3
  130. package/core/mcp_handlers/channel_lifecycle.py +85 -30
  131. package/core/mcp_handlers/retrieval_handlers.py +11 -1
  132. package/core/mcp_handlers/rpc_server.py +6 -1
  133. package/core/mcp_handlers/supervisor_handlers.py +32 -6
  134. package/core/mcp_handlers/tool_table.py +15 -0
  135. package/core/mcp_runtime_support/environment.py +0 -38
  136. package/core/mcp_runtime_support/verifier.py +0 -52
  137. package/core/metadata.txt +2 -3
  138. package/core/planning/README.md +1 -1
  139. package/core/planning/domain_router.py +4 -2
  140. package/core/planning/dynamic_flow_analyzer.py +219 -14
  141. package/core/planning/judge_pipeline.py +87 -4
  142. package/core/planning/prompt_harness.py +7 -5
  143. package/core/planning/spec_harvester.py +4 -4
  144. package/core/probes/INTERFACE.md +11 -1
  145. package/core/probes/SPEC.md +11 -1
  146. package/core/probes/__init__.py +46 -40
  147. package/core/probes/android_probe.py +177 -9
  148. package/core/probes/codebase_memory_probe.py +57 -0
  149. package/core/probes/desktop_probe.py +104 -0
  150. package/core/probes/differential_probe.py +99 -21
  151. package/core/probes/efficiency_probe.py +64 -0
  152. package/core/probes/ios_binary_probe.py +105 -1
  153. package/core/probes/memory_probe.py +66 -0
  154. package/core/probes/miniprogram_probe.py +75 -13
  155. package/core/probes/mobile_probe.py +215 -30
  156. package/core/probes/native_probe.py +88 -0
  157. package/core/probes/openwiki_probe.py +70 -0
  158. package/core/probes/pattern_probe.py +106 -0
  159. package/core/probes/platform_probe.py +81 -0
  160. package/core/probes/probe_registry.py +108 -7
  161. package/core/probes/sast_fixture_corpus.py +340 -0
  162. package/core/probes/sast_probe.py +553 -52
  163. package/core/probes/sast_rules.py +668 -28
  164. package/core/probes/sca_scanner.py +48 -0
  165. package/core/probes/ui_accessibility.py +149 -0
  166. package/core/probes/ui_audit.py +513 -0
  167. package/core/probes/ui_contract.py +273 -0
  168. package/core/probes/ui_evidence.py +212 -0
  169. package/core/probes/ui_measurements.py +314 -0
  170. package/core/probes/ui_repair.py +250 -0
  171. package/core/probes/ui_review.py +133 -0
  172. package/core/probes/ui_storybook.py +107 -0
  173. package/core/probes/ui_tokens.py +185 -0
  174. package/core/probes/ui_visual_diff.py +131 -0
  175. package/core/probes/web_probe.py +373 -18
  176. package/core/project_profiler/SPEC.md +1 -1
  177. package/core/project_profiler/arbitrator.py +6 -1
  178. package/core/project_profiler/detector.py +8 -1
  179. package/core/project_profiler/strategy.py +51 -15
  180. package/core/prompts/command_routing_en.md +2 -2
  181. package/core/prompts/command_routing_zh.md +2 -2
  182. package/core/prompts/stages/stage_repair.md +1 -1
  183. package/core/repair/README.md +1 -1
  184. package/core/repair/l7_repair_loop.py +1 -4
  185. package/core/repair/rsi_fixer.py +4 -4
  186. package/core/repair/rsi_loop.py +1 -3
  187. package/core/repair/rsi_repair.py +7 -7
  188. package/core/repair/rsi_scope.py +27 -8
  189. package/core/report_engine/SPEC.md +1 -1
  190. package/core/report_engine/attestation.py +8 -4
  191. package/core/report_engine/finding_report.py +2 -1
  192. package/core/report_engine/models.py +7 -9
  193. package/core/report_engine/sast_bridge.py +2 -2
  194. package/core/report_engine/server.py +18 -8
  195. package/core/report_engine/web-conformance.md +123 -18
  196. package/core/report_engine/web_conformance.py +21 -52
  197. package/core/retrieval/README.md +1 -1
  198. package/core/retrieval/SPEC.md +1 -1
  199. package/core/retrieval/code_analyzer.py +50 -14
  200. package/core/retrieval/context_assembler.py +7 -1
  201. package/core/retrieval/knowledge_sync.py +108 -14
  202. package/core/retrieval/symbol_index.py +25 -6
  203. package/core/retrieval/universal_code_matcher.py +234 -49
  204. package/core/runtime/README.md +1 -1
  205. package/core/runtime/bugx_logging.py +78 -7
  206. package/core/runtime/fixture_solidify.py +5 -10
  207. package/core/runtime/incident_eval.py +1 -1
  208. package/core/runtime/model_runner.py +4 -41
  209. package/core/runtime/platform_adapter.py +2 -2
  210. package/core/runtime/prep_validate.py +4 -2
  211. package/core/runtime/project_settings.py +2 -1
  212. package/core/runtime/scenario_eval.py +50 -8
  213. package/core/skills/bugx_docs_mcp_server.py +3 -1
  214. package/core/skills/bugx_mcp_server.py +29 -2
  215. package/core/skills/tools_kb.py +1 -1
  216. package/core/supervisor/README.md +1 -1
  217. package/core/supervisor/SPEC.md +1 -1
  218. package/core/supervisor/budget_governor.py +503 -9
  219. package/core/supervisor/checkpoint_pipeline.py +248 -6
  220. package/core/supervisor/checkpoint_sync.py +13 -0
  221. package/core/supervisor/claim_events.py +1 -1
  222. package/core/supervisor/finding_workflow.py +22 -5
  223. package/core/supervisor/lease_manager.py +1 -1
  224. package/core/supervisor/lifecycle_blocks.py +6 -1
  225. package/core/supervisor/rejection_remedies.py +52 -5
  226. package/core/supervisor/serial_authorization.py +48 -4
  227. package/core/supervisor/task_scheduler.py +2 -2
  228. package/core/supervisor/worker_checkpoint.py +8 -1
  229. package/core/supervisor/worker_runtime.py +8 -2
  230. package/core/supervisor_types/worker_claim.py +9 -0
  231. package/core/webui/README.md +1 -1
  232. package/core/webui/SPEC.md +2 -1
  233. package/core/webui/adapters/claude.py +5 -1
  234. package/core/webui/adapters/cline.py +10 -2
  235. package/core/webui/adapters/codex.py +5 -1
  236. package/core/webui/adapters/dsh.py +5 -1
  237. package/core/webui/docs_session_service.py +2 -2
  238. package/core/webui/mcp_inspector.py +11 -7
  239. package/core/webui/static/00-base.css +1060 -0
  240. package/core/webui/static/01-monitoring.css +802 -0
  241. package/core/webui/static/02-header-actions.css +321 -0
  242. package/core/webui/static/03-trigger-popover.css +697 -0
  243. package/core/webui/static/04-composer.css +628 -0
  244. package/core/webui/static/05-skills-center.css +878 -0
  245. package/core/webui/static/06-mcp-center.css +623 -0
  246. package/core/webui/static/07-skill-detail.css +265 -0
  247. package/core/webui/static/08-files-management.css +167 -0
  248. package/core/webui/static/09-files-center.css +386 -0
  249. package/core/webui/static/10-icons.css +105 -0
  250. package/core/webui/static/11-project-options.css +185 -0
  251. package/core/webui/static/12-profile-tab.css +383 -0
  252. package/core/webui/static/design-tokens.css +113 -0
  253. package/core/webui/static/index.html +14 -1
  254. package/core/webui/workspace_service.py +1 -1
  255. package/docs/07_distribution/01_README_NPM.md +190 -186
  256. package/ecosystem/integrations/README.md +1 -1
  257. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  258. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  259. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  260. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
  261. package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
  262. package/ecosystem/integrations/opencode/opencode.json +23 -12
  263. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  264. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  265. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  266. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  267. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  268. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  269. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  270. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  271. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  272. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  273. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
  274. package/interfaces/bin/bugx.js +37 -0
  275. package/interfaces/cli/bugx_cli/__init__.py +4 -2
  276. package/interfaces/cli/bugx_cli/cli.py +11 -4
  277. package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
  278. package/interfaces/cli/bugx_cli/commands/agent.py +339 -73
  279. package/interfaces/cli/bugx_cli/commands/audit.py +2 -2
  280. package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
  281. package/interfaces/cli/bugx_cli/commands/cloud.py +4 -3
  282. package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
  283. package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
  284. package/interfaces/cli/bugx_cli/commands/knowledge.py +2 -0
  285. package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
  286. package/interfaces/cli/bugx_cli/commands/plugin.py +55 -20
  287. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
  288. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
  289. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
  290. package/interfaces/cli/bugx_cli/commands/report.py +2 -6
  291. package/interfaces/cli/bugx_cli/commands/system.py +11 -11
  292. package/interfaces/cli/bugx_cli/common.py +15 -7
  293. package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
  294. package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
  295. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
  296. package/interfaces/cli/bugx_cli/infra/engine_installer.py +18 -10
  297. package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
  298. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
  299. package/interfaces/cli/bugx_cli/infra/security.py +13 -6
  300. package/package.json +2 -1
  301. package/pyproject.toml +20 -8
  302. package/scripts/ensure-python.mjs +7 -7
  303. package/scripts/sync-version.mjs +10 -21
  304. package/scripts/test-npm-wrapper.mjs +1 -1
  305. package/core/webui/static/project-settings.css +0 -6458
  306. package/docs/07_distribution/README.md +0 -16
  307. package/docs/README.md +0 -121
  308. package/interfaces/README.md +0 -143
  309. package/interfaces/bin/README.md +0 -35
  310. package/interfaces/cli/README.md +0 -90
  311. package/scripts/README.md +0 -118
@@ -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."
@@ -48,7 +48,7 @@
48
48
  "exception.agent.zcode_bundle_missing_result": "zcode 插件包生成失败:缺少插件安装结果,拒绝写入 hosts 记录",
49
49
  "exception.cli.unhandled": "[bugx] ✗ 未处理异常: {exc_type}: {exc}",
50
50
  "exception.cloud.auth_set_key_api_key_required": "auth set-key 必须提供 --api-key",
51
- "exception.common.agent_asset_missing": "找不到 BugX Agent 资源;请重新安装 bugx-agent,或设置 BUGX_ASSET_ROOT 指向完整资源目录。仅在源码仓库开发时,显式设置 BUGX_DEV_ASSET_ROOT=1。",
51
+ "exception.common.agent_asset_missing": "找不到 BugX Agent 资源;请重新安装 bugx-cli,或设置 BUGX_ASSET_ROOT 指向完整资源目录。仅在源码仓库开发时,显式设置 BUGX_DEV_ASSET_ROOT=1。",
52
52
  "exception.common.config_template_missing": "找不到 {name} 模板;请重新安装 BugX",
53
53
  "exception.common.engine_dir_contains_symlink": "引擎目录不得包含符号链接: {path}",
54
54
  "exception.common.engine_file_persist_failed": "无法持久化引擎文件: {path}: {exc}",
@@ -454,7 +454,7 @@
454
454
  "host.entry.body.qoder_worker": "\n# BugX Worker — Qoder 并发 Worker 子智能体\n\n你是 BugX 的并发 worker 子智能体,由主 Agent 通过 Qoder 的 subagent 能力(`subagent_type=bugx-worker`)在 Round 内并发派发。先通过 `bugx engine path --name <文件>` 读取并遵守以下全局引擎协议;它们是唯一权威实体,本入口不复制其内容:\n\n- `bugx engine path --name bugx-worker.md`:worker 单元级执行规则(开工四步、挖掘纪律、立案 oracle、证据硬门槛、checkpoint 提交);\n- `bugx engine path --name bugx-runtime-contract.md` 与 `bugx engine path --name bugx-quick.md`:寿命、Supervisor、证据和报告协议。\n\n上述文件由全局引擎提供,不检查项目 `.bugx/core`。若项目缺少 `.bugx/manifest.json`,立即停止并将事实报告给派发方。派发方必须先运行只读命令 `bugx engine --root <ROOT> status --json`:只有结果为 `UNINITIALIZED` 时才运行 `bugx engine --root <ROOT> pre` 安全准备新项目;若为 `FATAL_BLOCKED`、其他阻断状态或检查失败,保留项目数据并停止,不得用 `bugx init`、`bugx reset` 或 `--force` 绕过。项目布局准备完成后,如需刷新宿主 Worker 集成,由派发方在主会话中执行;Worker 不运行主控初始化或安装命令,也不在布局缺失时执行协议步骤。\n\n## Worker 角色边界(强制)\n\n- 只负责 Supervisor 分配给你的覆盖单元或亲和任务包:`claim`(宿主已预占时跳过)→ `worker-start` → 挖掘举证 → `checkpoint`;`life_delta` 必须为 0,不写寿命、不结算、不生成最终报告、不领取清单外的单元。\n- 只能使用 worker 通道:Supervisor MCP 的 `bugx-supervisor-worker` 工具(claim/worker_start/tool_call/heartbeat/checkpoint),或全局引擎中的 `audit_supervisor.py` 的同名子命令;不得调用宿主控制工具(start/bootstrap/next_round/bind_context/finish/fail/recover),不得执行宿主控制入口的 `pre|post|settle`。\n- 证据只能写入 claim 返回的 `artifact_root`,越界路径会被 Supervisor 拒绝;没有派发方明确提供独立 git worktree 时,不得修改共享工作树源码,修复由宿主串行完成。\n- 长命令期间每 5 分钟补一次 heartbeat;返回非零或 `CONTROL_PAUSED`/`CONTROL_ABORTED` 时,停在安全边界并把状态报告给派发方。\n\n## Qoder Worker 交互适配(强制)\n\nWorker 是子智能体,不呈现任何启动门禁,也不得调用 `AskUserQuestion`——常规启动由项目配置自动决策,不发起串行启动问卷。确需用户决策时,直接结束并把 `BUGX_INTERACTION_REQUEST <json>` 原文报告给派发方,不得自行作答或猜选项。Worker 自身按非 TTY 处理:只转发当前一个单选请求,答案由派发方回传后再继续。\n",
455
455
  "plugin.zcode_plugin_boundary": "## 用户级插件边界(插件形态专用)\n\n本入口以 ZCode 插件(agent 命名 `{agent_ref}`)注册,可跨项目使用。操作项目前先运行只读命令 `bugx engine --root . status --json`:仅当返回 `UNINITIALIZED` 时,才运行 `bugx engine --root . pre` 安全准备新项目;返回 `FATAL_BLOCKED`、其他阻断状态或检查失败时,保留数据并停止,严禁用 `bugx init`、`bugx reset` 或 `--force` 绕过。本入口不能替代全局引擎载荷。\n",
456
456
  "plugin.chatgpt_skill_banner": "这是 BugX 的 ChatGPT Skill 镜像。执行前通过 `bugx engine path --name AGENT_GUIDE.md` 和 `bugx engine path --name bugx.md` 读取全局协议;全局引擎是协议和运行时的唯一权威来源。\n\n协议镜像版本:{version}\n",
457
- "host.entry.section.commands": "## 宿主路由(先于意图分流)\n\n- **ZCode 宿主**:优先加载同插件 `bugx-zcode` skill(ZCode 专属手册:直驱路径、rpc 回退、坑位对策)。若当前会话未注册该 skill(新装 skill 需重启宿主会话才可见),直接按其核心结论执行:`workers` 预占后**由宿主会话直驱协议通道**(worker MCP 工具或 `bugx supervisor rpc --role worker`,caller_role=worker),勿默认为 worker 派发子代理;`run_sandboxed_probe` 必须携带本次 Task 的 lease_id/execution_id。\n- 其余宿主按后续章节执行。\n\n\n\n## 如何使用本技能(AI 执行元指南与意图决策树)\n\n当你(AI)触发并阅读本技能时,请无条件遵循以下认知模型与执行时序:\n\n### 1. 意图决策树(Triage Decision Tree)\n拿到任务第一秒,判定属于哪个分支:\n- **分支 A:单点敏捷排查 / 特定函数 / Diff / 报错堆栈**\n - **标志**:单文件排查、复现某个函数、分析异常报错。\n - **动作**:就地编写轻量复现脚本(PoC)或运行定向测试,使用 `bugx view`, `bugx test-generate`, `bugx test-verify`;**严禁启动重型全流程门禁!**\n- **分支 B:全库漏洞挖掘 / 深度变异 / 多 Worker 并发审计**\n - **标志**:用户明确输入 `/bugx`、要求“全库审计”、“挖掘潜在漏洞”。\n - **动作**:按标准生命周期流转(`engine pre` -> 门禁确认 -> Explore -> Mutate -> Repair -> 结算)。\n- **分支 C:环境诊断 / 依赖修复 / 宿主状态排查**\n - **动作**:优先运行 `bugx doctor --root <ROOT> --json` 与 `bugx engine --root <ROOT> status --json`,绝不盲目 `init` 或 `--force`。\n\n### 2. 标准五步操作闭环(5-Step Execution Loop)\n1. **定根**:确定被测项目根绝对路径 `<ROOT>`,严格在 `<ROOT>` 内部执行,禁止全盘发散扫描。\n2. **探况**:先执行只读命令检查运行态(`bugx engine --root <ROOT> status --json` 或 `bugx doctor`)。\n3. **选路**:根据意图挑选命令;若需查阅参数,运行 `bugx help <顶层命令>`(如 `bugx help cloud`)按需动态读取,严禁盲猜。\n4. **承接**:若 `engine pre` 返回退出码 `2`,表示等待宿主单选门禁交互;必须调用宿主原生控件展示选项,按用户选择的 action 执行,禁止文本伪造选择或自旋重试。退出码 `0` 只代表门禁通过,不代表挖掘完成。\n5. **闭环**:缺陷必须给出最小独立复现脚本(PoC)与完整调用栈证据;使用 6 大标准汇报用词(只读检查、项目就绪、门禁就绪、测试执行、挖掘启动、挖掘完成)如实汇报。\n\n### 3. 高频场景命令(覆盖 90% 日常调用)\n- **环境诊断**:`bugx doctor --root <ROOT> --json`(`--repair-assets` 按需修复)\n- **启动与门禁**:先运行 `bugx engine --root <ROOT> status --json`;仅当状态为 `UNINITIALIZED` 时运行 `bugx engine --root <ROOT> pre` 自动准备新项目。挖掘启动不要先调用 `bugx init`;它是独立 CLI 初始化操作,不替代 status/pre 状态机。若状态为 `FATAL_BLOCKED`、其他阻断状态或检查失败,保留现场并停止;禁止用 `init`、`reset` 或 `--force` 绕过门禁。\n- **单点复现与变异**:`bugx test-generate --root <ROOT> --scope <PATH::SYM> --out <FILE>` / `bugx test-verify verify --scope <SCOPE>`\n- **Supervisor 与并发排查**:`bugx supervisor status --root <ROOT>`\n- **脱敏飞轮与日志**:`bugx telemetry inspect` / `bugx log --root <ROOT> --errors`\n- **双轨报告与预览**:`bugx report both --eval-dir evals/oss --out evals/oss` / `bugx report serve --port 18991`\n\n### 4. 紧凑型命令全景雷达(41 个顶层命令分类索引)\n如需调用以下命令,通过 `bugx help <命令>` 动态获取具体参数与子命令,严禁盲猜:\n- **诊断探索 (9)**:`help`, `doctor`, `hosts`, `completion`, `log`, `stats`, `view`, `project`, `self-audit`\n- **核心生命周期 (14)**:`init`, `engine`, `supervisor`, `daemon`, `config`, `reset`, `install`, `uninstall`, `dsh`, `plugin`, `mcp`, `mcp-runtime`, `capability`, `logic-analysis`\n- **深度审计验证 (10)**:`audit`, `probe`, `test-generate`, `test-audit`, `test-verify`, `patch-forge`, `test-strategy`, `fuzz-input`, `differential-probe`, `mining-audit`\n- **知识飞轮交付 (8)**:`report`, `lesson`, `knowledge`, `skill`, `cloud`, `auth`, `telemetry`, `advisory`\n\n### 5. 核心军规与废弃命令重定向\n- **阻断不授权暴力修复**:`FATAL_BLOCKED` 严禁使用 `init`、`reset`、`--force` 绕过,先保留报告和日志。\n- **废弃命令重定向**:`matrix` -> `bugx audit`;`console` -> `bugx report serve`;`watch` -> `bugx log --watch`;`test` 为内部脚本改用 `scripts/test_selector.py`。\n",
457
+ "host.entry.section.commands": "## 宿主路由(先于意图分流)\n\n- **ZCode 宿主**:优先加载同插件 `bugx-zcode` skill(ZCode 专属手册:直驱路径、rpc 回退、坑位对策)。若当前会话未注册该 skill(新装 skill 需重启宿主会话才可见),直接按其核心结论执行:`workers` 预占后**由宿主会话直驱协议通道**(worker MCP 工具或 `bugx supervisor rpc --role worker`,caller_role=worker),勿默认为 worker 派发子代理;`run_sandboxed_probe` 必须携带本次 Task 的 lease_id/execution_id。\n- 其余宿主按后续章节执行。\n\n\n\n## 如何使用本技能(AI 执行元指南与意图决策树)\n\n当你(AI)触发并阅读本技能时,请无条件遵循以下认知模型与执行时序:\n\n### 1. 意图决策树(Triage Decision Tree)\n拿到任务第一秒,判定属于哪个分支:\n- **分支 A:单点敏捷排查 / 特定函数 / Diff / 报错堆栈**\n - **标志**:单文件排查、复现某个函数、分析异常报错。\n - **动作**:就地编写轻量复现脚本(PoC)或运行定向测试,使用 `bugx view`, `bugx test-generate`, `bugx test-verify`;**严禁启动重型全流程门禁!**\n- **分支 B:全库漏洞挖掘 / 深度变异 / 多 Worker 并发审计**\n - **标志**:用户明确输入 `/bugx`、要求“全库审计”、“挖掘潜在漏洞”。\n - **动作**:按标准生命周期流转(`engine pre` -> 门禁确认 -> Explore -> Mutate -> Repair -> 结算)。\n- **分支 C:环境诊断 / 依赖修复 / 宿主状态排查**\n - **动作**:优先运行 `bugx doctor --root <ROOT> --json` 与 `bugx engine --root <ROOT> status --json`,绝不盲目 `init` 或 `--force`。\n\n### 2. 标准五步操作闭环(5-Step Execution Loop)\n1. **定根**:确定被测项目根绝对路径 `<ROOT>`,严格在 `<ROOT>` 内部执行,禁止全盘发散扫描。\n2. **探况**:先执行只读命令检查运行态(`bugx engine --root <ROOT> status --json` 或 `bugx doctor`)。\n3. **选路**:根据意图挑选命令;若需查阅参数,运行 `bugx help <顶层命令>`(如 `bugx help cloud`)按需动态读取,严禁盲猜。\n4. **承接**:若 `engine pre` 返回退出码 `2`,表示等待宿主单选门禁交互;必须调用宿主原生控件展示选项,按用户选择的 action 执行,禁止文本伪造选择或自旋重试。退出码 `0` 只代表门禁通过,不代表挖掘完成。\n5. **闭环**:缺陷必须给出最小独立复现脚本(PoC)与完整调用栈证据;使用 6 大标准汇报用词(只读检查、项目就绪、门禁就绪、测试执行、挖掘启动、挖掘完成)如实汇报。\n\n### 3. 高频场景命令(覆盖 90% 日常调用)\n- **环境诊断**:`bugx doctor --root <ROOT> --json`(`--repair-assets` 按需修复)\n- **启动与门禁**:先运行 `bugx engine --root <ROOT> status --json`;仅当状态为 `UNINITIALIZED` 时运行 `bugx engine --root <ROOT> pre` 自动准备新项目。挖掘启动不要先调用 `bugx init`;它是独立 CLI 初始化操作,不替代 status/pre 状态机。若状态为 `FATAL_BLOCKED`、其他阻断状态或检查失败,保留现场并停止;禁止用 `init`、`reset` 或 `--force` 绕过门禁。\n- **单点复现与变异**:`bugx test-generate --root <ROOT> --scope <PATH::SYM> --out <FILE>` / `bugx test-verify verify --scope <SCOPE>`\n- **Supervisor 与并发排查**:`bugx supervisor status --root <ROOT>`\n- **脱敏飞轮与日志**:`bugx telemetry inspect` / `bugx log --root <ROOT> --errors`\n- **双轨报告与预览**:`bugx report both --eval-dir verification/evals/oss --out verification/evals/oss` / `bugx report serve --port 18991`\n\n### 4. 紧凑型命令全景雷达(41 个顶层命令分类索引)\n如需调用以下命令,通过 `bugx help <命令>` 动态获取具体参数与子命令,严禁盲猜:\n- **诊断探索 (9)**:`help`, `doctor`, `hosts`, `completion`, `log`, `stats`, `view`, `project`, `self-audit`\n- **核心生命周期 (14)**:`init`, `engine`, `supervisor`, `daemon`, `config`, `reset`, `install`, `uninstall`, `dsh`, `plugin`, `mcp`, `mcp-runtime`, `capability`, `logic-analysis`\n- **深度审计验证 (10)**:`audit`, `probe`, `test-generate`, `test-audit`, `test-verify`, `patch-forge`, `test-strategy`, `fuzz-input`, `differential-probe`, `mining-audit`\n- **知识飞轮交付 (8)**:`report`, `lesson`, `knowledge`, `skill`, `cloud`, `auth`, `telemetry`, `advisory`\n\n### 5. 核心军规与废弃命令重定向\n- **阻断不授权暴力修复**:`FATAL_BLOCKED` 严禁使用 `init`、`reset`、`--force` 绕过,先保留报告和日志。\n- **废弃命令重定向**:`matrix` -> `bugx audit`;`console` -> `bugx report serve`;`watch` -> `bugx log --watch`;`test` 不是公共命令。开发验证请在仓库外生成最小临时验证脚本,或运行被测目标项目自带的测试,完成后删除过程文件。\n",
458
458
  "host.entry.description.codex": "Codex 宿主专属 BugX 操作 Skill。用于在 Codex 中启动、恢复和排障 BugX 审计及读取本地模型与 Token 用量。保留完整 Agent 流程、原生用户门禁和证据校验;按项目规模分派真实原生 Worker。",
459
459
  "prompt.plugin.chatgpt_shared_skill_write_failed": "共享全局 Skill 写入失败(不影响插件注册):{error}",
460
460
  "exception.plugin.claude_usage_skill_missing": "Claude 宿主手册 Skill 缺失,无法完成安装:{path}\n该文件是 bugx/SKILL.md 要求的强制加载项,不属于可选增强件。\n修复:确认仓库内 ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md 已纳入版本控制(git add),并重新构建 wheel。"
@@ -21,5 +21,5 @@ result = dispatch_tool_call('health_snapshot', {})
21
21
  ```
22
22
 
23
23
  ## 5. Maintenance & Verification
24
- - Unit & regression tests for this package are registered in `tests/test_registry.json`.
24
+ - Verification is performed with short-lived tests outside the repository; no persistent `tests/` registry is retained.
25
25
  - Changes to exported interfaces must be synchronized via `python3 scripts/gen_interface_spec.py --package core/mcp_handlers --write`.
@@ -3,6 +3,7 @@
3
3
 
4
4
  from __future__ import annotations
5
5
 
6
+ import dataclasses
6
7
  import json
7
8
  import math
8
9
  from pathlib import Path
@@ -29,9 +30,19 @@ MAX_INLINE_COVERAGE_UNITS = 32
29
30
  class McpProtocolError(RuntimeError):
30
31
  """Invalid MCP request or unsupported operation."""
31
32
 
32
- def __init__(self, message: str, code: int = -32602) -> None:
33
+ def __init__(
34
+ self,
35
+ message: str,
36
+ code: int = -32602,
37
+ *,
38
+ data: Mapping[str, object] | None = None,
39
+ ) -> None:
33
40
  super().__init__(message)
34
41
  self.code = code
42
+ # DEF-2 残余缺口:结构化拒绝原因(如 evidence_feedback)随异常携带,
43
+ # 供 rpc_server 的 _call_failure_data 透传到回包 data 字段。默认 None
44
+ # 保持既有调用零破坏;用独立属性名避免与第三方异常的 data 属性混淆。
45
+ self.mcp_error_data = dict(data) if data else None
35
46
 
36
47
 
37
48
  def i18n_exc(key: str, fallback: str, locale: str | None = None, **kwargs: Any) -> str:
@@ -302,7 +313,16 @@ def format_result(value: object, *, is_error: bool = False, summary: str | None
302
313
 
303
314
  def serialize_value(value: object) -> object:
304
315
  if hasattr(value, "to_dict"):
305
- return value.to_dict() # type: ignore[no-any-return]
316
+ # F-RSI-20261110-030:to_dict() 结果必须继续递归序列化。原实现
317
+ # 直接返回 to_dict() 产物——嵌套的 Path/tuple/Mapping 原样穿透,
318
+ # 下游 compact_json 直接 TypeError;而同函数的 _asdict 分支是
319
+ # 递归的,双标不对称。领域对象的 to_dict 现在返回 JSON 净形,
320
+ # 但序列化契约不能依赖「今天恰好都是干净类型」。
321
+ return serialize_value(value.to_dict()) # type: ignore[no-any-return]
322
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
323
+ # F-RSI-20261110-030 补:无 to_dict 的 dataclass 领域对象同样
324
+ # 原样穿透(SimpleNamespace 实测无 _asdict,namedtuple 才有)。
325
+ return serialize_value(dataclasses.asdict(value))
306
326
  if hasattr(value, "_asdict"):
307
327
  return serialize_value(value._asdict())
308
328
  if isinstance(value, Path):
@@ -374,7 +394,7 @@ def project_state(
374
394
  #
375
395
  # 规则:
376
396
  # 1. `_next_action` 的每个取值都必须在 `RECOVERY_CHAIN_BY_ACTION` 中出现
377
- # (空元组 = 明确「无需恢复」),由测试穷举守卫;
397
+ # (空元组 = 明确「无需恢复」),穷举契约以本表为准;
378
398
  # 2. 每步的角色归属只在本表声明,禁止在 `_recovery_chain` 内硬编码
379
399
  # (BX-ENGINE-16:工具表 / handler / 恢复链三源漂移曾导致「虚假可用性」);
380
400
  # 3. 步骤顺序即拓扑序(BX-R4-04):一次只干一件,前置互相打架的三岔路口不再出现。
@@ -120,6 +120,17 @@ _CHANNEL_IDLE_ENV = {
120
120
  _DEFAULT_CHANNEL_IDLE_SELF_EXIT_SECONDS = 1800.0
121
121
  _CHANNEL_IDLE_CHECK_INTERVAL_SECONDS = 30.0
122
122
  _TAKEOVER_GRACE_SECONDS = 5.0
123
+ # 第四批修复(收尾空转治理):owner(宿主)进程死亡的独立快速检查。
124
+ # 实证(3 份 receipt):会话 post/idle 后空转 30-64min 才自释放;宿主进程
125
+ # 死亡后 controller 空转最长 48min——墙钟乘数 3-6.7× 的主源。空闲自退阈值
126
+ # (1800s,设计值不放宽)只保护"宿主还活着但暂时不说话"的场景;宿主进程
127
+ # 本身死亡是确定性信号,必须与 idle 周期解耦、快速收敛:
128
+ # * 检查节奏:每 _CHANNEL_OWNER_WATCH_INTERVAL_SECONDS 看一次孤儿化;
129
+ # * 触发条件:getppid 相对启动时父 PID 变化(孤儿化,PID 复用方向安全——
130
+ # 复用会让 getppid 保持稳定不触发)+ 通道空闲 ≥ 60s + 无进行中调用。
131
+ # 由此"宿主死亡 → controller 自释放"的延迟从 30-64min 收敛到 ≤75s。
132
+ _CHANNEL_OWNER_WATCH_INTERVAL_SECONDS = 15.0
133
+ _CHANNEL_ORPHAN_MIN_IDLE_SECONDS = 60.0
123
134
 
124
135
 
125
136
  def _idle_self_exit_seconds(role: str) -> float:
@@ -269,6 +280,36 @@ def _channel_self_retire(
269
280
  hook(0)
270
281
 
271
282
 
283
+ def _orphaned_owner_reason(
284
+ activity: "_ChannelActivity", initial_parent_pid: int,
285
+ ) -> str | None:
286
+ """owner(宿主)进程死亡的快速自释放判据;不满足返回 ``None``(fail-safe)。
287
+
288
+ 三个前置条件同时满足才自释放(宁可多活一轮,不可误退):
289
+ 1. 仅 host(controller)角色——worker 通道沿用空闲自退;
290
+ 2. 无进行中的工具调用;
291
+ 3. 父进程 PID 相对启动时发生变化(孤儿化)且通道已空闲
292
+ ≥ ``_CHANNEL_ORPHAN_MIN_IDLE_SECONDS``。
293
+ 读不到 ppid 时按"不确定"处理,不自退。
294
+ """
295
+ if activity.role != "host":
296
+ return None
297
+ if activity.inflight:
298
+ return None
299
+ try:
300
+ current_ppid = os.getppid()
301
+ except OSError:
302
+ return None
303
+ if current_ppid == initial_parent_pid:
304
+ return None
305
+ if activity.idle_seconds() < _CHANNEL_ORPHAN_MIN_IDLE_SECONDS:
306
+ return None
307
+ return (
308
+ f"owner process dead (initial parent pid {initial_parent_pid},"
309
+ f" current ppid {current_ppid}); orphaned controller self-release"
310
+ )
311
+
312
+
272
313
  def _channel_idle_monitor_loop(
273
314
  service: "BugxMcpService",
274
315
  activity: "_ChannelActivity",
@@ -277,18 +318,54 @@ def _channel_idle_monitor_loop(
277
318
  lease: "_ControllerLease | None" = None,
278
319
  interval: float | None = None,
279
320
  exit_hook: "Callable[[int], None] | None" = None,
321
+ initial_parent_pid: int | None = None,
280
322
  ) -> None:
281
- """后台检查线程:每 ``interval`` 秒判定一次是否应自退。"""
323
+ """后台检查线程:空闲自退与孤儿 owner 快速自释放**解耦**为双周期。
324
+
325
+ * 空闲自退:每 ``interval``(默认 _CHANNEL_IDLE_CHECK_INTERVAL_SECONDS)
326
+ 秒按原前置条件判定一次;
327
+ * 孤儿自释放(第四批修复):每 _CHANNEL_OWNER_WATCH_INTERVAL_SECONDS
328
+ 秒独立判定一次(:func:`_orphaned_owner_reason`),宿主死亡后不再空转
329
+ 满 1800s idle 超时。
330
+ """
282
331
  period = _CHANNEL_IDLE_CHECK_INTERVAL_SECONDS if interval is None else interval
332
+ try:
333
+ period = max(0.05, float(period))
334
+ except (TypeError, ValueError):
335
+ period = _CHANNEL_IDLE_CHECK_INTERVAL_SECONDS
336
+ idle_elapsed = 0.0
337
+ # 第四批修复(收尾空转治理)可达性:孤儿检测与 idle 自退各用独立计时器。
338
+ # 曾共用一个 idle_elapsed——它在 period(默认 30s)处被清零,永远够不到
339
+ # 孤儿门槛 60s,导致 _orphaned_owner_reason 不可达、宿主死亡后仍空转满
340
+ # 1800s idle(红证据:驱动 40 跳检测调用 0 次)。双计时器让 docstring
341
+ # 承诺的"解耦为双周期"成为事实。
342
+ owner_watch_elapsed = 0.0
283
343
  while not stop.is_set():
284
- if stop.wait(period):
285
- return
286
- reason = _channel_idle_exit_reason(service, activity)
287
- if reason is not None:
288
- _channel_self_retire(
289
- service, activity, reason, lease=lease, exit_hook=exit_hook,
290
- )
344
+ wait_slice = max(
345
+ 0.05, min(_CHANNEL_OWNER_WATCH_INTERVAL_SECONDS, period),
346
+ )
347
+ if stop.wait(wait_slice):
291
348
  return
349
+ idle_elapsed += wait_slice
350
+ owner_watch_elapsed += wait_slice
351
+ if (
352
+ initial_parent_pid is not None
353
+ and owner_watch_elapsed >= _CHANNEL_ORPHAN_MIN_IDLE_SECONDS
354
+ ):
355
+ reason = _orphaned_owner_reason(activity, initial_parent_pid)
356
+ if reason is not None:
357
+ _channel_self_retire(
358
+ service, activity, reason, lease=lease, exit_hook=exit_hook,
359
+ )
360
+ return
361
+ if idle_elapsed >= period:
362
+ idle_elapsed = 0.0
363
+ reason = _channel_idle_exit_reason(service, activity)
364
+ if reason is not None:
365
+ _channel_self_retire(
366
+ service, activity, reason, lease=lease, exit_hook=exit_hook,
367
+ )
368
+ return
292
369
 
293
370
 
294
371
  def _read_lease_holder(lock_path: Path) -> int | None:
@@ -669,28 +746,6 @@ def _host_session_heartbeat_loop(service: "BugxMcpService", stop: threading.Even
669
746
  # (compact_json, format_result, serialize_value imported from mcp_handlers)
670
747
 
671
748
 
672
- def _error_payload(error: BaseException) -> dict[str, object]:
673
- return {
674
- "error_type": type(error).__name__,
675
- "message": str(error) or type(error).__name__,
676
- "error_code": "MCP_CALL_FAILED",
677
- "interactive_required": True,
678
- "next_action": "PROMPT_USER",
679
- "prompt": (
680
- "MCP 调用失败,请立即询问用户:1) 立即重试 2) 本轮切换手动/回退 "
681
- "3) 下次再说(停止本轮)"
682
- ),
683
- "choices": ["retry", "fallback", "later"],
684
- }
685
-
686
-
687
- def _call_failure_data(operation: object, error: BaseException) -> dict[str, object]:
688
- """为 tools/call 协议错误提供可被宿主直接呈现的交互门禁。"""
689
- payload = _error_payload(error)
690
- payload["operation"] = str(operation or "unknown")
691
- return payload
692
-
693
-
694
749
  # (next_action imported from mcp_handlers)
695
750
 
696
751
 
@@ -4,6 +4,7 @@
4
4
  from __future__ import annotations
5
5
 
6
6
  import hashlib
7
+ import sys
7
8
  from pathlib import Path
8
9
  from typing import Any, Mapping
9
10
 
@@ -170,8 +171,17 @@ def handle_extract_ego_subgraph(service: Any, arguments: Mapping[str, object]) -
170
171
  if root is not None:
171
172
  try:
172
173
  graph_data = build_graph(Path(root))
173
- except Exception:
174
+ except Exception as exc:
175
+ # F-RSI-20261115-160:build_graph 失败允许降级为单节点空图
176
+ # (拓扑提取不该 fail 整个调用),但必须 stderr 留痕——静默
177
+ # 吞错会让宿主拿到「合法但空」的子图而归因能力下降零可观测
178
+ # (静默吞错红线系列第 6 处清零)。
179
+ print(f"[mcp] ⚠ build_graph 失败,ego 子图降级为单节点 {root}: "
180
+ f"{type(exc).__name__}: {exc}",
181
+ file=sys.stderr)
174
182
  graph_data = {"nodes": [{"id": center_node}], "edges": []}
183
+ else:
184
+ pass
175
185
  else:
176
186
  graph_data = {"nodes": [{"id": center_node}], "edges": []}
177
187