bugx-cli 0.1.0 → 0.1.2

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 (338) hide show
  1. package/README.md +193 -185
  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/README.md +3 -2
  11. package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  12. package/core/assets/axe-core/LICENSE.txt +362 -0
  13. package/core/assets/axe-core/UPSTREAM.md +10 -0
  14. package/core/assets/axe-core/axe.min.js +12 -0
  15. package/core/assets/bugx-hero-en.svg +74 -0
  16. package/core/assets/bugx-hero-zh.svg +74 -0
  17. package/core/assets/bugx-social-preview.svg +71 -0
  18. package/core/assets/bugx-wechat-group.png +0 -0
  19. package/core/assets/codex.png +0 -0
  20. package/core/assets/dsh.png +0 -0
  21. package/core/assets/webui-chatgpt.jpg +0 -0
  22. package/core/assets/webui-session.jpg +0 -0
  23. package/core/assets/webui-skills.jpg +0 -0
  24. package/core/assets/webui-studio.jpg +0 -0
  25. package/core/assets/webui-zcode.jpg +0 -0
  26. package/core/assets/zcode.png +0 -0
  27. package/core/audit_packs/README.md +2 -0
  28. package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
  29. package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
  30. package/core/audit_packs/pitfalls/go_backend.json +66 -0
  31. package/core/audit_packs/pitfalls/java_spring.json +64 -0
  32. package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
  33. package/core/audit_packs/pitfalls/python_web.json +82 -0
  34. package/core/autonomous_cve/SPEC.md +1 -1
  35. package/core/autonomous_cve/attack_graph_store.py +152 -106
  36. package/core/autonomous_cve/behavior_graph.py +8 -2
  37. package/core/autonomous_cve/verifier.py +4 -1
  38. package/core/bugx.md +1 -1
  39. package/core/bugx_paths.py +43 -8
  40. package/core/cli-help.txt +66 -0
  41. package/core/cloud_sync/SPEC.md +1 -1
  42. package/core/cloud_sync/cloud_client.py +81 -11
  43. package/core/cloud_sync/cloud_onboard.py +42 -1
  44. package/core/cloud_sync/consent.py +33 -3
  45. package/core/cloud_sync/flywheel_client.py +186 -15
  46. package/core/cloud_sync/network_transport.py +24 -3
  47. package/core/cloud_sync/sensitive_filter.py +2 -2
  48. package/core/cloud_sync/sync_push.py +12 -10
  49. package/core/contracts/AGENT_GUIDE.md +6 -9
  50. package/core/contracts/README.md +2 -2
  51. package/core/contracts/bugx-runtime-contract.md +1 -1
  52. package/core/contracts/bugx-worker.md +1 -1
  53. package/core/contracts/engine_gap_contracts.py +86 -3
  54. package/core/coverage/coverage_discovery.py +599 -29
  55. package/core/coverage/coverage_evidence.py +47 -0
  56. package/core/coverage/coverage_forensics.py +9 -0
  57. package/core/coverage/coverage_validate.py +6 -1
  58. package/core/dev_harness/SPEC.md +1 -1
  59. package/core/engine-integrity.json +670 -442
  60. package/core/fuzzing/concurrency_fuzzer.py +53 -0
  61. package/core/fuzzing/differential_oracle.py +562 -27
  62. package/core/fuzzing/fuzz_input.py +109 -6
  63. package/core/fuzzing/stateful_fuzzer.py +72 -0
  64. package/core/governance/secret_redactor.py +22 -10
  65. package/core/host_acp/SPEC.md +1 -1
  66. package/core/host_acp/__init__.py +4 -4
  67. package/core/host_acp/claude.py +59 -1
  68. package/core/host_acp/cline.py +64 -1
  69. package/core/host_acp/codex.py +56 -1
  70. package/core/host_acp/dsh.py +59 -1
  71. package/core/host_acp/opencode.py +56 -1
  72. package/core/host_acp/pi.py +59 -1
  73. package/core/host_acp/zcode.py +59 -1
  74. package/core/host_runtime/SPEC.md +1 -1
  75. package/core/host_runtime/adapters.py +1 -1
  76. package/core/host_runtime/cline.py +13 -0
  77. package/core/host_runtime/host_evaluators.py +44 -4
  78. package/core/host_runtime/host_probe.py +1 -1
  79. package/core/host_runtime/host_provider_arbitrator.py +116 -62
  80. package/core/host_runtime/host_registry.py +15 -8
  81. package/core/host_runtime/mcp_registry_gate.py +12 -1
  82. package/core/host_runtime/pi.py +102 -0
  83. package/core/host_runtime/provider_facts.py +66 -0
  84. package/core/hosts/SPEC.md +1 -1
  85. package/core/hosts/__init__.py +6 -2
  86. package/core/hosts/_dsh_usage.py +1 -1
  87. package/core/hosts/base.py +32 -4
  88. package/core/hosts/claude.py +55 -0
  89. package/core/hosts/cline.py +6 -2
  90. package/core/hosts/codex.py +58 -0
  91. package/core/hosts/dsh.py +9 -1
  92. package/core/hosts/opencode.py +6 -6
  93. package/core/hosts/pi.py +159 -2
  94. package/core/infra/README.md +4 -2
  95. package/core/infra/__init__.py +2 -0
  96. package/core/infra/build_info.py +22 -3
  97. package/core/infra/client_metadata.py +1 -1
  98. package/core/infra/json_utils.py +22 -0
  99. package/core/launch_phases/README.md +6 -3
  100. package/core/launch_phases/SPEC.md +1 -1
  101. package/core/launch_phases/common.py +21 -2
  102. package/core/launch_phases/finding_confirm_phase.py +170 -5
  103. package/core/launch_phases/finding_settlement.py +188 -1
  104. package/core/launch_phases/judge_phase.py +69 -12
  105. package/core/launch_phases/orchestrator_controls.py +11 -7
  106. package/core/launch_phases/post_coverage_sync.py +9 -2
  107. package/core/launch_phases/post_phase.py +144 -8
  108. package/core/launch_phases/post_receipt.py +12 -1
  109. package/core/launch_phases/pre_phase.py +3 -3
  110. package/core/launch_phases/pre_recon_scout.py +66 -36
  111. package/core/launch_phases/pre_state_builder.py +23 -176
  112. package/core/launch_phases/report_sharing.py +3 -7
  113. package/core/launch_phases/round_orchestrator.py +129 -58
  114. package/core/launch_phases/semantic_recon.py +545 -0
  115. package/core/launch_phases/session_runtime.py +56 -9
  116. package/core/launch_phases/startup_gates.py +36 -8
  117. package/core/launch_phases/startup_interaction.py +68 -12
  118. package/core/launch_phases/startup_version_gate.py +13 -3
  119. package/core/launch_phases/supervisor_bridge.py +46 -17
  120. package/core/launch_phases/supervisor_coverage.py +8 -2
  121. package/core/launch_phases/supervisor_degraded.py +1 -9
  122. package/core/launch_phases/verify_loop.py +767 -0
  123. package/core/launch_phases/worker_barriers.py +15 -5
  124. package/core/launch_phases/worker_orchestrator.py +105 -25
  125. package/core/launch_phases/worker_prior.py +115 -0
  126. package/core/ledger/README.md +2 -1
  127. package/core/ledger/SPEC.md +1 -1
  128. package/core/ledger/_facade.py +2 -1
  129. package/core/ledger/archive_ops.py +60 -2
  130. package/core/ledger/cli.py +6 -1
  131. package/core/ledger/export_ops.py +6 -1
  132. package/core/ledger/finding_confirmation.py +48 -6
  133. package/core/ledger/finding_lifecycle.py +428 -5
  134. package/core/ledger/finding_verification.py +555 -10
  135. package/core/ledger/fp_ledger.py +255 -0
  136. package/core/ledger/incidents.py +10 -4
  137. package/core/ledger/patterns.py +10 -7
  138. package/core/ledger/receipt_contract.py +17 -1
  139. package/core/ledger/sync_ops.py +21 -16
  140. package/core/ledger/tool_experience.py +2 -1
  141. package/core/ledger/verify_life.py +88 -17
  142. package/core/locales/en-US.json +2 -2
  143. package/core/locales/zh-CN.json +2 -2
  144. package/core/mcp_handlers/SPEC.md +1 -1
  145. package/core/mcp_handlers/base.py +23 -3
  146. package/core/mcp_handlers/channel_lifecycle.py +85 -30
  147. package/core/mcp_handlers/retrieval_handlers.py +11 -1
  148. package/core/mcp_handlers/rpc_server.py +6 -1
  149. package/core/mcp_handlers/supervisor_handlers.py +32 -6
  150. package/core/mcp_handlers/tool_table.py +15 -0
  151. package/core/mcp_runtime_support/environment.py +0 -38
  152. package/core/mcp_runtime_support/verifier.py +0 -52
  153. package/core/metadata.txt +2 -3
  154. package/core/planning/README.md +2 -1
  155. package/core/planning/domain_router.py +4 -2
  156. package/core/planning/dynamic_flow_analyzer.py +219 -14
  157. package/core/planning/judge_pipeline.py +87 -4
  158. package/core/planning/prompt_harness.py +57 -15
  159. package/core/planning/prompt_policy_engine.py +386 -0
  160. package/core/planning/spec_harvester.py +4 -4
  161. package/core/probes/INTERFACE.md +11 -1
  162. package/core/probes/SPEC.md +11 -1
  163. package/core/probes/__init__.py +46 -40
  164. package/core/probes/android_probe.py +177 -9
  165. package/core/probes/codebase_memory_probe.py +57 -0
  166. package/core/probes/desktop_probe.py +104 -0
  167. package/core/probes/differential_probe.py +99 -21
  168. package/core/probes/efficiency_probe.py +64 -0
  169. package/core/probes/ios_binary_probe.py +105 -1
  170. package/core/probes/memory_probe.py +66 -0
  171. package/core/probes/miniprogram_probe.py +75 -13
  172. package/core/probes/mobile_probe.py +215 -30
  173. package/core/probes/native_probe.py +88 -0
  174. package/core/probes/openwiki_probe.py +70 -0
  175. package/core/probes/pattern_probe.py +106 -0
  176. package/core/probes/platform_probe.py +81 -0
  177. package/core/probes/probe_registry.py +108 -7
  178. package/core/probes/sast_fixture_corpus.py +340 -0
  179. package/core/probes/sast_probe.py +553 -52
  180. package/core/probes/sast_rules.py +668 -28
  181. package/core/probes/sca_scanner.py +48 -0
  182. package/core/probes/ui_accessibility.py +149 -0
  183. package/core/probes/ui_audit.py +513 -0
  184. package/core/probes/ui_contract.py +273 -0
  185. package/core/probes/ui_evidence.py +212 -0
  186. package/core/probes/ui_measurements.py +314 -0
  187. package/core/probes/ui_repair.py +250 -0
  188. package/core/probes/ui_review.py +133 -0
  189. package/core/probes/ui_storybook.py +107 -0
  190. package/core/probes/ui_tokens.py +185 -0
  191. package/core/probes/ui_visual_diff.py +131 -0
  192. package/core/probes/web_probe.py +373 -18
  193. package/core/project_profiler/SPEC.md +1 -1
  194. package/core/project_profiler/arbitrator.py +6 -1
  195. package/core/project_profiler/detector.py +8 -1
  196. package/core/project_profiler/strategy.py +51 -15
  197. package/core/prompts/README.md +4 -2
  198. package/core/prompts/command_routing_en.md +2 -2
  199. package/core/prompts/command_routing_zh.md +2 -2
  200. package/core/prompts/policies/prompt_policies.json +101 -0
  201. package/core/prompts/stages/stage_repair.md +1 -1
  202. package/core/prompts/stages/stage_verify.defensive.md +42 -0
  203. package/core/prompts/stages/stage_verify.md +44 -0
  204. package/core/repair/README.md +1 -1
  205. package/core/repair/l7_repair_loop.py +1 -4
  206. package/core/repair/rsi_fixer.py +4 -4
  207. package/core/repair/rsi_loop.py +1 -3
  208. package/core/repair/rsi_repair.py +7 -7
  209. package/core/repair/rsi_scope.py +27 -8
  210. package/core/report_engine/SPEC.md +1 -1
  211. package/core/report_engine/attestation.py +8 -4
  212. package/core/report_engine/finding_report.py +2 -1
  213. package/core/report_engine/models.py +7 -9
  214. package/core/report_engine/report_share.py +0 -8
  215. package/core/report_engine/sast_bridge.py +2 -2
  216. package/core/report_engine/server.py +18 -8
  217. package/core/report_engine/web-conformance.md +123 -18
  218. package/core/report_engine/web_conformance.py +21 -52
  219. package/core/retrieval/README.md +2 -1
  220. package/core/retrieval/SPEC.md +1 -1
  221. package/core/retrieval/code_analyzer.py +50 -14
  222. package/core/retrieval/context_assembler.py +7 -1
  223. package/core/retrieval/knowledge_sync.py +108 -14
  224. package/core/retrieval/pitfall_packs.py +277 -0
  225. package/core/retrieval/symbol_index.py +25 -6
  226. package/core/retrieval/universal_code_matcher.py +234 -49
  227. package/core/runtime/README.md +1 -1
  228. package/core/runtime/bugx_logging.py +78 -7
  229. package/core/runtime/fixture_solidify.py +5 -10
  230. package/core/runtime/global_telemetry.py +20 -0
  231. package/core/runtime/incident_eval.py +1 -1
  232. package/core/runtime/model_runner.py +4 -41
  233. package/core/runtime/platform_adapter.py +2 -2
  234. package/core/runtime/prep_validate.py +4 -2
  235. package/core/runtime/project_settings.py +2 -1
  236. package/core/runtime/scenario_eval.py +50 -8
  237. package/core/skills/bugx_docs_mcp_server.py +3 -1
  238. package/core/skills/bugx_mcp_server.py +29 -2
  239. package/core/skills/tools_kb.py +1 -1
  240. package/core/supervisor/README.md +1 -1
  241. package/core/supervisor/SPEC.md +1 -1
  242. package/core/supervisor/budget_governor.py +503 -9
  243. package/core/supervisor/checkpoint_pipeline.py +248 -6
  244. package/core/supervisor/checkpoint_sync.py +13 -0
  245. package/core/supervisor/claim_events.py +1 -1
  246. package/core/supervisor/finding_workflow.py +22 -5
  247. package/core/supervisor/lease_manager.py +1 -1
  248. package/core/supervisor/lifecycle_blocks.py +6 -1
  249. package/core/supervisor/rejection_remedies.py +52 -5
  250. package/core/supervisor/serial_authorization.py +48 -4
  251. package/core/supervisor/task_scheduler.py +2 -2
  252. package/core/supervisor/worker_checkpoint.py +8 -1
  253. package/core/supervisor/worker_runtime.py +8 -2
  254. package/core/supervisor_types/worker_claim.py +9 -0
  255. package/core/webui/README.md +1 -1
  256. package/core/webui/SPEC.md +2 -1
  257. package/core/webui/adapters/claude.py +5 -1
  258. package/core/webui/adapters/cline.py +10 -2
  259. package/core/webui/adapters/codex.py +5 -1
  260. package/core/webui/adapters/dsh.py +5 -1
  261. package/core/webui/docs_session_service.py +2 -2
  262. package/core/webui/mcp_inspector.py +11 -7
  263. package/core/webui/static/00-base.css +1060 -0
  264. package/core/webui/static/01-monitoring.css +802 -0
  265. package/core/webui/static/02-header-actions.css +321 -0
  266. package/core/webui/static/03-trigger-popover.css +697 -0
  267. package/core/webui/static/04-composer.css +628 -0
  268. package/core/webui/static/05-skills-center.css +878 -0
  269. package/core/webui/static/06-mcp-center.css +623 -0
  270. package/core/webui/static/07-skill-detail.css +265 -0
  271. package/core/webui/static/08-files-management.css +167 -0
  272. package/core/webui/static/09-files-center.css +386 -0
  273. package/core/webui/static/10-icons.css +105 -0
  274. package/core/webui/static/11-project-options.css +185 -0
  275. package/core/webui/static/12-profile-tab.css +383 -0
  276. package/core/webui/static/design-tokens.css +113 -0
  277. package/core/webui/static/index.html +14 -1
  278. package/core/webui/workspace_service.py +1 -1
  279. package/docs/07_distribution/01_README_NPM.md +193 -185
  280. package/ecosystem/integrations/README.md +1 -1
  281. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  282. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  283. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  284. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
  285. package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
  286. package/ecosystem/integrations/opencode/opencode.json +23 -12
  287. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  288. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  289. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  290. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  291. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  292. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  293. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  294. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  295. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  296. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  297. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
  298. package/interfaces/bin/bugx.js +37 -0
  299. package/interfaces/cli/bugx_cli/__init__.py +4 -2
  300. package/interfaces/cli/bugx_cli/cli.py +172 -69
  301. package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
  302. package/interfaces/cli/bugx_cli/commands/agent.py +461 -134
  303. package/interfaces/cli/bugx_cli/commands/audit.py +10 -9
  304. package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
  305. package/interfaces/cli/bugx_cli/commands/cloud.py +31 -22
  306. package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
  307. package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
  308. package/interfaces/cli/bugx_cli/commands/knowledge.py +5 -4
  309. package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
  310. package/interfaces/cli/bugx_cli/commands/plugin.py +58 -23
  311. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
  312. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
  313. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
  314. package/interfaces/cli/bugx_cli/commands/project.py +6 -13
  315. package/interfaces/cli/bugx_cli/commands/report.py +2 -6
  316. package/interfaces/cli/bugx_cli/commands/system.py +524 -169
  317. package/interfaces/cli/bugx_cli/common.py +21 -15
  318. package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
  319. package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
  320. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
  321. package/interfaces/cli/bugx_cli/infra/engine_installer.py +35 -16
  322. package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
  323. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
  324. package/interfaces/cli/bugx_cli/infra/security.py +13 -6
  325. package/package.json +30 -15
  326. package/pyproject.toml +60 -9
  327. package/scripts/ensure-python.mjs +7 -7
  328. package/scripts/sync-version.mjs +10 -21
  329. package/scripts/test-npm-wrapper.mjs +1 -1
  330. package/core/assets/bugx-hero-cn.png +0 -0
  331. package/core/assets/bugx-hero-en.png +0 -0
  332. package/core/webui/static/project-settings.css +0 -6458
  333. package/docs/07_distribution/README.md +0 -16
  334. package/docs/README.md +0 -121
  335. package/interfaces/README.md +0 -143
  336. package/interfaces/bin/README.md +0 -35
  337. package/interfaces/cli/README.md +0 -90
  338. package/scripts/README.md +0 -118
