File size: 9,041 Bytes
edd15df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate the prepared files locally; no network calls or general proof claims."""
from fractions import Fraction
import hashlib
import json
import math
from pathlib import Path
import re
from urllib.parse import unquote

ROOT = Path(__file__).resolve().parents[1]

def no_constant(value):
    raise ValueError(f"Nonstandard JSON constant: {value}")

def unique_pairs(pairs):
    result = {}
    for key,value in pairs:
        if key in result: raise ValueError(f"Duplicate JSON key: {key}")
        result[key]=value
    return result

def loads(text):
    return json.loads(text,parse_constant=no_constant,object_pairs_hook=unique_pairs)

def load(path):
    return loads(path.read_text(encoding="utf-8"))

def fail(message):
    raise ValueError(message)

def require(condition, message):
    if not condition: fail(message)

def safe_path(base, relative):
    path=(base/relative).resolve()
    require(path.is_relative_to(base.resolve()),f"Path escapes root: {relative}")
    require(path.is_file(),f"Missing file: {relative}")
    return path

def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()

def matches(value, kind):
    if kind=="boolean": return isinstance(value,bool)
    if kind=="integer": return isinstance(value,int) and not isinstance(value,bool)
    if kind=="number": return isinstance(value,(float,int)) and not isinstance(value,bool) and math.isfinite(value)
    if kind=="string": return isinstance(value,str)
    if kind=="object": return isinstance(value,dict)
    if kind=="null": return value is None
    if kind=="array": return isinstance(value,list)
    if kind.startswith("array["):
        return isinstance(value,list) and all(matches(v,kind[6:-1]) for v in value)
    fail(f"Unsupported schema kind: {kind}")

def verify_manifest(base):
    manifest=safe_path(base,"SHA256SUMS.txt")
    names=set()
    for line in manifest.read_text(encoding="utf-8").splitlines():
        expected, relative=line.split("  ",1)
        require(relative not in names,f"Duplicate manifest path: {relative}")
        names.add(relative)
        require(sha(safe_path(base,relative))==expected,f"Hash mismatch: {relative}")
    actual={p.relative_to(base).as_posix() for p in base.rglob("*") if p.is_file() and p!=manifest and "__pycache__" not in p.parts and p.suffix!=".pyc"}
    require(actual==names,f"Manifest coverage mismatch: missing={sorted(actual-names)}, extra={sorted(names-actual)}")
    return len(names)

def polynomial(coeffs, z):
    return sum((Fraction(c)*z**i for i,c in enumerate(coeffs)), Fraction(0))

def main():
    schema=load(ROOT/"DATA_SCHEMA.json")
    configs=schema["configurations"]
    require(set(configs)=={"tomography_exact","suite_metrics","joint_loss_log_grid","joint_loss_survival_grid","tomography_conditioning","claims","research_sections"},"Unexpected configurations")
    rows_by_config={}
    total=0
    for name,config in configs.items():
        require(config["split"]=="test",f"Unexpected split for {name}")
        text=safe_path(ROOT,config["path"]).read_text(encoding="utf-8")
        rows=[loads(line) for line in text.splitlines()]
        require(len(rows)==config["rows"],f"Row count mismatch: {name}")
        ids=set()
        for row in rows:
            require(set(row)==set(config["fields"]),f"Field mismatch: {name}")
            for key,kind in config["fields"].items():
                require(matches(row[key],kind),f"Type mismatch: {name}.{key}")
                if key.endswith("_json"): loads(row[key])
            require(row["record_id"] not in ids,f"Duplicate record ID: {name}")
            ids.add(row["record_id"])
            safe_path(ROOT,row["source_file"])
        for source in config["source_files"]:
            require(sha(safe_path(ROOT,source["path"]))==source["sha256"],f"Source hash mismatch: {source['path']}")
        rows_by_config[name]=rows
        total+=len(rows)
    require(total==schema["total_rows"],"Total row count mismatch")

    response_checks=0
    original=load(ROOT/"research/v3/results/tomography_check.json")
    for index,row in enumerate(rows_by_config["tomography_exact"]):
        fixture=original["fixtures"][index]
        require(all(row[k]==v for k,v in fixture.items()),f"Tomography source changed: {index}")
        m=row["m"]
        require(row["rank"]==2*m,"Unexpected interpolation rank")
        require(len(row["t"])==len(row["r"])==m,"Tomography mode length")
        require(len(row["probe_z"])==len(row["probe_response_exact"])==2*m,"Tomography response length")
        t=list(map(Fraction,row["t"])); r=list(map(Fraction,row["r"]))
        require(all(v>0 for v in t+r) and len(set(t))==m and t==sorted(t),"Invalid visible measure")
        z_values=list(map(Fraction,row["probe_z"]))
        require(len(set(z_values))==2*m and all(z>0 for z in z_values),"Invalid probes")
        require(len(row["P_ascending"])==m and len(row["Q_ascending"])==m+1 and Fraction(row["Q_ascending"][-1])==1,"Invalid rational-function degrees")
        for field in ["t","r","probe_z","P_ascending","Q_ascending","probe_response_exact"]:
            require(all(str(Fraction(value))==value for value in row[field]),f"Noncanonical Fraction: {field}")
        # Two independent representations must match on every probe.
        for z,expected in zip(z_values,row["probe_response_exact"]):
            spectral=sum((w*v/(z+v) for v,w in zip(t,r)),Fraction(0))
            quotient=polynomial(row["P_ascending"],z)/polynomial(row["Q_ascending"],z)
            require(spectral==quotient==Fraction(expected),"Exact response mismatch")
            response_checks+=1

    ledger=load(ROOT/"CLAIM_LEDGER.json")
    claims=ledger["claims"]
    require(len(claims)==len(rows_by_config["claims"]),"Claim export count mismatch")
    tex=(ROOT/"research/Avenyra_Geometric_Memory_Physics.tex").read_text(encoding="utf-8")
    report_labels=set(re.findall(r"\\label\{([^}]+)\}",tex))
    evidence_count=0
    for claim,row in zip(claims,rows_by_config["claims"]):
        require(claim["id"]==row["record_id"] and claim["statement"]==row["statement"],"Claim export mismatch")
        ref=claim["report_reference"]
        for key in ["section_label","statement_label"]:
            if ref.get(key): require(ref[key] in report_labels,f"Missing report anchor: {ref[key]}")
        for label in ref.get("equation_labels",[]): require(label in report_labels,f"Missing equation: {label}")
        for evidence in claim["evidence"]:
            safe_path(ROOT,evidence["path"])
            evidence_count+=1

    sections=rows_by_config["research_sections"]
    for row in sections:
        require(row["text_latex"] in tex,"Section text changed")
        require(row["title_latex"]==re.match(r"\\section\{([^}\n]+)\}",row["text_latex"]).group(1),"Section title mismatch")

    import yaml
    card=(ROOT/"README.md").read_text(encoding="utf-8")
    require(card.startswith("---\n"),"Missing card front matter")
    metadata=yaml.safe_load(card.split("---",2)[1])
    require("license" not in metadata,"Unexpected license grant metadata")
    listed={c["config_name"]:c for c in metadata["configs"]}
    require(set(listed)==set(configs),"Metadata configuration mismatch")
    require([c["config_name"] for c in metadata["configs"] if c.get("default")] == ["claims"],"Unexpected default")
    for name,config in configs.items():
        require(listed[name]["data_files"]==[{"split":"test","path":config["path"]}],f"Metadata path mismatch: {name}")
    require(total<1000 and metadata["size_categories"]==["n<1K"],"Size category mismatch")

    markdown_links=0
    for path in ROOT.glob("*.md"):
        text=path.read_text(encoding="utf-8")
        # Check actual link destinations, not bare source filenames or bibliography URLs.
        for target in re.findall(r"\]\(([^)]+)\)",text):
            target=target.split(" \",",1)[0]
            if target.startswith(("https://","http://","mailto:","#")): continue
            target=unquote(target.split("#",1)[0])
            require(bool(target),f"Empty Markdown path: {path.name}")
            safe_path(path.parent,target)
            markdown_links+=1
        require(not re.search(r"/workspace/|libfile_|sandbox:|OPENAI_LIBRARY",text),f"Private runtime detail: {path.name}")
    for path in ROOT.rglob("*.py"):
        compile(path.read_text(encoding="utf-8"),str(path),"exec")

    core_hashes=verify_manifest(ROOT/"research")
    release_hashes=verify_manifest(ROOT)
    print(json.dumps({"status":"passed","configurations":len(configs),"export_rows":total,"exact_probe_response_checks":response_checks,"claims":len(claims),"claim_evidence_paths":evidence_count,"markdown_links":markdown_links,"research_manifest_entries":core_hashes,"release_manifest_entries":release_hashes,"remote_hub_viewer_tested":False},indent=2))

if __name__=="__main__": main()