File size: 5,747 Bytes
0cbb964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The sync: what the manifest names is published and nothing else, hashes tell a changed
task, the index follows."""

from __future__ import annotations

import json
import shutil
from pathlib import Path

import pytest

from sync import INDEX, PLAN, RECIPE, TASKS_DIR, TRUTH_DIR, hash_files, referenced_files, sync

AGENT_TASKS = Path(__file__).resolve().parents[2] / "agent" / "data" / "tasks"


def test_referenced_files_are_collected_at_any_depth_once() -> None:
    manifest = {
        "batches": [
            {
                "files": ["docs/a.pdf", "docs/b.csv"],
                "cards": [
                    {"files": ["cards/1/x.jpg"], "referenceImages": ["cards/1/x.jpg"]},
                    {
                        "files": [],
                        "variations": [{"files": ["cards/2/y.jpg"], "referenceImages": []}],
                    },
                ],
                "hiddenAnswers": [{"topic": "MissingCost", "files": ["extra/prices.csv"]}],
            }
        ],
        "shop": {"name": "files"},  # a value, not a key that names files
    }
    assert referenced_files(manifest) == [
        "cards/1/x.jpg",
        "cards/2/y.jpg",
        "docs/a.pdf",
        "docs/b.csv",
        "extra/prices.csv",
    ]


def test_hash_follows_content_not_order(tmp_path: Path) -> None:
    (tmp_path / "a.txt").write_text("one", encoding="utf-8")
    (tmp_path / "b.txt").write_text("two", encoding="utf-8")
    first = hash_files(tmp_path, ["a.txt", "b.txt"])
    assert hash_files(tmp_path, ["b.txt", "a.txt", "a.txt"]) == first
    (tmp_path / "b.txt").write_text("three", encoding="utf-8")
    assert hash_files(tmp_path, ["a.txt", "b.txt"]) != first


def _source_task(tmp_path: Path) -> Path:
    """A real task copied without its results and caches; skipped where the agent's tasks
    are not next to this repository."""
    candidates = sorted(AGENT_TASKS.glob("*-r101")) if AGENT_TASKS.is_dir() else []
    if not candidates:
        pytest.skip("no generated task under ../agent/data/tasks")
    source = tmp_path / "source" / candidates[0].name
    shutil.copytree(
        candidates[0], source, ignore=shutil.ignore_patterns("results", "images", "__pycache__")
    )
    return source


def test_sync_publishes_inputs_truth_and_index(tmp_path: Path) -> None:
    source = _source_task(tmp_path)
    (source / "oracle.json").write_text("{}", encoding="utf-8")  # a verdict: never published
    target = tmp_path / "target"
    target.mkdir()
    outcomes = sync(source.parent, target)
    assert [o.state for o in outcomes] == ["new"]
    name = source.name
    task_dir = target / TASKS_DIR / name
    manifest = json.loads((task_dir / "task.json").read_text(encoding="utf-8"))
    for file in referenced_files(manifest):
        assert (task_dir / file).is_file(), file
    assert not (task_dir / PLAN).exists() and not (task_dir / "oracle.json").exists()
    assert (target / TRUTH_DIR / name / PLAN).is_file()
    assert (target / TRUTH_DIR / name / RECIPE).is_file() == (source / RECIPE).is_file()
    rows = [json.loads(line) for line in (target / INDEX).read_text(encoding="utf-8").splitlines()]
    assert len(rows) == 1 and rows[0]["name"] == name and rows[0]["split"] == "test"
    assert rows[0]["files"] == len(referenced_files(manifest)) + 1  # the manifest too
    assert len(rows[0]["content_sha256"]) == 64 and rows[0]["expected_products"] > 0
    # Again: nothing to do.
    assert [o.state for o in sync(source.parent, target)] == ["unchanged"]


def test_a_changed_task_is_refused_unless_forced(tmp_path: Path) -> None:
    source = _source_task(tmp_path)
    target = tmp_path / "target"
    target.mkdir()
    sync(source.parent, target)
    manifest = json.loads((source / "task.json").read_text(encoding="utf-8"))
    doc = source / referenced_files(manifest)[0]
    doc.write_bytes(doc.read_bytes() + b"\n")
    before = (target / INDEX).read_text(encoding="utf-8")
    outcomes = sync(source.parent, target)
    assert outcomes[0].state == "refused" and (target / INDEX).read_text(encoding="utf-8") == before
    assert sync(source.parent, target, dry_run=True, force=True)[0].state == "changed"
    assert (target / INDEX).read_text(encoding="utf-8") == before  # a dry run writes nothing
    outcomes = sync(source.parent, target, force=True)
    assert outcomes[0].state == "changed"
    after = json.loads((target / INDEX).read_text(encoding="utf-8"))
    assert after["content_sha256"] != json.loads(before)["content_sha256"]
    assert after["truth_sha256"] == json.loads(before)["truth_sha256"]


def test_missing_and_stray_files_are_told(tmp_path: Path) -> None:
    source = _source_task(tmp_path)
    (source / "docs" / "stray.txt").write_text("not in the manifest", encoding="utf-8")
    target = tmp_path / "target"
    target.mkdir()
    outcome = sync(source.parent, target)[0]
    assert outcome.state == "new" and outcome.unreferenced == ["docs/stray.txt"]
    assert not (target / TASKS_DIR / source.name / "docs" / "stray.txt").exists()
    manifest = json.loads((source / "task.json").read_text(encoding="utf-8"))
    (source / referenced_files(manifest)[0]).unlink()
    outcome = sync(source.parent, tmp_path / "other", force=True, dry_run=True)[0]
    assert outcome.state == "failed" and "missing" in outcome.detail


def test_a_plan_the_schema_rejects_is_skipped(tmp_path: Path) -> None:
    source = tmp_path / "source" / "handmade"
    source.mkdir(parents=True)
    (source / "task.json").write_text("{}", encoding="utf-8")
    (source / PLAN).write_text('{"name": "handmade"}', encoding="utf-8")
    outcome = sync(source.parent, tmp_path / "target", dry_run=True)[0]
    assert outcome.state == "skipped" and "does not validate" in outcome.detail