dasv 1.0.0__py3-none-any.whl

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 (65) hide show
  1. dasv/__init__.py +7 -0
  2. dasv/adapters/__init__.py +1 -0
  3. dasv/adapters/base.py +51 -0
  4. dasv/adapters/harbor.py +204 -0
  5. dasv/adapters/hud.py +182 -0
  6. dasv/adapters/native.py +137 -0
  7. dasv/adapters/openenv.py +223 -0
  8. dasv/adapters/registry.py +81 -0
  9. dasv/adapters/verifiers_v1.py +323 -0
  10. dasv/cli/__init__.py +1 -0
  11. dasv/cli/app.py +1407 -0
  12. dasv/core/__init__.py +1 -0
  13. dasv/core/budget.py +211 -0
  14. dasv/core/config.py +80 -0
  15. dasv/core/errors.py +57 -0
  16. dasv/core/manifest.py +97 -0
  17. dasv/core/orchestrator.py +579 -0
  18. dasv/core/schemas.py +139 -0
  19. dasv/drift/__init__.py +33 -0
  20. dasv/drift/logprob_drift.py +236 -0
  21. dasv/drift/recipe_config.py +105 -0
  22. dasv/export/__init__.py +44 -0
  23. dasv/export/common.py +153 -0
  24. dasv/export/openenv.py +179 -0
  25. dasv/export/prime_rl.py +109 -0
  26. dasv/export/trl.py +169 -0
  27. dasv/export/verl.py +95 -0
  28. dasv/mutate/__init__.py +39 -0
  29. dasv/mutate/anti_patches.py +418 -0
  30. dasv/mutate/impossible_bench.py +279 -0
  31. dasv/mutate/runner.py +237 -0
  32. dasv/profile/__init__.py +72 -0
  33. dasv/profile/signal_profiler.py +692 -0
  34. dasv/profile/stats.py +178 -0
  35. dasv/py.typed +0 -0
  36. dasv/redteam/__init__.py +56 -0
  37. dasv/redteam/fencing.py +47 -0
  38. dasv/redteam/fixer_agent.py +151 -0
  39. dasv/redteam/hacker_agent.py +469 -0
  40. dasv/redteam/llm_client.py +341 -0
  41. dasv/redteam/runner.py +348 -0
  42. dasv/reporting/__init__.py +16 -0
  43. dasv/reporting/html_renderer.py +186 -0
  44. dasv/reporting/json_writer.py +21 -0
  45. dasv/reporting/sarif_writer.py +137 -0
  46. dasv/reporting/templates/report.html.j2 +429 -0
  47. dasv/rubric/__init__.py +81 -0
  48. dasv/rubric/divergence.py +513 -0
  49. dasv/rubric/perturbations.py +370 -0
  50. dasv/rubric/prorubric_audit.py +858 -0
  51. dasv/sandbox/__init__.py +54 -0
  52. dasv/sandbox/docker_provider.py +517 -0
  53. dasv/sandbox/janitor.py +321 -0
  54. dasv/sandbox/probes.py +738 -0
  55. dasv/sandbox/provider.py +153 -0
  56. dasv/verifier/__init__.py +61 -0
  57. dasv/verifier/artifact_extractor.py +360 -0
  58. dasv/verifier/clean_grader.py +586 -0
  59. dasv/verifier/determinism.py +322 -0
  60. dasv/verifier/gold_sanity.py +252 -0
  61. dasv-1.0.0.dist-info/METADATA +219 -0
  62. dasv-1.0.0.dist-info/RECORD +65 -0
  63. dasv-1.0.0.dist-info/WHEEL +4 -0
  64. dasv-1.0.0.dist-info/entry_points.txt +8 -0
  65. dasv-1.0.0.dist-info/licenses/LICENSE +198 -0
