diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..2bcd70e --- /dev/null +++ b/.flake8 @@ -0,0 +1,2 @@ +[flake8] +max-line-length = 88 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5929c38 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +# .github/workflows/ci.yml + +name: Python Code Harmonizer CI + +on: [push, pull_request] + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] + + steps: + - uses: actions/checkout@v3 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + pip install -e . + + - name: Lint with flake8 + run: | + # stop the build if there are Python syntax errors or undefined names + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + # exit-zero treats all errors as warnings + flake8 . --count --exit-zero --max-complexity=10 --statistics + + - name: Check formatting with black + run: | + black --check . + + - name: Test with pytest + run: | + pytest diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9c882b7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.egg-info/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..7b61673 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,79 @@ +# Contributing to the Python Code Harmonizer + +First off, thank you for considering contributing! This project is a unique blend of philosophy and code, and your help is welcome in making it better. + +## Getting Started + +To get the project set up for local development, please follow these steps: + +1. **Fork and Clone:** + * Fork the repository on GitHub. + * Clone your fork to your local machine: + ```sh + git clone https://github.com/YOUR_USERNAME/Python-Code-Harmonizer.git + cd Python-Code-Harmonizer + ``` + +2. **Set Up a Virtual Environment:** + * It is highly recommended to use a virtual environment to keep dependencies isolated. + ```sh + python -m venv .venv + source .venv/bin/activate + ``` + +3. **Install Dependencies:** + * The project and all its development dependencies can be installed with a single command. The `-e` flag installs the project in "editable" mode, which is essential for development. + ```sh + pip install -r requirements.txt + pip install -e . + ``` + +## Running the Tools + +### Running the Harmonizer + +Once installed, you can run the harmonizer on any Python file using the `harmonizer` command-line script: + +```sh +harmonizer examples/test_code.py +``` + +### Running the Test Suite + +This project uses `pytest` for testing. To run the full suite: + +```sh +pytest +``` + +## Code Quality and Style + +We use `black` for code formatting and `flake8` for linting to ensure a consistent and high-quality codebase. + +### Formatting + +Before you commit your changes, please run `black` to automatically format your code: + +```sh +black src/ tests/ +``` + +### Linting + +You can check for any style issues or potential errors with `flake8`: + +```sh +flake8 src/ tests/ +``` + +Our Continuous Integration (CI) pipeline will automatically check for formatting and linting issues, so it's a good idea to run these tools locally before pushing your changes. + +## Submitting a Pull Request + +1. Create a new branch for your feature or bug fix. +2. Make your changes, and be sure to add tests if you are adding new functionality. +3. Ensure your code is formatted with `black` and passes the `flake8` checks. +4. Make sure the full test suite passes with `pytest`. +5. Push your branch to your fork and open a pull request. + +Thank you for your contributions! diff --git a/anchor_analysis_V2.py b/anchor_analysis_V2.py index 8c89007..e4e5fd8 100644 --- a/anchor_analysis_V2.py +++ b/anchor_analysis_V2.py @@ -1,188 +1,193 @@ -""" -Anchor Point Mathematical Analysis (Harmonized V2) - -This script is the refactored version of the original anchor_analysis.py. -It has been "harmonized" to use the new 'divine_invitation_engine_V2.py' -engine, resolving the V1/V2 logical contradiction. - -This script validates that the Anchor Point (1,1,1,1) is the -mathematical representation of Perfect Harmony, using the -production-ready V2 engine. -""" - -import sys -import os -import math - -# --- V2 ENGINE IMPORT --- -# This now imports your production-ready V2 engine -try: - # We will use the 'Optimized Production-Ready' version - from src import divine_invitation_engine_V2 as dive -except ImportError: - print("FATAL ERROR: 'divine_invitation_engine_V2.py' not found.") - print("Please place the V2 engine file in the same directory.") - sys.exit(1) - - -def get_harmonized_semantic_clarity(coords: dive.Coordinates) -> float: - """ - Helper function to calculate semantic clarity using the - DIVE-V2 engine's logic (standard deviation). - - A perfectly balanced coordinate (like 1,1,1,1) will have a - std_dev of 0.0, resulting in a "perfect" clarity of 1.0. - """ - # The V2 Coordinates object is iterable - dims = list(coords) - if not dims: - return 0.0 - - mean = sum(dims) / len(dims) - variance = sum((d - mean) ** 2 for d in dims) / len(dims) - std_dev = math.sqrt(variance) - - # DIVE-V2 formula: Clarity = 1.0 minus normalized deviation. - # 0.5 is the max possible std_dev in a 0-1, 4D space. - clarity = max(0.0, 1.0 - (std_dev / 0.5)) - return clarity - - -def analyze_anchor_point_v2(): - print("=" * 80) - print("ANCHOR POINT MATHEMATICAL ANALYSIS (Harmonized V2)") - print("=" * 80) - print("Testing the fundamental properties of (1,1,1,1) as Perfect Harmony") - - # --- V2 ENGINE INITIALIZATION --- - engine = dive.DivineInvitationSemanticEngine() - anchor = engine.ANCHOR_POINT - - print(f"Powered By: {engine.get_engine_version()}") - print(f"Anchor Point: {anchor}") - print() - - # Test 1: Self-consistency - print("1. SELF-CONSISTENCY TEST") - print("-" * 50) - # --- Refactored to use V2 'get_distance' method --- - distance = engine.get_distance(anchor, anchor) - print(f"Anchor distance from itself: {distance}") - print("Expected: 0.0 (perfect self-consistency)") - print() - - # Test 2: Perfect harmony properties - print("2. PERFECT HARMONY PROPERTIES") - print("-" * 50) - total_harmony = anchor.love + anchor.justice + anchor.power + anchor.wisdom - print(f"Total Harmony Score: {total_harmony}") - print("Expected: 4.0 (perfect unity)") - print() - - dimensions = list(anchor) - balance = min(dimensions) / max(dimensions) - print(f"Dimensional Balance: {balance:.3f}") - print("Expected: 1.0 (perfect balance)") - print() - - # Test 3: Mathematical Properties - print("3. MATHEMATICAL PROPERTIES") - print("-" * 50) - # --- Refactored to use V2 'get_distance' method --- - origin = dive.Coordinates(0.0, 0.0, 0.0, 0.0) - pure_love = dive.Coordinates(1.0, 0.0, 0.0, 0.0) - pure_justice = dive.Coordinates(0.0, 1.0, 0.0, 0.0) - pure_power = dive.Coordinates(0.0, 0.0, 1.0, 0.0) - pure_wisdom = dive.Coordinates(0.0, 0.0, 0.0, 1.0) - - print(f"Distance from origin: {engine.get_distance(anchor, origin):.6f}") - print(f"Distance from pure Love: {engine.get_distance(anchor, pure_love):.6f}") - print(f"Distance from pure Justice: {engine.get_distance(anchor, pure_justice):.6f}") - print(f"Distance from pure Power: {engine.get_distance(anchor, pure_power):.6f}") - print(f"Distance from pure Wisdom: {engine.get_distance(anchor, pure_wisdom):.6f}") - print() - - # Test 4: Golden Ratio Relationships - print("4. GOLDEN RATIO RELATIONSHIPS") - print("-" * 50) - phi = (1 + 5**0.5) / 2 - print(f"Golden Ratio (phi): {phi:.10f}") - # This is a symbolic test from V1 - phi_love = 1 / (anchor.love + phi) - print(f" Symbolic Phi-Scaled Coord (Love): {phi_love:.6f}") - print(f" Expected: 0.381966 (1 / (1 + phi))") - print() - - # Test 5: Semantic Clarity of Perfection - print("5. SEMANTIC CLARITY OF PERFECTION") - print("-" * 50) - # --- Refactored to use V2 clarity logic --- - clarity = engine.get_semantic_clarity(anchor) - print(f"Anchor Point Semantic Clarity: {clarity:.6f}") - # --- "Expected" value is now corrected to 1.0 --- - print("Expected: 1.0 (perfect std_dev of 0.0)") - print() - - # Test 6: Perfect Concepts Proximity - print("6. PERFECT CONCEPTS PROXIMITY") - print("-" * 50) - print("Testing perfect concepts - they should approach Anchor Point:") - - concepts = { - 'perfect harmony': 'love justice power wisdom', - 'divine love': 'love', - 'absolute truth': 'justice wisdom', - 'infinite wisdom': 'wisdom', - 'ultimate justice': 'justice' - } - - for name, text in concepts.items(): - # --- Refactored to use V2 'analyze_text' method --- - # and get the .coordinates from the SemanticResult object - coords = engine.analyze_text(text).coordinates - distance = engine.get_distance(anchor, coords) - print(f" '{name}': distance = {distance:.6f}") - print() - - # Test 7: Geometric Properties - print("7. GEOMETRIC PROPERTIES") - print("-" * 50) - volume = anchor.love * anchor.justice * anchor.power * anchor.wisdom - # Formula from V1 spec (for a 3D prism, but we'll test it for consistency) - surface_area = 2 * ( - (anchor.love * anchor.justice) + (anchor.love * anchor.power) + - (anchor.love * anchor.wisdom) + (anchor.justice * anchor.power) + - (anchor.justice * anchor.wisdom) + (anchor.power * anchor.wisdom) - ) - print(f"4D Semantic Volume: {volume:.6f}") - print(f"4D Semantic 'Surface Area' (V1 Formula): {surface_area:.6f}") - print() - - # Test 8: Anchor Point Analysis Summary - print("8. ANCHOR POINT ANALYSIS SUMMARY") - print("-" * 50) - - findings = [] - if distance == 0.0: - findings.append("[OK] Perfect self-consistency") - if abs(total_harmony - 4.0) < 0.001: - findings.append("[OK] Perfect harmony achieved") - if abs(balance - 1.0) < 0.001: - findings.append("[OK] Perfect dimensional balance") - if abs(clarity - 1.0) < 0.001: - findings.append("[OK] Perfect semantic clarity") - - print("Mathematical Validation Results:") - for finding in findings: - print(f" {finding}") - - print() - print("CONCLUSION:") - print("=" * 50) - print("This harmonized test validates the Anchor Point as the") - print("mathematical representation of Perfect Harmony, using the") - print("project's unified V2 engine.") - print("=" * 80) - -if __name__ == "__main__": - analyze_anchor_point_v2() \ No newline at end of file +""" +Anchor Point Mathematical Analysis (Harmonized V2) + +This script is the refactored version of the original anchor_analysis.py. +It has been "harmonized" to use the new 'divine_invitation_engine_V2.py' +engine, resolving the V1/V2 logical contradiction. + +This script validates that the Anchor Point (1,1,1,1) is the +mathematical representation of Perfect Harmony, using the +production-ready V2 engine. +""" + +import sys +import math + +# --- V2 ENGINE IMPORT --- +# This now imports your production-ready V2 engine +try: + # We will use the 'Optimized Production-Ready' version + from src import divine_invitation_engine_V2 as dive +except ImportError: + print("FATAL ERROR: 'divine_invitation_engine_V2.py' not found.") + print("Please place the V2 engine file in the same directory.") + sys.exit(1) + + +def get_harmonized_semantic_clarity(coords: dive.Coordinates) -> float: + """ + Helper function to calculate semantic clarity using the + DIVE-V2 engine's logic (standard deviation). + + A perfectly balanced coordinate (like 1,1,1,1) will have a + std_dev of 0.0, resulting in a "perfect" clarity of 1.0. + """ + # The V2 Coordinates object is iterable + dims = list(coords) + if not dims: + return 0.0 + + mean = sum(dims) / len(dims) + variance = sum((d - mean) ** 2 for d in dims) / len(dims) + std_dev = math.sqrt(variance) + + # DIVE-V2 formula: Clarity = 1.0 minus normalized deviation. + # 0.5 is the max possible std_dev in a 0-1, 4D space. + clarity = max(0.0, 1.0 - (std_dev / 0.5)) + return clarity + + +def analyze_anchor_point_v2(): + print("=" * 80) + print("ANCHOR POINT MATHEMATICAL ANALYSIS (Harmonized V2)") + print("=" * 80) + print("Testing the fundamental properties of (1,1,1,1) as Perfect Harmony") + + # --- V2 ENGINE INITIALIZATION --- + engine = dive.DivineInvitationSemanticEngine() + anchor = engine.ANCHOR_POINT + + print(f"Powered By: {engine.get_engine_version()}") + print(f"Anchor Point: {anchor}") + print() + + # Test 1: Self-consistency + print("1. SELF-CONSISTENCY TEST") + print("-" * 50) + # --- Refactored to use V2 'get_distance' method --- + distance = engine.get_distance(anchor, anchor) + print(f"Anchor distance from itself: {distance}") + print("Expected: 0.0 (perfect self-consistency)") + print() + + # Test 2: Perfect harmony properties + print("2. PERFECT HARMONY PROPERTIES") + print("-" * 50) + total_harmony = anchor.love + anchor.justice + anchor.power + anchor.wisdom + print(f"Total Harmony Score: {total_harmony}") + print("Expected: 4.0 (perfect unity)") + print() + + dimensions = list(anchor) + balance = min(dimensions) / max(dimensions) + print(f"Dimensional Balance: {balance:.3f}") + print("Expected: 1.0 (perfect balance)") + print() + + # Test 3: Mathematical Properties + print("3. MATHEMATICAL PROPERTIES") + print("-" * 50) + # --- Refactored to use V2 'get_distance' method --- + origin = dive.Coordinates(0.0, 0.0, 0.0, 0.0) + pure_love = dive.Coordinates(1.0, 0.0, 0.0, 0.0) + pure_justice = dive.Coordinates(0.0, 1.0, 0.0, 0.0) + pure_power = dive.Coordinates(0.0, 0.0, 1.0, 0.0) + pure_wisdom = dive.Coordinates(0.0, 0.0, 0.0, 1.0) + + print(f"Distance from origin: {engine.get_distance(anchor, origin):.6f}") + print(f"Distance from pure Love: {engine.get_distance(anchor, pure_love):.6f}") + print( + f"Distance from pure Justice: {engine.get_distance(anchor, pure_justice):.6f}" + ) + print(f"Distance from pure Power: {engine.get_distance(anchor, pure_power):.6f}") + print(f"Distance from pure Wisdom: {engine.get_distance(anchor, pure_wisdom):.6f}") + print() + + # Test 4: Golden Ratio Relationships + print("4. GOLDEN RATIO RELATIONSHIPS") + print("-" * 50) + phi = (1 + 5**0.5) / 2 + print(f"Golden Ratio (phi): {phi:.10f}") + # This is a symbolic test from V1 + phi_love = 1 / (anchor.love + phi) + print(f" Symbolic Phi-Scaled Coord (Love): {phi_love:.6f}") + print(" Expected: 0.381966 (1 / (1 + phi))") + print() + + # Test 5: Semantic Clarity of Perfection + print("5. SEMANTIC CLARITY OF PERFECTION") + print("-" * 50) + # --- Refactored to use V2 clarity logic --- + clarity = engine.get_semantic_clarity(anchor) + print(f"Anchor Point Semantic Clarity: {clarity:.6f}") + # --- "Expected" value is now corrected to 1.0 --- + print("Expected: 1.0 (perfect std_dev of 0.0)") + print() + + # Test 6: Perfect Concepts Proximity + print("6. PERFECT CONCEPTS PROXIMITY") + print("-" * 50) + print("Testing perfect concepts - they should approach Anchor Point:") + + concepts = { + "perfect harmony": "love justice power wisdom", + "divine love": "love", + "absolute truth": "justice wisdom", + "infinite wisdom": "wisdom", + "ultimate justice": "justice", + } + + for name, text in concepts.items(): + # --- Refactored to use V2 'analyze_text' method --- + # and get the .coordinates from the SemanticResult object + coords = engine.analyze_text(text).coordinates + distance = engine.get_distance(anchor, coords) + print(f" '{name}': distance = {distance:.6f}") + print() + + # Test 7: Geometric Properties + print("7. GEOMETRIC PROPERTIES") + print("-" * 50) + volume = anchor.love * anchor.justice * anchor.power * anchor.wisdom + # Formula from V1 spec (for a 3D prism, but we'll test it for consistency) + surface_area = 2 * ( + (anchor.love * anchor.justice) + + (anchor.love * anchor.power) + + (anchor.love * anchor.wisdom) + + (anchor.justice * anchor.power) + + (anchor.justice * anchor.wisdom) + + (anchor.power * anchor.wisdom) + ) + print(f"4D Semantic Volume: {volume:.6f}") + print(f"4D Semantic 'Surface Area' (V1 Formula): {surface_area:.6f}") + print() + + # Test 8: Anchor Point Analysis Summary + print("8. ANCHOR POINT ANALYSIS SUMMARY") + print("-" * 50) + + findings = [] + if distance == 0.0: + findings.append("[OK] Perfect self-consistency") + if abs(total_harmony - 4.0) < 0.001: + findings.append("[OK] Perfect harmony achieved") + if abs(balance - 1.0) < 0.001: + findings.append("[OK] Perfect dimensional balance") + if abs(clarity - 1.0) < 0.001: + findings.append("[OK] Perfect semantic clarity") + + print("Mathematical Validation Results:") + for finding in findings: + print(f" {finding}") + + print() + print("CONCLUSION:") + print("=" * 50) + print("This harmonized test validates the Anchor Point as the") + print("mathematical representation of Perfect Harmony, using the") + print("project's unified V2 engine.") + print("=" * 80) + + +if __name__ == "__main__": + analyze_anchor_point_v2() diff --git a/examples/test_code.py b/examples/test_code.py index 6d78968..e387909 100644 --- a/examples/test_code.py +++ b/examples/test_code.py @@ -4,20 +4,23 @@ intentional, high disharmony. """ + # A (mock) database object to make the code valid class MockDB: def query(self, q: str): print(f"[DB] Querying: {q}") return {"user": "Test User"} - + def delete_user(self, token: str): print(f"[DB] DELETING USER WITH TOKEN: {token}") return True + db = MockDB() # --- A HARMONIOUS FUNCTION --- + def get_user_by_id(user_id: int): """ Fetches, reads, and returns a user's information @@ -25,27 +28,29 @@ def get_user_by_id(user_id: int): """ if not user_id: return None - + # The execution (query, read, return) matches the # intent (get, information). user_data = db.query(f"SELECT * FROM users WHERE id = {user_id}") return user_data + # --- A DISHARMONIOUS FUNCTION (THE "BUG") --- + def check_user_permissions(user_token: str): """ This function's INTENT is to validate, check, and get information about a user's permissions. It should be a 'justice' and 'wisdom' task. """ - + # !! DISHARMONY !! # The EXECUTION is 'delete', a high 'power'/'force' concept. # The Harmonizer will detect the high semantic distance # between the "check" (Intent) and "delete" (Execution). print("Checking token... (but not really)") db.delete_user(token=user_token) - + # This 'return' of 'information' is deceptive. - return "User Deleted" \ No newline at end of file + return "User Deleted" diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..e9e6065 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,21 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "PythonCodeHarmonizer" +version = "1.1.0" +description = "A semantic code debugger." +readme = "README.md" +license = { file="LICENSE" } +requires-python = ">=3.8" +classifiers = [ + "Programming Language :: Python :: 3", +] + +[project.scripts] +harmonizer = "src.harmonizer.main:run_cli" + +[tool.setuptools.packages.find] +where = ["."] +include = ["src*"] diff --git a/requirements.txt b/requirements.txt index e69de29..a5c58c2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -0,0 +1,3 @@ +pytest +black +flake8 diff --git a/src/ast_semantic_parser.py b/src/ast_semantic_parser.py index aba47fc..9bd2e2e 100644 --- a/src/ast_semantic_parser.py +++ b/src/ast_semantic_parser.py @@ -7,7 +7,7 @@ This class is the critical "bridge" in our Python Code Harmonizer. It walks a Python Abstract Syntax Tree (AST) and translates logical code -structures into the conceptual keywords understood by the +structures into the conceptual keywords understood by the Divine Invitation Semantic Engine (DIVE-V2). """ @@ -15,105 +15,108 @@ import re from typing import List, Optional, Set + class AST_Semantic_Parser(ast.NodeVisitor): """ A "Rosetta Stone" that translates Python AST nodes into DIVE-V2 conceptual keywords. """ - + def __init__(self, vocabulary: Set[str]): """ Initializes the parser with the known vocabulary from the DIVE-V2 engine to improve mapping accuracy. """ self.known_vocabulary = vocabulary - + # This map translates common function name prefixes and keywords # into DIVE-V2 concepts. This is the core "Intent" logic. self.intent_keyword_map = { # WISDOM (Information, Truth) - 'get': 'information', - 'read': 'information', - 'fetch': 'information', - 'query': 'information', - 'calculate': 'wisdom', - 'analyze': 'wisdom', - 'validate': 'truth', - 'check': 'truth', - 'is_': 'truth', - 'return': 'information', + "get": "information", + "read": "information", + "fetch": "information", + "query": "information", + "calculate": "wisdom", + "analyze": "wisdom", + "validate": "truth", + "check": "truth", + "is_": "truth", + "return": "information", # POWER (Action, Control) - 'set': 'power', - 'update': 'power', - 'create': 'create', - 'build': 'create', - 'write': 'manifest', - 'delete': 'force', - 'remove': 'force', - 'run': 'power', - 'execute': 'power', - 'raise': 'force', + "set": "power", + "update": "power", + "create": "create", + "build": "create", + "write": "manifest", + "delete": "force", + "remove": "force", + "run": "power", + "execute": "power", + "raise": "force", # JUSTICE (Order, Rules, Logic) - 'assert': 'law', - 'try': 'logic', - 'except': 'mercy', # (!) - 'if': 'logic', - 'else': 'logic', - 'for': 'process', - 'while': 'process', - 'order': 'order', + "assert": "law", + "try": "logic", + "except": "mercy", # (!) + "if": "logic", + "else": "logic", + "for": "process", + "while": "process", + "order": "order", # LOVE (Unity, Connection) - 'add': 'community', - 'append': 'community', - 'join': 'harmony', - 'connect': 'harmony', - 'merge': 'togetherness', + "add": "community", + "append": "community", + "join": "harmony", + "connect": "harmony", + "merge": "togetherness", } - + self._concepts_found: Set[str] = set() def _split_snake_case(self, name: str) -> List[str]: """Splits 'get_user_by_id' into ['get', 'user', 'by', 'id']""" - return name.split('_') + return name.split("_") def _map_word_to_concept(self, word: str) -> Optional[str]: """Finds the base concept for a given word.""" word_lower = word.lower() - + # Priority 1: Direct match in the map if word_lower in self.intent_keyword_map: return self.intent_keyword_map[word_lower] - + # Priority 2: Match in the full DIVE-V2 vocabulary if word_lower in self.known_vocabulary: return word_lower - + # Priority 3: Prefix match in the map for prefix, concept in self.intent_keyword_map.items(): if word_lower.startswith(prefix): return concept - + return None # --- PHASE 2: "INTENT" PARSING --- - def get_intent_concepts(self, function_name: str, docstring: Optional[str]) -> List[str]: + def get_intent_concepts( + self, function_name: str, docstring: Optional[str] + ) -> List[str]: """ Parses the function's name and docstring to find its "Stated Purpose" (Intent). """ concepts: Set[str] = set() - + # 1. Parse the function name name_words = self._split_snake_case(function_name) for word in name_words: concept = self._map_word_to_concept(word) if concept: concepts.add(concept) - + # 2. Parse the docstring (as a simple bag of words) if docstring: - doc_words = re.findall(r'\b\w+\b', docstring.lower()) + doc_words = re.findall(r"\b\w+\b", docstring.lower()) for word in doc_words: concept = self._map_word_to_concept(word) if concept: @@ -122,7 +125,7 @@ def get_intent_concepts(self, function_name: str, docstring: Optional[str]) -> L # Fallback: if no concepts found, use the raw words from the name if not concepts and name_words: return [word for word in name_words if word in self.known_vocabulary] - + return list(concepts) # --- PHASE 2: "EXECUTION" PARSING --- @@ -131,7 +134,7 @@ def get_execution_concepts(self, body: List[ast.AST]) -> List[str]: """ Parses the function's body (a list of AST nodes) to find its "Actual Action" (Execution). - + This method "walks" the AST using the ast.NodeVisitor pattern. """ self._concepts_found = set() @@ -149,62 +152,62 @@ def visit_Call(self, node: ast.Call): (a function call). """ concept = None - + # Check for obj.method() calls (e.g., db.delete) if isinstance(node.func, ast.Attribute): concept = self._map_word_to_concept(node.func.attr) - + # Check for simple function() calls (e.g., print) elif isinstance(node.func, ast.Name): concept = self._map_word_to_concept(node.func.id) - + if concept: self._concepts_found.add(concept) - + # Continue walking *inside* the call (e.g., its arguments) self.generic_visit(node) def visit_If(self, node: ast.If): """Maps 'if' statements to 'logic' (Justice)""" - self._concepts_found.add('logic') + self._concepts_found.add("logic") self.generic_visit(node) def visit_Assert(self, node: ast.Assert): """Maps 'assert' statements to 'truth' and 'law' (Justice)""" - self._concepts_found.add('truth') - self._concepts_found.add('law') + self._concepts_found.add("truth") + self._concepts_found.add("law") self.generic_visit(node) def visit_Try(self, node: ast.Try): """Maps 'try/except' blocks to 'logic' and 'mercy' (Justice/Love)""" - self._concepts_found.add('logic') - if node.handlers: # If there is an 'except' block - self._concepts_found.add('mercy') + self._concepts_found.add("logic") + if node.handlers: # If there is an 'except' block + self._concepts_found.add("mercy") self.generic_visit(node) def visit_Raise(self, node: ast.Raise): """Maps 'raise' to 'power' and 'force' (Power)""" - self._concepts_found.add('power') - self._concepts_found.add('force') + self._concepts_found.add("power") + self._concepts_found.add("force") self.generic_visit(node) def visit_For(self, node: ast.For): """Maps 'for' loops to 'process' (Justice)""" - self._concepts_found.add('process') + self._concepts_found.add("process") self.generic_visit(node) def visit_While(self, node: ast.While): """Maps 'while' loops to 'process' and 'control' (Justice/Power)""" - self._concepts_found.add('process') - self._concepts_found.add('control') + self._concepts_found.add("process") + self._concepts_found.add("control") self.generic_visit(node) def visit_Return(self, node: ast.Return): """Maps 'return' to 'information' and 'result' (Wisdom)""" - self._concepts_found.add('information') - self._concepts_found.add('wisdom') + self._concepts_found.add("information") + self._concepts_found.add("wisdom") self.generic_visit(node) def generic_visit(self, node: ast.AST): """This is the default visitor that just continues the walk.""" - super().generic_visit(node) \ No newline at end of file + super().generic_visit(node) diff --git a/src/divine_invitation_engine_V2.py b/src/divine_invitation_engine_V2.py index ed566d2..5b8d340 100644 --- a/src/divine_invitation_engine_V2.py +++ b/src/divine_invitation_engine_V2.py @@ -14,11 +14,12 @@ class Dimension(Enum): """Semantic dimensions""" + LOVE = "love" - JUSTICE = "justice" + JUSTICE = "justice" POWER = "power" WISDOM = "wisdom" - + # ICE Framework dimensions INTENT = "intent" CONTEXT = "context" @@ -29,14 +30,15 @@ class Dimension(Enum): @dataclass(frozen=True) class Coordinates: """Immutable 4D semantic coordinates""" + love: float justice: float power: float wisdom: float - + def __str__(self) -> str: - return f"Coordinates(L={self.love:.3f}, J={self.justice:.3f}, P={self.power:.3f}, W={self.wisdom:.3f})" - + return f"Coordinates(L={self.love:.3f}, J={self.justice:.3f}, P={self.power:.3f}, W={self.wisdom:.3f})" # noqa: E501 + def __iter__(self): return iter([self.love, self.justice, self.power, self.wisdom]) @@ -44,6 +46,7 @@ def __iter__(self): @dataclass class SemanticResult: """Complete semantic analysis result""" + coordinates: Coordinates distance_from_anchor: float semantic_clarity: float @@ -56,153 +59,256 @@ class SemanticResult: class VocabularyManager: """Optimized vocabulary management with caching""" - + def __init__(self): self._keyword_map: Dict[str, Dimension] = {} self._word_cache: Dict[str, Tuple[Coordinates, int]] = {} self._ice_dimension_map: Dict[Dimension, Dimension] = {} self._build_complete_vocabulary() - + def _build_complete_vocabulary(self) -> None: """Build optimized vocabulary from all components""" # Base vocabulary definitions base_vocab = { Dimension.LOVE: { - 'love', 'compassion', 'mercy', 'kindness', 'agape', 'care', - 'friendship', 'family', 'community', 'peace', 'harmony', 'togetherness' + "love", + "compassion", + "mercy", + "kindness", + "agape", + "care", + "friendship", + "family", + "community", + "peace", + "harmony", + "togetherness", }, Dimension.JUSTICE: { - 'justice', 'truth', 'fairness', 'righteousness', 'integrity', 'law', - 'rights', 'freedom', 'liberty', 'equality', 'legal', 'fair', 'order' + "justice", + "truth", + "fairness", + "righteousness", + "integrity", + "law", + "rights", + "freedom", + "liberty", + "equality", + "legal", + "fair", + "order", }, Dimension.POWER: { - 'power', 'strength', 'authority', 'sovereignty', 'might', - 'rule', 'govern', 'control', 'leadership', 'command', 'military', - 'force', 'create', 'manifest', 'action', 'build' + "power", + "strength", + "authority", + "sovereignty", + "might", + "rule", + "govern", + "control", + "leadership", + "command", + "military", + "force", + "create", + "manifest", + "action", + "build", }, Dimension.WISDOM: { - 'wisdom', 'knowledge', 'understanding', 'clarity', 'insight', 'reason', - 'logic', 'learn', 'study', 'education', 'school', 'university', 'research', - 'science', 'mathematics', 'geometry', 'algorithms', 'analysis', 'information' - } + "wisdom", + "knowledge", + "understanding", + "clarity", + "insight", + "reason", + "logic", + "learn", + "study", + "education", + "school", + "university", + "research", + "science", + "mathematics", + "geometry", + "algorithms", + "analysis", + "information", + }, } - + # ICE vocabulary mapping ice_vocab = { Dimension.INTENT: { - 'desire', 'purpose', 'goal', 'planning', 'strategy', 'wisdom', 'benevolence', - 'aspiration', 'hope', 'vision' + "desire", + "purpose", + "goal", + "planning", + "strategy", + "wisdom", + "benevolence", + "aspiration", + "hope", + "vision", }, Dimension.CONTEXT: { - 'reality', 'truth', 'situation', 'environment', 'constraints', 'actors', - 'conditions', 'state', 'status', 'assessment' + "reality", + "truth", + "situation", + "environment", + "constraints", + "actors", + "conditions", + "state", + "status", + "assessment", }, Dimension.EXECUTION: { - 'action', 'implementation', 'power', 'strength', 'authority', - 'control', 'govern', 'rule', 'capability', 'success', 'result', - 'outcome', 'influence', 'effectiveness' + "action", + "implementation", + "power", + "strength", + "authority", + "control", + "govern", + "rule", + "capability", + "success", + "result", + "outcome", + "influence", + "effectiveness", }, Dimension.BENEVOLENCE: { - 'care', 'service', 'help', 'support', 'giving', 'compassion', - 'kindness', 'mercy', 'friendship', 'family', 'community', 'peace', - 'harmony', 'cooperation', 'humanitarian', 'charity', 'love' - } + "care", + "service", + "help", + "support", + "giving", + "compassion", + "kindness", + "mercy", + "friendship", + "family", + "community", + "peace", + "harmony", + "cooperation", + "humanitarian", + "charity", + "love", + }, } - + # ICE to base dimension mapping self._ice_dimension_map = { Dimension.INTENT: Dimension.WISDOM, Dimension.CONTEXT: Dimension.JUSTICE, Dimension.EXECUTION: Dimension.POWER, - Dimension.BENEVOLENCE: Dimension.LOVE + Dimension.BENEVOLENCE: Dimension.LOVE, } - + # Enhanced vocabulary enhanced_vocab = { - 'government': {'justice', 'power', 'law', 'citizen'}, - 'democracy': {'justice', 'freedom', 'liberty', 'love'}, - 'autocracy': {'power', 'control', 'force'}, - 'communism': {'love', 'community', 'justice', 'power'}, - 'capitalism': {'power', 'justice', 'wisdom'}, - 'federalism': {'justice', 'power', 'order'}, - 'republic': {'justice', 'law', 'rights'}, - 'economy': {'power', 'wisdom', 'justice'}, - 'trade': {'justice', 'love', 'power'}, - 'currency': {'power', 'control', 'justice'}, - 'banking': {'power', 'justice', 'control'}, - 'military': {'power', 'force', 'control'}, - 'defense': {'power', 'justice', 'love'}, - 'strategic': {'wisdom', 'power', 'planning'}, - 'un': {'justice', 'peace', 'law', 'love', 'wisdom'}, - 'nato': {'power', 'defense', 'justice'}, - 'ngo': {'love', 'humanitarian', 'service', 'care'}, - 'corporation': {'power', 'wisdom', 'justice'}, - 'terrorism': {'power', 'force', 'justice'}, - 'protest': {'justice', 'freedom', 'love', 'power'}, - 'revolution': {'power', 'justice', 'force', 'change'}, - 'nationalism': {'love', 'power', 'justice'} + "government": {"justice", "power", "law", "citizen"}, + "democracy": {"justice", "freedom", "liberty", "love"}, + "autocracy": {"power", "control", "force"}, + "communism": {"love", "community", "justice", "power"}, + "capitalism": {"power", "justice", "wisdom"}, + "federalism": {"justice", "power", "order"}, + "republic": {"justice", "law", "rights"}, + "economy": {"power", "wisdom", "justice"}, + "trade": {"justice", "love", "power"}, + "currency": {"power", "control", "justice"}, + "banking": {"power", "justice", "control"}, + "military": {"power", "force", "control"}, + "defense": {"power", "justice", "love"}, + "strategic": {"wisdom", "power", "planning"}, + "un": {"justice", "peace", "law", "love", "wisdom"}, + "nato": {"power", "defense", "justice"}, + "ngo": {"love", "humanitarian", "service", "care"}, + "corporation": {"power", "wisdom", "justice"}, + "terrorism": {"power", "force", "justice"}, + "protest": {"justice", "freedom", "love", "power"}, + "revolution": {"power", "justice", "force", "change"}, + "nationalism": {"love", "power", "justice"}, } - + # Build complete keyword map for dimension, words in base_vocab.items(): for word in words: self._keyword_map[word] = dimension - + for ice_dim, words in ice_vocab.items(): base_dim = self._ice_dimension_map.get(ice_dim, Dimension.WISDOM) for word in words: if word not in self._keyword_map: self._keyword_map[word] = base_dim - + for word, domains in enhanced_vocab.items(): if word not in self._keyword_map and domains: first_concept = next(iter(domains)) - self._keyword_map[word] = self._keyword_map.get(first_concept, Dimension.WISDOM) - - print(f"VocabularyManager: Initialized with {len(self._keyword_map)} unique keywords.") - + self._keyword_map[word] = self._keyword_map.get( + first_concept, Dimension.WISDOM + ) + + print( + f"VocabularyManager: Initialized with {len(self._keyword_map)} unique keywords." + ) + def analyze_text(self, text: str) -> Tuple[Coordinates, int]: """Optimized text analysis with caching""" # Check cache first cache_key = text.lower().strip() if cache_key in self._word_cache: return self._word_cache[cache_key] - - words = re.findall(r'\b\w+\b', cache_key) + + words = re.findall(r"\b\w+\b", cache_key) counts = {dim: 0.0 for dim in Dimension} concept_count = 0 - + for word in words: dimension = self._keyword_map.get(word) if dimension: counts[dimension] += 1.0 concept_count += 1 - + if concept_count == 0: result = (Coordinates(0.0, 0.0, 0.0, 0.0), 0) else: total = sum(counts.values()) - result = (Coordinates( - love=counts[Dimension.LOVE] / total, - justice=counts[Dimension.JUSTICE] / total, - power=counts[Dimension.POWER] / total, - wisdom=counts[Dimension.WISDOM] / total - ), concept_count) - + result = ( + Coordinates( + love=counts[Dimension.LOVE] / total, + justice=counts[Dimension.JUSTICE] / total, + power=counts[Dimension.POWER] / total, + wisdom=counts[Dimension.WISDOM] / total, + ), + concept_count, + ) + # Cache result self._word_cache[cache_key] = result return result + @property + def all_keywords(self) -> Set[str]: + """Returns all unique keywords from the vocabulary.""" + return set(self._keyword_map.keys()) + @staticmethod def get_distance(c1: Coordinates, c2: Coordinates) -> float: """Optimized Euclidean distance calculation""" return math.sqrt( - (c1.love - c2.love) ** 2 + - (c1.justice - c2.justice) ** 2 + - (c1.power - c2.power) ** 2 + - (c1.wisdom - c2.wisdom) ** 2 + (c1.love - c2.love) ** 2 + + (c1.justice - c2.justice) ** 2 + + (c1.power - c2.power) ** 2 + + (c1.wisdom - c2.wisdom) ** 2 ) - + @staticmethod def get_semantic_clarity(coords: Coordinates) -> float: """Optimized semantic clarity calculation""" @@ -215,43 +321,47 @@ def get_semantic_clarity(coords: Coordinates) -> float: class SemanticAnalyzer: """High-performance semantic analysis""" - + def __init__(self, vocab_manager: VocabularyManager, anchor_point: Coordinates): self.vocab = vocab_manager self.ANCHOR_POINT = anchor_point - + def analyze_concept_cluster(self, concepts: List[str]) -> SemanticResult: """Optimized cluster analysis""" if not concepts: return self._empty_result() - + coords_list = [] total_concepts = 0 - + for concept in concepts: coords, count = self.vocab.analyze_text(concept) if count > 0: coords_list.append(coords) total_concepts += count - + if not coords_list: return self._empty_result() - + return self._calculate_cluster_metrics(coords_list, total_concepts) - + def _empty_result(self) -> SemanticResult: """Return empty semantic result""" empty_coords = Coordinates(0.0, 0.0, 0.0, 0.0) return SemanticResult( coordinates=empty_coords, - distance_from_anchor=self.vocab.get_distance(self.ANCHOR_POINT, empty_coords), + distance_from_anchor=self.vocab.get_distance( + self.ANCHOR_POINT, empty_coords + ), semantic_clarity=0.0, concept_count=0, confidence=0.0, - harmonic_cohesion=0.0 + harmonic_cohesion=0.0, ) - def _calculate_cluster_metrics(self, coords_list: List[Coordinates], concept_count: int) -> SemanticResult: + def _calculate_cluster_metrics( + self, coords_list: List[Coordinates], concept_count: int + ) -> SemanticResult: """Calculate optimized cluster metrics""" # Calculate centroid using vectorized approach love_sum = justice_sum = power_sum = wisdom_sum = 0.0 @@ -260,24 +370,21 @@ def _calculate_cluster_metrics(self, coords_list: List[Coordinates], concept_cou justice_sum += coords.justice power_sum += coords.power wisdom_sum += coords.wisdom - + n = len(coords_list) centroid = Coordinates( - love_sum / n, - justice_sum / n, - power_sum / n, - wisdom_sum / n + love_sum / n, justice_sum / n, power_sum / n, wisdom_sum / n ) - + # Calculate distances and cohesion distances = [self.vocab.get_distance(c, centroid) for c in coords_list] avg_distance = sum(distances) / n harmonic_cohesion = max(0.0, 1.0 - (avg_distance / 1.732)) - + # Final metrics distance_from_anchor = self.vocab.get_distance(self.ANCHOR_POINT, centroid) semantic_clarity = self.vocab.get_semantic_clarity(centroid) - + return SemanticResult( coordinates=centroid, distance_from_anchor=distance_from_anchor, @@ -286,87 +393,106 @@ def _calculate_cluster_metrics(self, coords_list: List[Coordinates], concept_cou confidence=harmonic_cohesion, distances=distances, centroid=centroid, - harmonic_cohesion=harmonic_cohesion + harmonic_cohesion=harmonic_cohesion, ) class MathematicalInferenceEngine: """Optimized mathematical inference engine""" - + def __init__(self, vocab_manager: VocabularyManager, analyzer: SemanticAnalyzer): self.vocab = vocab_manager self.analyzer = analyzer - - def infer_unknown_meaning(self, unknown_word: str, context_words: List[str]) -> SemanticResult: + + def infer_unknown_meaning( + self, unknown_word: str, context_words: List[str] + ) -> SemanticResult: """Optimized meaning inference""" context_result = self.analyzer.analyze_concept_cluster(context_words) - + if context_result.concept_count == 0: return self.analyzer._empty_result() - + return SemanticResult( coordinates=context_result.centroid, distance_from_anchor=context_result.distance_from_anchor, semantic_clarity=context_result.semantic_clarity, concept_count=context_result.concept_count, confidence=context_result.harmonic_cohesion, - centroid=context_result.centroid + centroid=context_result.centroid, ) class GeopoliticalAnalyzer: """Optimized geopolitical analysis""" - + def __init__(self, vocab_manager: VocabularyManager, analyzer: SemanticAnalyzer): self.vocab = vocab_manager self.analyzer = analyzer self.ANCHOR_POINT = analyzer.ANCHOR_POINT - - def analyze_entity_posture(self, entity_name: str, entity_type: str, - recent_actions: str, historical_context: str = "") -> Dict: + + def analyze_entity_posture( + self, + entity_name: str, + entity_type: str, + recent_actions: str, + historical_context: str = "", + ) -> Dict: """Optimized posture analysis""" actions_result = self.analyzer.analyze_concept_cluster([recent_actions]) - history_result = self.analyzer.analyze_concept_cluster([historical_context]) if historical_context else self.analyzer._empty_result() - + history_result = ( + self.analyzer.analyze_concept_cluster([historical_context]) + if historical_context + else self.analyzer._empty_result() + ) + # Weighted combination (70% recent, 30% historical) combined_coords = Coordinates( - love=(actions_result.coordinates.love * 0.7) + (history_result.coordinates.love * 0.3), - justice=(actions_result.coordinates.justice * 0.7) + (history_result.coordinates.justice * 0.3), - power=(actions_result.coordinates.power * 0.7) + (history_result.coordinates.power * 0.3), - wisdom=(actions_result.coordinates.wisdom * 0.7) + (history_result.coordinates.wisdom * 0.3) + love=(actions_result.coordinates.love * 0.7) + + (history_result.coordinates.love * 0.3), + justice=(actions_result.coordinates.justice * 0.7) + + (history_result.coordinates.justice * 0.3), + power=(actions_result.coordinates.power * 0.7) + + (history_result.coordinates.power * 0.3), + wisdom=(actions_result.coordinates.wisdom * 0.7) + + (history_result.coordinates.wisdom * 0.3), ) - + return self._determine_posture(combined_coords, entity_name, entity_type) - - def _determine_posture(self, coords: Coordinates, entity_name: str, entity_type: str) -> Dict: + + def _determine_posture( + self, coords: Coordinates, entity_name: str, entity_type: str + ) -> Dict: """Optimized posture determination""" distance = self.vocab.get_distance(self.ANCHOR_POINT, coords) clarity = self.vocab.get_semantic_clarity(coords) - + # Find dominant dimension dim_values = { Dimension.LOVE: coords.love, Dimension.JUSTICE: coords.justice, Dimension.POWER: coords.power, - Dimension.WISDOM: coords.wisdom + Dimension.WISDOM: coords.wisdom, } dominant_dim = max(dim_values, key=dim_values.get) dominant_val = dim_values[dominant_dim] - + posture_type = "Uncertain Position" if dominant_val > 0.4: posture_map = { Dimension.LOVE: "Humanitarian / Cooperative", - Dimension.JUSTICE: "Legalistic / Principled", + Dimension.JUSTICE: "Legalistic / Principled", Dimension.POWER: "Authoritative / Military", - Dimension.WISDOM: "Strategic / Technical" + Dimension.WISDOM: "Strategic / Technical", } posture_type = posture_map.get(dominant_dim, posture_type) - + if distance < 0.5: posture_type = "Balanced Leadership (Harmonized)" elif distance > 1.5: - posture_type = f"Chaotic / Destabilized ({dominant_dim.value.title()} Focus)" + posture_type = ( + f"Chaotic / Destabilized ({dominant_dim.value.title()} Focus)" + ) return { "entity_name": entity_name, @@ -383,43 +509,61 @@ def _determine_posture(self, coords: Coordinates, entity_name: str, entity_type: class ICEAnalyzer: """Optimized ICE Framework analyzer""" - + def __init__(self, vocab_manager: VocabularyManager, analyzer: SemanticAnalyzer): self.vocab = vocab_manager self.analyzer = analyzer self.ANCHOR_POINT = analyzer.ANCHOR_POINT - def analyze_ice(self, intent_words: List[str], context_words: List[str], - execution_words: List[str]) -> Dict: + def analyze_ice( + self, + intent_words: List[str], + context_words: List[str], + execution_words: List[str], + ) -> Dict: """Optimized ICE analysis""" # Validate input if not any([intent_words, context_words, execution_words]): return self._empty_ice_result() - + # Analyze components intent_result = self.analyzer.analyze_concept_cluster(intent_words) context_result = self.analyzer.analyze_concept_cluster(context_words) execution_result = self.analyzer.analyze_concept_cluster(execution_words) - + # Calculate distances - intent_context_dist = self.vocab.get_distance(intent_result.coordinates, context_result.coordinates) - intent_exec_dist = self.vocab.get_distance(intent_result.coordinates, execution_result.coordinates) - context_exec_dist = self.vocab.get_distance(context_result.coordinates, execution_result.coordinates) - + intent_context_dist = self.vocab.get_distance( + intent_result.coordinates, context_result.coordinates + ) + intent_exec_dist = self.vocab.get_distance( + intent_result.coordinates, execution_result.coordinates + ) + context_exec_dist = self.vocab.get_distance( + context_result.coordinates, execution_result.coordinates + ) + # Calculate ICE metrics - avg_disharmony = (intent_context_dist + intent_exec_dist + context_exec_dist) / 3.0 + avg_disharmony = ( + intent_context_dist + intent_exec_dist + context_exec_dist + ) / 3.0 ice_coherence = max(0.0, 1.0 - (avg_disharmony / 2.0)) - - avg_dist_from_anchor = (intent_result.distance_from_anchor + - context_result.distance_from_anchor + - execution_result.distance_from_anchor) / 3.0 + + avg_dist_from_anchor = ( + intent_result.distance_from_anchor + + context_result.distance_from_anchor + + execution_result.distance_from_anchor + ) / 3.0 ice_balance = max(0.0, 1.0 - (avg_dist_from_anchor / 2.0)) - - benevolence_score = (intent_result.coordinates.love + execution_result.coordinates.love) / 2.0 - + + benevolence_score = ( + intent_result.coordinates.love + execution_result.coordinates.love + ) / 2.0 + # Calculate ICE coordinate - ice_coord = self._calculate_ice_coordinate(intent_result, context_result, execution_result) - + ice_coord = self._calculate_ice_coordinate( + intent_result, context_result, execution_result + ) + return { "ice_components": { "intent": intent_result, @@ -433,17 +577,40 @@ def analyze_ice(self, intent_words: List[str], context_words: List[str], "benevolence_score": benevolence_score, "intent_execution_disharmony": intent_exec_dist, }, - "ice_harmony_level": self._determine_ice_harmony_level(ice_coherence, ice_balance), + "ice_harmony_level": self._determine_ice_harmony_level( + ice_coherence, ice_balance + ), } - def _calculate_ice_coordinate(self, intent: SemanticResult, context: SemanticResult, - execution: SemanticResult) -> Coordinates: + def _calculate_ice_coordinate( + self, intent: SemanticResult, context: SemanticResult, execution: SemanticResult + ) -> Coordinates: # noqa: E501 """Calculate ICE coordinate from components""" return Coordinates( - love=(intent.coordinates.love + context.coordinates.love + execution.coordinates.love) / 3, - justice=(intent.coordinates.justice + context.coordinates.justice + execution.coordinates.justice) / 3, - power=(intent.coordinates.power + context.coordinates.power + execution.coordinates.power) / 3, - wisdom=(intent.coordinates.wisdom + context.coordinates.wisdom + execution.coordinates.wisdom) / 3 + love=( + intent.coordinates.love + + context.coordinates.love + + execution.coordinates.love + ) + / 3, + justice=( + intent.coordinates.justice + + context.coordinates.justice + + execution.coordinates.justice + ) + / 3, + power=( + intent.coordinates.power + + context.coordinates.power + + execution.coordinates.power + ) + / 3, + wisdom=( + intent.coordinates.wisdom + + context.coordinates.wisdom + + execution.coordinates.wisdom + ) + / 3, ) def _empty_ice_result(self) -> Dict: @@ -454,7 +621,7 @@ def _empty_ice_result(self) -> Dict: distance_from_anchor=0.0, semantic_clarity=0.0, concept_count=0, - confidence=0.0 + confidence=0.0, ) return { "ice_components": { @@ -487,48 +654,48 @@ def _determine_ice_harmony_level(self, coherence: float, balance: float) -> str: class PhiOptimizer: """Optimized phi-enhanced mathematical optimization""" - + def __init__(self, vocab_manager: VocabularyManager, analyzer: SemanticAnalyzer): self.vocab = vocab_manager self.analyzer = analyzer self.PHI = 1.618033988749895 self.ANCHOR_POINT = analyzer.ANCHOR_POINT - + def calculate_phi_optimization(self, concepts: List[str]) -> Dict: """Optimized phi analysis""" if not concepts: return {"error": "No concepts provided"} - + # Analyze concepts valid_coords = [] for concept in concepts: result = self.analyzer.analyze_concept_cluster([concept]) if result.concept_count > 0: valid_coords.append(result.coordinates) - + if not valid_coords: return {"error": "No valid concepts found"} - + # Calculate phi metrics phi_distances = [] for coords in valid_coords: distance = self.vocab.get_distance(self.ANCHOR_POINT, coords) phi_distances.append(distance * self.PHI) - + # Calculate centroid centroid = self._calculate_centroid(valid_coords) - + # Calculate perfection score phi_mean = sum(phi_distances) / len(phi_distances) phi_perfection = max(0, (1.0 - (phi_mean / (2.0 * self.PHI)))) * 100 - + return { "centroid": centroid, "phi_distances": phi_distances, "phi_perfection": phi_perfection, "phi_mean": phi_mean, "min_phi_distance": min(phi_distances), - "max_phi_distance": max(phi_distances) + "max_phi_distance": max(phi_distances), } def _calculate_centroid(self, coords_list: List[Coordinates]) -> Coordinates: @@ -538,13 +705,8 @@ def _calculate_centroid(self, coords_list: List[Coordinates]) -> Coordinates: power_sum = sum(c.power for c in coords_list) wisdom_sum = sum(c.wisdom for c in coords_list) n = len(coords_list) - - return Coordinates( - love_sum / n, - justice_sum / n, - power_sum / n, - wisdom_sum / n - ) + + return Coordinates(love_sum / n, justice_sum / n, power_sum / n, wisdom_sum / n) class DivineInvitationSemanticEngine: @@ -552,21 +714,25 @@ class DivineInvitationSemanticEngine: Optimized Divine Invitation Semantic Substrate Engine (DIVE-V2) High-performance facade integrating all specialized sub-engines. """ - + def __init__(self): """Initialize optimized system""" self.ENGINE_VERSION = "DIVE-V2 (Optimized Production)" self.ANCHOR_POINT = Coordinates(1.0, 1.0, 1.0, 1.0) - + # Build core components self.vocabulary = VocabularyManager() self.semantic_analyzer = SemanticAnalyzer(self.vocabulary, self.ANCHOR_POINT) - + # Build specialized sub-engines - self.inference_engine = MathematicalInferenceEngine(self.vocabulary, self.semantic_analyzer) + self.inference_engine = MathematicalInferenceEngine( + self.vocabulary, self.semantic_analyzer + ) self.ice_analyzer = ICEAnalyzer(self.vocabulary, self.semantic_analyzer) self.phi_optimizer = PhiOptimizer(self.vocabulary, self.semantic_analyzer) - self.geopolitical_analyzer = GeopoliticalAnalyzer(self.vocabulary, self.semantic_analyzer) + self.geopolitical_analyzer = GeopoliticalAnalyzer( + self.vocabulary, self.semantic_analyzer + ) def get_engine_version(self) -> str: return self.ENGINE_VERSION @@ -577,44 +743,57 @@ def analyze_text(self, text: str) -> SemanticResult: coords, count = self.vocabulary.analyze_text(text) if count == 0: return self.semantic_analyzer._empty_result() - + return SemanticResult( coordinates=coords, distance_from_anchor=self.get_distance(self.ANCHOR_POINT, coords), semantic_clarity=self.get_semantic_clarity(coords), concept_count=count, - confidence=1.0 + confidence=1.0, ) def get_distance(self, c1: Coordinates, c2: Coordinates) -> float: """Calculate distance between coordinates""" return self.vocabulary.get_distance(c1, c2) - + def get_semantic_clarity(self, coords: Coordinates) -> float: """Calculate semantic clarity""" return self.vocabulary.get_semantic_clarity(coords) # Sub-engine facade methods - def perform_geopolitical_analysis(self, entity_name: str, entity_type: str, - recent_actions: str = "", historical_context: str = "") -> Dict: + def perform_geopolitical_analysis( + self, + entity_name: str, + entity_type: str, + recent_actions: str = "", + historical_context: str = "", + ) -> Dict: """Perform geopolitical analysis""" return self.geopolitical_analyzer.analyze_entity_posture( entity_name, entity_type, recent_actions, historical_context ) - + def perform_semantic_harmony_analysis(self, concepts: List[str]) -> SemanticResult: """Analyze semantic harmony""" return self.semantic_analyzer.analyze_concept_cluster(concepts) - - def perform_mathematical_inference(self, unknown_word: str, context_words: List[str]) -> SemanticResult: + + def perform_mathematical_inference( + self, unknown_word: str, context_words: List[str] + ) -> SemanticResult: """Perform mathematical inference""" return self.inference_engine.infer_unknown_meaning(unknown_word, context_words) - - def perform_ice_analysis(self, intent_words: List[str], context_words: List[str], - execution_words: List[str]) -> Dict: + + def perform_ice_analysis( + self, + intent_words: List[str], + context_words: List[str], + execution_words: List[str], + ) -> Dict: """Perform ICE framework analysis""" - return self.ice_analyzer.analyze_ice(intent_words, context_words, execution_words) - + return self.ice_analyzer.analyze_ice( + intent_words, context_words, execution_words + ) + def perform_phi_optimization(self, concepts: List[str]) -> Dict: """Perform phi-enhanced optimization""" return self.phi_optimizer.calculate_phi_optimization(concepts) @@ -627,12 +806,12 @@ def run_comprehensive_demo(): print("=" * 80) print("High-Performance Production System") print("=" * 80) - + # Initialize engine engine = DivineInvitationSemanticEngine() - + print("\n=== OPTIMIZED CAPABILITIES DEMONSTRATION ===") - + # 1. Basic analysis print("\n1. CORE SEMANTIC ANALYSIS") concept = "love justice power wisdom truth understanding" @@ -640,12 +819,13 @@ def run_comprehensive_demo(): print(f" Concept: '{concept}'") print(f" Coordinates: {result.coordinates}") print(f" Distance from Anchor: {result.distance_from_anchor:.3f}") - + # 2. Geopolitical analysis print("\n2. GEOPOLITICAL INTELLIGENCE") geo_result = engine.perform_geopolitical_analysis( - "United Nations", "international organization", - "peacekeeping humanitarian diplomacy cooperation" + "United Nations", + "international organization", + "peacekeeping humanitarian diplomacy cooperation", ) print(f" Entity: {geo_result['entity_name']}") print(f" Posture: {geo_result['posture_type']}") @@ -656,28 +836,29 @@ def run_comprehensive_demo(): ice_result = engine.perform_ice_analysis( intent_words=["peace", "cooperation", "development"], context_words=["global", "challenges", "opportunities"], - execution_words=["action", "implementation", "results"] + execution_words=["action", "implementation", "results"], ) print(f" ICE Harmony: {ice_result['ice_harmony_level']}") print(f" Coherence: {ice_result['ice_metrics']['ice_coherence']:.3f}") print(f" Benevolence: {ice_result['ice_metrics']['benevolence_score']:.3f}") - + # 4. Performance metrics print("\n4. PERFORMANCE VALIDATION") import time + start_time = time.time() - + # Batch processing test test_concepts = ["love", "justice", "power", "wisdom", "harmony", "balance"] for concept in test_concepts: engine.analyze_text(concept) - + processing_time = (time.time() - start_time) * 1000 print(f" Processed {len(test_concepts)} concepts in {processing_time:.2f}ms") print(f" Average: {processing_time/len(test_concepts):.2f}ms per concept") - + print("\n=== OPTIMIZED ENGINE READY ===") if __name__ == "__main__": - run_comprehensive_demo() \ No newline at end of file + run_comprehensive_demo() diff --git a/PythonCodeHarmonizer.py b/src/harmonizer/main.py similarity index 84% rename from PythonCodeHarmonizer.py rename to src/harmonizer/main.py index ed391e9..bd5387d 100644 --- a/PythonCodeHarmonizer.py +++ b/src/harmonizer/main.py @@ -1,178 +1,196 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -""" -Python Code Harmonizer (Version 1.1) - -This is the main application that integrates the Divine Invitation -Semantic Engine (DIVE-V2) with the AST Semantic Parser. - -It is guided by the principle of the "Logical Anchor Point" (S,L,I,E) -and uses the ICE (Intent, Context, Execution) framework to analyze -the "semantic harmony" of Python code. - -(HARMONIZATION_NOTE: v1.1 fixes a 'AttributeError' by correctly -referencing 'self.engine.vocabulary.all_keywords' from the -'Optimized Production-Ready' V2 engine.) -""" - -import ast -import sys -import os -from typing import Dict, Set - -# --- COMPONENT IMPORTS --- -# This script assumes the following two files are in the -# same directory or in Python's path. - -try: - # 1. Import your powerful V2 engine - # (This assumes 'divine_invitation_engine_V2.py' is the - # 'Optimized Production-Ready' version) - from src import divine_invitation_engine_V2 as dive -except ImportError: - print("FATAL ERROR: 'divine_invitation_engine_V2.py' not found.") - print("Please place the V2 engine file in the same directory.") - sys.exit(1) - -try: - # 2. Import our new "Rosetta Stone" parser - from src.ast_semantic_parser import AST_Semantic_Parser -except ImportError: - print("FATAL ERROR: 'ast_semantic_parser.py' not found.") - print("Please place the parser file in the same directory.") - sys.exit(1) - -# --- THE HARMONIZER APPLICATION --- - -class PythonCodeHarmonizer: - """ - Analyzes Python code for "Intent Harmony" using the DIVE-V2 - ICE (Intent, Context, Execution) framework. - """ - - def __init__(self, disharmony_threshold: float = 0.5): - # 1. Initialize your V2 engine. This is our "compass." - self.engine = dive.DivineInvitationSemanticEngine() - - # 2. Initialize our "Rosetta Stone" parser. - - # --- HARMONIZATION FIX (v1.1) --- - # The "Optimized" V2 engine's VocabularyManager stores its - # word list in the 'all_keywords' set. - # We now reference the correct attribute. - self.parser = AST_Semantic_Parser( - vocabulary=self.engine.vocabulary.all_keywords - ) - - # 3. Set the threshold for flagging disharmony. - self.disharmony_threshold = disharmony_threshold - - print("=" * 70) - print("Python Code Harmonizer (v1.1) ONLINE") - print("Actively guided by the Anchor Point framework.") - print(f"Powered By: {self.engine.get_engine_version()}") - print(f"Logical Anchor Point: (S=1, L=1, I=1, E=1)") - print(f"Disharmony Threshold: {self.disharmony_threshold}") - print("=" * 70) - - def analyze_file(self, file_path: str) -> Dict[str, float]: - """ - Analyzes a single Python file for Intent-Execution-Disharmony. - Returns a dictionary of {function_name: disharmony_score} - """ - print(f"\nAnalyzing file: {file_path}") - print("-" * 70) - - try: - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - except FileNotFoundError: - print(f"ERROR: File not found at '{file_path}'") - return {} - except Exception as e: - print(f"ERROR: Could not read file: {e}") - return {} - - # 1. Use Python's AST to parse the code into a logical tree - try: - tree = ast.parse(content) - except SyntaxError as e: - print(f"ERROR: Could not parse file. Syntax error on line {e.lineno}") - return {} - - harmony_report = {} - - # 2. "Walk" the tree and visit every function definition - for node in ast.walk(tree): - if isinstance(node, ast.FunctionDef): - function_name = node.name - docstring = ast.get_docstring(node) - - # 3. Get INTENT: "The Stated Purpose" - # We use our parser to get the concepts from the name/docstring - intent_concepts = self.parser.get_intent_concepts(function_name, docstring) - - # 4. Get EXECUTION: "The Actual Action" - # We use our parser to get the concepts from the function's body - execution_concepts = self.parser.get_execution_concepts(node.body) - - # 5. THE "A-HA!" MOMENT: Use the V2 ICEAnalyzer - # We pass our parsed concepts into the V2 engine's - # built-in ICE framework analyzer. - ice_result = self.engine.perform_ice_analysis( - intent_words=intent_concepts, - context_words=["python", "function", function_name], # Provide context - execution_words=execution_concepts - ) - - # The "bug" is the semantic distance between Intent and Execution - # This metric *is* returned by the "Optimized" V2 engine. - disharmony_score = ice_result['ice_metrics']['intent_execution_disharmony'] - - harmony_report[function_name] = disharmony_score - - return harmony_report - - def print_report(self, harmony_report: Dict[str, float]): - """Prints the final harmony report to the console.""" - - print("FUNCTION NAME | INTENT-EXECUTION DISHARMONY") - print("-----------------------------|--------------------------------") - - if not harmony_report: - print("No functions found to analyze.") - return - - sorted_report = sorted(harmony_report.items(), key=lambda item: item[1], reverse=True) - - for func_name, score in sorted_report: - status = "✓ HARMONIOUS" - if score > self.disharmony_threshold: - status = f"!! DISHARMONY (Score: {score:.2f})" - - print(f"{func_name:<28} | {status}") - - print("=" * 70) - print("Analysis Complete.") - -# --- MAIN EXECUTION --- - -if __name__ == "__main__": - if len(sys.argv) < 2: - print("Usage: python PythonCodeHarmonizer.py [file2.py ...]") - sys.exit(1) - - files_to_analyze = sys.argv[1:] - - # 1. Initialize the Harmonizer - harmonizer = PythonCodeHarmonizer() - - # 2. Run the analysis for all provided files - for file_path in files_to_analyze: - if os.path.exists(file_path): - report = harmonizer.analyze_file(file_path) - harmonizer.print_report(report) - else: - print(f"\nERROR: File not found: {file_path}") - print("-" * 70) \ No newline at end of file +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Python Code Harmonizer (Version 1.1) + +This is the main application that integrates the Divine Invitation +Semantic Engine (DIVE-V2) with the AST Semantic Parser. + +It is guided by the principle of the "Logical Anchor Point" (S,L,I,E) +and uses the ICE (Intent, Context, Execution) framework to analyze +the "semantic harmony" of Python code. + +(HARMONIZATION_NOTE: v1.1 fixes a 'AttributeError' by correctly +referencing 'self.engine.vocabulary.all_keywords' from the +'Optimized Production-Ready' V2 engine.) +""" + +import ast +import sys +import os +from typing import Dict + +# --- COMPONENT IMPORTS --- +# This script assumes the following two files are in the +# same directory or in Python's path. + +try: + # 1. Import your powerful V2 engine + # (This assumes 'divine_invitation_engine_V2.py' is the + # 'Optimized Production-Ready' version) + from src import divine_invitation_engine_V2 as dive +except ImportError: + print("FATAL ERROR: 'divine_invitation_engine_V2.py' not found.") + print("Please place the V2 engine file in the same directory.") + sys.exit(1) + +try: + # 2. Import our new "Rosetta Stone" parser + from src.ast_semantic_parser import AST_Semantic_Parser +except ImportError: + print("FATAL ERROR: 'ast_semantic_parser.py' not found.") + print("Please place the parser file in the same directory.") + sys.exit(1) + +# --- THE HARMONIZER APPLICATION --- + + +class PythonCodeHarmonizer: + """ + Analyzes Python code for "Intent Harmony" using the DIVE-V2 + ICE (Intent, Context, Execution) framework. + """ + + def __init__(self, disharmony_threshold: float = 0.5): + # 1. Initialize your V2 engine. This is our "compass." + self.engine = dive.DivineInvitationSemanticEngine() + + # 2. Initialize our "Rosetta Stone" parser. + + # --- HARMONIZATION FIX (v1.1) --- + # The "Optimized" V2 engine's VocabularyManager stores its + # word list in the 'all_keywords' set. + # We now reference the correct attribute. + self.parser = AST_Semantic_Parser( + vocabulary=self.engine.vocabulary.all_keywords + ) + + # 3. Set the threshold for flagging disharmony. + self.disharmony_threshold = disharmony_threshold + + print("=" * 70) + print("Python Code Harmonizer (v1.1) ONLINE") + print("Actively guided by the Anchor Point framework.") + print(f"Powered By: {self.engine.get_engine_version()}") + print("Logical Anchor Point: (S=1, L=1, I=1, E=1)") + print(f"Disharmony Threshold: {self.disharmony_threshold}") + print("=" * 70) + + def analyze_file(self, file_path: str) -> Dict[str, float]: + """ + Analyzes a single Python file for Intent-Execution-Disharmony. + Returns a dictionary of {function_name: disharmony_score} + """ + print(f"\nAnalyzing file: {file_path}") + print("-" * 70) + + try: + with open(file_path, "r", encoding="utf-8") as f: + content = f.read() + except FileNotFoundError: + print(f"ERROR: File not found at '{file_path}'") + return {} + except Exception as e: + print(f"ERROR: Could not read file: {e}") + return {} + + # 1. Use Python's AST to parse the code into a logical tree + try: + tree = ast.parse(content) + except SyntaxError as e: + print(f"ERROR: Could not parse file. Syntax error on line {e.lineno}") + return {} + + harmony_report = {} + + # 2. "Walk" the tree and visit every function definition + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef): + function_name = node.name + docstring = ast.get_docstring(node) + + # 3. Get INTENT: "The Stated Purpose" + # We use our parser to get the concepts from the name/docstring + intent_concepts = self.parser.get_intent_concepts( + function_name, docstring + ) + + # 4. Get EXECUTION: "The Actual Action" + # We use our parser to get the concepts from the function's body + execution_concepts = self.parser.get_execution_concepts(node.body) + + # 5. THE "A-HA!" MOMENT: Use the V2 ICEAnalyzer + # We pass our parsed concepts into the V2 engine's + # built-in ICE framework analyzer. + ice_result = self.engine.perform_ice_analysis( + intent_words=intent_concepts, + context_words=[ + "python", + "function", + function_name, + ], # Provide context + execution_words=execution_concepts, + ) + + # The "bug" is the semantic distance between Intent and Execution + # This metric *is* returned by the "Optimized" V2 engine. + disharmony_score = ice_result["ice_metrics"][ + "intent_execution_disharmony" + ] + + harmony_report[function_name] = disharmony_score + + return harmony_report + + def print_report(self, harmony_report: Dict[str, float]): + """Prints the final harmony report to the console.""" + + print("FUNCTION NAME | INTENT-EXECUTION DISHARMONY") + print("-----------------------------|--------------------------------") + + if not harmony_report: + print("No functions found to analyze.") + return + + sorted_report = sorted( + harmony_report.items(), key=lambda item: item[1], reverse=True + ) + + for func_name, score in sorted_report: + status = "✓ HARMONIOUS" + if score > self.disharmony_threshold: + status = f"!! DISHARMONY (Score: {score:.2f})" + + print(f"{func_name:<28} | {status}") + + print("=" * 70) + print("Analysis Complete.") + + +# --- MAIN EXECUTION --- + + +def run_cli(): + """Command-line interface entry point.""" + if len(sys.argv) < 2: + print("Usage: harmonizer [file2.py ...]") + sys.exit(1) + + files_to_analyze = sys.argv[1:] + + # 1. Initialize the Harmonizer + harmonizer = PythonCodeHarmonizer() + + # 2. Run the analysis for all provided files + for file_path in files_to_analyze: + if os.path.exists(file_path): + report = harmonizer.analyze_file(file_path) + harmonizer.print_report(report) + else: + print(f"\nERROR: File not found: {file_path}") + print("-" * 70) + + +if __name__ == "__main__": + run_cli() diff --git a/tests/test_engine.py b/tests/test_engine.py new file mode 100644 index 0000000..b146383 --- /dev/null +++ b/tests/test_engine.py @@ -0,0 +1,128 @@ +# tests/test_engine.py + +import pytest +from src.divine_invitation_engine_V2 import ( + DivineInvitationSemanticEngine, + Coordinates, +) + + +@pytest.fixture(scope="module") +def engine(): + """Provides a single instance of the engine for all tests in this module.""" + return DivineInvitationSemanticEngine() + + +def test_engine_initialization(engine): + """Tests that the engine and its components are initialized correctly.""" + assert engine is not None + assert engine.get_engine_version() == "DIVE-V2 (Optimized Production)" + assert engine.ANCHOR_POINT == Coordinates(1.0, 1.0, 1.0, 1.0) + assert engine.vocabulary is not None + assert engine.semantic_analyzer is not None + assert len(engine.vocabulary.all_keywords) > 0 + + +def test_vocabulary_manager_all_keywords(engine): + """Tests that the all_keywords property returns a comprehensive set of strings.""" + keywords = engine.vocabulary.all_keywords + assert isinstance(keywords, set) + assert "love" in keywords + assert "justice" in keywords + assert "power" in keywords + assert "wisdom" in keywords + assert len(keywords) > 50 # Ensure it's not a trivial set + + +def test_analyze_text_single_concept(engine): + """Tests the analysis of a single, clear concept.""" + coords, count = engine.vocabulary.analyze_text("love") + assert count == 1 + assert coords.love == 1.0 + assert coords.justice == 0.0 + assert coords.power == 0.0 + assert coords.wisdom == 0.0 + + +def test_analyze_text_mixed_concepts(engine): + """Tests the analysis of a text with multiple concepts, expecting a blend.""" + coords, count = engine.vocabulary.analyze_text("love justice power wisdom") + assert count == 4 + assert coords.love == pytest.approx(0.25) + assert coords.justice == pytest.approx(0.25) + assert coords.power == pytest.approx(0.25) + assert coords.wisdom == pytest.approx(0.25) + + +def test_analyze_text_no_concepts(engine): + """Tests that text with no known concepts returns zero coordinates.""" + coords, count = engine.vocabulary.analyze_text("xyz qwerty") + assert count == 0 + assert coords == Coordinates(0.0, 0.0, 0.0, 0.0) + + +def test_get_distance_calculation(engine): + """Tests the static distance calculation method.""" + c1 = Coordinates(0.0, 0.0, 0.0, 0.0) + c2 = Coordinates(1.0, 0.0, 0.0, 0.0) + assert engine.get_distance(c1, c2) == pytest.approx(1.0) + + c3 = Coordinates(1.0, 1.0, 1.0, 1.0) # Anchor Point + assert engine.get_distance(c1, c3) == pytest.approx(2.0) + + +def test_semantic_clarity(engine): + """Tests the semantic clarity calculation.""" + # A specialized, "spiky" concept has high standard deviation, and thus low clarity. + # The engine defines clarity as dimensional balance. + specialized_concept = Coordinates(1.0, 0.0, 0.0, 0.0) + assert engine.get_semantic_clarity(specialized_concept) == pytest.approx( + 0.13397, abs=1e-5 + ) + + # A perfectly balanced concept has zero standard deviation, and thus perfect clarity. + perfectly_balanced = Coordinates(0.25, 0.25, 0.25, 0.25) + assert engine.get_semantic_clarity(perfectly_balanced) == pytest.approx(1.0) + + # An unbalanced concept, should have lower clarity than a perfectly balanced one. + unbalanced = Coordinates(0.8, 0.2, 0.0, 0.0) + assert engine.get_semantic_clarity(unbalanced) < 1.0 + + +def test_semantic_analyzer_cluster(engine): + """Tests the semantic analyzer's ability to find the centroid of a concept cluster.""" # noqa: E501 + concepts = ["love", "justice"] + result = engine.perform_semantic_harmony_analysis(concepts) + + assert result.concept_count == 2 + # The centroid should be the average of (1,0,0,0) and (0,1,0,0) + assert result.coordinates.love == pytest.approx(0.5) + assert result.coordinates.justice == pytest.approx(0.5) + assert result.coordinates.power == pytest.approx(0.0) + assert result.coordinates.wisdom == pytest.approx(0.0) + + # Cohesion should be high for closely related concepts + assert result.harmonic_cohesion > 0.5 + + +def test_ice_analysis_highly_coherent(engine): + """ + Tests the ICE analysis for a highly coherent case where all concepts + belong to the same dimension (Wisdom). + """ # noqa: E501 + result = engine.perform_ice_analysis( + intent_words=["wisdom", "knowledge"], + context_words=["science", "research"], + execution_words=["analysis", "logic"], + ) + + assert "ice_metrics" in result + disharmony = result["ice_metrics"]["intent_execution_disharmony"] + harmony_level = result["ice_harmony_level"] + + # All concepts are pure Wisdom, so disharmony should be zero. + assert disharmony == pytest.approx(0.0) + + # Coherence is perfect, but balance is low because pure concepts are + # far from the (1,1,1,1) anchor. This should result in a "GOOD" score. + assert harmony_level == "GOOD_ICE_BALANCE" diff --git a/tests/test_harmonizer.py b/tests/test_harmonizer.py new file mode 100644 index 0000000..9af2cc9 --- /dev/null +++ b/tests/test_harmonizer.py @@ -0,0 +1,70 @@ +# tests/test_harmonizer.py + +import pytest +from src.harmonizer.main import PythonCodeHarmonizer +import tempfile +import os + +# A self-contained Python script to be used for testing. +# It contains one harmonious function and one disharmonious one. +TEST_CODE_CONTENT = """ +def get_user_data(): + \"\"\"Fetches user information from the database.\"\"\" + db.query("SELECT * FROM users") + return True + +def check_permissions(): + \"\"\"This function is supposed to check user rights.\"\"\" + # This is the logical bug: the name implies a check (Wisdom/Justice), + # but the action is a deletion (Power). + db.delete_user(user_id=42) + return False +""" + + +@pytest.fixture +def harmonizer(): + """Provides a standard instance of the Harmonizer.""" + return PythonCodeHarmonizer() + + +@pytest.fixture +def temp_python_file(): + """ + Creates a temporary Python file with the test code content. + This ensures the test is self-contained and doesn't rely on external files. + """ + # tempfile.NamedTemporaryFile creates a file and returns a file-like object. + # We use 'delete=False' to be able to close it and still use its name. + with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as fp: + fp.write(TEST_CODE_CONTENT) + filepath = fp.name + + # Yield the path to the test. The code inside the 'with' block runs before the test, + # and the code after the 'yield' runs after the test. + yield filepath + + # Teardown: Clean up the temporary file after the test is done. + os.unlink(filepath) + + +def test_harmonizer_end_to_end_analysis(harmonizer, temp_python_file): + """ + Performs an end-to-end integration test of the Harmonizer. + It runs the analysis on the temporary file and checks the report. + """ + # 1. Analyze the temporary file. + report = harmonizer.analyze_file(temp_python_file) + + # 2. Verify the report contents. + assert "get_user_data" in report + assert "check_permissions" in report + + # 3. Check the harmony scores. + # The 'get_user_data' function should be harmonious (low score). + # Intent: get, information. Execution: query, information. + assert report["get_user_data"] < harmonizer.disharmony_threshold + + # The 'check_permissions' function should be disharmonious (high score). + # Intent: check, truth. Execution: delete, force. + assert report["check_permissions"] > harmonizer.disharmony_threshold diff --git a/tests/test_parser.py b/tests/test_parser.py new file mode 100644 index 0000000..f6e2381 --- /dev/null +++ b/tests/test_parser.py @@ -0,0 +1,124 @@ +# tests/test_parser.py + +import pytest +from src.ast_semantic_parser import AST_Semantic_Parser +from src.divine_invitation_engine_V2 import DivineInvitationSemanticEngine + + +@pytest.fixture(scope="module") +def parser(): + """Provides a parser instance initialized with the engine's vocabulary.""" + engine = DivineInvitationSemanticEngine() + return AST_Semantic_Parser(vocabulary=engine.vocabulary.all_keywords) + + +# --- Test Intent Parsing --- + + +def test_intent_from_function_name(parser): + """ + Tests that concepts are correctly extracted from a function name, including + both mapped keywords and words present in the engine's vocabulary. + """ + name = "get_user_by_id_and_update_status" + # 'get' -> information, 'update' -> power + # 'status' is in the core vocabulary and should also be picked up. + expected_concepts = {"information", "power", "status"} + + concepts = parser.get_intent_concepts(name, None) + + assert set(concepts) == expected_concepts + + +def test_intent_from_docstring(parser): + """Tests that concepts from the docstring are merged with the name's concepts.""" + name = "process_data" + docstring = "This function will calculate and analyze the results." + # 'process' is not in the map, but 'calculate' and 'analyze' map to 'wisdom'. + expected_concepts = {"wisdom"} + + concepts = parser.get_intent_concepts(name, docstring) + + assert set(concepts) == expected_concepts + + +def test_intent_name_and_docstring_combined(parser): + """Ensures concepts from both the name and docstring are found.""" + name = "get_data" + docstring = "This function will create a new user." + # 'get' -> information, 'create' -> create + expected_concepts = {"information", "create"} + + concepts = parser.get_intent_concepts(name, docstring) + + assert set(concepts) == expected_concepts + + +# --- Test Execution Parsing --- + + +def test_execution_simple_function_call(parser): + """Tests that a simple function call is mapped to a concept.""" + code = "delete_user(user_id)" + # 'delete' is in the intent map and should be picked up. + expected_concepts = {"force"} + + # The parser expects a list of AST nodes, so we parse the code first. + import ast + + body = ast.parse(code).body + concepts = parser.get_execution_concepts(body) + + assert set(concepts) == expected_concepts + + +def test_execution_method_call(parser): + """Tests that a method call (e.g., db.query) is mapped correctly.""" + code = "db.query('SELECT * FROM users')" + # 'query' maps to 'information' + expected_concepts = {"information"} + + import ast + + body = ast.parse(code).body + concepts = parser.get_execution_concepts(body) + + assert set(concepts) == expected_concepts + + +def test_execution_control_flow(parser): + """Tests that control flow statements like 'if' and 'for' are mapped.""" + code = """ +if user.is_admin: + for item in items: + process_item(item) + """ + # 'if' -> logic, 'for' -> process + expected_concepts = {"logic", "process"} + + import ast + + body = ast.parse(code).body + concepts = parser.get_execution_concepts(body) + + assert set(concepts) == expected_concepts + + +def test_execution_error_handling(parser): + """Tests that 'try/except/raise' are mapped to their respective concepts.""" + code = """ +try: + result = 1 / 0 +except ZeroDivisionError: + log_error("Division by zero") + raise ValueError("Invalid operation") + """ + # 'try/except' -> logic, mercy; 'raise' -> power, force + expected_concepts = {"logic", "mercy", "power", "force"} + + import ast + + body = ast.parse(code).body + concepts = parser.get_execution_concepts(body) + + assert set(concepts) == expected_concepts