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,1286 @@
1
+ #!/usr/bin/env python3
2
+ """launch_phases/pre_state_builder.py - 选项归一化、预算门禁、会话状态准备与凭据授权。"""
3
+
4
+ from __future__ import annotations
5
+
6
+ import collections
7
+ import dataclasses
8
+ from dataclasses import dataclass, field
9
+ import hashlib
10
+ import json
11
+ import math
12
+ import os
13
+ import re
14
+ import sys
15
+ import time
16
+ from pathlib import Path
17
+ from typing import Any, Mapping
18
+
19
+ try:
20
+ import core.i18n as i18n
21
+ except ImportError:
22
+ try:
23
+ from core import i18n
24
+ except ImportError:
25
+ i18n = None # type: ignore[assignment]
26
+
27
+ from core.launch_phases.common import (
28
+ FIX_MODES,
29
+ resolve_project_root,
30
+ uses_project_layout,
31
+ child_environment,
32
+ run_child,
33
+ POLLING_DECISION_REQUIRED,
34
+ REVIEW_DECISION_LATER,
35
+ REPORT_POLICY_DEFAULT,
36
+ STRATEGY_PLAN_ACTIONS,
37
+ COMMIT_POLICIES,
38
+ REVIEW_MODES,
39
+ STARTUP_INTERACTION_CHOICES,
40
+ STARTUP_INTERACTION_MODES,
41
+ host_serial_worker,
42
+ run_verify_life,
43
+ bugx_paths,
44
+ )
45
+ from core.launch_phases.session_runtime import (
46
+ set_review_mode,
47
+ set_polling_policy,
48
+ set_commit_policy,
49
+ load_runtime,
50
+ save_runtime,
51
+ iso_time,
52
+ runtime_lock,
53
+ start_runtime,
54
+ refresh_runtime_paths,
55
+ )
56
+ from core.launch_phases.supervisor_bridge import (
57
+ run_tools_kb,
58
+ degraded_gate,
59
+ supervisor_mcp_gate,
60
+ auto_provision_accelerators,
61
+ autonomous_degraded_choices,
62
+ report_degraded_probes,
63
+ run_preflight_probes,
64
+ )
65
+ from core.launch_phases.report_sharing import normalize_report_policy
66
+ from core.launch_phases.startup_gates import (
67
+ compile_strategy_plan as _orig_compile_strategy_plan,
68
+ strategy_plan_gate as _orig_strategy_plan_gate,
69
+ report_policy_startup_gate as _orig_report_policy_startup_gate,
70
+ aborted_session_gate,
71
+ check_global_budget_gate,
72
+ check_stage_prompts_integrity,
73
+ coverage_startup_gate,
74
+ mark_strategy_customized,
75
+ refresh_startup_todo,
76
+ )
77
+
78
+ #: 运行态 ``report_policy_source`` 的「用户已决策」取值集合。
79
+ #: 命中即表示交互三选一门禁已有答案,不再重复询问;``default`` /
80
+ #: ``autonomous`` 是系统兜底,不算用户决策。
81
+ _REPORT_POLICY_DECIDED_SOURCES = frozenset({"cli", "profile", "config", "gate"})
82
+
83
+ def compile_strategy_plan(*args, **kwargs):
84
+ pp = _pp()
85
+ if pp and hasattr(pp, "compile_strategy_plan"):
86
+ fn = getattr(pp, "compile_strategy_plan")
87
+ if fn is not compile_strategy_plan:
88
+ return fn(*args, **kwargs)
89
+ return _orig_compile_strategy_plan(*args, **kwargs)
90
+
91
+ def strategy_plan_gate(*args, **kwargs):
92
+ pp = _pp()
93
+ if pp and hasattr(pp, "strategy_plan_gate"):
94
+ fn = getattr(pp, "strategy_plan_gate")
95
+ if fn is not strategy_plan_gate:
96
+ return fn(*args, **kwargs)
97
+ return _orig_strategy_plan_gate(*args, **kwargs)
98
+
99
+ def report_policy_startup_gate(*args, **kwargs):
100
+ pp = _pp()
101
+ if pp and hasattr(pp, "report_policy_startup_gate"):
102
+ fn = getattr(pp, "report_policy_startup_gate")
103
+ if fn is not report_policy_startup_gate:
104
+ return fn(*args, **kwargs)
105
+ return _orig_report_policy_startup_gate(*args, **kwargs)
106
+
107
+ def startup_policy_explicit_keys(*args, **kwargs):
108
+ pp = _pp()
109
+ if pp and hasattr(pp, "startup_policy_explicit_keys"):
110
+ fn = getattr(pp, "startup_policy_explicit_keys")
111
+ if fn is not startup_policy_explicit_keys:
112
+ return fn(*args, **kwargs)
113
+ return frozenset()
114
+
115
+
116
+ def baseline_json(*args, **kwargs):
117
+ pp = _pp()
118
+ if pp and hasattr(pp, "baseline_json"):
119
+ fn = getattr(pp, "baseline_json")
120
+ if fn is not baseline_json:
121
+ return fn(*args, **kwargs)
122
+ from core.launch_phases.session_runtime import baseline_json as real
123
+ return real(*args, **kwargs)
124
+
125
+ def _startup_policy_config(*args, **kwargs):
126
+ pp = _pp()
127
+ if pp and hasattr(pp, "_startup_policy_config"):
128
+ fn = getattr(pp, "_startup_policy_config")
129
+ if fn is not _startup_policy_config:
130
+ return fn(*args, **kwargs)
131
+ raise RuntimeError("pre_phase._startup_policy_config not available")
132
+
133
+ def resolve_project_root(*args, **kwargs):
134
+ pp = _pp()
135
+ if pp and hasattr(pp, "resolve_project_root"):
136
+ fn = getattr(pp, "resolve_project_root")
137
+ if fn is not resolve_project_root:
138
+ return fn(*args, **kwargs)
139
+ from core.launch_phases.common import resolve_project_root as real
140
+ return real(*args, **kwargs)
141
+
142
+ def load_runtime(*args, **kwargs):
143
+ pp = _pp()
144
+ if pp and hasattr(pp, "load_runtime"):
145
+ fn = getattr(pp, "load_runtime")
146
+ if fn is not load_runtime:
147
+ return fn(*args, **kwargs)
148
+ from core.launch_phases.session_runtime import load_runtime as real
149
+ return real(*args, **kwargs)
150
+
151
+ def save_runtime(*args, **kwargs):
152
+ pp = _pp()
153
+ if pp and hasattr(pp, "save_runtime"):
154
+ fn = getattr(pp, "save_runtime")
155
+ if fn is not save_runtime:
156
+ return fn(*args, **kwargs)
157
+ from core.launch_phases.session_runtime import save_runtime as real
158
+ return real(*args, **kwargs)
159
+
160
+
161
+ def detect_startup_environment(*args, **kwargs):
162
+ pp = _pp()
163
+ if pp and hasattr(pp, "detect_startup_environment"):
164
+ fn = getattr(pp, "detect_startup_environment")
165
+ if fn is not detect_startup_environment:
166
+ return fn(*args, **kwargs)
167
+ try:
168
+ from core.launch_phases.startup_gates import detect_startup_environment as real
169
+ return real(*args, **kwargs)
170
+ except Exception:
171
+ return "terminal"
172
+
173
+ def run_tools_kb(*args, **kwargs):
174
+ pp = _pp()
175
+ if pp and hasattr(pp, "run_tools_kb"):
176
+ fn = getattr(pp, "run_tools_kb")
177
+ if fn is not run_tools_kb:
178
+ return fn(*args, **kwargs)
179
+ from core.launch_phases.supervisor_bridge import run_tools_kb as real
180
+ return real(*args, **kwargs)
181
+
182
+ def run_preflight_probes(*args, **kwargs):
183
+ pp = _pp()
184
+ if pp and hasattr(pp, "run_preflight_probes"):
185
+ fn = getattr(pp, "run_preflight_probes")
186
+ if fn is not run_preflight_probes:
187
+ return fn(*args, **kwargs)
188
+ from core.launch_phases.supervisor_bridge import run_preflight_probes as real
189
+ return real(*args, **kwargs)
190
+
191
+ def report_degraded_probes(*args, **kwargs):
192
+ pp = _pp()
193
+ if pp and hasattr(pp, "report_degraded_probes"):
194
+ fn = getattr(pp, "report_degraded_probes")
195
+ if fn is not report_degraded_probes:
196
+ return fn(*args, **kwargs)
197
+ from core.launch_phases.supervisor_bridge import report_degraded_probes as real
198
+ return real(*args, **kwargs)
199
+
200
+ def auto_provision_accelerators(*args, **kwargs):
201
+ pp = _pp()
202
+ if pp and hasattr(pp, "auto_provision_accelerators"):
203
+ fn = getattr(pp, "auto_provision_accelerators")
204
+ if fn is not auto_provision_accelerators:
205
+ return fn(*args, **kwargs)
206
+ from core.launch_phases.supervisor_bridge import auto_provision_accelerators as real
207
+ return real(*args, **kwargs)
208
+
209
+ def degraded_gate(*args, **kwargs):
210
+ pp = _pp()
211
+ if pp and hasattr(pp, "degraded_gate"):
212
+ fn = getattr(pp, "degraded_gate")
213
+ if fn is not degraded_gate:
214
+ return fn(*args, **kwargs)
215
+ from core.launch_phases.supervisor_bridge import degraded_gate as real
216
+ return real(*args, **kwargs)
217
+
218
+ def run_verify_life(*args, **kwargs):
219
+ pp = _pp()
220
+ if pp and hasattr(pp, "run_verify_life"):
221
+ fn = getattr(pp, "run_verify_life")
222
+ if fn is not run_verify_life:
223
+ return fn(*args, **kwargs)
224
+ from core.launch_phases.common import run_verify_life as real
225
+ return real(*args, **kwargs)
226
+
227
+ def refresh_startup_todo(*args, **kwargs):
228
+ pp = _pp()
229
+ if pp and hasattr(pp, "refresh_startup_todo"):
230
+ fn = getattr(pp, "refresh_startup_todo")
231
+ if fn is not refresh_startup_todo:
232
+ return fn(*args, **kwargs)
233
+ from core.launch_phases.startup_gates import refresh_startup_todo as real
234
+ return real(*args, **kwargs)
235
+
236
+ def uses_project_layout(*args, **kwargs):
237
+ pp = _pp()
238
+ if pp and hasattr(pp, "uses_project_layout"):
239
+ fn = getattr(pp, "uses_project_layout")
240
+ if fn is not uses_project_layout:
241
+ return fn(*args, **kwargs)
242
+ from core.launch_phases.common import uses_project_layout as real
243
+ return real(*args, **kwargs)
244
+
245
+ def _pp():
246
+ return sys.modules.get("core.launch_phases.pre_phase") or sys.modules.get("launch_phases.pre_phase")
247
+
248
+ def _get_pp_attr(name: str, fallback=None):
249
+ pp = _pp()
250
+ if pp and hasattr(pp, name):
251
+ return getattr(pp, name)
252
+ return fallback
253
+
254
+ def begin_new_session(
255
+ bootstrap_coverage: bool = False, *, autonomous: bool = False,
256
+ ) -> tuple[dict, bool, int | None]:
257
+ """在已完成 Session 后创建新的 Session/首个 Round。
258
+
259
+ 新 Session 的覆盖清单门禁必须先于运行态创建。清单缺失时可以让新
260
+ Session 停留在 ``created``/待引导状态,但不能先写入 running runtime
261
+ 再把它错误收尾为 ``aborted``。返回值中的第三项用于把结构化门禁码
262
+ 交回 ``pre``,避免把“等待用户选择”误报成创建失败。
263
+ """
264
+ if not uses_project_layout() or bugx_paths is None:
265
+ runtime, started = start_runtime(new_lifecycle=True, new_session=True)
266
+ return runtime, started, None
267
+ previous = load_runtime()
268
+ previous_mode = (baseline_json() or {}).get("mode")
269
+ inherited = {
270
+ key: previous.get(key)
271
+ for key in (
272
+ "polling_policy", "review_mode", "review_mode_deferred",
273
+ "commit_policy", "report_policy", "sync_status",
274
+ )
275
+ }
276
+ try:
277
+ bugx_paths.create_session(resolve_project_root())
278
+ refresh_runtime_paths()
279
+ # create_session() has switched current.json to the new lifecycle, but
280
+ # no runtime has been created yet. Check the new lifecycle's coverage
281
+ # gate at this safe boundary BEFORE resetting the life ledger: a
282
+ # blocked/missing manifest must not consume the reset or clear the
283
+ # previous runnable state, and a fresh Session must not be turned
284
+ # into an aborted run by a missing manifest.
285
+ coverage_gate = coverage_startup_gate(
286
+ bootstrap_confirmed=bootstrap_coverage, autonomous=autonomous,
287
+ )
288
+ if coverage_gate != 0:
289
+ return load_runtime(), False, coverage_gate
290
+ if run_verify_life("reset", "--confirm-reset") != 0:
291
+ return load_runtime(), False, 1
292
+ if previous_mode in {"auto", "log-only"}:
293
+ if run_verify_life("set-mode", "--mode", previous_mode) != 0:
294
+ return load_runtime(), False, 1
295
+ # create_session() has already switched current.json to the new
296
+ # polling. Explicitly pass new_session so runtime identity, reports,
297
+ # and lifecycle history cannot accidentally remain attached to the
298
+ # completed/aborted Session from the previous startup.
299
+ runtime, started = start_runtime(new_lifecycle=True, new_session=True)
300
+ if started:
301
+ runtime.update({key: value for key, value in inherited.items() if value is not None})
302
+ runtime["startup_observation"] = "completed"
303
+ runtime["startup_intent"] = "new_session"
304
+ save_runtime(runtime)
305
+ return runtime, started, None
306
+ except (OSError, ValueError, RuntimeError) as exc:
307
+ print(f"[launch_bugx] ✗ 新 Session 创建失败: {exc}")
308
+ return previous, False, 1
309
+
310
+
311
+ class RuntimeMemo:
312
+ """PERF-05:``pre()`` 内单一 runtime 快照,仅在已知写操作后显式刷新。
313
+
314
+ 未刷新时返回同一对象,因此不会在写操作之后继续使用陈旧数据;
315
+ 拆分为步骤函数后以显式对象传递,保持与原闭包完全一致的语义。
316
+ """
317
+
318
+ __slots__ = ("_state",)
319
+
320
+ def __init__(self) -> None:
321
+ self._state: dict | None = None
322
+
323
+ def get(self, *, refresh: bool = False) -> dict:
324
+ """返回当前快照;``refresh=True`` 时强制重新读盘。"""
325
+ if refresh or self._state is None:
326
+ self._state = load_runtime()
327
+ return self._state
328
+
329
+ def seed(self, state: dict) -> None:
330
+ """在已知写操作之后接管新快照(等价于原 ``runtime_state = runtime``)。"""
331
+ self._state = state
332
+
333
+
334
+ @dataclass
335
+ class PreState:
336
+ """``pre()`` 门禁序列在步骤函数之间流转的可变状态载体。
337
+
338
+ 原先 600+ 行函数体里的启动决策变量集中到此对象,使每个门禁块
339
+ 可以独立成函数而不必以 8+ 个位置参数互相传递。字段语义与原始
340
+ 局部变量逐字对应,赋值顺序不变。
341
+ """
342
+
343
+ # 命令行显式参数(归一化后的值)
344
+ host: str | None = None
345
+ polling_policy: str | None = None
346
+ review_mode: str | None = None
347
+ review_mode_deferred: bool = False
348
+ fix_mode: str | None = None
349
+ commit_policy: str | None = None
350
+ session_recovery: str | None = None
351
+ startup_action: str | None = None
352
+ report_policy: str | None = None
353
+ # report_policy 的取值来源(cli/profile/config/gate/autonomous/default),
354
+ # 持久化为 runtime["report_policy_source"],用于判定三选一门禁是否已作答。
355
+ report_policy_source: str = "default"
356
+ # ``--replay-share-pending``:显式授权在 report_policy=local 下重放队列。
357
+ replay_share_pending_force: bool = False
358
+ strategy_plan: str | None = None
359
+ life_kind: str = "mine"
360
+ startup_interaction: str | None = None
361
+ profile: str | None = None
362
+ ignore_global_budget: bool = False
363
+ refresh_probes: bool = False
364
+ autonomous_mode: bool = False
365
+ max_round_wall_seconds: str | float | None = None
366
+ autonomous_policy: dict[str, Any] | None = None
367
+ tooling_choices: dict[str, str] | None = None
368
+ lesson_query: str = ""
369
+ lesson_category: str | None = None
370
+ allow_serial: bool = False
371
+ serial_reason: str | None = None
372
+ bootstrap_coverage: bool = False
373
+ # 派生标志
374
+ noninteractive_startup: bool = False
375
+ # 运行态现值
376
+ current_runtime: dict = field(default_factory=dict)
377
+ current_review_mode: str | None = None
378
+ current_review_deferred: bool = False
379
+ current_policy: str | None = None
380
+ current_fix_mode: str | None = None
381
+ current_commit_policy: str | None = None
382
+ life_state: dict = field(default_factory=dict)
383
+ aborted_new_session: bool = False
384
+ # 会话启动与就绪输出
385
+ new_session_started: bool = False
386
+ runtime: dict = field(default_factory=dict)
387
+ started: bool = False
388
+ supervisor_state: dict = field(default_factory=dict)
389
+ lesson_context: dict = field(default_factory=dict)
390
+ project_profile_prepared: bool = False
391
+ project_profile_data: dict[str, Any] | None = None
392
+
393
+
394
+ def normalize_pre_options(st: "_PreState") -> int:
395
+ """参数校验与归一化:profile 回填 + 逐项合法性门禁。
396
+
397
+ 原 ``pre()`` 393-474 逐字迁移;仅把原先的函数局部变量换成
398
+ ``_PreState`` 字段,校验顺序、错误文案与退出码完全不变。"""
399
+ profile = st.profile
400
+ polling_policy = st.polling_policy
401
+ review_mode = st.review_mode
402
+ fix_mode = st.fix_mode
403
+ commit_policy = st.commit_policy
404
+ session_recovery = st.session_recovery
405
+ startup_action = st.startup_action
406
+ report_policy = st.report_policy
407
+ strategy_plan = st.strategy_plan
408
+ life_kind = st.life_kind
409
+ startup_interaction = st.startup_interaction
410
+ review_mode_deferred = st.review_mode_deferred
411
+ cli_policy = {
412
+ "polling_policy": st.polling_policy,
413
+ "review_mode": st.review_mode,
414
+ "fix_mode": st.fix_mode,
415
+ "commit_policy": st.commit_policy,
416
+ "session_recovery": st.session_recovery,
417
+ "startup_action": st.startup_action,
418
+ "report_policy": st.report_policy,
419
+ }
420
+ profile_cfg = {}
421
+ if st.max_round_wall_seconds is not None:
422
+ try:
423
+ st.max_round_wall_seconds = float(st.max_round_wall_seconds)
424
+ except (TypeError, ValueError):
425
+ st.max_round_wall_seconds = None
426
+ if (st.max_round_wall_seconds is None
427
+ or not math.isfinite(st.max_round_wall_seconds)
428
+ or st.max_round_wall_seconds <= 0):
429
+ print("[launch_bugx] ✗ --max-round-wall-seconds 必须是正的有限秒数")
430
+ return 2
431
+ try:
432
+ from core.runtime import session_profile
433
+ except Exception:
434
+ if st.autonomous_mode:
435
+ print("[launch_bugx] ✗ 自治策略无效,拒绝猜测默认值")
436
+ return 2
437
+ profile_cfg = {}
438
+ else:
439
+ try:
440
+ profile_cfg = session_profile.load_profile(profile, root=resolve_project_root()) or {}
441
+ if st.autonomous_mode:
442
+ # Explicit CLI opt-in uses the audited preset, while a project
443
+ # profile may override only already-defined scalar fields.
444
+ preset = session_profile.load_profile("autonomous", root=resolve_project_root()) or {}
445
+ preset.update(profile_cfg)
446
+ profile_cfg = preset
447
+ st.autonomous_policy = session_profile.autonomous_policy(profile_cfg)
448
+ except session_profile.LegacySharePolicyError as exc:
449
+ print(f"[launch_bugx] ✗ 已移除的启动配置:{exc}")
450
+ return 2
451
+ except Exception:
452
+ if st.autonomous_mode:
453
+ print("[launch_bugx] ✗ 自治策略无效,拒绝猜测默认值")
454
+ return 2
455
+ profile_cfg = {}
456
+
457
+ if st.autonomous_policy is not None:
458
+ st.autonomous_mode = True
459
+
460
+ if profile_cfg:
461
+ if polling_policy is None and profile_cfg.get("polling_policy"):
462
+ polling_policy = profile_cfg["polling_policy"]
463
+ if review_mode is None and profile_cfg.get("review_mode"):
464
+ review_mode = profile_cfg["review_mode"]
465
+ if fix_mode is None and profile_cfg.get("fix_mode"):
466
+ fix_mode = profile_cfg["fix_mode"]
467
+ if commit_policy is None and profile_cfg.get("commit_policy"):
468
+ commit_policy = profile_cfg["commit_policy"]
469
+ if session_recovery is None and profile_cfg.get("session_recovery"):
470
+ session_recovery = profile_cfg["session_recovery"]
471
+ if startup_action is None and profile_cfg.get("startup_action"):
472
+ startup_action = profile_cfg["startup_action"]
473
+ if report_policy is None and profile_cfg.get("report_policy"):
474
+ report_policy = profile_cfg["report_policy"]
475
+ if st.autonomous_mode:
476
+ # In autonomous mode every strategy gate has a deterministic value;
477
+ # explicit CLI values remain honored, but no missing value reaches an
478
+ # interactive resolver.
479
+ autonomous_defaults = {
480
+ "polling_policy": "auto",
481
+ "review_mode": "mcp-auto",
482
+ "fix_mode": "auto",
483
+ "commit_policy": "round",
484
+ "session_recovery": "resume",
485
+ "startup_action": "start",
486
+ # DOC-236 C6:无人值守默认只保留本地报告(不对外提交)。
487
+ "report_policy": "local",
488
+ "strategy_plan": "approve",
489
+ }
490
+ polling_policy = polling_policy or autonomous_defaults["polling_policy"]
491
+ review_mode = review_mode or autonomous_defaults["review_mode"]
492
+ fix_mode = fix_mode or autonomous_defaults["fix_mode"]
493
+ commit_policy = commit_policy or autonomous_defaults["commit_policy"]
494
+ session_recovery = session_recovery or autonomous_defaults["session_recovery"]
495
+ startup_action = startup_action or autonomous_defaults["startup_action"]
496
+ report_policy = report_policy or autonomous_defaults["report_policy"]
497
+ strategy_plan = strategy_plan or autonomous_defaults["strategy_plan"]
498
+ st.bootstrap_coverage = bool(
499
+ (st.autonomous_policy or {}).get("coverage_bootstrap", True)
500
+ )
501
+
502
+ try:
503
+ layered = _startup_policy_config(resolve_project_root(), cli_policy)
504
+ except (OSError, UnicodeError, ValueError) as exc:
505
+ print(f"[launch_bugx] ✗ 启动报告提交策略配置无效:{exc}")
506
+ return 2
507
+ for key in cli_policy:
508
+ if cli_policy[key] is not None:
509
+ continue
510
+ profile_value = profile_cfg.get(key) if profile is not None else None
511
+ value = profile_value if isinstance(profile_value, str) else layered.get(key)
512
+ if key == "polling_policy":
513
+ polling_policy = value
514
+ elif key == "review_mode":
515
+ review_mode = value
516
+ elif key == "fix_mode":
517
+ fix_mode = value
518
+ elif key == "commit_policy":
519
+ commit_policy = value
520
+ elif key == "session_recovery":
521
+ session_recovery = value
522
+ elif key == "startup_action":
523
+ startup_action = value
524
+
525
+ # report_policy has an explicit source precedence that must not be
526
+ # accidentally changed by the generic startup-policy loop:
527
+ # CLI > selected/active profile > user/project config > safe default.
528
+ if st.report_policy is not None:
529
+ report_policy = st.report_policy
530
+ else:
531
+ profile_report_policy = profile_cfg.get("report_policy")
532
+ if isinstance(profile_report_policy, str) and profile_report_policy.strip():
533
+ report_policy = profile_report_policy
534
+ else:
535
+ report_policy = layered.get("report_policy", REPORT_POLICY_DEFAULT)
536
+
537
+ environment = detect_startup_environment()
538
+ terminal_interactive = bool(
539
+ environment is not None
540
+ and getattr(environment, "stdin_tty", False)
541
+ and getattr(environment, "stdout_tty", False)
542
+ )
543
+ # 无 TTY 不再单独触发非交互启动:探针已识别 native-question 宿主时,
544
+ # 策略门禁应经 BUGX_INTERACTION_REQUEST 交给宿主单选(与 git/云端门禁
545
+ # 同一通道),而不是把推荐预设静默当作用户批准。真正的 headless/ACP/
546
+ # blocked 交互面仍走自动只读路径(下方 interface/interaction 白名单判定)。
547
+ noninteractive_startup = st.autonomous_mode or environment is None or (
548
+ not terminal_interactive
549
+ and getattr(environment, "interaction", None)
550
+ not in {"native-question", "tty-radio", "text-menu"}
551
+ )
552
+ if noninteractive_startup:
553
+ # Headless/ACP launchers cannot answer a strategy questionnaire. Keep
554
+ # the automatic path read-only unless explicitly requested via CLI with approve.
555
+ if st.strategy_plan != "approve":
556
+ fix_mode = "log-only"
557
+ commit_policy = "manual"
558
+ strategy_plan = "approve"
559
+ else:
560
+ if fix_mode is None:
561
+ fix_mode = "log-only"
562
+ if commit_policy is None:
563
+ commit_policy = "manual"
564
+ if strategy_plan is None:
565
+ strategy_plan = "approve"
566
+ st.noninteractive_startup = noninteractive_startup
567
+ if startup_interaction is not None:
568
+ action_val = startup_interaction.strip().lower()
569
+ # 两套值域曾经被错误合并,导致 ``--startup-interaction auto``(help 里
570
+ # 白纸黑字声明的合法值)被判非法并返回 2,非交互启动直接失败:
571
+ # * ``auto|prompt``——本 flag 的原生语义:声明调用方如何应对启动门禁,
572
+ # 它不是「对某个门禁的作答」,因此只影响是否走自动决策,见下方
573
+ # ``noninteractive_startup`` 的推导,不在这里短路退出。
574
+ # * ``restart_host|run_tty|later``——MCP 门禁的**作答**,才需要短路。
575
+ if action_val in STARTUP_INTERACTION_MODES:
576
+ pass
577
+ elif action_val in STARTUP_INTERACTION_CHOICES or action_val in {"1", "2", "3"}:
578
+ if action_val in {"later", "3"}:
579
+ print("[launch_bugx] 已选择下次再说,本轮启动停止。")
580
+ return POLLING_DECISION_REQUIRED
581
+ elif action_val in {"restart_host", "1"}:
582
+ print("[launch_bugx] 已选择重启宿主,请重启当前宿主会话后重试。")
583
+ return POLLING_DECISION_REQUIRED
584
+ elif action_val in {"run_tty", "2"}:
585
+ print("[launch_bugx] 已选择在真实 TTY 中运行,请在外部终端中执行启动命令。")
586
+ return POLLING_DECISION_REQUIRED
587
+ else:
588
+ valid = "、".join(sorted(STARTUP_INTERACTION_MODES | STARTUP_INTERACTION_CHOICES))
589
+ print(f"[launch_bugx] ✗ 交互方式选择无效:只能是 {valid}")
590
+ return 2
591
+
592
+ # DOC-236 C1:`--review-mode later` 是"本轮不启动"。此时**任何运行态都不得
593
+ # 落盘**——旧实现会先走到下面的 `report_policy` 持久化(`save_runtime`),
594
+ # 于是"下次再说"仍然在磁盘上留下 runtime 状态。故此处前置短路,优先于持久化。
595
+ if review_mode == REVIEW_DECISION_LATER:
596
+ print("[launch_bugx] 已选择下次再说,本轮启动停止。")
597
+ return POLLING_DECISION_REQUIRED
598
+
599
+ # DOC-236 C6 补齐(2026-11-09 复盘 4.3-1):report_policy 此前只有
600
+ # CLI/config 入口,交互态用户被钉死在默认 local,无「不上报/上报云端」
601
+ # 入口。这里先只判定**显式来源**;历史决策回读与三选一门禁必须等到
602
+ # 下方全部参数校验通过之后执行(非法参数不得读 runtime、不得弹请求)。
603
+ report_policy_source = "default"
604
+ if st.report_policy is not None:
605
+ report_policy_source = "cli"
606
+ elif isinstance(profile_cfg.get("report_policy"), str) \
607
+ and profile_cfg["report_policy"].strip():
608
+ report_policy_source = "profile"
609
+ elif "report_policy" in startup_policy_explicit_keys(resolve_project_root()):
610
+ report_policy_source = "config"
611
+ elif st.autonomous_mode:
612
+ report_policy_source = "autonomous"
613
+
614
+ # DOC-236 C6:非法值 fail-closed(不得静默回退默认值);缺省值也必须
615
+ # 在 L1 这里落盘,L5 不再猜测或回退未声明的提交策略。
616
+ try:
617
+ report_val = normalize_report_policy(report_policy)
618
+ except ValueError as exc:
619
+ print(f"[launch_bugx] ✗ 报告提交策略无效:{exc}")
620
+ return 2
621
+ report_val = report_val or REPORT_POLICY_DEFAULT
622
+
623
+ if strategy_plan is not None:
624
+ normalized_strat = strategy_plan.strip().lower()
625
+ if normalized_strat not in STRATEGY_PLAN_ACTIONS and normalized_strat not in {"1", "2", "3"}:
626
+ print("[launch_bugx] ✗ 作战方案策略无效:只能是 approve、customize 或 later")
627
+ return 2
628
+
629
+ review_mode_deferred = False
630
+ if review_mode is not None and review_mode not in REVIEW_MODES:
631
+ print("[launch_bugx] ✗ 启动前审查方式无效:只能是 manual 或 mcp-auto")
632
+ return 2
633
+ if fix_mode is not None and fix_mode not in FIX_MODES:
634
+ print(
635
+ "[launch_bugx] ✗ 启动前修复方式无效:只能是 "
636
+ + " 或 ".join(FIX_MODES)
637
+ )
638
+ return 2
639
+ if life_kind not in {"mine", "fix"}:
640
+ print("[launch_bugx] ✗ Life 类型无效:只能是 mine 或 fix")
641
+ return 2
642
+ is_serial_host = host_serial_worker(st.host)
643
+ if st.allow_serial and life_kind != "fix" and not is_serial_host:
644
+ print("[launch_bugx] ✗ --allow-serial 仅允许用于 fix Life")
645
+ return 2
646
+ if st.allow_serial and (
647
+ not isinstance(st.serial_reason, str) or not st.serial_reason.strip()
648
+ ):
649
+ print("[launch_bugx] ✗ --allow-serial 必须同时提供非空 --serial-reason")
650
+ return 2
651
+ if commit_policy is not None and commit_policy.strip().lower() in {
652
+ "none", "no-submit", "no_submit", "不提交", "不自动提交",
653
+ }:
654
+ commit_policy = "manual"
655
+ if commit_policy is not None and commit_policy not in COMMIT_POLICIES - {"not_applicable"}:
656
+ print("[launch_bugx] ✗ 启动前提交策略无效:只能是 life、round、none 或 manual")
657
+ return 2
658
+ # 全部参数校验通过后才允许回读历史决策 / 发射三选一门禁。
659
+ if report_policy_source == "default" and not noninteractive_startup:
660
+ try:
661
+ previous_runtime = load_runtime()
662
+ except (OSError, ValueError):
663
+ previous_runtime = {}
664
+ inherited = previous_runtime.get("report_policy")
665
+ if str(previous_runtime.get("report_policy_source") or "") \
666
+ in _REPORT_POLICY_DECIDED_SOURCES \
667
+ and isinstance(inherited, str) and inherited.strip():
668
+ try:
669
+ inherited_val = normalize_report_policy(inherited)
670
+ except ValueError:
671
+ inherited_val = None
672
+ if inherited_val is not None:
673
+ report_policy = inherited_val
674
+ report_policy_source = "gate"
675
+ if report_policy_source == "default":
676
+ gate_code, gate_policy = report_policy_startup_gate(
677
+ environment, autonomous=st.autonomous_mode,
678
+ )
679
+ if gate_code != 0:
680
+ return gate_code
681
+ report_policy = gate_policy
682
+ report_policy_source = "gate"
683
+ report_val = normalize_report_policy(report_policy) or REPORT_POLICY_DEFAULT
684
+ # Validate the complete option set before the first runtime write. An
685
+ # invalid authorization must fail without touching any project lifecycle.
686
+ try:
687
+ with runtime_lock():
688
+ rt = load_runtime()
689
+ rt["report_policy"] = report_val
690
+ rt["report_policy_source"] = report_policy_source
691
+ save_runtime(rt)
692
+ except (OSError, TimeoutError, ValueError, RuntimeError) as exc:
693
+ print(f"[launch_bugx] ✗ 报告提交策略持久化失败:{exc}(硬阻断,拒绝继续启动)")
694
+ return 1
695
+ report_policy = report_val
696
+ st.polling_policy = polling_policy
697
+ st.review_mode = review_mode
698
+ st.fix_mode = fix_mode
699
+ st.commit_policy = commit_policy
700
+ st.session_recovery = session_recovery
701
+ st.startup_action = startup_action
702
+ st.report_policy = report_policy
703
+ st.report_policy_source = report_policy_source
704
+ st.strategy_plan = strategy_plan
705
+ st.life_kind = life_kind
706
+ st.review_mode_deferred = review_mode_deferred
707
+ return 0
708
+
709
+
710
+ def run_preflight_budget_gates(st: "_PreState") -> int:
711
+ """阶段提示词完整性防偷懒门禁 + 全局每日预算熔断门禁。
712
+
713
+ 原 ``pre()`` 476-496 逐字迁移。"""
714
+ ignore_global_budget = st.ignore_global_budget
715
+ # DOC-034 阶段 3:阶段提示词加载完整性防偷懒门禁(缺失立即阻断,不静默继续)
716
+ check_prompts_fn = _get_pp_attr("check_stage_prompts_integrity", check_stage_prompts_integrity)
717
+ prompts_ok, prompts_err = check_prompts_fn()
718
+ if not prompts_ok:
719
+ err = f"[launch_bugx] ✗ 阶段提示词章节缺失/加载失败: {prompts_err}(防偷懒门禁阻断)"
720
+ if i18n is not None:
721
+ err = i18n.exception_text("orchestrator.stage_prompts_failed", fallback=err, error=prompts_err)
722
+ print(err)
723
+ return 1
724
+
725
+ # DOC-049 全局每日预算与配额熔断门禁(超限立即阻断,防止 API 账单穿透)
726
+ check_budget_fn = _get_pp_attr("check_global_budget_gate", check_global_budget_gate)
727
+ budget_ok, budget_err = check_budget_fn(ignore_budget=ignore_global_budget)
728
+ if not budget_ok:
729
+ err = f"[launch_bugx] ✗ 全局预算熔断阻断: {budget_err}"
730
+ if i18n is not None:
731
+ err = i18n.exception_text("orchestrator.budget_blocked", fallback=err, error=budget_err)
732
+ print(err)
733
+ return 1
734
+ return 0
735
+
736
+
737
+ def resolve_resume_state(st: "_PreState", memo: "_RuntimeMemo") -> int:
738
+ """读取运行态现值并恢复中断会话、持久化轮询策略。
739
+
740
+ 原 ``pre()`` 498-551 逐字迁移;``_runtime()`` 换为显式 memo 访问器,
741
+ 以保持 PERF-05 的单快照语义。"""
742
+ review_mode = st.review_mode
743
+ startup_action = st.startup_action
744
+ polling_policy = st.polling_policy
745
+ session_recovery = st.session_recovery
746
+ review_mode_deferred = st.review_mode_deferred
747
+ current_runtime = st.current_runtime
748
+ current_review_mode = st.current_review_mode
749
+ current_review_deferred = st.current_review_deferred
750
+ current_policy = st.current_policy
751
+ current_commit_policy = st.current_commit_policy
752
+ aborted_new_session = st.aborted_new_session
753
+ try:
754
+ current_runtime = memo.get()
755
+ current_policy = current_runtime.get("polling_policy")
756
+ current_review_mode = current_runtime.get("review_mode")
757
+ current_review_deferred = bool(
758
+ current_runtime.get("review_mode_deferred", False)
759
+ )
760
+ current_commit_policy = current_runtime.get("commit_policy")
761
+ if current_review_deferred and not current_runtime.get("active", False):
762
+ current_review_mode = None
763
+ except (OSError, ValueError) as exc:
764
+ print(f"[launch_bugx] ✗ 无法读取启动决策: {exc}")
765
+ return 1
766
+
767
+ if polling_policy is not None:
768
+ try:
769
+ set_polling_policy(polling_policy)
770
+ except (OSError, TimeoutError, ValueError) as exc:
771
+ print(f"[launch_bugx] ✗ 启动前轮询策略无效: {exc}")
772
+ return 2
773
+ if session_recovery is not None and session_recovery not in {"resume", "new"}:
774
+ print("[launch_bugx] ✗ --session-recovery 只能是 resume 或 new")
775
+ return 2
776
+ if st.autonomous_mode:
777
+ aborted_code, aborted_choice = aborted_session_gate(
778
+ current_runtime, explicit_choice=session_recovery, autonomous=True,
779
+ )
780
+ else:
781
+ # Keep the legacy call shape for host adapters that patch this gate.
782
+ aborted_code, aborted_choice = aborted_session_gate(
783
+ current_runtime, explicit_choice=session_recovery,
784
+ )
785
+ if aborted_code != 0:
786
+ return aborted_code
787
+ aborted_new_session = (aborted_choice == "new")
788
+ if aborted_choice == "resume":
789
+ print("↻ 已选择恢复上一次会话,继续启动流程。")
790
+ st.current_runtime = current_runtime
791
+ st.current_review_mode = current_review_mode
792
+ st.current_review_deferred = current_review_deferred
793
+ st.current_policy = current_policy
794
+ st.current_commit_policy = current_commit_policy
795
+ st.startup_action = startup_action
796
+ st.review_mode = review_mode
797
+ st.review_mode_deferred = review_mode_deferred
798
+ st.aborted_new_session = aborted_new_session
799
+ return 0
800
+
801
+
802
+ def derive_and_persist_decisions(st: "_PreState", memo: "_RuntimeMemo") -> int:
803
+ """推导有效决策、执行作战方案策略门禁并持久化审查/轮询/提交/修复方式。
804
+
805
+ 原 ``pre()`` 553-625 逐字迁移。"""
806
+ review_mode = st.review_mode
807
+ review_mode_deferred = st.review_mode_deferred
808
+ current_review_mode = st.current_review_mode
809
+ polling_policy = st.polling_policy
810
+ current_policy = st.current_policy
811
+ fix_mode = st.fix_mode
812
+ current_fix_mode = st.current_fix_mode
813
+ commit_policy = st.commit_policy
814
+ current_commit_policy = st.current_commit_policy
815
+ strategy_plan = st.strategy_plan
816
+ life_state = st.life_state
817
+ current_review_deferred = st.current_review_deferred
818
+ life_state = baseline_json() or {}
819
+ current_fix_mode = life_state.get("mode")
820
+ if current_fix_mode not in {"auto", "log-only"}:
821
+ current_fix_mode = None
822
+ if current_fix_mode == "log-only":
823
+ current_commit_policy = "not_applicable"
824
+
825
+ eff_review = review_mode or current_review_mode
826
+ eff_polling = polling_policy or current_policy
827
+ eff_fix = fix_mode or current_fix_mode
828
+ eff_commit = commit_policy or current_commit_policy
829
+ has_all_startup_decisions = (
830
+ eff_review is not None
831
+ and eff_polling is not None
832
+ and eff_fix is not None
833
+ and (eff_commit is not None or eff_fix == "log-only")
834
+ )
835
+ if (
836
+ not st.noninteractive_startup
837
+ and st.autonomous_mode
838
+ and has_all_startup_decisions
839
+ and strategy_plan is None
840
+ ):
841
+ # 期间只有 ``set_polling_policy`` 可能写盘,且不改 ``strategy_plan``;
842
+ # 复用快照与重新读盘等价,因此无需再次读盘。
843
+ current_strat = (memo.get().get("strategy_plan") or {}).get("status")
844
+ if current_strat != "approved":
845
+ mark_strategy_customized(compile_strategy_plan())
846
+ else:
847
+ plan_data = None
848
+ if st.noninteractive_startup:
849
+ plan_data = compile_strategy_plan(resolve_project_root())
850
+ preset = dict(plan_data.get("recommended_preset") or {})
851
+ preset.update(fix_mode="log-only", commit_policy="manual")
852
+ plan_data["recommended_preset"] = preset
853
+ strat_code, strat_decision = strategy_plan_gate(
854
+ strategy_choice="approve" if st.noninteractive_startup else strategy_plan,
855
+ environment=detect_startup_environment(),
856
+ plan_data=plan_data,
857
+ cli_fix_mode=fix_mode,
858
+ )
859
+ if strat_code != 0:
860
+ return strat_code
861
+ if strat_decision == "approved":
862
+ # ``strategy_plan_gate`` 可能经 ``_apply_approved_strategy`` 写盘。
863
+ # current_* 必须播种为盘面真实值(preset 已落盘),下方比较才能
864
+ # 发现 CLI 显式值与盘面的差异并正确持久化——旧实现把 current_*
865
+ # 播种成 CLI 值,显式 --review-mode 等被 preset 静默吞掉。
866
+ current_runtime = memo.get(refresh=True)
867
+ current_review_mode = current_runtime.get("review_mode")
868
+ current_policy = current_runtime.get("polling_policy")
869
+ current_commit_policy = current_runtime.get("commit_policy")
870
+ current_fix_mode = (baseline_json() or {}).get("mode")
871
+ if review_mode is None:
872
+ review_mode = current_review_mode or "manual"
873
+ if polling_policy is None:
874
+ polling_policy = current_policy or "auto"
875
+ if commit_policy is None:
876
+ commit_policy = current_commit_policy or "round"
877
+ if fix_mode is None:
878
+ fix_mode = current_fix_mode or "auto"
879
+
880
+ try:
881
+ if review_mode is not None and current_review_mode != review_mode:
882
+ set_review_mode(review_mode, deferred=review_mode_deferred)
883
+ current_review_mode = review_mode
884
+ current_review_deferred = review_mode_deferred
885
+ elif review_mode is not None:
886
+ current_review_deferred = review_mode_deferred
887
+ if polling_policy is not None and current_policy != polling_policy:
888
+ set_polling_policy(polling_policy)
889
+ current_policy = polling_policy
890
+ if commit_policy is not None and current_commit_policy != commit_policy:
891
+ set_commit_policy(commit_policy)
892
+ current_commit_policy = commit_policy
893
+ except (OSError, TimeoutError, ValueError) as exc:
894
+ print(f"[launch_bugx] ✗ 启动前策略无效: {exc}")
895
+ return 2
896
+ if fix_mode is not None and current_fix_mode != fix_mode:
897
+ if run_verify_life("set-mode", "--mode", fix_mode, "--confirm") != 0:
898
+ if run_verify_life("check") != 0 and run_verify_life("repair") == 0 and run_verify_life("check") == 0:
899
+ print("→ 基线修复后重试修复方式设置…")
900
+ if run_verify_life("set-mode", "--mode", fix_mode, "--confirm") != 0:
901
+ print(f"[launch_bugx] ✗ 修复方式持久化失败: {fix_mode}(硬阻断,拒绝继续启动)")
902
+ return 1
903
+ else:
904
+ print(f"[launch_bugx] ✗ 修复方式持久化失败: {fix_mode}(硬阻断,拒绝继续启动)")
905
+ return 1
906
+ current_fix_mode = fix_mode
907
+ st.life_state = life_state
908
+ st.current_fix_mode = current_fix_mode
909
+ st.review_mode = review_mode
910
+ st.polling_policy = polling_policy
911
+ st.commit_policy = commit_policy
912
+ st.fix_mode = fix_mode
913
+ st.current_review_mode = current_review_mode
914
+ st.current_review_deferred = current_review_deferred
915
+ st.current_policy = current_policy
916
+ st.current_commit_policy = current_commit_policy
917
+ return 0
918
+
919
+
920
+ def run_tools_and_preflight_gates(st: "_PreState", memo: "_RuntimeMemo") -> int:
921
+ """工具知识库校验、预飞探针扇出、降级门禁与基线 check/repair。
922
+
923
+ 原 ``pre()`` 769-828 逐字迁移。末尾的 ``_replay_share_pending()`` 刻意
924
+ 留在 ``pre()`` 编排层内联——见 ``pre()`` 内的说明。"""
925
+ refresh_probes = st.refresh_probes
926
+ tooling_choices = st.tooling_choices
927
+ review_mode = st.review_mode
928
+ current_review_mode = st.current_review_mode
929
+ current_review_deferred = st.current_review_deferred
930
+ refresh_startup_todo(
931
+ "tools",
932
+ reason="启动配置和最终启动动作已确认,进入工具与 MCP 准备",
933
+ environment=detect_startup_environment(),
934
+ )
935
+ try:
936
+ # ``supervisor_mcp_gate`` 可能经 ``set_review_mode`` 写盘,必须刷新。
937
+ refreshed_runtime = memo.get(refresh=True)
938
+ current_review_mode = refreshed_runtime.get("review_mode") or current_review_mode
939
+ current_review_deferred = bool(
940
+ refreshed_runtime.get("review_mode_deferred", current_review_deferred)
941
+ )
942
+ if current_review_mode == "manual" and current_review_deferred:
943
+ review_mode = "manual"
944
+ except (OSError, ValueError):
945
+ pass
946
+
947
+ print("=" * 56)
948
+ print("bugx 启动前协议:校验基线 → 建立快照 → 输出外部基线")
949
+ print("=" * 56)
950
+
951
+ if run_tools_kb() != 0:
952
+ print("✗ tools-kb 存在过期/缺日期条目,先搜索更新后再启动")
953
+ return 1
954
+ # PERF-09 / DES-13:启动前探针由 probe_registry 按 lifecycle="preflight"
955
+ # 统一驱动,并在同一个并发扇出里各执行一次;不再手写 5 个顺序包装
956
+ # (原先 5 个探针各起一个解释器,随后环境画像又把它们重跑一遍)。
957
+ probe_result = run_preflight_probes(
958
+ refresh=refresh_probes,
959
+ include_profile=True,
960
+ project_profile_data=st.project_profile_data,
961
+ )
962
+ if len(probe_result) == 3:
963
+ probe_code, degraded_probes, preflight_profile = probe_result
964
+ else: # Preserve patched/legacy test doubles that return the public pair.
965
+ probe_code, degraded_probes = probe_result
966
+ preflight_profile = {}
967
+ if probe_code != 0:
968
+ return probe_code
969
+ report_degraded_probes(degraded=degraded_probes)
970
+ runtime_state = memo.get(refresh=True)
971
+ audit_strategy = runtime_state.get("audit_strategy")
972
+ skill_plan = (
973
+ audit_strategy.get("skill_plan")
974
+ if isinstance(audit_strategy, dict)
975
+ else None
976
+ )
977
+ try:
978
+ from core.governance import runtime_tool_gate
979
+
980
+ selected_tool_ids = runtime_tool_gate.required_tool_ids_for_active_stages(
981
+ skill_plan if isinstance(skill_plan, dict) else None,
982
+ )
983
+ except Exception as exc:
984
+ print(f"✗ required Skill Pack stage tools 无法解析:{type(exc).__name__}: {exc}")
985
+ return 1
986
+ # DOC-180 / 反官僚主义:无论是否自治模式,优先尝试自愈安装/装配加速器,杜绝能自愈非要降级
987
+ if degraded_probes:
988
+ degraded_probes, provisioned = auto_provision_accelerators(
989
+ resolve_project_root(), degraded_probes, required_tools=selected_tool_ids,
990
+ )
991
+ if provisioned:
992
+ print("[launch_bugx] ✓ 环境加速器已就地自愈装配:" + "; ".join(provisioned))
993
+
994
+ try:
995
+ readiness_receipt = runtime_tool_gate.enforce_required_runtime_tools(
996
+ resolve_project_root(),
997
+ skill_plan if isinstance(skill_plan, dict) else None,
998
+ runtime_state.get("project_classification"),
999
+ preflight_profile,
1000
+ )
1001
+ except Exception as exc:
1002
+ print(f"✗ required Skill Pack runtime tool gate 异常:{type(exc).__name__}: {exc}")
1003
+ return 1
1004
+ if readiness_receipt and readiness_receipt.get("status") != "READY":
1005
+ print("✗ required Skill Pack runtime tool gate: BLOCKED")
1006
+ for item in readiness_receipt.get("tools", []):
1007
+ if item.get("status") not in {"READY", "NOT_APPLICABLE", "OPTIONAL"}:
1008
+ print(f" - {item.get('name')}: {item.get('status')}")
1009
+ for check in item.get("checks", [])[:4]:
1010
+ if isinstance(check, dict):
1011
+ print(f" {check.get('name')}: {check.get('detail')}")
1012
+ if readiness_receipt.get("error"):
1013
+ print(f" 原因:{readiness_receipt['error']}")
1014
+ if readiness_receipt.get("receipt_path"):
1015
+ print(f" 收据:{readiness_receipt['receipt_path']}")
1016
+ return 1
1017
+ if readiness_receipt:
1018
+ print(
1019
+ "[launch_bugx] ✓ 当前 Skill Pack 的必需运行时工具已就绪 "
1020
+ f"({readiness_receipt.get('skill_id')})"
1021
+ )
1022
+
1023
+ # DOC-236 C1:删除"命令行显式允许回退"分支——缺能力只能自愈,自愈不成即阻断;
1024
+ # 无自动安装器的专有工具走 config.json `tooling_exemptions` 显式豁免(见 degraded_gate)。
1025
+ if st.autonomous_mode:
1026
+ if degraded_probes:
1027
+ choices = autonomous_degraded_choices(degraded_probes)
1028
+ if not degraded_gate(degraded_probes, explicit_choices=choices):
1029
+ return 1
1030
+ print("[launch_bugx] ✓ 自治模式仅保留结构化自愈成功、非适用剪枝或显式审计豁免")
1031
+ else:
1032
+ print("[launch_bugx] ✓ 自治模式加速器自动装配完成,环境满血就绪!")
1033
+ elif not degraded_gate(degraded_probes, explicit_choices=tooling_choices):
1034
+ return POLLING_DECISION_REQUIRED
1035
+ if run_verify_life("check") != 0:
1036
+ print("→ 基线不一致,先 repair 恢复…")
1037
+ if run_verify_life("repair") != 0:
1038
+ print("✗ repair 无法自动修复(可能 history 被篡改),基线不可用。")
1039
+ print(" 请人工复核 bugx-life.json,或 reset 后重建。")
1040
+ return 1
1041
+ if run_verify_life("check") != 0:
1042
+ print("✗ repair 后仍不一致,基线不可用。")
1043
+ return 1
1044
+ print("✓ 基线已修复")
1045
+ st.review_mode = review_mode
1046
+ st.current_review_mode = current_review_mode
1047
+ st.current_review_deferred = current_review_deferred
1048
+ return 0
1049
+
1050
+
1051
+ def ensure_autonomous_prep_record(root: Path | None = None) -> int:
1052
+ """Replace only the untouched init template with observed facts.
1053
+
1054
+ Autonomous runs cannot wait for a human to fill the preparation form, but
1055
+ they must not overwrite a user-authored record or weaken ``prep_validate``.
1056
+ Any non-template invalid record remains a hard post gate failure.
1057
+ """
1058
+ root = (root or resolve_project_root()).resolve()
1059
+ try:
1060
+ from core.runtime import prep_validate
1061
+ return prep_validate.ensure_prep_record(root)
1062
+ except Exception as exc:
1063
+ print(f"[launch_bugx] ✗ 准备记录生成失败: {exc}")
1064
+ return 1
1065
+
1066
+
1067
+ def start_or_resume_session(st: "_PreState", memo: "_RuntimeMemo") -> int:
1068
+ """会话启动:中断/完成会话的新建引导。
1069
+
1070
+ 原 ``pre()`` 830-862 逐字迁移。其后的覆盖清单门禁与快照刻意留在
1071
+ ``pre()`` 编排层内联——见 ``pre()`` 内的说明。"""
1072
+ aborted_new_session = st.aborted_new_session
1073
+ bootstrap_coverage = st.bootstrap_coverage
1074
+ life_state = st.life_state
1075
+ new_session_started = st.new_session_started
1076
+ life_state = baseline_json()
1077
+ try:
1078
+ # 期间没有任何 runtime 写操作(子进程 verify_life 不写 runtime.json),
1079
+ # 直接复用快照即可。
1080
+ previous_runtime = memo.get()
1081
+ except (OSError, ValueError):
1082
+ previous_runtime = {}
1083
+ new_session_started = False
1084
+ if aborted_new_session:
1085
+ print("↻ 上一个 Session 已中断,按显式新建请求创建新的 Session 和首个 Round。")
1086
+ runtime, started, startup_code = _begin_new_session(
1087
+ autonomous=st.autonomous_mode,
1088
+ )
1089
+ if not started:
1090
+ if startup_code is not None:
1091
+ return startup_code
1092
+ print("✗ 新 Session 未能建立,保留原中断状态并停止启动。")
1093
+ return 1
1094
+ new_session_started = True
1095
+ life_state = baseline_json()
1096
+ elif (not previous_runtime.get("active")
1097
+ and previous_runtime.get("lifecycle_terminal")):
1098
+ print("↻ 上一个 Session 已完成,正在创建新的 Session 和首个 Round。")
1099
+ runtime, started, startup_code = _begin_new_session(
1100
+ bootstrap_coverage=bootstrap_coverage, autonomous=st.autonomous_mode,
1101
+ )
1102
+ if not started:
1103
+ if startup_code is not None:
1104
+ return startup_code
1105
+ print("✗ 新 Session 未能建立,保留原完成状态并停止启动。")
1106
+ return 1
1107
+ new_session_started = True
1108
+ life_state = baseline_json()
1109
+ elif isinstance(life_state, dict) and life_state.get("life", 1) <= 0:
1110
+ print("✝ 当前 Life 已耗尽,但上一 Session 尚未安全收尾;进入恢复检查。")
1111
+ print(" 请先恢复或修复当前运行状态,禁止覆盖未完成 Session。")
1112
+ return 1
1113
+ st.life_state = life_state
1114
+ st.new_session_started = new_session_started
1115
+ return 0
1116
+
1117
+
1118
+ def serial_runtime_identity(runtime: Mapping[str, object]) -> dict[str, object]:
1119
+ """Validate the runtime-owned identity before it can bind a Supervisor run."""
1120
+ life_no = runtime.get("life_no")
1121
+ if isinstance(life_no, bool) or not isinstance(life_no, int) or life_no < 1:
1122
+ raise ValueError("runtime life_no must be a positive integer")
1123
+
1124
+ lifecycle_id = runtime.get("lifecycle_id")
1125
+ if not isinstance(lifecycle_id, str) or not lifecycle_id.strip():
1126
+ raise ValueError("runtime lifecycle_id must be a non-empty string")
1127
+ for field_name in ("round_id",):
1128
+ value = runtime.get(field_name)
1129
+ if value is not None and value != lifecycle_id:
1130
+ raise ValueError(f"runtime {field_name} does not match lifecycle_id")
1131
+
1132
+ expected_life_id = f"life-{life_no}"
1133
+ runtime_life_id = runtime.get("life_id")
1134
+ if runtime_life_id is not None and runtime_life_id != expected_life_id:
1135
+ raise ValueError("runtime life_id does not match life_no")
1136
+
1137
+ session_ids: list[str] = []
1138
+ for field_name in ("session_id", "polling_id"):
1139
+ value = runtime.get(field_name)
1140
+ if value is None:
1141
+ continue
1142
+ if not isinstance(value, str) or not value.strip():
1143
+ raise ValueError(f"runtime {field_name} must be a non-empty string")
1144
+ session_ids.append(value)
1145
+ if not session_ids:
1146
+ raise ValueError("runtime session identity is missing")
1147
+ if any(value != session_ids[0] for value in session_ids[1:]):
1148
+ raise ValueError("runtime session_id and polling_id conflict")
1149
+
1150
+ life_kind = runtime.get("life_kind")
1151
+ host = str(runtime.get("host") or "").strip().casefold()
1152
+ if life_kind == "fix":
1153
+ pass
1154
+ elif life_kind == "mine" and host_serial_worker(host):
1155
+ pass
1156
+ else:
1157
+ raise ValueError(
1158
+ f"serial authorization only supports fix Life or mine Life on a serial-worker host ({host})"
1159
+ )
1160
+ return {
1161
+ "session_id": session_ids[0],
1162
+ "lifecycle_id": lifecycle_id,
1163
+ "round_id": lifecycle_id,
1164
+ "life_id": expected_life_id,
1165
+ "life_no": life_no,
1166
+ "life_kind": life_kind,
1167
+ }
1168
+
1169
+
1170
+ def serial_authorization_intent(
1171
+ runtime: dict, supervisor_state: object, serial_reason: str,
1172
+ ) -> dict[str, object]:
1173
+ """Build the bounded pending record from matching runtime and Supervisor identities."""
1174
+ from core.supervisor.serial_authorization import derive_serial_policy_hash
1175
+
1176
+ def value(name: str) -> object:
1177
+ if isinstance(supervisor_state, Mapping):
1178
+ return supervisor_state.get(name)
1179
+ return getattr(supervisor_state, name, None)
1180
+
1181
+ runtime_identity = _serial_runtime_identity(runtime)
1182
+ lifecycle_id = runtime_identity["lifecycle_id"]
1183
+ identity: dict[str, object] = {
1184
+ "runtime_run_uuid": runtime.get("run_id"),
1185
+ "supervisor_run_id": value("run_id"),
1186
+ "session_id": value("session_id"),
1187
+ "lifecycle_id": lifecycle_id,
1188
+ "round_id": value("round_id"),
1189
+ "life_id": value("life_id"),
1190
+ "life_kind": value("life_kind"),
1191
+ "round_no": value("round_no"),
1192
+ }
1193
+ for field_name in ("session_id", "round_id", "life_id"):
1194
+ if identity[field_name] != runtime_identity[field_name]:
1195
+ raise ValueError(
1196
+ f"Supervisor {field_name} does not match runtime identity"
1197
+ )
1198
+ if identity["life_kind"] != runtime_identity["life_kind"]:
1199
+ raise ValueError("Supervisor Life kind does not match runtime identity")
1200
+ reason_digest = hashlib.sha256(serial_reason.encode("utf-8")).hexdigest()
1201
+ base_policy_hash = runtime.get("autonomous_policy_hash")
1202
+ policy_hash = derive_serial_policy_hash(
1203
+ identity=identity,
1204
+ base_policy_hash=base_policy_hash,
1205
+ serial_reason_sha256=reason_digest,
1206
+ )
1207
+ return {
1208
+ "schema_version": 1,
1209
+ "status": "pending",
1210
+ "authorization_source": "pre_cli",
1211
+ "allow_serial": True,
1212
+ "identity": identity,
1213
+ "base_policy_hash": base_policy_hash,
1214
+ "serial_reason_sha256": reason_digest,
1215
+ "policy_hash": policy_hash,
1216
+ }
1217
+
1218
+
1219
+ def persist_serial_authorization_record(
1220
+ runtime: dict, expected: dict[str, object], memo: "_RuntimeMemo", *,
1221
+ receipt: dict[str, object] | None = None,
1222
+ ) -> dict[str, object]:
1223
+ """Persist pending before issuing, then atomically bind the Supervisor receipt."""
1224
+ with runtime_lock():
1225
+ latest = load_runtime()
1226
+ if latest.get("run_id") != runtime.get("run_id"):
1227
+ raise ValueError("runtime identity changed during serial authorization")
1228
+ existing = latest.get("serial_authorization")
1229
+ # 回执是**运行级**凭据:`start_runtime` 每次调用都会铸造新的 run_id
1230
+ # (同一会话被再次 `pre` resume 时亦然),因此绑定旧 run 的回执属于
1231
+ # **陈旧**而非冲突。若按冲突处理,重复 `bugx pre --allow-serial`
1232
+ # 会永久失败(实测 test_auto_stop_uses_total_findings_of_big_lifecycle
1233
+ # 命中 `runtime serial authorization conflicts with explicit pre inputs`)。
1234
+ if isinstance(existing, Mapping):
1235
+ stored_identity = existing.get("identity")
1236
+ stored_run = (
1237
+ stored_identity.get("runtime_run_uuid")
1238
+ if isinstance(stored_identity, Mapping) else None
1239
+ )
1240
+ if stored_run != latest.get("run_id"):
1241
+ existing = None
1242
+ if existing is not None:
1243
+ if not isinstance(existing, Mapping):
1244
+ raise ValueError("runtime serial authorization record is malformed")
1245
+ expected_fields = set(expected)
1246
+ allowed = (expected_fields, expected_fields | {"receipt"})
1247
+ if set(existing) not in allowed or any(
1248
+ existing.get(key) != value
1249
+ for key, value in expected.items() if key != "status"
1250
+ ):
1251
+ raise ValueError("runtime serial authorization conflicts with explicit pre inputs")
1252
+ status = existing.get("status")
1253
+ if status not in {"pending", "authorized"}:
1254
+ raise ValueError("runtime serial authorization has an invalid status")
1255
+ if status == "authorized":
1256
+ if receipt is not None and existing.get("receipt") != receipt:
1257
+ raise ValueError("runtime serial authorization receipt changed")
1258
+ memo.seed(latest)
1259
+ return dict(existing)
1260
+ if "receipt" in existing:
1261
+ raise ValueError("pending serial authorization cannot contain a receipt")
1262
+ record = dict(expected)
1263
+ if receipt is not None:
1264
+ record["status"] = "authorized"
1265
+ record["receipt"] = receipt
1266
+ latest["serial_authorization"] = record
1267
+ save_runtime(latest)
1268
+ memo.seed(latest)
1269
+ return record
1270
+
1271
+
1272
+
1273
+
1274
+ _begin_new_session = begin_new_session
1275
+ _RuntimeMemo = RuntimeMemo
1276
+ _PreState = PreState
1277
+ _normalize_pre_options = normalize_pre_options
1278
+ _run_preflight_budget_gates = run_preflight_budget_gates
1279
+ _resolve_resume_state = resolve_resume_state
1280
+ _derive_and_persist_decisions = derive_and_persist_decisions
1281
+ _run_tools_and_preflight_gates = run_tools_and_preflight_gates
1282
+ _ensure_autonomous_prep_record = ensure_autonomous_prep_record
1283
+ _start_or_resume_session = start_or_resume_session
1284
+ _serial_runtime_identity = serial_runtime_identity
1285
+ _serial_authorization_intent = serial_authorization_intent
1286
+ _persist_serial_authorization_record = persist_serial_authorization_record