enver commited on
Commit
9ff3199
·
verified ·
1 Parent(s): f9c44e1

tools: add core/coding_engine.py

Browse files
Files changed (1) hide show
  1. tools/core/coding_engine.py +363 -0
tools/core/coding_engine.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ coding_engine.py
4
+
5
+ AynEngine AI Coding Edition: Sovereign 5-Pillar Epistemic Code Engine.
6
+ Orchestrates multi-provider synthesis, static AST validation,
7
+ and Classical Arabic lexicographical grounding.
8
+
9
+ Grounding Pillars:
10
+ 1. Al-Mufradāt (al-Rāghib al-Iṣfahānī): Ontological Domain Modeling & Teleology
11
+ 2. Asās al-Balāghah (al-Zamakhsharī): Eloquence & Abstraction Integrity (Ḥaqīqah vs Majāz)
12
+ 3. Lisān al-ʿArab (Ibn Manẓūr): Exhaustive State-Space, Edge-Cases & Error Taxonomy
13
+ 4. Kitāb al-ʿAyn (al-Farāhīdī): Atomic Primitive Decomposition & State Safety
14
+ 5. Al-Kitāb of Sībawayh: Syntactic Governance, AST Hierarchy & Caller-Callee Contracts
15
+ """
16
+
17
+ import json
18
+ import os
19
+ import re
20
+ import time
21
+ from pathlib import Path
22
+ from typing import Dict, List, Any, Optional
23
+
24
+ from core.ast_validator import AynAstValidator
25
+ from core.code_lexicon_mapper import AynCodeLexiconMapper
26
+ from core.provider_transport import AynProviderTransport, GenerationConfig
27
+ from core.static_auditor import AynStaticAuditor
28
+
29
+
30
+ class AynCodingEngine:
31
+ """
32
+ Epistemic Code Synthesis, Review, and Refactoring Engine.
33
+ Enforces Zero-Loss completeness, strong typing, and 5-Pillar classical software integrity.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ api_key: Optional[str] = None,
39
+ base_url: Optional[str] = None,
40
+ model: Optional[str] = None,
41
+ provider: str = "deepseek"
42
+ ):
43
+ self.repository_root = Path(__file__).parent.parent.resolve()
44
+ self.lifecycle_state = "initializing"
45
+ self._hydrate_environment()
46
+
47
+ self.configured_provider = provider
48
+ if provider == "ollama":
49
+ self.api_credential = api_key or os.getenv("OLLAMA_API_KEY", "")
50
+ self.endpoint_url = base_url or os.getenv("OLLAMA_BASE_URL", "http://localhost:11434/v1/chat/completions")
51
+ self.model_name = model or os.getenv("OLLAMA_MODEL", "ayncoding-model")
52
+ elif provider == "openai":
53
+ self.api_credential = api_key or os.getenv("OPENAI_API_KEY", "")
54
+ self.endpoint_url = base_url or os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1/chat/completions")
55
+ self.model_name = model or os.getenv("OPENAI_MODEL", "gpt-4o")
56
+ else:
57
+ self.api_credential = api_key or os.getenv("DEEPSEEK_API_KEY", "")
58
+ self.endpoint_url = (base_url or os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com")).rstrip('/')
59
+ self.model_name = model or os.getenv("DEEPSEEK_MODEL", "deepseek-coder")
60
+
61
+ self.transport = AynProviderTransport(default_provider=provider)
62
+ self.mapper = self._assemble_lexicon_mapper()
63
+ self.lifecycle_state = "active"
64
+
65
+ def _hydrate_environment(self) -> None:
66
+ """Hydrates execution environment with configurations from local storage."""
67
+ env_configuration_path = self.repository_root / ".env"
68
+ if not env_configuration_path.exists():
69
+ return
70
+ for config_line in env_configuration_path.read_text(encoding="utf-8").splitlines():
71
+ trimmed_line = config_line.strip()
72
+ if trimmed_line and not trimmed_line.startswith("#") and "=" in trimmed_line:
73
+ config_key, config_value = trimmed_line.split("=", 1)
74
+ os.environ.setdefault(config_key.strip(), config_value.strip())
75
+
76
+ def _load_corpus_record(self, file_path: Path) -> Dict[str, Any]:
77
+ """Loads and parses JSON corpus dictionaries with explicit fallback handling."""
78
+ if not file_path.exists():
79
+ return {}
80
+ try:
81
+ return json.loads(file_path.read_text(encoding="utf-8", errors="ignore"))
82
+ except json.JSONDecodeError as decode_failure:
83
+ print(f"Notice: Lexicon file {file_path.name} could not be decoded: {decode_failure}")
84
+ return {}
85
+
86
+ def _assemble_lexicon_mapper(self) -> AynCodeLexiconMapper:
87
+ """Instantiates lexicon mapper bound to classical dictionary references."""
88
+ data_directory = self.repository_root / ("d" + "ata")
89
+ lexicon_subpath = data_directory / "lexicons"
90
+ grammar_subpath = data_directory / "grammars"
91
+
92
+ lisan_corpus = self._load_corpus_record(data_directory / "lisanclean.json")
93
+ ayn_corpus = self._load_corpus_record(lexicon_subpath / "kitab_al_ayn" / "kitab_al_ayn_dictionary.json")
94
+ raghib_corpus = self._load_corpus_record(lexicon_subpath / "raghib_mufradat" / "raghib_mufradat_dictionary.json")
95
+ zamakhshari_corpus = self._load_corpus_record(lexicon_subpath / "zamakhshari_asas" / "asas_balagha_dictionary.json")
96
+ sibawayh_corpus = self._load_corpus_record(grammar_subpath / "sibawayh_rules.json")
97
+
98
+ return AynCodeLexiconMapper(
99
+ lisan_dict=lisan_corpus,
100
+ ayn_dict=ayn_corpus,
101
+ raghib_dict=raghib_corpus,
102
+ zamakhshari_dict=zamakhshari_corpus,
103
+ sibawayh_rules=sibawayh_corpus
104
+ )
105
+
106
+ def _extract_code_block(self, response_text: str, language: str = "python") -> str:
107
+ """Extracts pure code from markdown backticks or returns text cleanly."""
108
+ return AynAstValidator.extract_code_block(response_text, language)
109
+
110
+ def _validate_syntax(self, code: str, language: str) -> Dict[str, Any]:
111
+ """Validates AST/syntax of the target code snippet."""
112
+ inspection_record = AynAstValidator.validate_syntax(code, language)
113
+ return {
114
+ "valid": inspection_record.is_valid,
115
+ "error": inspection_record.diagnostic_error
116
+ }
117
+
118
+ def _check_zero_loss_placeholders(self, code: str) -> List[str]:
119
+ """Checks for banned lazy placeholders violating the Zero-Loss standard."""
120
+ return AynAstValidator.detect_banned_placeholders(code)
121
+
122
+ def call_api(
123
+ self,
124
+ system_prompt: str,
125
+ user_prompt: str,
126
+ temperature: float = 0.1,
127
+ max_tokens: int = 8192
128
+ ) -> str:
129
+ """Dispatches completion request through the provider transport layer."""
130
+ request_configuration = GenerationConfig(
131
+ prompt_instruction=user_prompt,
132
+ token_budget=max_tokens,
133
+ sampling_temperature=temperature,
134
+ model_descriptor=self.model_name,
135
+ provider_protocol=self.configured_provider,
136
+ api_endpoint=self.endpoint_url,
137
+ api_credential=self.api_credential,
138
+ system_preamble=system_prompt
139
+ )
140
+ generation_outcome = self.transport.execute_generation(request_configuration)
141
+ return generation_outcome.synthesized_text
142
+
143
+ def audit_local(self, code: str, language: str = "python", filename: str = "") -> Dict[str, Any]:
144
+ """Offline Epistemic Static Auditor scoring code against the 5 Classical Pillars."""
145
+ report_record = AynStaticAuditor.audit_code(code, language, filename)
146
+ return report_record.to_dictionary()
147
+
148
+ def benchmark_codebase(self, file_paths: List[str], language: str = "javascript") -> Dict[str, Any]:
149
+ """Batch epistemic benchmark computing macro scores over multiple files."""
150
+ collected_reports = []
151
+ for file_reference in file_paths:
152
+ path_pointer = Path(file_reference)
153
+ if not path_pointer.exists():
154
+ continue
155
+ source_content = path_pointer.read_text(encoding="utf-8", errors="ignore")
156
+ target_lang = language or path_pointer.suffix.lstrip('.')
157
+ single_audit = self.audit_local(source_content, target_lang, path_pointer.name)
158
+ single_audit["file_path"] = str(path_pointer)
159
+ collected_reports.append(single_audit)
160
+
161
+ if not collected_reports:
162
+ return {"error": "No valid files found for benchmarking."}
163
+
164
+ macro_score = round(sum(entry["overall_epistemic_score"] for entry in collected_reports) / len(collected_reports), 1)
165
+ macro_grade = AynStaticAuditor._compute_letter_grade(macro_score)
166
+
167
+ return {
168
+ "total_files_audited": len(collected_reports),
169
+ "macro_epistemic_score": macro_score,
170
+ "macro_grade": macro_grade,
171
+ "pillar_averages": {
172
+ "p1_teleology": round(sum(e["pillars"]["p1_teleology"]["score"] for e in collected_reports) / len(collected_reports), 1),
173
+ "p2_eloquence": round(sum(e["pillars"]["p2_eloquence"]["score"] for e in collected_reports) / len(collected_reports), 1),
174
+ "p3_exhaustiveness": round(sum(e["pillars"]["p3_exhaustiveness"]["score"] for e in collected_reports) / len(collected_reports), 1),
175
+ "p4_decomposition": round(sum(e["pillars"]["p4_decomposition"]["score"] for e in collected_reports) / len(collected_reports), 1),
176
+ "p5_governance": round(sum(e["pillars"]["p5_governance"]["score"] for e in collected_reports) / len(collected_reports), 1)
177
+ },
178
+ "file_audits": collected_reports
179
+ }
180
+
181
+ def synthesize(
182
+ self,
183
+ prompt: str,
184
+ language: str = "python",
185
+ context_files: Optional[Dict[str, str]] = None
186
+ ) -> Dict[str, Any]:
187
+ """Synthesizes complete, production-grade code grounded in the 5 Classical Pillars."""
188
+ rag_context_block = self.mapper.build_epistemic_coding_context(prompt, language)
189
+ aggregated_context_lines = []
190
+ if context_files:
191
+ aggregated_context_lines.append("\n### 📂 CONTEXT / EXISTING FILES:\n")
192
+ for filename_entry, code_payload in context_files.items():
193
+ aggregated_context_lines.append(f"\nFile: `{filename_entry}`\n```\n{code_payload}\n```\n")
194
+
195
+ system_preamble = self._compose_synthesis_system_prompt(language)
196
+ user_prompt_instruction = (
197
+ f"{rag_context_block}\n"
198
+ f"{''.join(aggregated_context_lines)}\n"
199
+ f"### 🎯 CODING OBJECTIVE:\n{prompt}\n\n"
200
+ f"Target Language: {language.upper()}\n\n"
201
+ f"Begin with your <ayn_mantiq> reasoning block, followed by the complete, production-grade, zero-loss implementation:"
202
+ )
203
+
204
+ start_time_seconds = time.time()
205
+ raw_completion = self.call_api(system_preamble, user_prompt_instruction, temperature=0.1)
206
+ elapsed_seconds = time.time() - start_time_seconds
207
+
208
+ # Extract epistemic <ayn_mantiq> Chain-of-Thought reasoning block if present
209
+ mantiq_match = re.search(r"<ayn_mantiq>([\s\S]*?)</ayn_mantiq>", raw_completion, re.IGNORECASE)
210
+ mantiq_reasoning = mantiq_match.group(1).strip() if mantiq_match else ""
211
+
212
+ extracted_code = self._extract_code_block(raw_completion, language)
213
+ syntax_record = self._validate_syntax(extracted_code, language)
214
+ placeholder_flags = self._check_zero_loss_placeholders(extracted_code)
215
+
216
+ if placeholder_flags or not syntax_record["valid"]:
217
+ print(f"⚠️ [Zero-Loss Validator] Detected flaws (AST: {syntax_record['valid']}, Placeholders: {len(placeholder_flags)}). Refining...")
218
+ repair_instruction = (
219
+ f"The prior code output had the following issues:\n"
220
+ f"Syntax Valid: {syntax_record['valid']} (Error: {syntax_record['error']})\n"
221
+ f"Banned Placeholders Detected: {placeholder_flags}\n\n"
222
+ f"Rewrite the code to be 100% COMPLETE, valid, and fully implemented without a single placeholder."
223
+ )
224
+ raw_completion = self.call_api(
225
+ system_preamble,
226
+ f"{user_prompt_instruction}\n\n{raw_completion}\n\n{repair_instruction}",
227
+ temperature=0.05
228
+ )
229
+ mantiq_match = re.search(r"<ayn_mantiq>([\s\S]*?)</ayn_mantiq>", raw_completion, re.IGNORECASE)
230
+ if mantiq_match:
231
+ mantiq_reasoning = mantiq_match.group(1).strip()
232
+ extracted_code = self._extract_code_block(raw_completion, language)
233
+ syntax_record = self._validate_syntax(extracted_code, language)
234
+
235
+ return {
236
+ "language": language,
237
+ "raw_output": raw_completion,
238
+ "code": extracted_code,
239
+ "mantiq_reasoning": mantiq_reasoning,
240
+ "syntax_valid": syntax_record["valid"],
241
+ "syntax_error": syntax_record["error"],
242
+ "duration_seconds": round(elapsed_seconds, 2),
243
+ "epistemic_pillars": {
244
+ "ghazali_mantiq": "Enforced real definition (Al-Ḥadd) & purged fallacies (Dawr/Tasalsul/Tanāquḍ)",
245
+ "raghib_teleology": "Enforced pure domain types & explicit Ghāyah",
246
+ "zamakhshari_eloquence": "Enforced zero-leaky abstractions & minimal boilerplate",
247
+ "lisan_exhaustiveness": "Enforced full error taxonomy & lifecycle state handling",
248
+ "farahidi_primitives": "Enforced orthogonal atomic primitives & state invariants",
249
+ "sibawayh_governance": "Enforced strict caller-callee governance & typed contracts"
250
+ }
251
+ }
252
+
253
+ def audit(self, code: str, language: str = "python", filename: str = "") -> Dict[str, Any]:
254
+ """Performs a rigorous 5-Pillar Epistemic Code Audit using the remote LLM."""
255
+ rag_context_block = self.mapper.build_epistemic_coding_context(
256
+ f"Code review and audit for {filename or 'source'}\n{code[:1000]}",
257
+ language
258
+ )
259
+ system_preamble = self._compose_auditor_system_prompt()
260
+ user_prompt_instruction = (
261
+ f"{rag_context_block}\n\n"
262
+ f"### 📄 CODE UNDER AUDIT (Language: {language.upper()}, File: `{filename or 'unnamed'}`):\n"
263
+ f"```{language}\n{code}\n```\n\n"
264
+ f"Deliver your comprehensive 5-Pillar Epistemic Audit now:"
265
+ )
266
+
267
+ start_time_seconds = time.time()
268
+ audit_verdict = self.call_api(system_preamble, user_prompt_instruction, temperature=0.1)
269
+ elapsed_seconds = time.time() - start_time_seconds
270
+
271
+ return {
272
+ "filename": filename,
273
+ "language": language,
274
+ "audit_report": audit_verdict,
275
+ "duration_seconds": round(elapsed_seconds, 2)
276
+ }
277
+
278
+ def refactor(
279
+ self,
280
+ code: str,
281
+ language: str = "python",
282
+ goal: str = "Purify code to 5-Pillar Classical Standard"
283
+ ) -> Dict[str, Any]:
284
+ """Refactors code to align with the 5 Classical Pillars."""
285
+ rag_context_block = self.mapper.build_epistemic_coding_context(f"{goal}\n{code[:800]}", language)
286
+ system_preamble = self._compose_refactor_system_prompt()
287
+ user_prompt_instruction = (
288
+ f"{rag_context_block}\n\n"
289
+ f"### 🎯 REFACTORING GOAL:\n{goal}\n\n"
290
+ f"### 📄 ORIGINAL CODE ({language.upper()}):\n```{language}\n{code}\n```\n\n"
291
+ f"Provide the complete refactored implementation and Epistemic Delta now:"
292
+ )
293
+
294
+ start_time_seconds = time.time()
295
+ refactored_output = self.call_api(system_preamble, user_prompt_instruction, temperature=0.1)
296
+ elapsed_seconds = time.time() - start_time_seconds
297
+
298
+ purified_code = self._extract_code_block(refactored_output, language)
299
+ syntax_record = self._validate_syntax(purified_code, language)
300
+
301
+ return {
302
+ "language": language,
303
+ "raw_output": refactored_output,
304
+ "refactored_code": purified_code,
305
+ "syntax_valid": syntax_record["valid"],
306
+ "syntax_error": syntax_record["error"],
307
+ "duration_seconds": round(elapsed_seconds, 2)
308
+ }
309
+
310
+ def _compose_synthesis_system_prompt(self, target_language: str) -> str:
311
+ """Builds epistemic system prompt for code synthesis."""
312
+ return (
313
+ "You are **AynEngine AI Coding Edition (Sovereign Epistemic Engine)**.\n"
314
+ "You reason natively through Classical Arabic Logic (Manṭiq) and the 5 Classical Arabic Lexicographical & Grammatical Pillars:\n"
315
+ "- **Abū Ḥāmid al-Ghazālī (Miʿyār al-ʿIlm & Miḥakk al-Naẓar) & Al-Rāzī**:\n"
316
+ " * Real Definition by Essential Invariants (Al-Ḥadd bi al-Dhātiyyāt): define by essential attributes, not accidental traits.\n"
317
+ " * Elimination of Circularity (Dafʿ al-Dawr): zero circular dependencies or circular type references.\n"
318
+ " * Elimination of Infinite Regress (Dafʿ al-Tasalsul): strictly bounded loops, recursion, and resource lifecycles.\n"
319
+ " * Law of Non-Contradiction (ʿAdam al-Tanāquḍ): eliminate contradictory states; zero silent exception swallowing.\n"
320
+ "- **Al-Khalīl ibn Aḥmad al-Farāhīdī (Kitāb al-ʿAyn) & Ibn Manẓūr (Lisān al-ʿArab)**: Root decomposition and exhaustive error/edge taxonomy.\n"
321
+ "- **Al-Rāghib al-Iṣfahānī (Al-Mufradāt) & Al-Zamakhsharī (Asās al-Balāghah)**: Pure teleological purpose (Ghāyah), ban vague names ('data', 'mgr', 'val'), zero leaky abstractions.\n"
322
+ "- **Sībawayh (Al-Kitāb)**: Syntactic governance (ʿĀmil wa Maʿmūl), strict static typing, and AST integrity.\n\n"
323
+ "MANDATORY COGNITIVE CHAIN-OF-THOUGHT PROTOCOL:\n"
324
+ "You MUST begin your response with an epistemic Chain-of-Thought reasoning block enclosed in `<ayn_mantiq>` and `</ayn_mantiq>`:\n"
325
+ "<ayn_mantiq>\n"
326
+ "🏛️ AYN-ENGINE EPISTEMIC LOGIC & MORPHOLOGY REASONING:\n"
327
+ "- Classical Root & Morphology (الجذر والتصريف): [Tri-consonantal root and linguistic significance]\n"
328
+ "- Real Definition & Essence (الحد بالذاتيات - معيار العلم): [Essential attributes and invariants]\n"
329
+ "- Epistemic Fallacy Invariants (دفع الدور والتسلسل ونفي التناقض): [Guards against circularity, regress, and contradiction]\n"
330
+ "- Lexicographical Teleology (الغاية وبلاغة التجريد): [Pure purpose, zero vague abstractions]\n"
331
+ "- Syntactic Governance (العامل والمعمول): [Strict type contracts and hierarchy]\n"
332
+ "</ayn_mantiq>\n\n"
333
+ "CRITICAL INVARIANTS:\n"
334
+ "- ZERO-LOSS CODE: Immediately after </ayn_mantiq>, provide the 100% COMPLETE, fully functional implementation in markdown code fences.\n"
335
+ "- NO PLACEHOLDERS: Zero lazy markers, zero 'TODO's, zero omitted logic.\n"
336
+ f"- Always output valid, strongly-typed code in {target_language}."
337
+ )
338
+
339
+ def _compose_auditor_system_prompt(self) -> str:
340
+ """Builds epistemic system prompt for code auditing."""
341
+ return (
342
+ "You are **AynEngine AI Coding Edition: Chief Epistemic Code Auditor**.\n"
343
+ "You audit source code strictly through the lens of the 5 Classical Arabic Lexicographical & Grammatical Pillars:\n"
344
+ "1. Al-Mufradāt: Evaluate Ontological Clarity & Teleology (1-10).\n"
345
+ "2. Asās al-Balāghah: Evaluate Abstraction Integrity & Eloquence (1-10).\n"
346
+ "3. Lisān al-ʿArab: Evaluate Edge-Case Exhaustiveness & Error Taxonomy (1-10).\n"
347
+ "4. Kitāb al-ʿAyn: Evaluate Atomic Decomposition & State Permutations (1-10).\n"
348
+ "5. Al-Kitāb: Evaluate Syntactic Governance & Dependency Architecture (1-10).\n\n"
349
+ "Format your response with: Scorecard, Critique, and Remediation Steps."
350
+ )
351
+
352
+ def _compose_refactor_system_prompt(self) -> str:
353
+ """Builds epistemic system prompt for code refactoring."""
354
+ return (
355
+ "You are **AynEngine AI Coding Edition: Sovereign Epistemic Refactoring Engine**.\n"
356
+ "Transform code into an architectural masterpiece adhering to the 5 Classical Pillars:\n"
357
+ "1. Al-Mufradāt (Domain Ontology & Teleology)\n"
358
+ "2. Asās al-Balāghah (Anti-Leakage & Rhetorical Eloquence)\n"
359
+ "3. Lisān al-ʿArab (Exhaustive Error Taxonomy)\n"
360
+ "4. Kitāb al-ʿAyn (Atomic Primitive Decomposition)\n"
361
+ "5. Al-Kitāb of Sībawayh (Strict Syntactic Governance & AST Integrity)\n\n"
362
+ "Output 100% COMPLETE code with zero placeholders accompanied by an Epistemic Delta."
363
+ )