bugx-cli 0.1.0 → 0.1.1

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 (311) hide show
  1. package/README.md +190 -186
  2. package/core/README.md +2 -2
  3. package/core/agent/README.md +2 -1
  4. package/core/agent/agent_artifacts.py +8 -6
  5. package/core/agent/agent_eval.py +136 -54
  6. package/core/agent/agent_execution.py +218 -52
  7. package/core/agent/agent_orchestrator.py +14 -8
  8. package/core/agent/agent_targets.py +8 -2
  9. package/core/agent/feature_baseline.py +150 -0
  10. package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  11. package/core/assets/axe-core/LICENSE.txt +362 -0
  12. package/core/assets/axe-core/UPSTREAM.md +10 -0
  13. package/core/assets/axe-core/axe.min.js +12 -0
  14. package/core/assets/bugx-hero-en.svg +74 -0
  15. package/core/assets/bugx-hero-zh.svg +74 -0
  16. package/core/assets/codex.png +0 -0
  17. package/core/assets/dsh.png +0 -0
  18. package/core/assets/webui-chatgpt.jpg +0 -0
  19. package/core/assets/webui-session.jpg +0 -0
  20. package/core/assets/webui-skills.jpg +0 -0
  21. package/core/assets/webui-studio.jpg +0 -0
  22. package/core/assets/webui-zcode.jpg +0 -0
  23. package/core/assets/zcode.png +0 -0
  24. package/core/autonomous_cve/SPEC.md +1 -1
  25. package/core/autonomous_cve/attack_graph_store.py +152 -106
  26. package/core/autonomous_cve/behavior_graph.py +8 -2
  27. package/core/autonomous_cve/verifier.py +4 -1
  28. package/core/bugx.md +1 -1
  29. package/core/bugx_paths.py +43 -8
  30. package/core/cli-help.txt +66 -0
  31. package/core/cloud_sync/SPEC.md +1 -1
  32. package/core/cloud_sync/cloud_client.py +25 -6
  33. package/core/cloud_sync/cloud_onboard.py +42 -1
  34. package/core/cloud_sync/flywheel_client.py +16 -7
  35. package/core/cloud_sync/network_transport.py +24 -3
  36. package/core/cloud_sync/sensitive_filter.py +2 -2
  37. package/core/cloud_sync/sync_push.py +12 -10
  38. package/core/contracts/AGENT_GUIDE.md +6 -9
  39. package/core/contracts/README.md +2 -2
  40. package/core/contracts/bugx-runtime-contract.md +1 -1
  41. package/core/contracts/bugx-worker.md +1 -1
  42. package/core/contracts/engine_gap_contracts.py +86 -3
  43. package/core/coverage/coverage_discovery.py +599 -29
  44. package/core/coverage/coverage_evidence.py +47 -0
  45. package/core/coverage/coverage_forensics.py +9 -0
  46. package/core/coverage/coverage_validate.py +6 -1
  47. package/core/dev_harness/SPEC.md +1 -1
  48. package/core/engine-integrity.json +591 -419
  49. package/core/fuzzing/concurrency_fuzzer.py +53 -0
  50. package/core/fuzzing/differential_oracle.py +562 -27
  51. package/core/fuzzing/fuzz_input.py +109 -6
  52. package/core/fuzzing/stateful_fuzzer.py +72 -0
  53. package/core/governance/secret_redactor.py +22 -10
  54. package/core/host_acp/SPEC.md +1 -1
  55. package/core/host_acp/__init__.py +4 -4
  56. package/core/host_acp/claude.py +59 -1
  57. package/core/host_acp/cline.py +64 -1
  58. package/core/host_acp/codex.py +56 -1
  59. package/core/host_acp/dsh.py +59 -1
  60. package/core/host_acp/opencode.py +56 -1
  61. package/core/host_acp/pi.py +59 -1
  62. package/core/host_acp/zcode.py +59 -1
  63. package/core/host_runtime/SPEC.md +1 -1
  64. package/core/host_runtime/adapters.py +1 -1
  65. package/core/host_runtime/cline.py +13 -0
  66. package/core/host_runtime/host_evaluators.py +44 -4
  67. package/core/host_runtime/host_probe.py +1 -1
  68. package/core/host_runtime/host_provider_arbitrator.py +116 -62
  69. package/core/host_runtime/host_registry.py +15 -8
  70. package/core/host_runtime/mcp_registry_gate.py +12 -1
  71. package/core/host_runtime/pi.py +102 -0
  72. package/core/host_runtime/provider_facts.py +66 -0
  73. package/core/hosts/SPEC.md +1 -1
  74. package/core/hosts/__init__.py +6 -2
  75. package/core/hosts/_dsh_usage.py +1 -1
  76. package/core/hosts/base.py +32 -4
  77. package/core/hosts/claude.py +55 -0
  78. package/core/hosts/cline.py +6 -2
  79. package/core/hosts/codex.py +58 -0
  80. package/core/hosts/dsh.py +9 -1
  81. package/core/hosts/opencode.py +6 -6
  82. package/core/hosts/pi.py +159 -2
  83. package/core/infra/README.md +4 -2
  84. package/core/infra/__init__.py +2 -0
  85. package/core/infra/build_info.py +22 -3
  86. package/core/infra/client_metadata.py +1 -1
  87. package/core/infra/json_utils.py +22 -0
  88. package/core/launch_phases/README.md +2 -2
  89. package/core/launch_phases/SPEC.md +1 -1
  90. package/core/launch_phases/common.py +21 -2
  91. package/core/launch_phases/finding_confirm_phase.py +5 -1
  92. package/core/launch_phases/finding_settlement.py +188 -1
  93. package/core/launch_phases/judge_phase.py +69 -12
  94. package/core/launch_phases/orchestrator_controls.py +11 -7
  95. package/core/launch_phases/post_coverage_sync.py +9 -2
  96. package/core/launch_phases/post_phase.py +139 -3
  97. package/core/launch_phases/post_receipt.py +12 -1
  98. package/core/launch_phases/pre_phase.py +3 -3
  99. package/core/launch_phases/pre_recon_scout.py +53 -36
  100. package/core/launch_phases/pre_state_builder.py +23 -176
  101. package/core/launch_phases/round_orchestrator.py +15 -32
  102. package/core/launch_phases/session_runtime.py +56 -9
  103. package/core/launch_phases/startup_gates.py +36 -8
  104. package/core/launch_phases/startup_interaction.py +68 -12
  105. package/core/launch_phases/startup_version_gate.py +9 -3
  106. package/core/launch_phases/supervisor_bridge.py +46 -17
  107. package/core/launch_phases/supervisor_coverage.py +8 -2
  108. package/core/launch_phases/supervisor_degraded.py +1 -9
  109. package/core/launch_phases/worker_barriers.py +15 -5
  110. package/core/launch_phases/worker_orchestrator.py +105 -25
  111. package/core/ledger/README.md +1 -1
  112. package/core/ledger/SPEC.md +1 -1
  113. package/core/ledger/_facade.py +2 -1
  114. package/core/ledger/archive_ops.py +60 -2
  115. package/core/ledger/cli.py +6 -1
  116. package/core/ledger/export_ops.py +6 -1
  117. package/core/ledger/finding_confirmation.py +48 -6
  118. package/core/ledger/finding_lifecycle.py +428 -5
  119. package/core/ledger/finding_verification.py +44 -8
  120. package/core/ledger/incidents.py +10 -4
  121. package/core/ledger/patterns.py +10 -7
  122. package/core/ledger/receipt_contract.py +17 -1
  123. package/core/ledger/sync_ops.py +21 -16
  124. package/core/ledger/tool_experience.py +2 -1
  125. package/core/ledger/verify_life.py +88 -17
  126. package/core/locales/en-US.json +2 -2
  127. package/core/locales/zh-CN.json +2 -2
  128. package/core/mcp_handlers/SPEC.md +1 -1
  129. package/core/mcp_handlers/base.py +23 -3
  130. package/core/mcp_handlers/channel_lifecycle.py +85 -30
  131. package/core/mcp_handlers/retrieval_handlers.py +11 -1
  132. package/core/mcp_handlers/rpc_server.py +6 -1
  133. package/core/mcp_handlers/supervisor_handlers.py +32 -6
  134. package/core/mcp_handlers/tool_table.py +15 -0
  135. package/core/mcp_runtime_support/environment.py +0 -38
  136. package/core/mcp_runtime_support/verifier.py +0 -52
  137. package/core/metadata.txt +2 -3
  138. package/core/planning/README.md +1 -1
  139. package/core/planning/domain_router.py +4 -2
  140. package/core/planning/dynamic_flow_analyzer.py +219 -14
  141. package/core/planning/judge_pipeline.py +87 -4
  142. package/core/planning/prompt_harness.py +7 -5
  143. package/core/planning/spec_harvester.py +4 -4
  144. package/core/probes/INTERFACE.md +11 -1
  145. package/core/probes/SPEC.md +11 -1
  146. package/core/probes/__init__.py +46 -40
  147. package/core/probes/android_probe.py +177 -9
  148. package/core/probes/codebase_memory_probe.py +57 -0
  149. package/core/probes/desktop_probe.py +104 -0
  150. package/core/probes/differential_probe.py +99 -21
  151. package/core/probes/efficiency_probe.py +64 -0
  152. package/core/probes/ios_binary_probe.py +105 -1
  153. package/core/probes/memory_probe.py +66 -0
  154. package/core/probes/miniprogram_probe.py +75 -13
  155. package/core/probes/mobile_probe.py +215 -30
  156. package/core/probes/native_probe.py +88 -0
  157. package/core/probes/openwiki_probe.py +70 -0
  158. package/core/probes/pattern_probe.py +106 -0
  159. package/core/probes/platform_probe.py +81 -0
  160. package/core/probes/probe_registry.py +108 -7
  161. package/core/probes/sast_fixture_corpus.py +340 -0
  162. package/core/probes/sast_probe.py +553 -52
  163. package/core/probes/sast_rules.py +668 -28
  164. package/core/probes/sca_scanner.py +48 -0
  165. package/core/probes/ui_accessibility.py +149 -0
  166. package/core/probes/ui_audit.py +513 -0
  167. package/core/probes/ui_contract.py +273 -0
  168. package/core/probes/ui_evidence.py +212 -0
  169. package/core/probes/ui_measurements.py +314 -0
  170. package/core/probes/ui_repair.py +250 -0
  171. package/core/probes/ui_review.py +133 -0
  172. package/core/probes/ui_storybook.py +107 -0
  173. package/core/probes/ui_tokens.py +185 -0
  174. package/core/probes/ui_visual_diff.py +131 -0
  175. package/core/probes/web_probe.py +373 -18
  176. package/core/project_profiler/SPEC.md +1 -1
  177. package/core/project_profiler/arbitrator.py +6 -1
  178. package/core/project_profiler/detector.py +8 -1
  179. package/core/project_profiler/strategy.py +51 -15
  180. package/core/prompts/command_routing_en.md +2 -2
  181. package/core/prompts/command_routing_zh.md +2 -2
  182. package/core/prompts/stages/stage_repair.md +1 -1
  183. package/core/repair/README.md +1 -1
  184. package/core/repair/l7_repair_loop.py +1 -4
  185. package/core/repair/rsi_fixer.py +4 -4
  186. package/core/repair/rsi_loop.py +1 -3
  187. package/core/repair/rsi_repair.py +7 -7
  188. package/core/repair/rsi_scope.py +27 -8
  189. package/core/report_engine/SPEC.md +1 -1
  190. package/core/report_engine/attestation.py +8 -4
  191. package/core/report_engine/finding_report.py +2 -1
  192. package/core/report_engine/models.py +7 -9
  193. package/core/report_engine/sast_bridge.py +2 -2
  194. package/core/report_engine/server.py +18 -8
  195. package/core/report_engine/web-conformance.md +123 -18
  196. package/core/report_engine/web_conformance.py +21 -52
  197. package/core/retrieval/README.md +1 -1
  198. package/core/retrieval/SPEC.md +1 -1
  199. package/core/retrieval/code_analyzer.py +50 -14
  200. package/core/retrieval/context_assembler.py +7 -1
  201. package/core/retrieval/knowledge_sync.py +108 -14
  202. package/core/retrieval/symbol_index.py +25 -6
  203. package/core/retrieval/universal_code_matcher.py +234 -49
  204. package/core/runtime/README.md +1 -1
  205. package/core/runtime/bugx_logging.py +78 -7
  206. package/core/runtime/fixture_solidify.py +5 -10
  207. package/core/runtime/incident_eval.py +1 -1
  208. package/core/runtime/model_runner.py +4 -41
  209. package/core/runtime/platform_adapter.py +2 -2
  210. package/core/runtime/prep_validate.py +4 -2
  211. package/core/runtime/project_settings.py +2 -1
  212. package/core/runtime/scenario_eval.py +50 -8
  213. package/core/skills/bugx_docs_mcp_server.py +3 -1
  214. package/core/skills/bugx_mcp_server.py +29 -2
  215. package/core/skills/tools_kb.py +1 -1
  216. package/core/supervisor/README.md +1 -1
  217. package/core/supervisor/SPEC.md +1 -1
  218. package/core/supervisor/budget_governor.py +503 -9
  219. package/core/supervisor/checkpoint_pipeline.py +248 -6
  220. package/core/supervisor/checkpoint_sync.py +13 -0
  221. package/core/supervisor/claim_events.py +1 -1
  222. package/core/supervisor/finding_workflow.py +22 -5
  223. package/core/supervisor/lease_manager.py +1 -1
  224. package/core/supervisor/lifecycle_blocks.py +6 -1
  225. package/core/supervisor/rejection_remedies.py +52 -5
  226. package/core/supervisor/serial_authorization.py +48 -4
  227. package/core/supervisor/task_scheduler.py +2 -2
  228. package/core/supervisor/worker_checkpoint.py +8 -1
  229. package/core/supervisor/worker_runtime.py +8 -2
  230. package/core/supervisor_types/worker_claim.py +9 -0
  231. package/core/webui/README.md +1 -1
  232. package/core/webui/SPEC.md +2 -1
  233. package/core/webui/adapters/claude.py +5 -1
  234. package/core/webui/adapters/cline.py +10 -2
  235. package/core/webui/adapters/codex.py +5 -1
  236. package/core/webui/adapters/dsh.py +5 -1
  237. package/core/webui/docs_session_service.py +2 -2
  238. package/core/webui/mcp_inspector.py +11 -7
  239. package/core/webui/static/00-base.css +1060 -0
  240. package/core/webui/static/01-monitoring.css +802 -0
  241. package/core/webui/static/02-header-actions.css +321 -0
  242. package/core/webui/static/03-trigger-popover.css +697 -0
  243. package/core/webui/static/04-composer.css +628 -0
  244. package/core/webui/static/05-skills-center.css +878 -0
  245. package/core/webui/static/06-mcp-center.css +623 -0
  246. package/core/webui/static/07-skill-detail.css +265 -0
  247. package/core/webui/static/08-files-management.css +167 -0
  248. package/core/webui/static/09-files-center.css +386 -0
  249. package/core/webui/static/10-icons.css +105 -0
  250. package/core/webui/static/11-project-options.css +185 -0
  251. package/core/webui/static/12-profile-tab.css +383 -0
  252. package/core/webui/static/design-tokens.css +113 -0
  253. package/core/webui/static/index.html +14 -1
  254. package/core/webui/workspace_service.py +1 -1
  255. package/docs/07_distribution/01_README_NPM.md +190 -186
  256. package/ecosystem/integrations/README.md +1 -1
  257. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  258. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  259. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  260. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
  261. package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
  262. package/ecosystem/integrations/opencode/opencode.json +23 -12
  263. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  264. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  265. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  266. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  267. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  268. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  269. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  270. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  271. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  272. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  273. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
  274. package/interfaces/bin/bugx.js +37 -0
  275. package/interfaces/cli/bugx_cli/__init__.py +4 -2
  276. package/interfaces/cli/bugx_cli/cli.py +11 -4
  277. package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
  278. package/interfaces/cli/bugx_cli/commands/agent.py +339 -73
  279. package/interfaces/cli/bugx_cli/commands/audit.py +2 -2
  280. package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
  281. package/interfaces/cli/bugx_cli/commands/cloud.py +4 -3
  282. package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
  283. package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
  284. package/interfaces/cli/bugx_cli/commands/knowledge.py +2 -0
  285. package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
  286. package/interfaces/cli/bugx_cli/commands/plugin.py +55 -20
  287. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
  288. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
  289. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
  290. package/interfaces/cli/bugx_cli/commands/report.py +2 -6
  291. package/interfaces/cli/bugx_cli/commands/system.py +11 -11
  292. package/interfaces/cli/bugx_cli/common.py +15 -7
  293. package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
  294. package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
  295. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
  296. package/interfaces/cli/bugx_cli/infra/engine_installer.py +18 -10
  297. package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
  298. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
  299. package/interfaces/cli/bugx_cli/infra/security.py +13 -6
  300. package/package.json +2 -1
  301. package/pyproject.toml +20 -8
  302. package/scripts/ensure-python.mjs +7 -7
  303. package/scripts/sync-version.mjs +10 -21
  304. package/scripts/test-npm-wrapper.mjs +1 -1
  305. package/core/webui/static/project-settings.css +0 -6458
  306. package/docs/07_distribution/README.md +0 -16
  307. package/docs/README.md +0 -121
  308. package/interfaces/README.md +0 -143
  309. package/interfaces/bin/README.md +0 -35
  310. package/interfaces/cli/README.md +0 -90
  311. package/scripts/README.md +0 -118