@@ -25,7 +25,6 @@ import hashlib
25
25
  import json
26
26
  import os
27
27
  import shutil
28
- import signal
29
28
  import statistics
30
29
  import subprocess
31
30
  import sys
@@ -52,7 +51,8 @@ for _p in (str(_CORE_DIR), str(REPO_ROOT)):
52
51
  sys.path.insert(0, _p)
53
52
 
54
53
  from core.retrieval import symbol_index
55
- _EVALS_DIR = (REPO_ROOT / "verification" / "evals") if (REPO_ROOT / "verification" / "evals").is_dir() else (REPO_ROOT / "evals")
54
+ from core.runtime.platform_adapter import terminate_process_tree as _terminate_runner
55
+ _EVALS_DIR = REPO_ROOT / "verification" / "evals"
56
56
  DEFAULT_CASES = _EVALS_DIR / "cases.json"
57
57
  DEFAULT_FINDINGS = _EVALS_DIR / "golden-findings.json"
58
58
  SEVERITY_ORDER = {"info": 0, "low": 1, "medium": 2, "high": 3, "critical": 4}
@@ -84,12 +84,6 @@ class EvalError(ValueError):
84
84
 
85
85
 
86
86
  def load_json(path: Path) -> dict:
87
- if not path.exists():
88
- p_str = str(path)
89
- if "/evals/" in p_str:
90
- alt = Path(p_str.replace("/evals/", "/verification/evals/"))
91
- if alt.exists():
92
- path = alt
93
87
  try:
