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.
- package/README.md +193 -185
- package/core/README.md +2 -2
- package/core/agent/README.md +2 -1
- package/core/agent/agent_artifacts.py +8 -6
- package/core/agent/agent_eval.py +136 -54
- package/core/agent/agent_execution.py +218 -52
- package/core/agent/agent_orchestrator.py +14 -8
- package/core/agent/agent_targets.py +8 -2
- package/core/agent/feature_baseline.py +150 -0
- package/core/assets/README.md +3 -2
- package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
- package/core/assets/axe-core/LICENSE.txt +362 -0
- package/core/assets/axe-core/UPSTREAM.md +10 -0
- package/core/assets/axe-core/axe.min.js +12 -0
- package/core/assets/bugx-hero-en.svg +74 -0
- package/core/assets/bugx-hero-zh.svg +74 -0
- package/core/assets/bugx-social-preview.svg +71 -0
- package/core/assets/bugx-wechat-group.png +0 -0
- package/core/assets/codex.png +0 -0
- package/core/assets/dsh.png +0 -0
- package/core/assets/webui-chatgpt.jpg +0 -0
- package/core/assets/webui-session.jpg +0 -0
- package/core/assets/webui-skills.jpg +0 -0
- package/core/assets/webui-studio.jpg +0 -0
- package/core/assets/webui-zcode.jpg +0 -0
- package/core/assets/zcode.png +0 -0
- package/core/audit_packs/README.md +2 -0
- package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
- package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
- package/core/audit_packs/pitfalls/go_backend.json +66 -0
- package/core/audit_packs/pitfalls/java_spring.json +64 -0
- package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
- package/core/audit_packs/pitfalls/python_web.json +82 -0
- package/core/autonomous_cve/SPEC.md +1 -1
- package/core/autonomous_cve/attack_graph_store.py +152 -106
- package/core/autonomous_cve/behavior_graph.py +8 -2
- package/core/autonomous_cve/verifier.py +4 -1
- package/core/bugx.md +1 -1
- package/core/bugx_paths.py +43 -8
- package/core/cli-help.txt +66 -0
- package/core/cloud_sync/SPEC.md +1 -1
- package/core/cloud_sync/cloud_client.py +81 -11
- package/core/cloud_sync/cloud_onboard.py +42 -1
- package/core/cloud_sync/consent.py +33 -3
- package/core/cloud_sync/flywheel_client.py +186 -15
- package/core/cloud_sync/network_transport.py +24 -3
- package/core/cloud_sync/sensitive_filter.py +2 -2
- package/core/cloud_sync/sync_push.py +12 -10
- package/core/contracts/AGENT_GUIDE.md +6 -9
- package/core/contracts/README.md +2 -2
- package/core/contracts/bugx-runtime-contract.md +1 -1
- package/core/contracts/bugx-worker.md +1 -1
- package/core/contracts/engine_gap_contracts.py +86 -3
- package/core/coverage/coverage_discovery.py +599 -29
- package/core/coverage/coverage_evidence.py +47 -0
- package/core/coverage/coverage_forensics.py +9 -0
- package/core/coverage/coverage_validate.py +6 -1
- package/core/dev_harness/SPEC.md +1 -1
- package/core/engine-integrity.json +670 -442
- package/core/fuzzing/concurrency_fuzzer.py +53 -0
- package/core/fuzzing/differential_oracle.py +562 -27
- package/core/fuzzing/fuzz_input.py +109 -6
- package/core/fuzzing/stateful_fuzzer.py +72 -0
- package/core/governance/secret_redactor.py +22 -10
- package/core/host_acp/SPEC.md +1 -1
- package/core/host_acp/__init__.py +4 -4
- package/core/host_acp/claude.py +59 -1
- package/core/host_acp/cline.py +64 -1
- package/core/host_acp/codex.py +56 -1
- package/core/host_acp/dsh.py +59 -1
- package/core/host_acp/opencode.py +56 -1
- package/core/host_acp/pi.py +59 -1
- package/core/host_acp/zcode.py +59 -1
- package/core/host_runtime/SPEC.md +1 -1
- package/core/host_runtime/adapters.py +1 -1
- package/core/host_runtime/cline.py +13 -0
- package/core/host_runtime/host_evaluators.py +44 -4
- package/core/host_runtime/host_probe.py +1 -1
- package/core/host_runtime/host_provider_arbitrator.py +116 -62
- package/core/host_runtime/host_registry.py +15 -8
- package/core/host_runtime/mcp_registry_gate.py +12 -1
- package/core/host_runtime/pi.py +102 -0
- package/core/host_runtime/provider_facts.py +66 -0
- package/core/hosts/SPEC.md +1 -1
- package/core/hosts/__init__.py +6 -2
- package/core/hosts/_dsh_usage.py +1 -1
- package/core/hosts/base.py +32 -4
- package/core/hosts/claude.py +55 -0
- package/core/hosts/cline.py +6 -2
- package/core/hosts/codex.py +58 -0
- package/core/hosts/dsh.py +9 -1
- package/core/hosts/opencode.py +6 -6
- package/core/hosts/pi.py +159 -2
- package/core/infra/README.md +4 -2
- package/core/infra/__init__.py +2 -0
- package/core/infra/build_info.py +22 -3
- package/core/infra/client_metadata.py +1 -1
- package/core/infra/json_utils.py +22 -0
- package/core/launch_phases/README.md +6 -3
- package/core/launch_phases/SPEC.md +1 -1
- package/core/launch_phases/common.py +21 -2
- package/core/launch_phases/finding_confirm_phase.py +170 -5
- package/core/launch_phases/finding_settlement.py +188 -1
- package/core/launch_phases/judge_phase.py +69 -12
- package/core/launch_phases/orchestrator_controls.py +11 -7
- package/core/launch_phases/post_coverage_sync.py +9 -2
- package/core/launch_phases/post_phase.py +144 -8
- package/core/launch_phases/post_receipt.py +12 -1
- package/core/launch_phases/pre_phase.py +3 -3
- package/core/launch_phases/pre_recon_scout.py +66 -36
- package/core/launch_phases/pre_state_builder.py +23 -176
- package/core/launch_phases/report_sharing.py +3 -7
- package/core/launch_phases/round_orchestrator.py +129 -58
- package/core/launch_phases/semantic_recon.py +545 -0
- package/core/launch_phases/session_runtime.py +56 -9
- package/core/launch_phases/startup_gates.py +36 -8
- package/core/launch_phases/startup_interaction.py +68 -12
- package/core/launch_phases/startup_version_gate.py +13 -3
- package/core/launch_phases/supervisor_bridge.py +46 -17
- package/core/launch_phases/supervisor_coverage.py +8 -2
- package/core/launch_phases/supervisor_degraded.py +1 -9
- package/core/launch_phases/verify_loop.py +767 -0
- package/core/launch_phases/worker_barriers.py +15 -5
- package/core/launch_phases/worker_orchestrator.py +105 -25
- package/core/launch_phases/worker_prior.py +115 -0
- package/core/ledger/README.md +2 -1
- package/core/ledger/SPEC.md +1 -1
- package/core/ledger/_facade.py +2 -1
- package/core/ledger/archive_ops.py +60 -2
- package/core/ledger/cli.py +6 -1
- package/core/ledger/export_ops.py +6 -1
- package/core/ledger/finding_confirmation.py +48 -6
- package/core/ledger/finding_lifecycle.py +428 -5
- package/core/ledger/finding_verification.py +555 -10
- package/core/ledger/fp_ledger.py +255 -0
- package/core/ledger/incidents.py +10 -4
- package/core/ledger/patterns.py +10 -7
- package/core/ledger/receipt_contract.py +17 -1
- package/core/ledger/sync_ops.py +21 -16
- package/core/ledger/tool_experience.py +2 -1
- package/core/ledger/verify_life.py +88 -17
- package/core/locales/en-US.json +2 -2
- package/core/locales/zh-CN.json +2 -2
- package/core/mcp_handlers/SPEC.md +1 -1
- package/core/mcp_handlers/base.py +23 -3
- package/core/mcp_handlers/channel_lifecycle.py +85 -30
- package/core/mcp_handlers/retrieval_handlers.py +11 -1
- package/core/mcp_handlers/rpc_server.py +6 -1
- package/core/mcp_handlers/supervisor_handlers.py +32 -6
- package/core/mcp_handlers/tool_table.py +15 -0
- package/core/mcp_runtime_support/environment.py +0 -38
- package/core/mcp_runtime_support/verifier.py +0 -52
- package/core/metadata.txt +2 -3
- package/core/planning/README.md +2 -1
- package/core/planning/domain_router.py +4 -2
- package/core/planning/dynamic_flow_analyzer.py +219 -14
- package/core/planning/judge_pipeline.py +87 -4
- package/core/planning/prompt_harness.py +57 -15
- package/core/planning/prompt_policy_engine.py +386 -0
- package/core/planning/spec_harvester.py +4 -4
- package/core/probes/INTERFACE.md +11 -1
- package/core/probes/SPEC.md +11 -1
- package/core/probes/__init__.py +46 -40
- package/core/probes/android_probe.py +177 -9
- package/core/probes/codebase_memory_probe.py +57 -0
- package/core/probes/desktop_probe.py +104 -0
- package/core/probes/differential_probe.py +99 -21
- package/core/probes/efficiency_probe.py +64 -0
- package/core/probes/ios_binary_probe.py +105 -1
- package/core/probes/memory_probe.py +66 -0
- package/core/probes/miniprogram_probe.py +75 -13
- package/core/probes/mobile_probe.py +215 -30
- package/core/probes/native_probe.py +88 -0
- package/core/probes/openwiki_probe.py +70 -0
- package/core/probes/pattern_probe.py +106 -0
- package/core/probes/platform_probe.py +81 -0
- package/core/probes/probe_registry.py +108 -7
- package/core/probes/sast_fixture_corpus.py +340 -0
- package/core/probes/sast_probe.py +553 -52
- package/core/probes/sast_rules.py +668 -28
- package/core/probes/sca_scanner.py +48 -0
- package/core/probes/ui_accessibility.py +149 -0
- package/core/probes/ui_audit.py +513 -0
- package/core/probes/ui_contract.py +273 -0
- package/core/probes/ui_evidence.py +212 -0
- package/core/probes/ui_measurements.py +314 -0
- package/core/probes/ui_repair.py +250 -0
- package/core/probes/ui_review.py +133 -0
- package/core/probes/ui_storybook.py +107 -0
- package/core/probes/ui_tokens.py +185 -0
- package/core/probes/ui_visual_diff.py +131 -0
- package/core/probes/web_probe.py +373 -18
- package/core/project_profiler/SPEC.md +1 -1
- package/core/project_profiler/arbitrator.py +6 -1
- package/core/project_profiler/detector.py +8 -1
- package/core/project_profiler/strategy.py +51 -15
- package/core/prompts/README.md +4 -2
- package/core/prompts/command_routing_en.md +2 -2
- package/core/prompts/command_routing_zh.md +2 -2
- package/core/prompts/policies/prompt_policies.json +101 -0
- package/core/prompts/stages/stage_repair.md +1 -1
- package/core/prompts/stages/stage_verify.defensive.md +42 -0
- package/core/prompts/stages/stage_verify.md +44 -0
- package/core/repair/README.md +1 -1
- package/core/repair/l7_repair_loop.py +1 -4
- package/core/repair/rsi_fixer.py +4 -4
- package/core/repair/rsi_loop.py +1 -3
- package/core/repair/rsi_repair.py +7 -7
- package/core/repair/rsi_scope.py +27 -8
- package/core/report_engine/SPEC.md +1 -1
- package/core/report_engine/attestation.py +8 -4
- package/core/report_engine/finding_report.py +2 -1
- package/core/report_engine/models.py +7 -9
- package/core/report_engine/report_share.py +0 -8
- package/core/report_engine/sast_bridge.py +2 -2
- package/core/report_engine/server.py +18 -8
- package/core/report_engine/web-conformance.md +123 -18
- package/core/report_engine/web_conformance.py +21 -52
- package/core/retrieval/README.md +2 -1
- package/core/retrieval/SPEC.md +1 -1
- package/core/retrieval/code_analyzer.py +50 -14
- package/core/retrieval/context_assembler.py +7 -1
- package/core/retrieval/knowledge_sync.py +108 -14
- package/core/retrieval/pitfall_packs.py +277 -0
- package/core/retrieval/symbol_index.py +25 -6
- package/core/retrieval/universal_code_matcher.py +234 -49
- package/core/runtime/README.md +1 -1
- package/core/runtime/bugx_logging.py +78 -7
- package/core/runtime/fixture_solidify.py +5 -10
- package/core/runtime/global_telemetry.py +20 -0
- package/core/runtime/incident_eval.py +1 -1
- package/core/runtime/model_runner.py +4 -41
- package/core/runtime/platform_adapter.py +2 -2
- package/core/runtime/prep_validate.py +4 -2
- package/core/runtime/project_settings.py +2 -1
- package/core/runtime/scenario_eval.py +50 -8
- package/core/skills/bugx_docs_mcp_server.py +3 -1
- package/core/skills/bugx_mcp_server.py +29 -2
- package/core/skills/tools_kb.py +1 -1
- package/core/supervisor/README.md +1 -1
- package/core/supervisor/SPEC.md +1 -1
- package/core/supervisor/budget_governor.py +503 -9
- package/core/supervisor/checkpoint_pipeline.py +248 -6
- package/core/supervisor/checkpoint_sync.py +13 -0
- package/core/supervisor/claim_events.py +1 -1
- package/core/supervisor/finding_workflow.py +22 -5
- package/core/supervisor/lease_manager.py +1 -1
- package/core/supervisor/lifecycle_blocks.py +6 -1
- package/core/supervisor/rejection_remedies.py +52 -5
- package/core/supervisor/serial_authorization.py +48 -4
- package/core/supervisor/task_scheduler.py +2 -2
- package/core/supervisor/worker_checkpoint.py +8 -1
- package/core/supervisor/worker_runtime.py +8 -2
- package/core/supervisor_types/worker_claim.py +9 -0
- package/core/webui/README.md +1 -1
- package/core/webui/SPEC.md +2 -1
- package/core/webui/adapters/claude.py +5 -1
- package/core/webui/adapters/cline.py +10 -2
- package/core/webui/adapters/codex.py +5 -1
- package/core/webui/adapters/dsh.py +5 -1
- package/core/webui/docs_session_service.py +2 -2
- package/core/webui/mcp_inspector.py +11 -7
- package/core/webui/static/00-base.css +1060 -0
- package/core/webui/static/01-monitoring.css +802 -0
- package/core/webui/static/02-header-actions.css +321 -0
- package/core/webui/static/03-trigger-popover.css +697 -0
- package/core/webui/static/04-composer.css +628 -0
- package/core/webui/static/05-skills-center.css +878 -0
- package/core/webui/static/06-mcp-center.css +623 -0
- package/core/webui/static/07-skill-detail.css +265 -0
- package/core/webui/static/08-files-management.css +167 -0
- package/core/webui/static/09-files-center.css +386 -0
- package/core/webui/static/10-icons.css +105 -0
- package/core/webui/static/11-project-options.css +185 -0
- package/core/webui/static/12-profile-tab.css +383 -0
- package/core/webui/static/design-tokens.css +113 -0
- package/core/webui/static/index.html +14 -1
- package/core/webui/workspace_service.py +1 -1
- package/docs/07_distribution/01_README_NPM.md +193 -185
- package/ecosystem/integrations/README.md +1 -1
- package/ecosystem/integrations/dsh/mcp/package.json +1 -1
- package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/integrations/dsh/ui/package.json +1 -1
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
- package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
- package/ecosystem/integrations/opencode/opencode.json +23 -12
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
- package/ecosystem/integrations/qoder/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
- package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
- package/interfaces/bin/bugx.js +37 -0
- package/interfaces/cli/bugx_cli/__init__.py +4 -2
- package/interfaces/cli/bugx_cli/cli.py +172 -69
- package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
- package/interfaces/cli/bugx_cli/commands/agent.py +461 -134
- package/interfaces/cli/bugx_cli/commands/audit.py +10 -9
- package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
- package/interfaces/cli/bugx_cli/commands/cloud.py +31 -22
- package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
- package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
- package/interfaces/cli/bugx_cli/commands/knowledge.py +5 -4
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
- package/interfaces/cli/bugx_cli/commands/plugin.py +58 -23
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
- package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
- package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
- package/interfaces/cli/bugx_cli/commands/project.py +6 -13
- package/interfaces/cli/bugx_cli/commands/report.py +2 -6
- package/interfaces/cli/bugx_cli/commands/system.py +524 -169
- package/interfaces/cli/bugx_cli/common.py +21 -15
- package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
- package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
- package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +35 -16
- package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
- package/interfaces/cli/bugx_cli/infra/security.py +13 -6
- package/package.json +30 -15
- package/pyproject.toml +60 -9
- package/scripts/ensure-python.mjs +7 -7
- package/scripts/sync-version.mjs +10 -21
- package/scripts/test-npm-wrapper.mjs +1 -1
- package/core/assets/bugx-hero-cn.png +0 -0
- package/core/assets/bugx-hero-en.png +0 -0
- package/core/webui/static/project-settings.css +0 -6458
- package/docs/07_distribution/README.md +0 -16
- package/docs/README.md +0 -121
- package/interfaces/README.md +0 -143
- package/interfaces/bin/README.md +0 -35
- package/interfaces/cli/README.md +0 -90
- package/scripts/README.md +0 -118
package/core/agent/agent_eval.py
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
411
|
-
"""
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
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
|
-
|
|
418
|
-
|
|
419
|
-
|
|
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
|
-
|
|
431
|
-
except ProcessLookupError:
|
|
576
|
+
send(signal.SIGTERM)
|
|
577
|
+
except (ProcessLookupError, PermissionError):
|
|
432
578
|
pass
|
|
433
|
-
except
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
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
|
-
|
|
441
|
-
except
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
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}
|
|
615
|
+
f"could not force-kill process group {pgid}: {exc}",
|
|
449
616
|
_unknown_observation(process),
|
|
450
617
|
) from exc
|
|
451
|
-
|
|
452
|
-
|
|
618
|
+
try:
|
|
619
|
+
process.wait(timeout=_KILL_VERIFY_SECONDS)
|
|
620
|
+
except subprocess.TimeoutExpired as exc:
|
|
453
621
|
raise ExecutionOutcomeUnknown(
|
|
454
|
-
f"
|
|
622
|
+
f"process leader {process.pid} could not be reaped",
|
|
455
623
|
_unknown_observation(process),
|
|
456
624
|
) from exc
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
)
|
|
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
|
-
|
|
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
|
|
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
|