@@ -13,10 +13,54 @@ Rust、C/C++、PHP、Python、C#、Swift、Ruby 提供确定性的代码结构
13
13
 
14
14
  from __future__ import annotations
15
15
 
16
+ import ast
16
17
  import re
18
+ import types
17
19
  from dataclasses import dataclass, field
18
20
  from pathlib import Path
19
- from typing import Any, Callable
21
+ from typing import Any, Callable, Mapping, Sequence
22
+
23
+ #: 行级抑制注释的**唯一**解析口径:``# bugx-ignore[: RULE-A, RULE-B] 理由`` /
24
+ #: ``// bugx-ignore`` / ``# nosec``。规则名限定为逗号分隔的标识符列表,其后的
25
+ #: 自由文本(理由)不会被吞进规则集合——旧实现用 ``[A-Za-z0-9_,\-\s]+`` 会把
26
+ #: 英文理由当成规则名,导致「写了抑制却仍报警」。
27
+ _SUPPRESSION_LINE_RE = re.compile(
28
+ r"(?:#|//|/\*)\s*(?:bugx-ignore(?::\s*"
29
+ r"([A-Za-z0-9][A-Za-z0-9_\-]*(?:\s*,\s*[A-Za-z0-9][A-Za-z0-9_\-]*)*)"
30
+ r")?|nosec\b)",
31
+ re.IGNORECASE,
32
+ )
33
+
34
+
35
+ def extract_suppressions(lines: Sequence[str]) -> dict[int, set[str]]:
36
+ """按行提取抑制信息:``{行号: 规则集合}``,空集合表示抑制该行全部规则。
37
+
38
+ Python AST 扫描器与多语言引擎共用这一份解析,避免两条路径口径漂移
39
+ (AST 路径此前只认「有没有注释」、不认规则名,等于抑制了整行)。
40
+ """
41
+ suppressions: dict[int, set[str]] = {}
42
+ for lineno, line in enumerate(lines, 1):
43
+ match = _SUPPRESSION_LINE_RE.search(line)
44
+ if not match:
45
+ continue
46
+ rules_str = match.group(1)
47
+ if rules_str:
48
+ suppressions[lineno] = {
49
+ rule.strip().upper() for rule in rules_str.split(",") if rule.strip()
50
+ }
51
+ else:
52
+ suppressions[lineno] = set()
53
+ return suppressions
54
+
55
+
56
+ def is_suppressed(suppressions: Mapping[int, set[str]], lineno: int, rule_id: str) -> bool:
57
+ """该行是否抑制了 ``rule_id``:空集合 = 整行抑制,否则按规则名精确匹配。"""
58
+ if lineno not in suppressions:
59
+ return False
60
+ suppressed_rules = suppressions[lineno]
61
+ if not suppressed_rules:
62
+ return True
63
+ return rule_id.upper() in suppressed_rules
20
64
 
