File size: 4,021 Bytes
4bebf98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""PRD parity and negative cases for the packaged routing/ACL definition."""

from pathlib import Path

import pytest
from pydantic import ValidationError

from polyhedra.core.quant_contracts import FilePermissions, QuantContracts, load_quant_contracts


def _table(text, heading):
    section = text.split(heading, 1)[1].split("\n#", 1)[0]
    return [
        [cell.strip().strip("`") for cell in line.strip("|").split("|")]
        for line in section.splitlines()
        if line.startswith("| `")
    ]


def _list(cell):
    return [] if cell == "[]" else cell.strip("[]").split(", ")


def test_exact_prd_routing_and_filename_permissions():
    prd = (Path(__file__).parents[1] / "docs/polyhedraV8.0.md").read_text(encoding="utf-8")
    contracts = load_quant_contracts()
    routing = _table(prd, "## Agreed Routing Table")
    acl = _table(prd, "#### ACL Table")
    baseline = _table(prd, "#### Baseline File Permissions")
    assert len(routing) == len(acl) == len(baseline) == len(contracts.agents) == 19
    for name, dependencies, scope in routing:
        agent = contracts.for_agent(name)
        assert list(agent.dependencies) == _list(dependencies)
        assert agent.scope == scope
    for name, *permissions in acl:
        actual = contracts.for_agent(name).permissions
        for field, expected in zip(("read", "create", "edit", "list"), permissions):
            assert list(getattr(actual, field)) == _list(expected), (name, field)
    for name, read, listing in baseline:
        actual = contracts.for_agent(name).permissions
        assert list(actual.baseline_read) == _list(read), name
        assert list(actual.baseline_list) == _list(listing), name


def test_contract_round_trip_and_fixed_support_contexts():
    contracts = load_quant_contracts()
    assert QuantContracts.model_validate_json(contracts.model_dump_json()) == contracts
    for symbol in ("BTC", "SPY", "QQQ", "GLD"):
        assert contracts.for_agent(f"{symbol}Analyst").symbol == symbol
    assert contracts.for_agent("VizAgent").context == "VISUALIZATION"
    assert contracts.for_agent("PortfolioMonitor").context == "PORTFOLIO_MONITOR"
    with pytest.raises(ValidationError):
        contracts.for_agent("DataFetcher").scope = "GENERAL"
    with pytest.raises(KeyError):
        contracts.for_agent("human")


@pytest.mark.parametrize("change", ["cycle", "unknown", "missing", "duplicate", "owner", "symbol", "context"])
def test_invalid_registry_is_rejected(change):
    data = load_quant_contracts().model_dump(mode="json")
    first = data["agents"][0]
    if change == "cycle":
        first["dependencies"] = ["Publisher"]
    elif change == "unknown":
        first["dependencies"] = ["human"]
    elif change == "missing":
        data["agents"].pop()
    elif change == "duplicate":
        data["agents"].append(first)
    elif change == "owner":
        data["agents"][1]["permissions"]["create"] += first["permissions"]["create"]
    elif change == "symbol":
        data["agents"][8]["symbol"] = "SPY"
    else:
        data["agents"][-1]["context"] = "YOLO"
    with pytest.raises(ValidationError):
        QuantContracts.model_validate(data)


@pytest.mark.parametrize("path", [
    "C:/secret.json", "../secret.json", "quant/runs/{run_id}/../secret.json",
    "quant/runs/{run_id}/*.json", "quant/runs/{other}/post.json",
    "quant/runs/{run_id}/raw/{ticker.__class__}.json", "quant/runs/{run_id}//post.json",
    "quant/runs/{baseline_run_id}/post.json",
])
def test_bad_current_filename_templates(path):
    with pytest.raises(ValidationError):
        FilePermissions(read=(path,))


def test_baseline_is_read_only_and_edits_require_ownership():
    with pytest.raises(ValidationError):
        FilePermissions(edit=("quant/runs/{run_id}/post.json",))
    with pytest.raises(ValidationError):
        FilePermissions(baseline_read=("quant/runs/{run_id}/post.json",))
    with pytest.raises(ValidationError):
        FilePermissions(baseline_edit=("quant/runs/{baseline_run_id}/post.json",))