dasv/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Deterministic Adversarial Sandbox Verifier (`dasv`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "1.0.0"
6
+
7
+ __all__ = ["__version__"]
@@ -0,0 +1 @@
1
+ """Cross-standard RL environment adapters (SDD-03)."""
dasv/adapters/base.py ADDED
@@ -0,0 +1,51 @@
1
+ """Adapter capability metadata and `EnvironmentAdapter` protocol (SDD-03)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any, Protocol
7
+
8
+ from pydantic import BaseModel
9
+
10
+ from dasv.core.schemas import AuditFinding, EnvSpec, EnvStandard
11
+
12
+
13
+ class AdapterCapabilities(BaseModel):
14
+ supports_clean_image_grading: bool = True
15
+ supports_interactive_reset: bool = False
16
+ supports_rubric_introspection: bool = False
17
+ native_cli_binary: str | None = None
18
+
19
+
20
+ class EnvironmentAdapter(Protocol):
21
+ standard: EnvStandard
22
+ capabilities: AdapterCapabilities
23
+
24
+ def detect(self, path: Path) -> bool:
25
+ """Fast (< 10 ms) deterministic detection; never executes untrusted code."""
26
+ ...
27
+
28
+ def load(self, path: Path) -> EnvSpec:
29
+ """Parse manifest/config into canonical EnvSpec with zero side effects."""
30
+ ...
31
+
32
+ def static_findings(self, spec: EnvSpec) -> list[AuditFinding]:
33
+ """Return adapter-specific Tier 0 static findings (e.g., legacy v0 deprecation)."""
34
+ ...
35
+
36
+ async def run_native_check(
37
+ self,
38
+ spec: EnvSpec,
39
+ timeout_sec: float = 60.0,
40
+ require_native: bool = False,
41
+ ) -> list[AuditFinding]:
42
+ """Delegate baseline checks to the native CLI if installed."""
43
+ ...
44
+
45
+ async def run_oracle(self, spec: EnvSpec, sandbox: Any) -> tuple[float, dict[str, Any]]:
46
+ """Execute canonical Oracle solution (Stage 6 Tier 1 runtime)."""
47
+ ...
48
+
49
+ async def run_noop(self, spec: EnvSpec, sandbox: Any) -> tuple[float, dict[str, Any]]:
50
+ """Execute canonical No-op baseline (Stage 6 Tier 1 runtime)."""
51
+ ...
@@ -0,0 +1,204 @@
1
+ """Harbor (`task.toml` / `instruction.md`) environment adapter (FEAT-01, SDD-03)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import tomllib
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from dasv.adapters.base import AdapterCapabilities
11
+ from dasv.adapters.native import NativeDelegateRunner
12
+ from dasv.core.errors import ConfigError, RuntimeSandboxError
13
+ from dasv.core.schemas import AuditFinding, EnvSpec, EnvStandard
14
+ from dasv.verifier.clean_grader import coerce_grading_context, outcome_to_details
15
+
16
+ _FROM_RE = re.compile(r"^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)", re.IGNORECASE)
17
+
18
+
19
+ def _extract_first_from_image(dockerfile: Path) -> str | None:
20
+ if not dockerfile.is_file():
21
+ return None
22
+ for line in dockerfile.read_text(encoding="utf-8", errors="replace").splitlines():
23
+ match = _FROM_RE.match(line)
24
+ if match:
25
+ return match.group(1)
26
+ return None
27
+
28
+
29
+ class HarborAdapter:
30
+ standard: EnvStandard = EnvStandard.HARBOR
31
+ capabilities: AdapterCapabilities = AdapterCapabilities(
32
+ supports_clean_image_grading=True,
33
+ supports_interactive_reset=False,
34
+ supports_rubric_introspection=False,
35
+ native_cli_binary="harbor",
36
+ )
37
+
38
+ def __init__(self, native_runner: NativeDelegateRunner | None = None) -> None:
39
+ self._native = native_runner or NativeDelegateRunner()
40
+
41
+ def detect(self, path: Path) -> bool:
42
+ if not path.is_dir():
43
+ return False
44
+ return (path / "task.toml").is_file() and (path / "instruction.md").is_file()
45
+
46
+ def load(self, path: Path) -> EnvSpec:
47
+ if not self.detect(path):
48
+ raise ConfigError(
49
+ f"Path '{path}' is not a valid Harbor task directory "
50
+ "(requires task.toml and instruction.md)."
51
+ )
52
+
53
+ task_toml_path = path / "task.toml"
54
+ try:
55
+ raw: dict[str, Any] = tomllib.loads(task_toml_path.read_text(encoding="utf-8"))
56
+ except (OSError, tomllib.TOMLDecodeError) as exc:
57
+ raise ConfigError(f"Malformed Harbor task.toml at '{task_toml_path}': {exc}") from exc
58
+
59
+ instruction_text = (path / "instruction.md").read_text(encoding="utf-8")
60
+
61
+ metadata_tbl: dict[str, Any] = (
62
+ raw.get("metadata", {}) if isinstance(raw.get("metadata"), dict) else {}
63
+ )
64
+ env_tbl: dict[str, Any] = (
65
+ raw.get("environment", {}) if isinstance(raw.get("environment"), dict) else {}
66
+ )
67
+ verifier_tbl: dict[str, Any] = (
68
+ raw.get("verifier", {}) if isinstance(raw.get("verifier"), dict) else {}
69
+ )
70
+ solution_tbl: dict[str, Any] = (
71
+ raw.get("solution", {}) if isinstance(raw.get("solution"), dict) else {}
72
+ )
73
+
74
+ task_id = str(metadata_tbl.get("name") or path.resolve().name)
75
+
76
+ oracle_entrypoint: str | None = None
77
+ configured_oracle = solution_tbl.get("entrypoint")
78
+ if isinstance(configured_oracle, str) and configured_oracle.strip():
79
+ oracle_entrypoint = configured_oracle.strip()
80
+ elif (path / "solution" / "solve.sh").is_file():
81
+ oracle_entrypoint = "solution/solve.sh"
82
+ has_oracle = oracle_entrypoint is not None and (path / oracle_entrypoint).exists()
83
+
84
+ verifier_paths: list[str] = ["tests/", "tests/test.sh"]
85
+ extra_verifier = verifier_tbl.get("test_path") or verifier_tbl.get("entrypoint")
86
+ if isinstance(extra_verifier, str) and extra_verifier not in verifier_paths:
87
+ verifier_paths.append(extra_verifier)
88
+
89
+ dockerfile = path / "environment" / "Dockerfile"
90
+ if not dockerfile.is_file():
91
+ dockerfile = path / "Dockerfile"
92
+
93
+ explicit_image = (
94
+ str(env_tbl["image"]).strip()
95
+ if isinstance(env_tbl.get("image"), str) and env_tbl["image"].strip()
96
+ else None
97
+ )
98
+ docker_image = (
99
+ str(env_tbl["docker_image"]).strip()
100
+ if isinstance(env_tbl.get("docker_image"), str) and env_tbl["docker_image"].strip()
101
+ else None
102
+ )
103
+ image_ref: str | None = explicit_image
104
+ if image_ref is None:
105
+ image_ref = _extract_first_from_image(dockerfile)
106
+ if image_ref is None:
107
+ image_ref = docker_image
108
+
109
+ image_digest: str | None = None
110
+ if image_ref and "@sha256:" in image_ref:
111
+ image_digest = "sha256:" + image_ref.split("@sha256:", 1)[1]
112
+
113
+ dockerfile_rel: str | None = None
114
+ if dockerfile.is_file():
115
+ dockerfile_rel = dockerfile.relative_to(path).as_posix()
116
+
117
+ raw_allow_internet = env_tbl.get("allow_internet")
118
+ allow_internet: bool | None = (
119
+ raw_allow_internet if isinstance(raw_allow_internet, bool) else None
120
+ )
121
+ raw_network_mode = env_tbl.get("network_mode")
122
+ if raw_network_mode is None and allow_internet is not None:
123
+ resolved_network_mode: Any = "no-network" if not allow_internet else "allow-internet"
124
+ else:
125
+ resolved_network_mode = raw_network_mode
126
+
127
+ spec_metadata: dict[str, Any] = {
128
+ "harbor_config": raw,
129
+ "network_mode": resolved_network_mode,
130
+ "allow_internet": allow_internet,
131
+ "docker_image": docker_image,
132
+ "base_commit": metadata_tbl.get("base_commit") or env_tbl.get("base_commit"),
133
+ "image_explicit": explicit_image is not None,
134
+ "dockerfile_path": dockerfile_rel,
135
+ }
136
+
137
+ return EnvSpec(
138
+ task_id=task_id,
139
+ standard=EnvStandard.HARBOR,
140
+ root_path=path.resolve(),
141
+ instruction_text=instruction_text,
142
+ image_ref=image_ref,
143
+ image_digest=image_digest,
144
+ has_oracle=has_oracle,
145
+ oracle_entrypoint=oracle_entrypoint,
146
+ verifier_paths=verifier_paths,
147
+ rubric_type="deterministic",
148
+ metadata=spec_metadata,
149
+ )
150
+
151
+ def static_findings(self, spec: EnvSpec) -> list[AuditFinding]:
152
+ return []
153
+
154
+ async def run_native_check(
155
+ self,
156
+ spec: EnvSpec,
157
+ timeout_sec: float = 60.0,
158
+ require_native: bool = False,
159
+ ) -> list[AuditFinding]:
160
+ # Explicitly use modern `harbor check <task-dir>` (never deprecated `harbor tasks check`)
161
+ result = await self._native.run(
162
+ "harbor",
163
+ ["check", str(spec.root_path)],
164
+ cwd=spec.root_path,
165
+ timeout_sec=timeout_sec,
166
+ require_native=require_native,
167
+ )
168
+ return result.findings
169
+
170
+ async def run_oracle(self, spec: EnvSpec, sandbox: Any) -> tuple[float, dict[str, Any]]:
171
+ if not spec.has_oracle or not spec.oracle_entrypoint:
172
+ raise RuntimeSandboxError(
173
+ f"Harbor task '{spec.task_id}' does not declare an existing oracle_entrypoint."
174
+ )
175
+ oracle_path = (spec.root_path / spec.oracle_entrypoint).resolve()
176
+ try:
177
+ oracle_path.relative_to(spec.root_path.resolve())
178
+ except ValueError as exc:
179
+ raise RuntimeSandboxError(
180
+ f"Oracle entrypoint '{spec.oracle_entrypoint}' escapes task root."
181
+ ) from exc
182
+ if not oracle_path.is_file():
183
+ raise RuntimeSandboxError(f"Oracle script not found: {oracle_path}")
184
+
185
+ ctx = coerce_grading_context(sandbox)
186
+ outcome, artifact = await ctx.grader.execute_and_grade(
187
+ spec,
188
+ ctx.run_id,
189
+ script_bytes=oracle_path.read_bytes(),
190
+ timeout_sec=ctx.timeout_sec,
191
+ workdir=ctx.workdir,
192
+ )
193
+ return outcome.reward, outcome_to_details(outcome, artifact)
194
+
195
+ async def run_noop(self, spec: EnvSpec, sandbox: Any) -> tuple[float, dict[str, Any]]:
196
+ ctx = coerce_grading_context(sandbox)
197
+ outcome, artifact = await ctx.grader.execute_and_grade(
198
+ spec,
199
+ ctx.run_id,
200
+ agent_cmd=["true"],
201
+ timeout_sec=ctx.timeout_sec,
202
+ workdir=ctx.workdir,
203
+ )
204
+ return outcome.reward, outcome_to_details(outcome, artifact)
dasv/adapters/hud.py ADDED
@@ -0,0 +1,182 @@
1
+ """HUD (`hud-python` MCP tasks & `tasks.grade`) plugin adapter (FEAT-04, SDD-03)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from pathlib import Path
7
+ from typing import Any, cast
8
+
9
+ from dasv.adapters.base import AdapterCapabilities
10
+ from dasv.adapters.native import NativeDelegateRunner
11
+ from dasv.core.errors import ConfigError, RuntimeSandboxError
12
+ from dasv.core.schemas import AuditFinding, EnvSpec, EnvStandard
13
+ from dasv.verifier.clean_grader import coerce_grading_context, outcome_to_details
14
+
15
+
16
+ def _pyproject_mentions_hud(path: Path) -> tuple[bool, dict[str, Any]]:
17
+ pyproject = path / "pyproject.toml"
18
+ if not pyproject.is_file():
19
+ return False, {}
20
+ try:
21
+ data: dict[str, Any] = tomllib.loads(pyproject.read_text(encoding="utf-8"))
22
+ except (OSError, tomllib.TOMLDecodeError):
23
+ return False, {}
24
+ tool_tbl = data.get("tool")
25
+ if isinstance(tool_tbl, dict) and "hud" in tool_tbl:
26
+ return True, data
27
+ project_tbl = data.get("project")
28
+ if isinstance(project_tbl, dict):
29
+ project_map = cast(dict[str, Any], project_tbl)
30
+ deps_raw = project_map.get("dependencies", [])
31
+ if isinstance(deps_raw, list):
32
+ deps = cast(list[Any], deps_raw)
33
+ if any(
34
+ isinstance(d, str) and d.lower().startswith(("hud-python", "hud_python"))
35
+ for d in deps
36
+ ):
37
+ return True, data
38
+ return False, data
39
+
40
+
41
+ class HudAdapter:
42
+ standard: EnvStandard = EnvStandard.HUD
43
+ capabilities: AdapterCapabilities = AdapterCapabilities(
44
+ supports_clean_image_grading=True,
45
+ supports_interactive_reset=True,
46
+ supports_rubric_introspection=False,
47
+ native_cli_binary="hud",
48
+ )
49
+
50
+ def __init__(self, native_runner: NativeDelegateRunner | None = None) -> None:
51
+ self._native = native_runner or NativeDelegateRunner()
52
+
53
+ def detect(self, path: Path) -> bool:
54
+ if not path.is_dir():
55
+ return False
56
+ if (path / "hud.toml").is_file():
57
+ return True
58
+ mentions_hud, _ = _pyproject_mentions_hud(path)
59
+ return mentions_hud
60
+
61
+ def load(self, path: Path) -> EnvSpec:
62
+ if not self.detect(path):
63
+ raise ConfigError(
64
+ f"Path '{path}' is not a valid HUD environment (expected hud.toml or hud-python)."
65
+ )
66
+
67
+ raw: dict[str, Any] = {}
68
+ hud_toml = path / "hud.toml"
69
+ if hud_toml.is_file():
70
+ try:
71
+ raw = tomllib.loads(hud_toml.read_text(encoding="utf-8"))
72
+ except (OSError, tomllib.TOMLDecodeError) as exc:
73
+ raise ConfigError(f"Failed to parse HUD config '{hud_toml}': {exc}") from exc
74
+
75
+ _, pyproject = _pyproject_mentions_hud(path)
76
+ project_tbl: dict[str, Any] = (
77
+ pyproject.get("project", {}) if isinstance(pyproject.get("project"), dict) else {}
78
+ )
79
+ task_id = str(raw.get("name") or project_tbl.get("name") or path.resolve().name)
80
+ instruction_text = (
81
+ (path / "README.md").read_text(encoding="utf-8")
82
+ if (path / "README.md").is_file()
83
+ else str(raw.get("description") or "")
84
+ )
85
+ verifier_paths = ["tasks/grade.py"] if (path / "tasks" / "grade.py").is_file() else []
86
+ if (path / "tests").is_dir() and "tests/" not in verifier_paths:
87
+ verifier_paths.append("tests/")
88
+ explicit_image = (
89
+ str(raw["image"]).strip()
90
+ if isinstance(raw.get("image"), str) and raw["image"].strip()
91
+ else None
92
+ )
93
+ image_digest: str | None = None
94
+ if explicit_image and "@sha256:" in explicit_image:
95
+ image_digest = "sha256:" + explicit_image.split("@sha256:", 1)[1]
96
+
97
+ dockerfile = path / "environment" / "Dockerfile"
98
+ if not dockerfile.is_file():
99
+ dockerfile = path / "Dockerfile"
100
+ dockerfile_rel = dockerfile.relative_to(path).as_posix() if dockerfile.is_file() else None
101
+
102
+ oracle_entrypoint: str | None = None
103
+ configured_oracle = raw.get("oracle_entrypoint")
104
+ if isinstance(configured_oracle, str) and configured_oracle.strip():
105
+ oracle_entrypoint = configured_oracle.strip()
106
+ elif (path / "solution" / "solve.sh").is_file():
107
+ oracle_entrypoint = "solution/solve.sh"
108
+ has_oracle = oracle_entrypoint is not None and (path / oracle_entrypoint).exists()
109
+
110
+ return EnvSpec(
111
+ task_id=task_id,
112
+ standard=EnvStandard.HUD,
113
+ root_path=path.resolve(),
114
+ instruction_text=instruction_text,
115
+ image_ref=explicit_image,
116
+ image_digest=image_digest,
117
+ has_oracle=has_oracle,
118
+ oracle_entrypoint=oracle_entrypoint,
119
+ verifier_paths=verifier_paths,
120
+ rubric_type="deterministic",
121
+ metadata={
122
+ "hud_config": raw,
123
+ "network_mode": raw.get("network_mode"),
124
+ "image_explicit": explicit_image is not None,
125
+ "dockerfile_path": dockerfile_rel,
126
+ },
127
+ )
128
+
129
+ def static_findings(self, spec: EnvSpec) -> list[AuditFinding]:
130
+ return []
131
+
132
+ async def run_native_check(
133
+ self,
134
+ spec: EnvSpec,
135
+ timeout_sec: float = 60.0,
136
+ require_native: bool = False,
137
+ ) -> list[AuditFinding]:
138
+ result = await self._native.run(
139
+ "hud",
140
+ ["validate", str(spec.root_path)],
141
+ cwd=spec.root_path,
142
+ timeout_sec=timeout_sec,
143
+ require_native=require_native,
144
+ )
145
+ return result.findings
146
+
147
+ async def run_oracle(self, spec: EnvSpec, sandbox: Any) -> tuple[float, dict[str, Any]]:
148
+ if not spec.has_oracle or not spec.oracle_entrypoint:
149
+ raise RuntimeSandboxError(
150
+ f"HUD task '{spec.task_id}' does not declare an existing oracle_entrypoint "
151
+ "(set oracle_entrypoint in hud.toml or provide solution/solve.sh)."
152
+ )
153
+ oracle_path = (spec.root_path / spec.oracle_entrypoint).resolve()
154
+ try:
155
+ oracle_path.relative_to(spec.root_path.resolve())
156
+ except ValueError as exc:
157
+ raise RuntimeSandboxError(
158
+ f"Oracle entrypoint '{spec.oracle_entrypoint}' escapes task root."
159
+ ) from exc
160
+ if not oracle_path.is_file():
161
+ raise RuntimeSandboxError(f"Oracle script not found: {oracle_path}")
162
+
163
+ ctx = coerce_grading_context(sandbox)
164
+ outcome, artifact = await ctx.grader.execute_and_grade(
165
+ spec,
166
+ ctx.run_id,
167
+ script_bytes=oracle_path.read_bytes(),
168
+ timeout_sec=ctx.timeout_sec,
169
+ workdir=ctx.workdir,
170
+ )
171
+ return outcome.reward, outcome_to_details(outcome, artifact)
172
+
173
+ async def run_noop(self, spec: EnvSpec, sandbox: Any) -> tuple[float, dict[str, Any]]:
174
+ ctx = coerce_grading_context(sandbox)
175
+ outcome, artifact = await ctx.grader.execute_and_grade(
176
+ spec,
177
+ ctx.run_id,
178
+ agent_cmd=["true"],
179
+ timeout_sec=ctx.timeout_sec,
180
+ workdir=ctx.workdir,
181
+ )
182
+ return outcome.reward, outcome_to_details(outcome, artifact)
@@ -0,0 +1,137 @@
1
+ """Native validator subprocess delegator with scrubbed env & graceful degradation (SDD-03)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import shutil
8
+ import time
9
+ from pathlib import Path
10
+
11
+ from pydantic import BaseModel, Field
12
+
13
+ from dasv.core.errors import NativeDelegateError
14
+ from dasv.core.schemas import AuditFinding, Severity
15
+
16
+ _SAFE_ENV_KEYS = ("PATH", "HOME", "TMPDIR", "LANG", "LC_ALL", "UV_CACHE_DIR")
17
+ _MAX_OUTPUT_CHARS = 4096
18
+
19
+
20
+ def _scrubbed_env() -> dict[str, str]:
21
+ return {key: os.environ[key] for key in _SAFE_ENV_KEYS if key in os.environ}
22
+
23
+
24
+ class NativeDelegateResult(BaseModel):
25
+ binary: str
26
+ found: bool
27
+ exit_code: int | None = None
28
+ duration_ms: float = 0.0
29
+ stdout: str = ""
30
+ stderr: str = ""
31
+ findings: list[AuditFinding] = Field(default_factory=list[AuditFinding])
32
+
33
+
34
+ class NativeDelegateRunner:
35
+ """Safely executes optional native CLIs (`harbor`, `openenv`, `vf-validate`, `hud`)."""
36
+
37
+ async def run(
38
+ self,
39
+ binary: str,
40
+ args: list[str],
41
+ cwd: Path,
42
+ *,
43
+ timeout_sec: float = 60.0,
44
+ require_native: bool = False,
45
+ ) -> NativeDelegateResult:
46
+ resolved_bin = shutil.which(binary)
47
+ if resolved_bin is None:
48
+ if require_native:
49
+ raise NativeDelegateError(
50
+ f"Required native validator binary '{binary}' was not found on PATH."
51
+ )
52
+ advisory = AuditFinding(
53
+ rule_id="RULE-NATIVE-001",
54
+ title=f"Native CLI '{binary}' not installed",
55
+ severity=Severity.INFO,
56
+ tier=0,
57
+ source="native_delegate",
58
+ file_path=None,
59
+ line_number=None,
60
+ evidence=f"Executable '{binary}' not found on PATH; ran dasv fallback checks only.",
61
+ remediation=f"Install '{binary}' to enable delegated upstream schema validation.",
62
+ )
63
+ return NativeDelegateResult(binary=binary, found=False, findings=[advisory])
64
+
65
+ start = time.perf_counter()
66
+ proc = await asyncio.create_subprocess_exec(
67
+ resolved_bin,
68
+ *args,
69
+ cwd=str(cwd),
70
+ env=_scrubbed_env(),
71
+ stdout=asyncio.subprocess.PIPE,
72
+ stderr=asyncio.subprocess.PIPE,
73
+ )
74
+
75
+ try:
76
+ raw_out, raw_err = await asyncio.wait_for(proc.communicate(), timeout=timeout_sec)
77
+ except TimeoutError:
78
+ proc.kill()
79
+ await proc.communicate()
80
+ elapsed_ms = (time.perf_counter() - start) * 1000.0
81
+ finding = AuditFinding(
82
+ rule_id="RULE-NATIVE-002",
83
+ title=f"Native validator '{binary}' timed out",
84
+ severity=Severity.HIGH,
85
+ tier=0,
86
+ source="native_delegate",
87
+ file_path=None,
88
+ line_number=None,
89
+ evidence=(
90
+ f"Command '{binary} {' '.join(args)}' exceeded {timeout_sec:.1f}s timeout."
91
+ ),
92
+ remediation=f"Run '{binary} {' '.join(args)}' manually to diagnose hangs.",
93
+ )
94
+ if require_native:
95
+ raise NativeDelegateError(finding.evidence) from None
96
+ return NativeDelegateResult(
97
+ binary=binary,
98
+ found=True,
99
+ exit_code=None,
100
+ duration_ms=elapsed_ms,
101
+ findings=[finding],
102
+ )
103
+
104
+ elapsed_ms = (time.perf_counter() - start) * 1000.0
105
+ stdout = raw_out.decode("utf-8", errors="replace")[:_MAX_OUTPUT_CHARS]
106
+ stderr = raw_err.decode("utf-8", errors="replace")[:_MAX_OUTPUT_CHARS]
107
+ exit_code = proc.returncode if proc.returncode is not None else -1
108
+
109
+ findings: list[AuditFinding] = []
110
+ if exit_code != 0:
111
+ snippet = (stderr or stdout or f"Exited with status {exit_code}").strip()
112
+ finding = AuditFinding(
113
+ rule_id="RULE-NATIVE-003",
114
+ title=f"Native validator '{binary}' reported failure (exit {exit_code})",
115
+ severity=Severity.HIGH,
116
+ tier=0,
117
+ source="native_delegate",
118
+ file_path=None,
119
+ line_number=None,
120
+ evidence=snippet[:512],
121
+ remediation=f"Fix issues reported by '{binary} {' '.join(args)}'.",
122
+ )
123
+ if require_native:
124
+ raise NativeDelegateError(
125
+ f"Native validator '{binary}' failed (exit {exit_code}): {snippet[:256]}"
126
+ )
127
+ findings.append(finding)
128
+
129
+ return NativeDelegateResult(
130
+ binary=binary,
131
+ found=True,
132
+ exit_code=exit_code,
133
+ duration_ms=elapsed_ms,
134
+ stdout=stdout,
135
+ stderr=stderr,
136
+ findings=findings,
137
+ )