bugx-cli 0.1.1__py3-none-any.whl

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 (762) hide show
  1. bugx_cli/__init__.py +6 -0
  2. bugx_cli/cli.py +1685 -0
  3. bugx_cli/commands/__init__.py +1 -0
  4. bugx_cli/commands/advisory.py +94 -0
  5. bugx_cli/commands/agent.py +4210 -0
  6. bugx_cli/commands/audit.py +632 -0
  7. bugx_cli/commands/autonomous.py +260 -0
  8. bugx_cli/commands/cloud.py +1371 -0
  9. bugx_cli/commands/daemon.py +50 -0
  10. bugx_cli/commands/doctor.py +1590 -0
  11. bugx_cli/commands/goal.py +107 -0
  12. bugx_cli/commands/interaction.py +248 -0
  13. bugx_cli/commands/knowledge.py +619 -0
  14. bugx_cli/commands/lifecycle.py +2763 -0
  15. bugx_cli/commands/patch.py +1014 -0
  16. bugx_cli/commands/plugin.py +2749 -0
  17. bugx_cli/commands/plugin_claude.py +1446 -0
  18. bugx_cli/commands/plugin_cline.py +269 -0
  19. bugx_cli/commands/plugin_codex.py +74 -0
  20. bugx_cli/commands/plugin_funide.py +729 -0
  21. bugx_cli/commands/plugin_qoder.py +216 -0
  22. bugx_cli/commands/plugin_zcode.py +710 -0
  23. bugx_cli/commands/project.py +670 -0
  24. bugx_cli/commands/report.py +256 -0
  25. bugx_cli/commands/skill.py +251 -0
  26. bugx_cli/commands/stats.py +133 -0
  27. bugx_cli/commands/system.py +2567 -0
  28. bugx_cli/common.py +906 -0
  29. bugx_cli/host_adapters.py +1892 -0
  30. bugx_cli/hosts/__init__.py +80 -0
  31. bugx_cli/hosts/base.py +99 -0
  32. bugx_cli/hosts/registry.py +573 -0
  33. bugx_cli/hosts/template_engine.py +188 -0
  34. bugx_cli/infra/__init__.py +209 -0
  35. bugx_cli/infra/ai_advisor.py +851 -0
  36. bugx_cli/infra/engine_installer.py +1945 -0
  37. bugx_cli/infra/host_sync.py +548 -0
  38. bugx_cli/infra/mcp_advisor.py +826 -0
  39. bugx_cli/infra/security.py +339 -0
  40. bugx_cli-0.1.1.data/data/share/bugx-agent/bugx-mcp-manifest.json +53 -0
  41. bugx_cli-0.1.1.data/data/share/bugx-agent/core/CATALOG.json +141 -0
  42. bugx_cli-0.1.1.data/data/share/bugx-agent/core/README.md +254 -0
  43. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/README.md +35 -0
  44. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/android-interaction.json +81 -0
  45. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/android.json +24 -0
  46. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/desktop-macos.json +20 -0
  47. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/ios-interaction.json +34 -0
  48. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/ios.json +23 -0
  49. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/memory-macos.json +24 -0
  50. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/README.md +51 -0
  51. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/__init__.py +146 -0
  52. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_artifacts.py +766 -0
  53. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_eval.py +1155 -0
  54. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_execution.py +718 -0
  55. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_orchestrator.py +1351 -0
  56. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_targets.py +877 -0
  57. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_workspace.py +770 -0
  58. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/feature_baseline.py +150 -0
  59. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/README.md +24 -0
  60. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  61. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/LICENSE.txt +362 -0
  62. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/UPSTREAM.md +10 -0
  63. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/axe.min.js +12 -0
  64. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-1024.png +0 -0
  65. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-512.png +0 -0
  66. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-tight.svg +23 -0
  67. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar.svg +28 -0
  68. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-cn.png +0 -0
  69. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-en.png +0 -0
  70. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-en.svg +74 -0
  71. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-zh.svg +74 -0
  72. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/codex.png +0 -0
  73. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/dsh.png +0 -0
  74. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/project-layout.md +42 -0
  75. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/zcode.png +0 -0
  76. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/README.md +37 -0
  77. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/manifest.json +94 -0
  78. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/00-scope.md +14 -0
  79. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
  80. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
  81. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
  82. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/manifest.json +123 -0
  83. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
  84. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
  85. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
  86. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
  87. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
  88. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/memory-testing.md +227 -0
  89. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/manifest.json +155 -0
  90. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/android.md +19 -0
  91. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/h5.md +18 -0
  92. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/ios.md +25 -0
  93. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
  94. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/webview.md +18 -0
  95. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
  96. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
  97. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
  98. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
  99. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
  100. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
  101. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/manifest.json +127 -0
  102. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/00-scope.md +14 -0
  103. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
  104. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
  105. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
  106. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
  107. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/platform-testing.md +174 -0
  108. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/manifest.json +191 -0
  109. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/graphql.md +5 -0
  110. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/h5.md +18 -0
  111. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
  112. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/oauth.md +4 -0
  113. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/upload.md +4 -0
  114. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/websocket.md +4 -0
  115. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/00-scope.md +13 -0
  116. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
  117. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
  118. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
  119. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
  120. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
  121. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
  122. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
  123. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
  124. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/INTERFACE.md +61 -0
  125. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/README.md +58 -0
  126. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/SPEC.md +25 -0
  127. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/__init__.py +109 -0
  128. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/attack_graph.py +1096 -0
  129. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/attack_graph_store.py +1868 -0
  130. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/audit_campaign.py +1232 -0
  131. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/behavior_graph.py +465 -0
  132. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/ghsa_advisories.py +174 -0
  133. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/models.py +93 -0
  134. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/mutator.py +87 -0
  135. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/patcher.py +126 -0
  136. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/scout.py +278 -0
  137. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/synthesizer.py +207 -0
  138. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/verifier.py +103 -0
  139. bugx_cli-0.1.1.data/data/share/bugx-agent/core/bugx.md +1299 -0
  140. bugx_cli-0.1.1.data/data/share/bugx-agent/core/bugx_paths.py +1881 -0
  141. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cli-help.txt +66 -0
  142. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/INTERFACE.md +32 -0
  143. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/README.md +62 -0
  144. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/SPEC.md +25 -0
  145. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/__init__.py +23 -0
  146. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/auto_sync.py +398 -0
  147. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_client.py +1218 -0
  148. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_onboard.py +743 -0
  149. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_schema.py +648 -0
  150. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/consent.py +81 -0
  151. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/device_identity.py +307 -0
  152. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/endpoint_router.py +415 -0
  153. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/flywheel_client.py +769 -0
  154. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/network_transport.py +296 -0
  155. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/onboard_wizard.py +493 -0
  156. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sensitive_filter.py +285 -0
  157. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sync_pull.py +695 -0
  158. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sync_push.py +723 -0
  159. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/AGENT_GUIDE.md +359 -0
  160. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/README.md +34 -0
  161. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-blackbox.md +541 -0
  162. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-opencode.md +469 -0
  163. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-quick.md +44 -0
  164. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-runtime-contract.md +353 -0
  165. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-worker.md +470 -0
  166. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/engine_gap_contracts.py +473 -0
  167. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/README.md +70 -0
  168. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/__init__.py +106 -0
  169. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_ai_review.py +185 -0
  170. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_backfill.py +54 -0
  171. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_bootstrap.py +713 -0
  172. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_business.py +36 -0
  173. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_cli.py +715 -0
  174. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_discovery.py +1429 -0
  175. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_evidence.py +1024 -0
  176. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_forensics.py +124 -0
  177. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_gate.py +277 -0
  178. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_intelligence.py +734 -0
  179. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_manifest.py +396 -0
  180. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_platform.py +77 -0
  181. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_validate.py +241 -0
  182. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/module_coverage.py +157 -0
  183. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/INTERFACE.md +20 -0
  184. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/README.md +21 -0
  185. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/SPEC.md +25 -0
  186. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/__init__.py +5 -0
  187. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/interaction_preset.py +408 -0
  188. bugx_cli-0.1.1.data/data/share/bugx-agent/core/engine-integrity.json +2797 -0
  189. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/README.md +49 -0
  190. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/__init__.py +82 -0
  191. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/concurrency_fuzzer.py +435 -0
  192. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/differential_oracle.py +1164 -0
  193. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/fuzz_input.py +1291 -0
  194. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/stateful_fuzzer.py +404 -0
  195. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/README.md +61 -0
  196. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/__init__.py +130 -0
  197. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/capacity_planner.py +124 -0
  198. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/dependency_lock.py +317 -0
  199. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/goal_governor.py +754 -0
  200. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/guide_budget.py +458 -0
  201. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/lockdown.sh +50 -0
  202. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/readonly_enforcer.py +154 -0
  203. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/runtime_tool_gate.py +373 -0
  204. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/secret_redactor.py +784 -0
  205. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/token_budget.py +38 -0
  206. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/INTERFACE.md +36 -0
  207. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/README.md +51 -0
  208. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/SPEC.md +25 -0
  209. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/__init__.py +121 -0
  210. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/base.py +111 -0
  211. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/claude.py +99 -0
  212. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/cline.py +298 -0
  213. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/codex.py +300 -0
  214. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/dsh.py +106 -0
  215. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/opencode.py +209 -0
  216. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/pi.py +94 -0
  217. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/zcode.py +99 -0
  218. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/INTERFACE.md +24 -0
  219. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/README.md +62 -0
  220. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/SPEC.md +25 -0
  221. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/__init__.py +21 -0
  222. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/adapters.py +412 -0
  223. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/autonomous_runner.py +1152 -0
  224. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/cline.py +448 -0
  225. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/common.py +103 -0
  226. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/free_models.py +786 -0
  227. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_bootstrap.py +389 -0
  228. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_evaluators.py +761 -0
  229. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_probe.py +41 -0
  230. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_provider_arbitrator.py +831 -0
  231. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_registry.py +662 -0
  232. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_usage.py +127 -0
  233. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/mcp_process_tracker.py +509 -0
  234. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/mcp_registry_gate.py +379 -0
  235. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/pi.py +102 -0
  236. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/provider_facts.py +66 -0
  237. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/INTERFACE.md +51 -0
  238. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/README.md +67 -0
  239. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/SPEC.md +25 -0
  240. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/__init__.py +140 -0
  241. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_base_usage.py +152 -0
  242. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_codex_usage.py +297 -0
  243. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_dsh_usage.py +184 -0
  244. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_mcp_toml.py +365 -0
  245. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_zcode_usage.py +269 -0
  246. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/base.py +479 -0
  247. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/claude.py +212 -0
  248. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/cline.py +229 -0
  249. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/codex.py +1006 -0
  250. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/dsh.py +526 -0
  251. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/opencode.py +358 -0
  252. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/pi.py +308 -0
  253. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/zcode.py +219 -0
  254. bugx_cli-0.1.1.data/data/share/bugx-agent/core/i18n.py +252 -0
  255. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/README.md +41 -0
  256. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/__init__.py +17 -0
  257. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/build_info.py +105 -0
  258. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/client_metadata.py +185 -0
  259. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/json_utils.py +22 -0
  260. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/python_runtime.py +540 -0
  261. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/safe_xml.py +221 -0
  262. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_bugx.py +118 -0
  263. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/INTERFACE.md +31 -0
  264. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/README.md +106 -0
  265. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/SPEC.md +25 -0
  266. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/__init__.py +29 -0
  267. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/candidate_revalidation.py +484 -0
  268. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/common.py +1060 -0
  269. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/finding_confirm_phase.py +391 -0
  270. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/finding_settlement.py +1432 -0
  271. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/findings_adjudication.py +666 -0
  272. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/findings_snapshot.py +357 -0
  273. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/judge_phase.py +848 -0
  274. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/lesson_context.py +536 -0
  275. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/lifecycle_reporter.py +627 -0
  276. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/orchestrator_controls.py +686 -0
  277. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_commit.py +567 -0
  278. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_coverage_sync.py +598 -0
  279. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_dry_run.py +817 -0
  280. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_observability.py +367 -0
  281. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_phase.py +1223 -0
  282. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_receipt.py +373 -0
  283. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_round_lifecycle.py +786 -0
  284. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_phase.py +1029 -0
  285. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_recon_scout.py +879 -0
  286. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_state_builder.py +1133 -0
  287. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/report_sharing.py +414 -0
  288. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/round_orchestrator.py +1116 -0
  289. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/session_runtime.py +1670 -0
  290. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_gates.py +1050 -0
  291. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_interaction.py +1003 -0
  292. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_version_gate.py +879 -0
  293. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_bridge.py +1253 -0
  294. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_coverage.py +423 -0
  295. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_degraded.py +1211 -0
  296. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_barriers.py +424 -0
  297. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_orchestrator.py +1246 -0
  298. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_prior.py +749 -0
  299. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/INTERFACE.md +35 -0
  300. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/README.md +160 -0
  301. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/SPEC.md +25 -0
  302. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/__init__.py +67 -0
  303. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/_facade.py +227 -0
  304. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/archive_ops.py +630 -0
  305. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/auto_materialization.py +459 -0
  306. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/bug-log.md +22 -0
  307. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/cli.py +275 -0
  308. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/export_ops.py +554 -0
  309. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_confirmation.py +1316 -0
  310. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_io.py +299 -0
  311. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_lifecycle.py +730 -0
  312. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_verification.py +405 -0
  313. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/incidents.py +1005 -0
  314. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson-replay-cases.json +20 -0
  315. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson_ledger.py +241 -0
  316. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson_replay.py +272 -0
  317. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/life_ledger.py +668 -0
  318. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/mistake-book.md +130 -0
  319. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/patterns.py +684 -0
  320. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/receipt_contract.py +269 -0
  321. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/schema.py +1192 -0
  322. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/sync_ops.py +940 -0
  323. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/tool_experience.py +683 -0
  324. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/verify_life.py +1597 -0
  325. bugx_cli-0.1.1.data/data/share/bugx-agent/core/lesson-ledger.json +275 -0
  326. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/README.md +19 -0
  327. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/en-US.json +462 -0
  328. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/zh-CN.json +462 -0
  329. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/INTERFACE.md +75 -0
  330. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/README.md +62 -0
  331. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/SPEC.md +25 -0
  332. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/__init__.py +128 -0
  333. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/base.py +717 -0
  334. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/channel_lifecycle.py +751 -0
  335. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/graph_handlers.py +222 -0
  336. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/knowledge_handlers.py +536 -0
  337. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/mining_handlers.py +586 -0
  338. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/resource_prompt_table.py +116 -0
  339. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/retrieval_handlers.py +249 -0
  340. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/rpc_server.py +470 -0
  341. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/supervisor_handlers.py +1461 -0
  342. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/telemetry_handlers.py +227 -0
  343. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/tool_table.py +1030 -0
  344. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/README.md +21 -0
  345. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/__init__.py +1 -0
  346. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/common.py +363 -0
  347. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/environment.py +567 -0
  348. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/verifier.py +758 -0
  349. bugx_cli-0.1.1.data/data/share/bugx-agent/core/metadata.txt +4 -0
  350. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/README.md +157 -0
  351. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/__init__.py +242 -0
  352. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/capability_plan.py +187 -0
  353. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/capability_planner.py +195 -0
  354. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/domain_archetype.py +542 -0
  355. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/domain_router.py +269 -0
  356. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/dynamic_flow_analyzer.py +533 -0
  357. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/impact_pruner.py +435 -0
  358. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/intent_adjudicator.py +175 -0
  359. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/judge_pipeline.py +1246 -0
  360. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/logic_analysis.py +419 -0
  361. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/prompt_harness.py +1704 -0
  362. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/source_inspector.py +267 -0
  363. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/spec_harvester.py +449 -0
  364. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/target_sandbox_manager.py +573 -0
  365. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/test_capability_verifier.py +1364 -0
  366. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/tools-kb.md +38 -0
  367. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/unit_kind.py +122 -0
  368. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/INTERFACE.md +83 -0
  369. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/README.md +51 -0
  370. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/SPEC.md +36 -0
  371. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/__init__.py +76 -0
  372. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/android_probe.py +552 -0
  373. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/base.py +147 -0
  374. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/codebase_memory_probe.py +647 -0
  375. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/desktop_probe.py +342 -0
  376. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/differential_probe.py +434 -0
  377. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/efficiency_probe.py +232 -0
  378. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ios_binary_probe.py +472 -0
  379. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/memory_probe.py +392 -0
  380. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/miniprogram_probe.py +385 -0
  381. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/mobile_probe.py +466 -0
  382. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/native_probe.py +302 -0
  383. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/openwiki_probe.py +263 -0
  384. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/pattern_probe.py +453 -0
  385. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/platform_probe.py +424 -0
  386. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/probe_registry.py +1770 -0
  387. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_fixture_corpus.py +340 -0
  388. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_probe.py +1510 -0
  389. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_rules.py +1481 -0
  390. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sca_scanner.py +779 -0
  391. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_accessibility.py +149 -0
  392. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_audit.py +513 -0
  393. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_contract.py +273 -0
  394. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_evidence.py +212 -0
  395. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_measurements.py +314 -0
  396. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_repair.py +250 -0
  397. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_review.py +133 -0
  398. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_storybook.py +107 -0
  399. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_tokens.py +185 -0
  400. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_visual_diff.py +131 -0
  401. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/web_probe.py +714 -0
  402. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/INTERFACE.md +62 -0
  403. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/README.md +53 -0
  404. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/SPEC.md +28 -0
  405. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/__init__.py +201 -0
  406. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/arbitrator.py +316 -0
  407. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/constants.py +247 -0
  408. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/detector.py +399 -0
  409. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/extractors.py +836 -0
  410. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/fingerprint.py +116 -0
  411. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/storage.py +258 -0
  412. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/strategy.py +301 -0
  413. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/README.md +35 -0
  414. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/codex_dialog_dispatch.md +9 -0
  415. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/command_routing_en.md +42 -0
  416. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/command_routing_zh.md +42 -0
  417. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/l0_router.md +47 -0
  418. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/anti_patterns.md +16 -0
  419. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/concurrency_rules.md +14 -0
  420. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/memory_leak_rules.md +13 -0
  421. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/prompt_injection_defense.md +13 -0
  422. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_explore.md +31 -0
  423. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_gate.md +43 -0
  424. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_mutate.md +42 -0
  425. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_repair.md +85 -0
  426. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/README.md +74 -0
  427. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/__init__.py +169 -0
  428. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/fix_watchlist.py +391 -0
  429. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_dynamic.py +418 -0
  430. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_repair_loop.py +462 -0
  431. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_selfcheck.py +862 -0
  432. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/minimize_repro.py +466 -0
  433. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/patch_synthesizer.py +617 -0
  434. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/regression_pack.py +379 -0
  435. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_fixer.py +910 -0
  436. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_loop.py +311 -0
  437. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_repair.py +348 -0
  438. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_rounds.py +212 -0
  439. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_scope.py +281 -0
  440. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/self_heal.py +604 -0
  441. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_generator.py +1108 -0
  442. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_quality_auditor.py +410 -0
  443. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_strategy.py +511 -0
  444. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/INTERFACE.md +59 -0
  445. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/README.md +69 -0
  446. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/SPEC.md +28 -0
  447. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/__init__.py +47 -0
  448. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/attestation.py +228 -0
  449. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/authority.py +255 -0
  450. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/finding_report.py +418 -0
  451. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/formal_report_builder.py +924 -0
  452. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/html_renderers.py +696 -0
  453. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/models.py +759 -0
  454. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/pdf_exporter.py +231 -0
  455. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/projects_assets.py +730 -0
  456. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_client.py +743 -0
  457. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_data_builder.py +388 -0
  458. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_share.py +459 -0
  459. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/sast_bridge.py +116 -0
  460. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/server.py +832 -0
  461. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/visual_report_builder.py +796 -0
  462. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/web-conformance.md +168 -0
  463. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/web_conformance.py +428 -0
  464. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/workbench_assets.py +484 -0
  465. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/INTERFACE.md +20 -0
  466. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/README.md +161 -0
  467. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/SPEC.md +25 -0
  468. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/__init__.py +3 -0
  469. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/code_analyzer.py +1720 -0
  470. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/codebase_memory_bridge.py +337 -0
  471. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/context_assembler.py +240 -0
  472. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/corpus_fetch.py +369 -0
  473. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/graph_ego.py +597 -0
  474. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_auto.py +662 -0
  475. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_sources.py +168 -0
  476. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_sync.py +1003 -0
  477. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/memory_store.py +480 -0
  478. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/query_planner.py +1020 -0
  479. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/rrf_engine.py +137 -0
  480. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_extractor.py +1209 -0
  481. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_normalizer.py +373 -0
  482. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_spec.py +357 -0
  483. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/symbol_index.py +1151 -0
  484. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/universal_code_matcher.py +622 -0
  485. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/xerj_bridge.py +476 -0
  486. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/xerj_supervisor.py +362 -0
  487. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/README.md +33 -0
  488. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/PROVENANCE.json +30 -0
  489. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/crypto.yaml +36 -0
  490. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/network.yaml +20 -0
  491. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/resilience.yaml +47 -0
  492. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/storage.yaml +48 -0
  493. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/LICENSE +173 -0
  494. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/PROVENANCE.json +270 -0
  495. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
  496. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
  497. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
  498. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
  499. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
  500. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
  501. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
  502. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
  503. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
  504. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
  505. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
  506. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
  507. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
  508. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
  509. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
  510. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
  511. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
  512. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
  513. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
  514. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
  515. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
  516. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
  517. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
  518. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
  519. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
  520. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
  521. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
  522. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
  523. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
  524. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
  525. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
  526. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
  527. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
  528. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
  529. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
  530. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
  531. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
  532. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
  533. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
  534. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
  535. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
  536. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
  537. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
  538. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
  539. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-strictmode.yml +10 -0
  540. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
  541. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
  542. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
  543. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
  544. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
  545. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/PROVENANCE.json +26 -0
  546. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/network.yaml +37 -0
  547. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/platform.yaml +36 -0
  548. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/storage.yaml +48 -0
  549. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/LICENSE +165 -0
  550. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
  551. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/auth.yaml +59 -0
  552. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/crypto.yaml +66 -0
  553. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
  554. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
  555. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/logging.yaml +23 -0
  556. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/network.yaml +55 -0
  557. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/resilience.yaml +29 -0
  558. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/secrets.yaml +33 -0
  559. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/storage.yaml +29 -0
  560. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/webview.yaml +32 -0
  561. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/README.md +198 -0
  562. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/__init__.py +3 -0
  563. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/bugx_logging.py +1464 -0
  564. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/daemon_runner.py +623 -0
  565. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/fixture_solidify.py +444 -0
  566. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/global_telemetry.py +549 -0
  567. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/incident_eval.py +148 -0
  568. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interaction.py +605 -0
  569. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interaction_store.py +435 -0
  570. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interactive_menu.py +95 -0
  571. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/log_analytics.py +922 -0
  572. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/mining_quality_framework.py +1387 -0
  573. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/model_runner.py +732 -0
  574. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/platform_adapter.py +579 -0
  575. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/prep_validate.py +478 -0
  576. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_graph.py +827 -0
  577. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_init.py +481 -0
  578. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_profile.py +224 -0
  579. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_settings.py +964 -0
  580. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/provider_window.py +97 -0
  581. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/resume_ticket.py +115 -0
  582. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/scenario_eval.py +856 -0
  583. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/seed_drill.py +549 -0
  584. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/self_audit.py +550 -0
  585. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/session_profile.py +205 -0
  586. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/setup_ui_env.py +229 -0
  587. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/startup_environment.py +859 -0
  588. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/sync_store.py +1421 -0
  589. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/tool_install_targets.py +18 -0
  590. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/README.md +35 -0
  591. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/agent-graph.schema.json +368 -0
  592. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/attack-graph.schema.json +88 -0
  593. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/evidence-bundle.schema.json +33 -0
  594. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/skill-pack.schema.json +230 -0
  595. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/worker-checkpoint.schema.json +119 -0
  596. bugx_cli-0.1.1.data/data/share/bugx-agent/core/secure_atomic.py +289 -0
  597. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/README.md +55 -0
  598. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/c.txt +29 -0
  599. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/cpp.txt +32 -0
  600. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/css.txt +70 -0
  601. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/go.txt +46 -0
  602. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/java.txt +30 -0
  603. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/javascript.txt +55 -0
  604. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/kotlin.txt +28 -0
  605. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/python.txt +71 -0
  606. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/rust.txt +53 -0
  607. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/swift.txt +29 -0
  608. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/typescript.txt +29 -0
  609. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/README.md +53 -0
  610. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/__init__.py +189 -0
  611. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/bugx_docs_mcp_server.py +418 -0
  612. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/bugx_mcp_server.py +1161 -0
  613. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mcp_runtime.py +968 -0
  614. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mcp_session_proof.py +605 -0
  615. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mobile_ui_inspector.py +405 -0
  616. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/skill_pack.py +1214 -0
  617. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/skill_synthesizer.py +1153 -0
  618. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/tools_kb.py +313 -0
  619. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/INTERFACE.md +121 -0
  620. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/README.md +209 -0
  621. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/SPEC.md +25 -0
  622. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/__init__.py +175 -0
  623. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/audit_supervisor.py +1015 -0
  624. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/budget_governor.py +1254 -0
  625. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_handler.py +368 -0
  626. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_pipeline.py +1564 -0
  627. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_sync.py +653 -0
  628. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/claim_events.py +74 -0
  629. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/claim_sync.py +590 -0
  630. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/cli.py +812 -0
  631. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/context_sync.py +55 -0
  632. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/coverage_sync.py +115 -0
  633. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_commit.py +470 -0
  634. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_sync.py +688 -0
  635. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_workflow.py +676 -0
  636. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finish_policy.py +224 -0
  637. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finish_sync.py +185 -0
  638. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/graph_sync.py +669 -0
  639. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/lease_manager.py +788 -0
  640. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/lifecycle_blocks.py +129 -0
  641. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/next_round_sync.py +126 -0
  642. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/observability.py +140 -0
  643. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/recovery_sync.py +165 -0
  644. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/rejection_remedies.py +355 -0
  645. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/round_governor.py +306 -0
  646. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/serial_authorization.py +544 -0
  647. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/start_sync.py +87 -0
  648. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/state_store.py +249 -0
  649. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/supervisor_host.py +511 -0
  650. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/supervisor_models.py +1143 -0
  651. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/systemic_failure.py +104 -0
  652. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/task_scheduler.py +1640 -0
  653. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_checkpoint.py +230 -0
  654. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_execution.py +265 -0
  655. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_handoff.py +192 -0
  656. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_lifecycle.py +396 -0
  657. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_runtime.py +1005 -0
  658. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_sync.py +89 -0
  659. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/README.md +36 -0
  660. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/__init__.py +0 -0
  661. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/exceptions.py +52 -0
  662. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/graph_models.py +357 -0
  663. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/path_containment.py +151 -0
  664. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/target_fingerprint.py +310 -0
  665. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/worker_claim.py +411 -0
  666. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/INTERFACE.md +50 -0
  667. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/README.md +57 -0
  668. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/SPEC.md +26 -0
  669. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/__init__.py +11 -0
  670. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/__init__.py +27 -0
  671. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/base.py +87 -0
  672. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/bugx.py +102 -0
  673. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/claude.py +222 -0
  674. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/cline.py +407 -0
  675. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/codex.py +260 -0
  676. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/dsh.py +177 -0
  677. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/opencode.py +218 -0
  678. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/pi.py +272 -0
  679. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/registry.py +100 -0
  680. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/zcode.py +312 -0
  681. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/api_routes_post.py +668 -0
  682. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/dispatcher.py +1376 -0
  683. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/docs_session_service.py +473 -0
  684. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/handler.py +674 -0
  685. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/ide_cloud_service.py +526 -0
  686. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/mcp_inspector.py +1747 -0
  687. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/00-base.css +1060 -0
  688. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/01-monitoring.css +802 -0
  689. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/02-header-actions.css +321 -0
  690. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/03-trigger-popover.css +697 -0
  691. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/04-composer.css +628 -0
  692. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/05-skills-center.css +878 -0
  693. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/06-mcp-center.css +623 -0
  694. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/07-skill-detail.css +265 -0
  695. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/08-files-management.css +167 -0
  696. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/09-files-center.css +386 -0
  697. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/10-icons.css +105 -0
  698. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/11-project-options.css +185 -0
  699. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/12-profile-tab.css +383 -0
  700. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/index-CXAsl8mr.js +333 -0
  701. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/index-DHQUtWtx.css +1 -0
  702. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
  703. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
  704. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
  705. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
  706. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
  707. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
  708. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
  709. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
  710. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
  711. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
  712. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
  713. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
  714. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
  715. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
  716. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
  717. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
  718. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
  719. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
  720. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
  721. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
  722. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
  723. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
  724. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
  725. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
  726. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/design-tokens.css +113 -0
  727. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/favicon.png +0 -0
  728. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/icon-192.png +0 -0
  729. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/index.html +55 -0
  730. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/manifest.webmanifest +19 -0
  731. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/project-settings.js +9602 -0
  732. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/sw.js +8 -0
  733. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/workspace_service.py +218 -0
  734. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/agents/bugx.md +27 -0
  735. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/dsh-patch.yml +18 -0
  736. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/cordis.patch.yml +4 -0
  737. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/index.js +219 -0
  738. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/package.json +28 -0
  739. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/skills/bugx/SKILL.md +70 -0
  740. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/skills/bugx-dsh/SKILL.md +229 -0
  741. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/client.js +87 -0
  742. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/cordis.patch.yml +4 -0
  743. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/index.js +7 -0
  744. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/package.json +27 -0
  745. bugx_cli-0.1.1.data/data/share/bugx-agent/mcp-lock.json +3075 -0
  746. bugx_cli-0.1.1.data/data/share/bugx-agent/opencode.json +129 -0
  747. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/README.md +12 -0
  748. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/index.ts +299 -0
  749. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/manifest.json +11 -0
  750. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/skills/bugx/SKILL.md +69 -0
  751. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
  752. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
  753. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
  754. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/connector-meta.json +19 -0
  755. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/icon.png +0 -0
  756. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/skills/bugx/SKILL.md +70 -0
  757. bugx_cli-0.1.1.dist-info/METADATA +335 -0
  758. bugx_cli-0.1.1.dist-info/RECORD +762 -0
  759. bugx_cli-0.1.1.dist-info/WHEEL +5 -0
  760. bugx_cli-0.1.1.dist-info/entry_points.txt +2 -0
  761. bugx_cli-0.1.1.dist-info/licenses/LICENSE +55 -0
  762. bugx_cli-0.1.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1881 @@
