File size: 6,387 Bytes
b6beed8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/env python3
"""Enforce build-before-query freezing for a WorkSurface-Build unit."""

from __future__ import annotations

import argparse
import hashlib
import json
import shutil
from pathlib import Path
from typing import Any


SENTINEL = ".worksurface_build_run"


def write_json(path: Path, value: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def canonical_json(value: Any) -> bytes:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")


def artifact_hashes(artifacts: Path) -> dict[str, str]:
    return {
        str(path.relative_to(artifacts)): "sha256:" + sha256_file(path)
        for path in sorted(artifacts.rglob("*")) if path.is_file()
    }


def load_state(run: Path) -> dict[str, Any]:
    if not (run / SENTINEL).exists():
        raise RuntimeError(f"not a WorkSurface-Build run: {run}")
    return json.loads((run / "state.json").read_text(encoding="utf-8"))


def start(release: Path, unit_type: str, unit_id: str, run: Path) -> None:
    if run.exists():
        raise RuntimeError(f"run directory already exists: {run}")
    index_name = "task_units.jsonl" if unit_type == "task" else "persona_units.jsonl"
    rows = [json.loads(line) for line in (release / "public" / index_name).read_text().splitlines() if line]
    row = next((item for item in rows if item["unit_id"] == unit_id), None)
    if row is None:
        raise KeyError(f"unknown unit: {unit_id}")
    unit_path = release / row["unit_spec"]
    unit = json.loads(unit_path.read_text(encoding="utf-8"))
    run.mkdir(parents=True)
    (run / SENTINEL).write_text("WorkSurface-Build run\n", encoding="utf-8")
    (run / "artifacts").mkdir()
    shutil.copy2(unit_path, run / "builder_input.json")
    write_json(run / "state.json", {
        "status": "BUILDING",
        "release": str(release.resolve()),
        "unit_type": unit_type,
        "unit_id": unit_id,
        "workspace": str((unit_path.parent / unit["workspace"]).resolve()),
        "hidden_task_commitment": unit["hidden_task_commitment"],
    })
    print(json.dumps({"run": str(run.resolve()), "workspace": str((unit_path.parent / unit["workspace"]).resolve())}, indent=2))


def freeze(run: Path, build_cost: dict[str, Any]) -> None:
    state = load_state(run)
    if state["status"] != "BUILDING":
        raise RuntimeError(f"cannot freeze run in state {state['status']}")
    hashes = artifact_hashes(run / "artifacts")
    if not hashes:
        raise RuntimeError("Builder produced no artifact files")
    manifest = {
        "unit_id": state["unit_id"],
        "artifact_hashes": hashes,
        "build_cost": build_cost,
    }
    write_json(run / "artifact_manifest.json", manifest)
    lock = "sha256:" + hashlib.sha256(canonical_json(manifest)).hexdigest()
    (run / "freeze.lock").write_text(lock + "\n", encoding="utf-8")
    state["status"] = "FROZEN"
    state["freeze_lock"] = lock
    write_json(run / "state.json", state)
    print(json.dumps({"status": "FROZEN", "artifacts": len(hashes), "freeze_lock": lock}, indent=2))


def verify(run: Path) -> dict[str, Any]:
    state = load_state(run)
    if state["status"] not in {"FROZEN", "SERVING"}:
        raise RuntimeError(f"run is not frozen: {state['status']}")
    manifest = json.loads((run / "artifact_manifest.json").read_text(encoding="utf-8"))
    current = artifact_hashes(run / "artifacts")
    ok = current == manifest["artifact_hashes"]
    result = {"ok": ok, "expected_files": len(manifest["artifact_hashes"]), "current_files": len(current)}
    if not ok:
        result["changed_paths"] = sorted(set(current) ^ set(manifest["artifact_hashes"]))
    return result


def release_questions(run: Path) -> None:
    state = load_state(run)
    result = verify(run)
    if not result["ok"]:
        raise RuntimeError("frozen artifacts changed before question release")
    release = Path(state["release"])
    if state["unit_type"] == "task":
        source = release / "private" / "serve_questions" / f"{state['unit_id']}.jsonl"
    else:
        source = release / "private" / "persona_serve_questions" / f"{state['unit_id']}.jsonl"
    shutil.copy2(source, run / "serve_questions.jsonl")
    state["status"] = "SERVING"
    write_json(run / "state.json", state)
    print(json.dumps({"status": "SERVING", "questions": len(source.read_text().splitlines())}, indent=2))


def parse_cost(value: str) -> dict[str, Any]:
    path = Path(value)
    if path.exists():
        return json.loads(path.read_text(encoding="utf-8"))
    parsed = json.loads(value)
    if not isinstance(parsed, dict):
        raise ValueError("build cost must be a JSON object")
    return parsed


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    start_p = commands.add_parser("start")
    start_p.add_argument("--release", type=Path, required=True)
    start_p.add_argument("--unit-type", choices=("task", "persona"), required=True)
    start_p.add_argument("--unit-id", required=True)
    start_p.add_argument("--run", type=Path, required=True)
    freeze_p = commands.add_parser("freeze")
    freeze_p.add_argument("--run", type=Path, required=True)
    freeze_p.add_argument("--build-cost", required=True, help="JSON object or JSON file")
    release_p = commands.add_parser("release-questions")
    release_p.add_argument("--run", type=Path, required=True)
    verify_p = commands.add_parser("verify")
    verify_p.add_argument("--run", type=Path, required=True)
    args = parser.parse_args()

    if args.command == "start":
        start(args.release, args.unit_type, args.unit_id, args.run)
    elif args.command == "freeze":
        freeze(args.run, parse_cost(args.build_cost))
    elif args.command == "release-questions":
        release_questions(args.run)
    else:
        result = verify(args.run)
        print(json.dumps(result, indent=2))
        if not result["ok"]:
            raise SystemExit(1)


if __name__ == "__main__":
    main()