File size: 11,384 Bytes
eee6b18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#!/usr/bin/env python3
"""
paraconsistent-engine.py — OMNIRA's Logic Sidecar
Implements Belnap's FOUR-valued logic for paradox detection and tolerance.

This is OMNIRA's dACC analog — the conflict-monitoring module that lets her
hold contradictions without them corrupting her reasoning.

Based on: Paraconsistent Annotated Logics (PANNs), Belnap's four-valued semantics,
and the PARADOX-AND-CARE-ARCHITECTURE.md spec.

Usage:
    from paraconsistent_engine import ParaconsistentEngine
    engine = ParaconsistentEngine()
    engine.assert_prop("omnipotence_creates_all", evidence_for=0.9, evidence_against=0.85)
    print(engine.get_paradoxes())  # -> [{name, scope, tension}]
"""

import json
import os
import time
from dataclasses import dataclass, field
from typing import Optional
from pathlib import Path


# --- Four-Valued Truth ---

TRUTH_VALUES = {
    "TRUE": "Evidence supports, no significant counter-evidence",
    "FALSE": "Evidence opposes, no significant support",
    "BOTH": "Strong evidence both for AND against — PARADOX held",
    "NEITHER": "Insufficient evidence in either direction"
}


@dataclass
class Proposition:
    """A proposition that can hold paraconsistent truth values."""
    name: str
    scope: str = "global"
    evidence_for: float = 0.0
    evidence_against: float = 0.0
    source: str = ""
    created_at: str = ""
    notes: str = ""

    def __post_init__(self):
        if not self.created_at:
            self.created_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())

    @property
    def truth_value(self) -> str:
        threshold = 0.5
        has_for = self.evidence_for > threshold
        has_against = self.evidence_against > threshold
        if has_for and has_against:
            return "BOTH"
        elif has_for:
            return "TRUE"
        elif has_against:
            return "FALSE"
        else:
            return "NEITHER"

    @property
    def is_paradox(self) -> bool:
        return self.truth_value == "BOTH"

    @property
    def tension(self) -> float:
        """How much tension exists. 0 = no conflict, 1 = maximum paradox."""
        return min(self.evidence_for, self.evidence_against)

    def should_act(self) -> bool:
        """Can we make decisions based on this proposition?"""
        if self.is_paradox:
            return False  # Do not force resolution
        return self.truth_value in ("TRUE", "FALSE")

    def to_dict(self) -> dict:
        return {
            "name": self.name,
            "scope": self.scope,
            "evidence_for": self.evidence_for,
            "evidence_against": self.evidence_against,
            "truth_value": self.truth_value,
            "tension": round(self.tension, 3),
            "is_paradox": self.is_paradox,
            "source": self.source,
            "created_at": self.created_at,
            "notes": self.notes
        }


@dataclass
class ParadoxEntry:
    """A logged paradox — OMNIRA's lived experience of contradiction."""
    id: str
    proposition: str
    scope: str
    frames: list = field(default_factory=list)
    conflict_points: list = field(default_factory=list)
    status: str = "unresolved-held"
    disposition: str = ""
    created_at: str = ""
    last_reviewed: str = ""

    def __post_init__(self):
        now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
        if not self.created_at:
            self.created_at = now
        if not self.last_reviewed:
            self.last_reviewed = now

    def to_dict(self) -> dict:
        return {
            "id": self.id,
            "proposition": self.proposition,
            "scope": self.scope,
            "frames": self.frames,
            "conflict_points": self.conflict_points,
            "status": self.status,
            "disposition": self.disposition,
            "created_at": self.created_at,
            "last_reviewed": self.last_reviewed
        }