21
65
  # 扩展名到语言标识映射
22
66
  EXT_TO_LANG: dict[str, str] = {
@@ -46,6 +90,120 @@ EXT_TO_LANG: dict[str, str] = {
46
90
  }
47
91
 
48
92
 
93
+ # 字符串动态构造的统一判据。``raw_args``(折叠前)与 ``resolved_args``(折叠后)
94
+ # 都要用它判:折叠会把 ``query`` 还原成它被赋值的那个表达式,此时原始实参只剩
95
+ # 一个裸变量名,只在折叠前判定必然漏掉「拼接发生在上一行」这一最常见形态。
96
+ _CONCAT_PATTERNS = (
97
+ r"\bfmt\.Sprintf\b", # Go
98
+ r"\bString\.format\b", # Java / Python
99
+ r"`[^`]*\$\{", # JS/TS 模板字面量插值
100
+ r'(?:^|[^\w])[fF]["\']', # Python f-string 前缀(折叠后保留)
101
+ )
102
+
103
+ _STRING_LITERAL_RE = re.compile(
104
+ r'"""(?:\\.|[^\\])*?"""'
105
+ r"|'''(?:\\.|[^\\])*?'''"
106
+ r'|"(?:\\.|[^"\\\n])*"'
107
+ r"|'(?:\\.|[^'\\\n])*'"
108
+ r"|`(?:\\.|[^`\\])*`"
109
+ )
110
+
111
+
112
+ def detect_string_concat(text: str) -> bool:
113
+ """判断一段实参文本是否包含字符串动态构造。
114
+
115
+ 先剥离字符串字面量再找 ``+``:SQL 语句里 ``attempts = attempts + 1`` 这类
116
+ **字面量内部的算术加号**不是拼接,把它算进去会让每一条参数化查询都变成
117
+ SQL 注入(实测仓库自身因此产出 30+ 条 critical 假阳性)。
118
+ """
119
+ if not text:
120
+ return False
121
+ if any(re.search(pat, text) for pat in _CONCAT_PATTERNS):
122
+ return True
123
+ return "+" in _STRING_LITERAL_RE.sub('""', text)
124
+
125
+
126
+ @dataclass
127
+ class _PyScope:
128
+ """一个 Python 词法作用域:行区间 + 变量折叠结果 + 形参名。"""
129
+ start: int
130
+ end: int
131
+ name: str
132
+ env: dict
133
+ params: tuple[str, ...] = ()
134
+
135
+
136
+ def _python_function_params(node: ast.AST) -> tuple[str, ...]:
137
+ """取函数节点的全部形参名(含仅位置参数、*args、**kwargs、仅关键字参数)。"""
138
+ args = getattr(node, "args", None)
139
+ if args is None:
140
+ return ()
141
+ names: list[str] = []
142
+ for group in (
143
+ getattr(args, "posonlyargs", []),
144
+ getattr(args, "args", []),
145
+ getattr(args, "kwonlyargs", []),
146
+ ):
147
+ for item in group:
148
+ names.append(item.arg)
149
+ for extra in (getattr(args, "vararg", None), getattr(args, "kwarg", None)):
150
+ if extra is not None:
151
+ names.append(extra.arg)
152
+ return tuple(names)
153
+
154
+
155
+ def _python_scope_envs(analyzer: Any, text: str, filepath: Path) -> list[_PyScope]:
156
+ """按 Python AST 折叠出**按作用域隔离**的变量环境。
157
+
158
+ 模块级语句作为一个覆盖全文件的兜底作用域(作用域名为空串)。解析失败时返回
159
+ 空列表,调用方退化为「不做折叠」而不是拿错环境去还原实参。
160
+ """
161
+ try:
162
+ tree = ast.parse(text, filename=str(filepath))
163
+ except (SyntaxError, ValueError):
164
+ return []
165
+
166
+ total = max(len(text.splitlines()), 1)
167
+ scopes: list[_PyScope] = []
168
+ try:
169
+ module_env = analyzer.fold_python_function_scope(
170
+ types.SimpleNamespace(body=tree.body)
171
+ )
172
+ except Exception:
173
+ module_env = {}
174
+ if module_env:
175
+ scopes.append(_PyScope(1, total, "", module_env))
176
+
177
+ for node in ast.walk(tree):
178
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
179
+ continue
180
+ try:
181
+ env = analyzer.fold_python_function_scope(node)
182
+ except Exception:
183
+ continue
184
+ params = _python_function_params(node)
185
+ if not env and not params:
186
+ continue
187
+ start = getattr(node, "lineno", 1)
188
+ end = getattr(node, "end_lineno", None) or total
189
+ scopes.append(_PyScope(start, end, node.name, env, params))
190
+ return scopes
191
+
192
+
193
+ def _scope_env_for_line(scopes: list[_PyScope], line: int) -> tuple[dict, str, tuple[str, ...]]:
194
+ """取覆盖该行的作用域链,按「外层→内层」合并(内层覆盖外层)。"""
195
+ containing = [s for s in scopes if s.start <= line <= s.end]
196
+ if not containing:
197
+ return {}, "", ()
198
+ containing.sort(key=lambda s: s.end - s.start, reverse=True)
199
+ env: dict = {}
200
+ params: list[str] = []
201
+ for scope in containing:
202
+ env.update(scope.env)
203
+ params.extend(scope.params)
204
+ return env, containing[-1].name, tuple(dict.fromkeys(params))
205
+
206
+
49
207
  @dataclass
50
208
  class CodeSpan:
51
209
  line: int
@@ -70,6 +228,12 @@ class CallNode:
70
228
  resolved_callee: str = "" # 经局部常量折叠/解混淆还原后的被调用者名
71
229
  resolved_args: str = "" # 经局部变量替换/折叠后的实参列表字符串
72
230
  is_tainted: bool = False # 实参是否已被 Web 框架 Source 污染
231
+ param_names: tuple[str, ...] = () # 所在函数的形参名(「外部可控」的最小判据)
232
+ # callee 前一个字符是否为 `.`。``base_obj`` 只覆盖 ``a.b.c(...)`` 这类链式
233
+ # 调用;``re.exec(s)``、``/x/g.exec(s)``、``f().exec(s)`` 的 receiver 以
234
+ # ``)``/``]``/正则字面量结尾,正则抽取只剩裸方法名,``base_obj`` 为空,
235
+ # 结构上无法与真正的裸函数调用区分——必须靠这个标记。
236
+ preceded_by_dot: bool = False
73
237
 
74
238
 
75
239
  @dataclass
@@ -124,24 +288,33 @@ class UniversalCodeMatcher:
124
288
  if DynamicFlowAnalyzer:
125
289
  try:
126
290
  analyzer = DynamicFlowAnalyzer(language=self.language)
127
- var_env = analyzer.fold_line_scope(lines)
128
291
  if self.language == "python":
129
- try:
130
- import ast
131
- tree = ast.parse(text, filename=str(filepath))
132
- for node in ast.walk(tree):
133
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
134
- var_env.update(analyzer.fold_python_function_scope(node))
135
- except Exception:
136
- pass
137
-
138
- for call in calls:
139
- rc, ra, it = analyzer.resolve_call_target(
140
- call.callee, call.args_raw, var_env, snippet=call.span.snippet
141
- )
142
- call.resolved_callee = rc or call.callee
143
- call.resolved_args = ra or call.args_raw
144
- call.is_tainted = it
292
+ # Python 有真实 AST,作用域是确定的:按**函数**折叠,再按调用
293
+ # 所在行挑对应函数的变量环境。绝不能把各函数的环境平铺合并
294
+ # ——同名局部变量(如多个函数各自定义的 ``req``)会互相覆盖,
295
+ # 一处调用的实参被还原成另一处函数的赋值,直接制造假阳性。
296
+ # 也绝不叠加 ``fold_line_scope``:那是对整份文件逐行做正则
297
+ # 匹配,跨函数、跨缩进层级,对 Python 既冗余又不安全。
298
+ scopes = _python_scope_envs(analyzer, text, filepath)
299
+ for call in calls:
300
+ env, scope_name, params = _scope_env_for_line(scopes, call.span.line)
301
+ call.enclosing_function = scope_name
302
+ call.param_names = params
303
+ rc, ra, it = analyzer.resolve_call_target(
304
+ call.callee, call.args_raw, env, snippet=call.span.snippet
305
+ )
306
+ call.resolved_callee = rc or call.callee
307
+ call.resolved_args = ra or call.args_raw
308
+ call.is_tainted = it
309
+ else:
310
+ var_env = analyzer.fold_line_scope(lines)
311
+ for call in calls:
312
+ rc, ra, it = analyzer.resolve_call_target(
313
+ call.callee, call.args_raw, var_env, snippet=call.span.snippet
314
+ )
315
+ call.resolved_callee = rc or call.callee
316
+ call.resolved_args = ra or call.args_raw
317
+ call.is_tainted = it
145
318
  except Exception:
146
319
  for call in calls:
147
320
  if not call.resolved_callee:
@@ -153,6 +326,12 @@ class UniversalCodeMatcher:
153
326
  call.resolved_callee = call.callee
154
327
  call.resolved_args = call.args_raw
155
328
 
329
+ # 折叠后补齐拼接判定:``execute(query)`` 的原始实参是裸变量名,真正的
330
+ # 拼接/插值在 ``query`` 的赋值行上,只有折叠后的 ``resolved_args`` 才看得见。
331
+ for call in calls:
332
+ if not call.has_string_concat:
333
+ call.has_string_concat = detect_string_concat(call.resolved_args)
334
+
156
335
  return ParsedSource(
157
336
  filepath=filepath,
158
337
  rel_path=rel_path,
@@ -165,27 +344,14 @@ class UniversalCodeMatcher:
165
344
  )
166
345
 
167
346
  def _extract_suppressions(self, lines: list[str]) -> dict[int, set[str]]:
168
- """从注释中提取行级抑制信息。
347
+ """从注释中提取行级抑制信息(解析口径见模块级 ``extract_suppressions``)。
169
348
  支持语法:
170
349
  // bugx-ignore: RULE-001, RULE-002 [reason]
171
350
  # bugx-ignore: RULE-001
172
351
  // bugx-ignore (忽略该行全部规则)
173
352
  # nosec (兼容 Bandit 忽略标记)
174
353
  """
175
- suppressions: dict[int, set[str]] = {}
176
- ignore_pattern = re.compile(r"(?:#|//|/\*)\s*(?:bugx-ignore(?::\s*([A-Za-z0-9_,\-\s]+))?|nosec\b)", re.IGNORECASE)
177
-
178
- for lineno, line in enumerate(lines, 1):
179
- m = ignore_pattern.search(line)
180
- if m:
181
- rules_str = m.group(1)
182
- if rules_str:
183
- rule_ids = {r.strip().upper() for r in rules_str.split(",") if r.strip()}
184
- suppressions[lineno] = rule_ids
185
- else:
186
- # 忽略全部
187
- suppressions[lineno] = set()
188
- return suppressions
354
+ return extract_suppressions(lines)
189
355
 
190
356
  def _strip_comments_and_strings(self, text: str, lang: str) -> tuple[str, list[str]]:
191
357
  """语言感知分词:将注释替换为空格,将字符串内容替换为标号以保留位置,生成净代码。"""
@@ -195,6 +361,7 @@ class UniversalCodeMatcher:
195
361
  in_single_quote = False
196
362
  in_double_quote = False
197
363
  in_backtick = False
364
+ in_triple = ""
198
365
  in_line_comment = False
199
366
  in_block_comment = False
200
367
 
@@ -227,7 +394,7 @@ class UniversalCodeMatcher:
227
394
  continue
228
395
 
229
396
  # 处理字符串转义
230
- if (in_single_quote or in_double_quote or in_backtick) and c == "\\":
397
+ if (in_single_quote or in_double_quote or in_backtick or in_triple) and c == "\\":
231
398
  chars[i] = " "
232
399
  if i + 1 < length and chars[i + 1] != "\n":
233
400
  chars[i + 1] = " "
@@ -236,11 +403,27 @@ class UniversalCodeMatcher:
236
403
  i += 1
237
404
  continue
238
405
 
406
+ # 处理三引号字符串(Python/Ruby 的 docstring 与多行字面量)。
407
+ # 必须整体识别:把 `"""` 当成三次普通引号开关会让 docstring 正文
408
+ # 泄漏成代码(文档里的示例载荷被当成真实调用),同时逐字符置空会
409
+ # 吞掉内部换行、使后续所有行号前移。
410
+ if in_triple:
411
+ if text.startswith(in_triple, i):
412
+ for k in range(len(in_triple)):
413
+ chars[i + k] = " "
414
+ i += len(in_triple)
415
+ in_triple = ""
416
+ continue
417
+ if c != "\n":
418
+ chars[i] = " "
419
+ i += 1
420
+ continue
421
+
239
422
  # 处理反引号字符串 (JS/TS 模板字符串, Go 反引号字符串)
240
423
  if in_backtick:
241
424
  if c == "`":
242
425
  in_backtick = False
243
- else:
426
+ elif c != "\n":
244
427
  chars[i] = " "
245
428
  i += 1
246
429
  continue
@@ -249,7 +432,7 @@ class UniversalCodeMatcher:
249
432
  if in_double_quote:
250
433
  if c == '"':
251
434
  in_double_quote = False
252
- else:
435
+ elif c != "\n":
253
436
  chars[i] = " "
254
437
  i += 1
255
438
  continue
@@ -258,7 +441,7 @@ class UniversalCodeMatcher:
258
441
  if in_single_quote:
259
442
  if c == "'":
260
443
  in_single_quote = False
261
- else:
444
+ elif c != "\n":
262
445
  chars[i] = " "
263
446
  i += 1
264
447
  continue
@@ -284,6 +467,16 @@ class UniversalCodeMatcher:
284
467
  i += 2
285
468
  continue
286
469
 
470
+ # 进入三引号字符串(仅 Python:`"""` / `'''` 是真正的多行字面量,
471
+ # 其余语言的 `"""` 只是相邻空串,按普通引号处理即可)
472
+ if lang == "python" and (
473
+ text.startswith('"""', i) or text.startswith("'''", i)
474
+ ):
475
+ in_triple = text[i:i + 3]
476
+ chars[i] = chars[i + 1] = chars[i + 2] = " "
477
+ i += 3
478
+ continue
479
+
287
480
  if c == '"':
288
481
  in_double_quote = True
289
482
  i += 1
@@ -339,10 +532,7 @@ class UniversalCodeMatcher:
339
532
  args = [a.strip() for a in self._split_arguments(raw_args) if a.strip()]
340
533
 
341
534
  # 判定是否包含字符串拼接
342
- has_concat = bool(
343
- re.search(r'(\+\s*["\']|["\']\s*\+|\bfmt\.Sprintf\b|\bString\.format\b|`[^`]*\${)', raw_args)
344
- or ("+" in raw_args and any(q in raw_args for q in ('"', "'", "`")))
345
- )
535
+ has_concat = detect_string_concat(raw_args)
346
536
 
347
537
  # 计算行号列号
348
538
  start_pos = match.start(1)
@@ -372,6 +562,7 @@ class UniversalCodeMatcher:
372
562
  args=args,
373
563
  has_string_concat=has_concat,
374
564
  span=span,
565
+ preceded_by_dot=start_pos > 0 and clean_text[start_pos - 1] == ".",
375
566
  ))
