enver commited on
Commit
e86be6b
·
verified ·
1 Parent(s): d740c22

tools: add core/mantiq_engine.py

Browse files
Files changed (1) hide show
  1. tools/core/mantiq_engine.py +271 -0
tools/core/mantiq_engine.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ mantiq_engine.py
4
+
5
+ AynEngine AI Coding Edition: Classical Arabic Logic (Manṭiq) & Morphology (Ishtiqāq) Engine.
6
+
7
+ Grounding Authorities:
8
+ - Abū Ḥāmid al-Ghazālī: Miʿyār al-ʿIlm fī Fann al-Manṭiq & Miḥakk al-Naẓar
9
+ - Fakhr al-Dīn al-Rāzī: Al-Mulakhkhaṣ fī al-Ḥikmah wa-al-Manṭiq
10
+ - Al-Khalīl ibn Aḥmad al-Farāhīdī: Kitāb al-ʿAyn (Root Permutations & Primitive Decomposition)
11
+ - Ibn Manẓūr: Lisān al-ʿArab (Exhaustive Morphological State Coverage)
12
+ - Al-Rāghib al-Iṣfahānī: Al-Mufradāt (Ontological Teleology & Distinction of Essence vs Accident)
13
+ """
14
+
15
+ from dataclasses import dataclass, field
16
+ from enum import Enum
17
+ from pathlib import Path
18
+ from typing import Dict, List, Any, Optional, Set, Tuple
19
+ import json
20
+ import re
21
+
22
+
23
+ class MantiqCategory(str, Enum):
24
+ """Classical Aristotelian-Ghazalian Epistemic Classifications."""
25
+ TASAWWUR = "tasawwur" # Conceptualization / Primitive Definition (Indivisible Essence)
26
+ TASDIQ = "tasdiq" # Judgment / Proposition / Assertive Relation
27
+ DHATI = "dhati" # Inherent / Essential / Immutable Property
28
+ ARADI = "aradi" # Accidental / Transient / Mutable State
29
+
30
+
31
+ class FallacyType(str, Enum):
32
+ """Classical Logical Fallacies in Software Architecture."""
33
+ DAWR = "dawr" # Circular Dependency / Mutual Deadlock (A requires B, B requires A)
34
+ TASALSUL = "tasalsul" # Infinite Regress / Unbounded Recursion / Memory Leak without Base Case
35
+ MAJAZ_MUKHIL = "majaz_mukhil" # Leaky Abstraction (Metaphor corrupting runtime machine reality)
36
+ TANAQUD = "tanaqud" # Contradiction / Representable Illegal States in Type System
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class MorphologicalRoot:
41
+ """Tri-consonantal classical root representing irreducible atomic primitive."""
42
+ root_letters: str # e.g., 'ح-ف-ظ'
43
+ lemma_title: str # e.g., 'حفظ'
44
+ semantic_core: str # e.g., 'Preservation, immutability, guarding against corruption'
45
+ software_analog: str # e.g., 'Immutable buffer, checksum guard, persistent memory'
46
+ governing_lexicon: str # e.g., 'Kitāb al-ʿAyn / Lisān al-ʿArab'
47
+
48
+
49
+ @dataclass
50
+ class EpistemicCritique:
51
+ """Logical assessment under Ghazalian Manṭiq rules."""
52
+ category: MantiqCategory
53
+ axiom_citation: str
54
+ is_valid: bool
55
+ detected_fallacies: List[FallacyType] = field(default_factory=list)
56
+ remediation: str = ""
57
+
58
+
59
+ class AynMantiqEngine:
60
+ """
61
+ Epistemic Logic & Morphology Evaluator.
62
+ Disproves software architecture fallacies (Dawr, Tasalsul, Majāz Mukhil)
63
+ and grounds code entities in tri-consonantal classical roots.
64
+ """
65
+
66
+ # Classical Software Tri-Consonantal Root Ontology
67
+ ROOT_ONTOLOGY: Dict[str, MorphologicalRoot] = {
68
+ "حفظ": MorphologicalRoot(
69
+ root_letters="ح-ف-ظ",
70
+ lemma_title="حفظ",
71
+ semantic_core="الصيانة والملازمة ودفع الفساد والنسيان",
72
+ software_analog="Immutability, persistent storage, memory retention, checksum integrity",
73
+ governing_lexicon="Kitāb al-ʿAyn & Lisān al-ʿArab"
74
+ ),
75
+ "قفل": MorphologicalRoot(
76
+ root_letters="ق-ف-ل",
77
+ lemma_title="قفل",
78
+ semantic_core="الإمساك والتضييق والامتناع عن الدخول إلا بإذن",
79
+ software_analog="Mutual exclusion, mutex lock, semaphore barrier, atomic CAS barrier",
80
+ governing_lexicon="Asās al-Balāghah"
81
+ ),
82
+ "نقل": MorphologicalRoot(
83
+ root_letters="ن-ق-ل",
84
+ lemma_title="نقل",
85
+ semantic_core="تحويل الشيء من موضع إلى موضع بتمامه",
86
+ software_analog="Data transport, packet serialization, zero-copy socket streaming",
87
+ governing_lexicon="Lisān al-ʿArab"
88
+ ),
89
+ "عقد": MorphologicalRoot(
90
+ root_letters="ع-ق-د",
91
+ lemma_title="عقد",
92
+ semantic_core="الربط والإحكام بين طرفين بحيث لا ينفك أحدهما إلا بفسخ",
93
+ software_analog="API contract, interface binding, cryptographic transaction consensus",
94
+ governing_lexicon="Al-Mufradāt"
95
+ ),
96
+ "حسب": MorphologicalRoot(
97
+ root_letters="ح-س-ب",
98
+ lemma_title="حسب",
99
+ semantic_core="العدّ والتقدير وتحديد المقدار المنضبط بلا زيادة ولا نقصان",
100
+ software_analog="Computational budget, rate-limiting tokens, algorithmic complexity bound",
101
+ governing_lexicon="Al-Mufradāt"
102
+ ),
103
+ "رتب": MorphologicalRoot(
104
+ root_letters="ر-ت-ب",
105
+ lemma_title="رتب",
106
+ semantic_core="الاستقرار في المنزلة والتقديم والتأخير المنضبط",
107
+ software_analog="Strict total ordering, monotonic priority queue, sequential execution",
108
+ governing_lexicon="Asās al-Balāghah"
109
+ ),
110
+ "ميز": MorphologicalRoot(
111
+ root_letters="م-ي-ز",
112
+ lemma_title="ميز",
113
+ semantic_core="فصل الشيء عن غيره بخصيصة ذاتية تمنع الاشتباه",
114
+ software_analog="Sum types, tagged unions, exhaustive pattern matching, type discrimination",
115
+ governing_lexicon="Kitāb al-ʿAyn"
116
+ ),
117
+ "سلم": MorphologicalRoot(
118
+ root_letters="س-ل-م",
119
+ lemma_title="سلم",
120
+ semantic_core="الخلو من الآفات والعيوب والأمن من التلف",
121
+ software_analog="Fault tolerance, graceful degradation, absence of undefined behavior",
122
+ governing_lexicon="Lisān al-ʿArab"
123
+ ),
124
+ "عمل": MorphologicalRoot(
125
+ root_letters="ع-م-ل",
126
+ lemma_title="عمل",
127
+ semantic_core="إحداث الأثر في الغير بمقتضى السلطة والاقتضاء",
128
+ software_analog="Syntactic governance (ʿĀmil/Maʿmūl), executor pipeline, runtime evaluation",
129
+ governing_lexicon="Al-Kitāb of Sībawayh"
130
+ ),
131
+ "حكم": MorphologicalRoot(
132
+ root_letters="ح-ك-م",
133
+ lemma_title="حكم",
134
+ semantic_core="الفصل القاطع والمنع من الفساد والإتقان",
135
+ software_analog="Validation predicate, invariant assertion, policy enforcement",
136
+ governing_lexicon="Al-Mufradāt"
137
+ )
138
+ }
139
+
140
+ def __init__(self, data_root: Optional[Path] = None):
141
+ self.data_root = data_root or Path("/home/absolut7/.gemini/antigravity/scratch/translation_engine_framework/data")
142
+ self.miyar_path = self.data_root / "texts/ghazali/miyar_al_ilm.txt"
143
+ self.mihakk_path = self.data_root / "texts/ghazali/mihakk_al_nazar.txt"
144
+ self.mufradat_path = self.data_root / "texts/raghib/al_mufradat_fi_gharib_al_quran.txt"
145
+ self.lisan_path = self.data_root / "lisanclean.json"
146
+
147
+ def resolve_roots_for_concept(self, query_text: str) -> List[MorphologicalRoot]:
148
+ """Maps an engineering prompt or architectural concept to relevant classical roots."""
149
+ q_lower = query_text.lower()
150
+ matched_roots: List[MorphologicalRoot] = []
151
+
152
+ mappings = {
153
+ ("lock", "mutex", "concurrency", "thread", "atomic", "sync"): "قفل",
154
+ ("immutable", "pure", "cache", "buffer", "persist", "save"): "حفظ",
155
+ ("transport", "network", "socket", "stream", "packet", "p2p"): "نقل",
156
+ ("contract", "interface", "protocol", "binding", "transaction"): "عقد",
157
+ ("limit", "token", "budget", "meter", "rate", "throttle"): "حسب",
158
+ ("order", "priority", "queue", "sort", "sequence"): "رتب",
159
+ ("type", "discriminate", "variant", "match", "enum"): "ميز",
160
+ ("error", "fault", "safe", "recover", "resilient"): "سلم",
161
+ ("eval", "execute", "governor", "call", "dispatch"): "عمل",
162
+ ("validate", "guard", "assert", "invariant", "rule"): "حكم"
163
+ }
164
+
165
+ for keywords, root_key in mappings.items():
166
+ if any(k in q_lower for k in keywords):
167
+ if root_key in self.ROOT_ONTOLOGY:
168
+ matched_roots.append(self.ROOT_ONTOLOGY[root_key])
169
+
170
+ # Default to essential roots if no specific domain matched
171
+ if not matched_roots:
172
+ matched_roots.append(self.ROOT_ONTOLOGY["حفظ"])
173
+ matched_roots.append(self.ROOT_ONTOLOGY["عقد"])
174
+
175
+ return matched_roots
176
+
177
+ def audit_logic_fallacies(self, code: str) -> EpistemicCritique:
178
+ """
179
+ Audits code for Classical Arabic Logic fallacies:
180
+ - Dawr (Cycles / mutual deadlocks)
181
+ - Tasalsul (Unbounded loops / infinite recursions)
182
+ - Majāz Mukhil (Leaky abstractions / raw exceptions exposed)
183
+ - Tanāquḍ (Illegal state contradictions)
184
+ """
185
+ fallacies: List[FallacyType] = []
186
+ remediations: List[str] = []
187
+
188
+ # 1. Check for Dawr (Circular references or bidirectional mutual locks)
189
+ if re.search(r"self\.\w+\s*=\s*\w+.*self", code, re.DOTALL):
190
+ fallacies.append(FallacyType.DAWR)
191
+ remediations.append("Eliminate circular self-binding (Dawr). Enforce unidirectional hierarchy.")
192
+
193
+ # 2. Check for Tasalsul (Unbounded recursive call without base condition check)
194
+ func_defs = re.findall(r"def\s+(\w+)\s*\((.*?)\):", code)
195
+ for func_name, _ in func_defs:
196
+ body_match = re.search(rf"def\s+{func_name}\b.*?(?=\ndef|\Z)", code, re.DOTALL)
197
+ if body_match:
198
+ body = body_match.group(0)
199
+ # If recursive call exists without a return/if guard
200
+ if re.search(rf"\b{func_name}\s*\(", body[len(func_name)+10:]) and "if " not in body:
201
+ fallacies.append(FallacyType.TASALSUL)
202
+ remediations.append(f"Recursive routine '{func_name}' lacks explicit base termination guard (Tasalsul).")
203
+
204
+ # 3. Check for Majāz Mukhil (Leaky Abstraction: bare Exception catching or generic 'data'/'manager')
205
+ if re.search(r"except\s*:", code) or re.search(r"except\s+Exception\s*:", code):
206
+ fallacies.append(FallacyType.MAJAZ_MUKHIL)
207
+ remediations.append("Bare/generic exception handler violates abstraction integrity (Majāz Mukhil). Use explicit domain error taxonomy.")
208
+
209
+ if re.search(r"\bclass\s+\w*(Manager|Helper|Data|Processor)\b", code):
210
+ fallacies.append(FallacyType.MAJAZ_MUKHIL)
211
+ remediations.append("Amorphous class nomenclature ('Manager'/'Helper'/'Data') corrupts ontological essence. Use precise teleological naming.")
212
+
213
+ # 4. Check for Tanāquḍ (Contradictory state representation, e.g. Optional attributes with conflicting booleans)
214
+ if "is_valid: bool" in code and "error_message: Optional[str]" in code:
215
+ remediations.append("Separate success and failure variants into distinct algebraic types (Al-Mīz) to make invalid combinations unrepresentable.")
216
+
217
+ is_valid = len(fallacies) == 0
218
+ citation = "Al-Ghazālī: Miʿyār al-ʿIlm (Bāb Madāriq al-Qiyās wa Mabāḥith al-Dalālāt)"
219
+
220
+ return EpistemicCritique(
221
+ category=MantiqCategory.TASDIQ,
222
+ axiom_citation=citation,
223
+ is_valid=is_valid,
224
+ detected_fallacies=fallacies,
225
+ remediation="; ".join(remediations) if remediations else "Code satisfies classical non-contradiction and acyclic invariants."
226
+ )
227
+
228
+ def generate_mantiq_scratchpad(self, prompt: str, target_language: str = "python") -> str:
229
+ """
230
+ Generates the formal <ayn_mantiq> Chain-of-Thought reasoning block
231
+ derived from Ghazalian Manṭiq and Farahidian Ishtiqāq.
232
+ """
233
+ roots = self.resolve_roots_for_concept(prompt)
234
+ primary_root = roots[0]
235
+ secondary_root = roots[1] if len(roots) > 1 else self.ROOT_ONTOLOGY["عقد"]
236
+
237
+ scratchpad = f"""<ayn_mantiq>
238
+ 🏛️ AYN-ENGINE EPISTEMIC CHAIN-OF-THOUGHT (MANṬIQ & ISHTIQĀQ)
239
+ Target Architecture: {target_language.upper()}
240
+ Problem Specification: "{prompt}"
241
+
242
+ 1. ISHTIQĀQ & MORPHOLOGICAL ROOTS (Kitāb al-ʿAyn & Lisān al-ʿArab):
243
+ • Primary Root: [{primary_root.root_letters}] ({primary_root.lemma_title})
244
+ - Classical Significance: {primary_root.semantic_core}
245
+ - Software Analog: {primary_root.software_analog}
246
+ • Secondary Root: [{secondary_root.root_letters}] ({secondary_root.lemma_title})
247
+ - Classical Significance: {secondary_root.semantic_core}
248
+ - Software Analog: {secondary_root.software_analog}
249
+
250
+ 2. TAṢAWWUR: ONTOLOGICAL ESSENCE VS ACCIDENT (Al-Mufradāt: al-Rāghib):
251
+ • Dhāt (Immutable Essence):
252
+ - Permanent domain entities, algebraic sum-types, immutable records, monotonic IDs.
253
+ • 'Araḍ (Transient Accident):
254
+ - I/O buffers, network latency, retry counts, eviction cursors.
255
+
256
+ 3. MANṬIQ: FALLACY ELIMINATION & PROOF THEORY (Miʿyār al-ʿIlm: al-Ghazālī):
257
+ • Dafʿ al-Dawr (Zero Circularity):
258
+ - Strict dependency hierarchy: Governor layer -> Runtime evaluator -> Immutable record.
259
+ - Never allow cyclic callbacks or bidirectional mutations.
260
+ • Dafʿ al-Tasalsul (Zero Unbounded Regress):
261
+ - Explicit bounded capacity, deterministic timeout bounds, guaranteed loop termination.
262
+ • 'Adam al-Tanāquḍ (Non-Contradiction):
263
+ - Illegal states made unrepresentable in the type system.
264
+ - Exhaustive state discrimination; zero unhandled match arms.
265
+
266
+ 4. SYNTACTIC GOVERNANCE & CONTRACTS (Al-Kitāb of Sībawayh):
267
+ • 'Āmil (The Governor): Controller / Engine entrypoint holding immutable execution context.
268
+ • Ma'mūl (The Governed): Pure domain data types subjected to non-destructive transformation.
269
+ • Strict Static Typing: Complete type annotations, zero 'Any' escape hatches, strict return contracts.
270
+ </ayn_mantiq>"""
271
+ return scratchpad