File size: 9,445 Bytes
fc3e70a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

"""Phase 14: Verification engine β€” all checks before artifact emission."""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Callable

from .boolean_engine import BooleanNormalForm, normalize
from .ir import Artifact, SemanticIR
from .latin import LatinCanonicalForm, vocabulary
from .rosetta import RosettaMapping
from .subleq import SubleqProgram, SubleqVM
from .token_engine import BooleanTokenStream, round_trip
from .types import FSMState, VerificationError, VerificationState


# ── Check result ──────────────────────────────────────────────────────────────

@dataclass
class CheckResult:
    name: str
    passed: bool
    message: str = ""

    def __repr__(self) -> str:
        status = "βœ“" if self.passed else "βœ—"
        return f"{status} {self.name}: {self.message}"


@dataclass
class VerificationReport:
    checks: list[CheckResult] = field(default_factory=list)
    state: VerificationState = VerificationState.UNVERIFIED

    @property
    def passed(self) -> bool:
        return all(c.passed for c in self.checks)

    def add(self, result: CheckResult) -> None:
        self.checks.append(result)

    def summary(self) -> str:
        lines = [repr(c) for c in self.checks]
        lines.append(f"\nResult: {'VERIFIED' if self.passed else 'REJECTED'}")
        return "\n".join(lines)


# ── Individual checks ─────────────────────────────────────────────────────────

def check_type_correctness(ir: SemanticIR) -> CheckResult:
    for node in ir.nodes:
        if node.operation and node.operation.arity != len(node.operands):
            if node.operation.arity > 0:
                return CheckResult(
                    "type_correctness", False,
                    f"Node {node.id}: arity {node.operation.arity} but {len(node.operands)} operands",
                )
    return CheckResult("type_correctness", True, "all arities match")


def check_geometry(ir: SemanticIR) -> CheckResult:
    for node in ir.nodes:
        if node.geometry and node.operation and node.operation.name == "multiply":
            if len(node.operands) >= 2:
                a = node.operands[0].geometry
                b = node.operands[1].geometry
                if a and b and a.col is not None and b.row is not None:
                    if a.col != b.row:
                        return CheckResult(
                            "geometry", False,
                            f"Matrix dim mismatch: A.col={a.col} β‰  B.row={b.row}",
                        )
    return CheckResult("geometry", True, "all dimensions compatible")


def check_temporal_state(ir: SemanticIR) -> CheckResult:
    transitions = ir.temporal_lock.audit()
    for t in transitions:
        if not t.is_valid():
            return CheckResult(
                "temporal_state", False,
                f"Invalid Ο„ transition: {t.from_tau} β†’ {t.to_tau}",
            )
    return CheckResult("temporal_state", True, f"{len(transitions)} temporal transitions valid")


def check_boolean_normalization(bnf: BooleanNormalForm) -> CheckResult:
    if not bnf.stable:
        bnf.verify_stability()
    if not bnf.stable:
        return CheckResult("boolean_normalization", False, "normalize(normalize(x)) β‰  normalize(x)")
    return CheckResult("boolean_normalization", True, "normalization idempotent")


def check_token_round_trip(stream: BooleanTokenStream) -> CheckResult:
    try:
        from .token_engine import decode_binary, encode_binary
        binary = encode_binary(stream)
        decoded = decode_binary(binary)
        if len(decoded.tokens) != len(stream.tokens):
            return CheckResult("token_round_trip", False,
                               f"Token count mismatch: {len(stream.tokens)} β†’ {len(decoded.tokens)}")
        for orig, dec in zip(stream.tokens, decoded.tokens):
            if orig.token_type != dec.token_type or orig.payload != dec.payload:
                return CheckResult("token_round_trip", False,
                                   f"Token mismatch at pos {orig.position}")
        return CheckResult("token_round_trip", True, "encode/decode invariant holds")
    except Exception as e:
        return CheckResult("token_round_trip", False, str(e))


def check_latin_vocabulary(form: LatinCanonicalForm) -> CheckResult:
    vocab = vocabulary()
    for tok in form.tokens:
        if tok.lexeme not in vocab and tok.lexeme not in ("OPUS",):
            return CheckResult(
                "latin_vocabulary", False,
                f"Lexeme '{tok.lexeme}' not in controlled vocabulary",
            )
    return CheckResult("latin_vocabulary", True, "all lexemes in vocabulary")


