bugx-cli 0.0.0-stage → 0.1.0

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 (751) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +280 -2
  3. package/core/CATALOG.json +141 -0
  4. package/core/README.md +254 -0
  5. package/core/adapters/README.md +35 -0
  6. package/core/adapters/android-interaction.json +81 -0
  7. package/core/adapters/android.json +24 -0
  8. package/core/adapters/desktop-macos.json +20 -0
  9. package/core/adapters/ios-interaction.json +34 -0
  10. package/core/adapters/ios.json +23 -0
  11. package/core/adapters/memory-macos.json +24 -0
  12. package/core/agent/README.md +50 -0
  13. package/core/agent/__init__.py +146 -0
  14. package/core/agent/agent_artifacts.py +764 -0
  15. package/core/agent/agent_eval.py +1073 -0
  16. package/core/agent/agent_execution.py +552 -0
  17. package/core/agent/agent_orchestrator.py +1345 -0
  18. package/core/agent/agent_targets.py +871 -0
  19. package/core/agent/agent_workspace.py +770 -0
  20. package/core/assets/README.md +24 -0
  21. package/core/assets/bugx-avatar-1024.png +0 -0
  22. package/core/assets/bugx-avatar-512.png +0 -0
  23. package/core/assets/bugx-avatar-tight.svg +23 -0
  24. package/core/assets/bugx-avatar.svg +28 -0
  25. package/core/assets/bugx-hero-cn.png +0 -0
  26. package/core/assets/bugx-hero-en.png +0 -0
  27. package/core/assets/project-layout.md +42 -0
  28. package/core/audit_packs/README.md +37 -0
  29. package/core/audit_packs/data-audit/manifest.json +94 -0
  30. package/core/audit_packs/data-audit/stages/00-scope.md +14 -0
  31. package/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
  32. package/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
  33. package/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
  34. package/core/audit_packs/desktop-audit/manifest.json +123 -0
  35. package/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
  36. package/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
  37. package/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
  38. package/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
  39. package/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
  40. package/core/audit_packs/memory-testing.md +227 -0
  41. package/core/audit_packs/mobile-audit/manifest.json +155 -0
  42. package/core/audit_packs/mobile-audit/modules/android.md +19 -0
  43. package/core/audit_packs/mobile-audit/modules/h5.md +18 -0
  44. package/core/audit_packs/mobile-audit/modules/ios.md +25 -0
  45. package/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
  46. package/core/audit_packs/mobile-audit/modules/webview.md +18 -0
  47. package/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
  48. package/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
  49. package/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
  50. package/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
  51. package/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
  52. package/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
  53. package/core/audit_packs/native-audit/manifest.json +127 -0
  54. package/core/audit_packs/native-audit/stages/00-scope.md +14 -0
  55. package/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
  56. package/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
  57. package/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
  58. package/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
  59. package/core/audit_packs/platform-testing.md +174 -0
  60. package/core/audit_packs/web-audit/manifest.json +191 -0
  61. package/core/audit_packs/web-audit/modules/graphql.md +5 -0
  62. package/core/audit_packs/web-audit/modules/h5.md +18 -0
  63. package/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
  64. package/core/audit_packs/web-audit/modules/oauth.md +4 -0
  65. package/core/audit_packs/web-audit/modules/upload.md +4 -0
  66. package/core/audit_packs/web-audit/modules/websocket.md +4 -0
  67. package/core/audit_packs/web-audit/stages/00-scope.md +13 -0
  68. package/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
  69. package/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
  70. package/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
  71. package/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
  72. package/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
  73. package/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
  74. package/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
  75. package/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
  76. package/core/autonomous_cve/INTERFACE.md +61 -0
  77. package/core/autonomous_cve/README.md +58 -0
  78. package/core/autonomous_cve/SPEC.md +25 -0
  79. package/core/autonomous_cve/__init__.py +109 -0
  80. package/core/autonomous_cve/attack_graph.py +1096 -0
  81. package/core/autonomous_cve/attack_graph_store.py +1822 -0
  82. package/core/autonomous_cve/audit_campaign.py +1232 -0
  83. package/core/autonomous_cve/behavior_graph.py +459 -0
  84. package/core/autonomous_cve/ghsa_advisories.py +174 -0
  85. package/core/autonomous_cve/models.py +93 -0
  86. package/core/autonomous_cve/mutator.py +87 -0
  87. package/core/autonomous_cve/patcher.py +126 -0
  88. package/core/autonomous_cve/scout.py +278 -0
  89. package/core/autonomous_cve/synthesizer.py +207 -0
  90. package/core/autonomous_cve/verifier.py +100 -0
  91. package/core/bugx.md +1299 -0
  92. package/core/bugx_paths.py +1846 -0
  93. package/core/cloud_sync/INTERFACE.md +32 -0
  94. package/core/cloud_sync/README.md +62 -0
  95. package/core/cloud_sync/SPEC.md +25 -0
  96. package/core/cloud_sync/__init__.py +23 -0
  97. package/core/cloud_sync/auto_sync.py +398 -0
  98. package/core/cloud_sync/cloud_client.py +1199 -0
  99. package/core/cloud_sync/cloud_onboard.py +702 -0
  100. package/core/cloud_sync/cloud_schema.py +648 -0
  101. package/core/cloud_sync/consent.py +81 -0
  102. package/core/cloud_sync/device_identity.py +307 -0
  103. package/core/cloud_sync/endpoint_router.py +415 -0
  104. package/core/cloud_sync/flywheel_client.py +760 -0
  105. package/core/cloud_sync/network_transport.py +275 -0
  106. package/core/cloud_sync/onboard_wizard.py +493 -0
  107. package/core/cloud_sync/sensitive_filter.py +285 -0
  108. package/core/cloud_sync/sync_pull.py +695 -0
  109. package/core/cloud_sync/sync_push.py +721 -0
  110. package/core/contracts/AGENT_GUIDE.md +362 -0
  111. package/core/contracts/README.md +34 -0
  112. package/core/contracts/bugx-blackbox.md +541 -0
  113. package/core/contracts/bugx-opencode.md +469 -0
  114. package/core/contracts/bugx-quick.md +44 -0
  115. package/core/contracts/bugx-runtime-contract.md +353 -0
  116. package/core/contracts/bugx-worker.md +470 -0
  117. package/core/contracts/engine_gap_contracts.py +390 -0
  118. package/core/coverage/README.md +70 -0
  119. package/core/coverage/__init__.py +106 -0
  120. package/core/coverage/coverage_ai_review.py +185 -0
  121. package/core/coverage/coverage_backfill.py +54 -0
  122. package/core/coverage/coverage_bootstrap.py +713 -0
  123. package/core/coverage/coverage_business.py +36 -0
  124. package/core/coverage/coverage_cli.py +715 -0
  125. package/core/coverage/coverage_discovery.py +859 -0
  126. package/core/coverage/coverage_evidence.py +977 -0
  127. package/core/coverage/coverage_forensics.py +115 -0
  128. package/core/coverage/coverage_gate.py +277 -0
  129. package/core/coverage/coverage_intelligence.py +734 -0
  130. package/core/coverage/coverage_manifest.py +396 -0
  131. package/core/coverage/coverage_platform.py +77 -0
  132. package/core/coverage/coverage_validate.py +236 -0
  133. package/core/coverage/module_coverage.py +157 -0
  134. package/core/dev_harness/INTERFACE.md +20 -0
  135. package/core/dev_harness/README.md +21 -0
  136. package/core/dev_harness/SPEC.md +25 -0
  137. package/core/dev_harness/__init__.py +5 -0
  138. package/core/dev_harness/interaction_preset.py +408 -0
  139. package/core/engine-integrity.json +2625 -0
  140. package/core/fuzzing/README.md +49 -0
  141. package/core/fuzzing/__init__.py +82 -0
  142. package/core/fuzzing/concurrency_fuzzer.py +382 -0
  143. package/core/fuzzing/differential_oracle.py +629 -0
  144. package/core/fuzzing/fuzz_input.py +1188 -0
  145. package/core/fuzzing/stateful_fuzzer.py +332 -0
  146. package/core/governance/README.md +61 -0
  147. package/core/governance/__init__.py +130 -0
  148. package/core/governance/capacity_planner.py +124 -0
  149. package/core/governance/dependency_lock.py +317 -0
  150. package/core/governance/goal_governor.py +754 -0
  151. package/core/governance/guide_budget.py +458 -0
  152. package/core/governance/lockdown.sh +50 -0
  153. package/core/governance/readonly_enforcer.py +154 -0
  154. package/core/governance/runtime_tool_gate.py +373 -0
  155. package/core/governance/secret_redactor.py +772 -0
  156. package/core/governance/token_budget.py +38 -0
  157. package/core/host_acp/INTERFACE.md +36 -0
  158. package/core/host_acp/README.md +51 -0
  159. package/core/host_acp/SPEC.md +25 -0
  160. package/core/host_acp/__init__.py +121 -0
  161. package/core/host_acp/base.py +111 -0
  162. package/core/host_acp/claude.py +41 -0
  163. package/core/host_acp/cline.py +235 -0
  164. package/core/host_acp/codex.py +245 -0
  165. package/core/host_acp/dsh.py +48 -0
  166. package/core/host_acp/opencode.py +154 -0
  167. package/core/host_acp/pi.py +36 -0
  168. package/core/host_acp/zcode.py +41 -0
  169. package/core/host_runtime/INTERFACE.md +24 -0
  170. package/core/host_runtime/README.md +62 -0
  171. package/core/host_runtime/SPEC.md +25 -0
  172. package/core/host_runtime/__init__.py +21 -0
  173. package/core/host_runtime/adapters.py +412 -0
  174. package/core/host_runtime/autonomous_runner.py +1152 -0
  175. package/core/host_runtime/cline.py +435 -0
  176. package/core/host_runtime/common.py +103 -0
  177. package/core/host_runtime/free_models.py +786 -0
  178. package/core/host_runtime/host_bootstrap.py +389 -0
  179. package/core/host_runtime/host_evaluators.py +721 -0
  180. package/core/host_runtime/host_probe.py +41 -0
  181. package/core/host_runtime/host_provider_arbitrator.py +777 -0
  182. package/core/host_runtime/host_registry.py +655 -0
  183. package/core/host_runtime/host_usage.py +127 -0
  184. package/core/host_runtime/mcp_process_tracker.py +509 -0
  185. package/core/host_runtime/mcp_registry_gate.py +368 -0
  186. package/core/hosts/INTERFACE.md +51 -0
  187. package/core/hosts/README.md +67 -0
  188. package/core/hosts/SPEC.md +25 -0
  189. package/core/hosts/__init__.py +136 -0
  190. package/core/hosts/_base_usage.py +152 -0
  191. package/core/hosts/_codex_usage.py +297 -0
  192. package/core/hosts/_dsh_usage.py +184 -0
  193. package/core/hosts/_mcp_toml.py +365 -0
  194. package/core/hosts/_zcode_usage.py +269 -0
  195. package/core/hosts/base.py +451 -0
  196. package/core/hosts/claude.py +157 -0
  197. package/core/hosts/cline.py +225 -0
  198. package/core/hosts/codex.py +948 -0
  199. package/core/hosts/dsh.py +518 -0
  200. package/core/hosts/opencode.py +358 -0
  201. package/core/hosts/pi.py +151 -0
  202. package/core/hosts/zcode.py +219 -0
  203. package/core/i18n.py +252 -0
  204. package/core/infra/README.md +39 -0
  205. package/core/infra/__init__.py +15 -0
  206. package/core/infra/build_info.py +86 -0
  207. package/core/infra/client_metadata.py +185 -0
  208. package/core/infra/python_runtime.py +540 -0
  209. package/core/infra/safe_xml.py +221 -0
  210. package/core/launch_bugx.py +118 -0
  211. package/core/launch_phases/INTERFACE.md +31 -0
  212. package/core/launch_phases/README.md +106 -0
  213. package/core/launch_phases/SPEC.md +25 -0
  214. package/core/launch_phases/__init__.py +29 -0
  215. package/core/launch_phases/candidate_revalidation.py +484 -0
  216. package/core/launch_phases/common.py +1041 -0
  217. package/core/launch_phases/finding_confirm_phase.py +387 -0
  218. package/core/launch_phases/finding_settlement.py +1245 -0
  219. package/core/launch_phases/findings_adjudication.py +666 -0
  220. package/core/launch_phases/findings_snapshot.py +357 -0
  221. package/core/launch_phases/judge_phase.py +791 -0
  222. package/core/launch_phases/lesson_context.py +536 -0
  223. package/core/launch_phases/lifecycle_reporter.py +627 -0
  224. package/core/launch_phases/orchestrator_controls.py +682 -0
  225. package/core/launch_phases/post_commit.py +567 -0
  226. package/core/launch_phases/post_coverage_sync.py +591 -0
  227. package/core/launch_phases/post_dry_run.py +817 -0
  228. package/core/launch_phases/post_observability.py +367 -0
  229. package/core/launch_phases/post_phase.py +1087 -0
  230. package/core/launch_phases/post_receipt.py +362 -0
  231. package/core/launch_phases/post_round_lifecycle.py +786 -0
  232. package/core/launch_phases/pre_phase.py +1029 -0
  233. package/core/launch_phases/pre_recon_scout.py +862 -0
  234. package/core/launch_phases/pre_state_builder.py +1286 -0
  235. package/core/launch_phases/report_sharing.py +414 -0
  236. package/core/launch_phases/round_orchestrator.py +1133 -0
  237. package/core/launch_phases/session_runtime.py +1623 -0
  238. package/core/launch_phases/startup_gates.py +1022 -0
  239. package/core/launch_phases/startup_interaction.py +947 -0
  240. package/core/launch_phases/startup_version_gate.py +873 -0
  241. package/core/launch_phases/supervisor_bridge.py +1224 -0
  242. package/core/launch_phases/supervisor_coverage.py +417 -0
  243. package/core/launch_phases/supervisor_degraded.py +1219 -0
  244. package/core/launch_phases/worker_barriers.py +414 -0
  245. package/core/launch_phases/worker_orchestrator.py +1166 -0
  246. package/core/launch_phases/worker_prior.py +749 -0
  247. package/core/ledger/INTERFACE.md +35 -0
  248. package/core/ledger/README.md +160 -0
  249. package/core/ledger/SPEC.md +25 -0
  250. package/core/ledger/__init__.py +67 -0
  251. package/core/ledger/_facade.py +226 -0
  252. package/core/ledger/archive_ops.py +572 -0
  253. package/core/ledger/auto_materialization.py +459 -0
  254. package/core/ledger/bug-log.md +22 -0
  255. package/core/ledger/cli.py +270 -0
  256. package/core/ledger/export_ops.py +549 -0
  257. package/core/ledger/finding_confirmation.py +1274 -0
  258. package/core/ledger/finding_io.py +299 -0
  259. package/core/ledger/finding_lifecycle.py +307 -0
  260. package/core/ledger/finding_verification.py +369 -0
  261. package/core/ledger/incidents.py +999 -0
  262. package/core/ledger/lesson-replay-cases.json +20 -0
  263. package/core/ledger/lesson_ledger.py +241 -0
  264. package/core/ledger/lesson_replay.py +272 -0
  265. package/core/ledger/life_ledger.py +668 -0
  266. package/core/ledger/mistake-book.md +130 -0
  267. package/core/ledger/patterns.py +681 -0
  268. package/core/ledger/receipt_contract.py +253 -0
  269. package/core/ledger/schema.py +1192 -0
  270. package/core/ledger/sync_ops.py +935 -0
  271. package/core/ledger/tool_experience.py +682 -0
  272. package/core/ledger/verify_life.py +1526 -0
  273. package/core/lesson-ledger.json +275 -0
  274. package/core/locales/README.md +19 -0
  275. package/core/locales/en-US.json +462 -0
  276. package/core/locales/zh-CN.json +462 -0
  277. package/core/mcp_handlers/INTERFACE.md +75 -0
  278. package/core/mcp_handlers/README.md +62 -0
  279. package/core/mcp_handlers/SPEC.md +25 -0
  280. package/core/mcp_handlers/__init__.py +128 -0
  281. package/core/mcp_handlers/base.py +697 -0
  282. package/core/mcp_handlers/channel_lifecycle.py +696 -0
  283. package/core/mcp_handlers/graph_handlers.py +222 -0
  284. package/core/mcp_handlers/knowledge_handlers.py +536 -0
  285. package/core/mcp_handlers/mining_handlers.py +586 -0
  286. package/core/mcp_handlers/resource_prompt_table.py +116 -0
  287. package/core/mcp_handlers/retrieval_handlers.py +239 -0
  288. package/core/mcp_handlers/rpc_server.py +465 -0
  289. package/core/mcp_handlers/supervisor_handlers.py +1435 -0
  290. package/core/mcp_handlers/telemetry_handlers.py +227 -0
  291. package/core/mcp_handlers/tool_table.py +1015 -0
  292. package/core/mcp_runtime_support/README.md +21 -0
  293. package/core/mcp_runtime_support/__init__.py +1 -0
  294. package/core/mcp_runtime_support/common.py +363 -0
  295. package/core/mcp_runtime_support/environment.py +605 -0
  296. package/core/mcp_runtime_support/verifier.py +810 -0
  297. package/core/metadata.txt +5 -0
  298. package/core/planning/README.md +157 -0
  299. package/core/planning/__init__.py +242 -0
  300. package/core/planning/capability_plan.py +187 -0
  301. package/core/planning/capability_planner.py +195 -0
  302. package/core/planning/domain_archetype.py +542 -0
  303. package/core/planning/domain_router.py +267 -0
  304. package/core/planning/dynamic_flow_analyzer.py +328 -0
  305. package/core/planning/impact_pruner.py +435 -0
  306. package/core/planning/intent_adjudicator.py +175 -0
  307. package/core/planning/judge_pipeline.py +1163 -0
  308. package/core/planning/logic_analysis.py +419 -0
  309. package/core/planning/prompt_harness.py +1702 -0
  310. package/core/planning/source_inspector.py +267 -0
  311. package/core/planning/spec_harvester.py +449 -0
  312. package/core/planning/target_sandbox_manager.py +573 -0
  313. package/core/planning/test_capability_verifier.py +1364 -0
  314. package/core/planning/tools-kb.md +38 -0
  315. package/core/planning/unit_kind.py +122 -0
  316. package/core/probes/INTERFACE.md +73 -0
  317. package/core/probes/README.md +51 -0
  318. package/core/probes/SPEC.md +26 -0
  319. package/core/probes/__init__.py +70 -0
  320. package/core/probes/android_probe.py +384 -0
  321. package/core/probes/base.py +147 -0
  322. package/core/probes/codebase_memory_probe.py +590 -0
  323. package/core/probes/desktop_probe.py +238 -0
  324. package/core/probes/differential_probe.py +356 -0
  325. package/core/probes/efficiency_probe.py +168 -0
  326. package/core/probes/ios_binary_probe.py +368 -0
  327. package/core/probes/memory_probe.py +326 -0
  328. package/core/probes/miniprogram_probe.py +323 -0
  329. package/core/probes/mobile_probe.py +281 -0
  330. package/core/probes/native_probe.py +214 -0
  331. package/core/probes/openwiki_probe.py +193 -0
  332. package/core/probes/pattern_probe.py +347 -0
  333. package/core/probes/platform_probe.py +343 -0
  334. package/core/probes/probe_registry.py +1669 -0
  335. package/core/probes/sast_probe.py +1009 -0
  336. package/core/probes/sast_rules.py +841 -0
  337. package/core/probes/sca_scanner.py +731 -0
  338. package/core/probes/web_probe.py +359 -0
  339. package/core/project_profiler/INTERFACE.md +62 -0
  340. package/core/project_profiler/README.md +53 -0
  341. package/core/project_profiler/SPEC.md +28 -0
  342. package/core/project_profiler/__init__.py +201 -0
  343. package/core/project_profiler/arbitrator.py +311 -0
  344. package/core/project_profiler/constants.py +247 -0
  345. package/core/project_profiler/detector.py +392 -0
  346. package/core/project_profiler/extractors.py +836 -0
  347. package/core/project_profiler/fingerprint.py +116 -0
  348. package/core/project_profiler/storage.py +258 -0
  349. package/core/project_profiler/strategy.py +265 -0
  350. package/core/prompts/README.md +35 -0
  351. package/core/prompts/codex_dialog_dispatch.md +9 -0
  352. package/core/prompts/command_routing_en.md +42 -0
  353. package/core/prompts/command_routing_zh.md +42 -0
  354. package/core/prompts/l0_router.md +47 -0
  355. package/core/prompts/rules/anti_patterns.md +16 -0
  356. package/core/prompts/rules/concurrency_rules.md +14 -0
  357. package/core/prompts/rules/memory_leak_rules.md +13 -0
  358. package/core/prompts/rules/prompt_injection_defense.md +13 -0
  359. package/core/prompts/stages/stage_explore.md +31 -0
  360. package/core/prompts/stages/stage_gate.md +43 -0
  361. package/core/prompts/stages/stage_mutate.md +42 -0
  362. package/core/prompts/stages/stage_repair.md +85 -0
  363. package/core/repair/README.md +74 -0
  364. package/core/repair/__init__.py +169 -0
  365. package/core/repair/fix_watchlist.py +391 -0
  366. package/core/repair/l7_dynamic.py +418 -0
  367. package/core/repair/l7_repair_loop.py +465 -0
  368. package/core/repair/l7_selfcheck.py +862 -0
  369. package/core/repair/minimize_repro.py +466 -0
  370. package/core/repair/patch_synthesizer.py +617 -0
  371. package/core/repair/regression_pack.py +379 -0
  372. package/core/repair/rsi_fixer.py +910 -0
  373. package/core/repair/rsi_loop.py +313 -0
  374. package/core/repair/rsi_repair.py +348 -0
  375. package/core/repair/rsi_rounds.py +212 -0
  376. package/core/repair/rsi_scope.py +262 -0
  377. package/core/repair/self_heal.py +604 -0
  378. package/core/repair/test_generator.py +1108 -0
  379. package/core/repair/test_quality_auditor.py +410 -0
  380. package/core/repair/test_strategy.py +511 -0
  381. package/core/report_engine/INTERFACE.md +59 -0
  382. package/core/report_engine/README.md +69 -0
  383. package/core/report_engine/SPEC.md +28 -0
  384. package/core/report_engine/__init__.py +47 -0
  385. package/core/report_engine/attestation.py +224 -0
  386. package/core/report_engine/authority.py +255 -0
  387. package/core/report_engine/finding_report.py +417 -0
  388. package/core/report_engine/formal_report_builder.py +924 -0
  389. package/core/report_engine/html_renderers.py +696 -0
  390. package/core/report_engine/models.py +761 -0
  391. package/core/report_engine/pdf_exporter.py +231 -0
  392. package/core/report_engine/projects_assets.py +730 -0
  393. package/core/report_engine/report_client.py +743 -0
  394. package/core/report_engine/report_data_builder.py +388 -0
  395. package/core/report_engine/report_share.py +459 -0
  396. package/core/report_engine/sast_bridge.py +116 -0
  397. package/core/report_engine/server.py +822 -0
  398. package/core/report_engine/visual_report_builder.py +796 -0
  399. package/core/report_engine/web-conformance.md +63 -0
  400. package/core/report_engine/web_conformance.py +459 -0
  401. package/core/report_engine/workbench_assets.py +484 -0
  402. package/core/retrieval/INTERFACE.md +20 -0
  403. package/core/retrieval/README.md +161 -0
  404. package/core/retrieval/SPEC.md +25 -0
  405. package/core/retrieval/__init__.py +3 -0
  406. package/core/retrieval/code_analyzer.py +1684 -0
  407. package/core/retrieval/codebase_memory_bridge.py +337 -0
  408. package/core/retrieval/context_assembler.py +234 -0
  409. package/core/retrieval/corpus_fetch.py +369 -0
  410. package/core/retrieval/graph_ego.py +597 -0
  411. package/core/retrieval/knowledge_auto.py +662 -0
  412. package/core/retrieval/knowledge_sources.py +168 -0
  413. package/core/retrieval/knowledge_sync.py +909 -0
  414. package/core/retrieval/memory_store.py +480 -0
  415. package/core/retrieval/query_planner.py +1020 -0
  416. package/core/retrieval/rrf_engine.py +137 -0
  417. package/core/retrieval/slice_extractor.py +1209 -0
  418. package/core/retrieval/slice_normalizer.py +373 -0
  419. package/core/retrieval/slice_spec.py +357 -0
  420. package/core/retrieval/symbol_index.py +1132 -0
  421. package/core/retrieval/universal_code_matcher.py +437 -0
  422. package/core/retrieval/xerj_bridge.py +476 -0
  423. package/core/retrieval/xerj_supervisor.py +362 -0
  424. package/core/rules/README.md +33 -0
  425. package/core/rules/ios/PROVENANCE.json +30 -0
  426. package/core/rules/ios/crypto.yaml +36 -0
  427. package/core/rules/ios/network.yaml +20 -0
  428. package/core/rules/ios/resilience.yaml +47 -0
  429. package/core/rules/ios/storage.yaml +48 -0
  430. package/core/rules/mastg/LICENSE +173 -0
  431. package/core/rules/mastg/PROVENANCE.json +270 -0
  432. package/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
  433. package/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
  434. package/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
  435. package/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
  436. package/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
  437. package/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
  438. package/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
  439. package/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
  440. package/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
  441. package/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
  442. package/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
  443. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
  444. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
  445. package/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
  446. package/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
  447. package/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
  448. package/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
  449. package/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
  450. package/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
  451. package/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
  452. package/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
  453. package/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
  454. package/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
  455. package/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
  456. package/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
  457. package/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
  458. package/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
  459. package/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
  460. package/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
  461. package/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
  462. package/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
  463. package/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
  464. package/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
  465. package/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
  466. package/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
  467. package/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
  468. package/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
  469. package/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
  470. package/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
  471. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
  472. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
  473. package/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
  474. package/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
  475. package/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
  476. package/core/rules/mastg/mastg-android-strictmode.yml +10 -0
  477. package/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
  478. package/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
  479. package/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
  480. package/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
  481. package/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
  482. package/core/rules/miniprogram/PROVENANCE.json +26 -0
  483. package/core/rules/miniprogram/network.yaml +37 -0
  484. package/core/rules/miniprogram/platform.yaml +36 -0
  485. package/core/rules/miniprogram/storage.yaml +48 -0
  486. package/core/rules/mobsfscan-swift/LICENSE +165 -0
  487. package/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
  488. package/core/rules/mobsfscan-swift/auth.yaml +59 -0
  489. package/core/rules/mobsfscan-swift/crypto.yaml +66 -0
  490. package/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
  491. package/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
  492. package/core/rules/mobsfscan-swift/logging.yaml +23 -0
  493. package/core/rules/mobsfscan-swift/network.yaml +55 -0
  494. package/core/rules/mobsfscan-swift/resilience.yaml +29 -0
  495. package/core/rules/mobsfscan-swift/secrets.yaml +33 -0
  496. package/core/rules/mobsfscan-swift/storage.yaml +29 -0
  497. package/core/rules/mobsfscan-swift/webview.yaml +32 -0
  498. package/core/runtime/README.md +198 -0
  499. package/core/runtime/__init__.py +3 -0
  500. package/core/runtime/bugx_logging.py +1393 -0
  501. package/core/runtime/daemon_runner.py +623 -0
  502. package/core/runtime/fixture_solidify.py +449 -0
  503. package/core/runtime/global_telemetry.py +549 -0
  504. package/core/runtime/incident_eval.py +148 -0
  505. package/core/runtime/interaction.py +605 -0
  506. package/core/runtime/interaction_store.py +435 -0
  507. package/core/runtime/interactive_menu.py +95 -0
  508. package/core/runtime/log_analytics.py +922 -0
  509. package/core/runtime/mining_quality_framework.py +1387 -0
  510. package/core/runtime/model_runner.py +769 -0
  511. package/core/runtime/platform_adapter.py +579 -0
  512. package/core/runtime/prep_validate.py +476 -0
  513. package/core/runtime/project_graph.py +827 -0
  514. package/core/runtime/project_init.py +481 -0
  515. package/core/runtime/project_profile.py +224 -0
  516. package/core/runtime/project_settings.py +963 -0
  517. package/core/runtime/provider_window.py +97 -0
  518. package/core/runtime/resume_ticket.py +115 -0
  519. package/core/runtime/scenario_eval.py +814 -0
  520. package/core/runtime/seed_drill.py +549 -0
  521. package/core/runtime/self_audit.py +550 -0
  522. package/core/runtime/session_profile.py +205 -0
  523. package/core/runtime/setup_ui_env.py +229 -0
  524. package/core/runtime/startup_environment.py +859 -0
  525. package/core/runtime/sync_store.py +1421 -0
  526. package/core/runtime/tool_install_targets.py +18 -0
  527. package/core/schemas/README.md +35 -0
  528. package/core/schemas/agent-graph.schema.json +368 -0
  529. package/core/schemas/attack-graph.schema.json +88 -0
  530. package/core/schemas/evidence-bundle.schema.json +33 -0
  531. package/core/schemas/skill-pack.schema.json +230 -0
  532. package/core/schemas/worker-checkpoint.schema.json +119 -0
  533. package/core/secure_atomic.py +289 -0
  534. package/core/seed_corpus/README.md +55 -0
  535. package/core/seed_corpus/c.txt +29 -0
  536. package/core/seed_corpus/cpp.txt +32 -0
  537. package/core/seed_corpus/css.txt +70 -0
  538. package/core/seed_corpus/go.txt +46 -0
  539. package/core/seed_corpus/java.txt +30 -0
  540. package/core/seed_corpus/javascript.txt +55 -0
  541. package/core/seed_corpus/kotlin.txt +28 -0
  542. package/core/seed_corpus/python.txt +71 -0
  543. package/core/seed_corpus/rust.txt +53 -0
  544. package/core/seed_corpus/swift.txt +29 -0
  545. package/core/seed_corpus/typescript.txt +29 -0
  546. package/core/skills/README.md +53 -0
  547. package/core/skills/__init__.py +189 -0
  548. package/core/skills/bugx_docs_mcp_server.py +416 -0
  549. package/core/skills/bugx_mcp_server.py +1134 -0
  550. package/core/skills/mcp_runtime.py +968 -0
  551. package/core/skills/mcp_session_proof.py +605 -0
  552. package/core/skills/mobile_ui_inspector.py +405 -0
  553. package/core/skills/skill_pack.py +1214 -0
  554. package/core/skills/skill_synthesizer.py +1153 -0
  555. package/core/skills/tools_kb.py +313 -0
  556. package/core/supervisor/INTERFACE.md +121 -0
  557. package/core/supervisor/README.md +209 -0
  558. package/core/supervisor/SPEC.md +25 -0
  559. package/core/supervisor/__init__.py +175 -0
  560. package/core/supervisor/audit_supervisor.py +1015 -0
  561. package/core/supervisor/budget_governor.py +760 -0
  562. package/core/supervisor/checkpoint_handler.py +368 -0
  563. package/core/supervisor/checkpoint_pipeline.py +1322 -0
  564. package/core/supervisor/checkpoint_sync.py +640 -0
  565. package/core/supervisor/claim_events.py +74 -0
  566. package/core/supervisor/claim_sync.py +590 -0
  567. package/core/supervisor/cli.py +812 -0
  568. package/core/supervisor/context_sync.py +55 -0
  569. package/core/supervisor/coverage_sync.py +115 -0
  570. package/core/supervisor/finding_commit.py +470 -0
  571. package/core/supervisor/finding_sync.py +688 -0
  572. package/core/supervisor/finding_workflow.py +659 -0
  573. package/core/supervisor/finish_policy.py +224 -0
  574. package/core/supervisor/finish_sync.py +185 -0
  575. package/core/supervisor/graph_sync.py +669 -0
  576. package/core/supervisor/lease_manager.py +788 -0
  577. package/core/supervisor/lifecycle_blocks.py +124 -0
  578. package/core/supervisor/next_round_sync.py +126 -0
  579. package/core/supervisor/observability.py +140 -0
  580. package/core/supervisor/recovery_sync.py +165 -0
  581. package/core/supervisor/rejection_remedies.py +308 -0
  582. package/core/supervisor/round_governor.py +306 -0
  583. package/core/supervisor/serial_authorization.py +500 -0
  584. package/core/supervisor/start_sync.py +87 -0
  585. package/core/supervisor/state_store.py +249 -0
  586. package/core/supervisor/supervisor_host.py +511 -0
  587. package/core/supervisor/supervisor_models.py +1143 -0
  588. package/core/supervisor/systemic_failure.py +104 -0
  589. package/core/supervisor/task_scheduler.py +1640 -0
  590. package/core/supervisor/worker_checkpoint.py +223 -0
  591. package/core/supervisor/worker_execution.py +265 -0
  592. package/core/supervisor/worker_handoff.py +192 -0
  593. package/core/supervisor/worker_lifecycle.py +396 -0
  594. package/core/supervisor/worker_runtime.py +999 -0
  595. package/core/supervisor/worker_sync.py +89 -0
  596. package/core/supervisor_types/README.md +36 -0
  597. package/core/supervisor_types/__init__.py +0 -0
  598. package/core/supervisor_types/exceptions.py +52 -0
  599. package/core/supervisor_types/graph_models.py +357 -0
  600. package/core/supervisor_types/path_containment.py +151 -0
  601. package/core/supervisor_types/target_fingerprint.py +310 -0
  602. package/core/supervisor_types/worker_claim.py +402 -0
  603. package/core/webui/INTERFACE.md +50 -0
  604. package/core/webui/README.md +57 -0
  605. package/core/webui/SPEC.md +25 -0
  606. package/core/webui/__init__.py +11 -0
  607. package/core/webui/adapters/__init__.py +27 -0
  608. package/core/webui/adapters/base.py +87 -0
  609. package/core/webui/adapters/bugx.py +102 -0
  610. package/core/webui/adapters/claude.py +218 -0
  611. package/core/webui/adapters/cline.py +399 -0
  612. package/core/webui/adapters/codex.py +256 -0
  613. package/core/webui/adapters/dsh.py +173 -0
  614. package/core/webui/adapters/opencode.py +218 -0
  615. package/core/webui/adapters/pi.py +272 -0
  616. package/core/webui/adapters/registry.py +100 -0
  617. package/core/webui/adapters/zcode.py +312 -0
  618. package/core/webui/api_routes_post.py +668 -0
  619. package/core/webui/dispatcher.py +1376 -0
  620. package/core/webui/docs_session_service.py +473 -0
  621. package/core/webui/handler.py +674 -0
  622. package/core/webui/ide_cloud_service.py +526 -0
  623. package/core/webui/mcp_inspector.py +1743 -0
  624. package/core/webui/static/assets/index-CXAsl8mr.js +333 -0
  625. package/core/webui/static/assets/index-DHQUtWtx.css +1 -0
  626. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
  627. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
  628. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
  629. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
  630. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
  631. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
  632. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
  633. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
  634. package/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
  635. package/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
  636. package/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
  637. package/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
  638. package/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
  639. package/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
  640. package/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
  641. package/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
  642. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
  643. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
  644. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
  645. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
  646. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
  647. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
  648. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
  649. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
  650. package/core/webui/static/favicon.png +0 -0
  651. package/core/webui/static/icon-192.png +0 -0
  652. package/core/webui/static/index.html +42 -0
  653. package/core/webui/static/manifest.webmanifest +19 -0
  654. package/core/webui/static/project-settings.css +6458 -0
  655. package/core/webui/static/project-settings.js +9602 -0
  656. package/core/webui/static/sw.js +8 -0
  657. package/core/webui/workspace_service.py +218 -0
  658. package/docs/07_distribution/01_README_NPM.md +281 -0
  659. package/docs/07_distribution/README.md +16 -0
  660. package/docs/README.md +121 -0
  661. package/ecosystem/README.md +129 -0
  662. package/ecosystem/integrations/README.md +38 -0
  663. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +69 -0
  664. package/ecosystem/integrations/dsh/agents/bugx.md +27 -0
  665. package/ecosystem/integrations/dsh/dsh-patch.yml +18 -0
  666. package/ecosystem/integrations/dsh/mcp/cordis.patch.yml +4 -0
  667. package/ecosystem/integrations/dsh/mcp/index.js +219 -0
  668. package/ecosystem/integrations/dsh/mcp/package.json +28 -0
  669. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +70 -0
  670. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +229 -0
  671. package/ecosystem/integrations/dsh/ui/client.js +87 -0
  672. package/ecosystem/integrations/dsh/ui/cordis.patch.yml +4 -0
  673. package/ecosystem/integrations/dsh/ui/index.js +7 -0
  674. package/ecosystem/integrations/dsh/ui/package.json +27 -0
  675. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +53 -0
  676. package/ecosystem/integrations/opencode/mcp-lock.json +3067 -0
  677. package/ecosystem/integrations/opencode/opencode.json +118 -0
  678. package/ecosystem/integrations/pi/extensions/bugx/README.md +12 -0
  679. package/ecosystem/integrations/pi/extensions/bugx/index.ts +299 -0
  680. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +11 -0
  681. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +69 -0
  682. package/ecosystem/integrations/qoder/CONNECTORS.md +54 -0
  683. package/ecosystem/integrations/qoder/connector-meta.json +21 -0
  684. package/ecosystem/integrations/workbuddy/connector-meta.json +19 -0
  685. package/ecosystem/integrations/workbuddy/icon.png +0 -0
  686. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +70 -0
  687. package/ecosystem/plugins/README.md +37 -0
  688. package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +17 -0
  689. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +16 -0
  690. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +41 -0
  691. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +19 -0
  692. package/ecosystem/plugins/bugx/agents/bugx-judge.md +71 -0
  693. package/ecosystem/plugins/bugx/agents/bugx-worker.md +31 -0
  694. package/ecosystem/plugins/bugx/agents/bugx.md +74 -0
  695. package/ecosystem/plugins/bugx/assets/bugx-avatar-512.png +0 -0
  696. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +118 -0
  697. package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
  698. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +229 -0
  699. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
  700. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
  701. package/interfaces/README.md +143 -0
  702. package/interfaces/bin/README.md +35 -0
  703. package/interfaces/bin/bugx.js +80 -0
  704. package/interfaces/cli/README.md +90 -0
  705. package/interfaces/cli/bugx_cli/__init__.py +4 -0
  706. package/interfaces/cli/bugx_cli/cli.py +1678 -0
  707. package/interfaces/cli/bugx_cli/commands/__init__.py +1 -0
  708. package/interfaces/cli/bugx_cli/commands/advisory.py +94 -0
  709. package/interfaces/cli/bugx_cli/commands/agent.py +3944 -0
  710. package/interfaces/cli/bugx_cli/commands/audit.py +632 -0
  711. package/interfaces/cli/bugx_cli/commands/autonomous.py +260 -0
  712. package/interfaces/cli/bugx_cli/commands/cloud.py +1370 -0
  713. package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
  714. package/interfaces/cli/bugx_cli/commands/doctor.py +1345 -0
  715. package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
  716. package/interfaces/cli/bugx_cli/commands/interaction.py +244 -0
  717. package/interfaces/cli/bugx_cli/commands/knowledge.py +617 -0
  718. package/interfaces/cli/bugx_cli/commands/lifecycle.py +2763 -0
  719. package/interfaces/cli/bugx_cli/commands/patch.py +1014 -0
  720. package/interfaces/cli/bugx_cli/commands/plugin.py +2714 -0
  721. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +1446 -0
  722. package/interfaces/cli/bugx_cli/commands/plugin_cline.py +269 -0
  723. package/interfaces/cli/bugx_cli/commands/plugin_codex.py +74 -0
  724. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +728 -0
  725. package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +216 -0
  726. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +710 -0
  727. package/interfaces/cli/bugx_cli/commands/project.py +670 -0
  728. package/interfaces/cli/bugx_cli/commands/report.py +260 -0
  729. package/interfaces/cli/bugx_cli/commands/skill.py +251 -0
  730. package/interfaces/cli/bugx_cli/commands/stats.py +133 -0
  731. package/interfaces/cli/bugx_cli/commands/system.py +2567 -0
  732. package/interfaces/cli/bugx_cli/common.py +898 -0
  733. package/interfaces/cli/bugx_cli/host_adapters.py +1917 -0
  734. package/interfaces/cli/bugx_cli/hosts/__init__.py +80 -0
  735. package/interfaces/cli/bugx_cli/hosts/base.py +99 -0
  736. package/interfaces/cli/bugx_cli/hosts/registry.py +571 -0
  737. package/interfaces/cli/bugx_cli/hosts/template_engine.py +188 -0
  738. package/interfaces/cli/bugx_cli/infra/__init__.py +209 -0
  739. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +721 -0
  740. package/interfaces/cli/bugx_cli/infra/engine_installer.py +1937 -0
  741. package/interfaces/cli/bugx_cli/infra/host_sync.py +545 -0
  742. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +755 -0
  743. package/interfaces/cli/bugx_cli/infra/security.py +332 -0
  744. package/package.json +98 -4
  745. package/pyproject.toml +246 -0
  746. package/scripts/README.md +118 -0
  747. package/scripts/ensure-python.mjs +97 -0
  748. package/scripts/isolate-npm-readme.mjs +40 -0
  749. package/scripts/runtime.lock.json +31 -0
  750. package/scripts/sync-version.mjs +37 -0
  751. package/scripts/test-npm-wrapper.mjs +265 -0
