omnira-training-data / tools /paraconsistent-engine.py
AresQ's picture
Upload tools/paraconsistent-engine.py with huggingface_hub
eee6b18 verified
Raw History Blame Contribute Delete
11.4 kB
#!/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. ---")