94
88
  value = json.loads(path.read_text(encoding="utf-8"))
95
89
  except OSError as exc:
@@ -108,8 +102,6 @@ def _resolve_in_root(raw: str, root: Path) -> Path | None:
108
102
  try:
109
103
  resolved_root = root.resolve(strict=True)
110
104
  candidate = root / path
111
- if not candidate.exists() and raw.startswith("evals/") and (root / "verification" / path).exists():
112
- candidate = root / "verification" / path
113
105
  resolved = candidate.resolve(strict=True)
114
106
  resolved.relative_to(resolved_root)
115
107
  except (OSError, ValueError):
@@ -278,6 +270,78 @@ def invalid_evidence_ids(findings: list[dict], root: Path = REPO_ROOT) -> list[s
278
270
  ]
279
271
 
280
272
 
273
+ # DEF-2:证据契约的正确格式样例(单一真源,拒绝回注与探针共用;只描述契约,
274
+ # 不放宽契约——path 仍必须是 workspace 内真实文件的相对路径)。
275
+ CORRECT_EVIDENCE_SAMPLE = '[{"path": "core/foo.py", "line": 42}]'
276
+
277
+
278
+ def evidence_item_valid(item: object, root: Path) -> bool:
279
+ """公开别名:与 ``_evidence_item_valid`` 同一实现(防漂移单一真源)。"""
280
+ return _evidence_item_valid(item, root)
281
+
282
+
283
+ def evidence_item_violation(item: object, root: Path) -> str | None:
284
+ """单条 evidence 证据项的结构化违规原因(``None`` = 通过契约校验)。
285
+
286
+ DEF-2:checkpoint 摄入侧拒绝时只给一行「缺真实 workspace evidence」,
287
+ 模型/宿主不知道缺什么字段、哪个 path 不存在,同因重试烧尽 attempt 预算。
288
+ 本函数把 ``_evidence_item_valid`` 的同一套判定谓词展开为可回注重试提示词
289
+ 的具体原因;接受条件与 ``_evidence_item_valid`` 逐字同源,绝不放宽
290
+ 真实文件/行号契约。
291
+ """
292
+ if not isinstance(item, dict):
293
+ return (
294
+ f"evidence 项必须是对象(收到 {type(item).__name__}),"
295
+ f"正确格式 {CORRECT_EVIDENCE_SAMPLE}"
296
+ )
297
+ path = item.get("path")
298
+ if not isinstance(path, str) or not path.strip():
299
+ return "evidence 缺 path(必须是非空字符串的 workspace 相对路径)"
300
+ raw = path.strip()
301
+ candidate = Path(raw)
302
+ if candidate.is_absolute():
303
+ return f"evidence path 是绝对路径(必须用相对 workspace 根的路径): {raw[:200]}"
304
+ try:
305
+ resolved_root = root.resolve(strict=True)
306
+ except OSError:
307
+ return f"workspace 根不可解析,无法校验 evidence path: {raw[:200]}"
308
+ resolved = (root / raw).resolve(strict=False)
309
+ try:
310
+ resolved.relative_to(resolved_root)
311
+ except ValueError:
312
+ return f"evidence path 越出 workspace 边界: {raw[:200]}"
313
+ if not resolved.exists():
314
+ return f"evidence path 在 workspace 内不存在(必须是真实文件): {raw[:200]}"
315
+ if not resolved.is_file():
316
+ return f"evidence path 不是普通文件: {raw[:200]}"
317
+ line = item.get("line")
318
+ if line is None:
319
+ return None
320
+ if not isinstance(line, int) or isinstance(line, bool) or line < 1:
321
+ return f"evidence line 必须是正整数(收到 {line!r})"
322
+ try:
323
+ with resolved.open("r", encoding="utf-8", errors="replace") as handle:
324
+ total = sum(1 for _ in handle)
325
+ except OSError:
326
+ return f"evidence path 文件不可读: {raw[:200]}"
327
+ if line > total:
328
+ return f"evidence line 超出文件行数(文件共 {total} 行,收到 {line})"
329
+ return None
330
+
331
+
332
+ def finding_evidence_violations(finding: dict, root: Path) -> list[str]:
333
+ """逐条列出 finding 全部 evidence 项的结构化违规(空列表 = 证据有效)。"""
334
+ evidence = finding.get("evidence")
335
+ if not isinstance(evidence, list) or not evidence:
336
+ return ["evidence 必须是非空数组"]
337
+ issues: list[str] = []
338
+ for index, item in enumerate(evidence, 1):
339
+ violation = evidence_item_violation(item, root)
340
+ if violation:
341
+ issues.append(f"evidence[{index}] {violation}")
342
+ return issues
343
+
344
+
281
345
  def _hard_confirmed(finding: dict) -> bool:
