File size: 9,723 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
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/usr/bin/env python3
"""Data-only JSON adapter for the exact AXIOMESH research backend.

This adapter does not call an LLM, execute proposed Python, or acquire evidence.
Every result concerns the declared finite linear family and trusted input data.
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path
import re
import sys

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT / "src"))

import numpy as np
from axiomesh.core import Capsule, FrozenModel, Memory, close_operators, hole_certificate
from axiomesh.esre_v01 import require_prime

MAX_BYTES = 1_048_576
MAX_DIM = 32
MAX_ROWS = 128
MAX_ACTIONS = 16
MAX_WORD = 256
ACTION_NAME = re.compile(r"[A-Za-z0-9_.+\-]{1,64}\Z")


def integer(value, label, low=0, high=250):
    if type(value) is not int or not low <= value <= high:
        raise ValueError(f"{label} must be an integer in {low}..{high}")
    return value


def keys(obj, required, optional=()):
    if not isinstance(obj, dict):
        raise ValueError("expected a JSON object")
    missing, extra = set(required) - obj.keys(), obj.keys() - set(required) - set(optional)
    if missing or extra:
        raise ValueError(f"object keys invalid: missing={sorted(missing)}, extra={sorted(extra)}")


def field(value):
    p = integer(value, "field p", 2, 251)
    require_prime(p)
    return p


def rows(value, label, p, width=None, minimum=0):
    if not isinstance(value, list) or not minimum <= len(value) <= MAX_ROWS:
        raise ValueError(f"{label}: expected {minimum}..{MAX_ROWS} rows")
    if width is None:
        if not value or not isinstance(value[0], list):
            raise ValueError(f"{label}: a nonempty matrix is required")
        width = integer(len(value[0]), f"{label} width", 1, MAX_DIM)
    for row in value:
        if not isinstance(row, list) or len(row) != width:
            raise ValueError(f"{label}: matrix width mismatch")
        for entry in row:
            integer(entry, f"{label} entry", 0, p - 1)
    return np.asarray(value, dtype=np.int64).reshape(len(value), width)


def operators(value, p, width):
    if not isinstance(value, dict) or len(value) > MAX_ACTIONS:
        raise ValueError(f"operators: expected at most {MAX_ACTIONS} actions")
    result = {}
    for name, data in value.items():
        if not isinstance(name, str) or not ACTION_NAME.fullmatch(name):
            raise ValueError("invalid action name")
        result[name] = rows(data, f"operator {name}", p, width)
        if result[name].shape != (width, width):
            raise ValueError("operators must be square")
    return result


def word(value, ops):
    if not isinstance(value, list) or len(value) > MAX_WORD:
        raise ValueError(f"word: expected at most {MAX_WORD} chronological actions")
    if any(not isinstance(a, str) or a not in ops for a in value):
        raise ValueError("word contains an undeclared action")
    return value


def load_json(path):
    with path.open("rb") as handle:
        data = handle.read(MAX_BYTES + 1)
    if len(data) > MAX_BYTES:
        raise ValueError("JSON input exceeds 1 MiB")
    return json.loads(data)


def envelope(task, status, **values):
    return {
        "format": "axiomesh-agent-response-v1",
        "task": task,
        "status": status,
        "scope": "declared small prime-field linear model; trusted input observations",
        "neural_rsi_demonstrated": False,
        **values,
    }


def recover_and_run(request, root):
    keys(request, ["task", "capsule", "word"])
    relative = request["capsule"]
    if not isinstance(relative, str) or not 1 <= len(relative) <= 256 or Path(relative).is_absolute():
        raise ValueError("capsule must be a repository-relative JSON path")
    path = (root / relative).resolve()
    if not path.is_relative_to(root.resolve()) or path.suffix.lower() != ".json":
        raise ValueError("capsule must remain inside the repository")
    obj = load_json(path)
    if not isinstance(obj, dict) or "program" not in obj or "memory" not in obj:
        raise ValueError("capsule requires program and memory objects")
    program, memory = obj["program"], obj["memory"]
    keys(program, ["p", "rank", "operators", "query"])
    keys(memory, ["p", "rank", "shares"])
    p = field(program["p"])
    rank = integer(program["rank"], "rank", 1, MAX_DIM)
    if field(memory["p"]) != p or integer(memory["rank"], "memory rank", 1, MAX_DIM) != rank:
        raise ValueError("program and memory fields/ranks disagree")
    ops = operators(program["operators"], p, rank)
    rows(program["query"], "query", p, rank, 1)
    actions = word(request["word"], ops)
    shares = memory["shares"]
    if not isinstance(shares, dict) or len(shares) > MAX_ROWS:
        raise ValueError("shares: expected at most 128 points")
    for point, value in shares.items():
        if not isinstance(point, str) or not point.isascii() or not point.isdigit():
            raise ValueError("share points must be canonical decimal strings")
        if str(int(point)) != point:
            raise ValueError("share points must be canonical decimal strings")
        integer(int(point), "share point", 0, p - 1)
        integer(value, "share value", 0, p - 1)
    status, seed = Capsule.from_json(memory).recover()
    if status != "exact":
        return envelope(request["task"], status, output=None, source_state_used=False)
    model = FrozenModel.from_json(program, seed=seed)
    return envelope(request["task"], "exact", output=model.run(actions).tolist(),
                    quotient_rank=rank, source_state_used=False,
                    damage_contract="known erasures; no general corruption certificate")


def linear_request(request):
    task = request["task"]
    optional = ["product_budget"] if task == "revalidate" else ["product_budget", "erasure_budget", "word"]
    keys(request, ["task", "p", "query", "operators", "memory"], optional)
    p = field(request["p"])
    query = rows(request["query"], "query", p, minimum=1)
    ops = operators(request["operators"], p, query.shape[1])
    keys(request["memory"], ["matrix", "rhs"])
    matrix = rows(request["memory"]["matrix"], "memory", p, query.shape[1])
    rhs = request["memory"]["rhs"]
    if not isinstance(rhs, list) or len(rhs) != len(matrix):
        raise ValueError("memory rhs length mismatch")
    for value in rhs:
        integer(value, "memory rhs", 0, p - 1)
    memory = Memory(matrix, np.asarray(rhs, dtype=np.int64), p)
    budget = integer(request.get("product_budget", MAX_DIM * MAX_ACTIONS), "product budget", 0, 512)
    closure = close_operators(query, ops, p, product_budget=budget)
    status, seed, _ = memory.recall(closure.basis)
    missing = None if status == "inconsistent" else memory.supplement(closure.basis).tolist()
    common = {
        "quotient_rank": closure.rank,
        "row_operator_products": closure.row_operator_products,
        "required_extra_scalar_observations": None if missing is None else len(missing),
        "suggested_observation_rows": missing,
        "observations_acquired": 0,
        "certificate": hole_certificate(closure, memory),
    }
    if task == "revalidate":
        return envelope(task, status, **common)
    erasures = integer(request.get("erasure_budget", 0), "erasure budget", 0, 32)
    actions = word(request.get("word", []), ops)
    if status != "exact" or closure.rank == 0:
        outcome = "zero_observable" if status == "exact" else status
        return envelope(task, outcome, output=None, **common)
    model = closure.compile(seed)
    capsule = Capsule.encode(seed, p, erasures)
    return envelope(task, "committed", output=model.run(actions).tolist(),
                    capsule={"format": "axiomesh-frozen-v0.2",
                             "program": model.json_object(include_seed=False),
                             "memory": capsule.json_object()}, **common)


def dispatch(request, root=ROOT):
    if not isinstance(request, dict) or request.get("task") not in {"revalidate", "compile", "recover_and_run"}:
        raise ValueError("task must be revalidate, compile, or recover_and_run")
    if request["task"] == "recover_and_run":
        return recover_and_run(request, root)
    return linear_request(request)


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    source = parser.add_mutually_exclusive_group()
    source.add_argument("--request", type=Path, help="read a JSON request file; default: stdin")
    source.add_argument("--schema", action="store_true", help="print the request JSON Schema")
    source.add_argument("--capabilities", action="store_true", help="print machine-readable capabilities")
    args = parser.parse_args(argv)
    try:
        if args.schema or args.capabilities:
            name = "agent_request.schema.json" if args.schema else "AGENT_CAPABILITIES.json"
            result = load_json(ROOT / name)
        else:
            if args.request:
                request = load_json(args.request)
            else:
                data = sys.stdin.buffer.read(MAX_BYTES + 1)
                if len(data) > MAX_BYTES:
                    raise ValueError("JSON input exceeds 1 MiB")
                request = json.loads(data)
            result = dispatch(request)
        print(json.dumps(result, ensure_ascii=False, allow_nan=False))
        return 2 if result.get("status") in {"ambiguous", "inconsistent", "zero_observable"} else 0
    except (OSError, ValueError, KeyError, TypeError, RuntimeError, OverflowError) as exc:
        print(json.dumps(envelope("request", "error", detail=str(exc)), allow_nan=False))
        return 1


if __name__ == "__main__":
    raise SystemExit(main())