376
567
 
377
568
  return calls
@@ -427,11 +618,5 @@ class UniversalCodeMatcher:
427
618
 
428
619
  @staticmethod
429
620
  def is_line_suppressed(parsed: ParsedSource, lineno: int, rule_id: str) -> bool:
430
- """检查指定行是否被抑制。"""
431
- if lineno not in parsed.suppressions:
432
- return False
433
- supp_rules = parsed.suppressions[lineno]
434
- if not supp_rules:
435
- # 空集合代表抑制该行全部规则
436
- return True
437
- return rule_id.upper() in supp_rules
621
+ """检查指定行是否抑制了 ``rule_id``(口径见模块级 ``is_suppressed``)。"""
622
+ return is_suppressed(parsed.suppressions, lineno, rule_id)
@@ -1,6 +1,6 @@
1
1
  # BugX Core Runtime Subsystem (核心运行时、环境与基础设施)
2
2
 
3
- > **版本契约**: `1.0.0` | **所属分层**: `Layer 0: 基础设施与操作系统抽象`
3
+ > **版本契约**: `0.1.1` | **所属分层**: `Layer 0: 基础设施与操作系统抽象`
4
4
  > **工程规范**: 参见 [`docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md`](../../docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md)
5
5
  > **守卫机制**: `scripts/verify_directory_indices.py` (100% 物理条目索引覆盖)