282
346
  """Count only findings that pass the shared confirmation gate."""
283
347
  try:
@@ -292,9 +356,18 @@ def _hard_confirmed(finding: dict) -> bool:
292
356
 
293
357
 
294
358
  def score(cases_payload: dict, findings_payload: dict,
295
- root: Path = REPO_ROOT) -> dict:
359
+ root: Path = REPO_ROOT,
360
+ feature_baseline_payload: dict | None = None) -> dict:
296
361
  cases = validate_cases(cases_payload, root)
297
362
  findings = validate_findings(findings_payload)
363
+ # F-022:feature baseline 可选。提供时计算 completeness 维度并重分配
364
+ # quality_score 权重(六维度①功能完备性为差异化核心);缺省时行为不变。
365
+ baseline_features = None
366
+ if feature_baseline_payload is not None:
367
+ from core.agent.feature_baseline import (
368
+ completeness_metrics, validate_feature_baseline, COMPLETENESS_WEIGHTED,
369
+ )
370
+ baseline_features = validate_feature_baseline(feature_baseline_payload)
298
371
  case_by_id = {case["id"]: case for case in cases}
299
372
  matched: dict[str, list[dict]] = {}
300
373
  for finding in findings:
@@ -381,7 +454,7 @@ def score(cases_payload: dict, findings_payload: dict,
381
454
  recall * 0.40 + precision * 0.25
382
455
  + evidence_validity * 0.20 + reproducibility * 0.15
383
456
  )
