File size: 5,339 Bytes
1c1abed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Check the actual adapter boundary: missing information and honest abstention."""
import copy
import importlib.util
import json
from pathlib import Path
import subprocess
import sys

import pytest
from axiomesh.core import word_matrix
import numpy as np

ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("axiomesh_agent_interface", ROOT / "agent_interface.py")
adapter = importlib.util.module_from_spec(spec)
spec.loader.exec_module(adapter)


def example(name):
    return json.loads((ROOT / "examples" / name).read_text())


def test_capability_growth_exposes_a_real_program_witness():
    request = example("agent_revalidate.json")
    old = copy.deepcopy(request)
    del old["operators"]["b"]
    assert adapter.dispatch(old)["status"] == "exact"
    result = adapter.dispatch(request)
    assert result["status"] == "ambiguous"
    assert result["required_extra_scalar_observations"] == 1
    witness = result["certificate"]
    v = np.asarray(witness["null_vector"])
    assert np.all(np.asarray(request["memory"]["matrix"]) @ v % request["p"] == 0)
    ops = {a: np.asarray(t) for a, t in request["operators"].items()}
    q = np.asarray(request["query"])[witness["query"]]
    difference = int(q @ word_matrix(witness["word"], ops, request["p"]) @ v) % request["p"]
    assert difference == witness["output_difference"] != 0
    assert result["observations_acquired"] == 0


def test_explicit_observation_permits_compilation_and_fresh_recovery(tmp_path):
    result = adapter.dispatch(example("agent_compile.json"))
    assert result["status"] == "committed" and result["output"] == [9]
    assert "seed" not in result["capsule"]["program"]
    capsule = result["capsule"]
    capsule["memory"]["shares"].pop("1")
    (tmp_path / "capsule.json").write_text(json.dumps(capsule))
    restored = adapter.dispatch({"task": "recover_and_run", "capsule": "capsule.json", "word": ["b", "a"]}, tmp_path)
    assert restored["status"] == "exact" and restored["output"] == [9]
    assert restored["source_state_used"] is False


def test_not_enough_surviving_shares_abstains(tmp_path):
    capsule = adapter.dispatch(example("agent_compile.json"))["capsule"]
    capsule["memory"]["shares"] = {"1": capsule["memory"]["shares"]["1"]}
    (tmp_path / "capsule.json").write_text(json.dumps(capsule))
    result = adapter.dispatch({"task": "recover_and_run", "capsule": "capsule.json", "word": []}, tmp_path)
    assert result["status"] == "ambiguous" and result["output"] is None


def test_inconsistent_measurements_do_not_get_repaired():
    request = example("agent_compile.json")
    request["memory"]["matrix"].append([1, 0, 0])
    request["memory"]["rhs"].append(7)
    result = adapter.dispatch(request)
    assert result["status"] == "inconsistent"
    assert result["required_extra_scalar_observations"] is None
    assert result["output"] is None


def test_adapter_budget_exhaustion_is_not_a_certificate():
    request = example("agent_revalidate.json")
    request["product_budget"] = 0
    with pytest.raises(RuntimeError, match="budget exhausted"):
        adapter.dispatch(request)


@pytest.mark.parametrize("bad_prime", [True, 4, 257])
def test_invalid_or_oversized_field_is_rejected(bad_prime):
    request = example("agent_revalidate.json")
    request["p"] = bad_prime
    with pytest.raises(ValueError):
        adapter.dispatch(request)


@pytest.mark.parametrize("bad", [True, 1.5, -1, 101])
def test_noncanonical_or_noninteger_coefficient_is_rejected(bad):
    request = example("agent_revalidate.json")
    request["query"][0][0] = bad
    with pytest.raises(ValueError):
        adapter.dispatch(request)


def test_capsule_path_cannot_leave_the_repository():
    with pytest.raises(ValueError, match="inside the repository"):
        adapter.dispatch({"task": "recover_and_run", "capsule": "../outside.json", "word": []})


def test_unknown_action_and_extra_keys_are_rejected():
    request = example("agent_compile.json")
    request["word"] = ["undeclared"]
    with pytest.raises(ValueError, match="undeclared"):
        adapter.dispatch(request)
    request = example("agent_revalidate.json")
    request["execute_python"] = "print('untrusted')"
    with pytest.raises(ValueError, match="extra"):
        adapter.dispatch(request)


def test_zero_query_compilation_reports_no_observable():
    request = example("agent_compile.json")
    request["query"] = [[0, 0, 0]]
    result = adapter.dispatch(request)
    assert result["status"] == "zero_observable" and result["output"] is None


def test_empty_memory_is_an_honest_hole():
    request = example("agent_revalidate.json")
    request["memory"] = {"matrix": [], "rhs": []}
    result = adapter.dispatch(request)
    assert result["status"] == "ambiguous"
    assert result["required_extra_scalar_observations"] == 3


def test_json_cli_recovery_and_hole_exit_codes():
    for name, expected_code, status in [("agent_recover.json", 0, "exact"), ("agent_revalidate.json", 2, "ambiguous")]:
        proc = subprocess.run([sys.executable, str(ROOT / "agent_interface.py"), "--request", str(ROOT / "examples" / name)],
                              capture_output=True, text=True)
        assert proc.returncode == expected_code
        assert json.loads(proc.stdout)["status"] == status
        assert not proc.stderr