@@ -0,0 +1,1623 @@
1
+ #!/usr/bin/env python3
2
+ """launch_phases/session_runtime.py - 状态机维护、runtime.json 加锁管理、时间分段与事件记录。"""
3
+
4
+ from __future__ import annotations
5
+
6
+ import datetime as dt
7
+ import json
8
+ import math
9
+ import os
10
+ import time
11
+ import contextvars
12
+ from contextlib import contextmanager
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from core.launch_phases.common import (
17
+ AGENT_DIR,
18
+ RUNTIME_FILE,
19
+ RUNTIME_LOCK_FILE,
20
+ RUNTIME_SCHEMA_VERSION,
21
+ RUNTIME_STATES,
22
+ HEARTBEAT_TIMEOUT_SECONDS,
23
+ POLLING_POLICIES,
24
+ REVIEW_MODES,
25
+ COMMIT_POLICIES,
26
+ REVIEW_DECISION_LATER,
27
+ POLLING_DECISION_REQUIRED,
28
+ AUDIT_TODO_ITEMS,
29
+ RUNTIME_STARTED_THIS_PROCESS,
30
+ set_runtime_started_this_process,
31
+ diagnostic_logger,
32
+ resolve_project_root,
33
+ uses_project_layout,
34
+ is_number,
35
+ format_duration,
36
+ SUPERVISOR_STATE,
37
+ COVERAGE_EVIDENCE,
38
+ LIFE_FILE,
39
+ LESSON_LEDGER_FILE,
40
+ GLOBAL_LESSON_LEDGER_FILE,
41
+ LIFECYCLE_MAX_NO_PROGRESS_CYCLES,
42
+ pollings_root,
43
+ bugx_paths,
44
+ )
45
+ import tempfile
46
+ import threading
47
+ import uuid
48
+ import core.secure_atomic as secure_atomic
49
+
50
+
51
+ #: ``runtime_lock`` 的同进程**同线程**重入深度(LOG-03)。flock 对不同 fd
52
+ #: 仍互斥,因此重入必须由本线程自己识别;必须是 thread-local 而非普通全局,
53
+ #: 否则线程 A 持锁会让线程 B 误以为「已持锁」而跳过 flock,互斥直接失效。
54
+ _RUNTIME_LOCK_STATE = threading.local()
55
+
56
+
57
+ #: 显式钉住的 runtime 路径。设置后 ``refresh_runtime_paths`` 用它取代按
58
+ #: ``resolve_project_root()`` 的重算——否则直接给 ``RUNTIME_FILE`` 赋值会被
59
+ #: ``runtime_lock()``/``load_runtime()`` 里的路径刷新静默覆盖,「指定 root」
60
+ #: 的调用方(MCP host 心跳)与测试夹具都会失效。contextvar 按线程隔离,
61
+ #: 心跳 loop 线程与调用线程各自持钉,不会互相污染。
62
+ _RUNTIME_PATH_PIN: contextvars.ContextVar[dict[str, Path] | None] = contextvars.ContextVar(
63
+ "bugx_runtime_path_pin", default=None,
64
+ )
65
+
66
+
67
+ @contextmanager
68
+ def _pinned_runtime_paths(runtime: Path, runtime_lock: Path | None = None):
69
+ """在动态作用域内钉住 runtime 与锁路径,绕过 ``resolve_project_root()`` 重算。
70
+
71
+ 进入时立即写入 globals(直接读 ``RUNTIME_FILE`` 的调用方也立刻看到钉住值),
72
+ 退出时还原,避免钉住值泄漏到后续不相关的项目访问。
73
+ """
74
+ lock = (
75
+ Path(runtime_lock) if runtime_lock is not None
76
+ else Path(runtime).with_name("runtime.lock")
77
+ )
78
+ paths = {"RUNTIME_FILE": Path(runtime), "RUNTIME_LOCK_FILE": lock}
79
+ previous = {k: v for k, v in ((k, globals().get(k)) for k in paths) if v is not None}
80
+ token = _RUNTIME_PATH_PIN.set(paths)
81
+ _apply_runtime_paths(paths)
82
+ try:
83
+ yield
84
+ finally:
85
+ _RUNTIME_PATH_PIN.reset(token)
86
+ if previous:
87
+ _apply_runtime_paths(previous)
88
+
89
+
90
+ def _runtime_lock_depth() -> int:
91
+ """当前线程持有运行状态锁的重入深度。"""
92
+ return int(getattr(_RUNTIME_LOCK_STATE, "depth", 0))
93
+
94
+
95
+ def _set_runtime_lock_depth(value: int) -> None:
96
+ _RUNTIME_LOCK_STATE.depth = value
97
+
98
+
99
+
100
+ def refresh_runtime_paths() -> None:
101
+ """Bind runtime paths to the active .bugx lifecycle.
102
+
103
+ The project .bugx directory contains runtime state only. Executable assets
104
+ are loaded from the global engine; a missing project layout is deliberately
105
+ surfaced to callers.
106
+ """
107
+ pinned = _RUNTIME_PATH_PIN.get()
108
+ if pinned is not None:
109
+ # 显式钉住优先于重算:调用方已指定 runtime 路径时,不得再按
110
+ # resolve_project_root() 覆盖,否则 root 参数静默失效。
111
+ _apply_runtime_paths(pinned)
112
+ return
113
+ if not uses_project_layout():
114
+ return
115
+ # Use the same root resolver as every other global-engine launcher path.
116
+ # Calling bugx_paths.project_root(AGENT_DIR) here is safe because the CLI
117
+ # binds BUGX_PROJECT_ROOT before starting the engine.
118
+ root = resolve_project_root()
119
+ active = bugx_paths.require(root)
120
+ _apply_runtime_paths({
121
+ "COVERAGE_EVIDENCE": active.coverage,
122
+ "SUPERVISOR_STATE": active.supervisor,
123
+ "LESSON_LEDGER_FILE": active.knowledge_seed,
124
+ "GLOBAL_LESSON_LEDGER_FILE": active.global_knowledge_seed,
125
+ "RUNTIME_FILE": active.runtime,
126
+ "RUNTIME_LOCK_FILE": active.runtime_lock,
127
+ })
128
+
129
+
130
+ def _apply_runtime_paths(path_updates: dict[str, Path]) -> None:
131
+ """把路径写进共享层与显式阶段模块,杜绝运行态路径漂移。
132
+
133
+ 阶段模块仍有少量历史 ``from common import`` 路径别名,需要同步以保持
134
+ 现有调用契约;使用显式包引用,不再通过 ``sys.modules`` 扫描并广播。
135
+ """
136
+ global COVERAGE_EVIDENCE, SUPERVISOR_STATE, LESSON_LEDGER_FILE
137
+ global GLOBAL_LESSON_LEDGER_FILE, RUNTIME_FILE, RUNTIME_LOCK_FILE
138
+ for k, v in path_updates.items():
139
+ globals()[k] = v
140
+
141
+ # These are explicit compatibility sinks for legacy ``from common import``
142
+ # aliases. Keep the list small and auditable until each consumer reads
143
+ # ``common`` directly.
144
+ from . import (
145
+ common,
146
+ finding_settlement,
147
+ lesson_context,
148
+ lifecycle_reporter,
149
+ post_phase,
150
+ pre_phase,
151
+ report_sharing,
152
+ round_orchestrator,
153
+ startup_gates,
154
+ supervisor_bridge,
155
+ worker_orchestrator,
156
+ )
157
+ for module in (
158
+ common,
159
+ lesson_context,
160
+ pre_phase,
161
+ round_orchestrator,
162
+ post_phase,
163
+ worker_orchestrator,
164
+ startup_gates,
165
+ lifecycle_reporter,
166
+ finding_settlement,
167
+ report_sharing,
168
+ supervisor_bridge,
169
+ ):
170
+ for k, v in path_updates.items():
171
+ if hasattr(module, k):
172
+ setattr(module, k, v)
173
+
174
+
175
+ def _ensure_project_runtime_paths() -> None:
176
+ """Refresh paths before direct runtime helpers use module-level defaults."""
177
+ if uses_project_layout():
178
+ refresh_runtime_paths()
179
+
180
+
181
+ def audit_todo_path() -> Path | None:
182
+ """Return the current Round's derived TODO view path.
183
+
184
+ The current pointer is the sole scope selector. This keeps the view in
185
+ the same lifecycle ``state`` directory as runtime/coverage evidence and
186
+ avoids accepting a path supplied by an agent or worker.
187
+ """
188
+ if not uses_project_layout() or bugx_paths is None:
189
+ return None
190
+ return bugx_paths.require(resolve_project_root()).state_root / "audit-todo.md"
191
+
192
+ def _audit_todo_content(runtime: dict, phase: str, reason: str | None = None) -> str:
193
+ """Build the human-readable current-Round progress view.
194
+
195
+ This is intentionally a projection of authoritative runtime boundaries;
196
+ it contains no coverage-unit, worker, finding, priority, or completion
197
+ decisions of its own.
198
+ """
199
+ runtime = runtime if isinstance(runtime, dict) else {}
200
+ phase = str(phase or "running")
201
+ completed_through = {
202
+ "running": 4,
203
+ "resumed": 4,
204
+ "life-settled": 9,
205
+ "round-completed": 11,
206
+ "session-completed": len(AUDIT_TODO_ITEMS) - 1,
207
+ "share-pending": len(AUDIT_TODO_ITEMS) - 1,
208
+ "share-completed": len(AUDIT_TODO_ITEMS),
209
+ "blocked": 11,
210
+ "aborted": 0,
211
+ }.get(phase, 0)
212
+ active_index = {
213
+ "running": 4,
214
+ "resumed": 4,
215
+ "life-settled": 9,
216
+ "round-completed": 11,
217
+ "session-completed": len(AUDIT_TODO_ITEMS) - 1,
218
+ "share-pending": len(AUDIT_TODO_ITEMS) - 1,
219
+ "blocked": 11,
220
+ }.get(phase)
221
+ lines = [
222
+ "# BugX 当前 Round TODO",
223
+ "",
224
+ f"- Session:`{runtime.get('session_id') or 'unknown'}`",
225
+ f"- Round:`{runtime.get('round_id') or runtime.get('lifecycle_id') or 'unknown'}`",
226
+ f"- Life:`{runtime.get('life_no') or 'unknown'}`",
227
+ f"- Runtime:`{runtime.get('state') or 'unknown'}`;事件数 `{len(runtime.get('events') or [])}`",
228
+ f"- 同步:`{runtime.get('sync_status') or 'unknown'}`;共享队列状态由 `share_pending.json` 体现",
229
+ f"- 阶段:`{phase}`",
230
+ f"- 最后校准:`{iso_time(time.time())}`",
231
+ "- 来源:`runtime.json`、事件账本、覆盖证据与 Round 报告(派生视图)",
232
+ "",
233
+ ]
234
+ for index, item in enumerate(AUDIT_TODO_ITEMS):
235
+ if index < completed_through:
236
+ marker = "x"
237
+ elif phase == "blocked" and index == active_index:
238
+ marker = "!"
239
+ elif active_index is not None and index == active_index:
240
+ marker = "~"
241
+ else:
242
+ marker = " "
243
+ lines.append(f"- [{marker}] {item}")
244
+ if reason:
245
+ lines.extend(["", f"- 当前原因:{reason}"])
246
+ lines.extend([
247
+ "",
248
+ "> 本文件仅是当前 Round 的操作视图,不是账本、覆盖清单、Finding 来源或完成判定器。",
249
+ ])
250
+ return "\n".join(lines) + "\n"
251
+
252
+ def refresh_audit_todo(runtime: dict, phase: str, reason: str | None = None) -> Path | None:
253
+ """Atomically refresh the derived TODO view without blocking authority."""
254
+ path = audit_todo_path()
255
+ if path is None:
256
+ return None
257
+ try:
258
+ secure_atomic.atomic_write_text(
259
+ path,
260
+ _audit_todo_content(runtime, phase, reason),
261
+ mode=0o600,
262
+ parent_mode=0o700,
263
+ )
264
+ except (OSError, ValueError, RuntimeError) as exc:
265
+ # Runtime/events/report remain authoritative. A stale or missing view
266
+ # is recoverable and must never turn a completed boundary into failure.
267
+ print(f" (TODO 清单视图刷新失败,不影响权威状态:{exc})")
268
+ return None
269
+ return path
270
+
271
+ def _default_runtime() -> dict:
272
+ return {
273
+ "schema_version": RUNTIME_SCHEMA_VERSION,
274
+ "run_id": None,
275
+ "state": "idle",
276
+ "active": False,
277
+ "pid": None,
278
+ "host_pid": None,
279
+ "started_at": None,
280
+ "started_epoch": None,
281
+ "session_started_at": None,
282
+ "session_started_epoch": None,
283
+ "startup_action": None,
284
+ "segment_started_epoch": None,
285
+ "paused_at": None,
286
+ "heartbeat_at": None,
287
+ "heartbeat_epoch": None,
288
+ "round_at_start": None,
289
+ "session_elapsed_seconds": 0.0,
290
+ "last_session_elapsed_seconds": 0.0,
291
+ "total_elapsed_seconds": 0.0,
292
+ "sessions_completed": 0,
293
+ "sessions_aborted": 0,
294
+ "sessions": [],
295
+ "life_runs": [],
296
+ "events": [],
297
+ # 轮询策略独立于 verify_life.mode:后者控制修复方式,这里只控制
298
+ # 当前轮死亡后的续轮行为。None 代表尚未完成启动前的必问交互。
299
+ "polling_policy": None,
300
+ # 提交策略属于启动上下文;log-only 会自动归一为 not_applicable。
301
+ "commit_policy": None,
302
+ "commit_status": None,
303
+ "commit_boundary": None,
304
+ "commit_ref": None,
305
+ "commit_error": None,
306
+ "sync_status": "local",
307
+ "startup_id": None,
308
+ "startup_observation": None,
309
+ "startup_intent": None,
310
+ "startup_result": None,
311
+ # DOC-138: explicit host-agent autonomous mode. The policy/hash are
312
+ # captured at Session start and must not be inferred from model output.
313
+ "host": None,
314
+ "autonomous_mode": False,
315
+ "execute": False,
316
+ "workers": 0,
317
+ "worker_capacity": None,
318
+ "subagent_type": "bugx-worker",
319
+ "stagger_seconds": 0.0,
320
+ "provider": None,
321
+ "autonomous_policy": None,
322
+ "autonomous_policy_hash": None,
323
+ "session_id": None,
324
+ "round_id": None,
325
+ "life_no": None,
326
+ "life_kind": "mine",
327
+ "session_state": "initializing",
328
+ "session_closed_at": None,
329
+ "final_round_id": None,
330
+ # 审查执行面:manual 由宿主/Agent 按步骤推进;mcp-auto 由唯一的
331
+ # bugx-supervisor MCP 负责状态、租约、心跳和门禁协调。None 代表
332
+ # 尚未完成启动前的必问交互。
333
+ "review_mode": None,
334
+ # 仅在明确选择手动回退时记录 deferred;“下次再说”会停止本轮。
335
+ "review_mode_deferred": False,
336
+ "polling_round_auto_started": False,
337
+ "polling_last_round": None,
338
+ "polling_stop_reason": None,
339
+ # Round 状态:verify_life.round/rounds_completed 表示 Round 内 Life。
340
+ "lifecycle_no": 0,
341
+ "lifecycle_id": None,
342
+ "lifecycle_auto_started": False,
343
+ "lifecycle_started_at": None,
344
+ "lifecycle_started_epoch": None,
345
+ "lifecycle_cycles_completed": 0,
346
+ "lifecycle_findings_total": 0,
347
+ "lifecycle_credited_total": 0,
348
+ "lifecycle_fraud_total": 0,
349
+ "lifecycle_last_life": None,
350
+ "lifecycle_terminal": False,
351
+ "lifecycle_last_report": None,
352
+ "lifecycle_no_progress_cycles": 0,
353
+ "lifecycle_stop_reason": None,
354
+ "lifecycle_history": [],
355
+ # Pattern IDs injected into this big lifecycle. A later small
356
+ # lifecycle receives only fresh cards, preventing stale repetition.
357
+ "lifecycle_lesson_ids": [],
358
+ "lifecycle_incident_ids": [],
359
+ "lesson_recent_signatures": [],
360
+ "realized_fix_incidents": [],
361
+ "lesson_context": None,
362
+ "project_profile_hash": None,
363
+ "project_profile_revision": None,
364
+ "project_profile_status": "unknown",
365
+ "project_classification": None,
366
+ "project_routing_tags": {},
367
+ "audit_strategy": None,
368
+ }
369
+
370
+ _RUNTIME_RESET_GUIDANCE = (
371
+ "旧状态不迁移。确认要丢弃旧运行态后,请执行 "
372
+ "`bugx reset --scope project --root <项目路径> --yes`;若重置被活动状态阻断,"
373
+ "先确认没有 Worker 仍会写入状态,再显式加 `--force`。项目 reset 会先创建项目外归档。"
374
+ )
375
+
376
+
377
+ def _require_current_runtime_schema(state: dict, source: Path) -> None:
378
+ """Reject old or incomplete runtime documents before they can be restored or used."""
379
+ schema_version = state.get("schema_version")
380
+ if schema_version != RUNTIME_SCHEMA_VERSION:
381
+ raise ValueError(
382
+ f"运行计时文件 schema_version 不受支持: {source} "
383
+ f"(expected={RUNTIME_SCHEMA_VERSION}, actual={schema_version!r});"
384
+ f"{_RUNTIME_RESET_GUIDANCE}"
385
+ )
386
+ missing = sorted(set(_default_runtime()) - state.keys())
387
+ if missing:
388
+ raise ValueError(
389
+ f"运行计时文件不符合当前 schema: {source};缺少必需字段 "
390
+ f"{', '.join(missing)};{_RUNTIME_RESET_GUIDANCE}"
391
+ )
392
+
393
+ def _is_pid_alive(pid: int | None) -> bool:
394
+ """检测进程是否依然存活(跨平台且不把 Windows WinError 87 当死亡)。"""
395
+ if pid is None or not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
396
+ return False
397
+ if os.name == "nt":
398
+ try:
399
+ import ctypes
400
+
401
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
402
+ kernel32.OpenProcess.argtypes = [ctypes.c_uint32, ctypes.c_int, ctypes.c_uint32]
403
+ kernel32.OpenProcess.restype = ctypes.c_void_p
404
+ kernel32.GetExitCodeProcess.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint32)]
405
+ kernel32.GetExitCodeProcess.restype = ctypes.c_int
406
+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
407
+ kernel32.CloseHandle.restype = ctypes.c_int
408
+ handle = kernel32.OpenProcess(0x1000, 0, pid) # PROCESS_QUERY_LIMITED_INFORMATION
409
+ if not handle:
410
+ return ctypes.get_last_error() == 5 # ERROR_ACCESS_DENIED: process exists
411
+ try:
412
+ exit_code = ctypes.c_uint32()
413
+ return bool(kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code))) \
414
+ and exit_code.value == 259 # STILL_ACTIVE
415
+ finally:
416
+ kernel32.CloseHandle(handle)
417
+ except (AttributeError, OSError, TypeError, ValueError):
418
+ return False
419
+ try:
420
+ os.kill(pid, 0)
421
+ return True
422
+ except ProcessLookupError:
423
+ return False
424
+ except PermissionError:
425
+ return True
426
+ except OSError as err:
427
+ import errno
428
+ if getattr(err, "errno", None) == errno.ESRCH:
429
+ return False
430
+ if getattr(err, "errno", None) == errno.EPERM:
431
+ return True
432
+ return False
433
+
434
+
435
+ def _auto_started_idle_shell(state: dict) -> bool:
436
+ """自动续轮建立的空壳回合:从未完成任何 Life 且零有效发现。
437
+
438
+ post 轮询对这类回合的既定收敛语义是 ``auto_lifecycle_zero_findings``
439
+ (post_phase 的非常驻收敛分支);孤儿裁决复用同一判据,避免把
440
+ 「宿主尚未派发 worker 就失去属主」的空壳回合记成挖掘事故。
441
+ """
442
+ if not state.get("polling_round_auto_started"):
443
+ return False
444
+ if int(state.get("lifecycle_cycles_completed", 0) or 0) != 0:
445
+ return False
446
+ return int(state.get("lifecycle_credited_total", 0) or 0) == 0
447
+
448
+
449
+ def _supervisor_terminal_awaiting_settle(state: dict) -> bool:
450
+ """Supervisor 权威终态已落盘、post 尚未消费时的免孤儿豁免。
451
+
452
+ Supervisor ``finish()``(coverage 未完成绝不产生 COMPLETE)与 COMPLETE
453
+ 后的 reset_budget 禁令共同保证:status=COMPLETE(或 INCOMPLETE/FAILED
454
+ 且 completed_at 已写)是**不可复活的终态**。此时挖掘工作已合法结束,
455
+ 仅因宿主 MCP 通道退出导致 runtime 无人续约;把它裁决成 aborted 会
456
+ 让 post 的 runtime_active 门永久拒绝结算。这里只承认终态,不刷新
457
+ 心跳、不放宽 post 门禁——身份不匹配或文件异常一律回退 abort 路径。
458
+ """
459
+ path = SUPERVISOR_STATE
460
+ if not isinstance(path, Path) or not path.is_file():
461
+ return False
462
+ try:
463
+ payload = json.loads(path.read_text(encoding="utf-8"))
464
+ except (OSError, ValueError):
465
+ return False
466
+ if not isinstance(payload, dict):
467
+ return False
468
+ status = payload.get("status")
469
+ terminal = status == "COMPLETE" or (
470
+ status in {"INCOMPLETE", "FAILED"} and payload.get("completed_at") is not None
471
+ )
472
+ if not terminal:
473
+ return False
474
+ session_id = state.get("session_id")
475
+ round_id = state.get("round_id") or state.get("lifecycle_id")
476
+ if not session_id or payload.get("session_id") != session_id:
477
+ return False
478
+ if not round_id or payload.get("round_id") != round_id:
479
+ return False
480
+ return True
481
+
482
+
483
+ def _reconcile_orphaned_state_locked(state: dict, now: float | None = None) -> bool:
484
+
485
+ """若当前为 active 状态但对应 PID 进程已死亡(或心跳严重超时),自动裁决为 aborted。"""
486
+ if not state.get("active"):
487
+ return False
488
+ pid = state.get("pid")
489
+ heartbeat_epoch = (
490
+ state.get("heartbeat_epoch")
491
+ or state.get("segment_started_epoch")
492
+ or state.get("started_epoch")
493
+ )
494
+ current = time.time() if now is None else now
495
+ heartbeat_stalled = (
496
+ heartbeat_epoch is not None
497
+ and is_number(heartbeat_epoch)
498
+ and (current - float(heartbeat_epoch)) > HEARTBEAT_TIMEOUT_SECONDS
499
+ )
500
+ is_dead = False
501
+ ownership_lost = False
502
+ if pid is not None and isinstance(pid, int) and not isinstance(pid, bool):
503
+ if not _is_pid_alive(pid):
504
+ if heartbeat_stalled or heartbeat_epoch is None:
505
+ is_dead = True
506
+ else:
507
+ # 认领属主(宿主 MCP server 等短生命周期通道)死亡但会话
508
+ # 心跳仍新鲜:只代表通道退出,不代表挖掘进程崩溃。清除
509
+ # 所有权即可;把通道死亡连坐成 Run 中止,会让宿主会话的
510
+ # 开关误杀后台无人值守 Run(真实事故:auto 续轮的 Round
511
+ # 被已退出 MCP 通道的 pid 拖成 aborted)。
512
+ ownership_lost = True
513
+ elif heartbeat_stalled:
514
+ is_dead = True
515
+
516
+ if ownership_lost:
517
+ state.update({"pid": None, "host_pid": None})
518
+ append_runtime_event(
519
+ state, "ownership_released", current,
520
+ "claimed owner process died; heartbeat still fresh",
521
+ )
522
+ # DOC-204 L7:取消回传结构化——"进程死但心跳新鲜"是宿主取消 agent
523
+ # 的引擎侧信号;落 supervisor 权威链 owner_cancelled(D27 修复钩子)。
524
+ try:
525
+ from core.launch_phases.supervisor_bridge import get_supervisor as _bridge_supervisor
526
+
527
+ _bridge_supervisor().record_lifecycle_block(
528
+ operation="lifecycle", gate="owner_cancelled",
529
+ reason="宿主取消 agent:owner 进程死亡而心跳仍新鲜(D27 取消回传)",
530
+ )
531
+ except Exception: # noqa: BLE001 - 回传失败不阻断 ownership 释放
532
+ pass
533
+ return True
534
+
535
+ if not is_dead:
536
+ return False
537
+
538
+ if _supervisor_terminal_awaiting_settle(state):
539
+ # Supervisor 已经合法收尾,但 post 尚未消费其结算副作用。这里不续期
540
+ # heartbeat,也不伪造存活;只把权威终态交给 post,避免先被孤儿裁决
541
+ # 写成 aborted 后永久堵死结算。
542
+ return False
543
+
544
+ if _auto_started_idle_shell(state):
545
+ # 空壳回合(自动续轮、零 Life、零有效发现)失去属主按收敛处理,
546
+ # 复用 post 轮询的 auto_lifecycle_zero_findings 语义:一次落
547
+ # polling_stop_reason 与 lifecycle_stop_reason 两个键,
548
+ # 且不计入 sessions_aborted。
549
+ _accrue_running_segment(state, current)
550
+ elapsed = float(state.get("session_elapsed_seconds", 0.0))
551
+ state.update({
552
+ "state": "completed",
553
+ "active": False,
554
+ "pid": None,
555
+ "host_pid": None,
556
+ "paused_at": None,
557
+ "segment_started_epoch": None,
558
+ "last_session_elapsed_seconds": round(elapsed, 3),
559
+ "sessions_completed": int(state.get("sessions_completed", 0)) + 1,
560
+ "polling_stop_reason": "auto_lifecycle_zero_findings",
561
+ "lifecycle_stop_reason": "auto_lifecycle_zero_findings",
562
+ })
563
+ append_runtime_event(
564
+ state, "orphaned_session_reconciled", current,
565
+ "auto-started idle shell converged (zero findings)",
566
+ )
567
+ return True
568
+
569
+ _accrue_running_segment(state, current)
570
+ elapsed = float(state.get("session_elapsed_seconds", 0.0))
571
+ life_run = {
572
+ "run_id": state.get("run_id"),
573
+ "session_id": state.get("session_id"),
574
+ "round_id": state.get("round_id") or state.get("lifecycle_id"),
575
+ "life_no": state.get("life_no"),
576
+ "outcome": "aborted",
577
+ "started_at": state.get("started_at"),
578
+ "finished_at": iso_time(current),
579
+ "elapsed_seconds": round(elapsed, 3),
580
+ "round_at_start": state.get("round_at_start"),
581
+ "round_at_finish": _current_round(),
582
+ "reason": "process terminated unexpectedly (orphaned)",
583
+ }
584
+ if not isinstance(state.get("life_runs"), list):
585
+ state["life_runs"] = []
586
+ state["life_runs"].append(life_run)
587
+ state.update({
588
+ "state": "aborted",
589
+ "active": False,
590
+ "pid": None,
591
+ "host_pid": None,
592
+ "paused_at": None,
593
+ "segment_started_epoch": None,
594
+ "last_session_elapsed_seconds": round(elapsed, 3),
595
+ "sessions_aborted": int(state.get("sessions_aborted", 0)) + 1,
596
+ })
597
+ append_runtime_event(state, "orphaned_session_reconciled", current, "process died")
598
+ return True
599
+
600
+
601
+ def load_runtime(*, reconcile: bool = True) -> dict:
602
+ """读取并校验计时状态;损坏时优先从 .bak 恢复,拒绝静默归零。
603
+
604
+ LOG-01:本函数**自身不写盘**。孤儿状态的裁决写入收敛到
605
+ :func:`_reconcile_runtime_locked`,它在运行状态锁内**重新读取**后再写。
606
+ 旧实现直接用调用方手上(可能已陈旧)的快照调 ``save_runtime``,会把另一个
607
+ 进程刚写入的 running 心跳整体覆盖成 aborted —— 状态回退。
608
+ """
609
+ _ensure_project_runtime_paths()
610
+ state = _read_runtime_state()
611
+ if not reconcile or not state.get("active"):
612
+ return state
613
+ return _reconcile_runtime_locked()
614
+
615
+
616
+ def _reconcile_runtime_locked() -> dict:
617
+ """在运行状态锁内重新读取并裁决孤儿状态。
618
+
619
+ 拿不到锁时退化为纯只读返回:宁可本轮不裁决,也不做无锁写入。
620
+ """
621
+ try:
622
+ with runtime_lock():
623
+ state = _read_runtime_state()
624
+ if state.get("active") and _reconcile_orphaned_state_locked(state):
625
+ if RUNTIME_FILE.parent.is_dir():
626
+ try:
627
+ save_runtime(state)
628
+ except OSError:
629
+ pass
630
+ return state
631
+ except (TimeoutError, OSError):
632
+ return _read_runtime_state()
633
+
634
+
635
+ def _read_runtime_state() -> dict:
636
+ """纯只读解析 + 校验运行计时文件(不裁决、不写盘)。"""
637
+ if RUNTIME_FILE.is_symlink():
638
+ raise ValueError(f"运行计时文件不能是符号链接: {RUNTIME_FILE}")
639
+ bak_path = RUNTIME_FILE.with_name(RUNTIME_FILE.name + ".bak")
640
+ if not RUNTIME_FILE.is_file():
641
+ if bak_path.is_file() and not bak_path.is_symlink():
642
+ recovered = None
643
+ try:
644
+ bak_content = bak_path.read_text(encoding="utf-8").strip()
645
+ if bak_content:
646
+ recovered = json.loads(bak_content)
647
+ except (OSError, json.JSONDecodeError):
648
+ recovered = None
649
+ if isinstance(recovered, dict):
650
+ _require_current_runtime_schema(recovered, bak_path)
651
+ try:
652
+ import shutil
653
+ shutil.copy2(bak_path, RUNTIME_FILE)
654
+ except OSError:
655
+ pass
656
+ if not RUNTIME_FILE.is_file():
657
+ supervisor_backup = SUPERVISOR_STATE.with_name(SUPERVISOR_STATE.name + ".bak")
658
+ if SUPERVISOR_STATE.exists() or supervisor_backup.exists():
659
+ raise ValueError(
660
+ f"活动生命周期运行计时文件缺失,拒绝回退为空闲状态: {RUNTIME_FILE}; "
661
+ "请先执行 bugx doctor --repair 或从备份恢复"
662
+ )
663
+ # 缺文件回退的默认 runtime 同样注入 polling_id:新建 Session 尚未
664
+ # 写 runtime 时,结算/报告路径也必须解析到真实 polling 目录。
665
+ return _inject_runtime_polling_id(_default_runtime())
666
+ try:
667
+ raw_text = RUNTIME_FILE.read_text(encoding="utf-8").strip()
668
+ if not raw_text:
669
+ raise ValueError("运行计时文件为空(0 字节)")
670
+ state = json.loads(raw_text)
671
+ except (json.JSONDecodeError, OSError, ValueError) as exc:
672
+ recovered = None
673
+ if bak_path.is_file() and not bak_path.is_symlink():
674
+ try:
675
+ bak_content = bak_path.read_text(encoding="utf-8").strip()
676
+ if bak_content:
677
+ candidate = json.loads(bak_content)
678
+ if isinstance(candidate, dict):
679
+ _require_current_runtime_schema(candidate, bak_path)
680
+ recovered = candidate
681
+ try:
682
+ import shutil
683
+ shutil.copy2(bak_path, RUNTIME_FILE)
684
+ except OSError:
685
+ pass
686
+ except (OSError, json.JSONDecodeError):
687
+ recovered = None
688
+ if recovered is not None:
689
+ state = recovered
690
+ else:
691
+ raise ValueError(f"运行计时文件无法解析: {exc}") from exc
692
+ if not isinstance(state, dict):
693
+ raise ValueError("运行计时文件根节点必须是对象")
694
+ _require_current_runtime_schema(state, RUNTIME_FILE)
695
+ if state.get("state") not in RUNTIME_STATES:
696
+ raise ValueError("运行计时文件 state 无效")
697
+ if not isinstance(state.get("active"), bool):
698
+ raise ValueError("运行计时文件 active 必须是布尔值")
699
+ if state["active"] != (state["state"] in {"running", "paused"}):
700
+ raise ValueError("运行计时文件 active 与 state 不一致")
701
+ for key in ("session_elapsed_seconds", "last_session_elapsed_seconds",
702
+ "total_elapsed_seconds"):
703
+ if not is_number(state.get(key)) or state[key] < 0:
704
+ raise ValueError(f"运行计时文件 {key} 无效")
705
+ if not isinstance(state.get("sessions_completed"), int) \
706
+ or isinstance(state["sessions_completed"], bool) \
707
+ or state["sessions_completed"] < 0:
708
+ raise ValueError("运行计时文件 sessions_completed 无效")
709
+ if not isinstance(state.get("sessions_aborted"), int) \
710
+ or isinstance(state["sessions_aborted"], bool) \
711
+ or state["sessions_aborted"] < 0:
712
+ raise ValueError("运行计时文件 sessions_aborted 无效")
713
+ if not isinstance(state.get("sessions"), list):
714
+ raise ValueError("运行计时文件 sessions 必须是列表")
715
+ if not isinstance(state.get("life_runs"), list):
716
+ raise ValueError("运行计时文件 life_runs 必须是列表")
717
+ if not isinstance(state.get("events"), list):
718
+ raise ValueError("运行计时文件 events 必须是列表")
719
+ policy = state.get("polling_policy")
720
+ if policy is not None and policy not in POLLING_POLICIES:
721
+ raise ValueError("运行计时文件 polling_policy 无效")
722
+ commit_policy = state.get("commit_policy")
723
+ if commit_policy is not None and commit_policy not in COMMIT_POLICIES:
724
+ raise ValueError("运行计时文件 commit_policy 无效")
725
+ review_mode = state.get("review_mode")
726
+ if review_mode is not None and review_mode not in REVIEW_MODES:
727
+ raise ValueError("运行计时文件 review_mode 无效")
728
+ if not isinstance(state.get("review_mode_deferred"), bool):
729
+ raise ValueError("运行计时文件 review_mode_deferred 无效")
730
+ if not isinstance(state.get("autonomous_mode"), bool):
731
+ raise ValueError("运行计时文件 autonomous_mode 无效")
732
+ host = state.get("host")
733
+ if host is not None and (
734
+ not isinstance(host, str) or not host.strip() or len(host.strip()) > 64
735
+ ):
736
+ raise ValueError("运行计时文件 host 无效")
737
+ if not isinstance(state.get("execute"), bool):
738
+ raise ValueError("运行计时文件 execute 无效")
739
+ for key in ("workers", "worker_capacity"):
740
+ value = state.get(key)
741
+ if value is not None and (
742
+ not isinstance(value, int) or isinstance(value, bool) or value < 0
743
+ ):
744
+ raise ValueError(f"运行计时文件 {key} 无效")
745
+ subagent_type = state.get("subagent_type")
746
+ if not isinstance(subagent_type, str) or not subagent_type.strip():
747
+ raise ValueError("运行计时文件 subagent_type 无效")
748
+ stagger_seconds = state.get("stagger_seconds")
749
+ if (
750
+ not isinstance(stagger_seconds, (int, float))
751
+ or isinstance(stagger_seconds, bool)
752
+ or not math.isfinite(float(stagger_seconds))
753
+ or stagger_seconds < 0
754
+ ):
755
+ raise ValueError("运行计时文件 stagger_seconds 无效")
756
+ provider = state.get("provider")
757
+ if provider is not None and (
758
+ not isinstance(provider, str) or not provider.strip()
759
+ ):
760
+ raise ValueError("运行计时文件 provider 无效")
761
+ policy_hash = state.get("autonomous_policy_hash")
762
+ if policy_hash is not None and (
763
+ not isinstance(policy_hash, str) or len(policy_hash) != 64
764
+ ):
765
+ raise ValueError("运行计时文件 autonomous_policy_hash 无效")
766
+ if not isinstance(state.get("polling_round_auto_started"), bool):
767
+ raise ValueError("运行计时文件 polling_round_auto_started 无效")
768
+ if state.get("polling_last_round") is not None \
769
+ and not isinstance(state.get("polling_last_round"), dict):
770
+ raise ValueError("运行计时文件 polling_last_round 无效")
771
+ if state.get("polling_stop_reason") is not None \
772
+ and not isinstance(state.get("polling_stop_reason"), str):
773
+ raise ValueError("运行计时文件 polling_stop_reason 无效")
774
+ if not isinstance(state.get("lifecycle_no"), int) \
775
+ or isinstance(state.get("lifecycle_no"), bool) \
776
+ or state["lifecycle_no"] < 0:
777
+ raise ValueError("运行计时文件 lifecycle_no 无效")
778
+ if state.get("lifecycle_id") is not None \
779
+ and not isinstance(state.get("lifecycle_id"), str):
780
+ raise ValueError("运行计时文件 lifecycle_id 无效")
781
+ if state.get("lifecycle_started_epoch") is not None \
782
+ and not is_number(state.get("lifecycle_started_epoch")):
783
+ raise ValueError("运行计时文件 lifecycle_started_epoch 无效")
784
+ if not isinstance(state.get("lifecycle_auto_started"), bool):
785
+ raise ValueError("运行计时文件 lifecycle_auto_started 无效")
786
+ if not isinstance(state.get("lifecycle_terminal"), bool):
787
+ raise ValueError("运行计时文件 lifecycle_terminal 无效")
788
+ for key in ("lifecycle_cycles_completed", "lifecycle_findings_total",
789
+ "lifecycle_credited_total", "lifecycle_fraud_total"):
790
+ if not isinstance(state.get(key), int) \
791
+ or isinstance(state.get(key), bool) or state[key] < 0:
792
+ raise ValueError(f"运行计时文件 {key} 无效")
793
+ if state.get("lifecycle_last_life") is not None \
794
+ and (not isinstance(state.get("lifecycle_last_life"), int)
795
+ or isinstance(state.get("lifecycle_last_life"), bool)):
796
+ raise ValueError("运行计时文件 lifecycle_last_life 无效")
797
+ if state.get("lifecycle_last_report") is not None \
798
+ and not isinstance(state.get("lifecycle_last_report"), str):
799
+ raise ValueError("运行计时文件 lifecycle_last_report 无效")
800
+ if not isinstance(state.get("lifecycle_no_progress_cycles"), int) \
801
+ or isinstance(state.get("lifecycle_no_progress_cycles"), bool) \
802
+ or state["lifecycle_no_progress_cycles"] < 0:
803
+ raise ValueError("运行计时文件 lifecycle_no_progress_cycles 无效")
804
+ if state.get("lifecycle_stop_reason") is not None \
805
+ and not isinstance(state.get("lifecycle_stop_reason"), str):
806
+ raise ValueError("运行计时文件 lifecycle_stop_reason 无效")
807
+ if not isinstance(state.get("lifecycle_history"), list):
808
+ raise ValueError("运行计时文件 lifecycle_history 必须是列表")
809
+ lesson_ids = state.get("lifecycle_lesson_ids")
810
+ if not isinstance(lesson_ids, list) or any(
811
+ not isinstance(item, str) or not item for item in lesson_ids):
812
+ raise ValueError("运行计时文件 lifecycle_lesson_ids 无效")
813
+ if len(lesson_ids) != len(set(lesson_ids)):
814
+ raise ValueError("运行计时文件 lifecycle_lesson_ids 不得重复")
815
+ for key in ("lifecycle_incident_ids", "lesson_recent_signatures", "realized_fix_incidents"):
816
+ values = state.get(key)
817
+ if not isinstance(values, list) or any(
818
+ not isinstance(item, str) or not item for item in values):
819
+ raise ValueError(f"运行计时文件 {key} 无效")
820
+ if len(values) != len(set(values)):
821
+ raise ValueError(f"运行计时文件 {key} 不得重复")
822
+ lesson_context = state.get("lesson_context")
823
+ if lesson_context is not None and not isinstance(lesson_context, dict):
824
+ raise ValueError("运行计时文件 lesson_context 无效")
825
+ if state["active"] and not is_number(state.get("started_epoch")):
826
+ raise ValueError("活动计时缺少 started_epoch")
827
+ if state["active"] and not isinstance(state.get("run_id"), str):
828
+ raise ValueError("活动计时缺少 run_id")
829
+ if state["state"] == "running" and not is_number(state.get("segment_started_epoch")):
830
+ raise ValueError("运行中计时缺少 segment_started_epoch")
831
+ if state["active"] and not is_number(state.get("heartbeat_epoch")):
832
+ raise ValueError("活动计时缺少 heartbeat_epoch")
833
+ if state.get("polling_id") is not None \
834
+ and not isinstance(state.get("polling_id"), str):
835
+ raise ValueError("运行计时文件 polling_id 无效")
836
+ return _inject_runtime_polling_id(state)
837
+
838
+ def _inject_runtime_polling_id(state: dict) -> dict:
839
+ """从布局权威 current.json 注入 polling_id(Session 标识)。
840
+
841
+ 运行计时文件历史上从不写 polling_id,结算/报告路径只能盲猜
842
+ polling-000001,第二个 Session 起会解析到错误目录。current.json
843
+ 是 Session/Round 活动指针的唯一权威;已有值(同生命周期持久化
844
+ 产物)优先,避免旧 runtime 被新 Session 指针劫持。
845
+ """
846
+ if "polling_id" in state:
847
+ return state
848
+ if bugx_paths is None:
849
+ return state
850
+ if not uses_project_layout():
851
+ # 自包含引擎副本布局没有 ``current.json`` 指针,Session 维度只能由
852
+ # 运行态自身承载。缺省时**就地铸造**一个稳定 id(同一 lifecycle 恒定),
853
+ # 让写入端与读取端指向同一目录。旧行为留空 ⇒ 双方各自落到
854
+ # ``polling-unknown`` 之外的私有推导,findings.json 成为孤儿,
855
+ # 表现为 "Finding 快照校验失败" 与 "finding_count=1,结算结果=0"。
856
+ return state
857
+ try:
858
+ polling_id = bugx_paths.read_current(resolve_project_root()).get("polling_id")
859
+ except (OSError, ValueError, RuntimeError, KeyError, TypeError):
860
+ return state
861
+ if isinstance(polling_id, str) and polling_id:
862
+ state["polling_id"] = polling_id
863
+ return state
864
+
865
+ @contextmanager
866
+ def runtime_lock(timeout_seconds: float = 3.0):
867
+ """用 flock 串行化短写操作;持有进程死亡时由内核自动释放(DOC-031 锁统一)。
868
+
869
+ 锁文件本身跨进程常驻(flock 语义下 unlink 会导致锁竞争窗口),不再
870
+ 写 pid/token,也不再做 age 抢占——陈旧锁由内核在进程退出时回收。
871
+
872
+ LOG-03:打开锁文件时加 ``O_NOFOLLOW`` 并预检符号链接。若 ``runtime.lock``
873
+ 被替换成符号链接,``flock`` 会作用到链接指向的任意文件,互斥被绕过。
874
+
875
+ 同进程重入:flock 对同一文件的**不同 fd** 仍互斥,因此 ``runtime_lock``
876
+ 内再调用 ``load_runtime(reconcile=True)`` 会自锁死;这里用**线程内**深度
877
+ 计数放行同线程重入(外层已持有锁,语义等价)。跨线程不共享该计数,因此
878
+ 线程 B 仍必须真正竞争 flock。
879
+ """
880
+ _ensure_project_runtime_paths()
881
+ depth = _runtime_lock_depth()
882
+ if depth > 0:
883
+ _set_runtime_lock_depth(depth + 1)
884
+ try:
885
+ yield
886
+ finally:
887
+ _set_runtime_lock_depth(depth)
888
+ return
889
+ lock_parent = RUNTIME_LOCK_FILE.parent
890
+ bugx_paths.assert_no_symlink_components(lock_parent)
891
+ bugx_paths.ensure_dir(lock_parent, mode=0o700)
892
+ bugx_paths.assert_no_symlink_components(lock_parent)
893
+ if RUNTIME_LOCK_FILE.is_symlink():
894
+ raise ValueError(f"运行状态锁不能是符号链接: {RUNTIME_LOCK_FILE}")
895
+ deadline = time.monotonic() + timeout_seconds
896
+ fd = os.open(
897
+ RUNTIME_LOCK_FILE,
898
+ os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0),
899
+ 0o600,
900
+ )
901
+ try:
902
+ try:
903
+ import fcntl
904
+ except ImportError: # pragma: no cover - Windows fallback
905
+ fcntl = None # type: ignore[assignment]
906
+ try:
907
+ import msvcrt
908
+ except ImportError: # pragma: no cover - POSIX fallback
909
+ msvcrt = None # type: ignore[assignment]
910
+ if fcntl is not None:
911
+ while True:
912
+ try:
913
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
914
+ break
915
+ except OSError:
916
+ if time.monotonic() >= deadline:
917
+ raise TimeoutError(
918
+ "运行状态正被另一进程更新,请稍后重试"
919
+ f"({RUNTIME_LOCK_FILE.name} flock 等待超过 {timeout_seconds:.0f}s)"
920
+ )
921
+ time.sleep(0.05)
922
+ elif msvcrt is not None:
923
+ # ``msvcrt.locking`` locks a byte range and requires the file to
924
+ # contain that byte. Keep the lock file resident and use the
925
+ # non-blocking primitive so Windows follows the same bounded wait
926
+ # contract as the POSIX flock path.
927
+ if os.fstat(fd).st_size == 0:
928
+ os.write(fd, b"\0")
929
+ os.lseek(fd, 0, os.SEEK_SET)
930
+ lock_mode = getattr(msvcrt, "LK_NBLCK", msvcrt.LK_LOCK)
931
+ while True:
932
+ try:
933
+ msvcrt.locking(fd, lock_mode, 1)
934
+ break
935
+ except OSError:
936
+ if time.monotonic() >= deadline:
937
+ raise TimeoutError(
938
+ "运行状态正被另一进程更新,请稍后重试"
939
+ f"({RUNTIME_LOCK_FILE.name} msvcrt 等待超过 {timeout_seconds:.0f}s)"
940
+ )
941
+ time.sleep(0.05)
942
+ else:
943
+ raise OSError("当前平台缺少 fcntl 和 msvcrt,无法安全锁定运行状态")
944
+ _set_runtime_lock_depth(depth + 1)
945
+ try:
946
+ yield
947
+ finally:
948
+ _set_runtime_lock_depth(depth)
949
+ if fcntl is not None:
950
+ try:
951
+ fcntl.flock(fd, fcntl.LOCK_UN)
952
+ except OSError:
953
+ pass
954
+ elif msvcrt is not None:
955
+ try:
956
+ os.lseek(fd, 0, os.SEEK_SET)
957
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
958
+ except OSError:
959
+ pass
960
+ finally:
961
+ os.close(fd)
962
+
963
+ def save_runtime(state: dict) -> None:
964
+ """原子写入计时状态,避免中断产生半个 JSON,并保持 .bak 容灾副本。"""
965
+ fd, temp_path = tempfile.mkstemp(
966
+ dir=str(RUNTIME_FILE.parent), prefix=".runtime-", suffix=".tmp",
967
+ )
968
+ backup_temp_path: str | None = None
969
+ try:
970
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
971
+ handle.write(json.dumps(state, ensure_ascii=False, indent=2) + "\n")
972
+ bak_path = RUNTIME_FILE.with_name(RUNTIME_FILE.name + ".bak")
973
+ if RUNTIME_FILE.is_file() and not RUNTIME_FILE.is_symlink():
974
+ backup_fd, backup_temp_path = tempfile.mkstemp(
975
+ dir=str(RUNTIME_FILE.parent), prefix=".runtime-bak-", suffix=".tmp",
976
+ )
977
+ os.close(backup_fd)
978
+ import shutil
979
+ shutil.copy2(RUNTIME_FILE, backup_temp_path)
980
+ os.replace(backup_temp_path, bak_path)
981
+ backup_temp_path = None
982
+ os.replace(temp_path, RUNTIME_FILE)
983
+ except BaseException:
984
+ try:
985
+ os.unlink(temp_path)
986
+ except OSError:
987
+ pass
988
+ if backup_temp_path is not None:
989
+ try:
990
+ os.unlink(backup_temp_path)
991
+ except OSError:
992
+ pass
993
+ raise
994
+
995
+ def iso_time(epoch: float) -> str:
996
+ return dt.datetime.fromtimestamp(epoch, tz=dt.timezone.utc).astimezone().isoformat(
997
+ timespec="seconds"
998
+ )
999
+
1000
+ _iso_time = iso_time
1001
+ _load_runtime = load_runtime
1002
+
1003
+ def _current_round() -> int | None:
1004
+ life = baseline_json()
1005
+ value = life.get("round") if life else None
1006
+ return value if isinstance(value, int) else None
1007
+
1008
+ def _round_or_default(new_lifecycle: bool) -> int | None:
1009
+ """新生命周期首个 Round 的兜底轮号。
1010
+
1011
+ auto 续轮先由 ``start_runtime`` 切换 current.json、life.json 随后才
1012
+ 初始化;此刻 ``_current_round()`` 读不到基线返回 None。运行时缺
1013
+ ``round`` 会让 findings 运行绑定按 fail-closed 拒绝结算,因此全新
1014
+ 生命周期按协议初始态取 1;非新生命周期(恢复/续开)保持原语义。
1015
+ """
1016
+ round_value = _current_round()
1017
+ if round_value is None and new_lifecycle:
1018
+ return 1
1019
+ return round_value
1020
+
1021
+ def diagnostic_context() -> dict[str, object]:
1022
+ """Attach runtime identity to diagnostic events without making logs authoritative."""
1023
+ try:
1024
+ state = load_runtime()
1025
+ except (OSError, ValueError, json.JSONDecodeError):
1026
+ return {}
1027
+ fields: dict[str, object] = {}
1028
+ for key in ("run_id", "lifecycle_id", "worker_id", "finding_id", "incident_id"):
1029
+ value = state.get(key)
1030
+ if isinstance(value, str) and value:
1031
+ fields[key] = value
1032
+ round_value = _current_round()
1033
+ if round_value is not None:
1034
+ fields["round"] = round_value
1035
+ return fields
1036
+
1037
+ def append_runtime_event(state: dict, event: str, now: float,
1038
+ message: str | None = None) -> None:
1039
+ item = {"at": iso_time(now), "epoch": now, "event": event}
1040
+ if message:
1041
+ item["message"] = message
1042
+ state["events"] = [*state.get("events", []), item][-200:]
1043
+
1044
+ def _accrue_running_segment(state: dict, now: float) -> None:
1045
+ if state.get("state") != "running":
1046
+ return
1047
+ started = float(state["segment_started_epoch"])
1048
+ state["session_elapsed_seconds"] = round(
1049
+ float(state["session_elapsed_seconds"]) + max(0.0, now - started), 3
1050
+ )
1051
+ state["segment_started_epoch"] = now
1052
+
1053
+ def reset_segment_timer(now: float | None = None) -> None:
1054
+ """更新会话起算点,避免将人类交互和环境探针的开销计入 Worker 任务执行时间。"""
1055
+ with runtime_lock():
1056
+ state = load_runtime()
1057
+ if not state.get("active") or state.get("state") != "running":
1058
+ return
1059
+ current = time.time() if now is None else now
1060
+ state["started_at"] = iso_time(current)
1061
+ state["started_epoch"] = current
1062
+ state["segment_started_epoch"] = current
1063
+ state["heartbeat_at"] = iso_time(current)
1064
+ state["heartbeat_epoch"] = current
1065
+ save_runtime(state)
1066
+
1067
+ def start_runtime(now: float | None = None,
1068
+ auto_started: bool | None = None,
1069
+ new_lifecycle: bool | None = None,
1070
+ new_session: bool | None = None) -> tuple[dict, bool]:
1071
+ global RUNTIME_STARTED_THIS_PROCESS
1072
+ with runtime_lock():
1073
+ state = load_runtime()
1074
+ if state["active"]:
1075
+ current = time.time() if now is None else now
1076
+ if _reconcile_orphaned_state_locked(state, current):
1077
+ save_runtime(state)
1078
+ else:
1079
+ return state, False
1080
+ current = time.time() if now is None else now
1081
+ if auto_started is None:
1082
+ auto_started = False
1083
+ if new_lifecycle is None:
1084
+ new_lifecycle = state.get("lifecycle_id") is None
1085
+ if new_session is None:
1086
+ # 自动续 Round 仍属于同一次 IDE Session;只有首次启动或新建
1087
+ # polling 容器时才建立新的 Session 身份。
1088
+ new_session = bool(new_lifecycle and not state.get("session_id"))
1089
+ session_state = {}
1090
+ if uses_project_layout():
1091
+ try:
1092
+ session_state = json.loads(
1093
+ bugx_paths.require(resolve_project_root()).session_state.read_text(
1094
+ encoding="utf-8"
1095
+ )
1096
+ )
1097
+ except (OSError, ValueError, json.JSONDecodeError):
1098
+ session_state = {}
1099
+ if new_lifecycle:
1100
+ if uses_project_layout():
1101
+ active = bugx_paths.require(resolve_project_root())
1102
+ current_layout = bugx_paths.read_current(resolve_project_root())
1103
+ if new_session or (state.get("lifecycle_id") is None and not state.get("lifecycle_no")):
1104
+ # The first runtime session adopts the lifecycle created by
1105
+ # `bugx init`; a new Session likewise adopts the fresh
1106
+ # polling/lifecycle tree created by create_session().
1107
+ lifecycle_no = int(current_layout["lifecycle_no"])
1108
+ lifecycle_id = str(current_layout["lifecycle_id"])
1109
+ else:
1110
+ lifecycle_no = int(state.get("lifecycle_no", 0)) + 1
1111
+ lifecycle_id = f"lifecycle-{lifecycle_no:06d}"
1112
+ bugx_paths.activate_lifecycle(
1113
+ resolve_project_root(), lifecycle_no, lifecycle_id,
1114
+ polling_id=str(current_layout["polling_id"]),
1115
+ polling_no=int(current_layout.get("polling_no", 1)),
1116
+ )
1117
+ # activate_lifecycle 已把 current.json 切到新生命周期;
1118
+ # 路径全局(RUNTIME_FILE/SUPERVISOR_STATE 等)必须立即
1119
+ # 重绑,否则新 Round 的 runtime 会写进旧生命周期的
1120
+ # state 目录——指针交叉与 runtime 缺失的根源。
1121
+ refresh_runtime_paths()
1122
+ else:
1123
+ lifecycle_no = int(state.get("lifecycle_no", 0)) + 1
1124
+ lifecycle_id = uuid.uuid4().hex
1125
+ lifecycle_fields = {
1126
+ "lifecycle_no": lifecycle_no,
1127
+ "lifecycle_id": lifecycle_id,
1128
+ "lifecycle_auto_started": bool(auto_started),
1129
+ "lifecycle_started_at": iso_time(current),
1130
+ "lifecycle_started_epoch": current,
1131
+ "lifecycle_cycles_completed": 0,
1132
+ "lifecycle_findings_total": 0,
1133
+ "lifecycle_credited_total": 0,
1134
+ "lifecycle_fraud_total": 0,
1135
+ "lifecycle_last_life": None,
1136
+ "lifecycle_terminal": False,
1137
+ "lifecycle_last_report": None,
1138
+ "lifecycle_no_progress_cycles": 0,
1139
+ "lifecycle_stop_reason": None,
1140
+ "lifecycle_lesson_ids": [],
1141
+ # Life 幂等键只属于当前 Round;新 Round
1142
+ # 即使复用相同的 verify_life.round,也必须重新计数。
1143
+ "polling_last_round": None,
1144
+ }
1145
+ else:
1146
+ lifecycle_fields = {
1147
+ "lifecycle_terminal": False,
1148
+ "lifecycle_last_report": None,
1149
+ }
1150
+ # A new Session gets a fresh intermediate-record space. The project
1151
+ # knowledge/coverage layers remain shared, but session-local run,
1152
+ # round, life and consumption history must never leak from the
1153
+ # completed/aborted predecessor.
1154
+ session_fields = {
1155
+ "startup_id": (
1156
+ uuid.uuid4().hex if new_session
1157
+ else state.get("startup_id") or uuid.uuid4().hex
1158
+ ),
1159
+ "startup_action": (
1160
+ None if new_session else state.get("startup_action")
1161
+ ),
1162
+ "life_runs": [] if new_session else list(state.get("life_runs", [])),
1163
+ "lifecycle_history": (
1164
+ [] if new_session else list(state.get("lifecycle_history", []))
1165
+ ),
1166
+ "lifecycle_incident_ids": (
1167
+ [] if new_session else list(state.get("lifecycle_incident_ids", []))
1168
+ ),
1169
+ "lesson_recent_signatures": (
1170
+ [] if new_session else list(state.get("lesson_recent_signatures", []))
1171
+ ),
1172
+ "realized_fix_incidents": (
1173
+ [] if new_session else list(state.get("realized_fix_incidents", []))
1174
+ ),
1175
+ "lesson_context": None if new_session else state.get("lesson_context"),
1176
+ }
1177
+ # DOC-RECOVERY-BINDING:恢复会话(非 new_session)时,若同 lifecycle 的
1178
+ # Supervisor 账本仍在(挖掘证据在链上),必须**收养**其 run_id——否则
1179
+ # runtime 与 supervisor 身份分裂,post 的 findings 绑定校验永久
1180
+ # findings_binding_mismatch(实测:恢复 pre 换新 run_id 后 9 条 confirmed
1181
+ # 无法结算)。仅 new_session 才铸造新身份。
1182
+ adopted_run_id = None
1183
+ if not new_session:
1184
+ try:
1185
+ sup_path = (
1186
+ pollings_root()
1187
+ / str(state.get("polling_id"))
1188
+ / "lifecycles" / str(state.get("lifecycle_id"))
1189
+ / "state" / "supervisor.json"
1190
+ )
1191
+ if sup_path.is_file():
1192
+ sup_run = json.loads(sup_path.read_text(encoding="utf-8")).get("run_id")
1193
+ if isinstance(sup_run, str) and sup_run.strip():
1194
+ adopted_run_id = sup_run
1195
+ except Exception:
1196
+ adopted_run_id = None
1197
+ state.update({
1198
+ "schema_version": RUNTIME_SCHEMA_VERSION,
1199
+ "run_id": adopted_run_id or uuid.uuid4().hex,
1200
+ "state": "running",
1201
+ "active": True,
1202
+ "pid": (
1203
+ int(os.environ["BUGX_PROCESS_PID"])
1204
+ if os.environ.get("BUGX_PROCESS_PID", "").isdigit()
1205
+ else None
1206
+ ),
1207
+ "host_pid": (
1208
+ int(os.environ["BUGX_HOST_PID"])
1209
+ if os.environ.get("BUGX_HOST_PID", "").isdigit()
1210
+ else None
1211
+ ),
1212
+ "started_at": iso_time(current),
1213
+ "started_epoch": current,
1214
+ "segment_started_epoch": current,
1215
+ "paused_at": None,
1216
+ "heartbeat_at": iso_time(current),
1217
+ "heartbeat_epoch": current,
1218
+ "round_at_start": _round_or_default(bool(new_lifecycle)),
1219
+ # 当前 Round 必须持久化:findings 运行绑定
1220
+ # (finding_settlement._expected_findings_binding / _auto_build_findings_json)
1221
+ # 与 lifecycle_reporter / post_dry_run 都读 runtime["round"],且缺该字段时
1222
+ # 结算按 fail-closed 拒绝(tests.test_finding_settlement
1223
+ # ::test_auto_build_rejects_missing_runtime_round_before_writing)。
1224
+ # 这里与 round_at_start 同源(本 Session 所属 Round),保证
1225
+ # 「本轮已结算后再 post」仍能通过绑定校验;新生命周期在 life
1226
+ # 初始化前取初始态 1(见 _round_or_default)。
1227
+ "round": _round_or_default(bool(new_lifecycle)),
1228
+ "session_elapsed_seconds": 0.0,
1229
+ "last_session_elapsed_seconds": 0.0,
1230
+ "events": [],
1231
+ "polling_round_auto_started": (
1232
+ bool(auto_started) if new_lifecycle
1233
+ else bool(state.get("polling_round_auto_started"))
1234
+ ),
1235
+ "polling_stop_reason": None,
1236
+ "startup_id": state.get("startup_id") or uuid.uuid4().hex,
1237
+ "session_id": (
1238
+ str(bugx_paths.read_current(resolve_project_root())["polling_id"])
1239
+ if new_session and uses_project_layout()
1240
+ else state.get("session_id") or str(
1241
+ state.get("polling_id") or "session-unknown"
1242
+ )
1243
+ ),
1244
+ "session_started_at": (
1245
+ iso_time(current) if new_session
1246
+ else state.get("session_started_at") or iso_time(current)
1247
+ ),
1248
+ "session_started_epoch": (
1249
+ current if new_session
1250
+ else state.get("session_started_epoch") or current
1251
+ ),
1252
+ "total_elapsed_seconds": float(
1253
+ session_state.get("total_elapsed_seconds", state.get("total_elapsed_seconds", 0.0))
1254
+ ),
1255
+ "sessions_completed": int(
1256
+ session_state.get("sessions_completed", state.get("sessions_completed", 0))
1257
+ ),
1258
+ "sessions_aborted": int(
1259
+ session_state.get("sessions_aborted", state.get("sessions_aborted", 0))
1260
+ ),
1261
+ "sessions": list(session_state.get("sessions", state.get("sessions", []))),
1262
+ "round_id": lifecycle_fields.get("lifecycle_id") or state.get("lifecycle_id"),
1263
+ "life_no": _current_round(),
1264
+ "startup_result": "resume" if not new_lifecycle else "new_session",
1265
+ "session_state": "running",
1266
+ "session_closed_at": None,
1267
+ "final_round_id": None,
1268
+ **session_fields,
1269
+ **lifecycle_fields,
1270
+ })
1271
+ append_runtime_event(state, "started", current)
1272
+ save_runtime(state)
1273
+ RUNTIME_STARTED_THIS_PROCESS = True
1274
+ set_runtime_started_this_process(True)
1275
+ return state, True
1276
+
1277
+ def runtime_summary(now: float | None = None) -> dict:
1278
+ state = load_runtime()
1279
+ current = time.time() if now is None else now
1280
+ live = float(state["session_elapsed_seconds"])
1281
+ if state["state"] == "running":
1282
+ live += max(0.0, current - float(state["segment_started_epoch"]))
1283
+ heartbeat_age = None
1284
+ if is_number(state.get("heartbeat_epoch")):
1285
+ heartbeat_age = max(0.0, current - float(state["heartbeat_epoch"]))
1286
+ stalled = state["state"] == "running" and (
1287
+ heartbeat_age is None or heartbeat_age > HEARTBEAT_TIMEOUT_SECONDS
1288
+ )
1289
+ health = "stalled" if stalled else state["state"]
1290
+ return {
1291
+ **state,
1292
+ "health": health,
1293
+ "stalled": stalled,
1294
+ "heartbeat_age_seconds": round(heartbeat_age, 3)
1295
+ if heartbeat_age is not None else None,
1296
+ "heartbeat_timeout_seconds": HEARTBEAT_TIMEOUT_SECONDS,
1297
+ "current_elapsed_seconds": round(live, 3),
1298
+ "effective_total_seconds": round(float(state["total_elapsed_seconds"]) + live, 3),
1299
+ "current_round": _current_round(),
1300
+ }
1301
+
1302
+ def close_runtime(outcome: str, now: float | None = None,
1303
+ reason: str | None = None) -> tuple[dict, bool]:
1304
+ with runtime_lock():
1305
+ state = load_runtime()
1306
+ if not state["active"]:
1307
+ return runtime_summary(now), False
1308
+ current = time.time() if now is None else now
1309
+ _accrue_running_segment(state, current)
1310
+ elapsed = float(state["session_elapsed_seconds"])
1311
+ life_run = {
1312
+ "run_id": state.get("run_id"),
1313
+ "session_id": state.get("session_id"),
1314
+ "round_id": state.get("round_id") or state.get("lifecycle_id"),
1315
+ "life_no": state.get("life_no"),
1316
+ "outcome": outcome,
1317
+ "started_at": state["started_at"],
1318
+ "finished_at": iso_time(current),
1319
+ "elapsed_seconds": round(elapsed, 3),
1320
+ "round_at_start": state.get("round_at_start"),
1321
+ "round_at_finish": _current_round(),
1322
+ }
1323
+ if reason:
1324
+ life_run["reason"] = reason
1325
+ state.update({
1326
+ "state": outcome,
1327
+ "active": False,
1328
+ "pid": None,
1329
+ "host_pid": None,
1330
+ "segment_started_epoch": None,
1331
+ "paused_at": None,
1332
+ "heartbeat_at": iso_time(current),
1333
+ "heartbeat_epoch": current,
1334
+ "total_elapsed_seconds": round(
1335
+ float(state["total_elapsed_seconds"]) + elapsed, 3
1336
+ ),
1337
+ "last_session_elapsed_seconds": round(elapsed, 3),
1338
+ "session_elapsed_seconds": 0.0,
1339
+ # A runtime file is rotated for every Life/ Round. Do not count
1340
+ # that segment as a completed Session; Session counters are
1341
+ # committed exactly once by _close_session below.
1342
+ "life_runs": [*state.get("life_runs", []), life_run][-100:],
1343
+ })
1344
+ append_runtime_event(state, outcome, current, reason)
1345
+ save_runtime(state)
1346
+ if uses_project_layout():
1347
+ # Keep the cumulative Session timer in the Session container so a
1348
+ # new Round can start with the same total instead of resetting it.
1349
+ try:
1350
+ bugx_paths.update_session_state(
1351
+ resolve_project_root(),
1352
+ {"total_elapsed_seconds": state["total_elapsed_seconds"]},
1353
+ )
1354
+ except (OSError, ValueError, RuntimeError):
1355
+ # The authoritative Life checkpoint is already durable. A
1356
+ # missing Session index is surfaced on the next startup rather
1357
+ # than silently changing the completed Life result.
1358
+ pass
1359
+ # TODO is a derived operator view, not the authority. Refresh it only
1360
+ # after the runtime checkpoint is durable so an aborted/completed segment
1361
+ # cannot leave the visible checklist claiming that work is still running.
1362
+ if outcome == "aborted":
1363
+ refresh_audit_todo(state, "aborted", reason)
1364
+ elif outcome == "completed":
1365
+ refresh_audit_todo(state, "life-settled")
1366
+ return runtime_summary(current), True
1367
+
1368
+ def finish_runtime(now: float | None = None) -> dict:
1369
+ runtime, _ = close_runtime("completed", now)
1370
+ return runtime
1371
+
1372
+ def pause_runtime(now: float | None = None) -> tuple[dict, bool]:
1373
+ with runtime_lock():
1374
+ state = load_runtime()
1375
+ if state["state"] != "running":
1376
+ return state, False
1377
+ current = time.time() if now is None else now
1378
+ _accrue_running_segment(state, current)
1379
+ state.update({
1380
+ "state": "paused",
1381
+ "active": True,
1382
+ "segment_started_epoch": None,
1383
+ "paused_at": iso_time(current),
1384
+ "heartbeat_at": iso_time(current),
1385
+ "heartbeat_epoch": current,
1386
+ })
1387
+ append_runtime_event(state, "paused", current)
1388
+ save_runtime(state)
1389
+ return state, True
1390
+
1391
+ def resume_runtime(now: float | None = None) -> tuple[dict, bool]:
1392
+ with runtime_lock():
1393
+ state = load_runtime()
1394
+ if state["state"] != "paused":
1395
+ return state, False
1396
+ current = time.time() if now is None else now
1397
+ state.update({
1398
+ "state": "running",
1399
+ "active": True,
1400
+ "segment_started_epoch": current,
1401
+ "paused_at": None,
1402
+ "heartbeat_at": iso_time(current),
1403
+ "heartbeat_epoch": current,
1404
+ })
1405
+ append_runtime_event(state, "resumed", current)
1406
+ save_runtime(state)
1407
+ return state, True
1408
+
1409
+ def heartbeat_runtime(now: float | None = None,
1410
+ owner_pid: int | None = None) -> tuple[dict, bool]:
1411
+ if owner_pid is not None and (
1412
+ not isinstance(owner_pid, int)
1413
+ or isinstance(owner_pid, bool)
1414
+ or owner_pid <= 0
1415
+ ):
1416
+ raise ValueError("heartbeat owner PID 无效")
1417
+ with runtime_lock():
1418
+ # A host MCP channel can outlive the short-lived pre process that
1419
+ # originally wrote ``pid``. Let that channel claim ownership before
1420
+ # the normal orphan reconciliation runs; ordinary reads keep the
1421
+ # existing fail-closed dead-process behavior.
1422
+ state = load_runtime(reconcile=owner_pid is None)
1423
+ if owner_pid is not None and state.get("state") == "running":
1424
+ state["pid"] = owner_pid
1425
+ state["host_pid"] = owner_pid
1426
+ if _reconcile_orphaned_state_locked(state):
1427
+ save_runtime(state)
1428
+ return state, False
1429
+ if state["state"] != "running":
1430
+ return state, False
1431
+ current = time.time() if now is None else now
1432
+ state.update({
1433
+ "heartbeat_at": iso_time(current),
1434
+ "heartbeat_epoch": current,
1435
+ })
1436
+ append_runtime_event(state, "heartbeat", current)
1437
+ save_runtime(state)
1438
+ return state, True
1439
+
1440
+ def print_runtime(summary: dict) -> None:
1441
+ labels = {
1442
+ "idle": "未运行", "running": "运行中", "paused": "已暂停",
1443
+ "completed": "已完成", "aborted": "已中止", "stalled": "疑似卡住",
1444
+ }
1445
+ status_text = labels.get(summary["health"], summary["health"])
1446
+ print(f"运行计时: {status_text}")
1447
+ if summary.get("run_id"):
1448
+ print(f" Run ID: {summary['run_id']}")
1449
+ if summary["active"]:
1450
+ print(f" 开始时间: {summary['started_at']}")
1451
+ print(f" 当前耗时: {format_duration(summary['current_elapsed_seconds'])}")
1452
+ if summary.get("heartbeat_at"):
1453
+ print(f" 最近心跳: {summary['heartbeat_at']}")
1454
+ if summary["stalled"]:
1455
+ print(f" ⚠ 超过 {summary['heartbeat_timeout_seconds']} 秒没有心跳")
1456
+ print(f" 累计耗时: {format_duration(summary['effective_total_seconds'])}")
1457
+ print(f" 完成会话: {summary['sessions_completed']}")
1458
+ print(f" 中止会话: {summary['sessions_aborted']}")
1459
+ policy = summary.get("polling_policy")
1460
+ print(f" Round 续轮策略: {policy or '待询问(启动前必须确认)'}")
1461
+ print(f" 提交策略: {summary.get('commit_policy') or '待询问(log-only 自动不适用)'}")
1462
+ if summary.get("commit_status"):
1463
+ print(f" 最近提交: {summary['commit_status']}"
1464
+ + (f"({summary.get('commit_ref')})" if summary.get("commit_ref") else ""))
1465
+ review_mode = summary.get("review_mode")
1466
+ print(
1467
+ " 审查方式: "
1468
+ f"{review_mode or '待询问(手动 / MCP 自动 / 下次再说)'}"
1469
+ + ("(本轮手动,下次重问)"
1470
+ if summary.get("review_mode_deferred") else "")
1471
+ )
1472
+ if summary.get("lifecycle_no"):
1473
+ lifecycle_state = "已完成" if summary.get("lifecycle_terminal") else "进行中"
1474
+ print(
1475
+ f" Round: #{summary['lifecycle_no']} {lifecycle_state};"
1476
+ f"Life {summary.get('lifecycle_cycles_completed', 0)} 个;"
1477
+ f"累计有效 Bug {summary.get('lifecycle_credited_total', 0)} 条;"
1478
+ f"连续无有效进展 {summary.get('lifecycle_no_progress_cycles', 0)}"
1479
+ f"/{LIFECYCLE_MAX_NO_PROGRESS_CYCLES} 次"
1480
+ )
1481
+ if summary.get("lifecycle_stop_reason"):
1482
+ print(f" Round 停止原因: {summary['lifecycle_stop_reason']}")
1483
+ if summary.get("lifecycle_last_report"):
1484
+ print(f" Round 报告: {summary['lifecycle_last_report']}")
1485
+ if summary.get("polling_stop_reason"):
1486
+ print(f" 轮询终止原因: {summary['polling_stop_reason']}")
1487
+ if summary.get("startup_result") or summary.get("startup_observation") or summary.get("startup_intent"):
1488
+ res = summary.get("startup_result") or "未记录"
1489
+ obs = summary.get("startup_observation") or "未记录"
1490
+ intent = summary.get("startup_intent") or "未记录"
1491
+ print(f" 启动判定: 结果={res} 观察={obs} 意图={intent}")
1492
+ if summary.get("current_round") is not None:
1493
+ print(f" 当前轮次: {summary['current_round']}")
1494
+
1495
+ _BASELINE_JSON_CACHE: dict[tuple[str, int, int], object] = {}
1496
+ _BASELINE_JSON_CACHE_LIMIT = 32
1497
+
1498
+
1499
+ def _clear_baseline_json_cache() -> None:
1500
+ """清空 ``baseline_json()`` 的 stat 记忆化缓存(测试或显式失效时使用)。"""
1501
+ _BASELINE_JSON_CACHE.clear()
1502
+
1503
+
1504
+ def baseline_json() -> dict | None:
1505
+ """读取当前 life 状态作为外部基线(供 pre 输出,防漏洞 2)。
1506
+
1507
+ PERF-05:``pre()`` 内本函数被调用多次,每次都会 ``bugx_paths.require``
1508
+ 再读取并解析 ``life.json``。按 ``(路径, st_mtime_ns, st_size)`` 记忆化:
1509
+ 任何写盘(``run_verify_life("snapshot")`` / ``repair`` / 新 Session)都会改变
1510
+ mtime 或 size,使缓存**自然失效**,因此写操作之后绝不会返回陈旧基线。
1511
+ 返回浅拷贝,避免调用方原地修改污染缓存。
1512
+ """
1513
+ if uses_project_layout():
1514
+ try:
1515
+ life = bugx_paths.require(resolve_project_root()).life
1516
+ except (OSError, ValueError, RuntimeError):
1517
+ return None
1518
+ else:
1519
+ # 外部基线 → life 的真实位置与 ``_path_values_for_root`` **同源**。
1520
+ # 旧实现写 ``AGENT_DIR / "bugx-life.json"``:``AGENT_DIR`` 是**可执行
1521
+ # 引擎目录**,而 pre 写入的寿命状态在项目根,于是独立运行
1522
+ # (``python core/launch_bugx.py pre``)读到空基线 ⇒
1523
+ # ``runtime life_no`` 为 None ⇒ 串行授权身份校验 fail-closed,
1524
+ # 而进程内车道(绑定了完整路径表)却通过——两条车道再次分叉。
1525
+ life = Path(LIFE_FILE)
1526
+ try:
1527
+ stat = life.stat()
1528
+ except OSError:
1529
+ return None
1530
+ key = (str(life), stat.st_mtime_ns, stat.st_size)
1531
+ if key in _BASELINE_JSON_CACHE:
1532
+ cached = _BASELINE_JSON_CACHE[key]
1533
+ return dict(cached) if isinstance(cached, dict) else cached # type: ignore[return-value]
1534
+ if not life.is_file():
1535
+ return None
1536
+ try:
1537
+ payload = json.loads(life.read_text(encoding="utf-8"))
1538
+ except (json.JSONDecodeError, OSError):
1539
+ return None
1540
+ if payload is None:
1541
+ return None
1542
+ if len(_BASELINE_JSON_CACHE) >= _BASELINE_JSON_CACHE_LIMIT:
1543
+ _BASELINE_JSON_CACHE.clear()
1544
+ _BASELINE_JSON_CACHE[key] = payload
1545
+ return dict(payload) if isinstance(payload, dict) else payload # type: ignore[return-value]
1546
+
1547
+ def set_polling_policy(policy: str) -> tuple[dict, bool]:
1548
+ if policy not in POLLING_POLICIES:
1549
+ raise ValueError(f"轮询策略必须是 auto 或 manual,收到: {policy}")
1550
+ with runtime_lock():
1551
+ state = load_runtime()
1552
+ changed = state.get("polling_policy") != policy
1553
+ state["polling_policy"] = policy
1554
+ if changed:
1555
+ append_runtime_event(state, "polling-policy", time.time(), policy)
1556
+ save_runtime(state)
1557
+ return state, changed
1558
+
1559
+ def set_review_mode(mode: str, deferred: bool = False) -> tuple[dict, bool]:
1560
+ """持久化审查执行面;deferred 表示本轮手动、下次启动重新询问。"""
1561
+ if mode not in REVIEW_MODES:
1562
+ raise ValueError(f"审查方式必须是 manual 或 mcp-auto,收到: {mode}")
1563
+ with runtime_lock():
1564
+ state = load_runtime()
1565
+ changed = (
1566
+ state.get("review_mode") != mode
1567
+ or state.get("review_mode_deferred", False) != deferred
1568
+ )
1569
+ state["review_mode"] = mode
1570
+ state["review_mode_deferred"] = deferred
1571
+ if changed:
1572
+ detail = f"{mode};next_start={'ask' if deferred else 'reuse'}"
1573
+ append_runtime_event(state, "review-mode", time.time(), detail)
1574
+ save_runtime(state)
1575
+ return state, changed
1576
+
1577
+ def _record_startup_action(action: str) -> tuple[dict, bool]:
1578
+ """Persist the explicit stale-MCP startup decision and its audit event."""
1579
+ if action != "start":
1580
+ raise ValueError(f"启动动作只能记录 start,收到: {action}")
1581
+ with runtime_lock():
1582
+ state = load_runtime()
1583
+ changed = state.get("startup_action") != action
1584
+ state["startup_action"] = action
1585
+ # ``start`` is a one-session manual fallback, not a lasting review
1586
+ # preference. Keep both facts in one atomic runtime update.
1587
+ state["review_mode"] = "manual"
1588
+ state["review_mode_deferred"] = True
1589
+ if changed:
1590
+ append_runtime_event(state, "startup-action", time.time(), action)
1591
+ save_runtime(state)
1592
+ return state, changed
1593
+
1594
+ def set_commit_policy(policy: str) -> tuple[dict, bool]:
1595
+ """持久化当前 Session 的提交边界;不把手动提交当作异常。"""
1596
+ if policy not in COMMIT_POLICIES:
1597
+ raise ValueError("提交策略必须是 life、round、manual 或 not_applicable")
1598
+ with runtime_lock():
1599
+ state = load_runtime()
1600
+ changed = state.get("commit_policy") != policy
1601
+ state["commit_policy"] = policy
1602
+ if changed:
1603
+ append_runtime_event(state, "commit-policy", time.time(), policy)
1604
+ save_runtime(state)
1605
+ return state, changed
1606
+
1607
+ def set_polling_stop(reason: str) -> dict:
1608
+ """持久化停止原因,同时落 ``polling_stop_reason`` 与 ``lifecycle_stop_reason``。
1609
+
1610
+ 两个键描述的是同一个事实(轮询/生命周期为何停止)。历史上只有
1611
+ post_phase 的 ``--final`` 分支写后者,而自治链路被宿主明令禁用
1612
+ ``--final``,于是 ``lifecycle_stop_reason`` 永远是 None,
1613
+ ``supervisor_host._autonomous_stop_reason`` 永远读不到
1614
+ ``coverage_target_completed``,成功收敛被误报成 blocked / exit 1。
1615
+ 在唯一写入口一次落两个键,同类断链不再复现。
1616
+ """
1617
+ with runtime_lock():
1618
+ state = load_runtime()
1619
+ state["polling_stop_reason"] = reason
1620
+ state["lifecycle_stop_reason"] = reason
1621
+ append_runtime_event(state, "polling-stopped", time.time(), reason)
1622
+ save_runtime(state)
1623
+ return state