384
- return {
457
+ metrics = {
385
458
  "cases_total": total_cases,
386
459
  "cases_found": found,
387
460
  "findings_total": total_findings,
@@ -408,6 +481,17 @@ def score(cases_payload: dict, findings_payload: dict,
408
481
  [float(item["confidence"]) for item in findings]
409
482
  ), 4) if findings else 0.0,
410
483
  }
484
+ if baseline_features is not None:
485
+ completeness = completeness_metrics(baseline_features, findings)
486
+ metrics.update(completeness)
487
+ metrics["quality_score"] = round((
488
+ recall * COMPLETENESS_WEIGHTED["recall"]
489
+ + precision * COMPLETENESS_WEIGHTED["precision"]
490
+ + evidence_validity * COMPLETENESS_WEIGHTED["evidence_validity"]
491
+ + reproducibility * COMPLETENESS_WEIGHTED["reproducibility"]
492
+ + completeness["completeness_recall"] * COMPLETENESS_WEIGHTED["completeness_recall"]
493
+ ) * 100, 2)
494
+ return metrics
411
495
 
412
496
 
413
497
  def threshold_failures(metrics: dict, thresholds: dict) -> list[str]:
@@ -416,9 +500,14 @@ def threshold_failures(metrics: dict, thresholds: dict) -> list[str]:
416
500
  "min_precision": "precision",
417
501
  "min_evidence_validity": "evidence_validity",
418
502
  "min_reproducibility": "reproducibility",
503
+ # F-022:completeness 阈值仅在提供 feature baseline(metrics 含键)时检查,
504
+ # 无 baseline 的存量评测集不受影响。
505
+ "min_completeness_recall": "completeness_recall",
419
506
  }
420
507
  failures = []
421
508
  for threshold_name, metric_name in mapping.items():
509
+ if threshold_name not in thresholds or metric_name not in metrics:
510
+ continue
422
511
  expected = float(thresholds[threshold_name])
423
512
  actual = float(metrics[metric_name])
424
513
  if actual < expected:
@@ -471,7 +560,8 @@ def _fixture_sha256(path: Path | None) -> str:
471
560
 
472
561
 
473
562
  def metrics_record(metrics: dict, cases_payload: dict,
474
- findings_payload: dict, root: Path = REPO_ROOT) -> dict:
563
+ findings_payload: dict, root: Path = REPO_ROOT,
564
+ feature_baseline_payload: dict | None = None) -> dict:
475
565
  """生成可持久化、可比较且不包含评测答案的基线记录。"""
476
566
  cases = validate_cases(cases_payload, root)
477
567
  cases_fingerprint = {
@@ -486,13 +576,17 @@ def metrics_record(metrics: dict, cases_payload: dict,
486
576
  for case in cases
487
577
  ],
488
578
  }