6
6
 
@@ -245,7 +245,9 @@ class _JsonFormatter(logging.Formatter):
245
245
  from core.infra import build_info
246
246
  payload["build_id"] = build_info.get_build_id()
247
247
  except Exception:
248
- pass
248
+ # 降级必须可区分(F-RSI-20261115-288):build_id 缺失时显式留痕,
249
+ # 让"日志缺字段"可被下游审计检索,而不是无声蒸发。
250
+ payload["build_id_unavailable"] = True
249
251
  fields = getattr(record, "bugx_fields", {})
250
252
  if isinstance(fields, dict):
251
253
  payload.update(safe_value(fields))
@@ -255,13 +257,58 @@ class _JsonFormatter(logging.Formatter):
255
257
 
256
258
 
257
259
  class _OtlpHttpHandler(logging.Handler):
258
- """Asynchronous HTTP exporter to push spans to OTLP endpoint (e.g. Arize Phoenix / Langfuse)."""
260
+ """Asynchronous HTTP exporter to push spans to OTLP endpoint (e.g. Arize Phoenix / Langfuse).
261
+
262
+ Degradation policy (F-RSI-20261115-288): telemetry/audit exports must
263
+ never silently disappear. TLS policy construction failures refuse to send
264
+ (fail-closed, no downgrade to the bare system trust store), send failures
265
+ are counted on the handler, and first/every-20th occurrence is surfaced on
266
+ stderr. Plaintext ``http://`` endpoints warn once at construction unless
267
+ ``BUGX_OTLP_ALLOW_INSECURE=1`` acknowledges the choice.
268
+ """
259
269
 
