#!/usr/bin/env bash
set -uo pipefail
umask 077
E="/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-gate20-corrected-harness-4e9962be49b72951c3b9ed7e1a4fe36d0ca03e757872ae03364c1ab7a790f32b-st_01a0080c";OLD="/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-gates18-20-clarification-normalized-4e9962be49b72951c3b9ed7e1a4fe36d0ca03e757872ae03364c1ab7a790f32b-st_01a0080c";C="/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-clarification-normalized-successor-4e9962be49b72951c3b9ed7e1a4fe36d0ca03e757872ae03364c1ab7a790f32b";R="/home/cube/projects/richard/hermes-agent";PY="$R/.venv/bin/python";PP="$R:/home/cube/.hermes/profiles/dualcoachtest/workspace/checkin_cli";mkdir -p "$E/artifacts" "$E/receipts";chmod 700 "$E" "$E/artifacts" "$E/receipts"
record(){ local n="$1";shift;local d="$E/artifacts/$n";mkdir -p "$d";printf '%q ' "$@">"$d/command.txt";printf '\n'>>"$d/command.txt";env -0|sort -z >"$d/launcher-environment.nul";date -u +%Y-%m-%dT%H:%M:%S.%NZ>"$d/started-at-utc.txt";local s e rc pid;s=$(date +%s%N);"$@">"$d/stdout.txt" 2>"$d/stderr.txt"&pid=$!;wait "$pid";rc=$?;e=$(date +%s%N);date -u +%Y-%m-%dT%H:%M:%S.%NZ>"$d/ended-at-utc.txt";echo "$rc">"$d/exit-code.txt";echo "$(((e-s)/1000000))">"$d/duration-ms.txt";(cd "$d"&&sha256sum command.txt launcher-environment.nul started-at-utc.txt ended-at-utc.txt exit-code.txt duration-ms.txt stdout.txt stderr.txt>files.sha256);chmod 600 "$d"/*;return 0;}
(cd "$OLD"&&find . -type f -print0|sort -z|xargs -0 sha256sum)>"$E/artifacts/original-fail-root-before.sha256"
sha256sum "$OLD/receipts/"*.json >"$E/artifacts/original-fail-receipts-before.sha256"
cd "$R";git status --porcelain=v1 -z >"$E/artifacts/git-status-before.nul";sha256sum "$C/candidate-manifest.json" "$C/hash-inventory.json" "$C/bindings/source-delta.json" "$C/artifacts/hermes_agent-0.17.0-py3-none-any.whl" >"$E/artifacts/candidate-pins-before.sha256";systemctl --user show hermes-gateway-dualcoachtest.service -p ActiveState -p SubState -p MainPID >"$E/artifacts/service-before.txt" 2>&1||true
"$PY" - <<'PY' "$OLD/artifacts/gate20-full-gateway.junit.xml" "$E/artifacts/failing-nodes.json" "$E/artifacts/failing-nodes.txt" "$E/artifacts/media-nodes.txt" "$E/artifacts/footer-node.txt"
import json,sys,xml.etree.ElementTree as ET
from pathlib import Path
src,out,txt,media,footer=map(Path,sys.argv[1:]);rows=[]
for tc in ET.parse(src).getroot().iter('testcase'):
 if tc.find('failure') is None and tc.find('error') is None:continue
 parts=tc.attrib['classname'].split('.');i=next(i for i,x in enumerate(parts) if x.startswith('test_'));path='/'.join(parts[:i+1])+'.py';tail=parts[i+1:];node='::'.join([path,*tail,tc.attrib['name']]);rows.append(node)
assert len(rows)==22 and len(set(rows))==22
f=[x for x in rows if x.endswith('::test_format_footer_skips_missing_context_length')];m=[x for x in rows if x not in f];assert len(f)==1 and len(m)==21
out.write_text(json.dumps({'source_junit_sha256':__import__('hashlib').sha256(src.read_bytes()).hexdigest(),'count':22,'nodes':rows},sort_keys=True,separators=(',',':'))+'\n');txt.write_text('\n'.join(rows)+'\n');media.write_text('\n'.join(m)+'\n');footer.write_text(f[0]+'\n')
PY
mapfile -t ALL <"$E/artifacts/failing-nodes.txt";mapfile -t MEDIA <"$E/artifacts/media-nodes.txt";FOOTER=$(<"$E/artifacts/footer-node.txt")
record control-a-direct-normal env -u TMPDIR HOME=/home/cube PYTHONPATH="$PP" PYTHONDONTWRITEBYTECODE=1 "$PY" -B -m pytest -q -p no:cacheprovider --junitxml="$E/artifacts/control-a-direct-normal.junit.xml" "${ALL[@]}"
record control-b-unshare-net-normal-home bwrap --die-with-parent --unshare-net --ro-bind / / --bind "$E" "$E" --tmpfs /tmp --tmpfs "$R/.pytest-cache" --dev /dev --proc /proc --setenv HOME /home/cube --setenv TMPDIR /tmp --setenv PYTHONPATH "$PP" --setenv PYTHONDONTWRITEBYTECODE 1 --chdir "$R" "$PY" -B -m pytest -q -p no:cacheprovider --junitxml="$E/artifacts/control-b-unshare-net-normal-home.junit.xml" "${MEDIA[@]}"
record control-c-footer-tmp-home env -u TMPDIR HOME=/tmp PYTHONPATH="$PP" PYTHONDONTWRITEBYTECODE=1 "$PY" -B -m pytest -q -p no:cacheprovider --junitxml="$E/artifacts/control-c-footer-tmp-home.junit.xml" "$FOOTER"
record control-c-footer-normal-home env -u TMPDIR HOME=/home/cube PYTHONPATH="$PP" PYTHONDONTWRITEBYTECODE=1 "$PY" -B -m pytest -q -p no:cacheprovider --junitxml="$E/artifacts/control-c-footer-normal-home.junit.xml" "$FOOTER"
record adjudicate-controls "$PY" -c '
import hashlib,json,sys,xml.etree.ElementTree as ET
from pathlib import Path
r=Path(sys.argv[1])
def j(n):
 p=r/f"{n}.junit.xml";x=ET.parse(p).getroot();ss=[x] if x.tag=="testsuite" else x.findall("testsuite");d={k:sum(int(float(s.attrib.get(k,0))) for s in ss) for k in ("tests","failures","errors","skipped")};d["passed"]=d["tests"]-d["failures"]-d["errors"]-d["skipped"];d["sha256"]=hashlib.sha256(p.read_bytes()).hexdigest();return d
a=j("control-a-direct-normal");b=j("control-b-unshare-net-normal-home");ct=j("control-c-footer-tmp-home");cn=j("control-c-footer-normal-home");bout=(r/"control-b-unshare-net-normal-home/stdout.txt").read_text();ctout=(r/"control-c-footer-tmp-home/stdout.txt").read_text();classes={"dns_resolution_failed":bout.count("DNS resolution failed"),"blocked_unsafe":bout.count("Blocked unsafe"),"url_safety":bout.count("url_safety")};ok=a=={**a,"tests":22} if False else (a["tests"]==22 and a["passed"]==22 and a["failures"]==a["errors"]==0 and b["tests"]==21 and b["failures"]==21 and b["errors"]==0 and (classes["dns_resolution_failed"]>0 or classes["blocked_unsafe"]>0) and ct["tests"]==1 and ct["failures"]==1 and "/tmp/wd" in ctout and "~/wd" in ctout and cn["tests"]==1 and cn["passed"]==1 and cn["failures"]==cn["errors"]==0);o={"candidate_digest":sys.argv[2],"control_a":a,"control_b":b,"control_b_failure_markers":classes,"control_c_tmp_home":ct,"control_c_normal_home":cn,"candidate_causality_count":0 if ok else None,"invalid_harness_proven":ok,"status":"PASS" if ok else "FAIL"};print(json.dumps(o,sort_keys=True,separators=(",",":")));raise SystemExit(not ok)
' "$E/artifacts" 4e9962be49b72951c3b9ed7e1a4fe36d0ca03e757872ae03364c1ab7a790f32b