def check_rosetta_mapping(mapping: RosettaMapping) -> CheckResult:
    if not mapping.complete:
        unmapped = [t.semantic_id for t in mapping.unmapped]
        return CheckResult("rosetta_mapping", False, f"Unmapped: {unmapped}")
    return CheckResult("rosetta_mapping", True, f"{len(mapping.entries)} entries mapped")


def check_subleq_validity(prog: SubleqProgram) -> CheckResult:
    if not prog.instructions:
        return CheckResult("subleq_validity", False, "Empty SUBLEQ program")
    vm = SubleqVM(max_steps=10_000)
    halts = vm.verify_halts(prog)
    if not halts:
        return CheckResult("subleq_validity", False, "Program does not halt within limit")
    return CheckResult("subleq_validity", True, f"{len(prog.instructions)} instructions, halts")


def check_artifact_provenance(artifact: Artifact, ir: SemanticIR) -> CheckResult:
    if artifact.semantic_root != ir.ir_id:
        return CheckResult(
            "artifact_provenance", False,
            f"Artifact root {artifact.semantic_root} β‰  IR id {ir.ir_id}",
        )
    return CheckResult("artifact_provenance", True, "provenance chain intact")


def check_template_bindings(artifact: Artifact) -> CheckResult:
    if not artifact.template:
        return CheckResult("template_bindings", False, "No template bound to artifact")
    if not artifact.content:
        return CheckResult("template_bindings", False, "Artifact content is empty")
    return CheckResult("template_bindings", True, "template bound and content non-empty")


# ── Verification engine ───────────────────────────────────────────────────────

class Verifier:
    def verify_ir(self, ir: SemanticIR) -> VerificationReport:
        report = VerificationReport(state=VerificationState.VALIDATING)
        report.add(check_type_correctness(ir))
        report.add(check_geometry(ir))
        report.add(check_temporal_state(ir))
        report.state = VerificationState.VERIFIED if report.passed else VerificationState.REJECTED
        return report

    def verify_boolean(self, bnf: BooleanNormalForm) -> VerificationReport:
        report = VerificationReport(state=VerificationState.VALIDATING)
        report.add(check_boolean_normalization(bnf))
        report.state = VerificationState.VERIFIED if report.passed else VerificationState.REJECTED
        return report

    def verify_tokens(self, stream: BooleanTokenStream) -> VerificationReport:
        report = VerificationReport(state=VerificationState.VALIDATING)
        report.add(check_token_round_trip(stream))
        report.state = VerificationState.VERIFIED if report.passed else VerificationState.REJECTED
        return report

    def verify_latin(self, form: LatinCanonicalForm) -> VerificationReport:
        report = VerificationReport(state=VerificationState.VALIDATING)
        report.add(check_latin_vocabulary(form))
        report.state = VerificationState.VERIFIED if report.passed else VerificationState.REJECTED
        return report

    def verify_rosetta(self, mapping: RosettaMapping) -> VerificationReport:
        report = VerificationReport(state=VerificationState.VALIDATING)
        report.add(check_rosetta_mapping(mapping))
        report.state = VerificationState.VERIFIED if report.passed else VerificationState.REJECTED
        return report

    def verify_subleq(self, prog: SubleqProgram) -> VerificationReport:
        report = VerificationReport(state=VerificationState.VALIDATING)
        report.add(check_subleq_validity(prog))
        report.state = VerificationState.VERIFIED if report.passed else VerificationState.REJECTED
        return report

    def verify_artifact(self, artifact: Artifact, ir: SemanticIR) -> VerificationReport:
        report = VerificationReport(state=VerificationState.VALIDATING)
        report.add(check_artifact_provenance(artifact, ir))
        report.add(check_template_bindings(artifact))
        report.state = VerificationState.VERIFIED if report.passed else VerificationState.REJECTED
        return report

    def reject_if_failed(self, report: VerificationReport, stage: FSMState) -> None:
        if not report.passed:
            raise VerificationError(stage, "Verification failed:\n" + report.summary())