bugx-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (751) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +280 -2
  3. package/core/CATALOG.json +141 -0
  4. package/core/README.md +254 -0
  5. package/core/adapters/README.md +35 -0
  6. package/core/adapters/android-interaction.json +81 -0
  7. package/core/adapters/android.json +24 -0
  8. package/core/adapters/desktop-macos.json +20 -0
  9. package/core/adapters/ios-interaction.json +34 -0
  10. package/core/adapters/ios.json +23 -0
  11. package/core/adapters/memory-macos.json +24 -0
  12. package/core/agent/README.md +50 -0
  13. package/core/agent/__init__.py +146 -0
  14. package/core/agent/agent_artifacts.py +764 -0
  15. package/core/agent/agent_eval.py +1073 -0
  16. package/core/agent/agent_execution.py +552 -0
  17. package/core/agent/agent_orchestrator.py +1345 -0
  18. package/core/agent/agent_targets.py +871 -0
  19. package/core/agent/agent_workspace.py +770 -0
  20. package/core/assets/README.md +24 -0
  21. package/core/assets/bugx-avatar-1024.png +0 -0
  22. package/core/assets/bugx-avatar-512.png +0 -0
  23. package/core/assets/bugx-avatar-tight.svg +23 -0
  24. package/core/assets/bugx-avatar.svg +28 -0
  25. package/core/assets/bugx-hero-cn.png +0 -0
  26. package/core/assets/bugx-hero-en.png +0 -0
  27. package/core/assets/project-layout.md +42 -0
  28. package/core/audit_packs/README.md +37 -0
  29. package/core/audit_packs/data-audit/manifest.json +94 -0
  30. package/core/audit_packs/data-audit/stages/00-scope.md +14 -0
  31. package/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
  32. package/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
  33. package/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
  34. package/core/audit_packs/desktop-audit/manifest.json +123 -0
  35. package/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
  36. package/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
  37. package/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
  38. package/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
  39. package/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
  40. package/core/audit_packs/memory-testing.md +227 -0
  41. package/core/audit_packs/mobile-audit/manifest.json +155 -0
  42. package/core/audit_packs/mobile-audit/modules/android.md +19 -0
  43. package/core/audit_packs/mobile-audit/modules/h5.md +18 -0
  44. package/core/audit_packs/mobile-audit/modules/ios.md +25 -0
  45. package/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
  46. package/core/audit_packs/mobile-audit/modules/webview.md +18 -0
  47. package/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
  48. package/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
  49. package/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
  50. package/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
  51. package/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
  52. package/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
  53. package/core/audit_packs/native-audit/manifest.json +127 -0
  54. package/core/audit_packs/native-audit/stages/00-scope.md +14 -0
  55. package/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
  56. package/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
  57. package/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
  58. package/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
  59. package/core/audit_packs/platform-testing.md +174 -0
  60. package/core/audit_packs/web-audit/manifest.json +191 -0
  61. package/core/audit_packs/web-audit/modules/graphql.md +5 -0
  62. package/core/audit_packs/web-audit/modules/h5.md +18 -0
  63. package/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
  64. package/core/audit_packs/web-audit/modules/oauth.md +4 -0
  65. package/core/audit_packs/web-audit/modules/upload.md +4 -0
  66. package/core/audit_packs/web-audit/modules/websocket.md +4 -0
  67. package/core/audit_packs/web-audit/stages/00-scope.md +13 -0
  68. package/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
  69. package/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
  70. package/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
  71. package/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
  72. package/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
  73. package/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
  74. package/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
  75. package/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
  76. package/core/autonomous_cve/INTERFACE.md +61 -0
  77. package/core/autonomous_cve/README.md +58 -0
  78. package/core/autonomous_cve/SPEC.md +25 -0
  79. package/core/autonomous_cve/__init__.py +109 -0
  80. package/core/autonomous_cve/attack_graph.py +1096 -0
  81. package/core/autonomous_cve/attack_graph_store.py +1822 -0
  82. package/core/autonomous_cve/audit_campaign.py +1232 -0
  83. package/core/autonomous_cve/behavior_graph.py +459 -0
  84. package/core/autonomous_cve/ghsa_advisories.py +174 -0
  85. package/core/autonomous_cve/models.py +93 -0
  86. package/core/autonomous_cve/mutator.py +87 -0
  87. package/core/autonomous_cve/patcher.py +126 -0
  88. package/core/autonomous_cve/scout.py +278 -0
  89. package/core/autonomous_cve/synthesizer.py +207 -0
  90. package/core/autonomous_cve/verifier.py +100 -0
  91. package/core/bugx.md +1299 -0
  92. package/core/bugx_paths.py +1846 -0
  93. package/core/cloud_sync/INTERFACE.md +32 -0
  94. package/core/cloud_sync/README.md +62 -0
  95. package/core/cloud_sync/SPEC.md +25 -0
  96. package/core/cloud_sync/__init__.py +23 -0
  97. package/core/cloud_sync/auto_sync.py +398 -0
  98. package/core/cloud_sync/cloud_client.py +1199 -0
  99. package/core/cloud_sync/cloud_onboard.py +702 -0
  100. package/core/cloud_sync/cloud_schema.py +648 -0
  101. package/core/cloud_sync/consent.py +81 -0
  102. package/core/cloud_sync/device_identity.py +307 -0
  103. package/core/cloud_sync/endpoint_router.py +415 -0
  104. package/core/cloud_sync/flywheel_client.py +760 -0
  105. package/core/cloud_sync/network_transport.py +275 -0
  106. package/core/cloud_sync/onboard_wizard.py +493 -0
  107. package/core/cloud_sync/sensitive_filter.py +285 -0
  108. package/core/cloud_sync/sync_pull.py +695 -0
  109. package/core/cloud_sync/sync_push.py +721 -0
  110. package/core/contracts/AGENT_GUIDE.md +362 -0
  111. package/core/contracts/README.md +34 -0
  112. package/core/contracts/bugx-blackbox.md +541 -0
  113. package/core/contracts/bugx-opencode.md +469 -0
  114. package/core/contracts/bugx-quick.md +44 -0
  115. package/core/contracts/bugx-runtime-contract.md +353 -0
  116. package/core/contracts/bugx-worker.md +470 -0
  117. package/core/contracts/engine_gap_contracts.py +390 -0
  118. package/core/coverage/README.md +70 -0
  119. package/core/coverage/__init__.py +106 -0
  120. package/core/coverage/coverage_ai_review.py +185 -0
  121. package/core/coverage/coverage_backfill.py +54 -0
  122. package/core/coverage/coverage_bootstrap.py +713 -0
  123. package/core/coverage/coverage_business.py +36 -0
  124. package/core/coverage/coverage_cli.py +715 -0
  125. package/core/coverage/coverage_discovery.py +859 -0
  126. package/core/coverage/coverage_evidence.py +977 -0
  127. package/core/coverage/coverage_forensics.py +115 -0
  128. package/core/coverage/coverage_gate.py +277 -0
  129. package/core/coverage/coverage_intelligence.py +734 -0
  130. package/core/coverage/coverage_manifest.py +396 -0
  131. package/core/coverage/coverage_platform.py +77 -0
  132. package/core/coverage/coverage_validate.py +236 -0
  133. package/core/coverage/module_coverage.py +157 -0
  134. package/core/dev_harness/INTERFACE.md +20 -0
  135. package/core/dev_harness/README.md +21 -0
  136. package/core/dev_harness/SPEC.md +25 -0
  137. package/core/dev_harness/__init__.py +5 -0
  138. package/core/dev_harness/interaction_preset.py +408 -0
  139. package/core/engine-integrity.json +2625 -0
  140. package/core/fuzzing/README.md +49 -0
  141. package/core/fuzzing/__init__.py +82 -0
  142. package/core/fuzzing/concurrency_fuzzer.py +382 -0
  143. package/core/fuzzing/differential_oracle.py +629 -0
  144. package/core/fuzzing/fuzz_input.py +1188 -0
  145. package/core/fuzzing/stateful_fuzzer.py +332 -0
  146. package/core/governance/README.md +61 -0
  147. package/core/governance/__init__.py +130 -0
  148. package/core/governance/capacity_planner.py +124 -0
  149. package/core/governance/dependency_lock.py +317 -0
  150. package/core/governance/goal_governor.py +754 -0
  151. package/core/governance/guide_budget.py +458 -0
  152. package/core/governance/lockdown.sh +50 -0
  153. package/core/governance/readonly_enforcer.py +154 -0
  154. package/core/governance/runtime_tool_gate.py +373 -0
  155. package/core/governance/secret_redactor.py +772 -0
  156. package/core/governance/token_budget.py +38 -0
  157. package/core/host_acp/INTERFACE.md +36 -0
  158. package/core/host_acp/README.md +51 -0
  159. package/core/host_acp/SPEC.md +25 -0
  160. package/core/host_acp/__init__.py +121 -0
  161. package/core/host_acp/base.py +111 -0
  162. package/core/host_acp/claude.py +41 -0
  163. package/core/host_acp/cline.py +235 -0
  164. package/core/host_acp/codex.py +245 -0
  165. package/core/host_acp/dsh.py +48 -0
  166. package/core/host_acp/opencode.py +154 -0
  167. package/core/host_acp/pi.py +36 -0
  168. package/core/host_acp/zcode.py +41 -0
  169. package/core/host_runtime/INTERFACE.md +24 -0
  170. package/core/host_runtime/README.md +62 -0
  171. package/core/host_runtime/SPEC.md +25 -0
  172. package/core/host_runtime/__init__.py +21 -0
  173. package/core/host_runtime/adapters.py +412 -0
  174. package/core/host_runtime/autonomous_runner.py +1152 -0
  175. package/core/host_runtime/cline.py +435 -0
  176. package/core/host_runtime/common.py +103 -0
  177. package/core/host_runtime/free_models.py +786 -0
  178. package/core/host_runtime/host_bootstrap.py +389 -0
  179. package/core/host_runtime/host_evaluators.py +721 -0
  180. package/core/host_runtime/host_probe.py +41 -0
  181. package/core/host_runtime/host_provider_arbitrator.py +777 -0
  182. package/core/host_runtime/host_registry.py +655 -0
  183. package/core/host_runtime/host_usage.py +127 -0
  184. package/core/host_runtime/mcp_process_tracker.py +509 -0
  185. package/core/host_runtime/mcp_registry_gate.py +368 -0
  186. package/core/hosts/INTERFACE.md +51 -0
  187. package/core/hosts/README.md +67 -0
  188. package/core/hosts/SPEC.md +25 -0
  189. package/core/hosts/__init__.py +136 -0
  190. package/core/hosts/_base_usage.py +152 -0
  191. package/core/hosts/_codex_usage.py +297 -0
  192. package/core/hosts/_dsh_usage.py +184 -0
  193. package/core/hosts/_mcp_toml.py +365 -0
  194. package/core/hosts/_zcode_usage.py +269 -0
  195. package/core/hosts/base.py +451 -0
  196. package/core/hosts/claude.py +157 -0
  197. package/core/hosts/cline.py +225 -0
  198. package/core/hosts/codex.py +948 -0
  199. package/core/hosts/dsh.py +518 -0
  200. package/core/hosts/opencode.py +358 -0
  201. package/core/hosts/pi.py +151 -0
  202. package/core/hosts/zcode.py +219 -0
  203. package/core/i18n.py +252 -0
  204. package/core/infra/README.md +39 -0
  205. package/core/infra/__init__.py +15 -0
  206. package/core/infra/build_info.py +86 -0
  207. package/core/infra/client_metadata.py +185 -0
  208. package/core/infra/python_runtime.py +540 -0
  209. package/core/infra/safe_xml.py +221 -0
  210. package/core/launch_bugx.py +118 -0
  211. package/core/launch_phases/INTERFACE.md +31 -0
  212. package/core/launch_phases/README.md +106 -0
  213. package/core/launch_phases/SPEC.md +25 -0
  214. package/core/launch_phases/__init__.py +29 -0
  215. package/core/launch_phases/candidate_revalidation.py +484 -0
  216. package/core/launch_phases/common.py +1041 -0
  217. package/core/launch_phases/finding_confirm_phase.py +387 -0
  218. package/core/launch_phases/finding_settlement.py +1245 -0
  219. package/core/launch_phases/findings_adjudication.py +666 -0
  220. package/core/launch_phases/findings_snapshot.py +357 -0
  221. package/core/launch_phases/judge_phase.py +791 -0
  222. package/core/launch_phases/lesson_context.py +536 -0
  223. package/core/launch_phases/lifecycle_reporter.py +627 -0
  224. package/core/launch_phases/orchestrator_controls.py +682 -0
  225. package/core/launch_phases/post_commit.py +567 -0
  226. package/core/launch_phases/post_coverage_sync.py +591 -0
  227. package/core/launch_phases/post_dry_run.py +817 -0
  228. package/core/launch_phases/post_observability.py +367 -0
  229. package/core/launch_phases/post_phase.py +1087 -0
  230. package/core/launch_phases/post_receipt.py +362 -0
  231. package/core/launch_phases/post_round_lifecycle.py +786 -0
  232. package/core/launch_phases/pre_phase.py +1029 -0
  233. package/core/launch_phases/pre_recon_scout.py +862 -0
  234. package/core/launch_phases/pre_state_builder.py +1286 -0
  235. package/core/launch_phases/report_sharing.py +414 -0
  236. package/core/launch_phases/round_orchestrator.py +1133 -0
  237. package/core/launch_phases/session_runtime.py +1623 -0
  238. package/core/launch_phases/startup_gates.py +1022 -0
  239. package/core/launch_phases/startup_interaction.py +947 -0
  240. package/core/launch_phases/startup_version_gate.py +873 -0
  241. package/core/launch_phases/supervisor_bridge.py +1224 -0
  242. package/core/launch_phases/supervisor_coverage.py +417 -0
  243. package/core/launch_phases/supervisor_degraded.py +1219 -0
  244. package/core/launch_phases/worker_barriers.py +414 -0
  245. package/core/launch_phases/worker_orchestrator.py +1166 -0
  246. package/core/launch_phases/worker_prior.py +749 -0
  247. package/core/ledger/INTERFACE.md +35 -0
  248. package/core/ledger/README.md +160 -0
  249. package/core/ledger/SPEC.md +25 -0
  250. package/core/ledger/__init__.py +67 -0
  251. package/core/ledger/_facade.py +226 -0
  252. package/core/ledger/archive_ops.py +572 -0
  253. package/core/ledger/auto_materialization.py +459 -0
  254. package/core/ledger/bug-log.md +22 -0
  255. package/core/ledger/cli.py +270 -0
  256. package/core/ledger/export_ops.py +549 -0
  257. package/core/ledger/finding_confirmation.py +1274 -0
  258. package/core/ledger/finding_io.py +299 -0
  259. package/core/ledger/finding_lifecycle.py +307 -0
  260. package/core/ledger/finding_verification.py +369 -0
  261. package/core/ledger/incidents.py +999 -0
  262. package/core/ledger/lesson-replay-cases.json +20 -0
  263. package/core/ledger/lesson_ledger.py +241 -0
  264. package/core/ledger/lesson_replay.py +272 -0
  265. package/core/ledger/life_ledger.py +668 -0
  266. package/core/ledger/mistake-book.md +130 -0
  267. package/core/ledger/patterns.py +681 -0
  268. package/core/ledger/receipt_contract.py +253 -0
  269. package/core/ledger/schema.py +1192 -0
  270. package/core/ledger/sync_ops.py +935 -0
  271. package/core/ledger/tool_experience.py +682 -0
  272. package/core/ledger/verify_life.py +1526 -0
  273. package/core/lesson-ledger.json +275 -0
  274. package/core/locales/README.md +19 -0
  275. package/core/locales/en-US.json +462 -0
  276. package/core/locales/zh-CN.json +462 -0
  277. package/core/mcp_handlers/INTERFACE.md +75 -0
  278. package/core/mcp_handlers/README.md +62 -0
  279. package/core/mcp_handlers/SPEC.md +25 -0
  280. package/core/mcp_handlers/__init__.py +128 -0
  281. package/core/mcp_handlers/base.py +697 -0
  282. package/core/mcp_handlers/channel_lifecycle.py +696 -0
  283. package/core/mcp_handlers/graph_handlers.py +222 -0
  284. package/core/mcp_handlers/knowledge_handlers.py +536 -0
  285. package/core/mcp_handlers/mining_handlers.py +586 -0
  286. package/core/mcp_handlers/resource_prompt_table.py +116 -0
  287. package/core/mcp_handlers/retrieval_handlers.py +239 -0
  288. package/core/mcp_handlers/rpc_server.py +465 -0
  289. package/core/mcp_handlers/supervisor_handlers.py +1435 -0
  290. package/core/mcp_handlers/telemetry_handlers.py +227 -0
  291. package/core/mcp_handlers/tool_table.py +1015 -0
  292. package/core/mcp_runtime_support/README.md +21 -0
  293. package/core/mcp_runtime_support/__init__.py +1 -0
  294. package/core/mcp_runtime_support/common.py +363 -0
  295. package/core/mcp_runtime_support/environment.py +605 -0
  296. package/core/mcp_runtime_support/verifier.py +810 -0
  297. package/core/metadata.txt +5 -0
  298. package/core/planning/README.md +157 -0
  299. package/core/planning/__init__.py +242 -0
  300. package/core/planning/capability_plan.py +187 -0
  301. package/core/planning/capability_planner.py +195 -0
  302. package/core/planning/domain_archetype.py +542 -0
  303. package/core/planning/domain_router.py +267 -0
  304. package/core/planning/dynamic_flow_analyzer.py +328 -0
  305. package/core/planning/impact_pruner.py +435 -0
  306. package/core/planning/intent_adjudicator.py +175 -0
  307. package/core/planning/judge_pipeline.py +1163 -0
  308. package/core/planning/logic_analysis.py +419 -0
  309. package/core/planning/prompt_harness.py +1702 -0
  310. package/core/planning/source_inspector.py +267 -0
  311. package/core/planning/spec_harvester.py +449 -0
  312. package/core/planning/target_sandbox_manager.py +573 -0
  313. package/core/planning/test_capability_verifier.py +1364 -0
  314. package/core/planning/tools-kb.md +38 -0
  315. package/core/planning/unit_kind.py +122 -0
  316. package/core/probes/INTERFACE.md +73 -0
  317. package/core/probes/README.md +51 -0
  318. package/core/probes/SPEC.md +26 -0
  319. package/core/probes/__init__.py +70 -0
  320. package/core/probes/android_probe.py +384 -0
  321. package/core/probes/base.py +147 -0
  322. package/core/probes/codebase_memory_probe.py +590 -0
  323. package/core/probes/desktop_probe.py +238 -0
  324. package/core/probes/differential_probe.py +356 -0
  325. package/core/probes/efficiency_probe.py +168 -0
  326. package/core/probes/ios_binary_probe.py +368 -0
  327. package/core/probes/memory_probe.py +326 -0
  328. package/core/probes/miniprogram_probe.py +323 -0
  329. package/core/probes/mobile_probe.py +281 -0
  330. package/core/probes/native_probe.py +214 -0
  331. package/core/probes/openwiki_probe.py +193 -0
  332. package/core/probes/pattern_probe.py +347 -0
  333. package/core/probes/platform_probe.py +343 -0
  334. package/core/probes/probe_registry.py +1669 -0
  335. package/core/probes/sast_probe.py +1009 -0
  336. package/core/probes/sast_rules.py +841 -0
  337. package/core/probes/sca_scanner.py +731 -0
  338. package/core/probes/web_probe.py +359 -0
  339. package/core/project_profiler/INTERFACE.md +62 -0
  340. package/core/project_profiler/README.md +53 -0
  341. package/core/project_profiler/SPEC.md +28 -0
  342. package/core/project_profiler/__init__.py +201 -0
  343. package/core/project_profiler/arbitrator.py +311 -0
  344. package/core/project_profiler/constants.py +247 -0
  345. package/core/project_profiler/detector.py +392 -0
  346. package/core/project_profiler/extractors.py +836 -0
  347. package/core/project_profiler/fingerprint.py +116 -0
  348. package/core/project_profiler/storage.py +258 -0
  349. package/core/project_profiler/strategy.py +265 -0
  350. package/core/prompts/README.md +35 -0
  351. package/core/prompts/codex_dialog_dispatch.md +9 -0
  352. package/core/prompts/command_routing_en.md +42 -0
  353. package/core/prompts/command_routing_zh.md +42 -0
  354. package/core/prompts/l0_router.md +47 -0
  355. package/core/prompts/rules/anti_patterns.md +16 -0
  356. package/core/prompts/rules/concurrency_rules.md +14 -0
  357. package/core/prompts/rules/memory_leak_rules.md +13 -0
  358. package/core/prompts/rules/prompt_injection_defense.md +13 -0
  359. package/core/prompts/stages/stage_explore.md +31 -0
  360. package/core/prompts/stages/stage_gate.md +43 -0
  361. package/core/prompts/stages/stage_mutate.md +42 -0
  362. package/core/prompts/stages/stage_repair.md +85 -0
  363. package/core/repair/README.md +74 -0
  364. package/core/repair/__init__.py +169 -0
  365. package/core/repair/fix_watchlist.py +391 -0
  366. package/core/repair/l7_dynamic.py +418 -0
  367. package/core/repair/l7_repair_loop.py +465 -0
  368. package/core/repair/l7_selfcheck.py +862 -0
  369. package/core/repair/minimize_repro.py +466 -0
  370. package/core/repair/patch_synthesizer.py +617 -0
  371. package/core/repair/regression_pack.py +379 -0
  372. package/core/repair/rsi_fixer.py +910 -0
  373. package/core/repair/rsi_loop.py +313 -0
  374. package/core/repair/rsi_repair.py +348 -0
  375. package/core/repair/rsi_rounds.py +212 -0
  376. package/core/repair/rsi_scope.py +262 -0
  377. package/core/repair/self_heal.py +604 -0
  378. package/core/repair/test_generator.py +1108 -0
  379. package/core/repair/test_quality_auditor.py +410 -0
  380. package/core/repair/test_strategy.py +511 -0
  381. package/core/report_engine/INTERFACE.md +59 -0
  382. package/core/report_engine/README.md +69 -0
  383. package/core/report_engine/SPEC.md +28 -0
  384. package/core/report_engine/__init__.py +47 -0
  385. package/core/report_engine/attestation.py +224 -0
  386. package/core/report_engine/authority.py +255 -0
  387. package/core/report_engine/finding_report.py +417 -0
  388. package/core/report_engine/formal_report_builder.py +924 -0
  389. package/core/report_engine/html_renderers.py +696 -0
  390. package/core/report_engine/models.py +761 -0
  391. package/core/report_engine/pdf_exporter.py +231 -0
  392. package/core/report_engine/projects_assets.py +730 -0
  393. package/core/report_engine/report_client.py +743 -0
  394. package/core/report_engine/report_data_builder.py +388 -0
  395. package/core/report_engine/report_share.py +459 -0
  396. package/core/report_engine/sast_bridge.py +116 -0
  397. package/core/report_engine/server.py +822 -0
  398. package/core/report_engine/visual_report_builder.py +796 -0
  399. package/core/report_engine/web-conformance.md +63 -0
  400. package/core/report_engine/web_conformance.py +459 -0
  401. package/core/report_engine/workbench_assets.py +484 -0
  402. package/core/retrieval/INTERFACE.md +20 -0
  403. package/core/retrieval/README.md +161 -0
  404. package/core/retrieval/SPEC.md +25 -0
  405. package/core/retrieval/__init__.py +3 -0
  406. package/core/retrieval/code_analyzer.py +1684 -0
  407. package/core/retrieval/codebase_memory_bridge.py +337 -0
  408. package/core/retrieval/context_assembler.py +234 -0
  409. package/core/retrieval/corpus_fetch.py +369 -0
  410. package/core/retrieval/graph_ego.py +597 -0
  411. package/core/retrieval/knowledge_auto.py +662 -0
  412. package/core/retrieval/knowledge_sources.py +168 -0
  413. package/core/retrieval/knowledge_sync.py +909 -0
  414. package/core/retrieval/memory_store.py +480 -0
  415. package/core/retrieval/query_planner.py +1020 -0
  416. package/core/retrieval/rrf_engine.py +137 -0
  417. package/core/retrieval/slice_extractor.py +1209 -0
  418. package/core/retrieval/slice_normalizer.py +373 -0
  419. package/core/retrieval/slice_spec.py +357 -0
  420. package/core/retrieval/symbol_index.py +1132 -0
  421. package/core/retrieval/universal_code_matcher.py +437 -0
  422. package/core/retrieval/xerj_bridge.py +476 -0
  423. package/core/retrieval/xerj_supervisor.py +362 -0
  424. package/core/rules/README.md +33 -0
  425. package/core/rules/ios/PROVENANCE.json +30 -0
  426. package/core/rules/ios/crypto.yaml +36 -0
  427. package/core/rules/ios/network.yaml +20 -0
  428. package/core/rules/ios/resilience.yaml +47 -0
  429. package/core/rules/ios/storage.yaml +48 -0
  430. package/core/rules/mastg/LICENSE +173 -0
  431. package/core/rules/mastg/PROVENANCE.json +270 -0
  432. package/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
  433. package/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
  434. package/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
  435. package/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
  436. package/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
  437. package/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
  438. package/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
  439. package/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
  440. package/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
  441. package/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
  442. package/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
  443. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
  444. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
  445. package/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
  446. package/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
  447. package/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
  448. package/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
  449. package/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
  450. package/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
  451. package/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
  452. package/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
  453. package/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
  454. package/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
  455. package/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
  456. package/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
  457. package/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
  458. package/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
  459. package/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
  460. package/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
  461. package/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
  462. package/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
  463. package/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
  464. package/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
  465. package/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
  466. package/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
  467. package/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
  468. package/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
  469. package/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
  470. package/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
  471. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
  472. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
  473. package/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
  474. package/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
  475. package/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
  476. package/core/rules/mastg/mastg-android-strictmode.yml +10 -0
  477. package/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
  478. package/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
  479. package/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
  480. package/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
  481. package/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
  482. package/core/rules/miniprogram/PROVENANCE.json +26 -0
  483. package/core/rules/miniprogram/network.yaml +37 -0
  484. package/core/rules/miniprogram/platform.yaml +36 -0
  485. package/core/rules/miniprogram/storage.yaml +48 -0
  486. package/core/rules/mobsfscan-swift/LICENSE +165 -0
  487. package/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
  488. package/core/rules/mobsfscan-swift/auth.yaml +59 -0
  489. package/core/rules/mobsfscan-swift/crypto.yaml +66 -0
  490. package/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
  491. package/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
  492. package/core/rules/mobsfscan-swift/logging.yaml +23 -0
  493. package/core/rules/mobsfscan-swift/network.yaml +55 -0
  494. package/core/rules/mobsfscan-swift/resilience.yaml +29 -0
  495. package/core/rules/mobsfscan-swift/secrets.yaml +33 -0
  496. package/core/rules/mobsfscan-swift/storage.yaml +29 -0
  497. package/core/rules/mobsfscan-swift/webview.yaml +32 -0
  498. package/core/runtime/README.md +198 -0
  499. package/core/runtime/__init__.py +3 -0
  500. package/core/runtime/bugx_logging.py +1393 -0
  501. package/core/runtime/daemon_runner.py +623 -0
  502. package/core/runtime/fixture_solidify.py +449 -0
  503. package/core/runtime/global_telemetry.py +549 -0
  504. package/core/runtime/incident_eval.py +148 -0
  505. package/core/runtime/interaction.py +605 -0
  506. package/core/runtime/interaction_store.py +435 -0
  507. package/core/runtime/interactive_menu.py +95 -0
  508. package/core/runtime/log_analytics.py +922 -0
  509. package/core/runtime/mining_quality_framework.py +1387 -0
  510. package/core/runtime/model_runner.py +769 -0
  511. package/core/runtime/platform_adapter.py +579 -0
  512. package/core/runtime/prep_validate.py +476 -0
  513. package/core/runtime/project_graph.py +827 -0
  514. package/core/runtime/project_init.py +481 -0
  515. package/core/runtime/project_profile.py +224 -0
  516. package/core/runtime/project_settings.py +963 -0
  517. package/core/runtime/provider_window.py +97 -0
  518. package/core/runtime/resume_ticket.py +115 -0
  519. package/core/runtime/scenario_eval.py +814 -0
  520. package/core/runtime/seed_drill.py +549 -0
  521. package/core/runtime/self_audit.py +550 -0
  522. package/core/runtime/session_profile.py +205 -0
  523. package/core/runtime/setup_ui_env.py +229 -0
  524. package/core/runtime/startup_environment.py +859 -0
  525. package/core/runtime/sync_store.py +1421 -0
  526. package/core/runtime/tool_install_targets.py +18 -0
  527. package/core/schemas/README.md +35 -0
  528. package/core/schemas/agent-graph.schema.json +368 -0
  529. package/core/schemas/attack-graph.schema.json +88 -0
  530. package/core/schemas/evidence-bundle.schema.json +33 -0
  531. package/core/schemas/skill-pack.schema.json +230 -0
  532. package/core/schemas/worker-checkpoint.schema.json +119 -0
  533. package/core/secure_atomic.py +289 -0
  534. package/core/seed_corpus/README.md +55 -0
  535. package/core/seed_corpus/c.txt +29 -0
  536. package/core/seed_corpus/cpp.txt +32 -0
  537. package/core/seed_corpus/css.txt +70 -0
  538. package/core/seed_corpus/go.txt +46 -0
  539. package/core/seed_corpus/java.txt +30 -0
  540. package/core/seed_corpus/javascript.txt +55 -0
  541. package/core/seed_corpus/kotlin.txt +28 -0
  542. package/core/seed_corpus/python.txt +71 -0
  543. package/core/seed_corpus/rust.txt +53 -0
  544. package/core/seed_corpus/swift.txt +29 -0
  545. package/core/seed_corpus/typescript.txt +29 -0
  546. package/core/skills/README.md +53 -0
  547. package/core/skills/__init__.py +189 -0
  548. package/core/skills/bugx_docs_mcp_server.py +416 -0
  549. package/core/skills/bugx_mcp_server.py +1134 -0
  550. package/core/skills/mcp_runtime.py +968 -0
  551. package/core/skills/mcp_session_proof.py +605 -0
  552. package/core/skills/mobile_ui_inspector.py +405 -0
  553. package/core/skills/skill_pack.py +1214 -0
  554. package/core/skills/skill_synthesizer.py +1153 -0
  555. package/core/skills/tools_kb.py +313 -0
  556. package/core/supervisor/INTERFACE.md +121 -0
  557. package/core/supervisor/README.md +209 -0
  558. package/core/supervisor/SPEC.md +25 -0
  559. package/core/supervisor/__init__.py +175 -0
  560. package/core/supervisor/audit_supervisor.py +1015 -0
  561. package/core/supervisor/budget_governor.py +760 -0
  562. package/core/supervisor/checkpoint_handler.py +368 -0
  563. package/core/supervisor/checkpoint_pipeline.py +1322 -0
  564. package/core/supervisor/checkpoint_sync.py +640 -0
  565. package/core/supervisor/claim_events.py +74 -0
  566. package/core/supervisor/claim_sync.py +590 -0
  567. package/core/supervisor/cli.py +812 -0
  568. package/core/supervisor/context_sync.py +55 -0
  569. package/core/supervisor/coverage_sync.py +115 -0
  570. package/core/supervisor/finding_commit.py +470 -0
  571. package/core/supervisor/finding_sync.py +688 -0
  572. package/core/supervisor/finding_workflow.py +659 -0
  573. package/core/supervisor/finish_policy.py +224 -0
  574. package/core/supervisor/finish_sync.py +185 -0
  575. package/core/supervisor/graph_sync.py +669 -0
  576. package/core/supervisor/lease_manager.py +788 -0
  577. package/core/supervisor/lifecycle_blocks.py +124 -0
  578. package/core/supervisor/next_round_sync.py +126 -0
  579. package/core/supervisor/observability.py +140 -0
  580. package/core/supervisor/recovery_sync.py +165 -0
  581. package/core/supervisor/rejection_remedies.py +308 -0
  582. package/core/supervisor/round_governor.py +306 -0
  583. package/core/supervisor/serial_authorization.py +500 -0
  584. package/core/supervisor/start_sync.py +87 -0
  585. package/core/supervisor/state_store.py +249 -0
  586. package/core/supervisor/supervisor_host.py +511 -0
  587. package/core/supervisor/supervisor_models.py +1143 -0
  588. package/core/supervisor/systemic_failure.py +104 -0
  589. package/core/supervisor/task_scheduler.py +1640 -0
  590. package/core/supervisor/worker_checkpoint.py +223 -0
  591. package/core/supervisor/worker_execution.py +265 -0
  592. package/core/supervisor/worker_handoff.py +192 -0
  593. package/core/supervisor/worker_lifecycle.py +396 -0
  594. package/core/supervisor/worker_runtime.py +999 -0
  595. package/core/supervisor/worker_sync.py +89 -0
  596. package/core/supervisor_types/README.md +36 -0
  597. package/core/supervisor_types/__init__.py +0 -0
  598. package/core/supervisor_types/exceptions.py +52 -0
  599. package/core/supervisor_types/graph_models.py +357 -0
  600. package/core/supervisor_types/path_containment.py +151 -0
  601. package/core/supervisor_types/target_fingerprint.py +310 -0
  602. package/core/supervisor_types/worker_claim.py +402 -0
  603. package/core/webui/INTERFACE.md +50 -0
  604. package/core/webui/README.md +57 -0
  605. package/core/webui/SPEC.md +25 -0
  606. package/core/webui/__init__.py +11 -0
  607. package/core/webui/adapters/__init__.py +27 -0
  608. package/core/webui/adapters/base.py +87 -0
  609. package/core/webui/adapters/bugx.py +102 -0
  610. package/core/webui/adapters/claude.py +218 -0
  611. package/core/webui/adapters/cline.py +399 -0
  612. package/core/webui/adapters/codex.py +256 -0
  613. package/core/webui/adapters/dsh.py +173 -0
  614. package/core/webui/adapters/opencode.py +218 -0
  615. package/core/webui/adapters/pi.py +272 -0
  616. package/core/webui/adapters/registry.py +100 -0
  617. package/core/webui/adapters/zcode.py +312 -0
  618. package/core/webui/api_routes_post.py +668 -0
  619. package/core/webui/dispatcher.py +1376 -0
  620. package/core/webui/docs_session_service.py +473 -0
  621. package/core/webui/handler.py +674 -0
  622. package/core/webui/ide_cloud_service.py +526 -0
  623. package/core/webui/mcp_inspector.py +1743 -0
  624. package/core/webui/static/assets/index-CXAsl8mr.js +333 -0
  625. package/core/webui/static/assets/index-DHQUtWtx.css +1 -0
  626. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
  627. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
  628. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
  629. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
  630. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
  631. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
  632. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
  633. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
  634. package/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
  635. package/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
  636. package/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
  637. package/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
  638. package/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
  639. package/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
  640. package/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
  641. package/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
  642. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
  643. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
  644. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
  645. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
  646. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
  647. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
  648. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
  649. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
  650. package/core/webui/static/favicon.png +0 -0
  651. package/core/webui/static/icon-192.png +0 -0
  652. package/core/webui/static/index.html +42 -0
  653. package/core/webui/static/manifest.webmanifest +19 -0
  654. package/core/webui/static/project-settings.css +6458 -0
  655. package/core/webui/static/project-settings.js +9602 -0
  656. package/core/webui/static/sw.js +8 -0
  657. package/core/webui/workspace_service.py +218 -0
  658. package/docs/07_distribution/01_README_NPM.md +281 -0
  659. package/docs/07_distribution/README.md +16 -0
  660. package/docs/README.md +121 -0
  661. package/ecosystem/README.md +129 -0
  662. package/ecosystem/integrations/README.md +38 -0
  663. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +69 -0
  664. package/ecosystem/integrations/dsh/agents/bugx.md +27 -0
  665. package/ecosystem/integrations/dsh/dsh-patch.yml +18 -0
  666. package/ecosystem/integrations/dsh/mcp/cordis.patch.yml +4 -0
  667. package/ecosystem/integrations/dsh/mcp/index.js +219 -0
  668. package/ecosystem/integrations/dsh/mcp/package.json +28 -0
  669. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +70 -0
  670. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +229 -0
  671. package/ecosystem/integrations/dsh/ui/client.js +87 -0
  672. package/ecosystem/integrations/dsh/ui/cordis.patch.yml +4 -0
  673. package/ecosystem/integrations/dsh/ui/index.js +7 -0
  674. package/ecosystem/integrations/dsh/ui/package.json +27 -0
  675. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +53 -0
  676. package/ecosystem/integrations/opencode/mcp-lock.json +3067 -0
  677. package/ecosystem/integrations/opencode/opencode.json +118 -0
  678. package/ecosystem/integrations/pi/extensions/bugx/README.md +12 -0
  679. package/ecosystem/integrations/pi/extensions/bugx/index.ts +299 -0
  680. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +11 -0
  681. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +69 -0
  682. package/ecosystem/integrations/qoder/CONNECTORS.md +54 -0
  683. package/ecosystem/integrations/qoder/connector-meta.json +21 -0
  684. package/ecosystem/integrations/workbuddy/connector-meta.json +19 -0
  685. package/ecosystem/integrations/workbuddy/icon.png +0 -0
  686. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +70 -0
  687. package/ecosystem/plugins/README.md +37 -0
  688. package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +17 -0
  689. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +16 -0
  690. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +41 -0
  691. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +19 -0
  692. package/ecosystem/plugins/bugx/agents/bugx-judge.md +71 -0
  693. package/ecosystem/plugins/bugx/agents/bugx-worker.md +31 -0
  694. package/ecosystem/plugins/bugx/agents/bugx.md +74 -0
  695. package/ecosystem/plugins/bugx/assets/bugx-avatar-512.png +0 -0
  696. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +118 -0
  697. package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
  698. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +229 -0
  699. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
  700. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
  701. package/interfaces/README.md +143 -0
  702. package/interfaces/bin/README.md +35 -0
  703. package/interfaces/bin/bugx.js +80 -0
  704. package/interfaces/cli/README.md +90 -0
  705. package/interfaces/cli/bugx_cli/__init__.py +4 -0
  706. package/interfaces/cli/bugx_cli/cli.py +1678 -0
  707. package/interfaces/cli/bugx_cli/commands/__init__.py +1 -0
  708. package/interfaces/cli/bugx_cli/commands/advisory.py +94 -0
  709. package/interfaces/cli/bugx_cli/commands/agent.py +3944 -0
  710. package/interfaces/cli/bugx_cli/commands/audit.py +632 -0
  711. package/interfaces/cli/bugx_cli/commands/autonomous.py +260 -0
  712. package/interfaces/cli/bugx_cli/commands/cloud.py +1370 -0
  713. package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
  714. package/interfaces/cli/bugx_cli/commands/doctor.py +1345 -0
  715. package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
  716. package/interfaces/cli/bugx_cli/commands/interaction.py +244 -0
  717. package/interfaces/cli/bugx_cli/commands/knowledge.py +617 -0
  718. package/interfaces/cli/bugx_cli/commands/lifecycle.py +2763 -0
  719. package/interfaces/cli/bugx_cli/commands/patch.py +1014 -0
  720. package/interfaces/cli/bugx_cli/commands/plugin.py +2714 -0
  721. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +1446 -0
  722. package/interfaces/cli/bugx_cli/commands/plugin_cline.py +269 -0
  723. package/interfaces/cli/bugx_cli/commands/plugin_codex.py +74 -0
  724. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +728 -0
  725. package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +216 -0
  726. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +710 -0
  727. package/interfaces/cli/bugx_cli/commands/project.py +670 -0
  728. package/interfaces/cli/bugx_cli/commands/report.py +260 -0
  729. package/interfaces/cli/bugx_cli/commands/skill.py +251 -0
  730. package/interfaces/cli/bugx_cli/commands/stats.py +133 -0
  731. package/interfaces/cli/bugx_cli/commands/system.py +2567 -0
  732. package/interfaces/cli/bugx_cli/common.py +898 -0
  733. package/interfaces/cli/bugx_cli/host_adapters.py +1917 -0
  734. package/interfaces/cli/bugx_cli/hosts/__init__.py +80 -0
  735. package/interfaces/cli/bugx_cli/hosts/base.py +99 -0
  736. package/interfaces/cli/bugx_cli/hosts/registry.py +571 -0
  737. package/interfaces/cli/bugx_cli/hosts/template_engine.py +188 -0
  738. package/interfaces/cli/bugx_cli/infra/__init__.py +209 -0
  739. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +721 -0
  740. package/interfaces/cli/bugx_cli/infra/engine_installer.py +1937 -0
  741. package/interfaces/cli/bugx_cli/infra/host_sync.py +545 -0
  742. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +755 -0
  743. package/interfaces/cli/bugx_cli/infra/security.py +332 -0
  744. package/package.json +98 -4
  745. package/pyproject.toml +246 -0
  746. package/scripts/README.md +118 -0
  747. package/scripts/ensure-python.mjs +97 -0
  748. package/scripts/isolate-npm-readme.mjs +40 -0
  749. package/scripts/runtime.lock.json +31 -0
  750. package/scripts/sync-version.mjs +37 -0
  751. package/scripts/test-npm-wrapper.mjs +265 -0