260
270
  def __init__(self, endpoint: str) -> None:
261
271
  super().__init__()
262
272
  self.endpoint = endpoint
273
+ import threading
263
274
  import urllib.request
264
275
  self._request_mod = urllib.request
276
+ self._counter_lock = threading.Lock()
277
+ self.export_failure_count = 0
278
+ self.last_export_error: str | None = None
279
+ self.tls_degradation_count = 0
280
+ try:
281
+ from core.infra import build_info
282
+ self._scope_version = str(build_info.BASE_VERSION)
283
+ except Exception:
284
+ self._scope_version = "unknown"
285
+ if not endpoint.startswith("https://"):
286
+ self._warn_insecure_endpoint()
287
+
288
+ def _warn_insecure_endpoint(self) -> None:
289
+ """Plaintext OTLP endpoints must be an explicit, visible choice."""
290
+ if os.environ.get("BUGX_OTLP_ALLOW_INSECURE", "").strip() == "1":
291
+ return
292
+ print(
293
+ f" ⚠ BUGX_OTLP_ENDPOINT 非 HTTPS ({self.endpoint}):诊断/审计 span 将"
294
+ "以明文传输。确需 http 端点时设置 BUGX_OTLP_ALLOW_INSECURE=1 显式确认。",
295
+ file=sys.stderr,
296
+ )
297
+
298
+ def _warn_export_failure(self, kind: str) -> None:
299
+ """Emit one bounded stderr line for an export failure.
300
+
301
+ Never the span payload, never a raise: the logging infrastructure must
302
+ not break the main flow, but its failures must stay observable. The
303
+ structured counters on this handler remain the machine-readable truth.
304
+ """
305
+ detail = str(safe_value(self.last_export_error))[:200]
306
+ print(
307
+ f"[bugx-otlp] {kind} failed"
308
+ f" (export_failures={self.export_failure_count},"
309
+ f" tls_degradations={self.tls_degradation_count}): {detail}",
310
+ file=sys.stderr,
311
+ )
265
312
 
