Skip to content

Commit 945b6bb

Browse files
authored
preserve(harness): consolidate benchmark envelope work
Auto-squash after required CI and review gates pass; source branch retained.
1 parent b9ff1a4 commit 945b6bb

9 files changed

Lines changed: 157 additions & 9 deletions

File tree

codex-cli/package-lock.json

Lines changed: 19 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

harness/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ build-backend = "hatchling.build"
1313
helios-harness = "harness.scripts.run_harness:main"
1414

1515
[tool.hatch.build.targets.wheel]
16-
packages = ["harness.src.harness"]
16+
packages = ["src/harness"]
1717

1818
# M1/Apple Silicon build settings
1919
[tool.hatch.envs.default]

harness/scripts/run-harness.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,6 @@
1010
from datetime import UTC, datetime
1111
from pathlib import Path
1212

13-
from jsonschema import validate
14-
1513
ROOT = Path(__file__).resolve().parents[1] / "src"
1614
if str(ROOT) not in sys.path:
1715
sys.path.insert(0, str(ROOT))
@@ -174,6 +172,8 @@ def run_runner(repo: str, profile: str, out: str, args) -> None:
174172

175173
if args.dry_run:
176174
result["result_code"] = "WARN" if not commands else "PASS"
175+
from harness.benchmark_envelope import add_envelope
176+
result = add_envelope(result, repo=repo, profile=profile, plan_hash=command_hash)
177177
Path(out).write_text(json.dumps(result, indent=2))
178178
return
179179

@@ -195,6 +195,8 @@ def run_runner(repo: str, profile: str, out: str, args) -> None:
195195
payload["reproducibility"] = _reproducibility_metadata(profile, args)
196196
payload["created_at"] = datetime.now(tz=UTC).isoformat()
197197
payload["command_count"] = len(commands)
198+
from harness.benchmark_envelope import add_envelope
199+
payload = add_envelope(payload, repo=repo, profile=profile, plan_hash=command_hash)
198200

199201
if args.replay:
200202
replay_path = Path(args.replay)
@@ -277,6 +279,8 @@ def normalize_run(input_file: str, out: str) -> None:
277279

278280