@@ -0,0 +1,1345 @@
1
+ #!/usr/bin/env python3
2
+ """Deterministic, bounded graph orchestration for native BugX agents.
3
+
4
+ The engine owns graph state, immutable input snapshots, artifact receipts, and
5
+ controlled checks. It does not launch native agents or call host UI APIs; the
6
+ Host MCP channel binds native agent identities and dispatches the returned
7
+ Task prompt through its own native interface.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import contextlib
14
+ import datetime as dt
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import signal
21
+ import stat
22
+ import subprocess
23
+ import sys
24
+ import tempfile
25
+ import threading
26
+ import time
27
+ import uuid
28
+ from pathlib import Path, PurePosixPath
29
+ from typing import Any, Iterator, Mapping, Sequence
30
+
31
+ try:
32
+ import fcntl
33
+ except ImportError: # pragma: no cover - Windows uses msvcrt.
34
+ fcntl = None # type: ignore[assignment]
35
+
36
+ try:
37
+ import msvcrt
38
+ except ImportError: # pragma: no cover - POSIX uses fcntl.
39
+ msvcrt = None # type: ignore[assignment]
40
+
41
+ try:
42
+ import core.bugx_paths as bugx_paths
43
+ except ImportError:
44
+ from core import bugx_paths
45
+
46
+ try:
47
+ import core.secure_atomic as secure_atomic
48
+ except ImportError:
49
+ from core import secure_atomic
50
+
51
+
52
+ SCHEMA_VERSION = 1
53
+ MAX_ATTEMPTS = 3
54
+ MAX_CONCURRENCY = 16
55
+ MAX_SPEC_BYTES = 64 * 1024
56
+ MAX_TASK_TEXT_LENGTH = 8 * 1024
57
+ MAX_TARGET_FILES = 100
58
+ MAX_SNAPSHOT_FILES = 100_000
59
+ MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024 * 1024
60
+ MAX_CONTEXT_FILE_BYTES = 512 * 1024
61
+ MAX_CONTEXT_BYTES = 4 * 1024 * 1024
62
+ MAX_ENVELOPE_BYTES = 128 * 1024
63
+ MAX_ATTACHMENT_BYTES = 256 * 1024
64
+ MAX_ATTACHMENTS_BYTES = 300 * 1024
65
+ MAX_CHECK_FILES = 20
66
+ MAX_CHECK_TIMEOUT_SECONDS = 300
67
+ MAX_CHECK_OUTPUT_BYTES = 32 * 1024
68
+ GRAPH_ID_RE = re.compile(r"^[0-9a-f]{32}$")
69
+ SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
70
+ NATIVE_AGENT_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:@/-]{0,255}$")
71
+ STAGES = ("Recon", "Repro", "Review", "Patch", "Check", "Report")
72
+ ACTIVE_TASK_STATES = frozenset({"assigned", "running"})
73
+ RESERVED_TASK_STATES = frozenset({"offered", *ACTIVE_TASK_STATES})
74
+ TERMINAL_TASK_STATES = frozenset({"complete", "failed", "cancelled", "superseded"})
75
+ IGNORED_NAMES = frozenset({
76
+ ".bugx", ".git", ".hg", ".svn", ".DS_Store", "node_modules", "venv",
77
+ ".venv", "__pycache__", ".pytest_cache", ".mypy_cache", ".tox",
78
+ })
79
+
80
+ STAGE_INSTRUCTIONS = {
81
+ "Recon": (
82
+ "Inspect the immutable project snapshot and identify concrete candidate behavior. "
83
+ "Do not modify source files. Keep observations separate from hypotheses."
84
+ ),
85
+ "Repro": (
86
+ "Produce a minimal, repeatable reproduction for the candidate using the snapshot. "
87
+ "Do not modify source files and preserve exact commands, inputs, and observed output."
88
+ ),
89
+ "Review": (
90
+ "Independently review the candidate and reproduction artifacts. Verify the claimed "
91
+ "cause, scope, and evidence. Do not rely on the producer's conclusion alone."
92
+ ),
93
+ "Patch": (
94
+ "Apply the smallest change needed to address the reviewed issue, staying inside the "
95
+ "declared modification and ownership boundaries. Preserve all stated invariants."
96
+ ),
97
+ "Check": (
98
+ "Submit a bounded CheckPlan with tests under tests/ using graph_run_check. Do not "
99
+ "claim a check passed without its returned Observation."
100
+ ),
101
+ "Report": (
102
+ "Compile the final report from checkpointed artifacts and Observations. Clearly mark "
103
+ "unsupported or unverified claims; do not invent host or runtime evidence."
104
+ ),
105
+ }
106
+
107
+
108
+ class GraphError(RuntimeError):
109
+ """Invalid graph transition, identity, or bounded input."""
110
+
111
+
112
+ def _now() -> str:
113
+ return dt.datetime.now(dt.timezone.utc).isoformat(timespec="milliseconds")
114
+
115
+
116
+ def _canonical_json(value: object) -> bytes:
117
+ return json.dumps(
118
+ value, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
119
+ ).encode("utf-8")
120
+
121
+
122
+ def _text(value: object, name: str, *, maximum: int = MAX_TASK_TEXT_LENGTH) -> str:
123
+ if not isinstance(value, str) or not value.strip():
124
+ raise GraphError(f"{name} 必须是非空字符串")
125
+ if len(value) > maximum:
126
+ raise GraphError(f"{name} 过长(>{maximum})")
127
+ return value
128
+
129
+
130
+ def _string_list(
131
+ value: object, name: str, *, minimum: int = 0, maximum: int = 64,
132
+ ) -> list[str]:
133
+ if not isinstance(value, list) or len(value) < minimum or len(value) > maximum:
134
+ raise GraphError(f"{name} 必须是 {minimum}..{maximum} 项字符串数组")
135
+ result = []
136
+ for index, item in enumerate(value):
137
+ result.append(_text(item, f"{name}[{index}]"))
138
+ return result
139
+
140
+
141
+ def _safe_relative_path(value: object, name: str = "path") -> str:
142
+ if not isinstance(value, str) or not value or len(value) > 512:
143
+ raise GraphError(f"{name} 必须是非空相对路径")
144
+ if "\\" in value or "\x00" in value or ":" in value:
145
+ raise GraphError(f"{name} 格式无效")
146
+ path = PurePosixPath(value)
147
+ if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):
148
+ raise GraphError(f"{name} 必须是规范化的项目相对路径")
149
+ if any(part in IGNORED_NAMES for part in path.parts):
150
+ raise GraphError(f"{name} 位于被排除的项目目录")
151
+ normalized = path.as_posix()
152
+ if normalized != value:
153
+ raise GraphError(f"{name} 必须是规范化的项目相对路径")
154
+ return normalized
155
+
156
+
157
+ def _normalize_task_input(arguments: Mapping[str, object]) -> dict[str, object]:
158
+ target_files = _string_list(
159
+ arguments.get("target_files"), "target_files", minimum=1,
160
+ maximum=MAX_TARGET_FILES,
161
+ )
162
+ normalized_paths = [_safe_relative_path(item, "target_files") for item in target_files]
163
+ if len(set(normalized_paths)) != len(normalized_paths):
164
+ raise GraphError("target_files 不得包含重复路径")
165
+ patch_requested = arguments.get("patch_requested", False)
166
+ if not isinstance(patch_requested, bool):
167
+ raise GraphError("patch_requested 必须是布尔值")
168
+ concurrency = arguments.get("max_concurrency", 1)
169
+ if isinstance(concurrency, bool) or not isinstance(concurrency, int):
170
+ raise GraphError("max_concurrency 必须是整数")
171
+ if not 1 <= concurrency <= MAX_CONCURRENCY:
172
+ raise GraphError(f"max_concurrency 必须位于 1..{MAX_CONCURRENCY}")
173
+ value: dict[str, object] = {
174
+ "target": _text(arguments.get("target"), "target", maximum=2048),
175
+ "goal": _text(arguments.get("goal"), "goal"),
176
+ "modifications": _string_list(arguments.get("modifications"), "modifications", minimum=1),
177
+ "invariants": _string_list(arguments.get("invariants"), "invariants", minimum=1),
178
+ "ownership_boundaries": _string_list(
179
+ arguments.get("ownership_boundaries"), "ownership_boundaries", minimum=1,
180
+ ),
181
+ "acceptance_criteria": _string_list(
182
+ arguments.get("acceptance_criteria"), "acceptance_criteria", minimum=1,
183
+ ),
184
+ "target_files": normalized_paths,
185
+ "patch_requested": patch_requested,
186
+ "max_concurrency": concurrency,
187
+ }
188
+ if len(_canonical_json(value)) > MAX_SPEC_BYTES:
189
+ raise GraphError(f"Task Spec 超过 {MAX_SPEC_BYTES} 字节")
190
+ return value
191
+
192
+
193
+ def assemble_task_prompt(
194
+ task_input: Mapping[str, object], stage: str, attempt: int,
195
+ feedback: Mapping[str, object] | None = None,
196
+ ) -> str:
197
+ """Assemble one canonical, self-contained native Task prompt.
198
+
199
+ All caller-authored lines are included verbatim. A single function is
200
+ shared by initial tasks and revision attempts so neither path silently
201
+ drops scope, invariants, ownership, or acceptance evidence.
202
+ """
203
+ if stage not in STAGE_INSTRUCTIONS:
204
+ raise GraphError(f"未知 Graph 阶段: {stage}")
205
+ sections = [
206
+ "BugX native Task",
207
+ f"Stage: {stage} (attempt {attempt}/{MAX_ATTEMPTS})",
208
+ f"Stage objective: {STAGE_INSTRUCTIONS[stage]}",
209
+ f"Target: {task_input['target']}",
210
+ f"Goal: {task_input['goal']}",
211
+ "Requested modifications (verbatim):",
212
+ *[f"- {item}" for item in task_input["modifications"]],
213
+ "Invariants (must remain true):",
214
+ *[f"- {item}" for item in task_input["invariants"]],
215
+ "Ownership boundaries:",
216
+ *[f"- {item}" for item in task_input["ownership_boundaries"]],
217
+ "Observable acceptance criteria:",
218
+ *[f"- {item}" for item in task_input["acceptance_criteria"]],
219
+ "Declared snapshot files:",
220
+ *[f"- {item}" for item in task_input["target_files"]],
221
+ "Execution boundaries:",
222
+ "- Work only in the graph's private snapshot workspace.",
223
+ "- Do not call host UI APIs or claim that a native host action occurred.",
224
+ "- Do not invent observations, test results, identities, or artifact contents.",
225
+ "- Return a checkpoint with concrete evidence and an explicit outcome.",
226
+ ]
227
+ if feedback is not None:
228
+ sections.extend([
229
+ "Revision feedback from the previous attempt (verbatim):",
230
+ f"Reason: {feedback.get('reason', '')}",
231
+ "Context:",
232
+ json.dumps(feedback.get("context", {}), ensure_ascii=False, sort_keys=True),
233
+ ])
234
+ return "\n".join(sections)
235
+
236
+
237
+ def _new_task(
238
+ state: dict[str, Any], stage: str, attempt: int,
239
+ dependencies: Sequence[str], feedback: Mapping[str, object] | None = None,
240
+ ) -> dict[str, Any]:
241
+ graph_id = state["graph_id"]
242
+ task_id = "task_" + hashlib.sha256(
243
+ f"{graph_id}:{stage}:{attempt}".encode("utf-8")
244
+ ).hexdigest()[:24]
245
+ task_input = state["task_input"]
246
+ return {
247
+ "task_id": task_id,
248
+ "stage": stage,
249
+ "attempt": attempt,
250
+ "dependencies": list(dependencies),
251
+ "status": "pending",
252
+ "native_agent_id": None,
253
+ "fencing_token": 0,
254
+ "created_at": _now(),
255
+ "started_at": None,
256
+ "finished_at": None,
257
+ "feedback": dict(feedback or {}),
258
+ "prompt": assemble_task_prompt(task_input, stage, attempt, feedback),
259
+ "check_observation": None,
260
+ "checkpoint": None,
261
+ "failure_context": None,
262
+ }
263
+
264
+
265
+ def _copy_snapshot(source: Path, destination: Path) -> dict[str, object]:
266
+ """Copy regular project files into a private workspace without following links."""
267
+ if not source.is_dir() or source.is_symlink():
268
+ raise GraphError(f"snapshot source is not a regular directory: {source}")
269
+ source = source.resolve()
270
+ destination = Path(os.path.abspath(str(destination)))
271
+ try:
272
+ destination.relative_to(source)
273
+ except ValueError:
274
+ pass
275
+ else:
276
+ raise GraphError("graph private root must be outside the source project")
277
+ destination.mkdir(mode=0o700, parents=True, exist_ok=False)
278
+ count = 0
279
+ total_bytes = 0
280
+ excluded_links: list[str] = []
281
+ try:
282
+ for current, dirs, files in os.walk(source, topdown=True, followlinks=False):
283
+ current_path = Path(current)
284
+ relative_dir = current_path.relative_to(source)
285
+ kept_dirs: list[str] = []
286
+ for name in sorted(dirs):
287
+ if name in IGNORED_NAMES:
288
+ continue
289
+ source_dir = current_path / name
290
+ if source_dir.is_symlink():
291
+ if len(excluded_links) < 1000:
292
+ excluded_links.append((relative_dir / name).as_posix())
293
+ continue
294
+ kept_dirs.append(name)
295
+ dirs[:] = kept_dirs
296
+ target_dir = destination / relative_dir
297
+ target_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
298
+ for name in sorted(files):
299
+ if name in IGNORED_NAMES:
300
+ continue
301
+ source_file = current_path / name
302
+ relative = source_file.relative_to(source)
303
+ if source_file.is_symlink():
304
+ if len(excluded_links) < 1000:
305
+ excluded_links.append(relative.as_posix())
306
+ continue
307
+ try:
308
+ info = source_file.stat(follow_symlinks=False)
309
+ except OSError as exc:
310
+ raise GraphError(f"无法安全读取 snapshot 文件 {relative}: {exc}") from exc
311
+ if not source_file.is_file() or source_file.is_symlink():
312
+ continue
313
+ if info.st_size < 0 or total_bytes + info.st_size > MAX_SNAPSHOT_BYTES:
314
+ raise GraphError(f"snapshot 超过 {MAX_SNAPSHOT_BYTES} 字节")
315
+ count += 1
316
+ if count > MAX_SNAPSHOT_FILES:
317
+ raise GraphError(f"snapshot 文件数超过 {MAX_SNAPSHOT_FILES}")
318
+ target_file = destination / relative
319
+ target_file.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
320
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
321
+ source_fd: int | None = None
322
+ target_fd: int | None = None
323
+ try:
324
+ source_fd = os.open(source_file, flags)
325
+ source_stat = os.fstat(source_fd)
326
+ if not stat.S_ISREG(source_stat.st_mode):
327
+ raise GraphError(f"snapshot 仅接受普通文件: {relative}")
328
+ target_fd = os.open(
329
+ target_file,
330
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0),
331
+ 0o600,
332
+ )
333
+ with os.fdopen(source_fd, "rb", closefd=False) as src, os.fdopen(
334
+ target_fd, "wb", closefd=False,
335
+ ) as dst:
336
+ remaining = MAX_SNAPSHOT_BYTES - total_bytes
337
+ while True:
338
+ block = src.read(min(1024 * 1024, remaining + 1))
339
+ if not block:
340
+ break
341
+ total_bytes += len(block)
342
+ if total_bytes > MAX_SNAPSHOT_BYTES:
343
+ raise GraphError(f"snapshot 超过 {MAX_SNAPSHOT_BYTES} 字节")
344
+ dst.write(block)
345
+ dst.flush()
346
+ os.fsync(dst.fileno())
347
+ try:
348
+ os.chmod(target_file, 0o700 if source_stat.st_mode & 0o111 else 0o600)
349
+ except OSError:
350
+ pass
351
+ finally:
352
+ if source_fd is not None:
353
+ os.close(source_fd)
354
+ if target_fd is not None:
355
+ os.close(target_fd)
356
+ return {
357
+ "file_count": count,
358
+ "bytes": total_bytes,
359
+ "excluded_symlinks": excluded_links,
360
+ "excluded_symlinks_truncated": len(excluded_links) >= 1000,
361
+ }
362
+ except BaseException:
363
+ shutil.rmtree(destination, ignore_errors=True)
364
+ raise
365
+
366
+
367
+ _LOCKS_GUARD = threading.Lock()
368
+ _LOCKS: dict[Path, threading.RLock] = {}
369
+
370
+
371
+ class AgentOrchestrator:
372
+ """Persist and advance one deterministic Recon→Report task graph."""
373
+
374
+ def __init__(self, private_root: Path, graph_id: str) -> None:
375
+ if not isinstance(graph_id, str) or not GRAPH_ID_RE.fullmatch(graph_id):
376
+ raise GraphError("graph_id 格式无效")
377
+ self.private_root = Path(private_root).expanduser()
378
+ self.graph_id = graph_id
379
+ self.run_dir = self.private_root / graph_id
380
+ self.state_path = self.run_dir / "graph.json"
381
+ self.lock_path = self.run_dir / "graph.lock"
382
+ self.workspace = self.run_dir / "workspace"
383
+
384
+ @classmethod
385
+ def start(
386
+ cls, source_root: Path, private_root: Path, task_input: Mapping[str, object],
387
+ ) -> tuple["AgentOrchestrator", dict[str, Any]]:
388
+ source = Path(source_root).expanduser().resolve()
389
+ private = Path(private_root).expanduser()
390
+ bugx_paths.assert_no_symlink_components(private)
391
+ private.mkdir(mode=0o700, parents=True, exist_ok=True)
392
+ try:
393
+ private_resolved = private.resolve(strict=True)
394
+ private_resolved.relative_to(source)
395
+ except ValueError:
396
+ pass
397
+ else:
398
+ raise GraphError("graph private root must be outside the source project")
399
+ if private_resolved == source:
400
+ raise GraphError("graph private root must be outside the source project")
401
+ graph_id = uuid.uuid4().hex
402
+ run_dir = private_resolved / graph_id
403
+ run_dir.mkdir(mode=0o700, parents=False, exist_ok=False)
404
+ orchestrator = cls(private_resolved, graph_id)
405
+ try:
406
+ manifest = _copy_snapshot(source, orchestrator.workspace)
407
+ for relative in task_input["target_files"]:
408
+ target_path = orchestrator.workspace / relative
409
+ if target_path.is_symlink() or not target_path.is_file():
410
+ raise GraphError(f"声明的 snapshot 文件缺失或不安全: {relative}")
411
+ first_task = _new_task({"graph_id": graph_id, "task_input": dict(task_input)}, "Recon", 1, [])
412
+ state: dict[str, Any] = {
413
+ "schema_version": SCHEMA_VERSION,
414
+ "graph_id": graph_id,
415
+ "source_root_sha256": hashlib.sha256(str(source).encode("utf-8")).hexdigest(),
416
+ "workspace": str(orchestrator.workspace),
417
+ "created_at": _now(),
418
+ "updated_at": _now(),
419
+ "revision": 1,
420
+ "status": "running",
421
+ "task_input": dict(task_input),
422
+ "snapshot": manifest,
423
+ "max_concurrency": int(task_input["max_concurrency"]),
424
+ "tasks": [first_task],
425
+ "events": [{"event": "graph_started", "at": _now()}],
426
+ "final_report": None,
427
+ }
428
+ with orchestrator._file_lock():
429
+ orchestrator._save_unlocked(state)
430
+ return orchestrator, first_task
431
+ except BaseException:
432
+ shutil.rmtree(run_dir, ignore_errors=True)
433
+ raise
434
+
435
+ @classmethod
436
+ def open(cls, private_root: Path, graph_id: str) -> "AgentOrchestrator":
437
+ instance = cls(private_root, graph_id)
438
+ bugx_paths.assert_no_symlink_components(instance.run_dir)
439
+ if instance.run_dir.is_symlink() or not instance.run_dir.is_dir():
440
+ raise GraphError(f"graph 不存在: {graph_id}")
441
+ return instance
442
+
443
+ @contextlib.contextmanager
444
+ def _file_lock(self) -> Iterator[None]:
445
+ bugx_paths.assert_no_symlink_components(self.run_dir)
446
+ if self.run_dir.is_symlink() or not self.run_dir.is_dir():
447
+ raise GraphError(f"graph 不存在或不安全: {self.graph_id}")
448
+ with _LOCKS_GUARD:
449
+ thread_lock = _LOCKS.setdefault(self.lock_path, threading.RLock())
450
+ with thread_lock:
451
+ flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0)
452
+ try:
453
+ descriptor = os.open(self.lock_path, flags, 0o600)
454
+ except OSError as exc:
455
+ raise GraphError(f"无法安全打开 graph lock: {exc}") from exc
456
+ try:
457
+ if fcntl is not None:
458
+ fcntl.flock(descriptor, fcntl.LOCK_EX)
459
+ elif msvcrt is not None:
460
+ if os.fstat(descriptor).st_size == 0:
461
+ os.write(descriptor, b"0")
462
+ os.lseek(descriptor, 0, os.SEEK_SET)
463
+ msvcrt.locking(descriptor, msvcrt.LK_LOCK, 1)
464
+ else: # pragma: no cover - unsupported platform.
465
+ raise GraphError("当前平台不支持 graph 跨进程锁")
466
+ yield
467
+ finally:
468
+ try:
469
+ if fcntl is not None:
470
+ fcntl.flock(descriptor, fcntl.LOCK_UN)
471
+ elif msvcrt is not None:
472
+ os.lseek(descriptor, 0, os.SEEK_SET)
473
+ msvcrt.locking(descriptor, msvcrt.LK_UNLCK, 1)
474
+ finally:
475
+ os.close(descriptor)
476
+
477
+ def _load_unlocked(self) -> dict[str, Any]:
478
+ if self.state_path.is_symlink() or not self.state_path.is_file():
479
+ raise GraphError("graph state 缺失或不安全")
480
+ try:
481
+ raw = self.state_path.read_bytes()
482
+ if len(raw) > 16 * 1024 * 1024:
483
+ raise GraphError("graph state 超过大小限制")
484
+ state = json.loads(raw.decode("utf-8"))
485
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
486
+ raise GraphError(f"graph state 无法读取: {exc}") from exc
487
+ if not isinstance(state, dict) or state.get("schema_version") != SCHEMA_VERSION:
488
+ raise GraphError("graph state schema 无效")
489
+ if state.get("graph_id") != self.graph_id or not isinstance(state.get("tasks"), list):
490
+ raise GraphError("graph state 身份或任务列表无效")
491
+ return state
492
+
493
+ def _save_unlocked(self, state: dict[str, Any]) -> None:
494
+ state["revision"] = int(state.get("revision", 0)) + 1
495
+ state["updated_at"] = _now()
496
+ try:
497
+ secure_atomic.atomic_write_json(
498
+ self.state_path, state, mode=0o600, parent_mode=0o700,
499
+ )
500
+ except (OSError, ValueError, TypeError) as exc:
501
+ raise GraphError(f"graph state 写入失败: {exc}") from exc
502
+
503
+ def snapshot(self) -> dict[str, Any]:
504
+ with self._file_lock():
505
+ return self._load_unlocked()
506
+
507
+ @staticmethod
508
+ def _task(state: Mapping[str, Any], task_id: object) -> dict[str, Any]:
509
+ if not isinstance(task_id, str) or not task_id:
510
+ raise GraphError("task_id 必须是非空字符串")
511
+ for task in state["tasks"]:
512
+ if task.get("task_id") == task_id:
513
+ return task
514
+ raise GraphError(f"task 不属于当前 graph: {task_id}")
515
+
516
+ @staticmethod
517
+ def _dependencies_complete(state: Mapping[str, Any], task: Mapping[str, Any]) -> bool:
518
+ by_id = {item["task_id"]: item for item in state["tasks"]}
519
+ for dependency in task.get("dependencies", []):
520
+ parent = by_id.get(dependency)
521
+ if parent is None or parent.get("status") != "complete":
522
+ return False
523
+ return True
524
+
525
+ def next_task(self) -> dict[str, Any] | None:
526
+ with self._file_lock():
527
+ state = self._load_unlocked()
528
+ if state["status"] != "running":
529
+ return None
530
+ offered = next((
531
+ task for task in state["tasks"]
532
+ if task.get("status") == "offered"
533
+ and self._dependencies_complete(state, task)
534
+ ), None)
535
+ if offered is not None:
536
+ return dict(offered)
537
+ active = sum(task.get("status") in RESERVED_TASK_STATES for task in state["tasks"])
538
+ if active >= state["max_concurrency"]:
539
+ return None
540
+ order = {stage: index for index, stage in enumerate(STAGES)}
541
+ candidates = [
542
+ task for task in state["tasks"]
543
+ if task.get("status") == "pending" and self._dependencies_complete(state, task)
544
+ ]
545
+ if not candidates:
546
+ return None
547
+ task = min(candidates, key=lambda item: (order.get(item["stage"], 99), item["attempt"]))
548
+ task["status"] = "offered"
549
+ task["fencing_token"] = int(task.get("fencing_token", 0)) + 1
550
+ task["offered_at"] = _now()
551
+ state["events"].append({
552
+ "event": "task_offered", "task_id": task["task_id"],
553
+ "stage": task["stage"], "fencing_token": task["fencing_token"],
554
+ "at": task["offered_at"],
555
+ })
556
+ self._save_unlocked(state)
557
+ return dict(task)
558
+
559
+ def bind_agent(self, task_id: str, native_agent_id: str) -> dict[str, Any]:
560
+ if not isinstance(native_agent_id, str) or not NATIVE_AGENT_ID_RE.fullmatch(native_agent_id):
561
+ raise GraphError("native_agent_id 格式无效")
562
+ with self._file_lock():
563
+ state = self._load_unlocked()
564
+ if state["status"] != "running":
565
+ raise GraphError(f"graph 不可调度: {state['status']}")
566
+ task = self._task(state, task_id)
567
+ if task["status"] in ACTIVE_TASK_STATES:
568
+ if task.get("native_agent_id") == native_agent_id:
569
+ return dict(task)
570
+ raise GraphError("task 已绑定到其他 native_agent_id")
571
+ if task["status"] != "offered" or not self._dependencies_complete(state, task):
572
+ raise GraphError("task 尚未依赖就绪或已不可调度")
573
+ active = sum(
574
+ item.get("status") in RESERVED_TASK_STATES and item.get("task_id") != task_id
575
+ for item in state["tasks"]
576
+ )
577
+ if active >= state["max_concurrency"]:
578
+ raise GraphError("graph 并发容量已满")
579
+ if task["stage"] == "Review":
580
+ producers = {
581
+ item.get("native_agent_id") for item in state["tasks"]
582
+ if item.get("stage") in {"Recon", "Repro"}
583
+ and item.get("native_agent_id")
584
+ }
585
+ if native_agent_id in producers:
586
+ raise GraphError("Review 必须由不同于 Recon/Repro 生产者的 native_agent_id 执行")
587
+ task["native_agent_id"] = native_agent_id
588
+ task["status"] = "assigned"
589
+ task["started_at"] = _now()
590
+ state["events"].append({
591
+ "event": "agent_bound", "task_id": task_id,
592
+ "stage": task["stage"], "native_agent_id": native_agent_id,
593
+ "fencing_token": task["fencing_token"], "at": _now(),
594
+ })
595
+ self._save_unlocked(state)
596
+ return dict(task)
597
+
598
+ def _verify_worker(
599
+ self, state: Mapping[str, Any], task_id: str, native_agent_id: str,
600
+ fencing_token: int, *, require_active: bool = True,
601
+ ) -> dict[str, Any]:
602
+ if not isinstance(native_agent_id, str) or not NATIVE_AGENT_ID_RE.fullmatch(native_agent_id):
603
+ raise GraphError("native_agent_id 格式无效")
604
+ if isinstance(fencing_token, bool) or not isinstance(fencing_token, int) or fencing_token < 1:
605
+ raise GraphError("fencing_token 必须是正整数")
606
+ task = self._task(state, task_id)
607
+ if task.get("native_agent_id") != native_agent_id:
608
+ raise GraphError("Worker 身份与 Host 绑定的 native_agent_id 不匹配")
609
+ if task.get("fencing_token") != fencing_token:
610
+ raise GraphError("Worker fencing_token 已失效")
611
+ if require_active and task.get("status") not in ACTIVE_TASK_STATES:
612
+ raise GraphError(f"task 不处于可执行状态: {task.get('status')}")
613
+ return task
614
+
615
+ def _assemble_file_context(self, relative: str, data: bytes, content: str) -> str:
616
+ """Assemble Tiered Progressive Context (imports + 1-hop ego + slice) for code files."""
617
+ try:
618
+ from core.retrieval.slice_extractor import SliceExtractor
619
+ from core.retrieval.slice_normalizer import SliceNormalizer
620
+ except ImportError:
621
+ try:
622
+ from core.retrieval.slice_extractor import SliceExtractor
623
+ from core.retrieval.slice_normalizer import SliceNormalizer
624
+ except ImportError:
625
+ return content
626
+
627
+ try:
628
+ extractor = SliceExtractor(
629
+ project_id=self.graph_id,
630
+ snapshot_digest=hashlib.sha256(data).hexdigest(),
631
+ generation=1,
632
+ )
633
+ specs = extractor.extract(data, file=relative)
634
+ if not specs:
635
+ return content
636
+
637
+ import_lines: list[str] = []
638
+ for line in content.splitlines()[:60]:
639
+ stripped = line.strip()
640
+ if stripped.startswith(("import ", "from ")) and not stripped.startswith("from ."):
641
+ import_lines.append(stripped)
642
+
643
+ ego_graph = {
644
+ "center_node": relative,
645
+ "neighbors": {
646
+ "callers": [],
647
+ "callees": [s.symbol_name for s in specs[:5] if s.symbol_name],
648
+ },
649
+ }
650
+
651
+ assembled_parts: list[str] = []
652
+ for spec in specs[:3]:
653
+ part = SliceNormalizer.assemble_context(
654
+ spec,
655
+ imports=import_lines[:10],
656
+ ego_graph=ego_graph,
657
+ include_header=True,
658
+ )
659
+ assembled_parts.append(part)
660
+
661
+ return "\n\n---\n\n".join(assembled_parts)
662
+ except Exception:
663
+ return content
664
+
665
+ def context(
666
+ self, task_id: str, native_agent_id: str, fencing_token: int,
667
+ ) -> dict[str, Any]:
668
+ with self._file_lock():
669
+ state = self._load_unlocked()
670
+ task = self._verify_worker(state, task_id, native_agent_id, fencing_token)
671
+ if task["status"] == "assigned":
672
+ task["status"] = "running"
673
+ state["events"].append({
674
+ "event": "worker_started", "task_id": task_id,
675
+ "native_agent_id": native_agent_id, "at": _now(),
676
+ })
677
+ self._save_unlocked(state)
678
+ workspace = Path(state["workspace"])
679
+ try:
680
+ workspace.resolve(strict=True).relative_to(self.run_dir.resolve(strict=True))
681
+ except (OSError, ValueError) as exc:
682
+ raise GraphError("graph workspace 不在运行副本内") from exc
683
+ files: list[dict[str, str]] = []
684
+ total = 0
685
+ for relative in state["task_input"]["target_files"]:
686
+ path = workspace / relative
687
+ try:
688
+ resolved = bugx_paths.confined_regular_file(
689
+ workspace, path, error_cls=GraphError,
690
+ )
691
+ data = resolved.read_bytes()
692
+ except (OSError, UnicodeError, GraphError) as exc:
693
+ raise GraphError(f"无法读取声明的 snapshot 文件 {relative}: {exc}") from exc
694
+ if len(data) > MAX_CONTEXT_FILE_BYTES:
695
+ raise GraphError(f"snapshot 文件超过上下文上限: {relative}")
696
+ try:
697
+ content = data.decode("utf-8")
698
+ except UnicodeDecodeError as exc:
699
+ raise GraphError(f"声明的 snapshot 文件不是 UTF-8 文本: {relative}") from exc
700
+ assembled_content = self._assemble_file_context(relative, data, content)
701
+ total += len(assembled_content.encode("utf-8"))
702
+ if total > MAX_CONTEXT_BYTES:
703
+ raise GraphError("snapshot 文件总上下文超过大小上限")
704
+ files.append({"path": relative, "content": assembled_content})
705
+ parent_artifacts = self._parent_artifacts(state, task)
706
+ total += sum(len(item.get("content_base64", "")) for item in parent_artifacts)
707
+ if total > MAX_CONTEXT_BYTES:
708
+ raise GraphError("父工件与 snapshot 总上下文超过大小上限")
709
+ return {
710
+ "graph_id": self.graph_id,
711
+ "task_id": task_id,
712
+ "stage": task["stage"],
713
+ "attempt": task["attempt"],
714
+ "native_agent_id": native_agent_id,
715
+ "fencing_token": fencing_token,
716
+ "task_spec": task["prompt"],
717
+ "files": files,
718
+ "parent_artifacts": parent_artifacts,
719
+ "snapshot": state["snapshot"],
720
+ }
721
+
722
+ def _parent_artifacts(
723
+ self, state: Mapping[str, Any], task: Mapping[str, Any],
724
+ ) -> list[dict[str, Any]]:
725
+ by_id = {item["task_id"]: item for item in state["tasks"]}
726
+ results: list[dict[str, Any]] = []
727
+ ordered: list[dict[str, Any]] = []
728
+ visited: set[str] = set()
729
+
730
+ def add_ancestors(task_id: str) -> None:
731
+ if task_id in visited:
732
+ return
733
+ visited.add(task_id)
734
+ parent = by_id.get(task_id)
735
+ if parent is None:
736
+ raise GraphError("graph dependency 引用缺失")
737
+ for dependency in parent.get("dependencies", []):
738
+ add_ancestors(dependency)
739
+ ordered.append(parent)
740
+
741
+ for dependency in task.get("dependencies", []):
742
+ add_ancestors(dependency)
743
+ for parent in ordered:
744
+ if not parent or not parent.get("checkpoint"):
745
+ continue
746
+ checkpoint_path = self.run_dir / parent["checkpoint"]["path"]
747
+ if checkpoint_path.is_symlink() or not checkpoint_path.is_file():
748
+ raise GraphError("父工件信封缺失或不安全")
749
+ try:
750
+ envelope = json.loads(checkpoint_path.read_text(encoding="utf-8"))
751
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
752
+ raise GraphError(f"父工件信封读取失败: {exc}") from exc
753
+ for item in envelope.get("attachments", []):
754
+ digest = item.get("sha256")
755
+ if not isinstance(digest, str) or not SHA256_RE.fullmatch(digest):
756
+ raise GraphError("父工件附件哈希无效")
757
+ artifact_path = self.run_dir / "artifacts" / "sha256" / digest[:2] / digest
758
+ if artifact_path.is_symlink() or not artifact_path.is_file():
759
+ raise GraphError("父工件附件缺失或不安全")
760
+ data = artifact_path.read_bytes()
761
+ if hashlib.sha256(data).hexdigest() != digest:
762
+ raise GraphError("父工件内容寻址校验失败")
763
+ results.append({
764
+ "task_id": parent["task_id"], "stage": parent["stage"],
765
+ "filename": item["filename"], "sha256": digest,
766
+ "content_base64": base64.b64encode(data).decode("ascii"),
767
+ })
768
+ if len(results) > 50:
769
+ raise GraphError("父工件数量超过限制")
770
+ return results
771
+
772
+ @staticmethod
773
+ def _check_plan(plan: object) -> tuple[list[str], int, str]:
774
+ if not isinstance(plan, Mapping):
775
+ raise GraphError("CheckPlan 必须是对象")
776
+ if set(plan) - {"test_files", "timeout_seconds", "plan_id"}:
777
+ raise GraphError("CheckPlan 含有未支持字段")
778
+ test_files = _string_list(
779
+ plan.get("test_files"), "CheckPlan.test_files", minimum=1,
780
+ maximum=MAX_CHECK_FILES,
781
+ )
782
+ normalized = []
783
+ for item in test_files:
784
+ path = _safe_relative_path(item, "CheckPlan.test_files")
785
+ if not path.startswith("tests/") or not path.endswith(".py"):
786
+ raise GraphError("CheckPlan 仅允许 tests/ 下的 Python 测试文件")
787
+ if not PurePosixPath(path).name.startswith("test_"):
788
+ raise GraphError("CheckPlan 仅允许 test_*.py 文件")
789
+ normalized.append(path)
790
+ if len(set(normalized)) != len(normalized):
791
+ raise GraphError("CheckPlan.test_files 不得重复")
792
+ timeout = plan.get("timeout_seconds", 60)
793
+ if isinstance(timeout, bool) or not isinstance(timeout, int):
794
+ raise GraphError("CheckPlan.timeout_seconds 必须是整数")
795
+ if not 1 <= timeout <= MAX_CHECK_TIMEOUT_SECONDS:
796
+ raise GraphError(f"CheckPlan.timeout_seconds 必须位于 1..{MAX_CHECK_TIMEOUT_SECONDS}")
797
+ plan_id = _text(plan.get("plan_id", "check"), "CheckPlan.plan_id", maximum=128)
798
+ return normalized, timeout, plan_id
799
+
800
+ def run_check(
801
+ self, task_id: str, native_agent_id: str, fencing_token: int,
802
+ plan: object,
803
+ ) -> dict[str, Any]:
804
+ test_files, timeout, plan_id = self._check_plan(plan)
805
+ plan_record = {"test_files": test_files, "timeout_seconds": timeout, "plan_id": plan_id}
806
+ plan_digest = hashlib.sha256(_canonical_json(plan_record)).hexdigest()
807
+ with self._file_lock():
808
+ state = self._load_unlocked()
809
+ task = self._verify_worker(state, task_id, native_agent_id, fencing_token)
810
+ if task["stage"] != "Check":
811
+ raise GraphError("graph_run_check 仅允许 Check 阶段")
812
+ existing = task.get("check_observation")
813
+ if existing is not None:
814
+ if existing.get("plan_sha256") == plan_digest:
815
+ return dict(existing)
816
+ raise GraphError("当前 Check attempt 已执行其他 CheckPlan")
817
+ reservation = task.get("check_plan")
818
+ if reservation is not None:
819
+ if reservation.get("sha256") == plan_digest:
820
+ raise GraphError("相同 CheckPlan 正在执行")
821
+ raise GraphError("当前 Check attempt 已保留其他 CheckPlan")
822
+ workspace = Path(state["workspace"])
823
+ modules = []
824
+ for relative in test_files:
825
+ path = workspace / relative
826
+ if path.is_symlink() or not path.is_file():
827
+ raise GraphError(f"CheckPlan 测试文件缺失或不安全: {relative}")
828
+ modules.append(PurePosixPath(relative).with_suffix("").as_posix().replace("/", "."))
829
+ command = [sys.executable, "-P", "-m", "unittest", *modules]
830
+ temp_root = self.run_dir / "tmp"
831
+ temp_root.mkdir(mode=0o700, exist_ok=True)
832
+ task["check_plan"] = {"sha256": plan_digest, **plan_record}
833
+ task["check_pid"] = None
834
+ state["events"].append({
835
+ "event": "check_started", "task_id": task_id,
836
+ "plan_sha256": plan_digest, "at": _now(),
837
+ })
838
+ self._save_unlocked(state)
839
+ env = {
840
+ "PATH": os.environ.get("PATH", ""),
841
+ "PYTHONPATH": str(workspace),
842
+ "PYTHONUTF8": "1",
843
+ "PYTHONDONTWRITEBYTECODE": "1",
844
+ "HOME": str(temp_root),
845
+ "TMPDIR": str(temp_root),
846
+ "TMP": str(temp_root),
847
+ "TEMP": str(temp_root),
848
+ }
849
+ if os.name == "nt":
850
+ for name in ("SystemRoot", "WINDIR"):
851
+ if name in os.environ:
852
+ env[name] = os.environ[name]
853
+ started = time.monotonic()
854
+ timed_out = False
855
+ output = b""
856
+ error_output = b""
857
+ return_code: int | None = None
858
+ process: subprocess.Popen[bytes] | None = None
859
+ stdout_tail = bytearray()
860
+ stderr_tail = bytearray()
861
+ drain_threads: list[threading.Thread] = []
862
+
863
+ def drain(stream: Any, tail: bytearray) -> None:
864
+ while True:
865
+ block = stream.read(8192)
866
+ if not block:
867
+ return
868
+ tail.extend(block)
869
+ if len(tail) > MAX_CHECK_OUTPUT_BYTES:
870
+ del tail[:-MAX_CHECK_OUTPUT_BYTES]
871
+
872
+ try:
873
+ options: dict[str, Any] = {}
874
+ if os.name == "nt":
875
+ options["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
876
+ else:
877
+ options["start_new_session"] = True
878
+ process = subprocess.Popen(
879
+ command, cwd=workspace, env=env, stdin=subprocess.DEVNULL,
880
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False,
881
+ **options,
882
+ )
883
+ cancelled_before_registration = False
884
+ with self._file_lock():
885
+ state = self._load_unlocked()
886
+ current = self._task(state, task_id)
887
+ if (
888
+ current.get("status") not in ACTIVE_TASK_STATES
889
+ or current.get("fencing_token") != fencing_token
890
+ or current.get("check_plan", {}).get("sha256") != plan_digest
891
+ ):
892
+ cancelled_before_registration = True
893
+ else:
894
+ current["check_pid"] = process.pid
895
+ self._save_unlocked(state)
896
+ if cancelled_before_registration:
897
+ self._terminate_check_process(process.pid)
898
+ for stream, tail, name in (
899
+ (process.stdout, stdout_tail, "graph-check-stdout"),
900
+ (process.stderr, stderr_tail, "graph-check-stderr"),
901
+ ):
902
+ if stream is not None:
903
+ thread = threading.Thread(
904
+ target=drain, args=(stream, tail), name=name, daemon=True,
905
+ )
906
+ thread.start()
907
+ drain_threads.append(thread)
908
+ try:
909
+ process.wait(timeout=timeout)
910
+ except subprocess.TimeoutExpired:
911
+ timed_out = True
912
+ self._terminate_check_process(process.pid)
913
+ process.wait()
914
+ for thread in drain_threads:
915
+ thread.join(timeout=0.5)
916
+ if any(thread.is_alive() for thread in drain_threads):
917
+ self._terminate_check_process(process.pid)
918
+ for stream in (process.stdout, process.stderr):
919
+ if stream is not None:
920
+ stream.close()
921
+ for thread in drain_threads:
922
+ thread.join(timeout=0.5)
923
+ for stream in (process.stdout, process.stderr):
924
+ if stream is not None:
925
+ stream.close()
926
+ output = bytes(stdout_tail)
927
+ error_output = bytes(stderr_tail)
928
+ return_code = process.returncode
929
+ except OSError as exc:
930
+ error_output = str(exc).encode("utf-8", errors="replace")
931
+ return_code = -1
932
+ with self._file_lock():
933
+ state = self._load_unlocked()
934
+ task = self._task(state, task_id)
935
+ graph_cancelled = state.get("status") == "cancelled" or task.get("status") == "cancelled"
936
+ if graph_cancelled:
937
+ status = "cancelled"
938
+ elif timed_out:
939
+ status = "timeout"
940
+ else:
941
+ status = "passed" if return_code == 0 else "failed"
942
+ observation = {
943
+ "schema_version": 1,
944
+ "observation_id": "obs_" + uuid.uuid4().hex,
945
+ "graph_id": self.graph_id,
946
+ "task_id": task_id,
947
+ "native_agent_id": native_agent_id,
948
+ "plan_id": plan_id,
949
+ "plan_sha256": plan_digest,
950
+ "command": command,
951
+ "test_files": test_files,
952
+ "status": status,
953
+ "exit_code": return_code,
954
+ "duration_seconds": round(time.monotonic() - started, 3),
955
+ "stdout": output[-MAX_CHECK_OUTPUT_BYTES:].decode("utf-8", errors="replace"),
956
+ "stderr": error_output[-MAX_CHECK_OUTPUT_BYTES:].decode("utf-8", errors="replace"),
957
+ "timeout_seconds": timeout,
958
+ "created_at": _now(),
959
+ }
960
+ task["check_observation"] = observation
961
+ task["check_pid"] = None
962
+ state["events"].append({
963
+ "event": "check_observation", "task_id": task_id,
964
+ "observation_id": observation["observation_id"],
965
+ "status": observation["status"], "at": observation["created_at"],
966
+ })
967
+ self._save_unlocked(state)
968
+ return observation
969
+
970
+ @staticmethod
971
+ def _terminate_check_process(pid: int) -> None:
972
+ try:
973
+ if os.name == "nt":
974
+ os.kill(pid, signal.SIGTERM)
975
+ else:
976
+ os.killpg(pid, signal.SIGKILL)
977
+ except OSError:
978
+ pass
979
+
980
+ @staticmethod
981
+ def _normalize_envelope(envelope: object) -> dict[str, Any]:
982
+ if not isinstance(envelope, Mapping):
983
+ raise GraphError("artifact envelope 必须是对象")
984
+ allowed = {"outcome", "summary", "reason", "context", "retry_stage", "result"}
985
+ unknown = set(envelope) - allowed
986
+ if unknown:
987
+ raise GraphError(f"artifact envelope 含有未支持字段: {sorted(unknown)}")
988
+ outcome = envelope.get("outcome")
989
+ if not isinstance(outcome, str) or outcome not in {"complete", "needs_revision", "failed"}:
990
+ raise GraphError("artifact envelope.outcome 必须是 complete/needs_revision/failed")
991
+ summary = _text(envelope.get("summary"), "artifact envelope.summary")
992
+ reason = envelope.get("reason", "")
993
+ if reason is not None and (not isinstance(reason, str) or len(reason) > 8192):
994
+ raise GraphError("artifact envelope.reason 无效")
995
+ context = envelope.get("context", {})
996
+ if not isinstance(context, Mapping):
997
+ raise GraphError("artifact envelope.context 必须是对象")
998
+ if len(_canonical_json(context)) > MAX_ENVELOPE_BYTES:
999
+ raise GraphError("artifact envelope.context 超过大小上限")
1000
+ retry_stage = envelope.get("retry_stage")
1001
+ if retry_stage is not None and (
1002
+ not isinstance(retry_stage, str) or retry_stage not in {"Recon", "Repro"}
1003
+ ):
1004
+ raise GraphError("Review retry_stage 仅支持 Recon/Repro")
1005
+ result = envelope.get("result", {})
1006
+ if not isinstance(result, Mapping) or len(_canonical_json(result)) > MAX_ENVELOPE_BYTES:
1007
+ raise GraphError("artifact envelope.result 必须是有界对象")
1008
+ normalized = {
1009
+ "outcome": outcome,
1010
+ "summary": summary,
1011
+ "reason": reason or "",
1012
+ "context": dict(context),
1013
+ "result": dict(result),
1014
+ }
1015
+ if retry_stage is not None:
1016
+ normalized["retry_stage"] = retry_stage
1017
+ if len(_canonical_json(normalized)) > MAX_ENVELOPE_BYTES:
1018
+ raise GraphError("artifact envelope 超过大小上限")
1019
+ return normalized
1020
+
1021
+ @staticmethod
1022
+ def _decode_attachments(attachments: object) -> list[dict[str, Any]]:
1023
+ if not isinstance(attachments, list) or len(attachments) > 50:
1024
+ raise GraphError("attachments 必须是最多 50 项的数组")
1025
+ decoded: list[dict[str, Any]] = []
1026
+ total = 0
1027
+ for index, item in enumerate(attachments):
1028
+ if not isinstance(item, Mapping) or set(item) != {"filename", "sha256", "content_base64"}:
1029
+ raise GraphError(f"attachments[{index}] 字段无效")
1030
+ filename = _text(item["filename"], f"attachments[{index}].filename", maximum=512)
1031
+ if "/" in filename or "\\" in filename or filename in {".", ".."}:
1032
+ raise GraphError("attachment filename 必须是单个文件名")
1033
+ digest = item["sha256"]
1034
+ if not isinstance(digest, str) or not SHA256_RE.fullmatch(digest):
1035
+ raise GraphError("attachment sha256 格式无效")
1036
+ content_b64 = item["content_base64"]
1037
+ if not isinstance(content_b64, str):
1038
+ raise GraphError("attachment content_base64 必须是字符串")
1039
+ try:
1040
+ data = base64.b64decode(content_b64, validate=True)
1041
+ except (ValueError, base64.binascii.Error) as exc:
1042
+ raise GraphError("attachment base64 无效") from exc
1043
+ if len(data) > MAX_ATTACHMENT_BYTES:
1044
+ raise GraphError("单个 attachment 超过大小上限")
1045
+ total += len(data)
1046
+ if total > MAX_ATTACHMENTS_BYTES:
1047
+ raise GraphError("attachments 总大小超过上限")
1048
+ actual = hashlib.sha256(data).hexdigest()
1049
+ if actual != digest:
1050
+ raise GraphError("attachment sha256 与内容不匹配")
1051
+ decoded.append({
1052
+ "filename": filename, "sha256": digest,
1053
+ "content_base64": content_b64, "data": data,
1054
+ })
1055
+ return decoded
1056
+
1057
+ def checkpoint(
1058
+ self, task_id: str, native_agent_id: str, fencing_token: int,
1059
+ envelope: object, attachments: object = None,
1060
+ ) -> dict[str, Any]:
1061
+ normalized = self._normalize_envelope(envelope)
1062
+ decoded = self._decode_attachments([] if attachments is None else attachments)
1063
+ request_digest = hashlib.sha256(_canonical_json({
1064
+ "envelope": normalized,
1065
+ "attachments": [
1066
+ {"filename": item["filename"], "sha256": item["sha256"]}
1067
+ for item in decoded
1068
+ ],
1069
+ })).hexdigest()
1070
+ with self._file_lock():
1071
+ state = self._load_unlocked()
1072
+ task = self._verify_worker(state, task_id, native_agent_id, fencing_token, require_active=False)
1073
+ previous = task.get("checkpoint")
1074
+ if previous is not None:
1075
+ if previous.get("request_sha256") == request_digest:
1076
+ return dict(previous)
1077
+ raise GraphError("task 已有不同内容的 checkpoint,拒绝覆盖")
1078
+ if task["status"] not in ACTIVE_TASK_STATES:
1079
+ raise GraphError(f"task 不处于可 checkpoint 状态: {task.get('status')}")
1080
+ if normalized["outcome"] == "complete" and task["stage"] == "Check":
1081
+ observation = task.get("check_observation")
1082
+ if not isinstance(observation, Mapping):
1083
+ raise GraphError("Check 阶段缺少 graph_run_check Observation")
1084
+ if observation.get("status") != "passed":
1085
+ raise GraphError("Check Observation 未通过,不能 checkpoint complete")
1086
+ attachment_refs = []
1087
+ for item in decoded:
1088
+ digest = item["sha256"]
1089
+ artifact_dir = self.run_dir / "artifacts" / "sha256" / digest[:2]
1090
+ bugx_paths.assert_no_symlink_components(artifact_dir)
1091
+ artifact_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
1092
+ target = artifact_dir / digest
1093
+ if target.exists():
1094
+ if target.is_symlink() or not target.is_file():
1095
+ raise GraphError("content-addressed attachment path 不安全")
1096
+ existing = target.read_bytes()
1097
+ if hashlib.sha256(existing).hexdigest() != digest:
1098
+ raise GraphError("既有 content-addressed attachment 内容损坏")
1099
+ else:
1100
+ try:
1101
+ secure_atomic.atomic_write_bytes(
1102
+ target, item["data"], mode=0o600, parent_mode=0o700,
1103
+ )
1104
+ except OSError as exc:
1105
+ raise GraphError(f"attachment 写入失败: {exc}") from exc
1106
+ attachment_refs.append({"filename": item["filename"], "sha256": digest})
1107
+ envelope_payload = {
1108
+ "schema_version": 1,
1109
+ "graph_id": self.graph_id,
1110
+ "task_id": task_id,
1111
+ "stage": task["stage"],
1112
+ "attempt": task["attempt"],
1113
+ "native_agent_id": native_agent_id,
1114
+ "fencing_token": fencing_token,
1115
+ "submitted_at": _now(),
1116
+ **normalized,
1117
+ "check_observation": task.get("check_observation"),
1118
+ "attachments": attachment_refs,
1119
+ }
1120
+ envelope_bytes = _canonical_json(envelope_payload)
1121
+ checkpoint_id = hashlib.sha256(envelope_bytes).hexdigest()
1122
+ envelope_path = self.run_dir / "checkpoints" / f"{task_id}.json"
1123
+ envelope_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
1124
+ try:
1125
+ secure_atomic.atomic_write_bytes(
1126
+ envelope_path, envelope_bytes, mode=0o600, parent_mode=0o700,
1127
+ )
1128
+ except OSError as exc:
1129
+ raise GraphError(f"checkpoint envelope 写入失败: {exc}") from exc
1130
+ receipt = {
1131
+ "checkpoint_id": checkpoint_id,
1132
+ "request_sha256": request_digest,
1133
+ "path": str(envelope_path.relative_to(self.run_dir)),
1134
+ "envelope_sha256": checkpoint_id,
1135
+ "attachments": attachment_refs,
1136
+ }
1137
+ task["checkpoint"] = receipt
1138
+ outcome = normalized["outcome"]
1139
+ if outcome == "complete":
1140
+ task["status"] = "complete"
1141
+ task["finished_at"] = _now()
1142
+ self._ensure_successor(state, task)
1143
+ else:
1144
+ task["status"] = "needs_revision"
1145
+ task["finished_at"] = _now()
1146
+ task["failure_context"] = {
1147
+ "reason": normalized["reason"] or normalized["summary"],
1148
+ "context": normalized["context"],
1149
+ "checkpoint_id": checkpoint_id,
1150
+ }
1151
+ self._retry_or_fail(state, task, normalized)
1152
+ state["events"].append({
1153
+ "event": "task_checkpointed", "task_id": task_id,
1154
+ "stage": task["stage"], "attempt": task["attempt"],
1155
+ "outcome": outcome, "checkpoint_id": checkpoint_id, "at": _now(),
1156
+ })
1157
+ self._save_unlocked(state)
1158
+ return receipt
1159
+
1160
+ def _ensure_successor(self, state: dict[str, Any], task: Mapping[str, Any]) -> None:
1161
+ stage = task["stage"]
1162
+ if stage == "Report":
1163
+ return
1164
+ next_stage = {
1165
+ "Recon": "Repro", "Repro": "Review", "Review": (
1166
+ "Patch" if state["task_input"]["patch_requested"] else "Check"
1167
+ ), "Patch": "Check", "Check": "Report",
1168
+ }.get(stage)
1169
+ if next_stage is None:
1170
+ return
1171
+ if any(
1172
+ item.get("stage") == next_stage
1173
+ and task["task_id"] in item.get("dependencies", [])
1174
+ and item.get("status") not in {"failed", "cancelled", "superseded"}
1175
+ for item in state["tasks"]
1176
+ ):
1177
+ return
1178
+ previous = [item for item in state["tasks"] if item.get("stage") == next_stage]
1179
+ attempt = max((int(item["attempt"]) for item in previous), default=0) + 1
1180
+ if attempt > MAX_ATTEMPTS:
1181
+ state["status"] = "failed"
1182
+ state["failure_reason"] = f"{next_stage} 超过最大 attempt 次数"
1183
+ return
1184
+ state["tasks"].append(_new_task(
1185
+ state, next_stage, attempt, [str(task["task_id"])],
1186
+ feedback=task.get("feedback") if task.get("feedback") else None,
1187
+ ))
1188
+
1189
+ def _retry_or_fail(
1190
+ self, state: dict[str, Any], task: dict[str, Any], envelope: Mapping[str, Any],
1191
+ ) -> None:
1192
+ next_attempt = int(task["attempt"]) + 1
1193
+ if next_attempt > MAX_ATTEMPTS:
1194
+ task["status"] = "failed"
1195
+ state["status"] = "failed"
1196
+ state["failure_reason"] = task["failure_context"]["reason"]
1197
+ return
1198
+ if task["stage"] == "Review":
1199
+ retry_stage = envelope.get("retry_stage") or "Repro"
1200
+ producer_attempts = [
1201
+ item for item in state["tasks"] if item.get("stage") == retry_stage
1202
+ ]
1203
+ retry_number = max((int(item["attempt"]) for item in producer_attempts), default=0) + 1
1204
+ if retry_number > MAX_ATTEMPTS:
1205
+ task["status"] = "failed"
1206
+ state["status"] = "failed"
1207
+ state["failure_reason"] = f"{retry_stage} 已达到 {MAX_ATTEMPTS} 次 attempt 上限"
1208
+ return
1209
+ original = max(producer_attempts, key=lambda item: int(item["attempt"]))
1210
+ feedback = {
1211
+ "reason": envelope["reason"] or envelope["summary"],
1212
+ "context": envelope["context"],
1213
+ "from_stage": "Review",
1214
+ "from_task_id": task["task_id"],
1215
+ }
1216
+ retry = _new_task(
1217
+ state, retry_stage, retry_number,
1218
+ original.get("dependencies", []), feedback=feedback,
1219
+ )
1220
+ state["tasks"].append(retry)
1221
+ return
1222
+ retry = _new_task(
1223
+ state, task["stage"], next_attempt,
1224
+ task.get("dependencies", []),
1225
+ feedback={
1226
+ "reason": envelope["reason"] or envelope["summary"],
1227
+ "context": envelope["context"],
1228
+ "from_stage": task["stage"],
1229
+ "from_task_id": task["task_id"],
1230
+ },
1231
+ )
1232
+ state["tasks"].append(retry)
1233
+
1234
+ def cancel(self, reason: str, task_id: str | None = None) -> dict[str, Any]:
1235
+ reason = _text(reason, "reason", maximum=2048)
1236
+ process_ids: list[int] = []
1237
+ with self._file_lock():
1238
+ state = self._load_unlocked()
1239
+ if task_id is not None:
1240
+ self._task(state, task_id)
1241
+ if state["status"] in {"finalized", "cancelled"}:
1242
+ return {"graph_id": self.graph_id, "status": state["status"], "cancelled": False}
1243
+ for task in state["tasks"]:
1244
+ if task.get("status") not in TERMINAL_TASK_STATES:
1245
+ process_id = task.get("check_pid")
1246
+ if isinstance(process_id, int) and process_id > 0:
1247
+ process_ids.append(process_id)
1248
+ if task.get("status") in RESERVED_TASK_STATES:
1249
+ task["fencing_token"] = int(task.get("fencing_token", 0)) + 1
1250
+ task["status"] = "cancelled"
1251
+ task["finished_at"] = _now()
1252
+ state["status"] = "cancelled"
1253
+ state["cancel_reason"] = reason
1254
+ state["cancelled_at"] = _now()
1255
+ state["events"].append({
1256
+ "event": "graph_cancelled", "task_id": task_id,
1257
+ "reason": reason, "at": state["cancelled_at"],
1258
+ })
1259
+ self._save_unlocked(state)
1260
+ # Native agents are fenced by task state/token. The engine has no host
1261
+ # UI handle to stop them; it reclaims only the owned snapshot workspace.
1262
+ for process_id in process_ids:
1263
+ self._terminate_check_process(process_id)
1264
+ if self.workspace.exists() and not self.workspace.is_symlink():
1265
+ shutil.rmtree(self.workspace)
1266
+ return {"graph_id": self.graph_id, "status": "cancelled", "cancelled": True}
1267
+
1268
+ def finalize(self, decision: str, summary: str) -> dict[str, Any]:
1269
+ if decision not in {"accepted", "rejected", "inconclusive"}:
1270
+ raise GraphError("decision 必须是 accepted/rejected/inconclusive")
1271
+ summary = _text(summary, "summary", maximum=8192)
1272
+ with self._file_lock():
1273
+ state = self._load_unlocked()
1274
+ if state["status"] == "finalized":
1275
+ report = state.get("final_report")
1276
+ if report and report.get("decision") == decision and report.get("summary") == summary:
1277
+ return dict(report)
1278
+ raise GraphError("graph 已最终固化,不能覆盖裁决")
1279
+ if any(task.get("status") in ACTIVE_TASK_STATES for task in state["tasks"]):
1280
+ raise GraphError("仍有已绑定或执行中的 task,不能 finalize")
1281
+ if state["status"] == "running":
1282
+ report_task = next((
1283
+ item for item in state["tasks"]
1284
+ if item.get("stage") == "Report" and item.get("status") == "complete"
1285
+ ), None)
1286
+ if report_task is None:
1287
+ raise GraphError("Report 阶段未完成,不能 finalize")
1288
+ overall = "complete" if state["status"] == "running" else state["status"]
1289
+ payload = {
1290
+ "schema_version": 1,
1291
+ "graph_id": self.graph_id,
1292
+ "status": overall,
1293
+ "decision": decision,
1294
+ "summary": summary,
1295
+ "created_at": _now(),
1296
+ "source_root_sha256": state["source_root_sha256"],
1297
+ "snapshot": state["snapshot"],
1298
+ "tasks": [
1299
+ {
1300
+ "task_id": task["task_id"], "stage": task["stage"],
1301
+ "attempt": task["attempt"], "status": task["status"],
1302
+ "dependencies": task["dependencies"],
1303
+ "native_agent_id": task["native_agent_id"],
1304
+ "checkpoint": task["checkpoint"],
1305
+ "check_observation": task["check_observation"],
1306
+ "failure_context": task["failure_context"],
1307
+ }
1308
+ for task in state["tasks"]
1309
+ ],
1310
+ "events": state["events"],
1311
+ "failure_reason": state.get("failure_reason"),
1312
+ "cancel_reason": state.get("cancel_reason"),
1313
+ }
1314
+ report_path = self.run_dir / "final-report.json"
1315
+ try:
1316
+ secure_atomic.atomic_write_json(
1317
+ report_path, payload, mode=0o600, parent_mode=0o700,
1318
+ )
1319
+ except (OSError, ValueError, TypeError) as exc:
1320
+ raise GraphError(f"final report 写入失败: {exc}") from exc
1321
+ report_sha256 = hashlib.sha256(_canonical_json(payload)).hexdigest()
1322
+ receipt = {
1323
+ "graph_id": self.graph_id,
1324
+ "status": overall,
1325
+ "decision": decision,
1326
+ "summary": summary,
1327
+ "report_path": str(report_path.relative_to(self.run_dir)),
1328
+ "report_sha256": report_sha256,
1329
+ "task_count": len(state["tasks"]),
1330
+ "at": payload["created_at"],
1331
+ }
1332
+ state["status"] = "finalized"
1333
+ state["final_report"] = receipt
1334
+ state["events"].append({
1335
+ "event": "graph_finalized", "report_sha256": report_sha256,
1336
+ "decision": decision, "at": payload["created_at"],
1337
+ })
1338
+ self._save_unlocked(state)
1339
+ return receipt
1340
+
1341
+
1342
+ __all__ = [
1343
+ "AgentOrchestrator", "GraphError", "MAX_ATTEMPTS", "MAX_CHECK_TIMEOUT_SECONDS",
1344
+ "assemble_task_prompt",
1345
+ ]