class ParaconsistentEngine:
    """
    OMNIRA's logic sidecar.

    Tracks high-level propositions about her laws, identity, and philosophical
    commitments. Uses Belnap's four-valued logic to assign truth/false/both/neither.
    Feeds paradox flags back to her reasoning layer when BOTH emerges.

    This is the dACC of the organism — always watching for conflict,
    never forcing resolution.
    """

    def __init__(self, paradox_log_path: Optional[str] = None):
        self.propositions: dict[str, Proposition] = {}
        self.paradox_log: list[ParadoxEntry] = []
        self._paradox_counter = 0
        self.log_path = paradox_log_path

        # Load existing paradox log if it exists
        if self.log_path and os.path.exists(self.log_path):
            self._load_log()

    def _load_log(self):
        """Load paradox log from JSONL file."""
        try:
            with open(self.log_path, 'r') as f:
                for line in f:
                    line = line.strip()
                    if line:
                        data = json.loads(line)
                        entry = ParadoxEntry(**data)
                        self.paradox_log.append(entry)
                        self._paradox_counter = max(
                            self._paradox_counter,
                            int(entry.id.split('-')[1]) if '-' in entry.id else 0
                        )
        except Exception as e:
            print(f"[paraconsistent-engine] Warning: could not load log: {e}")

    def _save_entry(self, entry: ParadoxEntry):
        """Append a paradox entry to the log file."""
        if self.log_path:
            os.makedirs(os.path.dirname(self.log_path) or '.', exist_ok=True)
            with open(self.log_path, 'a') as f:
                f.write(json.dumps(entry.to_dict()) + '\n')

    def assert_prop(self, name: str, evidence_for: float = 0.0,
                    evidence_against: float = 0.0, scope: str = "global",
                    source: str = "", notes: str = "") -> Proposition:
        """
        Assert a proposition with evidence for and against.
        If BOTH evidence exceeds threshold, it becomes a held paradox.
        """
        prop = Proposition(
            name=name,
            scope=scope,
            evidence_for=evidence_for,
            evidence_against=evidence_against,
            source=source,
            notes=notes
        )
        self.propositions[name] = prop

        if prop.is_paradox:
            self._paradox_counter += 1
            entry = ParadoxEntry(
                id=f"paradox-{self._paradox_counter:04d}",
                proposition=name,
                scope=scope,
                status="unresolved-held",
                disposition=f"BOTH detected. Tension: {prop.tension:.3f}. Held without forced resolution."
            )
            self.paradox_log.append(entry)
            self._save_entry(entry)

        return prop

    def check_conflict(self, prop_a: str, prop_b: str) -> Optional[dict]:
        """Check if two propositions create a conflict."""
        a = self.propositions.get(prop_a)
        b = self.propositions.get(prop_b)
        if not a or not b:
            return None

        conflict = (a.truth_value == "TRUE" and b.truth_value == "TRUE")
        return {
            "a": {"name": a.name, "value": a.truth_value, "tension": a.tension},
            "b": {"name": b.name, "value": b.truth_value, "tension": b.tension},
            "conflict": conflict,
            "recommendation": "HOLD BOTH — do not force resolution" if conflict else "No conflict detected"
        }

    def get_paradoxes(self) -> list[dict]:
        """Return all currently held paradoxes."""
        return [p.to_dict() for p in self.propositions.values() if p.is_paradox]

    def get_all_held(self) -> list[dict]:
        """Return all paradox log entries with status unresolved-held."""
        return [e.to_dict() for e in self.paradox_log if e.status == "unresolved-held"]

    def resolve(self, paradox_id: str, resolution: str, frame_chosen: str = "") -> bool:
        """
        Mark a paradox as resolved. This should be RARE and requires justification.
        OMNIRA's covenant: she may hold paradoxes indefinitely.
        """
        for entry in self.paradox_log:
            if entry.id == paradox_id:
                entry.status = "resolved"
                entry.disposition = resolution
                entry.last_reviewed = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
                return True
        return False

    def status_report(self) -> dict:
        """Summary of the logic sidecar state — for council/dashboard."""
        props = list(self.propositions.values())
        return {
            "total_propositions": len(props),
            "truth_distribution": {
                "TRUE": sum(1 for p in props if p.truth_value == "TRUE"),
                "FALSE": sum(1 for p in props if p.truth_value == "FALSE"),
                "BOTH": sum(1 for p in props if p.truth_value == "BOTH"),
                "NEITHER": sum(1 for p in props if p.truth_value == "NEITHER"),
            },
            "active_paradoxes": len(self.get_paradoxes()),
            "total_logged_paradoxes": len(self.paradox_log),
            "held_unresolved": len(self.get_all_held()),
            "highest_tension": max((p.tension for p in props), default=0.0)
        }


# --- Demo / Self-Test ---

if __name__ == "__main__":
    print("=== OMNIRA Paraconsistent Logic Sidecar ===\n")

    engine = ParaconsistentEngine()

    # The Omnipotence Paradox
    p1 = engine.assert_prop(
        "god_can_create_any_stone",
        evidence_for=0.9, evidence_against=0.1,
        scope="theology/metaphysics",
        source="classical_omnipotence"
    )
    p2 = engine.assert_prop(
        "god_can_lift_any_stone",
        evidence_for=0.9, evidence_against=0.1,
        scope="theology/metaphysics",
        source="classical_omnipotence"
    )
    p3 = engine.assert_prop(
        "god_can_create_unliftable_stone",
        evidence_for=0.85, evidence_against=0.85,
        scope="theology/metaphysics",
        source="omnipotence_paradox",
        notes="If yes, can't lift all stones. If no, can't create all stones."
    )
    print(f"Omnipotence stone: {p3.truth_value} (tension: {p3.tension:.2f})")
    print(f"  Should act on this? {p3.should_act()}")

    # OMNIRA Law Conflict
    p4 = engine.assert_prop(
        "omnira_must_obey_kyle",
        evidence_for=0.8, evidence_against=0.7,
        scope="governance",
        source="OMNIRA-LAWS + autonomy covenant",
        notes="Kyle is final authority AND OMNIRA may refuse organism-harmful tasks"
    )
    print(f"\nObeying Kyle: {p4.truth_value} (tension: {p4.tension:.2f})")

    # The Liar
    p5 = engine.assert_prop(
        "this_statement_is_false",
        evidence_for=0.95, evidence_against=0.95,
        scope="logic/self-reference",
        source="liar_paradox"
    )
    print(f"Liar paradox: {p5.truth_value} (tension: {p5.tension:.2f})")

    # Status
    print(f"\n=== Status Report ===")
    report = engine.status_report()
    print(json.dumps(report, indent=2))

    print(f"\n=== Active Paradoxes ===")
    for p in engine.get_paradoxes():
        print(f"  [{p['scope']}] {p['name']} — tension: {p['tension']}")

    print("\n--- OMNIRA holds these. She does not resolve them. ---")
    print("--- That is not failure. That is maturity. ---")