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,1132 @@
1
+ #!/usr/bin/env python3
2
+ """为 BugX 建立轻量、零依赖的源码符号索引。
3
+
4
+ Python 使用标准库 AST 精确解析;其他受支持语言使用保守的声明级扫描器。
5
+ 索引既可以供人查看,也可以让 module_coverage 把文件继续拆到函数、类、方法、
6
+ 路由处理器等可独立审计单元。解析失败会显式记录,不会静默把失败当成无符号文件。
7
+ """
8
+ from __future__ import annotations
9
+ # --- 引擎导入根(直接执行脚本时自举 core.* 命名空间)---
10
+ import sys as _sys
11
+ from pathlib import Path as _Path
12
+
13
+ for _p in _Path(__file__).resolve().parents:
14
+ if (_p / "core" / "bugx.md").is_file():
15
+ if str(_p) not in _sys.path:
16
+ _sys.path.insert(0, str(_p))
17
+ break
18
+ del _p
19
+ import sys
20
+ from pathlib import Path
21
+
22
+
23
+ import argparse
24
+ import ast
25
+ import json
26
+ import hashlib
27
+ import os
28
+ import re
29
+ from dataclasses import asdict, dataclass, field, replace
30
+ from fnmatch import fnmatchcase
31
+
32
+ SCHEMA_VERSION = 2
33
+ # These directories belong to the host/agent/runtime rather than the product
34
+ # being audited. They are excluded at every depth: a checked-out worktree
35
+ # under .claude/worktrees is still another branch, not another product module.
36
+ #
37
+ # DOC-239:已迁移宿主(``opencode`` / ``cline`` / ...)的目录只能来自
38
+ # ``core/hosts/<host>.py``(``install.marker`` / ``generated_dirs``),不得在此
39
+ # 重复声明;下面只剩**未迁移宿主**与通用工具目录的待迁移基线。
40
+ _LEGACY_HOST_RUNTIME_DIRS = {
41
+ ".claude", ".pi", ".agents", ".dsh", ".gstack", ".mirasim",
42
+ ".bugx", ".code-review-graph",
43
+ ".workbuddy", ".codebuddy", ".qoder", ".trea", ".trae", ".trae-cn", ".zcode",
44
+ }
45
+
46
+
47
+ def _is_engine_namespace_segment(part: str) -> bool:
48
+ """任一目录分量是否属于 BugX 引擎自己的运行态命名空间。
49
+
50
+ ``_LEGACY_HOST_RUNTIME_DIRS`` 只登记了确切的 ``.bugx``,而引擎与宿主 AI
51
+ 会派生**同前缀**的兄弟目录:``.bugx-audit-artifacts``(host 写探针/复现
52
+ 脚本)、``.bugx-patches``(PE 工单补丁包)、``.bugx-cache`` ……。这些全部
53
+ 是审计产物而不是被审产品材料。
54
+
55
+ 实测后果(bugx-audit-dsh 靶场):宿主在项目根写下
56
+ ``.bugx-audit-artifacts/repro.py`` 后,它被当成 3 个新内部单元
57
+ (``probe_sqli.py``、``repro.py::record``、``repro.py::__module__``)并入
58
+ 清单,``post`` 随即报「符号索引不完整」;宿主删掉文件后单元又变
59
+ ``removed``,``workspace`` 指纹反复漂移触发 ``target_rebound``,覆盖状态
60
+ 在 ``covered → stale → pending → removed`` 之间来回翻烧。
61
+
62
+ 前缀匹配而不是枚举名单:新派生的运行态目录不会因为漏登记再次污染覆盖。
63
+ 用户自己的 ``.bugxfoo`` 产品目录同样被排除,但这与 ``.git*`` 的既有约定
64
+ 一致——点前缀命名空间归工具所有。
65
+ """
66
+ return part == ".bugx" or part.startswith(".bugx-") or part.startswith(".bugx_")
67
+
68
+
69
+ def _plugin_host_runtime_dirs() -> set[str]:
70
+ """已迁移插件声明的宿主目录(模块布局残缺时 fail-soft 为空集)。"""
71
+
72
+ try: # 引擎运行时:``core/`` 在 sys.path 上
73
+ from core.host_runtime.host_registry import host_workspace_dirs
74
+ except ImportError: # pragma: no cover - 仅模块被单独拷出时发生
75
+ return set()
76
+ return set(host_workspace_dirs())
77
+
78
+
79
+ #: 引擎自产的运行态目录(**目录名**,按路径分量匹配)。
80
+ #: 自包含引擎副本布局把 Session/Round 账本放在项目根的 ``pollings/`` 下
81
+ #: (见 ``launch_phases.common.pollings_root``),而不是 ``.bugx/`` 内。
82
+ #: 不排除它们会把 ``findings.json`` 当成被审源码资产,要求给出覆盖单元与
83
+ #: 证据(实测 ``post --final`` 报 "#3 findings.json 缺证据")。
84
+ RUNTIME_ARTIFACT_DIRS = {"pollings", "receipts", "artifacts", "backups"}
85
+
86
+ HOST_RUNTIME_DIRS = (
87
+ _LEGACY_HOST_RUNTIME_DIRS | _plugin_host_runtime_dirs() | RUNTIME_ARTIFACT_DIRS
88
+ )
89
+ HOST_ROOT_CONFIG_NAMES = {
90
+ "opencode.json", ".mcp.json",
91
+ }
92
+ DEPENDENCY_OR_GENERATED_DIRS = {
93
+ ".git", "node_modules", "target", "dist", ".venv", "venv", "__pycache__",
94
+ ".gradle", "vendor", "third_party", ".pytest_cache", ".ruff_cache",
95
+ }
96
+ # Keep the old public name for callers that used it, but do not use it as a
97
+ # blunt ``any path segment`` filter: src/build/rule.py is product code.
98
+ EXCLUDED_DIRS = HOST_RUNTIME_DIRS | DEPENDENCY_OR_GENERATED_DIRS | {
99
+ "build", "tests", "test", "__tests__", "docs", "examples", "evals",
100
+ }
101
+ TOP_LEVEL_SOURCE_EXCLUDED_DIRS = {
102
+ "build", "tests", "test", "__tests__", "docs", "examples", "evals",
103
+ # BugX 自身产物约定:patch-forge 的 PE 工单补丁包(repro/tests 记录),
104
+ # 与 plugins/bugx 同类——是引擎历史工件而非被测产品代码。
105
+ ".bugx-patches",
106
+ }
107
+ # 资产发现(include_test_assets=True)额外排除的顶层目录:BugX 双轨报告/
108
+ # 收据默认输出到 ``evals/oss``(HTML/JSON 均在资产扩展名清单内)——审计
109
+ # 产物喂回覆盖清单是自增强污染(实测 evals 报告被列为审计单元)。
110
+ TOP_LEVEL_ASSET_EXCLUDED_DIRS = {
111
+ "evals",
112
+ ".bugx-patches",
113
+ }
114
+ SOURCE_EXTS = {
115
+ ".py", ".js", ".mjs", ".cjs", ".jsx", ".ts", ".tsx", ".java", ".kt", ".kts", ".go",
116
+ ".rs", ".swift", ".c", ".h", ".cc", ".cpp", ".cxx", ".cs", ".rb",
117
+ ".php", ".vue", ".svelte",
118
+ }
119
+ AUDIT_ASSET_EXTS = {
120
+ ".sh", ".bash", ".zsh", ".fish", ".sql", ".yaml", ".yml", ".toml",
121
+ ".json", ".jsonc", ".xml", ".ini", ".cfg", ".conf", ".properties",
122
+ ".proto", ".graphql", ".gql", ".tf", ".tfvars", ".html", ".css",
123
+ ".scss", ".sass", ".less", ".lock",
124
+ }
125
+ AUDIT_ASSET_NAMES = {
126
+ "Dockerfile", "Makefile", "GNUmakefile", "CMakeLists.txt", "Procfile",
127
+ "Justfile", "go.mod", "go.sum", "Cargo.toml", "Cargo.lock", "pom.xml",
128
+ "build.gradle", "settings.gradle", "Gemfile", "Gemfile.lock",
129
+ "composer.json", "requirements.txt", "requirements-dev.txt", "Pipfile",
130
+ "Pipfile.lock", "package-lock.json", "pnpm-lock.yaml", "yarn.lock",
131
+ "poetry.lock", "uv.lock", "setup.cfg", "tox.ini",
132
+ ".pre-commit-config.yaml", ".env.example",
133
+ }
134
+ RUNTIME_ARTIFACT_NAMES = {
135
+ "bugx-life.json", "bugx-life.json.lock", "bugx-runtime.json",
136
+ "bugx-runtime.json.lock", "bugx-runtime.lock", "audit-supervisor.json",
137
+ "audit-supervisor.json.lock",
138
+ "coverage-evidence.json", "coverage-evidence.json.lock", "lesson-review.json",
139
+ "lesson-review.json.lock", "module-coverage.md", "prep-record.md",
140
+ # Flat/legacy launch mode writes the formal lifecycle artifacts at the
141
+ # project root. Formal projects are already protected by the .bugx
142
+ # directory exclusion; keeping the names here protects the legacy mode
143
+ # without excluding a same-named product file in a subdirectory.
144
+ "life.json", "runtime.json", "runtime.json.lock", "supervisor.json",
145
+ "supervisor.json.lock", "state.json", "current.json", "events.jsonl",
146
+ "report.md", "conclusion.json", "integrity.json", "inventory-diff.json",
147
+ "finding-ledger.json", "finding-ledger.json.lock", ".finding-ledger.json.lock",
148
+ "findings.json", "findings.json.lock", ".findings.json.lock",
149
+ "audit-campaign.json", "finding-lifecycle.json", "bugx-life.json.snapshot",
150
+ "lesson-ledger.sqlite3.journal-mode.lock",
151
+ # 项目错题集是引擎运行态(``common.LESSON_LEDGER_FILE``:项目根的
152
+ # lesson-ledger.json,由 lesson_ledger.py 写入),旧清单漏登记它,
153
+ # 结果它被当成**被审产品资产**参与覆盖门禁:新工程刚初始化就必然
154
+ # 报「最小单元清单漏列源码或行为资产: lesson-ledger.json」,
155
+ # 而它根本不该有覆盖单元。同类运行态(finding-ledger.json 等)已在册。
156
+ "lesson-ledger.json", "lesson-ledger.json.lock",
157
+ # 云端 onboarding 写入项目根的云端身份标记(cloud_onboard.py),
158
+ # 属引擎运行态而非产品材料——与 .bugx 目录同类。
159
+ ".bugx-project.json",
160
+ }
161
+
162
+
163
+ class SourceDiscoveryError(ValueError):
164
+ """源码枚举不完整,调用方不得继续声称全覆盖。"""
165
+
166
+
167
+ @dataclass(frozen=True)
168
+ class Symbol:
169
+ name: str
170
+ qualified_name: str
171
+ kind: str
172
+ start_line: int
173
+ end_line: int
174
+ parent: str | None
175
+ parser: str
176
+ start_byte: int | None = field(default=None, compare=False, repr=False)
177
+
178
+ @property
179
+ def scope_name(self) -> str:
180
+ return self.qualified_name
181
+
182
+
183
+ def _gitignore_rules(root: Path) -> list[str]:
184
+ """Read the root ignore file once for both source and asset discovery."""
185
+ try:
186
+ lines = (root / ".gitignore").read_text(encoding="utf-8").splitlines()
187
+ except (OSError, UnicodeError):
188
+ return []
189
+ return [
190
+ line.strip() for line in lines
191
+ if line.strip() and not line.lstrip().startswith("#")
192
+ ]
193
+
194
+
195
+ def _gitignore_matches(relative: Path, *, is_dir: bool, rules: list[str]) -> bool:
196
+ """Apply the root .gitignore's last matching rule to a relative path."""
197
+ # 只剥掉调用方可能带来的 "./" 前缀;str.lstrip("./") 是字符集剥离,
198
+ # 会把点前缀文件名(.bugx-project.json、.env、.github…)的开头点吃掉,
199
+ # 导致 gitignore 名单对全部隐藏文件静默失效——而引擎自产工件恰恰
200
+ # 集中在点前缀命名空间(实测 .myapp-state.json 已入 .gitignore 仍被
201
+ # 发现)。
202
+ raw_path = relative.as_posix()
203
+ path = raw_path[2:] if raw_path.startswith("./") else raw_path
204
+ ignored = False
205
+ for raw in rules:
206
+ negated = raw.startswith("!")
207
+ pattern = raw[1:] if negated else raw
208
+ directory_only = pattern.endswith("/")
209
+ pattern = pattern.rstrip("/").lstrip("/")
210
+ if not pattern or (directory_only and not is_dir):
211
+ continue
212
+ if "/" not in pattern:
213
+ matched = any(fnmatchcase(part, pattern) for part in Path(path).parts)
214
+ else:
215
+ matched = fnmatchcase(path, pattern) or fnmatchcase(path, f"*/{pattern}")
216
+ if matched:
217
+ ignored = not negated
218
+ return ignored
219
+
220
+
221
+ def _generated_directory(relative: Path) -> bool:
222
+ """Filter generated variants without hiding product code in src/build."""
223
+ parts = relative.parts
224
+ for index, part in enumerate(parts):
225
+ lowered = part.casefold()
226
+ if lowered == "dist" or lowered.startswith("dist-") \
227
+ or lowered.startswith(".tmp-"):
228
+ return True
229
+ if lowered == "build" and index + 1 < len(parts) \
230
+ and parts[index + 1].casefold() == "generated":
231
+ return True
232
+ return False
233
+
234
+
235
+ _PROJECT_EXCLUDE_TOP_DIRS_CACHE: dict[Path, frozenset[str]] = {}
236
+
237
+
238
+ def _project_exclude_top_dirs(root: Path) -> frozenset[str]:
239
+ """项目级覆盖排除,两路来源取并集(AI 复核为主,手工配置为辅):
240
+
241
+ 1. **AI 复核定案**(主通道):``.bugx/knowledge/coverage-review.json``
242
+ 里宿主 AI 逐目录排查后的 ``exclude`` 裁决——裁决带理由/时间/裁决者,
243
+ 换项目时由该机制重新排查,不携带任何项目名清单(DOC-AIREV)。
244
+ 2. **手工覆盖**(辅助):``.bugx/config.json`` 的
245
+ ``coverage.exclude_top_dirs`` 顶层目录名列表,供人工紧急纠偏。
246
+
247
+ 读取失败一律返回空集(fail-open:宁可多扫,不因配置错误吞掉产品代码)。
248
+ """
249
+ cached = _PROJECT_EXCLUDE_TOP_DIRS_CACHE.get(root)
250
+ if cached is not None:
251
+ return cached
252
+ names: set[str] = set()
253
+ try:
254
+ from core.coverage import coverage_ai_review
255
+
256
+ names |= set(coverage_ai_review.excluded_top_dirs(root))
257
+ except Exception: # pragma: no cover - 复核模块缺失/损坏时退回配置通道
258
+ pass
259
+ try:
260
+ cfg = root / ".bugx" / "config.json"
261
+ if cfg.is_file():
262
+ data = json.loads(cfg.read_text(encoding="utf-8"))
263
+ raw = (data.get("coverage") or {}).get("exclude_top_dirs")
264
+ if isinstance(raw, list):
265
+ names |= {
266
+ str(item).strip().strip("/")
267
+ for item in raw
268
+ if isinstance(item, str) and item.strip().strip("/")
269
+ }
270
+ except (OSError, ValueError, AttributeError):
271
+ pass
272
+ frozen = frozenset(names)
273
+ _PROJECT_EXCLUDE_TOP_DIRS_CACHE[root] = frozen
274
+ return frozen
275
+
276
+
277
+ def _directory_is_excluded(
278
+ relative: Path, *, include_test_assets: bool,
279
+ gitignore_rules: list[str] | None = None, is_dir: bool = True,
280
+ project_root: Path | None = None,
281
+ ) -> bool:
282
+ parts = set(relative.parts)
283
+ if parts & (HOST_RUNTIME_DIRS | DEPENDENCY_OR_GENERATED_DIRS) \
284
+ or any(_is_engine_namespace_segment(part) for part in parts) \
285
+ or _generated_directory(relative):
286
+ return True
287
+ if include_test_assets and relative.parts and relative.parts[0] in TOP_LEVEL_ASSET_EXCLUDED_DIRS:
288
+ return True
289
+ if not include_test_assets and relative.parts and relative.parts[0] in TOP_LEVEL_SOURCE_EXCLUDED_DIRS:
290
+ return True
291
+ if project_root is not None and relative.parts and relative.parts[0] in _project_exclude_top_dirs(project_root):
292
+ return True
293
+ return _gitignore_matches(relative, is_dir=is_dir, rules=gitignore_rules or [])
294
+
295
+
296
+ _ENGINE_PLUGIN_PACKAGE_PREFIX = ("plugins", "bugx")
297
+ _ENGINE_PLUGIN_PACKAGE_CACHE: dict[Path, bool] = {}
298
+
299
+
300
+ def _is_engine_plugin_package(relative: Path, root: Path) -> bool:
301
+ """安装器写入项目的 BugX 自产插件包不是被审计产品材料。
302
+
303
+ ``bugx install`` 会在项目根写入可分发的 ``plugins/bugx/.zcode-plugin``
304
+ 插件包(清单 + agents);它属于宿主集成产物而非用户源码,与
305
+ ``.bugx/`` 同类。判定用指纹而非目录名:相对路径必须以
306
+ ``plugins/bugx/`` 开头,且该目录下的清单声明 ``name == "bugx"``。
307
+ 用户自己的 ``plugins/bugx`` 产品代码(无该清单或声明其他 name)
308
+ 不受影响。结果按 root 缓存,walk 期间零额外 IO。
309
+ """
310
+ parts = relative.parts
311
+ if len(parts) < 2 or parts[:2] != _ENGINE_PLUGIN_PACKAGE_PREFIX:
312
+ return False
313
+ root = root.resolve()
314
+ cached = _ENGINE_PLUGIN_PACKAGE_CACHE.get(root)
315
+ if cached is None:
316
+ cached = False
317
+ manifest = root.joinpath(*_ENGINE_PLUGIN_PACKAGE_PREFIX, ".zcode-plugin", "plugin.json")
318
+ try:
319
+ if manifest.is_file():
320
+ payload = json.loads(manifest.read_text(encoding="utf-8"))
321
+ cached = isinstance(payload, dict) and payload.get("name") == "bugx"
322
+ except (OSError, ValueError):
323
+ cached = False
324
+ _ENGINE_PLUGIN_PACKAGE_CACHE[root] = cached
325
+ return cached
326
+
327
+
328
+ def _is_runtime_artifact(path: Path, root: Path) -> bool:
329
+ """Exclude root-level legacy runtime output and host root configs, not product assets.
330
+
331
+ A project may legitimately contain ``config/runtime.json`` or
332
+ ``docs/report.md``. Runtime names and host configs therefore are not a global
333
+ blacklist; only flat launcher output and root host configs (e.g. opencode.json,
334
+ .mcp.json) directly below the audited root are ignored.
335
+ In the formal layout all runtime files live below ``.bugx`` and are
336
+ excluded by the directory policy before this check matters.
337
+ """
338
+ try:
339
+ relative = path.relative_to(root)
340
+ except ValueError:
341
+ return False
342
+ return relative.parent == Path(".") and (
343
+ path.name in RUNTIME_ARTIFACT_NAMES
344
+ or path.name in HOST_ROOT_CONFIG_NAMES
345
+ )
346
+
347
+
348
+ def _discover_paths(
349
+ root: Path, *, extensions: set[str], names: set[str] | None = None,
350
+ strict: bool = False, include_test_assets: bool = False,
351
+ ) -> list[Path]:
352
+ """Walk the authorized root without following directory symlinks.
353
+
354
+ ``Path.rglob`` silently skips inaccessible subdirectories on some Python
355
+ versions. The audit gate must be able to distinguish an empty directory
356
+ from an incomplete enumeration, so ``os.walk(onerror=...)`` is used here.
357
+ """
358
+ root = root.resolve()
359
+ if not root.is_dir():
360
+ if strict:
361
+ raise SourceDiscoveryError(f"项目根目录不存在或不可访问: {root}")
362
+ return []
363
+ paths: list[Path] = []
364
+ seen_targets: set[Path] = set()
365
+ gitignore_rules = _gitignore_rules(root)
366
+
367
+ def onerror(exc: OSError) -> None:
368
+ if strict:
369
+ raise SourceDiscoveryError(f"项目文件枚举失败: {exc}") from exc
370
+
371
+ try:
372
+ for directory, dirnames, filenames in os.walk(
373
+ root, topdown=True, followlinks=False, onerror=onerror,
374
+ ):
375
+ directory_path = Path(directory)
376
+ relative_dir = directory_path.relative_to(root)
377
+ dirnames[:] = [
378
+ name for name in dirnames
379
+ if not _directory_is_excluded(
380
+ relative_dir / name, include_test_assets=include_test_assets,
381
+ gitignore_rules=gitignore_rules, project_root=root,
382
+ )
383
+ and not _is_engine_plugin_package(relative_dir / name, root)
384
+ ]
385
+ for name in filenames:
386
+ path = directory_path / name
387
+ relative = path.relative_to(root)
388
+ if _is_runtime_artifact(path, root):
389
+ continue
390
+ if _is_engine_plugin_package(relative, root):
391
+ continue
392
+ if _directory_is_excluded(
393
+ relative, include_test_assets=include_test_assets,
394
+ gitignore_rules=gitignore_rules, is_dir=False,
395
+ project_root=root,
396
+ ):
397
+ continue
398
+ if path.suffix.lower() not in extensions and name not in (names or set()):
399
+ continue
400
+ try:
401
+ resolved = path.resolve(strict=True)
402
+ resolved.relative_to(root)
403
+ if not path.is_file() or resolved in seen_targets:
404
+ continue
405
+ seen_targets.add(resolved)
406
+ paths.append(path)
407
+ except ValueError:
408
+ # 指向授权根目录之外的符号链接不属于审计范围。
409
+ continue
410
+ except OSError as exc:
411
+ if strict:
412
+ raise SourceDiscoveryError(f"项目文件枚举失败 {path}: {exc}") from exc
413
+ except OSError as exc:
414
+ if strict:
415
+ raise SourceDiscoveryError(f"项目目录遍历失败 {root}: {exc}") from exc
416
+ return sorted(paths, key=lambda item: str(item.relative_to(root)))
417
+
418
+
419
+ def discover_source_paths(root: Path, strict: bool = False) -> list[Path]:
420
+ """递归返回产品源码,排除依赖、构建产物、测试和 Agent 自身。"""
421
+ return _discover_paths(
422
+ root, extensions=SOURCE_EXTS, strict=strict, include_test_assets=False,
423
+ )
424
+
425
+
426
+ def discover_asset_paths(root: Path, strict: bool = False) -> list[Path]:
427
+ """发现会改变运行行为的配置、依赖、构建、CI 与部署资产。
428
+
429
+ 测试/文档目录不作为源码模块,但其中的脚本和配置仍可能是验收证据,
430
+ 因此资产发现保留这些目录;宿主运行目录和生成/第三方目录仍始终排除。
431
+ """
432
+ return _discover_paths(
433
+ root, extensions=AUDIT_ASSET_EXTS, names=AUDIT_ASSET_NAMES,
434
+ strict=strict, include_test_assets=True,
435
+ )
436
+
437
+
438
+ def _decode_source(raw: bytes) -> str:
439
+ """Decode bytes exactly like ``Path.read_text(encoding="utf-8", errors="replace")``.
440
+
441
+ ``Path.read_text`` opens in universal-newline mode, which rewrites CRLF and
442
+ lone CR to LF. Decoding the cached bytes must do the same, otherwise symbol
443
+ line ranges and ``ast.get_source_segment`` evidence would change on CRLF
444
+ checkouts. The replacement order matters: ``\\r\\n`` first, then ``\\r``.
445
+ """
446
+ return raw.decode("utf-8", errors="replace").replace("\r\n", "\n").replace("\r", "\n")
447
+
448
+
449
+ class SourceContentCache:
450
+ """Per-pass cache of raw source bytes so a pass reads each file once.
451
+
452
+ BugX re-reads every source file two to three times per pass: ``parse_file``
453
+ for symbols, ``file_sha256`` for the content hash, and again when the
454
+ project graph re-parses Python sources. Threading one cache through a pass
455
+ collapses those into a single read per file.
456
+
457
+ Lifetime is deliberately a *single pass* (one ``index_repository`` /
458
+ ``audit_units`` / ``inventory_snapshot`` / ``build_graph`` call), never a
459
+ process-global memo. The audit engine re-runs against a workspace that can
460
+ change between passes (edits, ``git checkout``, generated files), so a
461
+ process-wide cache would silently serve stale content. Read failures are
462
+ not cached, so an unreadable file still raises the same ``OSError`` on every
463
+ attempt and a mid-pass change is never masked by a cached failure.
464
+ """
465
+
466
+ __slots__ = ("_bytes",)
467
+
468
+ def __init__(self) -> None:
469
+ self._bytes: dict[Path, bytes] = {}
470
+
471
+ def read_bytes(self, path: Path) -> bytes:
472
+ """Return the file's bytes, hitting the disk at most once per pass."""
473
+ try:
474
+ return self._bytes[path]
475
+ except KeyError:
476
+ data = path.read_bytes()
477
+ self._bytes[path] = data
478
+ return data
479
+
480
+ def read_text(self, path: Path) -> str:
481
+ """Return the file as text with ``Path.read_text`` newline semantics."""
482
+ return _decode_source(self.read_bytes(path))
483
+
484
+
485
+ def file_sha256(path: Path, cache: SourceContentCache | None = None) -> str:
486
+ """计算文件内容的 SHA-256(1 MiB 分块,避免整文件驻留内存)。
487
+
488
+ 这是全仓文件哈希的唯一实现(QUA-03):``coverage_evidence.sha256_file`` 与
489
+ ``mcp_runtime.sha256_file`` 都复用本函数。本模块保持零本地依赖——它会被
490
+ 复制进隔离的 launch 目录单独运行,不能引入 core 内其它模块。
491
+ """
492
+ if cache is not None:
493
+ return hashlib.sha256(cache.read_bytes(path)).hexdigest()
494
+ digest = hashlib.sha256()
495
+ with path.open("rb") as handle:
496
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
497
+ digest.update(chunk)
498
+ return digest.hexdigest()
499
+
500
+
501
+ class _PythonVisitor(ast.NodeVisitor):
502
+ def __init__(self) -> None:
503
+ self.symbols: list[Symbol] = []
504
+ self.parents: list[str] = []
505
+
506
+ def _record(self, node: ast.AST, name: str, kind: str) -> None:
507
+ qualified = ".".join([*self.parents, name])
508
+ self.symbols.append(Symbol(
509
+ name=name,
510
+ qualified_name=qualified,
511
+ kind=kind,
512
+ start_line=int(getattr(node, "lineno", 1)),
513
+ end_line=int(getattr(node, "end_lineno", getattr(node, "lineno", 1))),
514
+ parent=".".join(self.parents) or None,
515
+ parser="python-ast",
516
+ ))
517
+
518
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
519
+ self._record(node, node.name, "class")
520
+ self.parents.append(node.name)
521
+ self.generic_visit(node)
522
+ self.parents.pop()
523
+
524
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
525
+ kind = "method" if self.parents else "function"
526
+ self._record(node, node.name, kind)
527
+ self.parents.append(node.name)
528
+ self.generic_visit(node)
529
+ self.parents.pop()
530
+
531
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
532
+ kind = "async-method" if self.parents else "async-function"
533
+ self._record(node, node.name, kind)
534
+ self.parents.append(node.name)
535
+ self.generic_visit(node)
536
+ self.parents.pop()
537
+
538
+
539
+ def _python_symbols(source: str) -> tuple[list[Symbol], str | None]:
540
+ try:
541
+ tree = ast.parse(source)
542
+ except SyntaxError as exc:
543
+ return [], f"Python 语法错误: line {exc.lineno}: {exc.msg}"
544
+ visitor = _PythonVisitor()
545
+ visitor.visit(tree)
546
+ module_nodes = [
547
+ node for node in tree.body
548
+ if not isinstance(node, (ast.Import, ast.ImportFrom, ast.ClassDef,
549
+ ast.FunctionDef, ast.AsyncFunctionDef))
550
+ and not (
551
+ isinstance(node, ast.Expr)
552
+ and isinstance(getattr(node, "value", None), ast.Constant)
553
+ and isinstance(node.value.value, str)
554
+ )
555
+ ]
556
+ if module_nodes:
557
+ visitor.symbols.append(Symbol(
558
+ name="__module__",
559
+ qualified_name="__module__",
560
+ kind="module",
561
+ start_line=min(int(getattr(node, "lineno", 1)) for node in module_nodes),
562
+ end_line=max(int(getattr(node, "end_lineno", getattr(node, "lineno", 1)))
563
+ for node in module_nodes),
564
+ parent=None,
565
+ parser="python-ast",
566
+ ))
567
+ return visitor.symbols, None
568
+
569
+
570
+ DECLARATION_PATTERNS: dict[str, tuple[tuple[str, str], ...]] = {
571
+ "javascript": (
572
+ ("class", r"^\s*(?:export\s+(?:default\s+)?)?class\s+([A-Za-z_$][\w$]*)"),
573
+ ("function", r"^\s*(?:export\s+)?(?:async\s+)?function\s+"
574
+ r"([A-Za-z_$][\w$]*)\s*\("),
575
+ ("function", r"^\s*(?:export\s+)?(?:const|let|var)\s+"
576
+ r"([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?"
577
+ r"(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>"),
578
+ ),
579
+ "jvm": (
580
+ ("class", r"^\s*(?:(?:public|private|protected|internal|abstract|final|open|"
581
+ r"data|sealed)\s+)*(?:class|interface|object|enum\s+class)\s+"
582
+ r"([A-Za-z_$][\w$]*)"),
583
+ ("function", r"^\s*(?:(?:public|private|protected|internal|static|final|open|"
584
+ r"suspend|override|abstract)\s+)*(?:fun\s+|[\w<>\[\],.?]+\s+)"
585
+ r"([A-Za-z_$][\w$]*)\s*\([^;]*\)\s*(?:\{|=|throws\b)"),
586
+ ),
587
+ "go": (
588
+ ("type", r"^\s*type\s+([A-Za-z_]\w*)\s+(?:struct|interface)\b"),
589
+ ("function", r"^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)\s*\("),
590
+ ),
591
+ "rust": (
592
+ ("type", r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:struct|enum|trait)\s+([A-Za-z_]\w*)"),
593
+ ("function", r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:unsafe\s+)?"
594
+ r"fn\s+([A-Za-z_]\w*)\s*(?:<[^>]+>)?\s*\("),
595
+ ),
596
+ "swift": (
597
+ ("type", r"^\s*(?:(?:public|private|internal|open|final)\s+)*"
598
+ r"(?:class|struct|enum|protocol|actor)\s+([A-Za-z_]\w*)"),
599
+ ("function", r"^\s*(?:(?:public|private|internal|open|static|class|override|"
600
+ r"mutating)\s+)*func\s+([A-Za-z_]\w*)\s*\("),
601
+ ),
602
+ "c-family": (
603
+ ("type", r"^\s*(?:(?:public|private|protected|internal|static|abstract|sealed|"
604
+ r"partial)\s+)*(?:class|struct|interface|enum)\s+([A-Za-z_]\w*)"),
605
+ ("function", r"^\s*(?:(?:public|private|protected|internal|static|virtual|"
606
+ r"override|inline|constexpr|extern)\s+)*"
607
+ r"[A-Za-z_][\w:<>,*&\[\]\s]*\s+([A-Za-z_]\w*)\s*"
608
+ r"\([^;]*\)\s*(?:\{|=>)"),
609
+ ),
610
+ "ruby": (
611
+ ("type", r"^\s*(?:class|module)\s+([A-Za-z_]\w*(?:::[A-Za-z_]\w*)*)"),
612
+ ("function", r"^\s*def\s+(?:self\.)?([A-Za-z_]\w*[!?=]?)"),
613
+ ),
614
+ "php": (
615
+ ("class", r"^\s*(?:(?:abstract|final)\s+)?(?:class|interface|trait|enum)\s+([A-Za-z_]\w*)"),
616
+ ("function", r"^\s*(?:(?:public|private|protected|static|final|abstract)\s+)*"
617
+ r"function\s+&?([A-Za-z_]\w*)\s*\("),
618
+ ),
619
+ }
620
+ JAVASCRIPT_METHOD_RE = re.compile(
621
+ r"^\s*(?:(?:public|private|protected|static|async|get|set)\s+)*"
622
+ r"([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*\{"
623
+ )
624
+ JAVASCRIPT_CONTROL_WORDS = {"if", "for", "while", "switch", "catch", "with"}
625
+
626
+
627
+ def _language_for(path: Path) -> str:
628
+ suffix = path.suffix.lower()
629
+ if suffix == ".py":
630
+ return "python"
631
+ if suffix in {".js", ".mjs", ".cjs", ".jsx", ".ts", ".tsx", ".vue", ".svelte"}:
632
+ return "javascript"
633
+ if suffix in {".java", ".kt", ".kts"}:
634
+ return "jvm"
635
+ if suffix == ".go":
636
+ return "go"
637
+ if suffix == ".rs":
638
+ return "rust"
639
+ if suffix == ".swift":
640
+ return "swift"
641
+ if suffix in {".c", ".h", ".cc", ".cpp", ".cxx", ".cs"}:
642
+ return "c-family"
643
+ if suffix == ".rb":
644
+ return "ruby"
645
+ return "php"
646
+
647
+
648
+ TREE_SITTER_LANGUAGES = {
649
+ ".js": "javascript", ".mjs": "javascript", ".cjs": "javascript",
650
+ ".jsx": "javascript", ".ts": "typescript", ".tsx": "tsx",
651
+ ".java": "java", ".kt": "kotlin", ".kts": "kotlin", ".go": "go",
652
+ ".rs": "rust", ".swift": "swift", ".c": "c", ".h": "c",
653
+ ".cc": "cpp", ".cpp": "cpp", ".cxx": "cpp", ".cs": "c_sharp",
654
+ ".rb": "ruby", ".php": "php", ".vue": "vue", ".svelte": "svelte",
655
+ }
656
+ TREE_SITTER_NODE_KINDS = {
657
+ "class_declaration": "class", "class_definition": "class",
658
+ "interface_declaration": "type", "object_declaration": "type",
659
+ "struct_item": "type", "struct_specifier": "type", "enum_item": "type",
660
+ "enum_declaration": "type", "trait_item": "type", "protocol_declaration": "type",
661
+ "function_declaration": "function", "function_definition": "function",
662
+ "function_item": "function", "method_definition": "method",
663
+ "method_declaration": "method", "function_method_declaration": "method",
664
+ }
665
+ TREE_SITTER_NAME_TYPES = {
666
+ "identifier", "type_identifier", "property_identifier", "field_identifier",
667
+ "constant", "operator_name", "name",
668
+ }
669
+
670
+
671
+ def _tree_sitter_name(node: object) -> str | None:
672
+ direct = node.child_by_field_name("name")
673
+ if direct is not None:
674
+ return direct.text.decode("utf-8", errors="replace")
675
+ declarator = node.child_by_field_name("declarator")
676
+ queue = [declarator] if declarator is not None else list(node.named_children[:4])
677
+ while queue:
678
+ current = queue.pop(0)
679
+ if current.type in TREE_SITTER_NAME_TYPES:
680
+ return current.text.decode("utf-8", errors="replace")
681
+ queue[0:0] = list(current.named_children[:4])
682
+ return None
683
+
684
+
685
+ def _tree_sitter_symbols(source: str, language: str) -> tuple[list[Symbol], str | None]:
686
+ try:
687
+ from tree_sitter_language_pack import get_parser
688
+ except ImportError:
689
+ return [], "Tree-sitter 后端未安装;安装 bugx-agent[graph]"
690
+ try:
691
+ tree = get_parser(language).parse(source.encode("utf-8"))
692
+ except Exception as exc: # language-pack 对不支持语法抛出多种运行时异常
693
+ return [], f"Tree-sitter 无法加载 {language}: {exc}"
694
+ symbols: list[Symbol] = []
695
+
696
+ def walk(node: object, parents: list[str]) -> None:
697
+ kind = TREE_SITTER_NODE_KINDS.get(node.type)
698
+ name = _tree_sitter_name(node) if kind else None
699
+ child_parents = parents
700
+ if kind and name:
701
+ qualified = ".".join([*parents, name])
702
+ actual_kind = "method" if kind == "function" and parents else kind
703
+ symbols.append(Symbol(
704
+ name=name,
705
+ qualified_name=qualified,
706
+ kind=actual_kind,
707
+ start_line=node.start_point[0] + 1,
708
+ end_line=node.end_point[0] + 1,
709
+ parent=".".join(parents) or None,
710
+ parser=f"tree-sitter-{language}",
711
+ start_byte=node.start_byte,
712
+ ))
713
+ child_parents = [*parents, name]
714
+ for child in node.named_children:
715
+ walk(child, child_parents)
716
+
717
+ walk(tree.root_node, [])
718
+ error = f"Tree-sitter {language} 语法树包含 ERROR 节点" if tree.root_node.has_error else None
719
+ return symbols, error
720
+
721
+
722
+ def _declaration_symbols(source: str, language: str) -> tuple[list[Symbol], None]:
723
+ symbols: list[Symbol] = []
724
+ seen: set[tuple[str, int]] = set()
725
+ lines = source.splitlines()
726
+ for line_number, line in enumerate(lines, 1):
727
+ for kind, pattern in DECLARATION_PATTERNS[language]:
728
+ match = re.search(pattern, line)
729
+ if not match:
730
+ continue
731
+ name = match.group(1)
732
+ key = (name, line_number)
733
+ if key not in seen:
734
+ symbols.append(Symbol(
735
+ name=name,
736
+ qualified_name=name,
737
+ kind=kind,
738
+ start_line=line_number,
739
+ end_line=_declaration_end_line(lines, line_number),
740
+ parent=None,
741
+ parser=f"{language}-declaration",
742
+ ))
743
+ seen.add(key)
744
+ break
745
+ return symbols, None
746
+
747
+
748
+ def _declaration_end_line(lines: list[str], start_line: int) -> int:
749
+ """Estimate a declaration body range for the dependency-free scanner."""
750
+ depth = 0
751
+ saw_brace = False
752
+ for index in range(start_line - 1, len(lines)):
753
+ line = lines[index]
754
+ opening = line.count("{")
755
+ closing = line.count("}")
756
+ if opening:
757
+ saw_brace = True
758
+ depth += opening - closing
759
+ if saw_brace and depth <= 0:
760
+ return index + 1
761
+ return start_line
762
+
763
+
764
+ def _javascript_symbols(source: str) -> tuple[list[Symbol], None]:
765
+ symbols: list[Symbol] = []
766
+ brace_depth = 0
767
+ class_stack: list[tuple[str, int]] = []
768
+ for line_number, line in enumerate(source.splitlines(), 1):
769
+ while class_stack and brace_depth < class_stack[-1][1]:
770
+ class_stack.pop()
771
+ class_match = re.search(DECLARATION_PATTERNS["javascript"][0][1], line)
772
+ pending_class = class_match.group(1) if class_match else None
773
+ if pending_class:
774
+ symbols.append(Symbol(
775
+ name=pending_class,
776
+ qualified_name=pending_class,
777
+ kind="class",
778
+ start_line=line_number,
779
+ end_line=line_number,
780
+ parent=None,
781
+ parser="javascript-declaration",
782
+ ))
783
+ elif class_stack:
784
+ method_match = JAVASCRIPT_METHOD_RE.search(line)
785
+ if method_match and method_match.group(1) not in JAVASCRIPT_CONTROL_WORDS:
786
+ name = method_match.group(1)
787
+ parent = class_stack[-1][0]
788
+ symbols.append(Symbol(
789
+ name=name,
790
+ qualified_name=f"{parent}.{name}",
791
+ kind="method",
792
+ start_line=line_number,
793
+ end_line=_declaration_end_line(source.splitlines(), line_number),
794
+ parent=parent,
795
+ parser="javascript-declaration",
796
+ ))
797
+ else:
798
+ for kind, pattern in DECLARATION_PATTERNS["javascript"][1:]:
799
+ match = re.search(pattern, line)
800
+ if match:
801
+ name = match.group(1)
802
+ symbols.append(Symbol(
803
+ name=name,
804
+ qualified_name=name,
805
+ kind=kind,
806
+ start_line=line_number,
807
+ end_line=_declaration_end_line(source.splitlines(), line_number),
808
+ parent=None,
809
+ parser="javascript-declaration",
810
+ ))
811
+ break
812
+ old_depth = brace_depth
813
+ brace_depth += line.count("{") - line.count("}")
814
+ if pending_class and brace_depth > old_depth:
815
+ class_stack.append((pending_class, brace_depth))
816
+ return symbols, None
817
+
818
+
819
+ def _deduplicate_scopes(symbols: list[Symbol]) -> list[Symbol]:
820
+ seen: set[str] = set()
821
+ result: list[Symbol] = []
822
+ for symbol in symbols:
823
+ qualified_name = symbol.qualified_name
824
+ if qualified_name in seen:
825
+ line_suffix = f"@L{symbol.start_line}"
826
+ candidate = f"{qualified_name}{line_suffix}"
827
+ if candidate in seen:
828
+ if symbol.start_byte is None:
829
+ candidate = f"{qualified_name}#2{line_suffix}"
830
+ else:
831
+ candidate = f"{qualified_name}@B{symbol.start_byte}{line_suffix}"
832
+ ordinal = 2
833
+ while candidate in seen:
834
+ if symbol.start_byte is None:
835
+ candidate = f"{qualified_name}#{ordinal}{line_suffix}"
836
+ else:
837
+ candidate = (
838
+ f"{qualified_name}#{ordinal}@B{symbol.start_byte}{line_suffix}"
839
+ )
840
+ ordinal += 1
841
+ symbol = replace(
842
+ symbol,
843
+ qualified_name=candidate,
844
+ )
845
+ seen.add(symbol.qualified_name)
846
+ result.append(symbol)
847
+ return result
848
+
849
+
850
+ def _merge_parser_symbols(primary: list[Symbol], fallback: list[Symbol]) -> list[Symbol]:
851
+ """补上增强解析器漏掉的声明,同时保留其精确范围和父子关系。"""
852
+ merged = list(primary)
853
+ seen = {(symbol.name, symbol.start_line) for symbol in primary}
854
+ for symbol in fallback:
855
+ key = (symbol.name, symbol.start_line)
856
+ if key not in seen:
857
+ merged.append(symbol)
858
+ seen.add(key)
859
+ return sorted(
860
+ merged,
861
+ key=lambda symbol: (symbol.start_line, symbol.end_line, symbol.qualified_name),
862
+ )
863
+
864
+
865
+ def parse_file(
866
+ path: Path, backend: str = "auto", *, cache: SourceContentCache | None = None,
867
+ ) -> tuple[list[Symbol], str | None, str]:
868
+ language = _language_for(path)
869
+ try:
870
+ if cache is not None:
871
+ source = cache.read_text(path)
872
+ else:
873
+ source = path.read_text(encoding="utf-8", errors="replace")
874
+ except OSError as exc:
875
+ return [], f"无法读取: {exc}", language
876
+ if backend not in {"auto", "builtin", "tree-sitter"}:
877
+ return [], f"未知解析后端: {backend}", language
878
+ tree_language = TREE_SITTER_LANGUAGES.get(path.suffix.lower())
879
+ if language == "python":
880
+ symbols, error = _python_symbols(source)
881
+ elif backend in {"auto", "tree-sitter"} and tree_language:
882
+ symbols, error = _tree_sitter_symbols(source, tree_language)
883
+ fallback, _ = (
884
+ _javascript_symbols(source) if language == "javascript"
885
+ else _declaration_symbols(source, language)
886
+ )
887
+ if backend == "auto":
888
+ # Always merge the conservative scanner: tree-sitter currently
889
+ # does not expose top-level variable/arrow declarations uniformly.
890
+ # A syntax error remains visible even when a fallback declaration
891
+ # was recovered; otherwise strict mode would claim false coverage.
892
+ symbols = _merge_parser_symbols(symbols, fallback)
893
+ if error and ("未安装" in error or "无法加载" in error):
894
+ error = None
895
+ elif language == "javascript":
896
+ symbols, error = _javascript_symbols(source)
897
+ else:
898
+ symbols, error = _declaration_symbols(source, language)
899
+ return _deduplicate_scopes(symbols), error, language
900
+
901
+
902
+ def _leaf_symbols(symbols: list[Symbol]) -> list[Symbol]:
903
+ parents = {symbol.parent for symbol in symbols if symbol.parent}
904
+ callable_names = {
905
+ symbol.qualified_name for symbol in symbols
906
+ if symbol.kind in {"function", "method", "async-function", "async-method"}
907
+ }
908
+
909
+ def nested_in_callable(symbol: Symbol) -> bool:
910
+ parent = symbol.parent
911
+ while parent:
912
+ if parent in callable_names:
913
+ return True
914
+ parent = parent.rsplit(".", 1)[0] if "." in parent else None
915
+ return False
916
+
917
+ return [
918
+ symbol for symbol in symbols
919
+ if not (symbol.kind in {"class", "type"} and symbol.qualified_name in parents)
920
+ and not nested_in_callable(symbol)
921
+ ]
922
+
923
+
924
+ def index_repository(
925
+ root: Path, backend: str = "auto", strict: bool = False,
926
+ *, cache: SourceContentCache | None = None,
927
+ ) -> dict:
928
+ root = root.resolve()
929
+ cache = cache if cache is not None else SourceContentCache()
930
+ files: list[dict] = []
931
+ nodes: list[dict] = []
932
+ edges: list[dict] = []
933
+ for path in discover_source_paths(root, strict=strict):
934
+ relative = path.relative_to(root).as_posix()
935
+ symbols, error, language = parse_file(path, backend, cache=cache)
936
+ try:
937
+ digest = file_sha256(path, cache)
938
+ size = path.stat().st_size
939
+ except OSError as exc:
940
+ if strict:
941
+ raise SourceDiscoveryError(f"源码读取失败 {path}: {exc}") from exc
942
+ digest = ""
943
+ size = 0
944
+ file_id = f"file:{relative}"
945
+ nodes.append({"id": file_id, "type": "file", "path": relative})
946
+ symbol_payload = []
947
+ for symbol in symbols:
948
+ item = asdict(symbol)
949
+ # Byte offsets are an internal stable disambiguator for colliding
950
+ # AST scopes; they are not part of the public index payload schema.
951
+ item.pop("start_byte", None)
952
+ item["scope"] = f"{relative}::{symbol.scope_name}"
953
+ symbol_payload.append(item)
954
+ symbol_id = f"symbol:{relative}::{symbol.qualified_name}"
955
+ nodes.append({"id": symbol_id, "type": "symbol", "path": relative, **item})
956
+ parent_id = (
957
+ f"symbol:{relative}::{symbol.parent}" if symbol.parent else file_id
958
+ )
959
+ edges.append({"type": "contains", "from": parent_id, "to": symbol_id})
960
+ files.append({
961
+ "path": relative,
962
+ "language": language,
963
+ "parser": symbols[0].parser if symbols else (
964
+ "python-ast" if language == "python" else f"{language}-declaration"
965
+ ),
966
+ "error": error,
967
+ "content_hash": digest,
968
+ "size": size,
969
+ "symbols": symbol_payload,
970
+ })
971
+ return {
972
+ "schema_version": SCHEMA_VERSION,
973
+ "root": ".",
974
+ "files": files,
975
+ "nodes": nodes,
976
+ "edges": edges,
977
+ "summary": {
978
+ "files": len(files),
979
+ "symbols": sum(len(item["symbols"]) for item in files),
980
+ "parse_errors": sum(bool(item["error"]) for item in files),
981
+ },
982
+ }
983
+
984
+
985
+ def audit_units(
986
+ root: Path, backend: str = "auto", strict: bool = False,
987
+ *, cache: SourceContentCache | None = None,
988
+ ) -> list[dict]:
989
+ """返回最细审计单元;有符号时取叶子符号,否则退回文件。"""
990
+ root = root.resolve()
991
+ cache = cache if cache is not None else SourceContentCache()
992
+ result: list[dict] = []
993
+ for path in discover_source_paths(root, strict=strict):
994
+ relative = path.relative_to(root).as_posix()
995
+ symbols, error, language = parse_file(path, backend, cache=cache)
996
+ try:
997
+ digest = file_sha256(path, cache)
998
+ except OSError as exc:
999
+ if strict:
1000
+ raise SourceDiscoveryError(f"源码读取失败 {path}: {exc}") from exc
1001
+ digest = ""
1002
+ leaves = _leaf_symbols(symbols)
1003
+ if leaves and all(symbol.kind == "module" for symbol in leaves):
1004
+ # A file containing only constants/configuration remains a useful
1005
+ # file-level task; do not manufacture a synthetic callable task.
1006
+ leaves = []
1007
+ if leaves:
1008
+ result.extend({
1009
+ "scope": f"{relative}::{symbol.scope_name}",
1010
+ "path": relative,
1011
+ "name": symbol.name,
1012
+ "kind": symbol.kind,
1013
+ "line": symbol.start_line,
1014
+ "parser": symbol.parser,
1015
+ "error": error,
1016
+ "end_line": symbol.end_line,
1017
+ "content_hash": digest,
1018
+ "language": language,
1019
+ } for symbol in leaves)
1020
+ else:
1021
+ result.append({
1022
+ "scope": relative,
1023
+ "path": relative,
1024
+ "name": path.stem,
1025
+ "kind": "file",
1026
+ "line": 1,
1027
+ "parser": "fallback-file",
1028
+ "error": error,
1029
+ "language": language,
1030
+ "content_hash": digest,
1031
+ })
1032
+ return result
1033
+
1034
+
1035
+ def inventory_snapshot(
1036
+ root: Path, backend: str = "auto", strict: bool = False,
1037
+ *, cache: SourceContentCache | None = None,
1038
+ ) -> dict:
1039
+ """Return one hashable inventory for source and behavior-affecting assets."""
1040
+ root = root.resolve()
1041
+ cache = cache if cache is not None else SourceContentCache()
1042
+ source_paths = discover_source_paths(root, strict=strict)
1043
+ asset_paths = discover_asset_paths(root, strict=strict)
1044
+ records: list[dict] = []
1045
+ for path in source_paths:
1046
+ relative = path.relative_to(root).as_posix()
1047
+ symbols, error, language = parse_file(path, backend, cache=cache)
1048
+ records.append({
1049
+ "path": relative, "kind": "source", "language": language,
1050
+ "content_hash": file_sha256(path, cache), "parse_error": error,
1051
+ "scopes": [f"{relative}::{symbol.scope_name}" for symbol in symbols],
1052
+ })
1053
+ for path in asset_paths:
1054
+ records.append({
1055
+ "path": path.relative_to(root).as_posix(), "kind": "asset",
1056
+ "content_hash": file_sha256(path, cache),
1057
+ })
1058
+ records.sort(key=lambda item: (item["kind"], item["path"]))
1059
+ encoded = json.dumps(records, ensure_ascii=False, sort_keys=True).encode("utf-8")
1060
+ return {
1061
+ "schema_version": SCHEMA_VERSION,
1062
+ "files": records,
1063
+ "inventory_hash": hashlib.sha256(encoded).hexdigest(),
1064
+ }
1065
+
1066
+
1067
+ def main(argv: list[str] | None = None) -> int:
1068
+ parser = argparse.ArgumentParser(description=__doc__)
1069
+ parser.add_argument(
1070
+ "command", choices=("scan", "units", "inventory"), nargs="?", default="scan",
1071
+ )
1072
+ parser.add_argument("--root", type=Path, default=Path.cwd())
1073
+ parser.add_argument("--json", action="store_true")
1074
+ parser.add_argument("--strict", action="store_true",
1075
+ help="任一文件解析失败时返回非零")
1076
+ parser.add_argument("--backend", choices=("auto", "builtin", "tree-sitter"),
1077
+ default="auto")
1078
+ args = parser.parse_args(argv)
1079
+ if args.command == "inventory":
1080
+ try:
1081
+ payload = inventory_snapshot(args.root, args.backend, strict=args.strict)
1082
+ except SourceDiscoveryError as exc:
1083
+ print(f"[symbol_index] ✗ {exc}", file=sys.stderr)
1084
+ return 2
1085
+ except OSError as exc:
1086
+ print(f"[symbol_index] ✗ 项目清单读取失败: {exc}", file=sys.stderr)
1087
+ return 2
1088
+ if args.json:
1089
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
1090
+ else:
1091
+ print(f"[symbol_index] 清单文件 {len(payload['files'])},"
1092
+ f"inventory_hash={payload['inventory_hash']}")
1093
+ parse_errors = [item for item in payload["files"] if item.get("parse_error")]
1094
+ return 1 if args.strict and parse_errors else 0
1095
+ if args.command == "units":
1096
+ try:
1097
+ units = audit_units(args.root, args.backend, strict=args.strict)
1098
+ except SourceDiscoveryError as exc:
1099
+ print(f"[symbol_index] ✗ {exc}", file=sys.stderr)
1100
+ return 2
1101
+ if args.json:
1102
+ print(json.dumps({"schema_version": SCHEMA_VERSION, "units": units},
1103
+ ensure_ascii=False, indent=2))
1104
+ else:
1105
+ for unit in units:
1106
+ print(f"{unit['scope']}\t{unit['kind']}\tline {unit['line']}")
1107
+ parse_errors = sum(bool(unit.get("error")) for unit in units)
1108
+ if args.strict and parse_errors:
1109
+ return 1
1110
+ return 0 if units else 1
1111
+ try:
1112
+ payload = index_repository(args.root, args.backend, strict=args.strict)
1113
+ except SourceDiscoveryError as exc:
1114
+ print(f"[symbol_index] ✗ {exc}", file=sys.stderr)
1115
+ return 2
1116
+ if args.json:
1117
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
1118
+ else:
1119
+ summary = payload["summary"]
1120
+ print(f"[symbol_index] 文件 {summary['files']},符号 {summary['symbols']},"
1121
+ f"解析错误 {summary['parse_errors']}")
1122
+ for item in payload["files"]:
1123
+ status = (
1124
+ f"ERROR: {item['error']}" if item["error"]
1125
+ else f"{len(item['symbols'])} symbols"
1126
+ )
1127
+ print(f" {item['path']}: {status}")
1128
+ return 1 if args.strict and payload["summary"]["parse_errors"] else 0
1129
+
1130
+
1131
+ if __name__ == "__main__":
1132
+ sys.exit(main())