1
+ #!/usr/bin/env python3
2
+ """BugX project runtime layout and recovery-safe path resolver."""
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import datetime as dt
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import re
11
+ import shutil
12
+ import tempfile
13
+ import threading
14
+ import time
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ SCHEMA_VERSION = 1
20
+ # Layout 2 removes the project-local executable engine. ``.bugx`` now stores
21
+ # only project state/configuration; executable assets are resolved from the
22
+ # trusted global engine by the CLI/bootstrap layer.
23
+ LAYOUT_VERSION = "2.0.0"
24
+ POLLING_ID_RE = re.compile(r"^polling-[0-9]{6,}$")
25
+ LIFECYCLE_ID_RE = re.compile(r"^lifecycle-[0-9]{6,}$")
26
+ VERSION_RE = re.compile(r"^\d+\.\d+\.\d+(?:\+[0-9A-Za-z.-]+)?$")
27
+
28
+ # 版本契约的**唯一**归一化规则(DES-17 单一实现来源)。
29
+ #
30
+ # 兼容边界是 `major.minor.patch`;预发布后缀(`rc1`/`beta2`…)与构建/本地
31
+ # 后缀(`+2`)都不构成不兼容跃迁,因此不参与契约比较。历史缺陷:门禁的
32
+ # `_normalize_cli_version` 把 `+build` 留在 base 组里,而 CLI 侧
33
+ # `_contract_version` 把它丢掉——同一份清单,`bugx doctor` 判"一致"、
34
+ # `bugx engine` 门禁判"不一致并拒绝启动",两条入口互相打脸。
35
+ CONTRACT_VERSION_RE = re.compile(
36
+ r"^v?(?P<base>\d+\.\d+\.\d+)"
37
+ r"(?:[-.]?(?:alpha|a|beta|b|rc)[-.]?\d+)?"
38
+ r"(?:\+[0-9A-Za-z.-]+)?$",
39
+ re.IGNORECASE,
40
+ )
41
+
42
+
43
+ def contract_version(value: object) -> str | None:
44
+ """Return the compatibility contract version (``x.y.z``).
45
+
46
+ 预发布与构建后缀被忽略:``0.1.1+2``、``0.1.0rc1``、``v0.1.0`` 都归一到
47
+ ``0.1.1``。这是门禁与 CLI 共用的唯一实现;任何一侧自行实现比较规则都会
48
+ 重新引入"两个入口结论相反"的缺陷。
49
+ """
50
+ if not isinstance(value, str):
51
+ return None
52
+ match = CONTRACT_VERSION_RE.fullmatch(value.strip())
53
+ return match.group("base") if match else None
54
+
55
+ # These names are data or preparation artifacts, not executable engine assets.
56
+ # Layout 2 keeps them under the project state tree; the project has no
57
+ # executable core link or snapshot.
58
+ PROJECT_OWNED_CORE_NAMES = frozenset({
59
+ "bug-log.md",
60
+ "mistake-book.md",
61
+ "lesson-ledger.json",
62
+ "lesson-ledger.json.lock",
63
+ "prep-record.md",
64
+ "module-coverage.md",
65
+ })
66
+
67
+ #: 同时是**项目数据名**与**引擎载荷模板**的文件名(D1 根因修正)。
68
+ #:
69
+ #: ``PROJECT_OWNED_CORE_NAMES`` 只说明「在项目树里这些文件属于用户数据,不进
70
+ #: 项目核心完整性校验」。历史缺陷:引擎安装器把同一份名单直接当成「全局引擎
71
+ #: 载荷剥离名单」,于是 ``~/.bugx/core/lesson-ledger.json``(内置知识种子模板)
72
+ #: 等模板从未被安装,而 ``project_init._initialize_project_ledger``、
73
+ #: ``launch_phases.common.LESSON_LEDGER_FILE``、``incident_eval.run`` 都要求
74
+ #: 该模板存在于引擎根 —— 新项目 ``pre`` 直接报「缺少内置知识种子」。
75
+ #:
76
+ #: 语义边界:**项目树**里这些名字永远是项目数据(照旧剥离/忽略);**引擎树**
77
+ #: 里它们是随包分发的只读模板(必须安装,安装后不得被运行态写坏)。
78
+ ENGINE_ASSET_SEED_NAMES = frozenset({
79
+ "lesson-ledger.json",
80
+ "bug-log.md",
81
+ "mistake-book.md",
82
+ })
83
+
84
+
85
+
86
+ class LayoutError(RuntimeError):
87
+ """The project runtime layout is missing, invalid, or unsafe."""
88
+
89
+
90
+ def _version_from_text(path: Path, pattern: re.Pattern[str],
91
+ *, allow_symlink: bool = False) -> str | None:
92
+ """Read a version marker without trusting malformed or symlinked files."""
93
+ if allow_symlink and path.is_symlink():
94
+ try:
95
+ path = path.resolve(strict=True)
96
+ except OSError:
97
+ return None
98
+ else:
99
+ _assert_no_symlink_components(path)
100
+ if not path.is_file():
101
+ return None
102
+ try:
103
+ match = pattern.search(path.read_text(encoding="utf-8"))
104
+ except (OSError, UnicodeError):
105
+ return None
106
+ value = match.group(1) if match else None
107
+ if value == "0.1.1":
108
+ value = os.environ.get("BUGX_VERSION", "0.1.1").strip()
109
+ return value if value and VERSION_RE.fullmatch(value) else None
110
+
111
+
112
+ def _version_from_json(path: Path, key: str) -> str | None:
113
+ """Read a version field from a trusted JSON object."""
114
+ _assert_no_symlink_components(path)
115
+ if path.is_symlink() or not path.is_file():
116
+ return None
117
+ try:
118
+ payload = json.loads(path.read_text(encoding="utf-8"))
119
+ except (OSError, UnicodeError, json.JSONDecodeError):
120
+ return None
121
+ value = payload.get(key) if isinstance(payload, dict) else None
122
+ return value if isinstance(value, str) and VERSION_RE.fullmatch(value) else None
123
+
124
+
125
+ # PERF-08:项目核心完整性校验的 (size, mtime_ns) 指纹缓存。
126
+ # 每次启动对 192 个引擎文件做 read_bytes()+sha256 约 443.7 ms(冷读)/ 14.5 ms
127
+ # (热读),其中 99% 的成本是重复哈希未变化的文件。缓存把「上次已与清单核对
128
+ # 通过」的文件指纹记在 .bugx/index/ 下,下次启动只做 stat();指纹变化(或缓存
129
+ # 缺失/损坏/清单变更)时仍回退到全量哈希——**判定强度不降低**。
130
+ #
131
+ # 残余理论盲点:攻击者改写文件后把 mtime 精确还原成缓存记录的值且保持 size
132
+ # 不变,可命中快速路径。为缩小该窗口,文件的 mtime 若晚于清单本身(说明它
133
+ # 在清单生成之后被动过)也强制重新哈希。
134
+ _INTEGRITY_STAT_CACHE_SCHEMA = 1
135
+ _INTEGRITY_STAT_CACHE_NAME = "engine-integrity-statcache.json"
136
+
137
+
138
+ def _integrity_stat_cache_path(root: Path) -> Path:
139
+ return bugx_root(root) / "index" / _INTEGRITY_STAT_CACHE_NAME
140
+
141
+
142
+ def _load_integrity_stat_cache(
143
+ root: Path, manifest_sha256: str,
144
+ ) -> dict[str, tuple[int, int, str]]:
145
+ """读取上次校验的 (size, mtime_ns, sha256) 指纹。
146
+
147
+ 任何异常(缺失、损坏、schema 不符、清单已变更)都返回空表,调用方随即
148
+ 回退到全量哈希——缓存失效必须是 fail-closed,绝不能反过来放宽判定。
149
+ """
150
+ path = _integrity_stat_cache_path(root)
151
+ try:
152
+ if path.is_symlink() or not path.is_file():
153
+ return {}
154
+ payload = json.loads(path.read_text(encoding="utf-8"))
155
+ except (OSError, UnicodeError, json.JSONDecodeError):
156
+ return {}
157
+ if not isinstance(payload, dict):
158
+ return {}
159
+ if payload.get("schema_version") != _INTEGRITY_STAT_CACHE_SCHEMA:
160
+ return {}
161
+ if payload.get("manifest_sha256") != manifest_sha256:
162
+ return {}
163
+ entries = payload.get("files")
164
+ if not isinstance(entries, dict):
165
+ return {}
166
+ result: dict[str, tuple[int, int, str]] = {}
167
+ for relative, entry in entries.items():
168
+ if not isinstance(relative, str) or not isinstance(entry, dict):
169
+ continue
170
+ size = entry.get("size")
171
+ mtime_ns = entry.get("mtime_ns")
172
+ sha = entry.get("sha256")
173
+ if isinstance(size, int) and isinstance(mtime_ns, int) and isinstance(sha, str):
174
+ result[relative] = (size, mtime_ns, sha)
175
+ return result
176
+
177
+
178
+ def _save_integrity_stat_cache(
179
+ root: Path, manifest_sha256: str,
180
+ fingerprints: dict[str, tuple[int, int, str]],
181
+ ) -> None:
182
+ """尽力持久化指纹缓存;写入失败(只读项目等)不影响本次判定结果。"""
183
+ payload = {
184
+ "schema_version": _INTEGRITY_STAT_CACHE_SCHEMA,
185
+ "manifest_sha256": manifest_sha256,
186
+ "files": {
187
+ relative: {"size": size, "mtime_ns": mtime_ns, "sha256": sha}
188
+ for relative, (size, mtime_ns, sha) in fingerprints.items()
189
+ },
190
+ }
191
+ try:
192
+ _atomic_json(_integrity_stat_cache_path(root), payload)
193
+ except (OSError, ValueError, LayoutError):
194
+ pass
195
+
196
+
197
+ def _project_core_files(project: Path) -> set[str]:
198
+ """Enumerate materialized compatibility-core files without following dirs."""
199
+ files: set[str] = set()
200
+ if not project.is_dir() or project.is_symlink():
201
+ return files
202
+ for path in project.rglob("*"):
203
+ if path.is_dir() or "__pycache__" in path.parts or path.suffix == ".pyc":
204
+ continue
205
+ relative = path.relative_to(project)
206
+ if relative.name in PROJECT_OWNED_CORE_NAMES or relative.name == "engine-integrity.json":
207
+ continue
208
+ files.add(relative.as_posix())
209
+ return files
210
+
211
+
212
+ def project_core_integrity_status(root: Path, engine_root: Path) -> dict[str, Any]:
213
+ """Report the removed project executable-engine surface.
214
+
215
+ Layout 2 deliberately does not hash or repair ``.bugx/core``. A project
216
+ that still has that path is an un-migrated legacy installation. The next
217
+ ``init`` or ``install`` deletes it after moving recognised project data.
218
+ A project without it is healthy: the global engine is checked by the
219
+ engine contract itself.
220
+ """
221
+ project = bugx_root(root) / "core"
222
+ try:
223
+ if project.is_symlink() or project.exists():
224
+ return {
225
+ "available": True,
226
+ "ok": False,
227
+ "detail": f"旧项目引擎入口仍存在: {project};运行 bugx init/install 将直接删除",
228
+ }
229
+ except OSError as exc:
230
+ return {"available": True, "ok": False, "detail": f"旧项目引擎入口无法检查: {exc}"}
231
+ return {
232
+ "available": True,
233
+ "ok": True,
234
+ "detail": "项目不包含可执行引擎;运行时统一使用全局引擎",
235
+ }
236
+
237
+
238
+ def version_status(root: Path, engine_root: Path,
239
+ *, cli_version: str | None = None) -> dict[str, Any]:
240
+ """Return the global-engine version contract for a running project."""
241
+ root = root.resolve()
242
+ engine_root = engine_root.resolve()
243
+ values: dict[str, str | None] = {
244
+ "cli": cli_version,
245
+ "engine_metadata": _version_from_text(
246
+ engine_root / "metadata.txt",
247
+ re.compile(
248
+ r'bugx_version:\s*"([\d.]+(?:\+[0-9A-Za-z.-]+)?|\$\{BUGX_VERSION\})"',
249
+ ),
250
+ ),
251
+ "engine_integrity": _version_from_json(
252
+ engine_root / "engine-integrity.json", "bugx_version",
253
+ ),
254
+ "engine_descriptor": _version_from_text(
255
+ engine_root / "bugx.md",
256
+ re.compile(
257
+ r"^version:\s*([\d.]+(?:\+[0-9A-Za-z.-]+)?|\$\{BUGX_VERSION\})",
258
+ re.M,
259
+ ),
260
+ ),
261
+ }
262
+ legacy_manifest = _version_from_json(
263
+ bugx_root(root) / "manifest.json", "bugx_version",
264
+ )
265
+ project_layout = _version_from_text(
266
+ bugx_root(root) / "manifest.json",
267
+ re.compile(r'"layout_version"\s*:\s*"([\d.]+)"'),
268
+ )
269
+ # 契约比较只看 x.y.z,忽略预发布/构建后缀——与 CLI 侧(doctor)共用
270
+ # `contract_version` 这一条规则,避免两条入口对同一份清单给出相反结论。
271
+ contract_values = {
272
+ name: contract_version(value) for name, value in values.items()
273
+ }
274
+ contract_manifest = contract_version(legacy_manifest)
275
+ errors: list[str] = []
276
+ for name, value in values.items():
277
+ if value is None:
278
+ errors.append(f"{name}=missing_or_invalid")
279
+ if project_layout != LAYOUT_VERSION:
280
+ errors.append(
281
+ f"project_layout={project_layout or 'missing'}(项目状态格式应为 {LAYOUT_VERSION})"
282
+ )
283
+ distinct = sorted({value for value in contract_values.values() if value is not None})
284
+ project_integrity = project_core_integrity_status(root, engine_root)
285
+ if project_integrity.get("available") and not project_integrity.get("ok"):
286
+ errors.append("project_core_integrity=failed")
287
+ if len(distinct) > 1:
288
+ errors.append("版本不一致")
289
+ if legacy_manifest is not None and distinct and contract_manifest not in distinct:
290
+ errors.append(f"project_manifest={legacy_manifest}(与核心版本不一致)")
291
+ if errors:
292
+ detail = ";".join(errors)
293
+ else:
294
+ detail = f"所有核心版本标记一致:{distinct[0]}"
295
+ return {
296
+ "consistent": not errors,
297
+ "versions": values,
298
+ "legacy_versions": {
299
+ "project_manifest": legacy_manifest,
300
+ "project_layout": project_layout,
301
+ },
302
+ "errors": errors,
303
+ "detail": detail,
304
+ "project_core_integrity": project_integrity,
305
+ }
306
+
307
+
308
+ def utc_now() -> str:
309
+ return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
310
+
311
+
312
+ def project_root(script_dir: Path | None = None) -> Path:
313
+ override = os.environ.get("BUGX_PROJECT_ROOT")
314
+ if override:
315
+ root = Path(override).expanduser().resolve()
316
+ if not root.is_dir():
317
+ raise LayoutError(f"BUGX_PROJECT_ROOT 不是目录: {root}")
318
+ return root
319
+ directory = (script_dir or Path(__file__).resolve()).resolve()
320
+ # DOC-004 Engine-State Separation:静态协议脚本位于全局引擎
321
+ # ~/.bugx/core,其父目录名也是 .bugx,与目录名检测冲突——必须
322
+ # 优先判定。命中全局引擎时回退到 cwd(调用方已 cd 到项目根),
323
+ # 与 BUGX_PROJECT_ROOT 显式覆盖共同保证正确性。
324
+ global_engine_marker = Path.home() / ".bugx" / "core"
325
+ if (
326
+ directory == global_engine_marker
327
+ or directory.is_relative_to(global_engine_marker)
328
+ ):
329
+ return Path.cwd().resolve()
330
+ if directory.name == "core" and directory.parent.name == ".bugx":
331
+ return directory.parent.parent
332
+ return Path.cwd().resolve()
333
+
334
+
335
+ def bugx_root(root: Path) -> Path:
336
+ return root.resolve() / ".bugx"
337
+
338
+
339
+ def project_knowledge_root(root: Path) -> Path:
340
+ return bugx_root(root) / "knowledge"
341
+
342
+
343
+ def global_knowledge_root() -> Path:
344
+ override = os.environ.get("BUGX_GLOBAL_KNOWLEDGE_ROOT")
345
+ return (Path(override).expanduser() if override else Path.home() / ".bugx" / "knowledge").resolve()
346
+
347
+
348
+ def global_engine_root() -> Path:
349
+ """Return the trusted global BugX engine root directory."""
350
+ override = os.environ.get("BUGX_GLOBAL_ENGINE_ROOT")
351
+ return (Path(override).expanduser() if override else Path.home() / ".bugx" / "core").resolve()
352
+
353
+
354
+ def global_skills_dir() -> Path:
355
+ """Return the global skills directory without creating it."""
356
+ override = os.environ.get("BUGX_GLOBAL_SKILLS_DIR")
357
+ return (Path(override).expanduser() if override else Path.home() / ".bugx" / "skills").resolve()
358
+
359
+
360
+ def global_cache_root() -> Path:
361
+ """Return the per-user cache root without creating or resolving it."""
362
+ override = os.environ.get("BUGX_GLOBAL_CACHE_ROOT")
363
+ return Path(override).expanduser() if override else Path.home() / ".bugx" / "cache"
364
+
365
+
366
+ def global_telemetry_root() -> Path:
367
+ override = os.environ.get("BUGX_GLOBAL_TELEMETRY_ROOT")
368
+ if override:
369
+ return Path(override).expanduser().resolve()
370
+ knowledge_override = os.environ.get("BUGX_GLOBAL_KNOWLEDGE_ROOT")
371
+ if knowledge_override:
372
+ return (Path(knowledge_override).expanduser().resolve().parent / "telemetry").resolve()
373
+ return (Path.home() / ".bugx" / "telemetry").resolve()
374
+
375
+
376
+ def global_telemetry_path() -> Path:
377
+ override = os.environ.get("BUGX_GLOBAL_TELEMETRY_PATH")
378
+ if override:
379
+ return Path(override).expanduser().resolve()
380
+ return global_telemetry_root() / "stats.sqlite3"
381
+
382
+
383
+ def is_reparse_point(path: Path) -> bool:
384
+ """Return whether ``path`` is a symlink, a Windows junction, or a reparse point.
385
+
386
+ DES-17:这是符号链接防越界的**唯一平台分支**。POSIX 上
387
+ ``is_symlink()`` 已足够;Windows 上 junction 与其它 reparse point
388
+ 同样是可被用来把写入重定向到边界之外的目录重定向,必须一并拒绝,
389
+ 否则同一条安全路径在 Windows 上会被绕过。
390
+ """
391
+ if path.is_symlink():
392
+ return True
393
+ is_junction = getattr(path, "is_junction", None)
394
+ if callable(is_junction) and is_junction():
395
+ return True
396
+ if os.name != "nt":
397
+ return False
398
+ try:
399
+ import ctypes
400
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
401
+ get_attributes = kernel32.GetFileAttributesW
402
+ get_attributes.argtypes = [ctypes.c_wchar_p]
403
+ get_attributes.restype = ctypes.c_uint32
404
+ attributes = get_attributes(str(path))
405
+ if attributes == 0xFFFFFFFF:
406
+ # 路径不存在(2/3)不算 reparse;其它错误保守视为不安全。
407
+ return ctypes.get_last_error() not in (2, 3)
408
+ return bool(attributes & 0x400) # FILE_ATTRIBUTE_REPARSE_POINT
409
+ except (AttributeError, OSError, ValueError):
410
+ return False
411
+
412
+
413
+ def _system_alias(path: Path) -> Path | None:
414
+ """Return the real path for macOS's harmless ``/tmp`` and ``/var`` aliases.
415
+
416
+ 这两个别名是系统安装时就存在的(``/tmp -> /private/tmp``、
417
+ ``/var -> /private/var``),普通用户无法创建或篡改,不构成写入越界的
418
+ 攻击面;把它们当成攻击特征会让「HOME 落在 /tmp」的隔离环境(mktemp
419
+ 沙箱、CI)彻底装不了引擎。
420
+
421
+ 判定必须**精确**:只有「父目录就是根、名字恰为 tmp/var、且确实解析到
422
+ ``/private/<name>``」才算系统别名。用户区里的同名目录、以及其它顶层
423
+ 符号链接(``/opt`` 之类)一律按普通符号链接拒绝——这正是旧实现
424
+ (``current.parent == anchor`` 不限名字)过宽的地方。
425
+ """
426
+ if path.parent != Path(path.anchor) or path.name not in {"tmp", "var"}:
427
+ return None
428
+ try:
429
+ resolved = path.resolve(strict=True)
430
+ except OSError:
431
+ return None
432
+ expected = Path("/private") / path.name
433
+ return resolved if resolved == expected else None
434
+
435
+
436
+ def assert_no_symlink_components(
437
+ path: Path,
438
+ error_cls: type[Exception] = LayoutError,
439
+ message_formatter: Any = None,
440
+ allow_var_alias: bool = True,
441
+ ) -> None:
442
+ """Reject a path whose existing parent or target component is a symlink.
443
+
444
+ ``Path.resolve()`` alone is insufficient: it follows the link before the
445
+ confinement check and can therefore make an escaped path look legitimate.
446
+ This check is intentionally lexical and runs before every runtime mkdir or
447
+ atomic replace performed by this module.
448
+
449
+ DES-17:组件判定统一走 :func:`is_reparse_point`,Windows 上同时覆盖
450
+ junction / reparse point;``src/bugx_cli/infra/security.py`` 与
451
+ ``core/verify_life.py`` 均委托到本函数,不再各自维护一份实现。
452
+
453
+ ``allow_var_alias`` 豁免的是 :func:`_system_alias` 认定的**系统别名**
454
+ (精确到 ``/tmp``、``/var`` 解析到 ``/private/<name>``),不是「任意顶层
455
+ 符号链接」。``core/secure_atomic.reject_symlink_components`` 一直按这个
456
+ 语义判定,此前本函数用「父目录是根」做条件,两者口径不一致,导致同一
457
+ 路径在安装器里被拒、在原子写入里被接受。
458
+ """
459
+ absolute = Path(os.path.abspath(str(path)))
460
+ current = Path(absolute.anchor)
461
+ for component in absolute.parts[1:]:
462
+ current /= component
463
+ if is_reparse_point(current):
464
+ if allow_var_alias and _system_alias(current) is not None:
465
+ continue
466
+ if callable(message_formatter):
467
+ err_msg = message_formatter(current, path)
468
+ elif isinstance(message_formatter, str):
469
+ err_msg = message_formatter
470
+ elif error_cls.__name__ == "SyncStoreError":
471
+ err_msg = f"sync store 路径包含符号链接: {current}"
472
+ elif error_cls.__name__ == "CliError":
473
+ err_msg = f"拒绝通过符号链接写入: {path}"
474
+ elif error_cls.__name__ in ("LessonLedgerError", "OSError"):
475
+ err_msg = f"拒绝使用符号链接路径组件: {path}"
476
+ else:
477
+ err_msg = f"拒绝使用符号链接路径组件: {current}"
478
+ raise error_cls(err_msg)
479
+
480
+
481
+ _assert_no_symlink_components = assert_no_symlink_components
482
+
483
+
484
+ def ensure_dir(path: Path, mode: int | None = None) -> Path:
485
+ """Create ``path`` if it is not already a directory.
486
+
487
+ ``Path.mkdir(exist_ok=True)`` is the idiomatic form, but it is not portable
488
+ across the brokered filesystems BugX runs inside: some host shims replace
489
+ ``Path.mkdir`` with a version that raises ``PermissionError: EEXIST`` when
490
+ the target already exists instead of honouring ``exist_ok``. Since BugX is
491
+ designed to run *inside* sandboxed hosts, the explicit ``is_dir`` pre-check
492
+ keeps directory setup idempotent there as well.
493
+ """
494
+ if path.is_dir():
495
+ return path
496
+ if mode is None:
497
+ path.mkdir(parents=True, exist_ok=True)
498
+ else:
499
+ path.mkdir(mode=mode, parents=True, exist_ok=True)
500
+ return path
501
+
502
+
503
+ def confined_regular_file(
504
+ root: Path,
505
+ raw_path: str | Path,
506
+ *,
507
+ error_cls: type[Exception] = LayoutError,
508
+ ) -> Path:
509
+ """Resolve ``raw_path`` inside ``root`` and prove it is a regular file.
510
+
511
+ ``resolve() + relative_to()`` alone is not enough: ``resolve`` follows
512
+ symlinks *before* the boundary check, so a link inside the project can make
513
+ an out-of-tree file look legitimate. This helper therefore checks the
514
+ lexical path first, then every component for symlinks, and only then
515
+ canonicalises. It is the single entry point for "read a project file named
516
+ by untrusted input" (BugX audits other people's repositories, so every path
517
+ that arrives over MCP or from a project artifact is untrusted).
518
+ """
519
+ root_raw = Path(os.path.abspath(str(Path(root))))
520
+ root_resolved = Path(root).resolve()
521
+ raw = Path(raw_path)
522
+ candidate = raw if raw.is_absolute() else root_raw / raw
523
+ resolved = candidate.resolve()
524
+
525
+ # Canonical confinement is authoritative: a link inside the project that
526
+ # points outside resolves to an outside path and is rejected here.
527
+ try:
528
+ resolved.relative_to(root_resolved)
529
+ except ValueError as exc:
530
+ raise error_cls(f"路径必须位于项目根目录内: {raw_path}") from exc
531
+ if resolved == root_resolved:
532
+ raise error_cls(f"路径必须指向项目内的文件: {raw_path}")
533
+
534
+ # Refuse symlinked components as well (stronger than the boundary check:
535
+ # a link that still resolves inside the project is refused too, because it
536
+ # can be swapped between this check and the read).
537
+ #
538
+ # When the caller used a system alias (macOS ``/var`` -> ``/private/var``)
539
+ # the raw and canonical spellings share no lexical prefix, so only the
540
+ # canonical confinement above applies; otherwise walk the raw in-project
541
+ # components.
542
+ lexical = Path(os.path.abspath(str(candidate)))
543
+ try:
544
+ raw_relative = lexical.relative_to(root_raw)
545
+ except ValueError:
546
+ raw_relative = None
547
+ if raw_relative is not None:
548
+ current = root_raw
549
+ for part in raw_relative.parts:
550
+ current /= part
551
+ if current.is_symlink():
552
+ raise error_cls(f"路径不能包含符号链接: {raw_path}")
553
+
554
+ if not resolved.is_file():
555
+ raise error_cls(f"路径不是普通文件: {raw_path}")
556
+ return resolved
557
+
558
+
559
+ def read_confined_bytes(
560
+ root: Path,
561
+ raw_path: str | Path,
562
+ *,
563
+ max_bytes: int | None = None,
564
+ error_cls: type[Exception] = LayoutError,
565
+ ) -> bytes:
566
+ """Read a project-confined regular file with an optional size ceiling.
567
+
568
+ The ceiling is enforced *after* reading only because a regular file cannot
569
+ be safely pre-sized for the caller's purpose; callers that need a hard
570
+ memory bound must pass ``max_bytes`` and treat the failure as fatal.
571
+ """
572
+ path = confined_regular_file(root, raw_path, error_cls=error_cls)
573
+ if max_bytes is not None and max_bytes > 0:
574
+ try:
575
+ size = path.stat().st_size
576
+ except OSError as exc:
577
+ raise error_cls(f"无法读取文件大小: {raw_path}") from exc
578
+ if size > max_bytes:
579
+ raise error_cls(f"文件超过大小上限({size} > {max_bytes}): {raw_path}")
580
+ try:
581
+ return path.read_bytes()
582
+ except OSError as exc:
583
+ raise error_cls(f"无法读取文件: {raw_path}") from exc
584
+
585
+
586
+ def _validate_identifier(value: object, kind: str) -> str:
587
+ if not isinstance(value, str):
588
+ raise LayoutError(f"{kind} 标识无效: {value!r}")
589
+ pattern = POLLING_ID_RE if kind == "polling" else LIFECYCLE_ID_RE
590
+ if not pattern.fullmatch(value):
591
+ raise LayoutError(f"{kind} 标识无效: {value!r}")
592
+ return value
593
+
594
+
595
+ def _id_path(root: Path, value: str, kind: str) -> Path:
596
+ identifier = _validate_identifier(value, kind)
597
+ candidate = root / identifier
598
+ _assert_no_symlink_components(root)
599
+ _assert_no_symlink_components(candidate)
600
+ try:
601
+ candidate.resolve(strict=False).relative_to(root.resolve())
602
+ except ValueError as exc: # defensive: the identifier regex must be enough
603
+ raise LayoutError(f"{kind} 路径越出受控目录: {value!r}") from exc
604
+ return candidate
605
+
606
+
607
+ def _atomic_json(path: Path, payload: dict[str, Any]) -> None:
608
+ _assert_no_symlink_components(path.parent)
609
+ path.parent.mkdir(parents=True, exist_ok=True)
610
+ _assert_no_symlink_components(path)
611
+ fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
612
+ try:
613
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
614
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
615
+ handle.write("\n")
616
+ os.chmod(temporary, 0o600)
617
+ os.replace(temporary, path)
618
+ except BaseException:
619
+ try:
620
+ os.unlink(temporary)
621
+ except OSError:
622
+ pass
623
+ raise
624
+
625
+
626
+ def _read_json(path: Path) -> dict[str, Any]:
627
+ _assert_no_symlink_components(path)
628
+ if path.is_symlink() or not path.is_file():
629
+ raise LayoutError(f"缺少或不安全的布局文件: {path}")
630
+ try:
631
+ value = json.loads(path.read_text(encoding="utf-8"))
632
+ except (OSError, json.JSONDecodeError) as exc:
633
+ raise LayoutError(f"布局文件无法解析: {path}: {exc}") from exc
634
+ if not isinstance(value, dict):
635
+ raise LayoutError(f"布局文件必须是对象: {path}")
636
+ return value
637
+
638
+
639
+ _PROJECT_LOCK_THREAD = threading.RLock()
640
+
641
+
642
+ @contextlib.contextmanager
643
+ def _project_lock(root: Path, timeout: float = 10.0):
644
+ """项目级互斥:串行化 Session 创建与 current/ manifest 变更。
645
+
646
+ 在 ``.bugx/locks/project.lock`` 上使用 ``fcntl.flock``(POSIX)或
647
+ ``msvcrt.locking``(Windows)实现跨进程互斥;缺一不可时显式阻断而非
648
+ 静默无锁,避免并发复用同一 Session 编号。进程内再用线程锁避免同进程
649
+ 重入竞争。
650
+ """
651
+ root = root.resolve()
652
+ base = bugx_root(root)
653
+ _assert_no_symlink_components(base)
654
+ locks_dir = base / "locks"
655
+ # locks 目录在并发初始化时可能不存在,创建放在线程锁外但需校验
656
+ # 符号链接,避免把锁文件建在被劫持的目录。
657
+ locks_dir.mkdir(parents=True, exist_ok=True)
658
+ _assert_no_symlink_components(locks_dir)
659
+ try:
660
+ os.chmod(locks_dir, 0o700)
661
+ except OSError:
662
+ pass
663
+ lock_path = locks_dir / "project.lock"
664
+ _assert_no_symlink_components(lock_path.parent)
665
+ if lock_path.is_symlink():
666
+ raise LayoutError(f"拒绝使用符号链接锁文件: {lock_path}")
667
+ # 线程内串行化,避免同进程多线程同时抢文件锁
668
+ with _PROJECT_LOCK_THREAD:
669
+ if lock_path.is_symlink():
670
+ raise LayoutError(f"拒绝使用符号链接锁文件: {lock_path}")
671
+ # O_NOFOLLOW closes the check-then-open symlink race on POSIX. The
672
+ # explicit pre-check remains useful on platforms without the flag;
673
+ # either way, never follow a lock path supplied by an attacker.
674
+ open_flags = os.O_RDWR | os.O_CREAT
675
+ nofollow = getattr(os, "O_NOFOLLOW", 0)
676
+ try:
677
+ descriptor = os.open(str(lock_path), open_flags | nofollow, 0o600)
678
+ except OSError as exc:
679
+ raise LayoutError(f"无法安全打开项目锁: {lock_path}") from exc
680
+ handle = os.fdopen(descriptor, "a+")
681
+ try:
682
+ try:
683
+ import fcntl as _fcntl
684
+ except ImportError:
685
+ _fcntl = None # type: ignore[assignment]
686
+ try:
687
+ import msvcrt as _msvcrt
688
+ except ImportError:
689
+ _msvcrt = None # type: ignore[assignment]
690
+ if _fcntl is not None:
691
+ deadline = time.monotonic() + timeout
692
+ while True:
693
+ try:
694
+ _fcntl.flock(handle.fileno(), _fcntl.LOCK_EX | _fcntl.LOCK_NB)
695
+ break
696
+ except BlockingIOError:
697
+ if time.monotonic() >= deadline:
698
+ raise LayoutError("项目锁等待超时")
699
+ time.sleep(0.01)
700
+ elif _msvcrt is not None:
701
+ deadline = time.monotonic() + timeout
702
+ while True:
703
+ try:
704
+ _msvcrt.locking(handle.fileno(), _msvcrt.LK_NBLCK, 1)
705
+ break
706
+ except OSError:
707
+ if time.monotonic() >= deadline:
708
+ raise LayoutError("项目锁等待超时")
709
+ time.sleep(0.01)
710
+ else: # pragma: no cover - 无任何可用锁原语的平台
711
+ raise LayoutError("项目锁在当前平台不可用(fcntl 和 msvcrt 均缺失),拒绝并发不安全写")
712
+ yield
713
+ finally:
714
+ try:
715
+ if _fcntl is not None:
716
+ _fcntl.flock(handle.fileno(), _fcntl.LOCK_UN)
717
+ elif _msvcrt is not None:
718
+ try:
719
+ _msvcrt.locking(handle.fileno(), _msvcrt.LK_UNLCK, 1)
720
+ except OSError:
721
+ pass
722
+ finally:
723
+ handle.close()
724
+
725
+
726
+ def _validate_polling_manifest(root: Path, polling_id: str, expected_no: int | None = None) -> dict[str, Any]:
727
+ """校验 polling manifest 与磁盘指针一致性。"""
728
+ base = bugx_root(root)
729
+ polling_root = _id_path(base / "pollings", polling_id, "polling")
730
+ if not polling_root.is_dir() or polling_root.is_symlink():
731
+ raise LayoutError(f"polling 目录缺失或不安全: {polling_root}")
732
+ manifest_path = polling_root / "manifest.json"
733
+ payload = _read_json(manifest_path)
734
+ if payload.get("polling_id") != polling_id:
735
+ raise LayoutError(f"polling manifest 归属不一致: {polling_id}")
736
+ if payload.get("schema_version") != SCHEMA_VERSION:
737
+ raise LayoutError(f"polling manifest schema_version 不受支持: {manifest_path}")
738
+ polling_no = payload.get("polling_no")
739
+ if isinstance(polling_no, bool) or not isinstance(polling_no, int) or polling_no < 1:
740
+ raise LayoutError(f"polling manifest polling_no 无效: {manifest_path}")
741
+ if expected_no is not None and polling_no != expected_no:
742
+ raise LayoutError(f"polling_no 指针不一致: manifest={polling_no} vs expected={expected_no}")
743
+ # polling state 也作为指针完整性的一部分
744
+ state_path = polling_root / "state.json"
745
+ if not state_path.is_file() or state_path.is_symlink():
746
+ raise LayoutError(f"polling state 缺失或不安全: {state_path}")
747
+ state = _read_json(state_path)
748
+ if state.get("polling_id") != polling_id:
749
+ raise LayoutError(f"polling state 归属不一致: {polling_id}")
750
+ return payload
751
+
752
+
753
+ def _validate_lifecycle_manifest(root: Path, polling_id: str, lifecycle_id: str,
754
+ expected_no: int | None = None) -> dict[str, Any]:
755
+ """校验 lifecycle manifest 归属与编号。"""
756
+ base = bugx_root(root)
757
+ polling_root = _id_path(base / "pollings", polling_id, "polling")
758
+ lifecycle_root = _id_path(polling_root / "lifecycles", lifecycle_id, "lifecycle")
759
+ if not lifecycle_root.is_dir() or lifecycle_root.is_symlink():
760
+ raise LayoutError(f"lifecycle 目录缺失或不安全: {lifecycle_root}")
761
+ manifest_path = lifecycle_root / "manifest.json"
762
+ payload = _read_json(manifest_path)
763
+ if payload.get("polling_id") != polling_id:
764
+ raise LayoutError(f"lifecycle manifest polling 归属不一致: {lifecycle_id} not in {polling_id}")
765
+ if payload.get("lifecycle_id") != lifecycle_id:
766
+ raise LayoutError(f"lifecycle manifest 标识不一致: {lifecycle_id}")
767
+ if payload.get("schema_version") != SCHEMA_VERSION:
768
+ raise LayoutError(f"lifecycle manifest schema_version 不受支持: {manifest_path}")
769
+ lifecycle_no = payload.get("lifecycle_no")
770
+ if isinstance(lifecycle_no, bool) or not isinstance(lifecycle_no, int) or lifecycle_no < 1:
771
+ raise LayoutError(f"lifecycle manifest lifecycle_no 无效: {manifest_path}")
772
+ if expected_no is not None and lifecycle_no != expected_no:
773
+ raise LayoutError(f"lifecycle_no 指针不一致: manifest={lifecycle_no} vs expected={expected_no}")
774
+ # lifecycle state
775
+ state_path = lifecycle_root / "state.json"
776
+ if not state_path.is_file() or state_path.is_symlink():
777
+ raise LayoutError(f"lifecycle state 缺失或不安全: {state_path}")
778
+ state = _read_json(state_path)
779
+ if state.get("lifecycle_id") != lifecycle_id:
780
+ raise LayoutError(f"lifecycle state 标识不一致: {lifecycle_id}")
781
+ return payload
782
+
783
+
784
+ #: ``.bugx`` 里持久化项目身份的键(清单与索引各存一份,互为交叉校验)。
785
+ PROJECT_UID_KEY = "project_uid"
786
+
787
+
788
+ def _path_fingerprint(root: Path) -> str:
789
+ """根路径哈希——只作为**旧布局**(无 uid)的身份,以及新布局 uid 的初值。"""
790
+ return hashlib.sha256(str(root.resolve()).encode("utf-8")).hexdigest()[:16]
791
+
792
+
793
+ def _new_project_uid(root: Path) -> str:
794
+ """生成与路径无关的项目身份(首次初始化时落盘,此后不再随路径变化)。
795
+
796
+ 缺陷 #10:``project_id`` 原本恒为 ``sha256(根路径)[:16]``,于是项目目录被
797
+ 搬移/改名/换机恢复后,``require()`` 直接抛「.bugx 与当前项目不匹配」,而
798
+ 错误给出的唯一出路是 ``rm -rf .bugx``——账本、知识库、报告全部作废。
799
+ 身份必须随布局持久化,不能从路径反推。
800
+ """
801
+ return _path_fingerprint(root)
802
+
803
+
804
+ def _read_index_uid(base: Path) -> str:
805
+ """读索引里记录的项目身份;缺失/损坏时返回空串。"""
806
+ try:
807
+ index_path = base / "index" / "index.json"
808
+ if index_path.is_file() and not index_path.is_symlink():
809
+ value = _read_json(index_path).get(PROJECT_UID_KEY)
810
+ return value.strip() if isinstance(value, str) else ""
811
+ except (OSError, ValueError, LayoutError):
812
+ return ""
813
+ return ""
814
+
815
+
816
+ def _project_id(root: Path) -> str:
817
+ """项目身份:优先取持久化的 ``project_uid``,旧布局退回路径指纹。
818
+
819
+ 新布局一旦落盘 uid,身份就与路径解绑——搬移目录后 ``project_id`` 不变。
820
+ 旧布局(无 uid)保持原有路径哈希语义,行为与历史完全一致。
821
+ """
822
+ base = bugx_root(root)
823
+ try:
824
+ manifest_path = base / "manifest.json"
825
+ if manifest_path.is_file() and not manifest_path.is_symlink():
826
+ persisted = _read_json(manifest_path).get(PROJECT_UID_KEY)
827
+ if isinstance(persisted, str) and persisted.strip():
828
+ return persisted.strip()
829
+ except (OSError, ValueError, LayoutError):
830
+ # 清单读不出来时退回路径指纹:真正的诊断由 initialize/require 各自报出,
831
+ # 身份计算这一层不吞错也不越权。
832
+ pass
833
+ return _path_fingerprint(root)
834
+
835
+
836
+ def _identity_mismatch(root: Path, manifest: dict) -> bool:
837
+ """``.bugx`` 是否属于**当前**根(fail-closed 判据)。
838
+
839
+ 判定依旧锚定路径指纹:把 ``.bugx`` 拷进另一个项目必须被拒绝——清单只是
840
+ 元数据,而账本、知识库、pollings 报告全在目录里,自动放行等于让源项目的
841
+ 洞察/错题集/机密静默流进目标项目(B4 红线契约,以本注释为准)。
842
+
843
+ 可移植性由**显式迁移**提供,而不是自动放行:``bugx project rebind --migrate``
844
+ 把 ``project_id`` 重写为新根指纹,并保留持久化的 ``project_uid``——于是项目
845
+ 搬移后身份(云端 wire id、全局工程表)连续,同时"串用他人布局"仍然被拒。
846
+ """
847
+ return manifest.get("project_id") != _path_fingerprint(root)
848
+
849
+
850
+ def _scope_root(root: Path, polling_id: str, lifecycle_id: str) -> Path:
851
+ polling_root = _id_path(bugx_root(root) / "pollings", polling_id, "polling")
852
+ lifecycle_root = _id_path(polling_root / "lifecycles", lifecycle_id, "lifecycle")
853
+ return lifecycle_root
854
+
855
+
856
+ @dataclass(frozen=True)
857
+ class Scope:
858
+ root: Path
859
+ polling_root: Path
860
+ session_state: Path
861
+ lifecycle_root: Path
862
+ state_root: Path
863
+ locks_root: Path
864
+ life: Path
865
+ life_snapshot: Path
866
+ life_lock: Path
867
+ runtime: Path
868
+ runtime_lock: Path
869
+ supervisor: Path
870
+ supervisor_lock: Path
871
+ coverage: Path
872
+ prep_record: Path
873
+ events: Path
874
+ conclusion: Path
875
+ report: Path
876
+ integrity: Path
877
+ knowledge_root: Path
878
+ knowledge_seed: Path
879
+ knowledge_db: Path
880
+ bug_log: Path
881
+ mistake_book: Path
882
+ global_knowledge_root: Path
883
+ global_knowledge_seed: Path
884
+ global_knowledge_db: Path
885
+ logs_root: Path
886
+ diagnostic_log: Path
887
+
888
+
889
+ def scope(root: Path, current: dict[str, Any] | None = None) -> Scope:
890
+ root = root.resolve()
891
+ current = current or read_current(root)
892
+ polling_id = current.get("polling_id")
893
+ lifecycle_id = current.get("lifecycle_id")
894
+ if not isinstance(polling_id, str) or not isinstance(lifecycle_id, str):
895
+ raise LayoutError("current.json 缺少 polling_id 或 lifecycle_id")
896
+ polling_root = _id_path(bugx_root(root) / "pollings", polling_id, "polling")
897
+ lifecycle_root = _scope_root(root, polling_id, lifecycle_id)
898
+ state_root = lifecycle_root / "state"
899
+ locks_root = state_root / "locks"
900
+ return Scope(
901
+ root=root,
902
+ polling_root=polling_root,
903
+ session_state=polling_root / "state.json",
904
+ lifecycle_root=lifecycle_root,
905
+ state_root=state_root,
906
+ locks_root=locks_root,
907
+ life=state_root / "life.json",
908
+ life_snapshot=state_root / "snapshots" / "life.snapshot.json",
909
+ life_lock=locks_root / "life.lock",
910
+ runtime=state_root / "runtime.json",
911
+ runtime_lock=locks_root / "runtime.lock",
912
+ supervisor=state_root / "supervisor.json",
913
+ supervisor_lock=locks_root / "supervisor.lock",
914
+ coverage=state_root / "coverage-evidence.json",
915
+ prep_record=state_root / "prep-record.md",
916
+ events=lifecycle_root / "events.jsonl",
917
+ conclusion=lifecycle_root / "conclusion.json",
918
+ report=lifecycle_root / "report.md",
919
+ integrity=lifecycle_root / "integrity.json",
920
+ knowledge_root=project_knowledge_root(root),
921
+ knowledge_seed=project_knowledge_root(root) / "lesson-ledger.json",
922
+ knowledge_db=project_knowledge_root(root) / "lesson-ledger.sqlite3",
923
+ bug_log=project_knowledge_root(root) / "bug-log.md",
924
+ mistake_book=project_knowledge_root(root) / "mistake-book.md",
925
+ global_knowledge_root=global_knowledge_root(),
926
+ global_knowledge_seed=global_knowledge_root() / "global.json",
927
+ global_knowledge_db=global_knowledge_root() / "global.sqlite3",
928
+ logs_root=bugx_root(root) / "logs",
929
+ diagnostic_log=bugx_root(root) / "logs" / "bugx.jsonl",
930
+ )
931
+
932
+
933
+ def read_current(root: Path) -> dict[str, Any]:
934
+ current = _read_json(bugx_root(root) / "current.json")
935
+ if current.get("schema_version") != SCHEMA_VERSION:
936
+ raise LayoutError("current.json schema_version 不受支持")
937
+ _validate_identifier(current.get("polling_id"), "polling")
938
+ _validate_identifier(current.get("lifecycle_id"), "lifecycle")
939
+ for name in ("polling_no", "lifecycle_no"):
940
+ value = current.get(name)
941
+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:
942
+ raise LayoutError(f"current.json {name} 无效")
943
+ return current
944
+
945
+
946
+ def _write_current(root: Path, polling_id: str, lifecycle_id: str,
947
+ polling_no: int, lifecycle_no: int) -> dict[str, Any]:
948
+ value = {
949
+ "schema_version": SCHEMA_VERSION,
950
+ "layout_version": LAYOUT_VERSION,
951
+ "polling_id": polling_id,
952
+ "polling_no": polling_no,
953
+ "lifecycle_id": lifecycle_id,
954
+ "lifecycle_no": lifecycle_no,
955
+ "updated_at": utc_now(),
956
+ }
957
+ _atomic_json(bugx_root(root) / "current.json", value)
958
+ # PERF-06:current.json 被改写,显式失效 require() 的 Scope 缓存,
959
+ # 避免仅依赖 mtime 粒度(部分文件系统会粗化时间戳)导致读到过期 Scope。
960
+ clear_require_cache(root)
961
+ return value
962
+
963
+
964
+ def restore_current(root: Path, polling_id: str, lifecycle_id: str) -> Scope:
965
+ """回滚/恢复场景:把 current.json 原子指回既有 Session/Round。
966
+
967
+ 两个 id 都必须在磁盘上真实存在(各自 manifest 可读)才写回,
968
+ 保证 current.json 不指向不存在的布局;编号从 manifest 读取,
969
+ 避免调用方手填出错。返回恢复后的 Scope。
970
+ """
971
+ root = root.resolve()
972
+ base = bugx_root(root)
973
+ if not base.is_dir() or base.is_symlink():
974
+ raise LayoutError(f"缺少或不安全的 .bugx 目录: {base}")
975
+ _validate_identifier(polling_id, "polling")
976
+ _validate_identifier(lifecycle_id, "lifecycle")
977
+ pollings = base / "pollings"
978
+ polling_root = _id_path(pollings, polling_id, "polling")
979
+ manifest = _read_json(polling_root / "manifest.json")
980
+ polling_no = int(manifest["polling_no"])
981
+ lifecycles = polling_root / "lifecycles"
982
+ lifecycle_root = _id_path(lifecycles, lifecycle_id, "lifecycle")
983
+ lc_manifest = _read_json(lifecycle_root / "manifest.json")
984
+ lifecycle_no = int(lc_manifest["lifecycle_no"])
985
+ return _write_current(root, polling_id, lifecycle_id, polling_no, lifecycle_no)
986
+
987
+
988
+ def _create_scope(root: Path, polling_id: str, lifecycle_id: str) -> Scope:
989
+ active = scope(root, {"polling_id": polling_id, "lifecycle_id": lifecycle_id})
990
+ for directory in (
991
+ bugx_root(root), active.polling_root, active.lifecycle_root, active.state_root,
992
+ active.locks_root, active.life_snapshot.parent, active.lifecycle_root / "rounds",
993
+ active.lifecycle_root / "recovery", active.lifecycle_root / "workers",
994
+ active.knowledge_root, active.logs_root, bugx_root(root) / "backups",
995
+ bugx_root(root) / "artifacts", bugx_root(root) / "index",
996
+ ):
997
+ _assert_no_symlink_components(directory)
998
+ directory.mkdir(parents=True, exist_ok=True)
999
+ _assert_no_symlink_components(directory)
1000
+ os.chmod(directory, 0o700)
1001
+ return active
1002
+
1003
+
1004
+ def compute_project_hash(path: Path | str) -> str:
1005
+ """Compute standard hash for a project path: <name>-<sha256[:8]>."""
1006
+ p = Path(path).resolve()
1007
+ h = hashlib.sha256(str(p).encode("utf-8")).hexdigest()[:8]
1008
+ return f"{p.name}-{h}"
1009
+
1010
+
1011
+ def count_project_sessions(root: Path) -> int:
1012
+ """Count sessions/pollings in a project."""
1013
+ count = 0
1014
+ try:
1015
+ pollings_dir = root / ".bugx" / "pollings"
1016
+ if pollings_dir.is_dir():
1017
+ count += len([p for p in pollings_dir.iterdir() if p.name.startswith("polling-")])
1018
+ sessions_dir = root / ".bugx" / "sessions"
1019
+ if sessions_dir.is_dir():
1020
+ count += len([s for s in sessions_dir.iterdir() if not s.name.startswith(".")])
1021
+ except Exception:
1022
+ pass
1023
+ return max(1, count) if (root / ".bugx").is_dir() else 0
1024
+
1025
+
1026
+ def get_project_cloud_info(root: Path) -> dict[str, str]:
1027
+ """Retrieve bound cloud project_id / account_id if available."""
1028
+ info: dict[str, str] = {}
1029
+ try:
1030
+ cf = root / ".bugx" / "cloud-project.json"
1031
+ if cf.is_file():
1032
+ data = json.loads(cf.read_text(encoding="utf-8"))
1033
+ if isinstance(data, dict):
1034
+ if data.get("project_id"):
1035
+ info["cloud_project_id"] = str(data["project_id"])
1036
+ if data.get("account_id"):
1037
+ info["cloud_account_id"] = str(data["account_id"])
1038
+ except Exception:
1039
+ pass
1040
+ return info
1041
+
1042
+
1043
+ def is_system_temp_dir(path: Path | str) -> bool:
1044
+ """Check if path is inside system temp directory (/tmp, /var/folders, etc.)."""
1045
+ try:
1046
+ resolved = Path(path).resolve()
1047
+ system_temps = [
1048
+ Path(tempfile.gettempdir()).resolve(),
1049
+ Path("/tmp").resolve(),
1050
+ Path("/private/tmp").resolve(),
1051
+ Path("/var/folders").resolve(),
1052
+ Path("/private/var/folders").resolve(),
1053
+ Path("/private/var/tmp").resolve(),
1054
+ Path("/var/tmp").resolve(),
1055
+ ]
1056
+ for st in system_temps:
1057
+ try:
1058
+ resolved.relative_to(st)
1059
+ return True
1060
+ except ValueError:
1061
+ pass
1062
+ return False
1063
+ except Exception:
1064
+ return False
1065
+
1066
+
1067
+ def is_ephemeral_test_name(name: str) -> bool:
1068
+ """Check if project/directory name is an automated test ephemeral name (e.g. tmp9kt7dn15, auto-continue-xxx)."""
1069
+ n = name.lower()
1070
+ if n.startswith("auto-continue-") or n.startswith("pytest-") or n.startswith("tox-"):
1071
+ return True
1072
+ # tempfile 随机命名,如 tmp9kt7dn15, tmp_3oktjrb
1073
+ if n.startswith("tmp") and len(n) >= 7 and any(c.isdigit() for c in n):
1074
+ return True
1075
+ return False
1076
+
1077
+
1078
+ def is_valid_project_dir(path: Path | str, *, name: str | None = None, allow_registered: bool = False) -> bool:
1079
+ """Strict check: directory is a valid BugX project, never home, root, or ephemeral test trash."""
1080
+ try:
1081
+ resolved = Path(path).resolve()
1082
+ home = Path.home().resolve()
1083
+ root = Path("/").resolve()
1084
+ # 1. 绝不能是家目录、根目录,且磁盘上必须真实存在并且是目录
1085
+ if resolved in (home, root) or not resolved.is_dir():
1086
+ return False
1087
+
1088
+ # 2. 检查名称是否为自动化测试随机临时名
1089
+ if name and not is_ephemeral_test_name(name):
1090
+ pass # 显式登记了合法的业务项目名称(如 sample-agent-project),放行
1091
+ elif is_ephemeral_test_name(resolved.name):
1092
+ return False
1093
+ elif name and is_ephemeral_test_name(name):
1094
+ return False
1095
+
1096
+ # 3. 必须具备实际的 BugX 特征(有 .bugx 目录或 .bugx-project.json)
1097
+ return (resolved / ".bugx").is_dir() or (resolved / ".bugx-project.json").is_file()
1098
+ except Exception:
1099
+ return False
1100
+
1101
+
1102
+ def sync_global_projects(workspace: Path | None = None) -> list[dict[str, Any]]:
1103
+ """Scan, reconcile, and persist all valid BugX projects into ~/.bugx/projects.json."""
1104
+ home = Path.home().resolve()
1105
+ pfile = home / ".bugx" / "projects.json"
1106
+ pfile.parent.mkdir(mode=0o700, exist_ok=True)
1107
+
1108
+ # 1. Load existing registered projects, hidden_hashes, and purge invalid/temp/deleted entries (Self-Healing)
1109
+ existing_projects: list[dict[str, Any]] = []
1110
+ hidden_hashes: set[str] = set()
1111
+ if pfile.is_file():
1112
+ try:
1113
+ raw = json.loads(pfile.read_text(encoding="utf-8"))
1114
+ if isinstance(raw, dict):
1115
+ if isinstance(raw.get("projects"), list):
1116
+ existing_projects = raw["projects"]
1117
+ if isinstance(raw.get("hidden_hashes"), list):
1118
+ hidden_hashes = {str(h) for h in raw["hidden_hashes"] if h}
1119
+ elif isinstance(raw, list):
1120
+ existing_projects = raw
1121
+ except Exception:
1122
+ existing_projects = []
1123
+
1124
+ # Map of resolved Path -> existing dict (严格过滤掉所有临时、已删除、已隐藏或非法的垃圾条目)
1125
+ known_map: dict[Path, dict[str, Any]] = {}
1126
+ for p in existing_projects:
1127
+ if isinstance(p, dict) and p.get("working_dir"):
1128
+ wdir = Path(p["working_dir"]).resolve()
1129
+ h_cand = p.get("hash") or compute_project_hash(wdir)
1130
+ if h_cand in hidden_hashes or compute_project_hash(wdir) in hidden_hashes:
1131
+ continue
1132
+ p_name = p.get("name")
1133
+ if is_valid_project_dir(wdir, name=p_name):
1134
+ known_map[wdir] = p
1135
+
1136
+ # 2. Add active workspace if provided or Path.cwd()
1137
+ # 活跃工作区必须自可见:hidden_hashes 只抑制**非活跃**项目的自动复活。
1138
+ # 否则在当前项目里 remove 过一次(或历史测试遗留)之后,服务把自己所在的
1139
+ # 工作区从 /projects 里永久隐藏,列表里连"我正在用的项目"都没有。
1140
+ active_ws = (workspace or Path.cwd()).resolve()
1141
+ if is_valid_project_dir(active_ws):
1142
+ if active_ws not in known_map:
1143
+ known_map[active_ws] = {}
1144
+
1145
+ # 3. Discover sibling workspaces (e.g. ~/workspace/*)
1146
+ # 核心硬防线:如果父目录是系统临时目录、家目录或根目录,绝对禁止扫描兄弟目录;已隐藏项目绝不复活!
1147
+ try:
1148
+ ws_parent = active_ws.parent.resolve()
1149
+ if (
1150
+ ws_parent not in (home, Path("/").resolve())
1151
+ and ws_parent.is_dir()
1152
+ and not is_system_temp_dir(ws_parent)
1153
+ ):
1154
+ for sub in sorted(ws_parent.iterdir()):
1155
+ if sub.is_dir():
1156
+ sub_res = sub.resolve()
1157
+ if (
1158
+ sub_res not in known_map
1159
+ and compute_project_hash(sub_res) not in hidden_hashes
1160
+ and is_valid_project_dir(sub_res)
1161
+ ):
1162
+ known_map[sub_res] = {}
1163
+ except Exception:
1164
+ pass
1165
+
1166
+ # 4. Check ~/.atomcode/recent_dirs.txt if exists
1167
+ recent_file = home / ".atomcode" / "recent_dirs.txt"
1168
+ if recent_file.is_file():
1169
+ try:
1170
+ for line in recent_file.read_text(encoding="utf-8").splitlines():
1171
+ line = line.strip()
1172
+ if line:
1173
+ rp = Path(line).resolve()
1174
+ if (
1175
+ rp not in known_map
1176
+ and compute_project_hash(rp) not in hidden_hashes
1177
+ and is_valid_project_dir(rp)
1178
+ ):
1179
+ known_map[rp] = {}
1180
+ except Exception:
1181
+ pass
1182
+
1183
+ # 5. Build consolidated project records
1184
+ now_ms = int(time.time() * 1000)
1185
+ consolidated: list[dict[str, Any]] = []
1186
+
1187
+ # Put active_ws at top if valid, followed by other projects
1188
+ target_paths = list(known_map.keys())
1189
+ if active_ws in target_paths:
1190
+ target_paths.remove(active_ws)
1191
+ ordered_paths = [active_ws] + sorted(target_paths, key=lambda p: p.name.lower())
1192
+ else:
1193
+ ordered_paths = sorted(target_paths, key=lambda p: p.name.lower())
1194
+
1195
+ for p in ordered_paths:
1196
+ orig = known_map.get(p) or {}
1197
+ h = compute_project_hash(p)
1198
+ added_at = orig.get("added_at") or now_ms
1199
+ last_seen = now_ms if p == active_ws else (orig.get("last_seen_at") or added_at)
1200
+ session_cnt = count_project_sessions(p)
1201
+ cloud_info = get_project_cloud_info(p)
1202
+ archived = bool(orig.get("archived", False))
1203
+
1204
+ record: dict[str, Any] = {
1205
+ "hash": h,
1206
+ "name": orig.get("name") or p.name,
1207
+ "working_dir": str(p),
1208
+ "session_count": session_cnt,
1209
+ "added_at": added_at,
1210
+ "last_seen_at": last_seen,
1211
+ "archived": archived,
1212
+ }
1213
+ if orig.get("archived_at"):
1214
+ record["archived_at"] = orig["archived_at"]
1215
+ if cloud_info.get("cloud_project_id"):
1216
+ record["cloud_project_id"] = cloud_info["cloud_project_id"]
1217
+ if cloud_info.get("cloud_account_id"):
1218
+ record["cloud_account_id"] = cloud_info["cloud_account_id"]
1219
+
1220
+ consolidated.append(record)
1221
+
1222
+ # 6. Atomically persist to projects.json
1223
+ payload = {
1224
+ "version": 1,
1225
+ "projects": consolidated,
1226
+ "hidden_hashes": sorted(hidden_hashes),
1227
+ }
1228
+ tmp = pfile.with_suffix(".tmp")
1229
+ tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
1230
+ tmp.replace(pfile)
1231
+
1232
+ return consolidated
1233
+
1234
+
1235
+ def archive_global_project(proj_hash: str, *, archived: bool = True, workspace: Path | None = None) -> dict[str, Any] | None:
1236
+ """Archive or unarchive a project in ~/.bugx/projects.json (REQ-06)."""
1237
+ home = Path.home().resolve()
1238
+ pfile = home / ".bugx" / "projects.json"
1239
+ sync_global_projects(workspace=workspace)
1240
+ if not pfile.is_file():
1241
+ return None
1242
+ try:
1243
+ raw = json.loads(pfile.read_text(encoding="utf-8"))
1244
+ projects = raw.get("projects", []) if isinstance(raw, dict) else []
1245
+ hidden_hashes = raw.get("hidden_hashes", []) if isinstance(raw, dict) else []
1246
+ target: dict[str, Any] | None = None
1247
+ now_ms = int(time.time() * 1000)
1248
+ for item in projects:
1249
+ if isinstance(item, dict) and item.get("hash") == proj_hash:
1250
+ item["archived"] = bool(archived)
1251
+ if archived:
1252
+ item["archived_at"] = now_ms
1253
+ else:
1254
+ item.pop("archived_at", None)
1255
+ target = item
1256
+ break
1257
+ if target is not None:
1258
+ payload = {"version": 1, "projects": projects, "hidden_hashes": hidden_hashes}
1259
+ tmp = pfile.with_suffix(".tmp")
1260
+ tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
1261
+ tmp.replace(pfile)
1262
+ return target
1263
+ except Exception:
1264
+ return None
1265
+
1266
+
1267
+ def remove_global_project(
1268
+ proj_hash: str | Path,
1269
+ *,
1270
+ mode: str = "remove",
1271
+ workspace: Path | None = None,
1272
+ ) -> dict[str, Any]:
1273
+ """Remove a project from ~/.bugx/projects.json and suppress auto-resurrection (REQ-06).
1274
+
1275
+ Modes:
1276
+ - 'remove': remove from list and record in hidden_hashes; keep .bugx on disk.
1277
+ - 'purge': remove from list, record in hidden_hashes, and safely delete ONLY <project_root>/.bugx
1278
+ (never touching user source files).
1279
+ """
1280
+ if mode not in ("remove", "purge"):
1281
+ raise ValueError(f"Unsupported delete mode: {mode}")
1282
+ if isinstance(proj_hash, Path) or (isinstance(proj_hash, str) and ("/" in proj_hash or "\\" in proj_hash)):
1283
+ proj_hash = compute_project_hash(Path(proj_hash).resolve())
1284
+ proj_hash = str(proj_hash)
1285
+ home = Path.home().resolve()
1286
+ pfile = home / ".bugx" / "projects.json"
1287
+ sync_global_projects(workspace=workspace)
1288
+ projects: list[dict[str, Any]] = []
1289
+ hidden_hashes: set[str] = set()
1290
+ if pfile.is_file():
1291
+ try:
1292
+ raw = json.loads(pfile.read_text(encoding="utf-8"))
1293
+ if isinstance(raw, dict):
1294
+ projects = list(raw.get("projects") or [])
1295
+ hidden_hashes = {str(h) for h in (raw.get("hidden_hashes") or []) if h}
1296
+ except Exception:
1297
+ projects = []
1298
+
1299
+ removed_entry: dict[str, Any] | None = None
1300
+ remaining: list[dict[str, Any]] = []
1301
+ for item in projects:
1302
+ if isinstance(item, dict) and item.get("hash") == proj_hash:
1303
+ removed_entry = item
1304
+ else:
1305
+ remaining.append(item)
1306
+
1307
+ hidden_hashes.add(proj_hash)
1308
+ purged_bugx = False
1309
+ if mode == "purge" and removed_entry and removed_entry.get("working_dir"):
1310
+ proj_root = Path(removed_entry["working_dir"]).resolve()
1311
+ dot_bugx = proj_root / ".bugx"
1312
+ # Red-team invariant: strictly assert we only ever delete the '.bugx' subdirectory inside proj_root
1313
+ if (
1314
+ proj_root not in (home, Path("/").resolve())
1315
+ and dot_bugx.name == ".bugx"
1316
+ and dot_bugx.parent.resolve() == proj_root
1317
+ and dot_bugx.exists()
1318
+ and not dot_bugx.is_symlink()
1319
+ ):
1320
+ shutil.rmtree(dot_bugx, ignore_errors=True)
1321
+ purged_bugx = not dot_bugx.exists()
1322
+
1323
+ pfile.parent.mkdir(mode=0o700, exist_ok=True)
1324
+ payload = {
1325
+ "version": 1,
1326
+ "projects": remaining,
1327
+ "hidden_hashes": sorted(hidden_hashes),
1328
+ }
1329
+ tmp = pfile.with_suffix(".tmp")
1330
+ tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
1331
+ tmp.replace(pfile)
1332
+
1333
+ return {
1334
+ "ok": True,
1335
+ "deleted": True,
1336
+ "hash": proj_hash,
1337
+ "mode": mode,
1338
+ "purged_bugx": purged_bugx,
1339
+ "purged_bugx_dir": purged_bugx,
1340
+ "suppressed": proj_hash in hidden_hashes,
1341
+ "working_dir": removed_entry.get("working_dir") if removed_entry else None,
1342
+ }
1343
+
1344
+
1345
+ def is_bugx_source_repo(root: Path) -> bool:
1346
+ """判断该目录是否是 BugX 自身的**源码检出**(而非被扫描的用户项目)。
1347
+
1348
+ 权威判定放在 ``core/``:``core/`` 不能反向依赖 ``interfaces/cli/``,而
1349
+ CLI 侧原先自带一份同名实现(``bugx_cli.common._is_bugx_source_repo``),
1350
+ 两处独立推导正是本仓反复出现的缺陷族,故统一到这里、CLI 改为委托。
1351
+
1352
+ 特征取「构建脚本 + 打包清单」同时存在:普通用户项目不会同时具备
1353
+ ``scripts/bump_version.py`` 与 ``pyproject.toml``。
1354
+ """
1355
+ try:
1356
+ base = Path(root)
1357
+ return (base / "scripts" / "bump_version.py").is_file() \
1358
+ and (base / "pyproject.toml").is_file()
1359
+ except OSError:
1360
+ return False
1361
+
1362
+
1363
+ def _register_global_project(root: Path) -> None:
1364
+ """Record initialized project into global ~/.bugx/projects.json (bypasses temp/test directories)."""
1365
+ try:
1366
+ # 如果是临时测试随机目录,严禁写入宿主全局注册表
1367
+ if is_ephemeral_test_name(root.name) or (is_system_temp_dir(root) and is_ephemeral_test_name(root.name)):
1368
+ return
1369
+ # BugX 自己的源码检出不是"用户用 BugX 扫过的项目",不能进这张表。
1370
+ # ``~/.bugx/projects.json`` 描述的是安装后用户的扫描对象清单,
1371
+ # 开发仓库混进去会让 Web 控制台列出指向开发树的伪项目(实测已积累
1372
+ # 3 条源码/测试树条目)。这条判定**不依赖环境变量**,因此对
1373
+ # 手工运行、引擎子进程、宿主调用同样生效。
1374
+ if is_bugx_source_repo(root):
1375
+ return
1376
+ # 如果处于单元测试运行环境,亦严禁污染真实注册表
1377
+ if any(k in os.environ for k in ("PYTEST_CURRENT_TEST", "BUGX_TEST_MODE", "BUGX_SANDBOX_TEST")):
1378
+ return
1379
+ sync_global_projects(workspace=root)
1380
+ except Exception:
1381
+ pass
1382
+
1383
+
1384
+ def initialize(root: Path, *, bugx_version: str = "unknown") -> Scope:
1385
+ root = root.resolve()
1386
+ if not root.is_dir():
1387
+ raise LayoutError(f"项目根目录不存在: {root}")
1388
+ base = bugx_root(root)
1389
+ if base.is_symlink():
1390
+ raise LayoutError(f"拒绝使用符号链接 .bugx: {base}")
1391
+ _assert_no_symlink_components(base)
1392
+ base.mkdir(mode=0o700, exist_ok=True)
1393
+ manifest_path = base / "manifest.json"
1394
+ if manifest_path.exists():
1395
+ manifest = _read_json(manifest_path)
1396
+ if manifest.get("schema_version") != SCHEMA_VERSION:
1397
+ raise LayoutError(".bugx/manifest.json schema_version 不受支持")
1398
+ if _identity_mismatch(root, manifest):
1399
+ # ``project_id`` 是 ``sha256(根路径)``,即整份 ``.bugx`` 的身份
1400
+ # **绑死在绝对路径**上——它按设计就不可移植。因此清单对不上新根
1401
+ # 不是"脏状态",而是**这份状态不属于这个根**。
1402
+ #
1403
+ # 绝不能"就地重建清单然后继续":清单只是元数据,``.bugx`` 下的
1404
+ # 寿命账本、知识库、pollings 报告统统保留,于是源项目的洞察、
1405
+ # 错题集乃至机密会静默流进目标项目(实测:copytree 后的项目能
1406
+ # 直接读到源项目的 knowledge_seed 与 life 账本)。那是 fail-open
1407
+ # 数据污染,比拒绝服务严重得多。
1408
+ #
1409
+ # 正确处置是 fail-closed 并且**把出路写进错误**:唯一安全的迁移
1410
+ # 是整目录重建(旧状态整体作废),由用户显式执行。
1411
+ raise LayoutError(
1412
+ f"'.bugx' 目录不属于当前项目:{base}\n"
1413
+ f" 该目录绑定的根与当前根不一致(project_id 由根路径哈希得出,"
1414
+ f"因此 .bugx 不可复制/搬移)。\n"
1415
+ f" 若这是从别处复制来的布局,其中的寿命账本、知识库和报告都"
1416
+ f"属于原项目,继续使用会污染本项目。\n"
1417
+ f" 修复方式(二选一):\n"
1418
+ f" 1) 备份后删除该目录并重新初始化:rm -rf {base} && bugx init\n"
1419
+ f" 2) 若确认要保留其中人工产出,先手工取出需要的文件,再执行 1)"
1420
+ )
1421
+ if (manifest.get("bugx_version") != bugx_version
1422
+ or manifest.get("layout_version") != LAYOUT_VERSION):
1423
+ # Version metadata is installation state, not user-authored
1424
+ # runtime state. Refresh it atomically so a project does not keep
1425
+ # claiming the version/layout from its first initialization forever.
1426
+ manifest["bugx_version"] = bugx_version
1427
+ manifest["layout_version"] = LAYOUT_VERSION
1428
+ manifest["updated_at"] = utc_now()
1429
+ _atomic_json(manifest_path, manifest)
1430
+ else:
1431
+ _atomic_json(manifest_path, {
1432
+ "schema_version": SCHEMA_VERSION,
1433
+ "layout_version": LAYOUT_VERSION,
1434
+ "project_id": _path_fingerprint(root),
1435
+ PROJECT_UID_KEY: _new_project_uid(root),
1436
+ "bugx_version": bugx_version,
1437
+ "created_at": utc_now(),
1438
+ })
1439
+ # PERF-06:manifest.json 被改写,显式失效 require() 的 Scope 缓存。
1440
+ clear_require_cache(root)
1441
+ # 登记必须在**布局建立之后**:``is_valid_project_dir`` 要求目录已含
1442
+ # ``.bugx``,而历史实现把登记放在 ``base.mkdir()`` 之前,于是全新项目
1443
+ # 首次 ``initialize`` 永远登记失败(要跑第二次才进表)——这正是
1444
+ # ``~/.bugx/projects.json`` 里混着开发树/测试副本、且真实项目缺失的原因。
1445
+ _register_global_project(root)
1446
+ current_path = base / "current.json"
1447
+ if current_path.exists():
1448
+ current = _read_json(current_path)
1449
+ active = scope(root, current)
1450
+ _create_scope(root, current["polling_id"], current["lifecycle_id"])
1451
+ return active
1452
+ polling_id = "polling-000001"
1453
+ lifecycle_id = "lifecycle-000001"
1454
+ _create_scope(root, polling_id, lifecycle_id)
1455
+ _write_current(root, polling_id, lifecycle_id, 1, 1)
1456
+ polling_root = bugx_root(root) / "pollings" / polling_id
1457
+ _atomic_json(polling_root / "manifest.json", {
1458
+ "schema_version": SCHEMA_VERSION,
1459
+ "polling_id": polling_id,
1460
+ "polling_no": 1,
1461
+ "policy": None,
1462
+ "created_at": utc_now(),
1463
+ })
1464
+ _atomic_json(polling_root / "state.json", {
1465
+ "schema_version": SCHEMA_VERSION,
1466
+ "state": "created",
1467
+ "polling_id": polling_id,
1468
+ "lifecycle_ids": [lifecycle_id],
1469
+ })
1470
+ # 索引里冗余一份 project_uid:整目录 copytree 会同时带走清单与索引,两者
1471
+ # 一致 ⇒ 合法搬移;手工拼装/串用他人布局 ⇒ 不一致 ⇒ fail-closed。
1472
+ _atomic_json(bugx_root(root) / "index" / "index.json", {
1473
+ "schema_version": SCHEMA_VERSION,
1474
+ "last_polling_id": polling_id,
1475
+ PROJECT_UID_KEY: _new_project_uid(root),
1476
+ })
1477
+ lifecycle_root = _scope_root(root, polling_id, lifecycle_id)
1478
+ _atomic_json(lifecycle_root / "manifest.json", {
1479
+ "schema_version": SCHEMA_VERSION,
1480
+ "polling_id": polling_id,
1481
+ "lifecycle_id": lifecycle_id,
1482
+ "lifecycle_no": 1,
1483
+ "created_at": utc_now(),
1484
+ })
1485
+ _atomic_json(lifecycle_root / "state.json", {
1486
+ "schema_version": SCHEMA_VERSION,
1487
+ "state": "created",
1488
+ "lifecycle_id": lifecycle_id,
1489
+ })
1490
+ return scope(root)
1491
+
1492
+
1493
+ # PERF-06:``require()`` 每次都会重读并解析 manifest.json / current.json(还要
1494
+ # 走一遍符号链接组件检查)。这里缓存「解析后的 Scope」,并用两个布局文件的
1495
+ # mtime_ns+size 作为失效戳:引擎写入新生命周期会改写 current.json,戳变化即
1496
+ # 自动重算,因此不会把运行期状态变更固定住。仅缓存成功结果,异常不缓存。
1497
+ _REQUIRE_CACHE: dict[Path, tuple[tuple[Any, ...], Scope]] = {}
1498
+
1499
+
1500
+ def _layout_stamp(base: Path) -> tuple[Any, ...]:
1501
+ """布局失效戳:manifest.json / current.json 的 (mtime_ns, size)。"""
1502
+ stamps: list[Any] = []
1503
+ for name in ("manifest.json", "current.json"):
1504
+ try:
1505
+ stat = (base / name).stat()
1506
+ stamps.append((stat.st_mtime_ns, stat.st_size))
1507
+ except OSError:
1508
+ stamps.append(None)
1509
+ return tuple(stamps)
1510
+
1511
+
1512
+ def clear_require_cache(root: Path | None = None) -> None:
1513
+ """清空 ``require()`` 的 Scope 缓存(不传 root 则全部清空)。"""
1514
+ if root is None:
1515
+ _REQUIRE_CACHE.clear()
1516
+ else:
1517
+ _REQUIRE_CACHE.pop(root.resolve(), None)
1518
+
1519
+
1520
+ def require(root: Path) -> Scope:
1521
+ root = root.resolve()
1522
+ base = bugx_root(root)
1523
+ stamp = _layout_stamp(base)
1524
+ if all(part is not None for part in stamp):
1525
+ cached = _REQUIRE_CACHE.get(root)
1526
+ if cached is not None and cached[0] == stamp:
1527
+ active = cached[1]
1528
+ # 缓存命中也复核派生目录仍在:目录被删除时立即回退到完整校验,
1529
+ # 由完整路径抛出 LayoutError,而不是返回过期 Scope。
1530
+ if active.lifecycle_root.is_dir() and active.state_root.is_dir():
1531
+ return active
1532
+ if not base.is_dir() or base.is_symlink():
1533
+ raise LayoutError(f"缺少或不安全的 .bugx 目录: {base};请先运行 bugx init")
1534
+ manifest = _read_json(base / "manifest.json")
1535
+ if _identity_mismatch(root, manifest):
1536
+ raise LayoutError(".bugx/manifest.json 与当前项目不匹配")
1537
+ current = read_current(root)
1538
+ active = scope(root, current)
1539
+ if not active.lifecycle_root.is_dir() or not active.state_root.is_dir():
1540
+ raise LayoutError("当前生命周期目录缺失;请运行 bugx doctor --repair 或恢复备份")
1541
+ _REQUIRE_CACHE[root] = (stamp, active)
1542
+ return active
1543
+
1544
+
1545
+ def repair(root: Path) -> Scope:
1546
+ """Rebuild only derived layout pointers and directories.
1547
+
1548
+ This function is intentionally conservative: it requires the immutable
1549
+ project manifest and an existing polling/lifecycle manifest. It may
1550
+ recreate ``current.json`` and empty derived directories, but it never
1551
+ creates a life file, settlement, report, or knowledge database. Missing
1552
+ authority therefore remains visible to ``doctor`` instead of becoming a
1553
+ fresh, silently reset project.
1554
+ """
1555
+ root = root.resolve()
1556
+ base = bugx_root(root)
1557
+ if not base.is_dir() or base.is_symlink():
1558
+ raise LayoutError(f"缺少或不安全的 .bugx 目录: {base}")
1559
+ manifest = _read_json(base / "manifest.json")
1560
+ if _identity_mismatch(root, manifest):
1561
+ raise LayoutError(".bugx/manifest.json 与当前项目不匹配")
1562
+
1563
+ candidates: list[tuple[int, int, str, str]] = []
1564
+ pollings = base / "pollings"
1565
+ if pollings.is_dir() and not pollings.is_symlink():
1566
+ for polling_dir in pollings.iterdir():
1567
+ if not polling_dir.is_dir() or polling_dir.is_symlink():
1568
+ continue
1569
+ try:
1570
+ polling_manifest = _read_json(polling_dir / "manifest.json")
1571
+ polling_id = str(polling_manifest["polling_id"])
1572
+ polling_no = int(polling_manifest["polling_no"])
1573
+ _id_path(pollings, polling_id, "polling")
1574
+ except (KeyError, TypeError, ValueError, LayoutError):
1575
+ continue
1576
+ lifecycle_root = polling_dir / "lifecycles"
1577
+ if not lifecycle_root.is_dir() or lifecycle_root.is_symlink():
1578
+ continue
1579
+ for lifecycle_dir in lifecycle_root.iterdir():
1580
+ if not lifecycle_dir.is_dir() or lifecycle_dir.is_symlink():
1581
+ continue
1582
+ try:
1583
+ lifecycle_manifest = _read_json(lifecycle_dir / "manifest.json")
1584
+ lifecycle_id = str(lifecycle_manifest["lifecycle_id"])
1585
+ lifecycle_no = int(lifecycle_manifest["lifecycle_no"])
1586
+ if lifecycle_manifest.get("polling_id") != polling_id:
1587
+ continue
1588
+ _id_path(lifecycle_root, lifecycle_id, "lifecycle")
1589
+ except (KeyError, TypeError, ValueError, LayoutError):
1590
+ continue
1591
+ candidates.append((polling_no, lifecycle_no, polling_id, lifecycle_id))
1592
+ if not candidates:
1593
+ raise LayoutError("没有可验证的 polling/lifecycle manifest,拒绝重建为新项目")
1594
+
1595
+ current_path = base / "current.json"
1596
+ selected: tuple[int, int, str, str] | None = None
1597
+ if current_path.is_file() and not current_path.is_symlink():
1598
+ try:
1599
+ current = _read_json(current_path)
1600
+ key = (int(current["polling_no"]), int(current["lifecycle_no"]),
1601
+ str(current["polling_id"]), str(current["lifecycle_id"]))
1602
+ if key in candidates:
1603
+ selected = key
1604
+ except (KeyError, TypeError, ValueError, LayoutError):
1605
+ selected = None
1606
+ selected = selected or max(candidates)
1607
+ polling_no, lifecycle_no, polling_id, lifecycle_id = selected
1608
+ _create_scope(root, polling_id, lifecycle_id)
1609
+ _write_current(root, polling_id, lifecycle_id, polling_no, lifecycle_no)
1610
+ index = base / "index" / "index.json"
1611
+ _atomic_json(index, {
1612
+ "schema_version": SCHEMA_VERSION,
1613
+ "last_polling_id": polling_id,
1614
+ "last_lifecycle_id": lifecycle_id,
1615
+ "repaired_at": utc_now(),
1616
+ })
1617
+ return scope(root)
1618
+
1619
+
1620
+ def activate_lifecycle(root: Path, lifecycle_no: int, lifecycle_id: str,
1621
+ *, polling_id: str | None = None, polling_no: int | None = None) -> Scope:
1622
+ if isinstance(lifecycle_no, bool) or not isinstance(lifecycle_no, int) or lifecycle_no < 1:
1623
+ raise LayoutError("lifecycle_no 无效")
1624
+ _validate_identifier(lifecycle_id, "lifecycle")
1625
+ if polling_id is not None:
1626
+ _validate_identifier(polling_id, "polling")
1627
+ if polling_no is not None:
1628
+ if isinstance(polling_no, bool) or not isinstance(polling_no, int) or polling_no < 1:
1629
+ raise LayoutError("polling_no 无效")
1630
+ root = root.resolve()
1631
+ base = bugx_root(root)
1632
+ if not base.is_dir() or base.is_symlink():
1633
+ raise LayoutError(f"缺少或不安全的 .bugx 目录: {base}")
1634
+ with _project_lock(root):
1635
+ current = read_current(root)
1636
+ # 指针完整性:current 必须能定位到已存在的 polling/lifecycle
1637
+ _validate_polling_manifest(root, str(current["polling_id"]),
1638
+ expected_no=int(current["polling_no"]))
1639
+ _validate_lifecycle_manifest(root, str(current["polling_id"]),
1640
+ str(current["lifecycle_id"]),
1641
+ expected_no=int(current["lifecycle_no"]))
1642
+ # 解析目标 polling:同一 polling 下仅递增 lifecycle,不得篡改 polling_no
1643
+ if polling_id is None:
1644
+ resolved_polling_id = str(current["polling_id"])
1645
+ resolved_polling_no = int(current["polling_no"])
1646
+ if polling_no is not None and polling_no != resolved_polling_no:
1647
+ raise LayoutError(
1648
+ f"polling_no 与当前 polling 不一致: current={resolved_polling_no} vs provided={polling_no}"
1649
+ )
1650
+ else:
1651
+ resolved_polling_id = polling_id
1652
+ _validate_identifier(resolved_polling_id, "polling")
1653
+ if polling_no is None:
1654
+ # 调用方指定了新 polling 但未提供编号时,以磁盘 manifest 为准
1655
+ try:
1656
+ manifest = _read_json(base / "pollings" / resolved_polling_id / "manifest.json")
1657
+ resolved_polling_no = int(manifest["polling_no"])
1658
+ except (LayoutError, KeyError, TypeError, ValueError, OSError) as exc:
1659
+ raise LayoutError("指定 polling_id 时必须提供 polling_no") from exc
1660
+ if isinstance(resolved_polling_no, bool) or resolved_polling_no < 1:
1661
+ raise LayoutError("polling_no 无效")
1662
+ else:
1663
+ resolved_polling_no = polling_no
1664
+ # 若切换到同一 polling,polling_no 必须与当前 manifest 一致;若切换到新 polling,则校验目标 polling
1665
+ _validate_polling_manifest(root, resolved_polling_id, expected_no=resolved_polling_no)
1666
+ # 若目标 lifecycle 已存在,校验其归属;若不存在则本次激活将创建它,仍需保证 polling 归属一致
1667
+ target_polling_root = _id_path(base / "pollings", resolved_polling_id, "polling")
1668
+ target_lifecycle_root = _id_path(target_polling_root / "lifecycles", lifecycle_id, "lifecycle")
1669
+ if target_lifecycle_root.is_dir() and not target_lifecycle_root.is_symlink():
1670
+ manifest_path = target_lifecycle_root / "manifest.json"
1671
+ if manifest_path.is_file() and not manifest_path.is_symlink():
1672
+ existing = _read_json(manifest_path)
1673
+ if existing.get("polling_id") != resolved_polling_id:
1674
+ raise LayoutError(
1675
+ f"lifecycle 归属不一致: {lifecycle_id} 属于 {existing.get('polling_id')} 而非 {resolved_polling_id}"
1676
+ )
1677
+ if existing.get("lifecycle_id") != lifecycle_id:
1678
+ raise LayoutError(f"lifecycle manifest 标识不一致: {lifecycle_id}")
1679
+ if int(existing.get("lifecycle_no", -1)) != lifecycle_no:
1680
+ raise LayoutError(
1681
+ f"lifecycle_no 指针不一致: manifest={existing.get('lifecycle_no')} vs expected={lifecycle_no}"
1682
+ )
1683
+ active = _create_scope(root, resolved_polling_id, lifecycle_id)
1684
+ # 若 lifecycle manifest 尚不存在则原子创建,保证后续校验完整
1685
+ lifecycle_manifest_path = active.lifecycle_root / "manifest.json"
1686
+ if not lifecycle_manifest_path.is_file():
1687
+ _atomic_json(lifecycle_manifest_path, {
1688
+ "schema_version": SCHEMA_VERSION,
1689
+ "polling_id": resolved_polling_id,
1690
+ "lifecycle_id": lifecycle_id,
1691
+ "lifecycle_no": lifecycle_no,
1692
+ "created_at": utc_now(),
1693
+ })
1694
+ lifecycle_state_path = active.lifecycle_root / "state.json"
1695
+ if not lifecycle_state_path.is_file():
1696
+ _atomic_json(lifecycle_state_path, {
1697
+ "schema_version": SCHEMA_VERSION,
1698
+ "state": "created",
1699
+ "lifecycle_id": lifecycle_id,
1700
+ })
1701
+ # 最终校验:激活前后指针必须完整
1702
+ _validate_polling_manifest(root, resolved_polling_id, expected_no=resolved_polling_no)
1703
+ _validate_lifecycle_manifest(root, resolved_polling_id, lifecycle_id, expected_no=lifecycle_no)
1704
+ _write_current(root, resolved_polling_id, lifecycle_id, resolved_polling_no, lifecycle_no)
1705
+ return active
1706
+
1707
+
1708
+ def create_session(root: Path, *, session_no: int | None = None) -> Scope:
1709
+ """Create a fresh Project Session and its first Round.
1710
+
1711
+ The on-disk ``pollings/lifecycles`` names are retained as storage details,
1712
+ but this operation is the single authority for the public
1713
+ ``Session → Round → Life`` boundary. It never overwrites an existing
1714
+ session and updates ``current.json`` only after both manifests exist.
1715
+ """
1716
+ root = root.resolve()
1717
+ base = bugx_root(root)
1718
+ if not base.is_dir() or base.is_symlink():
1719
+ raise LayoutError(f"缺少或不安全的 .bugx 目录: {base}")
1720
+ _read_json(base / "manifest.json")
1721
+ if session_no is not None:
1722
+ if isinstance(session_no, bool) or not isinstance(session_no, int) or session_no < 1:
1723
+ raise LayoutError("Session 编号无效")
1724
+ with _project_lock(root):
1725
+ pollings = base / "pollings"
1726
+ _assert_no_symlink_components(pollings)
1727
+ pollings.mkdir(parents=True, exist_ok=True)
1728
+ try:
1729
+ os.chmod(pollings, 0o700)
1730
+ except OSError:
1731
+ pass
1732
+ _assert_no_symlink_components(pollings)
1733
+ numbers: list[int] = []
1734
+ for item in pollings.iterdir():
1735
+ if not item.is_dir() or item.is_symlink():
1736
+ continue
1737
+ try:
1738
+ value = _read_json(item / "manifest.json")
1739
+ numbers.append(int(value["polling_no"]))
1740
+ except (LayoutError, KeyError, TypeError, ValueError):
1741
+ continue
1742
+ next_no = session_no if session_no is not None else (max(numbers, default=0) + 1)
1743
+ if isinstance(next_no, bool) or not isinstance(next_no, int) or next_no < 1:
1744
+ raise LayoutError("Session 编号无效")
1745
+ polling_id = f"polling-{next_no:06d}"
1746
+ _validate_identifier(polling_id, "polling")
1747
+ # 显式 session_no 不得覆盖既有 Session:原子预留检查
1748
+ candidate_polling_root = _id_path(pollings, polling_id, "polling")
1749
+ if candidate_polling_root.exists():
1750
+ # 目录或文件已存在即视为冲突;显式和自动均拒绝复用
1751
+ raise LayoutError(f"Session 已存在,拒绝覆盖: {polling_id}")
1752
+ if next_no in numbers:
1753
+ raise LayoutError(f"Session 编号已存在: {polling_id}")
1754
+ lifecycle_id = "lifecycle-000001"
1755
+ active = _create_scope(root, polling_id, lifecycle_id)
1756
+ _atomic_json(active.polling_root / "manifest.json", {
1757
+ "schema_version": SCHEMA_VERSION,
1758
+ "polling_id": polling_id,
1759
+ "polling_no": next_no,
1760
+ "policy": None,
1761
+ "created_at": utc_now(),
1762
+ })
1763
+ _atomic_json(active.polling_root / "state.json", {
1764
+ "schema_version": SCHEMA_VERSION,
1765
+ "state": "created",
1766
+ "polling_id": polling_id,
1767
+ "lifecycle_ids": [lifecycle_id],
1768
+ "session_id": polling_id,
1769
+ "sessions_completed": 0,
1770
+ "sessions_aborted": 0,
1771
+ "sessions": [],
1772
+ })
1773
+ _atomic_json(active.lifecycle_root / "manifest.json", {
1774
+ "schema_version": SCHEMA_VERSION,
1775
+ "polling_id": polling_id,
1776
+ "lifecycle_id": lifecycle_id,
1777
+ "lifecycle_no": 1,
1778
+ "created_at": utc_now(),
1779
+ })
1780
+ _atomic_json(active.lifecycle_root / "state.json", {
1781
+ "schema_version": SCHEMA_VERSION,
1782
+ "state": "created",
1783
+ "lifecycle_id": lifecycle_id,
1784
+ })
1785
+ # 指针更新放在所有 manifest 落盘之后,保证 current 指向的必已完整
1786
+ _write_current(root, polling_id, lifecycle_id, next_no, 1)
1787
+ # 保留既有 project_uid:索引重建不得把项目身份抹掉(否则下一次
1788
+ # ``_identity_mismatch`` 会误判成「他人布局」,正常项目反被拒绝)。
1789
+ index_path = base / "index" / "index.json"
1790
+ index_uid = ""
1791
+ try:
1792
+ if index_path.is_file() and not index_path.is_symlink():
1793
+ index_uid = str(_read_json(index_path).get(PROJECT_UID_KEY) or "")
1794
+ except (OSError, ValueError, LayoutError):
1795
+ index_uid = ""
1796
+ _atomic_json(index_path, {
1797
+ "schema_version": SCHEMA_VERSION,
1798
+ "last_polling_id": polling_id,
1799
+ "last_lifecycle_id": lifecycle_id,
1800
+ PROJECT_UID_KEY: index_uid or _project_id(root),
1801
+ "updated_at": utc_now(),
1802
+ })
1803
+ return active
1804
+
1805
+
1806
+ def update_session_state(root: Path, updates: dict[str, Any]) -> dict[str, Any]:
1807
+ """Atomically update the public Session state stored beside its Rounds.
1808
+
1809
+ ``pollings/<id>/state.json`` is the Session-level index. Round runtime
1810
+ files are intentionally disposable checkpoints and must not be used to
1811
+ count a whole Session across multiple Rounds.
1812
+ """
1813
+ if not isinstance(updates, dict):
1814
+ raise LayoutError("Session 状态更新必须是对象")
1815
+ root = root.resolve()
1816
+ base = bugx_root(root)
1817
+ if not base.is_dir() or base.is_symlink():
1818
+ raise LayoutError(f"缺少或不安全的 .bugx 目录: {base}")
1819
+ with _project_lock(root):
1820
+ active = require(root)
1821
+ current = read_current(root)
1822
+ # 指针完整性:current 指向的 polling/lifecycle 必须与 manifest 一致
1823
+ _validate_polling_manifest(root, str(current["polling_id"]),
1824
+ expected_no=int(current["polling_no"]))
1825
+ _validate_lifecycle_manifest(root, str(current["polling_id"]),
1826
+ str(current["lifecycle_id"]),
1827
+ expected_no=int(current["lifecycle_no"]))
1828
+ # 会话归属:active 的 polling 必须等于 current polling
1829
+ if active.polling_root.name != str(current["polling_id"]):
1830
+ raise LayoutError(
1831
+ f"Session 归属不一致: active {active.polling_root.name} vs current {current['polling_id']}"
1832
+ )
1833
+ if active.lifecycle_root.name != str(current["lifecycle_id"]):
1834
+ raise LayoutError(
1835
+ f"Lifecycle 指针不一致: active {active.lifecycle_root.name} vs current {current['lifecycle_id']}"
1836
+ )
1837
+ payload = _read_json(active.session_state)
1838
+ # 会话文件归属校验
1839
+ if payload.get("polling_id") and payload.get("polling_id") != active.polling_root.name:
1840
+ raise LayoutError(
1841
+ f"Session state 归属不一致: {payload.get('polling_id')} vs {active.polling_root.name}"
1842
+ )
1843
+ if payload.get("session_id") and payload.get("session_id") != active.polling_root.name:
1844
+ # session_id 与 polling_id 同义,允许一致性校验
1845
+ if str(payload.get("session_id")) != active.polling_root.name and str(payload.get("session_id")) != str(payload.get("polling_id") or ""):
1846
+ raise LayoutError(f"Session state session_id 不一致: {payload.get('session_id')}")
1847
+ payload.update(updates)
1848
+ # 禁止通过 updates 悄然篡改归属指针
1849
+ if payload.get("polling_id") and payload.get("polling_id") != active.polling_root.name:
1850
+ raise LayoutError(f"禁止篡改 Session polling_id: {payload.get('polling_id')}")
1851
+ if payload.get("session_id") and str(payload.get("session_id")) != active.polling_root.name:
1852
+ raise LayoutError(f"禁止篡改 Session session_id: {payload.get('session_id')}")
1853
+ payload["schema_version"] = SCHEMA_VERSION
1854
+ payload["session_id"] = str(payload.get("session_id") or active.polling_root.name)
1855
+ _atomic_json(active.session_state, payload)
1856
+ return payload
1857
+
1858
+
1859
+ _FORBIDDEN_BROAD_PATTERNS = (
1860
+ re.compile(r"\bfind\s+(?:-[a-zA-Z0-9_-]+\s+)*(?:/Users|/home|/private|\$HOME|\$\{HOME\}|/|~)(?:\s|$|/)"),
1861
+ re.compile(r"\b(?:grep\s+.*-[a-zA-Z0-9]*r|grep\s+.*--recursive|rgrep\b).*(?:\s|^)(?:/Users|/home|/private|\$HOME|\$\{HOME\}|/|~)(?:\s|$|/)"),
1862
+ re.compile(r"\bls\s+(?:-[a-zA-Z0-9]+\s+)*(?:/Users(?:\*|/|\s|$)|/(?:\*|\s|$)|~(?:\*|/|\s|$))"),
1863
+ )
1864
+
1865
+
1866
+ def assert_safe_command(cmd: str, *, root: Path | None = None) -> None:
1867
+ """前置校验待执行的外部命令,坚决拦截违规全盘广域搜索反模式 (DOC-170)。
1868
+
1869
+ 根据《耗时防卫宪法》第一条:严禁在排查或任何自动化任务中执行 find ~、find /Users/、find /
1870
+ 等跨越当前工作区边界的发散式全盘搜索。命中即刻抛出 LayoutError 阻断执行。
1871
+ """
1872
+ if not isinstance(cmd, str) or not cmd.strip():
1873
+ return
1874
+ normalized = " ".join(cmd.strip().split())
1875
+ for pat in _FORBIDDEN_BROAD_PATTERNS:
1876
+ if pat.search(normalized):
1877
+ raise LayoutError(
1878
+ f"[FATAL_BLOCKED] 命令安全防卫拦截:禁止执行发散式全盘搜索 '{cmd}'!"
1879
+ "根据《耗时防卫宪法》,文件排查必须严格限定在当前被测项目作用域内,"
1880
+ "严禁发起无边界全盘扫描(单次将导致 120 秒超时黑洞)。"
1881
+ )