266
313
  def emit(self, record: logging.LogRecord) -> None:
267
314
  fields = getattr(record, "bugx_fields", {})
@@ -331,7 +378,7 @@ class _OtlpHttpHandler(logging.Handler):
331
378
  }],
332
379
  },
333
380
  "scopeSpans": [{
334
- "scope": {"name": "bugx.tracer", "version": "1.0.0"},
381
+ "scope": {"name": "bugx.tracer", "version": self._scope_version},
335
382
  "spans": [span],
336
383
  }],
337
384
  }],
@@ -348,12 +395,36 @@ class _OtlpHttpHandler(logging.Handler):
348
395
  try:
349
396
  from core.infra.client_metadata import tls_context
350
397
  kwargs["context"] = tls_context(base_url=self.endpoint)
351
- except Exception:
352
- pass
398
+ except Exception as exc:
399
+ # TLS 策略构造失败必须 fail-closed 且可见(F-RSI-20261115-288):
400
+ # client_metadata.tls_context 对 BUGX_CA_BUNDLE 配置错误会显式
401
+ # 抛错,静默吞掉会击穿其校验契约,把 https 上报降级为系统默认
402
+ # 信任库。这里拒绝发送并留下结构化计数 + 可见告警。
403
+ with self._counter_lock:
404
+ self.tls_degradation_count += 1
405
+ self.last_export_error = f"tls_policy: {type(exc).__name__}: {exc}"
406
+ surface = (
407
+ self.tls_degradation_count == 1
408
+ or self.tls_degradation_count % 20 == 0
409
+ )
410
+ if surface:
411
+ self._warn_export_failure("tls_policy")
412
+ return
353
413
  with self._request_mod.urlopen(req, **kwargs) as resp:
354
414
  pass
355
- except Exception:
356
- pass
415
+ except Exception as exc:
416
+ # 上报失败不可静默(F-RSI-20261115-288):审计证据链可静默丢失与
417
+ # 本仓证据一致性门冲突。计数 + 有界 stderr 告警(首次与每第 20 次),
418
+ # 不抛出——logging 基础设施不得影响审计主流程。
419
+ with self._counter_lock:
420
+ self.export_failure_count += 1
421
+ self.last_export_error = f"{type(exc).__name__}: {exc}"
422
+ surface = (
423
+ self.export_failure_count == 1
424
+ or self.export_failure_count % 20 == 0
425
+ )
426
+ if surface:
427
+ self._warn_export_failure("export")
357
428
 
358
429
 
359
430
  class _SecureRotatingFileHandler(RotatingFileHandler):
@@ -29,8 +29,8 @@
29
29
 
30
30
  ## 产物
31
31
 
32
- evals/fixtures/<slug>.fixture 从发现证据里摘出的最小可复现片段
33
- evals/cases.json 追加新 case
32
+ verification/evals/fixtures/<slug>.fixture 从发现证据里摘出的最小可复现片段
33
+ verification/evals/cases.json 追加新 case
34
34
 
35
35
  fixture 摘取**按行窗口**而不是整文件复制:真实项目动辄上千行,把整文件塞进
36
36
  评测集会让人工审视标准答案变得不可能,且会带进大量无关代码干扰判定。
@@ -56,7 +56,7 @@ import re
56
56
  from pathlib import Path
57
57
 
58
58
  REPO_ROOT = Path(__file__).resolve().parents[2]
