diff --git a/README.md b/README.md index 49a0941..532e74b 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,33 @@ Analysis Complete. --- +## Documentation + +### Getting Started +- **[User Guide](docs/USER_GUIDE.md)** - Comprehensive guide to using Python Code Harmonizer + - Installation and setup + - Understanding disharmony scores + - Integration into your workflow + - Best practices and troubleshooting + +- **[Tutorial](docs/TUTORIAL.md)** - Hands-on learning with real examples + - Step-by-step walkthroughs + - Common disharmony patterns + - Refactoring exercises + - Real-world scenarios + +- **[FAQ](docs/FAQ.md)** - Frequently Asked Questions + - Quick answers to common questions + - Interpretation guidance + - Troubleshooting tips + +### Advanced Topics +- **[Philosophy](docs/PHILOSOPHY.md)** *(Coming Soon)* - Deep dive into the Anchor Point and ICE Framework +- **[Architecture](docs/ARCHITECTURE.md)** *(Coming Soon)* - Technical implementation details for developers +- **[API Reference](docs/API.md)** *(Coming Soon)* - Programmatic usage and integration + +--- + ## Development & Contribution This project is now equipped with a full suite of professional development tools to ensure code quality and stability. diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 0000000..3eea42a --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,714 @@ +# Python Code Harmonizer - Frequently Asked Questions (FAQ) + +## Table of Contents + +### General Questions +- [What is Python Code Harmonizer?](#what-is-python-code-harmonizer) +- [How is this different from other code analysis tools?](#how-is-this-different-from-other-code-analysis-tools) +- [Do I still need linters and type checkers?](#do-i-still-need-linters-and-type-checkers) +- [What problems does it actually solve?](#what-problems-does-it-actually-solve) + +### Technical Questions +- [What does "semantic code debugging" mean?](#what-does-semantic-code-debugging-mean) +- [How does it calculate disharmony scores?](#how-does-it-calculate-disharmony-scores) +- [What is the Anchor Point (1,1,1,1)?](#what-is-the-anchor-point-1111) +- [What is the ICE Framework?](#what-is-the-ice-framework) +- [Does it use AI/ML?](#does-it-use-aiml) + +### Usage Questions +- [Can I customize the disharmony threshold?](#can-i-customize-the-disharmony-threshold) +- [Can I use it in CI/CD pipelines?](#can-i-use-it-in-cicd-pipelines) +- [Does it work with other Python tools?](#does-it-work-with-other-python-tools) +- [Can I integrate it with my IDE?](#can-i-integrate-it-with-my-ide) +- [Does it work on large codebases?](#does-it-work-on-large-codebases) + +### Interpretation Questions +- [Why is my function flagged when it seems fine?](#why-is-my-function-flagged-when-it-seems-fine) +- [Should I fix ALL disharmony?](#should-i-fix-all-disharmony) +- [What if my function legitimately does multiple things?](#what-if-my-function-legitimately-does-multiple-things) +- [Are low scores always good?](#are-low-scores-always-good) + +### Philosophical Questions +- [Why does naming matter so much?](#why-does-naming-matter-so-much) +- [Isn't this just enforcing subjective style preferences?](#isnt-this-just-enforcing-subjective-style-preferences) +- [What's the philosophy behind this tool?](#whats-the-philosophy-behind-this-tool) + +### Troubleshooting +- [The tool isn't detecting obvious problems](#the-tool-isnt-detecting-obvious-problems) +- [I'm getting import errors](#im-getting-import-errors) +- [Scores seem inconsistent](#scores-seem-inconsistent) + +--- + +## General Questions + +### What is Python Code Harmonizer? + +Python Code Harmonizer is the world's first **semantic code debugger**. Unlike traditional tools that check syntax and style, it analyzes the **meaning** of your code to detect logical inconsistencies. + +**Specifically, it asks:** *"Does your code DO what its name SAYS it does?"* + +**Example:** +```python +def get_user(user_id): + db.delete_user(user_id) # Says "get" but does "delete"! +``` + +Traditional tools say: ✓ No syntax errors +Harmonizer says: ⚠️ Semantic disharmony detected + +--- + +### How is this different from other code analysis tools? + +| Tool Type | What It Checks | Example | +|-----------|----------------|---------| +| **Syntax Checkers** (python -m py_compile) | Valid Python syntax | `def foo(` → Syntax Error | +| **Linters** (flake8, pylint) | Code style, basic issues | Missing docstring, unused variable | +| **Type Checkers** (mypy) | Type consistency | `str` where `int` expected | +| **Test Frameworks** (pytest) | Functional correctness | Does the code produce expected outputs? | +| **Harmonizer** | **Semantic meaning** | Does function name match implementation? | + +**Harmonizer catches bugs that other tools miss:** +- Function names that promise one thing but deliver another +- Semantic contradictions (e.g., "validate" that actually "deletes") +- Logic that's technically correct but conceptually wrong + +--- + +### Do I still need linters and type checkers? + +**Yes!** Harmonizer complements, doesn't replace. + +**Use all of them together:** +```bash +# Check syntax +python -m py_compile mycode.py + +# Check style and common issues +flake8 mycode.py + +# Check type consistency +mypy mycode.py + +# Check functional correctness +pytest tests/ + +# Check semantic meaning +harmonizer mycode.py +``` + +**Each catches different categories of bugs:** +- Linters: Style and simple errors +- Type checkers: Type mismatches +- Tests: Wrong behavior +- **Harmonizer: Wrong meaning** + +--- + +### What problems does it actually solve? + +**Real-world scenarios where Harmonizer helps:** + +**1. Misleading Function Names** +```python +def check_permissions(user): + user.permissions = "admin" # Checking? Or modifying? +``` +→ Caught by Harmonizer, missed by other tools + +**2. API Design Issues** +```python +@app.route("/users/", methods=["GET"]) +def get_user(id): + update_last_accessed(id) # GET shouldn't modify state! +``` +→ REST principle violation, semantic bug + +**3. Code Review Clarity** +```python +def process_data(data): + db.delete(data) # "Process" is too vague +``` +→ Vague naming caught + +**4. Refactoring Gone Wrong** +```python +# Originally was validate_email, then requirements changed +def validate_email(email): + send_welcome_email(email) # Name never updated! +``` +→ Stale name detected + +--- + +## Technical Questions + +### What does "semantic code debugging" mean? + +**Semantic** = relating to meaning in language + +**Semantic code debugging** = analyzing what code **means**, not just what it **says**. + +**Example:** +```python +def create_backup(): + database.drop_all_tables() # Syntax: ✓ Meaning: ✗ +``` + +- **Syntactically**: Valid Python +- **Semantically**: "create_backup" implies preservation, but code destroys data +- **Traditional tools**: Won't catch this +- **Harmonizer**: Detects semantic contradiction + +--- + +### How does it calculate disharmony scores? + +**High-level process:** + +1. **Parse function name** → Extract semantic concepts + - `get_user_by_id` → "get", "user", "information" + +2. **Parse function body** → Extract action concepts + - `db.delete(user)` → "delete", "remove", "force" + +3. **Map to semantic dimensions** → Using DIVE-V2 engine + - "get" → Wisdom (information seeking) + - "delete" → Power (destructive action) + +4. **Calculate semantic distance** → Euclidean distance in 4D space + - Distance between Intent and Execution coordinates + +5. **Report score** → Higher distance = higher disharmony + +**Simplified example:** +``` +Intent "get": (Love=0.1, Justice=0.2, Power=0.0, Wisdom=0.7) +Execution "delete": (Love=0.0, Justice=0.2, Power=0.8, Wisdom=0.0) + +Distance = sqrt((0.1-0.0)² + (0.2-0.2)² + (0.0-0.8)² + (0.7-0.0)²) + ≈ 1.05 → HIGH DISHARMONY +``` + +--- + +### What is the Anchor Point (1,1,1,1)? + +The **Anchor Point** represents "Perfect Logical Harmony" in 4-dimensional semantic space. + +**The four dimensions:** +- **Love (L)** = Unity, compassion, connection +- **Justice (J)** = Truth, fairness, order +- **Power (P)** = Action, strength, execution +- **Wisdom (W)** = Knowledge, understanding, insight + +**(1,1,1,1)** = Perfect balance of all four dimensions + +**In practice:** +- All disharmony scores are measured as distance from this anchor +- Closer to (1,1,1,1) = more harmonious +- Further from (1,1,1,1) = more disharmonious + +**For more details**, see [Philosophy documentation](PHILOSOPHY.md) + +--- + +### What is the ICE Framework? + +**ICE** = **Intent, Context, Execution** + +**A framework for analyzing code semantically:** + +1. **Intent** (I): What the function **promises** to do + - Extracted from: function name, docstring + - Semantic components: Love + Wisdom + +2. **Context** (C): The **situation** in which it operates + - Extracted from: function signature, parameters + - Semantic component: Justice (truth about reality) + +3. **Execution** (E): What the function **actually** does + - Extracted from: function body, operations + - Semantic component: Power (manifestation) + +**Harmonious code** = Intent and Execution align + +**Disharmonious code** = Intent and Execution contradict + +--- + +### Does it use AI/ML? + +**No**, Python Code Harmonizer does **not** use machine learning or AI models. + +**It uses:** +- **Semantic vocabulary mapping** (predefined keyword-to-concept mappings) +- **Abstract Syntax Tree (AST) parsing** (Python's built-in `ast` module) +- **Mathematical distance calculations** (Euclidean geometry in 4D space) +- **Deterministic algorithms** (same input = same output, always) + +**Advantages:** +- Fast and deterministic +- No training data needed +- No "black box" decisions +- Fully explainable results +- Works offline + +--- + +## Usage Questions + +### Can I customize the disharmony threshold? + +**Currently:** The threshold is set to **0.5** in the code. + +**Future enhancement:** We plan to add command-line options: + +```bash +# Strict mode (flag anything > 0.3) +harmonizer --threshold 0.3 mycode.py + +# Lenient mode (only critical issues > 0.8) +harmonizer --threshold 0.8 mycode.py +``` + +**For now**, you can modify the threshold in your code: + +```python +from src.harmonizer.main import PythonCodeHarmonizer + +harmonizer = PythonCodeHarmonizer(disharmony_threshold=0.3) +report = harmonizer.analyze_file("mycode.py") +``` + +--- + +### Can I use it in CI/CD pipelines? + +**Yes!** Harmonizer works great in continuous integration. + +**Example GitHub Actions:** +```yaml +name: Code Harmony Check + +on: [push, pull_request] + +jobs: + harmony: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.8' + - name: Install harmonizer + run: | + pip install . + - name: Run harmony analysis + run: | + harmonizer src/**/*.py +``` + +**Example GitLab CI:** +```yaml +harmony_check: + script: + - pip install . + - harmonizer src/ + only: + - merge_requests +``` + +**Parsing output in CI:** +Currently, Harmonizer outputs human-readable text. For CI integration, you can: +1. Parse the text output +2. Set exit codes based on severity +3. (Future) Use JSON output mode (planned enhancement) + +--- + +### Does it work with other Python tools? + +**Yes!** Harmonizer integrates well with standard Python tooling. + +**pre-commit integration:** +```yaml +# .pre-commit-config.yaml +repos: + - repo: local + hooks: + - id: harmonizer + name: Python Code Harmonizer + entry: harmonizer + language: system + types: [python] +``` + +**With tox:** +```ini +# tox.ini +[testenv:harmony] +deps = + path/to/harmonizer +commands = + harmonizer src/ +``` + +**With make:** +```makefile +# Makefile +.PHONY: harmony +harmony: + harmonizer src/**/*.py + +.PHONY: quality +quality: lint typecheck test harmony +``` + +--- + +### Can I integrate it with my IDE? + +**Not yet directly**, but you can: + +**1. Run as external tool:** +Most IDEs allow configuring external commands. Add harmonizer as an external tool. + +**VS Code example:** +```json +// tasks.json +{ + "version": "2.0.0", + "tasks": [ + { + "label": "Check Harmony", + "type": "shell", + "command": "harmonizer ${file}", + "group": "test" + } + ] +} +``` + +**2. Use with file watchers:** +Configure your IDE to run harmonizer when files are saved. + +**3. Future plans:** +We're exploring official IDE plugins for: +- VS Code +- PyCharm +- Sublime Text + +--- + +### Does it work on large codebases? + +**Yes**, but with some considerations: + +**Performance:** +- Analyzing individual files is fast (< 100ms per file) +- Large codebases: analyze file-by-file or in parallel + +**Scalability tips:** +```bash +# Analyze specific modules +harmonizer src/core/**/*.py + +# Analyze changed files only (for CI) +git diff --name-only main | grep '\.py$' | xargs harmonizer + +# Parallel analysis (GNU parallel) +find src/ -name "*.py" | parallel harmonizer {} +``` + +**Recommended workflow for large projects:** +1. Start with high-priority modules +2. Run on changed files in CI/CD +3. Gradually expand coverage +4. Track average harmony scores over time + +--- + +## Interpretation Questions + +### Why is my function flagged when it seems fine? + +**Common reasons:** + +**1. Mixed semantics (intentional but detected)** +```python +def get_or_create_user(id): + # "get" (read) + "create" (write) = slight disharmony + # This is OK if name accurately describes dual purpose +``` + +**2. Vague verb with specific action** +```python +def process_data(data): + db.delete(data) # "process" is vague, "delete" is specific +``` + +**3. Semantic distance calculation** +Sometimes concepts that seem similar are semantically distant: +```python +def validate_input(data): + sanitize_and_transform(data) # "validate" ≠ "transform" +``` + +**What to do:** +1. Read the function carefully +2. Ask: "Does the name accurately describe what it does?" +3. If yes and disharmony is low (0.5-0.6), it's probably fine +4. If disharmony is high (> 0.8), investigate further + +--- + +### Should I fix ALL disharmony? + +**No!** Use judgment. + +**Fix these:** +- ✅ High scores (> 0.8): Likely real issues +- ✅ Contradictory semantics: Clear bugs +- ✅ Misleading names: Confusion for developers + +**Consider these:** +- ⚠️ Medium scores (0.5-0.8): Might be intentional +- ⚠️ Functions with documented dual purposes +- ⚠️ Legacy code that works correctly + +**Don't worry about these:** +- ✓ Low scores (< 0.5): Probably fine +- ✓ Slight disharmony with clear documentation +- ✓ Established patterns that team understands + +**Context matters!** + +--- + +### What if my function legitimately does multiple things? + +**Option 1: Rename to reflect dual purpose** +```python +def validate_and_save_user(user): + """Validate user data and save to database if valid""" + if not is_valid(user): + raise ValidationError() + db.save(user) +``` + +**Option 2: Split into separate functions** (preferred) +```python +def validate_user(user): + """Check if user data is valid""" + if not is_valid(user): + raise ValidationError() + +def save_user(user): + """Save user to database""" + db.save(user) + +# Usage +validate_user(user) +save_user(user) +``` + +**Option 3: Document the intentional disharmony** +```python +def fetch_and_cache_data(key): + """ + Retrieve data and cache result (dual purpose). + + Note: This function both reads and writes. + Harmonizer may flag due to mixed semantics - this is intentional. + """ + data = api.fetch(key) + cache.set(key, data) + return data +``` + +--- + +### Are low scores always good? + +**Mostly yes, but not always.** + +**Low score scenarios:** + +**Good (true harmony):** +```python +def delete_user(id): + db.delete(id) # Low score, good alignment ✓ +``` + +**Less informative (vague name):** +```python +def do_something(data): + do_something_else(data) # Low score but unhelpful names +``` + +**Harmonizer checks semantic alignment, not code quality overall.** + +**Other tools for:** +- Code complexity: Use `radon` or `mccabe` +- Documentation: Use `pydocstyle` +- Test coverage: Use `pytest-cov` + +--- + +## Philosophical Questions + +### Why does naming matter so much? + +**Three reasons:** + +**1. Communication** +Code is read 10x more than it's written. Names are your interface to other developers (including future you). + +**2. Intention** +Good names reveal **intent**. Bad names hide it. +```python +# What does this do? +def process_data(data): + ... + +# Now we know! +def archive_inactive_users(users): + ... +``` + +**3. Bugs** +Misleading names cause bugs when developers make wrong assumptions: +```python +def get_config(): + # Developer assumes read-only + # Actually modifies global state + # Bugs follow +``` + +--- + +### Isn't this just enforcing subjective style preferences? + +**No, it's detecting semantic contradictions.** + +**Subjective (style):** +- "Use snake_case vs camelCase" +- "Max line length should be 80" +- "Always use type hints" + +**Objective (semantics):** +- "Function named 'get' shouldn't delete data" +- "Function named 'validate' shouldn't send emails" +- "Read operations shouldn't modify state" + +**Harmonizer detects objective semantic mismatches, not style preferences.** + +--- + +### What's the philosophy behind this tool? + +Python Code Harmonizer is built on the **ICE Framework** and **Anchor Point** philosophy. + +**Core idea:** All meaningful action can be understood through three lenses: +1. **Intent** (what you want to do) +2. **Context** (the situation you're in) +3. **Execution** (what you actually do) + +**In code:** +- Intent = function name and documentation +- Context = parameters and environment +- Execution = function body + +**Harmony** = alignment between these three. + +**Detailed explanation:** See [PHILOSOPHY.md](PHILOSOPHY.md) + +--- + +## Troubleshooting + +### The tool isn't detecting obvious problems + +**Possible reasons:** + +**1. Function name is vague** +```python +def process_user(id): + db.delete(id) +``` +"process" is semantically vague, so distance might be moderate rather than high. + +**2. Concepts aren't in vocabulary** +If using domain-specific terms not in DIVE-V2's vocabulary, mapping may be imprecise. + +**3. Semantic distance calculation** +Some concepts that seem obviously different might be closer in 4D semantic space than expected. + +**What to do:** +- Use specific, clear verbs in function names +- Focus on high scores (> 0.8) for most obvious issues +- File an issue if you find cases where it should flag but doesn't + +--- + +### I'm getting import errors + +**Error:** `No module named 'src.divine_invitation_engine_V2'` + +**Solution:** +```bash +# Reinstall package +pip uninstall PythonCodeHarmonizer +pip install . + +# Or install in editable mode for development +pip install -e . +``` + +**Error:** `No module named 'src.ast_semantic_parser'` + +**Solution:** Same as above - ensure package is properly installed. + +--- + +### Scores seem inconsistent + +**Why this might happen:** + +**1. Function context affects score** +The same operation in different contexts may score differently based on surrounding code. + +**2. Caching in DIVE-V2** +DIVE-V2 caches concept analysis for performance. Restart if you suspect stale cache. + +**3. Complex interactions** +Functions with multiple operations have scores based on semantic centroid of all operations. + +**What to do:** +- Focus on relative scores (which functions score highest) +- Don't over-interpret small differences (0.52 vs 0.54) +- Use scores as conversation starters, not absolute truth + +--- + +## Still Have Questions? + +**Documentation:** +- [User Guide](USER_GUIDE.md) - Comprehensive usage information +- [Tutorial](TUTORIAL.md) - Hands-on learning with examples +- [Philosophy](PHILOSOPHY.md) - Deep dive into the framework +- [Architecture](ARCHITECTURE.md) - Technical implementation details + +**Support:** +- GitHub Issues: [github.com/BruinGrowly/Python-Code-Harmonizer/issues](https://github.com/BruinGrowly/Python-Code-Harmonizer/issues) +- Discussions: Ask questions and share insights + +**Contributing:** +- See [CONTRIBUTING.md](../CONTRIBUTING.md) for how to contribute + +--- + +**Happy harmonizing! May your code always say what it means and mean what it says.** 💛⚓ diff --git a/docs/TUTORIAL.md b/docs/TUTORIAL.md new file mode 100644 index 0000000..e26ffd4 --- /dev/null +++ b/docs/TUTORIAL.md @@ -0,0 +1,679 @@ +# Python Code Harmonizer - Tutorial + +## Welcome! + +This tutorial will walk you through using Python Code Harmonizer with real examples. By the end, you'll understand how to identify semantic bugs and improve your code's clarity. + +--- + +## Table of Contents + +1. [Setup](#setup) +2. [Tutorial 1: Your First Analysis](#tutorial-1-your-first-analysis) +3. [Tutorial 2: Understanding Disharmony Patterns](#tutorial-2-understanding-disharmony-patterns) +4. [Tutorial 3: Refactoring for Harmony](#tutorial-3-refactoring-for-harmony) +5. [Tutorial 4: Real-World Scenarios](#tutorial-4-real-world-scenarios) +6. [Tutorial 5: Building Good Habits](#tutorial-5-building-good-habits) +7. [Exercises](#exercises) + +--- + +## Setup + +**Before starting, ensure you have:** +```bash +# Install Python Code Harmonizer +pip install . + +# Verify installation +harmonizer --help +``` + +**Create a practice directory:** +```bash +mkdir harmony-tutorial +cd harmony-tutorial +``` + +--- + +## Tutorial 1: Your First Analysis + +### Step 1: Create a Simple File + +Create `simple_example.py`: + +```python +def get_user_data(user_id): + """Retrieve user information from database""" + user = database.query("SELECT * FROM users WHERE id = ?", user_id) + return user + +def calculate_price(items): + """Calculate total price of items""" + total = sum(item.price for item in items) + return total + +def remove_user(user_id): + """Delete user from database""" + database.execute("DELETE FROM users WHERE id = ?", user_id) + return True +``` + +### Step 2: Run the Harmonizer + +```bash +harmonizer simple_example.py +``` + +### Step 3: Observe the Output + +``` +====================================================================== +Python Code Harmonizer (v1.1) ONLINE +... +====================================================================== + +Analyzing file: simple_example.py +---------------------------------------------------------------------- +FUNCTION NAME | INTENT-EXECUTION DISHARMONY +-----------------------------|-------------------------------- +get_user_data | ✓ HARMONIOUS +calculate_price | ✓ HARMONIOUS +remove_user | ✓ HARMONIOUS +====================================================================== +Analysis Complete. +``` + +### What Just Happened? + +**All three functions are HARMONIOUS** because: + +1. **`get_user_data`**: + - Name says: "get" (retrieve information) + - Code does: `query` (retrieve information) + - ✓ ALIGNED + +2. **`calculate_price`**: + - Name says: "calculate" (compute a value) + - Code does: `sum` (compute a value) + - ✓ ALIGNED + +3. **`remove_user`**: + - Name says: "remove" (delete/destroy) + - Code does: `DELETE` (delete/destroy) + - ✓ ALIGNED + +**Key Learning:** When function names match their implementation's semantic meaning, harmony scores stay low. + +--- + +## Tutorial 2: Understanding Disharmony Patterns + +Now let's introduce semantic bugs and see how Harmonizer catches them. + +### Pattern 1: Action Contradiction + +Create `contradictions.py`: + +```python +def get_user_data(user_id): + """Retrieve user information""" + # BUG: Says "get" but actually "delete"! + database.execute("DELETE FROM users WHERE id = ?", user_id) + return None + +def validate_email(email): + """Check if email is valid format""" + # BUG: Says "validate" but actually "send"! + email_service.send_welcome_email(email) + return True + +def check_permissions(user): + """Verify user has required permissions""" + # BUG: Says "check" but actually "modify"! + user.permissions = "admin" + database.save(user) + return True +``` + +Run the harmonizer: + +```bash +harmonizer contradictions.py +``` + +**Expected Output:** + +``` +FUNCTION NAME | INTENT-EXECUTION DISHARMONY +-----------------------------|-------------------------------- +get_user_data | !! DISHARMONY (Score: 1.41) +validate_email | !! DISHARMONY (Score: 0.95) +check_permissions | !! DISHARMONY (Score: 0.78) +``` + +### Why These Score High: + +1. **`get_user_data` (Score: 1.41 - CRITICAL)** + - Intent: "get" = retrieve, read (Wisdom domain) + - Execution: "delete" = destroy, force (Power domain) + - These are **semantic opposites** → Very high score + +2. **`validate_email` (Score: 0.95 - HIGH)** + - Intent: "validate" = check, verify (Justice domain) + - Execution: "send" = action, transmission (Power domain) + - Checking vs. acting → Significant mismatch + +3. **`check_permissions` (Score: 0.78 - HIGH)** + - Intent: "check" = read-only verification (Justice/Wisdom) + - Execution: "modify" = state change (Power) + - Read vs. write → Clear violation + +### Pattern 2: Scope Mismatch + +Create `scope_mismatch.py`: + +```python +def delete_user_session(session_id): + """Remove user's current session""" + # BUG: Deletes entire user, not just session! + database.execute("DELETE FROM users WHERE session_id = ?", session_id) + database.execute("DELETE FROM sessions WHERE id = ?", session_id) + +def update_username(user_id, new_name): + """Change user's username""" + # BUG: Updates more than just username! + database.execute(""" + UPDATE users + SET username = ?, + email = ?, + permissions = 'admin', + last_modified = NOW() + WHERE id = ? + """, new_name, "admin@example.com", user_id) +``` + +Run harmonizer: + +```bash +harmonizer scope_mismatch.py +``` + +**Why These Score High:** + +- Function promises specific scope but delivers broader scope +- `delete_user_session` says "session" but deletes "user" → Semantic overreach +- `update_username` says "username" but changes email, permissions, etc. → Scope violation + +### Pattern 3: Vague Names with Specific Actions + +Create `vague_names.py`: + +```python +def process_data(data): + """Process incoming data""" + # What does "process" mean? This is TOO specific for such a vague name + database.execute("DELETE FROM archive WHERE data_id = ?", data.id) + +def handle_request(request): + """Handle incoming request""" + # "Handle" is vague, but this does something very specific + user_service.permanently_ban_user(request.user_id) + +def manage_user(user_id): + """Manage user account""" + # "Manage" is vague, this is destructive + database.execute("DROP TABLE users") +``` + +**Why These May Show Moderate Disharmony:** + +- Vague verbs ("process", "handle", "manage") paired with specific, powerful actions +- Creates semantic ambiguity +- Scores may be moderate (0.4-0.7) depending on specific implementation + +--- + +## Tutorial 3: Refactoring for Harmony + +Let's take disharmonious code and fix it. + +### Example: The "get_user" Bug + +**BEFORE (Disharmonious):** + +```python +def get_user(user_id): + """Retrieve user by ID""" + database.execute("DELETE FROM users WHERE id = ?", user_id) + return None +``` + +**Harmonizer says:** `!! DISHARMONY (Score: 1.41)` + +### Fix Option 1: Correct the Implementation + +If the name is right but code is wrong: + +```python +def get_user(user_id): + """Retrieve user by ID""" + user = database.query("SELECT * FROM users WHERE id = ?", user_id) + return user +``` + +**Harmonizer says:** `✓ HARMONIOUS` + +### Fix Option 2: Correct the Name + +If the code is right but name is wrong: + +```python +def delete_user(user_id): + """Remove user from system""" + database.execute("DELETE FROM users WHERE id = ?", user_id) + return None +``` + +**Harmonizer says:** `✓ HARMONIOUS` + +### Fix Option 3: Split the Function + +If it legitimately does both: + +```python +def get_and_archive_user(user_id): + """Retrieve user data and move to archive (deletes from active users)""" + user = database.query("SELECT * FROM users WHERE id = ?", user_id) + database.execute("INSERT INTO archived_users SELECT * FROM users WHERE id = ?", user_id) + database.execute("DELETE FROM users WHERE id = ?", user_id) + return user +``` + +**Note:** This might still show slight disharmony (mixed semantics), which is OK if intentional and documented. + +### Practice Exercise + +**Fix this code:** + +```python +def validate_and_send_email(email): + """Check email format and send welcome message""" + if "@" not in email: + return False + email_service.send(email, "Welcome!") + return True +``` + +**Refactoring options:** + +**Option A: Split into two functions** +```python +def validate_email(email): + """Check if email format is valid""" + return "@" in email + +def send_welcome_email(email): + """Send welcome message to email""" + email_service.send(email, "Welcome!") + return True + +# Usage +if validate_email(user.email): + send_welcome_email(user.email) +``` + +**Option B: Rename to match dual purpose** +```python +def validate_and_send_welcome_email(email): + """Validate email format, then send welcome message if valid""" + if "@" not in email: + return False + email_service.send(email, "Welcome!") + return True +``` + +**Which is better?** +- **Option A** = Better separation of concerns, more testable, more reusable +- **Option B** = Acceptable if this specific sequence is always needed together + +--- + +## Tutorial 4: Real-World Scenarios + +### Scenario 1: Code Review + +You're reviewing a pull request. Run harmonizer: + +```bash +harmonizer pr_branch/new_feature.py +``` + +**Output:** +``` +FUNCTION NAME | INTENT-EXECUTION DISHARMONY +-----------------------------|-------------------------------- +authenticate_user | !! DISHARMONY (Score: 0.92) +fetch_data | ✓ HARMONIOUS +save_results | ✓ HARMONIOUS +``` + +**Investigation:** + +```python +def authenticate_user(username, password): + """Verify user credentials""" + if check_password(username, password): + # BUG: Authentication function is creating sessions! + session = create_new_session(username) + grant_admin_privileges(username) # BUG: And granting admin! + return session + return None +``` + +**Problem:** Function promises authentication (verification) but also performs authorization actions (granting privileges). + +**Fix:** +```python +def authenticate_user(username, password): + """Verify user credentials and return user object if valid""" + if check_password(username, password): + return get_user(username) + return None + +def create_user_session(user): + """Create new session for authenticated user""" + return create_new_session(user.username) +``` + +### Scenario 2: Legacy Code Cleanup + +You're refactoring old code. Run harmonizer on legacy module: + +```bash +harmonizer legacy/user_management.py +``` + +**Output:** +``` +FUNCTION NAME | INTENT-EXECUTION DISHARMONY +-----------------------------|-------------------------------- +process_user | !! DISHARMONY (Score: 1.15) +handle_data | !! DISHARMONY (Score: 0.89) +do_stuff | !! DISHARMONY (Score: 0.76) +user_function | !! DISHARMONY (Score: 0.65) +``` + +**Analysis:** All functions have vague names. Let's look at one: + +```python +def process_user(user_id): + """Process user""" + # What does this actually do? + database.execute("DELETE FROM temp_users WHERE id = ?", user_id) + database.execute("INSERT INTO permanent_users SELECT * FROM users WHERE id = ?", user_id) + send_confirmation_email(user_id) + log_event("user_activated", user_id) +``` + +**Better name:** +```python +def activate_user_account(user_id): + """Activate user by moving from temporary to permanent storage""" + database.execute("DELETE FROM temp_users WHERE id = ?", user_id) + database.execute("INSERT INTO permanent_users SELECT * FROM users WHERE id = ?", user_id) + send_confirmation_email(user_id) + log_event("user_activated", user_id) +``` + +**Key insight:** Vague names like "process", "handle", "do_stuff", "function" are code smells that harmonizer catches. + +### Scenario 3: API Design + +You're designing a public API. Run harmonizer: + +```bash +harmonizer api/endpoints.py +``` + +**Output:** +``` +FUNCTION NAME | INTENT-EXECUTION DISHARMONY +-----------------------------|-------------------------------- +get_user | !! DISHARMONY (Score: 0.71) +``` + +**Investigation:** +```python +@app.route("/api/users/", methods=["GET"]) +def get_user(user_id): + """GET /api/users/:id - Retrieve user information""" + user = database.query("SELECT * FROM users WHERE id = ?", user_id) + + # BUG: GET endpoint is modifying state! + database.execute("UPDATE users SET last_accessed = NOW() WHERE id = ?", user_id) + analytics.track_access(user_id) + + return jsonify(user) +``` + +**Problem:** GET requests should be read-only (REST principle), but this modifies database. + +**Fix Option 1: Make it truly read-only** +```python +@app.route("/api/users/", methods=["GET"]) +def get_user(user_id): + """GET /api/users/:id - Retrieve user information""" + user = database.query("SELECT * FROM users WHERE id = ?", user_id) + # Track access asynchronously without blocking/modifying + analytics_queue.add("user_accessed", user_id) + return jsonify(user) +``` + +**Fix Option 2: Use POST if modification is essential** +```python +@app.route("/api/users//access", methods=["POST"]) +def record_user_access(user_id): + """POST /api/users/:id/access - Record access and return user data""" + user = database.query("SELECT * FROM users WHERE id = ?", user_id) + database.execute("UPDATE users SET last_accessed = NOW() WHERE id = ?", user_id) + analytics.track_access(user_id) + return jsonify(user) +``` + +--- + +## Tutorial 5: Building Good Habits + +### Habit 1: Name Functions After What They DO + +**Bad:** +```python +def user_function(user): # What does this do? +def handle_user(user): # Handle how? +def process_data(data): # Process how? +``` + +**Good:** +```python +def delete_inactive_user(user) +def send_welcome_email_to_user(user) +def archive_user_data(data) +``` + +### Habit 2: Use Semantic Verb Patterns + +**Reading Operations** (Wisdom domain): +- `get_*`, `fetch_*`, `retrieve_*`, `find_*`, `query_*`, `read_*` + +**Validation Operations** (Justice domain): +- `validate_*`, `verify_*`, `check_*`, `is_*`, `has_*` + +**Writing Operations** (Power domain): +- `create_*`, `update_*`, `delete_*`, `remove_*`, `insert_*`, `save_*` + +**Computation Operations** (Wisdom domain): +- `calculate_*`, `compute_*`, `analyze_*`, `transform_*` + +**Mixed Operations** (Be explicit): +- `get_or_create_*`, `find_and_update_*`, `validate_and_save_*` + +### Habit 3: Run Harmonizer on New Code + +**Before committing:** +```bash +git diff --name-only | grep '\.py$' | xargs harmonizer +``` + +**Before pushing:** +```bash +harmonizer $(git diff origin/main --name-only | grep '\.py$') +``` + +### Habit 4: Set Team Standards + +**Example team policy:** +- ✅ All functions must score < 0.5 (harmonious) +- ⚠️ Functions 0.5-0.8 require explanation in PR +- ❌ Functions > 0.8 must be refactored + +--- + +## Exercises + +### Exercise 1: Identify the Bug + +What's wrong with this code? Run harmonizer to verify your intuition. + +```python +def backup_database(): + """Create backup of database""" + database.execute("DROP DATABASE production") +``` + +
+Answer + +**Problem:** Function says "backup" (preservation) but does "DROP" (destruction) + +**Fix:** +```python +def backup_database(): + """Create backup of database""" + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + database.execute(f"CREATE DATABASE backup_{timestamp} AS COPY OF production") +``` +
+ +### Exercise 2: Refactor for Harmony + +Refactor this function to reduce disharmony: + +```python +def get_user_profile(user_id): + """Retrieve user profile information""" + user = database.query("SELECT * FROM users WHERE id = ?", user_id) + user.last_login = datetime.now() + database.save(user) + send_analytics_event("profile_viewed", user_id) + return user +``` + +
+Solution + +**Option A: Make it truly read-only** +```python +def get_user_profile(user_id): + """Retrieve user profile information (read-only)""" + user = database.query("SELECT * FROM users WHERE id = ?", user_id) + return user + +def record_profile_view(user_id): + """Record that user profile was viewed""" + user = get_user_profile(user_id) + user.last_login = datetime.now() + database.save(user) + send_analytics_event("profile_viewed", user_id) +``` + +**Option B: Rename to match behavior** +```python +def get_user_profile_and_record_access(user_id): + """Retrieve user profile and record access time""" + user = database.query("SELECT * FROM users WHERE id = ?", user_id) + user.last_login = datetime.now() + database.save(user) + send_analytics_event("profile_viewed", user_id) + return user +``` +
+ +### Exercise 3: Design Good Names + +You need functions that: +1. Check if email format is valid +2. Send email to user +3. Check email validity AND send if valid +4. Delete user's email from database +5. Update user's email address + +Write good function names and verify with harmonizer. + +
+Solution + +```python +def validate_email_format(email): + """Check if email string has valid format""" + return "@" in email and "." in email + +def send_email(to_address, subject, body): + """Send email message to address""" + email_service.send(to_address, subject, body) + +def validate_and_send_email(email, subject, body): + """Validate email format and send message if valid""" + if validate_email_format(email): + send_email(email, subject, body) + return True + return False + +def delete_user_email(user_id): + """Remove user's email address from database""" + database.execute("UPDATE users SET email = NULL WHERE id = ?", user_id) + +def update_user_email(user_id, new_email): + """Change user's email address""" + database.execute("UPDATE users SET email = ? WHERE id = ?", new_email, user_id) +``` + +All should show low disharmony scores! +
+ +--- + +## Next Steps + +**You've completed the tutorial!** You now understand: + +✅ How to run Python Code Harmonizer +✅ How to interpret disharmony scores +✅ Common patterns that cause semantic bugs +✅ How to refactor code for harmony +✅ How to build good naming habits + +**Continue learning:** +- Read the [User Guide](USER_GUIDE.md) for comprehensive usage info +- Explore the [Philosophy](PHILOSOPHY.md) to understand the Anchor Point and ICE Framework +- Check the [FAQ](FAQ.md) for common questions + +**Practice makes perfect:** +- Run harmonizer on your own code +- Make it part of your daily workflow +- Share findings with your team + +--- + +**Happy coding, and may your functions always do what their names promise!** 💛⚓ diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md new file mode 100644 index 0000000..6ddc662 --- /dev/null +++ b/docs/USER_GUIDE.md @@ -0,0 +1,533 @@ +# Python Code Harmonizer - User Guide + +## Table of Contents + +1. [Introduction](#introduction) +2. [Installation](#installation) +3. [Quick Start](#quick-start) +4. [Understanding the Output](#understanding-the-output) +5. [Interpreting Disharmony Scores](#interpreting-disharmony-scores) +6. [Common Use Cases](#common-use-cases) +7. [Integration into Your Workflow](#integration-into-your-workflow) +8. [Best Practices](#best-practices) +9. [Troubleshooting](#troubleshooting) +10. [Getting Help](#getting-help) + +--- + +## Introduction + +### What is Python Code Harmonizer? + +Python Code Harmonizer is the world's first **semantic code debugger**. Unlike traditional tools that only check syntax, it analyzes the **meaning** of your code to find logical inconsistencies. + +**The core question it asks:** *"Does your code DO what its name SAYS it does?"* + +### What Problems Does It Solve? + +Traditional bugs that compilers and linters miss: + +- **Semantic bugs**: Code that runs without errors but does the wrong thing +- **Intent-execution mismatches**: Function names that promise one thing but deliver another +- **Logic contradictions**: Code that works technically but violates its own purpose + +### Example Problem It Detects + +```python +def get_user_by_id(user_id): + """Fetch user information by ID""" + # This WORKS syntactically, but it's semantically WRONG + db.delete_user(user_id) # Deleting instead of getting! + return None +``` + +**Traditional tools say:** ✓ No syntax errors +**Python Code Harmonizer says:** ⚠️ DISHARMONY - Function promises to "get" but actually "deletes" + +--- + +## Installation + +### Prerequisites + +- Python 3.8 or higher +- pip (Python package installer) + +### Basic Installation + +1. **Clone the repository:** + ```bash + git clone https://github.com/BruinGrowly/Python-Code-Harmonizer.git + cd Python-Code-Harmonizer + ``` + +2. **Install the package:** + ```bash + pip install . + ``` + +3. **Verify installation:** + ```bash + harmonizer --help + ``` + + If you see usage information, you're ready to go! + +### Installation in Virtual Environment (Recommended) + +```bash +# Create virtual environment +python -m venv venv + +# Activate it +source venv/bin/activate # On Windows: venv\Scripts\activate + +# Install +pip install . +``` + +### Development Installation + +If you want to modify the code or contribute: + +```bash +pip install -r requirements.txt +pip install -e . +``` + +--- + +## Quick Start + +### Analyzing Your First File + +1. **Create a test file** (or use the included example): + ```bash + harmonizer examples/test_code.py + ``` + +2. **See the results:** + ``` + ====================================================================== + Python Code Harmonizer (v1.1) ONLINE + Actively guided by the Anchor Point framework. + Powered By: DIVE-V2 (Optimized Production) + Logical Anchor Point: (S=1, L=1, I=1, E=1) + Disharmony Threshold: 0.5 + ====================================================================== + + Analyzing file: examples/test_code.py + ---------------------------------------------------------------------- + FUNCTION NAME | INTENT-EXECUTION DISHARMONY + -----------------------------|-------------------------------- + check_user_permissions | !! DISHARMONY (Score: 0.62) + delete_user | !! DISHARMONY (Score: 1.41) + get_user_by_id | ✓ HARMONIOUS + query | ✓ HARMONIOUS + ====================================================================== + Analysis Complete. + ``` + +### Analyzing Multiple Files + +```bash +harmonizer file1.py file2.py file3.py +``` + +### Analyzing Your Project + +```bash +# Analyze all Python files in a directory +find . -name "*.py" -exec harmonizer {} \; + +# Or use a loop +for file in src/**/*.py; do + harmonizer "$file" +done +``` + +--- + +## Understanding the Output + +### Report Header + +``` +Python Code Harmonizer (v1.1) ONLINE +Actively guided by the Anchor Point framework. +Powered By: DIVE-V2 (Optimized Production) +Logical Anchor Point: (S=1, L=1, I=1, E=1) +Disharmony Threshold: 0.5 +``` + +**What this means:** +- **Anchor Point (1,1,1,1)**: The reference point for "perfect logical harmony" +- **Threshold 0.5**: Functions scoring above 0.5 are flagged as disharmonious + +### Function Analysis Results + +Each function in your file gets a disharmony score: + +``` +FUNCTION NAME | INTENT-EXECUTION DISHARMONY +-----------------------------|-------------------------------- +check_user_permissions | !! DISHARMONY (Score: 0.62) +delete_user | !! DISHARMONY (Score: 1.41) +get_user_by_id | ✓ HARMONIOUS +query | ✓ HARMONIOUS +``` + +**Status Indicators:** +- `✓ HARMONIOUS`: Function name matches what the code does (score ≤ 0.5) +- `!! DISHARMONY (Score: X.XX)`: Semantic mismatch detected (score > 0.5) + +**Results are sorted by severity** (highest disharmony first) + +--- + +## Interpreting Disharmony Scores + +### Score Ranges and What They Mean + +| Score Range | Severity | Meaning | Action Recommended | +|-------------|----------|---------|-------------------| +| **0.0 - 0.3** | None | Perfect or near-perfect harmony | No action needed | +| **0.3 - 0.5** | Low | Minor semantic drift | Review for clarity | +| **0.5 - 0.8** | Medium | Notable semantic mismatch | Investigate and likely refactor | +| **0.8 - 1.2** | High | Significant logical contradiction | Definitely needs attention | +| **1.2+** | Critical | Severe semantic disharmony | Urgent review required | + +### What Causes High Disharmony? + +**1. Contradictory Action Verbs** + +```python +def get_user(user_id): + db.delete_user(user_id) # "get" vs "delete" = HIGH DISHARMONY +``` + +**Why:** "get" implies retrieval (information-seeking), "delete" implies destruction (force/power). These are semantically opposite. + +**2. Purpose-Action Mismatch** + +```python +def validate_email(email): + send_email(email) # "validate" vs "send" = MEDIUM DISHARMONY +``` + +**Why:** "validate" implies checking/verification, "send" implies action. The function promises to check but actually acts. + +**3. Read-Write Confusion** + +```python +def check_permissions(user): + user.permissions = "admin" # "check" vs "set" = HIGH DISHARMONY +``` + +**Why:** "check" implies read-only operation, but code is modifying state. + +### What Doesn't Cause Disharmony? + +**Properly Named Functions:** + +```python +def delete_user(user_id): + db.delete_user(user_id) # HARMONIOUS - name matches action + +def get_user(user_id): + return db.query(user_id) # HARMONIOUS - "get" and "query" align + +def calculate_total(items): + return sum(item.price for item in items) # HARMONIOUS +``` + +--- + +## Common Use Cases + +### 1. Code Review + +**Before merging code:** +```bash +harmonizer src/new_feature.py +``` + +Look for functions with high disharmony scores. These often indicate: +- Poorly named functions (fix the name) +- Functions doing too much (refactor/split) +- Logic errors (actual bugs!) + +### 2. Refactoring Legacy Code + +**When cleaning up old code:** +```bash +harmonizer legacy/old_module.py +``` + +High disharmony functions are prime refactoring candidates. They often reveal: +- Functions that have grown beyond their original purpose +- Misleading names that confuse developers +- Hidden side effects + +**Example workflow:** +1. Run harmonizer on legacy code +2. Sort functions by disharmony score +3. Start refactoring from highest scores +4. Re-run harmonizer to verify improvement + +### 3. Teaching/Learning Code Quality + +**For educators:** +- Show students how function names should match implementation +- Demonstrate semantic bugs that compilers miss +- Build intuition for "meaningful code" + +**For learners:** +- Scan your own code to find naming issues +- Learn to think semantically, not just syntactically +- Develop clearer coding habits + +### 4. API Design Review + +**When designing public APIs:** +```bash +harmonizer src/api/endpoints.py +``` + +API function names are especially critical - they're contracts with users. High disharmony here means: +- Misleading API documentation +- Developer confusion +- Integration bugs + +### 5. Bug Prevention in CI/CD + +**Add to your CI pipeline:** +```yaml +# .github/workflows/harmony-check.yml +- name: Check Code Harmony + run: | + pip install /path/to/harmonizer + harmonizer src/**/*.py +``` + +**Set standards:** +- Fail builds if any function scores > 1.0 +- Warn if any function scores > 0.5 +- Track harmony scores over time + +--- + +## Integration into Your Workflow + +### Daily Development + +**1. Pre-commit Hook** +```bash +# .git/hooks/pre-commit +#!/bin/bash +harmonizer $(git diff --cached --name-only --diff-filter=ACM | grep '\.py$') +``` + +**2. IDE Integration** +Run harmonizer on save or as part of your linting process. + +**3. Pull Request Checks** +Include harmony analysis in PR descriptions: +```markdown +## Code Harmony Analysis +- 15 functions analyzed +- 13 harmonious ✓ +- 2 with minor disharmony (scores: 0.52, 0.61) +- Addressed by renaming functions +``` + +### Team Standards + +**Establish harmony thresholds:** +- **Strict teams**: No functions > 0.5 allowed +- **Moderate teams**: Functions > 0.8 require justification +- **Legacy cleanup**: Track average harmony score over time (aim for improvement) + +**Code review checklist:** +- [ ] Does function name match implementation? +- [ ] Would harmonizer flag this function? +- [ ] Are semantic concepts aligned? + +--- + +## Best Practices + +### 1. Run Harmonizer Early and Often + +**Don't wait until code review:** +- Run on new functions as you write them +- Catch semantic issues immediately +- Build better naming habits + +### 2. Use Disharmony as a Discussion Tool + +**Not a strict rule, but a conversation starter:** +- "Why does this function score 0.85?" +- "Is the name wrong, or is the implementation wrong?" +- "Should we split this into two functions?" + +### 3. Context Matters + +**Some disharmony is intentional:** +```python +def safe_delete_user(user_id): + # High-level function that does validation + deletion + if validate_user_deletion(user_id): + db.delete_user(user_id) +``` + +This might show slight disharmony between "safe" (wisdom/caution) and "delete" (power/force), but it's **intentional** - the name communicates important safety semantics. + +**Use judgment:** Harmonizer highlights potential issues; you decide if they're real problems. + +### 4. Combine with Other Tools + +**Harmonizer complements, doesn't replace:** +- Use alongside `flake8`, `pylint` (syntax/style) +- Use alongside `mypy` (type checking) +- Use alongside `pytest` (functional correctness) + +**Each tool catches different issues:** +- `flake8`: "Your syntax has issues" +- `mypy`: "Your types don't match" +- `pytest`: "Your code doesn't work as expected" +- **`harmonizer`**: "Your code doesn't mean what it says" + +### 5. Document Intentional Disharmony + +If a function legitimately needs to do something unexpected: + +```python +def get_or_create_user(user_id): + """ + Retrieves user if exists, creates if not. + + Note: This function may modify database (create operation). + Harmonizer may flag due to 'get' + 'create' semantic mix. + This is intentional - name reflects dual purpose. + """ + user = db.query(user_id) + if not user: + user = db.create_user(user_id) + return user +``` + +--- + +## Troubleshooting + +### "No module named 'src.divine_invitation_engine_V2'" + +**Problem:** Import error when running harmonizer + +**Solution:** +```bash +# Ensure you installed the package properly +pip install -e . + +# Or reinstall +pip uninstall PythonCodeHarmonizer +pip install . +``` + +### "Syntax error on line X" + +**Problem:** Harmonizer can't parse your file + +**Solution:** +- Fix the syntax error first (use `python -m py_compile yourfile.py` to check) +- Harmonizer requires valid Python syntax before semantic analysis + +### File Not Found + +**Problem:** `ERROR: File not found at 'path/to/file.py'` + +**Solution:** +- Use absolute paths or verify your current directory +- Check file permissions + +### "No functions found to analyze" + +**Problem:** Report shows "No functions found" + +**Solution:** +- File might only contain classes, variables, or imports +- Harmonizer only analyzes function definitions +- Empty files or comment-only files will show no results + +### Unexpected Disharmony Scores + +**Problem:** Function you think is fine shows high disharmony + +**Solution:** +1. **Review the function name carefully** - does it promise something specific? +2. **Check the implementation** - does it do something different? +3. **Consider semantic distance** - are you mixing concepts (e.g., "validate" + "send")? + +**Common surprise:** +```python +def process_data(data): # "process" is vague + db.delete_data(data) # Specific action + # Score may be higher than expected +``` + +**Why:** "process" is semantically broad; "delete" is specific and powerful. If function primarily deletes, consider renaming to `delete_processed_data()` or `remove_data()`. + +--- + +## Getting Help + +### Documentation + +- **User Guide**: You're reading it! (docs/USER_GUIDE.md) +- **Tutorial**: Step-by-step examples (docs/TUTORIAL.md) +- **Philosophy**: Deep dive into how it works (docs/PHILOSOPHY.md) +- **Architecture**: Technical implementation details (docs/ARCHITECTURE.md) +- **FAQ**: Common questions answered (docs/FAQ.md) + +### Support Channels + +- **GitHub Issues**: Report bugs or request features at [github.com/BruinGrowly/Python-Code-Harmonizer/issues](https://github.com/BruinGrowly/Python-Code-Harmonizer/issues) +- **Discussions**: Ask questions and share experiences + +### Contributing + +Found a bug? Have an improvement? See [CONTRIBUTING.md](../CONTRIBUTING.md) for how to contribute. + +--- + +## Quick Reference Card + +### Installation +```bash +pip install . +``` + +### Basic Usage +```bash +harmonizer yourfile.py +``` + +### Multiple Files +```bash +harmonizer file1.py file2.py file3.py +``` + +### Understanding Scores +- **0.0-0.5**: Harmonious (✓) +- **0.5-0.8**: Medium disharmony (⚠️) +- **0.8+**: High disharmony (❗) + +### Key Concept +**Does the function name match what the code actually does?** +- If yes → Low score (harmonious) +- If no → High score (disharmony detected) + +--- + +**Happy harmonizing! May your code's intent and execution always align.** 💛⚓