Coverage for scripts/vault_record.py: 100%

63 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Record a phase gate in the local Aether-Vault repository: its rules, ledger, frozen configs and weight files, with 

2metrics, in one tagged commit. Nothing is pushed. The commit's timestamp is what shows a rule existed before the 

3scores it judged. 

4 

5 python scripts/vault_record.py --label rules --metric trials=0 ml/evaluation/v650/rules.json 

6""" 

7 

8from __future__ import annotations 

9 

10import argparse 

11import json 

12import os 

13import shutil 

14import sys 

15from pathlib import Path 

16 

17ROOT = Path(__file__).resolve().parent.parent 

18sys.path.insert(0, str(ROOT)) 

19 

20from retraining.vault_client import parse_av_envelope, run_av_command, staged_leftovers, vault_preflight # noqa: E402 

21from retraining.vault_commands import build_av_add_command, build_av_commit_command # noqa: E402 

22 

23 

24def find_av_binary() -> str: 

25 """`AQ_AV_BINARY`, then PATH, then the per-user scripts folder pip installs to on Windows.""" 

26 configured = os.environ.get("AQ_AV_BINARY") 

27 if configured: 

28 return configured 

29 found = shutil.which("av") 

30 if found: 

31 return found 

32 appdata = os.environ.get("APPDATA") 

33 if appdata: 

34 for candidate in sorted(Path(appdata).glob("Python/Python*/Scripts/av.exe")): 

35 return str(candidate) 

36 return "av" 

37 

38 

39def parse_metrics(raw: list[str]) -> dict[str, float]: 

40 metrics: dict[str, float] = {} 

41 for item in raw: 

42 key, separator, value = item.partition("=") 

43 if not separator or not key: 

44 raise ValueError(f"metric must be key=value: {item!r}") 

45 metrics[key] = float(value) 

46 return metrics 

47 

48 

49def record(label: str, paths: list[str], metrics: dict[str, float], *, cwd: Path = ROOT, av_binary: str | None = None) -> dict: 

50 """Returns {"ok": bool, "stage": str, "commit": str | None, "detail": str | None}. Never raises on an `av` failure.""" 

51 binary = av_binary or find_av_binary() 

52 config = {"av_binary": binary, "timeout_seconds": 600} 

53 preflight = vault_preflight(config, cwd=cwd) 

54 if not preflight["ok"]: 

55 return {"ok": False, "stage": "preflight", "commit": None, "detail": preflight["reason"]} 

56 # A failed gate's leftovers must not land under this gate's label. 

57 leftovers = staged_leftovers(binary, cwd=cwd, timeout=600) 

58 if leftovers: 

59 return {"ok": False, "stage": "staged_leftovers", "commit": None, "detail": f"run `av unstage` first: {leftovers[:5]}"} 

60 added = run_av_command(build_av_add_command(paths, av_binary=binary), cwd=cwd, timeout=600) 

61 if not added["ok"]: 

62 return {"ok": False, "stage": "add", "commit": None, "detail": added["error"]} 

63 committed = run_av_command( 

64 build_av_commit_command(f"gate {label}", f"gate:{label}", metrics, av_binary=binary, no_upload=True), cwd=cwd, timeout=600 

65 ) 

66 envelope = parse_av_envelope(committed["stdout"]) 

67 if not committed["ok"]: 

68 error = (envelope or {}).get("error") or {} 

69 # The same files recorded at an earlier gate are not a failure: that commit already holds them. 

70 if error.get("code") == "nothing_to_commit": 

71 return {"ok": True, "stage": "unchanged", "commit": None, "detail": "nothing_to_commit"} 

72 return {"ok": False, "stage": "commit", "commit": None, "detail": committed["error"]} 

73 data = (envelope or {}).get("data") or {} 

74 return {"ok": True, "stage": "done", "commit": data.get("hash"), "detail": None} 

75 

76 

77def main(argv: list[str] | None = None) -> int: 

78 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

79 parser.add_argument("--label", required=True) 

80 parser.add_argument("--metric", action="append", default=[], help="key=value, repeatable") 

81 parser.add_argument("paths", nargs="+") 

82 args = parser.parse_args(argv) 

83 result = record(args.label, args.paths, parse_metrics(args.metric)) 

84 print(json.dumps(result, indent=1)) 

85 return 0 if result["ok"] else 1 

86 

87 

88if __name__ == "__main__": 

89 raise SystemExit(main())