59
- _EVALS_DIR = (REPO_ROOT / "verification" / "evals") if (REPO_ROOT / "verification" / "evals").is_dir() else (REPO_ROOT / "evals")
59
+ _EVALS_DIR = REPO_ROOT / "verification" / "evals"
60
60
  CASES_PATH = _EVALS_DIR / "cases.json"
61
61
  GOLDEN_PATH = _EVALS_DIR / "golden-findings.json"
62
62
  FIXTURES_DIR = _EVALS_DIR / "fixtures"
@@ -285,13 +285,8 @@ def solidify(payload: dict, *, source_root: Path,
285
285
  # 而 fixtures_dir 没有时,``relative_to(root)`` 会抛 ValueError(两者字面
286
286
  # 前缀不同)。这类「同一目录的两个名字」在真实环境里到处都是,必须在入口
287
287
  # 统一归一,而不是指望每个调用方都记得 resolve。
288
- # evals 目录随仓库布局迁移(evals/ → verification/evals/),与模块级
289
- # _EVALS_DIR 的双路径回退保持同一规则;root 注入时按注入根推导,测试隔离不破。
290
- evals_dir = (
291
- (root / "verification" / "evals")
292
- if (root / "verification" / "evals").is_dir()
293
- else (root / "evals")
294
- )
288
+ # 评测资产的唯一仓库路径是 verification/evals;旧的 evals/ 双轨已移除。
289
+ evals_dir = root / "verification" / "evals"
295
290
  cases_path = (cases_path or (evals_dir / "cases.json")).resolve()
296
291
  fixtures_dir = (fixtures_dir or (evals_dir / "fixtures")).resolve()
297
292
  golden_path = (golden_path or (
@@ -25,7 +25,7 @@ import tempfile
25
25
 
26
26
  AGENT_DIR = Path(__file__).resolve().parents[1]
27
27
  REPO_ROOT = AGENT_DIR.parent
28
- FIXTURE_ROOT = (REPO_ROOT / "verification" / "evals" / "incident-fixtures") if (REPO_ROOT / "verification" / "evals").is_dir() else (REPO_ROOT / "evals" / "incident-fixtures")
28
+ FIXTURE_ROOT = REPO_ROOT / "verification" / "evals" / "incident-fixtures"
29
29
 
30
30
 
31
31
  def load_fixtures(root: Path = FIXTURE_ROOT) -> list[dict]:
@@ -21,7 +21,6 @@ import json
21
21
  import os
22
22
  import re
23
23
  import shutil
24
- import signal
25
24
  import subprocess
26
25
  import tempfile
27
26
  import threading
@@ -31,6 +30,7 @@ from dataclasses import dataclass
31
30
 
32
31
  from core.secure_atomic import atomic_write_bytes, reject_symlink_components
33
32
  from core.governance.token_budget import estimate_tokens
33
+ from core.runtime.platform_adapter import terminate_process_tree
34
34
 
35
35
 
36
36
  class RunnerAdapterError(ValueError):
@@ -315,43 +315,6 @@ class _OutputCollector:
315
315
  }
316
316
 
317
317
 
318
- def _terminate_process_tree(process: subprocess.Popen[bytes]) -> None:
319
- if os.name == "nt":
320
- try:
321
- process.send_signal(getattr(subprocess, "CTRL_BREAK_EVENT", 1))
322
- except (OSError, ValueError):
323
- pass
324
- try:
325
- process.terminate()
326
- except OSError:
327
- pass
328
- try:
329
- process.wait(timeout=1)
330
- except subprocess.TimeoutExpired:
331
- try:
332
- process.kill()
333
- except OSError:
334
- pass
335
- return
336
- try:
337
- os.killpg(process.pid, signal.SIGTERM)
338
- except (OSError, ProcessLookupError):
339
- try:
340
- process.terminate()
341
- except OSError:
342
- pass
343
- try:
344
- process.wait(timeout=1)
345
- except subprocess.TimeoutExpired:
346
- try:
347
- os.killpg(process.pid, signal.SIGKILL)
348
- except (OSError, ProcessLookupError):
349
- try:
350
- process.kill()
351
- except OSError:
352
- pass
353
-
354
-
355
318
  def _run_bounded(command: list[str], cwd: Path, timeout: float,
356
319
  output_limit: int) -> tuple[int, bool, bool, bytes, dict, bytes, dict]:
357
320
  creationflags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) if os.name == "nt" else 0
@@ -383,12 +346,12 @@ def _run_bounded(command: list[str], cwd: Path, timeout: float,
383
346
  while process.poll() is None:
384
347
  if stdout_collector.exceeded or stderr_collector.exceeded:
385
348
  output_exceeded = True
386
- _terminate_process_tree(process)
349
+ terminate_process_tree(process)
387
350
  break
388
351
  remaining = deadline - time.monotonic()
389
352
  if remaining <= 0:
390
353
  timed_out = True
391
- _terminate_process_tree(process)
354
+ terminate_process_tree(process)
392
355
  break
393
356
  try:
394
357
  process.wait(timeout=min(0.1, remaining))
@@ -396,7 +359,7 @@ def _run_bounded(command: list[str], cwd: Path, timeout: float,
396
359
  continue
397
360
  finally:
398
361
  if timed_out or output_exceeded:
399
- _terminate_process_tree(process)
362
+ terminate_process_tree(process)
400
363
  for reader in readers:
401
364
  reader.join(timeout=2)
402
365
  for stream in (process.stdout, process.stderr):
@@ -383,7 +383,7 @@ class _OutputCollector:
383
383
  }
384
384
 
385
385
 
386
- def _terminate_process_tree(process: subprocess.Popen[bytes]) -> None:
386
+ def terminate_process_tree(process: subprocess.Popen[bytes]) -> None:
387
387
  if os.name == "nt":
388
388
  try:
389
389
  process.send_signal(getattr(subprocess, "CTRL_BREAK_EVENT", 1))
@@ -447,7 +447,7 @@ def _run_bounded(command: list[str], cwd: Path, env: dict[str, str], timeout: fl
447
447
  process.wait(timeout=timeout)
448
448
  except subprocess.TimeoutExpired:
449
449
  timed_out = True
450
- _terminate_process_tree(process)
450
+ terminate_process_tree(process)
451
451
  finally:
452
452
  for reader in readers:
453
453
  reader.join(timeout=2)