489
- return {
579
+ record = {
490
580
  "schema_version": 1,
491
581
  "created_at": dt.datetime.now(dt.timezone.utc).isoformat(),
492
582
  "cases_digest": canonical_digest(cases_fingerprint),
493
583
  "findings_digest": canonical_digest(findings_payload),
494
584
  "metrics": dict(metrics),
495
585
  }
586
+ if feature_baseline_payload is not None:
587
+ # baseline 对比必须绑定同一份功能基准(不同基准的 completeness 不可比)
588
+ record["feature_baseline_digest"] = canonical_digest(feature_baseline_payload)
589
+ return record
496
590
 
497
591
 
498
592
  def baseline_failures(metrics: dict, baseline_payload: dict,
@@ -503,7 +597,12 @@ def baseline_failures(metrics: dict, baseline_payload: dict,
503
597
  if baseline_payload.get("schema_version") != 1 or not isinstance(baseline, dict):
504
598
  raise EvalError("baseline metrics 协议无效")
505
599
  failures: list[str] = []
506
- for name in QUALITY_METRICS:
600
+ # F-022:completeness_recall 数据驱动纳入回归对比——基线记录里带了它
601
+ # (生成时提供了 feature baseline)才要求当前运行也有。
602
+ watched = list(QUALITY_METRICS)
603
+ if "completeness_recall" in baseline:
604
+ watched.append("completeness_recall")
605
+ for name in watched:
507
606
  expected = baseline.get(name)
508
607
  actual = metrics.get(name)
509
608
  if not isinstance(expected, (int, float)) or isinstance(expected, bool):
@@ -688,43 +787,6 @@ class _RunnerOutput:
688
787
  return bytes(self.prefix)
689
788
 
690
789
 
691
- def _terminate_runner(process: subprocess.Popen[bytes]) -> None:
692
- if os.name == "nt":
693
- try:
694
- process.send_signal(getattr(subprocess, "CTRL_BREAK_EVENT", 1))
695
- except (OSError, ValueError):
696
- pass
697
- try:
698
- process.terminate()
699
- except OSError:
700
- pass
701
- try:
702
- process.wait(timeout=1)
703
- except subprocess.TimeoutExpired:
704
- try:
705
- process.kill()
706
- except OSError:
707
- pass
708
- return
709
- try:
710
- os.killpg(process.pid, signal.SIGTERM)
711
- except (OSError, ProcessLookupError):
712
- try:
713
- process.terminate()
714
- except OSError:
715
- pass
716
- try:
717
- process.wait(timeout=1)
718
- except subprocess.TimeoutExpired:
719
- try:
720
- os.killpg(process.pid, signal.SIGKILL)
721
- except (OSError, ProcessLookupError):
722
- try:
723
- process.kill()
724
- except OSError:
725
- pass
726
-
727
-
728
790
  def _run_runner_process(command: list[str], input_text: str, cwd: Path,
729
791
  env: dict[str, str] | None, timeout: float,
730
792
  output_limit: int) -> tuple[int, bool, bool, bytes, bytes]:
@@ -951,9 +1013,17 @@ def _print_score(metrics: dict, failures: list[str]) -> None:
951
1013
  print(f" 重复率: {metrics['duplicate_rate'] * 100:.1f}%")
952
1014
  print(f" 确认率: {metrics['confirmation_rate'] * 100:.1f}%")
953
1015
  print(f" 综合质量分: {metrics['quality_score']:.2f}/100")
1016
+ if "completeness_recall" in metrics:
1017
+ # F-022:feature baseline 提供时输出 completeness 维度(管线解析依赖
1018
+ # 这些行前缀,勿改措辞)
1019
+ print(f" 完备性召回: {metrics['completeness_recall'] * 100:.1f}%")
1020
+ print(f" 完备性精确: {metrics['completeness_precision'] * 100:.1f}%")
1021
+ print(f" 植入缺失检出: {metrics['planted_gaps_found']}/{metrics['planted_gaps_total']}")
954
1022
  print(f" 耗时/Token: {metrics['duration_seconds']:.3f}s / {metrics['token_count']}")
955
1023
  if metrics["missed_case_ids"]:
956
1024
  print(" 漏检: " + ", ".join(metrics["missed_case_ids"]))
1025
+ if metrics.get("missed_gap_ids"):
1026
+ print(" 漏检缺失: " + ", ".join(metrics["missed_gap_ids"]))
957
1027
  if failures:
958
1028
  print("[agent_eval] FAIL:")
959
1029
  for failure in failures:
@@ -994,6 +1064,8 @@ def main(argv: list[str] | None = None) -> int:
994
1064
  parser.add_argument("--save-metrics", type=Path)
995
1065
  parser.add_argument("--baseline-metrics", type=Path)
996
1066
  parser.add_argument("--regression-tolerance", type=float, default=0.0)
1067
+ parser.add_argument("--feature-baseline", type=Path,
1068
+ help="功能完备性基准 JSON(F-022):提供时计算 completeness 维度并计入 quality_score")
997
1069
  args = parser.parse_args(argv)
998
1070
  try:
999
1071
  if args.protocol_only and args.command != "run":
@@ -1044,7 +1116,16 @@ def main(argv: list[str] | None = None) -> int:
1044
1116
  raise EvalError("finding 缺真实证据: " + ", ".join(invalid_evidence))
1045
1117
  print("[agent_eval] OK: cases/findings 协议与证据路径有效")
1046
1118
  return 0
1047
- metrics = score(cases_payload, findings_payload, args.root)
1119
+ feature_baseline_payload = None
1120
+ if args.feature_baseline:
1121
+ feature_baseline_payload = load_json(args.feature_baseline)
1122
+ elif isinstance(cases_payload.get("feature_baseline"), dict):
1123
+ # F-022 管线接线:feature baseline 可随评测集内嵌(与 cases 同
1124
+ # 版本化),scenario_eval/fixture 场景无需独立 flag 即可启用
1125
+ # completeness 维度。显式 --feature-baseline 优先。
1126
+ feature_baseline_payload = cases_payload["feature_baseline"]
1127
+ metrics = score(cases_payload, findings_payload, args.root,
1128
+ feature_baseline_payload=feature_baseline_payload)
1048
1129
  failures = threshold_failures(metrics, cases_payload["thresholds"])
1049
1130
  if args.baseline_metrics:
1050
1131
  failures.extend(baseline_failures(
@@ -1053,7 +1134,8 @@ def main(argv: list[str] | None = None) -> int:
1053
1134
  if args.save_metrics:
1054
1135
  _save_json_atomic(
1055
1136
  args.save_metrics,
1056
- metrics_record(metrics, cases_payload, findings_payload, args.root),
1137
+ metrics_record(metrics, cases_payload, findings_payload, args.root,
1138
+ feature_baseline_payload=feature_baseline_payload),
1057
1139
  )
1058
1140
  except EvalError as exc:
1059
1141
  if args.json:
@@ -11,6 +11,7 @@ import os
11
11
  import re
12
12
  import signal
13
13
  import subprocess
14
+ import sys
14
15
  import threading
15
16
  import time
16
17
  from dataclasses import asdict, dataclass, field
@@ -302,6 +303,11 @@ def execute_check_plan(
302
303
  except (OSError, ValueError) as exc:
303
304
  raise ExecutionError(f"CheckPlan process could not be started: {exc}") from exc
304
305
 
306
+ # Bind the kernel identity at creation time, before any poll()/wait() can
307
+ # reap the leader and release its PID for reuse. The numeric PGID below is
308
+ # observation-only; all group signals are gated by this handle.
309
+ identity = _GroupIdentity.bind(process)
310
+
305
311
  assert process.stdout is not None and process.stderr is not None
306
312
  for name, pipe in (("stdout", process.stdout), ("stderr", process.stderr)):
307
313
  thread = threading.Thread(target=capture.drain, args=(name, pipe), daemon=True)
@@ -322,7 +328,7 @@ def execute_check_plan(
322
328
  # Cleanup also runs after a normal parent exit: descendants are not allowed
323
329
  # to outlive the CheckPlan or keep captured pipes open.
324
330
  try:
325
- _terminate_and_reap_group(process)
331
+ _terminate_and_reap_group(process, identity)
326
332
  except (ExecutionError, OSError) as exc:
327
333
  cleanup_error = str(exc)
328
334
  for thread in threads:
@@ -407,65 +413,222 @@ class _BoundedCapture:
407
413
  )
408
414
 
409
415
 
410
- def _terminate_and_reap_group(process: subprocess.Popen[bytes]) -> None:
411
- """Terminate descendants before reaping the leader, then verify cleanup."""
412
- pgid = process.pid
413
- # Signal before poll()/wait(): those calls reap an exited leader and release
414
- # its PID. Keeping the leader unreaped until this first group signal avoids
415
- # a fast PID reuse racing cleanup after a short-lived command.
416
+ def _group_identity_token(pid: int) -> tuple[object, ...] | None:
417
+ """Return a kernel-backed incarnation token for ``pid`` (or ``None``).
418
+
419
+ The token is *not* just the numeric PID: it also binds the process start
420
+ time and its process group, so a recycled PID can never reproduce the same
421
+ token. This is the portable equivalent of a Linux pidfd identity handle.
422
+
423
+ Platform landing points:
424
+ * Linux: ``/proc/<pid>/stat`` starttime (field 22) + pgrp (field 5).
425
+ * macOS: libproc ``proc_pidinfo(PROC_PIDTBSDINFO)`` start time + pgid.
426
+ * Other POSIX: ``None`` -> the caller fails closed (never sends a group
427
+ signal it cannot bind to a verified incarnation).
428
+ """
429
+ if sys.platform == "linux":
430
+ try:
431
+ with open(f"/proc/{pid}/stat", "r", encoding="ascii") as handle:
432
+ stat = handle.read()
433
+ # comm may contain spaces/parentheses; everything after the last ')'
434
+ # begins at field 3 (state). pgrp=field5 -> index 2,
435
+ # starttime=field22 -> index 19 relative to field 3.
436
+ fields = stat[stat.rindex(")") + 2:].split()
437
+ pgrp = int(fields[2])
438
+ starttime = int(fields[19])
439
+ return ("linux", pid, starttime, pgrp)
440
+ except (OSError, ValueError, IndexError):
441
+ return None
442
+ if sys.platform == "darwin":
443
+ try:
444
+ import ctypes
445
+ import ctypes.util
446
+
447
+ class _ProcBsdInfo(ctypes.Structure):
448
+ _fields_ = [
449
+ ("pbi_flags", ctypes.c_uint32),
450
+ ("pbi_status", ctypes.c_uint32),
451
+ ("pbi_xstatus", ctypes.c_uint32),
452
+ ("pbi_pid", ctypes.c_uint32),
453
+ ("pbi_ppid", ctypes.c_uint32),
454
+ ("pbi_uid", ctypes.c_uint32),
455
+ ("pbi_gid", ctypes.c_uint32),
456
+ ("pbi_ruid", ctypes.c_uint32),
457
+ ("pbi_rgid", ctypes.c_uint32),
458
+ ("pbi_svuid", ctypes.c_uint32),
459
+ ("pbi_svgid", ctypes.c_uint32),
460
+ ("rfu_1", ctypes.c_uint32),
461
+ ("pbi_comm", ctypes.c_char * 16),
462
+ ("pbi_name", ctypes.c_char * 32),
463
+ ("pbi_nfiles", ctypes.c_uint32),
464
+ ("pbi_pgid", ctypes.c_uint32),
465
+ ("pbi_pjobc", ctypes.c_uint32),
466
+ ("e_tdev", ctypes.c_uint32),
467
+ ("e_tpgid", ctypes.c_uint32),
468
+ ("pbi_nice", ctypes.c_int32),
469
+ ("pbi_start_tvsec", ctypes.c_uint64),
470
+ ("pbi_start_tvusec", ctypes.c_uint64),
471
+ ]
472
+
473
+ name = ctypes.util.find_library("proc") or "/usr/lib/libproc.dylib"
474
+ libproc = ctypes.CDLL(name)
475
+ libproc.proc_pidinfo.argtypes = [
476
+ ctypes.c_int, ctypes.c_int, ctypes.c_uint64,
477
+ ctypes.c_void_p, ctypes.c_int,
478
+ ]
479
+ libproc.proc_pidinfo.restype = ctypes.c_int
480
+ info = _ProcBsdInfo()
481
+ read = libproc.proc_pidinfo(
482
+ pid, 3, 0, ctypes.byref(info), ctypes.sizeof(info) # 3 = PROC_PIDTBSDINFO
483
+ )
484
+ if read <= 0 or info.pbi_pid != pid:
485
+ return None
486
+ return (
487
+ "darwin", info.pbi_pid, info.pbi_start_tvsec,
488
+ info.pbi_start_tvusec, info.pbi_pgid,
489
+ )
490
+ except (OSError, ValueError, AttributeError):
491
+ return None
492
+ return None
493
+
494
+
495
+ class _GroupIdentity:
496
+ """Kernel-backed identity binding for a spawned process group.
497
+
498
+ The numeric PGID is retained only for observation / diagnostics. Sending a
499
+ group signal is allowed only while ``matches()`` confirms the bound
500
+ incarnation still owns that PGID; otherwise the caller fails closed.
501
+ """
502
+
503
+ def __init__(self, pid: int, pgid: int, token: tuple[object, ...] | None, pidfd: object | None) -> None:
504
+ self.pid = pid
505
+ self.pgid = pgid
506
+ self._token = token
507
+ self._pidfd = pidfd
508
+
509
+ @classmethod
510
+ def bind(cls, process: subprocess.Popen[bytes]) -> "_GroupIdentity":
511
+ """Capture the incarnation identity at creation time, before any reap."""
512
+ pid = process.pid
513
+ token = _group_identity_token(pid)
514
+ pidfd = None
515
+ if sys.platform == "linux":
516
+ try:
517
+ pidfd = os.pidfd_open(pid) # type: ignore[attr-defined]
518
+ except (OSError, AttributeError):
519
+ pidfd = None
520
+ return cls(pid, pid, token, pidfd)
521
+
522
+ def matches(self) -> bool:
523
+ """True only if the bound incarnation still owns the numeric PGID."""
524
+ if self._token is None:
525
+ return False
526
+ current = _group_identity_token(self.pid)
527
+ return current is not None and current == self._token
528
+
529
+ def close(self) -> None:
530
+ if self._pidfd is not None:
531
+ try:
532
+ os.close(self._pidfd) # type: ignore[arg-type]
533
+ except OSError:
534
+ pass
535
+ self._pidfd = None
536
+
537
+
538
+ def _terminate_and_reap_group(
539
+ process: subprocess.Popen[bytes], identity: _GroupIdentity
540
+ ) -> None:
541
+ """Terminate descendants before reaping the leader, then verify cleanup.
542
+
543
+ Every group signal is gated by ``identity.matches()``: the numeric PGID is
544
+ observation-only and is never used as a send credential on its own.
545
+ """
546
+ pgid = identity.pgid
547
+
548
+ def send(sig: int) -> None:
549
+ """Send one group signal only after proving the group identity.
550
+
551
+ Fails closed with ``ExecutionOutcomeUnknown`` when identity cannot be
552
+ proven but the group still appears alive (never signals an unverified
553
+ or possibly-reused group). A gone group is a no-op. OS errors from
554
+ the actual ``killpg`` propagate to the caller's typed handlers below.
555
+ """
556
+ if not identity.matches():
557
+ # Observation only: signal 0 delivers nothing. If the group is
558
+ # already gone there is nothing to clean up; if it is still alive
559
+ # we must not send unverified signals to it.
560
+ try:
561
+ os.killpg(pgid, 0)
562
+ except OSError:
563
+ return
564
+ raise ExecutionOutcomeUnknown(
565
+ f"process group identity for {pgid} could not be confirmed; "
566
+ f"refusing to send signal {sig}",
567
+ _unknown_observation(process),
568
+ )
569
+ os.killpg(pgid, sig)
570
+
416
571
  try:
417
- os.killpg(pgid, signal.SIGTERM)
418
- except (ProcessLookupError, PermissionError):
419
- pass
420
- except OSError as exc:
421
- raise ExecutionOutcomeUnknown(
422
- f"could not signal process group {pgid}: {exc}", _unknown_observation(process)
423
- ) from exc
424
-
425
- # Do not reap the leader before the last group signal. Its PID is also the
426
- # process-group ID; after wait() another process could reuse that ID and a
427
- # late killpg(SIGKILL) would target an unrelated group.
428
- if not _wait_group_gone(pgid, _TERM_GRACE_SECONDS):
572
+ # Signal before poll()/wait(): those calls reap an exited leader and
573
+ # release its PID. Keeping the leader unreaped until this first
574
+ # identity-checked group signal avoids a fast PID reuse racing cleanup.
429
575
  try:
430
- os.killpg(pgid, signal.SIGKILL)
431
- except ProcessLookupError:
576
+ send(signal.SIGTERM)
577
+ except (ProcessLookupError, PermissionError):
432
578
  pass
433
- except PermissionError as exc:
434
- # On POSIX hosts a terminated group leader may remain as a zombie
435
- # until its parent reaps it. Some kernels report EPERM for both
436
- # killpg(0) and SIGKILL while that zombie is the only group member.
437
- # Reap the leader, then only observe the numeric PGID: never signal
438
- # it again after reaping, since the identifier could be reused.
579
+ except OSError as exc:
580
+ raise ExecutionOutcomeUnknown(
581
+ f"could not signal process group {pgid}: {exc}",
582
+ _unknown_observation(process),
583
+ ) from exc
584
+
585
+ # Do not reap the leader before the last group signal. Its PID is also
586
+ # the process-group ID; after wait() another process could reuse that
587
+ # ID, so every send re-proves the bound identity first.
588
+ if not _wait_group_gone(pgid, _TERM_GRACE_SECONDS):
439
589
  try:
440
- process.wait(timeout=_KILL_VERIFY_SECONDS)
441
- except subprocess.TimeoutExpired as wait_exc:
442
- raise ExecutionOutcomeUnknown(
443
- f"process leader {process.pid} could not be reaped",
444
- _unknown_observation(process),
445
- ) from wait_exc
446
- if not _wait_group_gone(pgid, _KILL_VERIFY_SECONDS):
590
+ send(signal.SIGKILL)
591
+ except ProcessLookupError:
592
+ pass
593
+ except PermissionError as exc:
594
+ # On POSIX hosts a terminated group leader may remain as a
595
+ # zombie until its parent reaps it. Some kernels report EPERM
596
+ # for both killpg(0) and SIGKILL while that zombie is the only
597
+ # group member. Reap the leader, then only observe the numeric
598
+ # PGID: never signal it again after reaping, since the
599
+ # identifier could be reused.
600
+ try:
601
+ process.wait(timeout=_KILL_VERIFY_SECONDS)
602
+ except subprocess.TimeoutExpired as wait_exc:
603
+ raise ExecutionOutcomeUnknown(
604
+ f"process leader {process.pid} could not be reaped",
605
+ _unknown_observation(process),
606
+ ) from wait_exc
607
+ if not _wait_group_gone(pgid, _KILL_VERIFY_SECONDS):
608
+ raise ExecutionOutcomeUnknown(
609
+ f"process group {pgid} remains after SIGKILL was denied: {exc}",
610
+ _unknown_observation(process),
611
+ ) from exc
612
+ return
613
+ except OSError as exc:
447
614
  raise ExecutionOutcomeUnknown(
448
- f"process group {pgid} remains after SIGKILL was denied: {exc}",
615
+ f"could not force-kill process group {pgid}: {exc}",
449
616
  _unknown_observation(process),
450
617
  ) from exc
451
- return
452
- except OSError as exc:
618
+ try:
619
+ process.wait(timeout=_KILL_VERIFY_SECONDS)
620
+ except subprocess.TimeoutExpired as exc:
453
621
  raise ExecutionOutcomeUnknown(
454
- f"could not force-kill process group {pgid}: {exc}",
622
+ f"process leader {process.pid} could not be reaped",
455
623
  _unknown_observation(process),
456
624
  ) from exc
457
- try:
458
- process.wait(timeout=_KILL_VERIFY_SECONDS)
459
- except subprocess.TimeoutExpired as exc:
460
- raise ExecutionOutcomeUnknown(
461
- f"process leader {process.pid} could not be reaped",
462
- _unknown_observation(process),
463
- ) from exc
464
- if not _wait_group_gone(pgid, _KILL_VERIFY_SECONDS):
465
- raise ExecutionOutcomeUnknown(
466
- f"process group {pgid} remains after termination",
467
- _unknown_observation(process),
468
- )
625
+ if not _wait_group_gone(pgid, _KILL_VERIFY_SECONDS):
626
+ raise ExecutionOutcomeUnknown(
627
+ f"process group {pgid} remains after termination",
628
+ _unknown_observation(process),
629
+ )
630
+ finally:
631
+ identity.close()
469
632
 
470
633
 
471
634
  def _wait_group_gone(pgid: int, timeout: float) -> bool:
@@ -515,14 +678,17 @@ def _match_target_frame(
515
678
  ) -> TargetCallEvidence | None:
516
679
  normalized_frame = frame_path.replace("\\", "/")
517
680
  for target in targets:
518
- suffix = target.module_path.replace("\\", "/").lstrip("./")
681
+ # 延迟导入:agent_targets 反向依赖本模块,顶层 import 会成环
682
+ from .agent_targets import _strip_dot_prefix
683
+ suffix = _strip_dot_prefix(target.module_path.replace("\\", "/"))
519
684
  if suffix.endswith(".py") or re.search(r"\.(?:[cm]?js|tsx?)$", suffix):
520
685
  expected = suffix
521
686
  elif "." in suffix and "/" not in suffix:
522
687
  expected = suffix.replace(".", "/") + ".py"
523
688
  else:
524
689
  expected = suffix
525
- if not normalized_frame.endswith(expected):
690
+ if not (normalized_frame == expected
691
+ or normalized_frame.endswith("/" + expected)):
526
692
  continue
527
693
  if target.function_names and function_name not in target.function_names:
528
694
  continue