279281
def validate_artifacts(schema: str, file: str) -> None:
282+
from jsonschema import validate
283+
280284
payload = json.loads(Path(file).read_text())
281285
schema_json = json.loads(Path(schema).read_text())
282286
validate(instance=payload, schema=schema_json)
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""Deterministic umbrella evidence envelope for harness runs."""
2+
3+
from __future__ import annotations
4+
5+
import hashlib
6+
import json
7+
from datetime import UTC, datetime
8+
9+
10+
def _digest(value: object) -> str:
11+
encoded = json.dumps(value, sort_keys=True, separators=(",", ":")).encode()
12+
return hashlib.sha256(encoded).hexdigest()
13+
14+
15+
def add_envelope(payload: dict, *, repo: str, profile: str, plan_hash: str) -> dict:
16+
identity = {"repo": repo, "commit": "0000000", "harness": "helios-harness", "model": "unknown", "task_id": f"plan:{plan_hash}", "hardware": "unknown"}
17+
digest = _digest(identity)
18+
run_id = f"run_{digest}"
19+
session_id = f"ses_{_digest({'run_id': run_id, 'session': 'default'})}"
20+
attempt_id = f"att_{_digest({'run_id': run_id, 'attempt': 0})}"
21+
causality = {"tenant_id": "phenotype", "session_id": session_id, "run_id": run_id, "attempt_id": attempt_id}
22+
now = datetime.now(UTC).isoformat()
23+
checkpoint_id = f"cp_{_digest({'run_id': run_id, 'checkpoint': 0})[:16]}"
24+
events = []
25+
for seq, event_type in enumerate(("run_started", "checkpoint", "compaction", "run_finished")):
26+
event = {"event_id": f"evt_{_digest({'run_id': run_id, 'seq': seq, 'type': event_type})}", "seq": seq, "ts": now, "type": event_type, "payload_sha256": _digest({"type": event_type, "seq": seq}), "causality": causality}
27+
if event_type in ("checkpoint", "compaction"):
28+
event["checkpoint_id"] = checkpoint_id
29+
if event_type == "compaction":
30+
event["details"] = {"tokens_before": 0, "tokens_after": 0, "retained_event_ids": [], "dropped_event_ids": []}
31+
events.append(event)
32+
passed = payload.get("result_code") == "PASS"
33+
legacy_digest = _digest(payload)
34+
return {
35+
"schema_version": "1.0.0",
36+
"tenant_id": "phenotype", "session_id": session_id, "run_id": run_id, "attempt_id": attempt_id,
37+
"deterministic_identity": {"algorithm": "sha256(canonical-json(inputs))", "canonical_json_sha256": digest, "inputs": identity},
38+
"subject": {"repo": repo, "commit": "unknown", "harness": "helios-harness", "runtime": "python", "model": "unknown", "hardware": "unknown"},
39+
"lease": {"lease_id": f"lease_{attempt_id[4:20]}", "owner": "helios-harness", "ttl_seconds": 120, "heartbeat_interval_seconds": 20},
40+
"task_manifest": {"task_id": f"plan:{plan_hash}", "input_sha256": plan_hash, "timeout_seconds": 1, "assertions": [{"id": "plan_discovered", "kind": "command_plan", "expected": True}], "judge": {"name": "helios-harness", "version": "0.1.0"}},
41+
"events": events,
42+
"result": {"status": "passed" if passed else "failed", "outcome_sha256": legacy_digest, "replay_hash": _digest(events), "failure_class": "none" if passed else "unknown", "artifacts": [{"kind": "report", "uri": f"urn:helios:legacy-evidence:{legacy_digest}", "sha256": legacy_digest}]},
43+
"provenance": {"collector": "helios-harness", "collected_at": now, "source_hashes": {"plan": plan_hash}},
44+
"signature": {"algorithm": "placeholder", "key_id": "unconfigured", "signature_b64": ""},
45+
}

harness/src/harness/interfaces.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,17 +53,23 @@ class RepoManifest:
5353

5454
@classmethod
5555
def from_repo(cls, repo_root: Path, repo_id: str) -> RepoManifest:
56-
from subprocess import CalledProcessError, check_output
56+
from subprocess import CalledProcessError, TimeoutExpired, check_output
57+
58+
def git_output(*args: str) -> str:
59+
try:
60+
return check_output(["git", "-C", root, *args], text=True, timeout=2).strip()
61+
except (CalledProcessError, TimeoutExpired, FileNotFoundError):
62+
return ""
5763

5864
root = str(repo_root.resolve())
5965
try:
60-
remote = check_output(["git", "-C", root, "remote", "get-url", "origin"], text=True).strip()
61-
except CalledProcessError:
66+
remote = git_output("remote", "get-url", "origin")
67+
except (CalledProcessError, TimeoutExpired):
6268
remote = "(no-remote)"
6369
try:
64-
branch = check_output(["git", "-C", root, "branch", "--show-current"], text=True).strip()
65-
commit = check_output(["git", "-C", root, "rev-parse", "--short", "HEAD"], text=True).strip()
66-
except CalledProcessError:
70+
branch = git_output("branch", "--show-current")
71+
commit = git_output("rev-parse", "--short", "HEAD")
72+
except (CalledProcessError, TimeoutExpired):
6773
branch = "(no-git)"
6874
commit = ""
6975
default_branch = branch or "main"
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"""Importable harness command entrypoints."""
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""Importable wrapper for the repository's legacy hyphenated runner script."""
2+
3+
from __future__ import annotations
4+
5+
import importlib.util
6+
from pathlib import Path
7+
from types import ModuleType
8+
9+
10+
def _legacy_module() -> ModuleType:
11+
script = Path(__file__).resolve().parents[3] / "scripts" / "run-harness.py"
12+
spec = importlib.util.spec_from_file_location("helios_harness_legacy_runner", script)
13+
if spec is None or spec.loader is None:
14+
raise ImportError(f"Unable to load harness runner: {script}")
15+
module = importlib.util.module_from_spec(spec)
16+
spec.loader.exec_module(module)
17+
return module
18+
19+
20+
def main() -> None:
21+
"""Run the canonical harness CLI."""
22+
_legacy_module().main()
23+
24+
25+
def run_runner(repo: str, profile: str, out: str, args) -> None:
26+
"""Expose the runner seam for integration tests and adapters."""
27+
_legacy_module().run_runner(repo, profile, out, args)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import json
2+
import tempfile
3+
from types import SimpleNamespace
4+
5+
from harness.scripts.run_harness import run_runner
6+
7+
8+
def test_run_runner_emits_benchmark_envelope(tmp_path):
9+
repo = tmp_path / "repo"
10+
repo.mkdir()
11+
(repo / "Makefile").write_text("check:\n\t@echo check\n")
12+
out = tmp_path / "run.json"
13+
run_runner(str(repo), "strict-full", str(out), SimpleNamespace(
14+
replay=None, dry_run=True, max_parallel=2, timeout=2, retries=0,
15+
retry_delay=1.0, budget=None, continue_on_fail=False,
16+
))
17+
payload = json.loads(out.read_text())
18+
try:
19+
import jsonschema
20+
from pathlib import Path
21+
schema_path = Path(__file__).parents[3] / "docs/sessions/20260722-agent-harness-portfolio/artifacts/benchmark_run.schema.json"
22+
jsonschema.Draft202012Validator(json.loads(schema_path.read_text())).validate(payload)
23+
except ModuleNotFoundError:
24+
pass
25+
assert payload["tenant_id"] == "phenotype"
26+
assert payload["session_id"].startswith("ses_")
27+
assert payload["run_id"].startswith("run_")
28+
assert payload["attempt_id"].startswith("att_")
29+
assert payload["subject"]["harness"] == "helios-harness"
30+
assert payload["provenance"]["collector"] == "helios-harness"
31+
assert payload["signature"]["algorithm"] == "placeholder"
32+
assert {event["type"] for event in payload["events"]} >= {"checkpoint", "compaction"}
33+
34+
35+
if __name__ == "__main__":
36+
with tempfile.TemporaryDirectory() as directory:
37+
from pathlib import Path
38+
test_run_runner_emits_benchmark_envelope(Path(directory))
39+
print("direct_envelope_test_pass")
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from importlib import import_module
2+
3+
4+
def test_harness_entrypoint_is_importable():
5+
module = import_module("harness.scripts.run_harness")
6+
assert callable(module.main)
7+
assert callable(module.run_runner)

0 commit comments

Comments
 (0)