File size: 6,907 Bytes
2e7de11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Preserve and report incomplete work without claiming native visual validity.

Runs after the agent phase, or offline against a downloaded checkpoint.
No model calls, project edits, or GUI actions.
"""
import argparse
import datetime as dt
import hashlib
import json
from pathlib import Path, PurePosixPath
import shutil
import tarfile
import tempfile

import visual_score


def unpack_checkpoint(archive, root):
    """Read regular files only; never follow candidate-controlled links."""
    with tarfile.open(archive) as tar:
        members = tar.getmembers()
        seen = set()
        for member in members:
            path = PurePosixPath(member.name)
            if (path.is_absolute() or ".." in path.parts or
                    not (member.isfile() or member.isdir()) or path in seen):
                raise ValueError("Unsafe or duplicate checkpoint entry")
            seen.add(path)
        if sum(m.size for m in members) > 20 * 1024**3:
            raise ValueError("Checkpoint exceeds 20 GiB extraction limit")
        for member in members:
            if member.isfile():
                target = root / member.name
                target.parent.mkdir(parents=True, exist_ok=True)
                with tar.extractfile(member) as source, target.open("wb") as dest:
                    shutil.copyfileobj(source, dest)


def inventory(root, out):
    items = []
    # Preserve recovery paths rather than flattening duplicate autosave names.
    for relative in ("edit", "Desktop", "Downloads", ".local/share/stalefiles"):
        base = root / relative
        if not base.is_dir() or base.is_symlink():
            continue
        for path in sorted(base.rglob("*")):
            if (not path.is_file() or path.is_symlink() or
                    any((root / parent).is_symlink()
                        for parent in path.relative_to(root).parents)):
                continue
            if path.suffix.lower() not in (".friction", ".autosave", ".mp4"):
                continue
            relative_path = path.relative_to(root)
            target = out / "progress-evidence" / relative_path
            target.parent.mkdir(parents=True, exist_ok=True)
            try:
                shutil.copy2(path, target)
                with target.open("rb") as saved:
                    digest = hashlib.file_digest(saved, "sha256").hexdigest()
                item = {"path": str(relative_path), "bytes": target.stat().st_size,
                        "sha256": digest, "evidence": str(target.relative_to(out))}
                if path.suffix.lower() == ".mp4":
                    try:
                        item["media_probe"] = visual_score.probe(target)
                    except Exception as exc:
                        item["media_probe_error"] = type(exc).__name__
                else:
                    item["native_validity"] = "unverified: reopen and render required"
                items.append(item)
            except OSError as exc:
                items.append({"path": str(relative_path), "collection_error": type(exc).__name__})
    return items


def evaluate_partial(root, out, reference_dir, provenance):
    root, out = Path(root), Path(out)
    out.mkdir(parents=True, exist_ok=True)
    for stale in ("reward.json", "reward.txt", "visual-diagnostics.json", "evaluation-error.json"):
        (out / stale).unlink(missing_ok=True)
    report = {
        "created_at": dt.datetime.now(dt.timezone.utc).isoformat(),
        "provenance": provenance,
        "files": inventory(root, out),
        "native_validity": "unverified",
        "visual_status": "pending",
        "limitations": [
            "Saved files and autosaves only; unsaved in-memory work may be absent.",
            "File presence, hashes and media metadata do not establish native validity.",
            "Only complete conforming videos receive the existing visual diagnostics.",
            "Missing or invalid exports are unmeasurable, not observed motion failures.",
            "Rendered progress reward does not certify native validity or semantic completion.",
        ],
    }
    report_path = out / "partial-progress.json"
    report_path.write_text(json.dumps(report, indent=2) + "\n")
    try:
        result = visual_score.evaluate(root, out, reference_dir)
        report["visual_status"] = "rendered progress measurements available"
        report["individual_visual_coverage"] = result["individual_visual_coverage"]
        report["delivery_fraction"] = result["delivery_fraction"]
        native = {f["path"] for f in report["files"] if "native_validity" in f and f["bytes"] > 0}
        report["categories"] = [
            {"name": c["name"],
             "saved_project": f'edit/individual/{c["name"]}.friction' in native,
             "individual_visual_measured": c["individual"] is not None,
             "gallery_visual_measured": c["gallery"] is not None,
             "native_validity": "unverified"}
            for c in result["categories"]
        ]
    except Exception as exc:
        report["visual_status"] = "evaluator error; preserved evidence remains available"
        report["evaluator_error"] = {"type": type(exc).__name__, "message": str(exc)}
        for stale in ("reward.json", "reward.txt"):
            (out / stale).unlink(missing_ok=True)
        (out / "evaluation-error.json").write_text(json.dumps(report["evaluator_error"]) + "\n")
        raise
    finally:
        report_path.write_text(json.dumps(report, indent=2) + "\n")
        rows = ["# Partial progress", "", f'Evidence source: {provenance}', "",
                "| Animation | Saved project | Individual video measured | Gallery measured |",
                "|---|---|---|---|"]
        for c in report.get("categories", []):
            rows.append(f'| {c["name"]} | {c["saved_project"]} | '
                        f'{c["individual_visual_measured"]} | {c["gallery_visual_measured"]} |')
        rows += ["", report["visual_status"], ""] + ["- " + s for s in report["limitations"]]
        (out / "PARTIAL_PROGRESS.md").write_text("\n".join(rows) + "\n")
    return report


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", default="/root")
    parser.add_argument("--out", required=True)
    parser.add_argument("--checkpoint", type=Path)
    parser.add_argument("--reference-dir", default=str(Path(__file__).parent / "reference"))
    args = parser.parse_args()
    if args.checkpoint:
        with tempfile.TemporaryDirectory(prefix="t29-checkpoint-") as directory:
            root = Path(directory)
            unpack_checkpoint(args.checkpoint, root)
            evaluate_partial(root, args.out, args.reference_dir,
                             "Downloaded checkpoint: " + str(args.checkpoint.resolve()))
    else:
        evaluate_partial(args.root, args.out, args.reference_dir, "Post-agent filesystem snapshot")