{"id":46496146,"url":"https://github.com/vicsanity623/pyob","last_synced_at":"2026-03-10T08:04:55.369Z","repository":{"id":342256618,"uuid":"1171553074","full_name":"vicsanity623/PyOB","owner":"vicsanity623","description":"The Self-Healing, Symbolic Autonomous Source Code Architect. 100%[Python] Py-Ouroborus (PyOB)","archived":false,"fork":false,"pushed_at":"2026-03-06T13:40:40.000Z","size":1529,"stargazers_count":4,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-03-06T14:40:02.087Z","etag":null,"topics":["ai-tools","autonomous-architect","gemini-api","ollama","pure-python","self-healing-code","source-code-analysis","source-code-management","surgical-code-modifications","symbolic-links"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/vicsanity623.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":"ROADMAP.md","authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-03T11:03:39.000Z","updated_at":"2026-03-06T13:37:58.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/vicsanity623/PyOB","commit_stats":null,"previous_names":["vicsanity623/noclaw","vicsanity623/pyob"],"tags_count":12,"template":false,"template_full_name":null,"purl":"pkg:github/vicsanity623/PyOB","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vicsanity623%2FPyOB","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vicsanity623%2FPyOB/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vicsanity623%2FPyOB/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vicsanity623%2FPyOB/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vicsanity623","download_url":"https://codeload.github.com/vicsanity623/PyOB/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vicsanity623%2FPyOB/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30327583,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-10T05:25:20.737Z","status":"ssl_error","status_checked_at":"2026-03-10T05:25:17.430Z","response_time":106,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-tools","autonomous-architect","gemini-api","ollama","pure-python","self-healing-code","source-code-analysis","source-code-management","surgical-code-modifications","symbolic-links"],"created_at":"2026-03-06T12:04:09.127Z","updated_at":"2026-03-10T08:04:55.355Z","avatar_url":"https://github.com/vicsanity623.png","language":"Python","readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"pyob.png\" alt=\"PyOB\" width=\"512\" /\u003e\n\u003c/p\u003e\n\u003cdiv align=\"center\"\u003e\n\n# ∞ PyOuroBorus\n\n### The Self-Healing, Symbolic Autonomous Code Architect\n\n[![Python](https://img.shields.io/badge/Python-3.12+-3776AB?style=for-the-badge\u0026logo=python\u0026logoColor=white)](https://python.org)\n[![Gemini](https://img.shields.io/badge/Gemini-2.5_Flash-8E75B2?style=for-the-badge\u0026logo=google-gemini\u0026logoColor=white)](https://ai.google.dev/)\n[![Ollama](https://img.shields.io/badge/Ollama-Local_LLM-000000?style=for-the-badge\u0026logo=ollama\u0026logoColor=white)](https://ollama.ai)\n[![License](https://img.shields.io/badge/License-MIT-green?style=for-the-badge)]()\n![Verify Codebase](https://github.com/vicsanity623/PyOB/actions/workflows/verify.yml/badge.svg)\n![Marketplace](https://img.shields.io/badge/Marketplace-PyOB-green?logo=github)\n\n**PYOB is a high-fidelity autonomous agent that performs surgical code modifications, cross-file dependency tracking, and self-healing verification — all without destroying your codebase.**\n\n[Getting Started](#-getting-started) · [How It Works](#phase-1-initial-assessment--codebase-scan) · [Architecture](#system-overview) · [Documentation](#pyob--complete-technical-documentation)\n\n---\n\n\u003c/div\u003e\n\n## 🧠 What is PyOB?\n\nPYOB is NOT a personal AI CHAT assistant. PyOB is an **autonomous code review and feature engineering system** that continuously analyzes, patches, and evolves your codebase through a multi-stage verification pipeline. Unlike \"black-box\" coding assistants that rewrite entire files, PyOB operates with **surgical XML-based edits**, a **persistent symbolic dependency ledger**, and **automated GitHub integration** — ensuring your project is never left in a broken state. It **already knows its purpose and goals**.\n\n### Key Differentiators\n\n| Feature | Traditional AI Assistants | PYOB |\n|---|---|---|\n| **Edit Strategy** | Full file rewrites | Surgical `\u003cSEARCH\u003e/\u003cREPLACE\u003e` XML blocks |\n| **Dependency Awareness** | None | Symbolic ledger (`SYMBOLS.json`) with ripple detection |\n| **Error Recovery** | Manual | Context-aware self-healing with auto-rollback |\n| **Verification** | None | 5-layer pipeline: XML matching → linting → Mypy → PIR → runtime test |\n| **State Persistence** | Stateless | Hidden `.pyob/` vault: `MEMORY.md`, `ANALYSIS.md`, `HISTORY.md` |\n| **API Resilience** | Single key, fails on rate limit | 10-key rotation with **Smart Sleep Backoff** and local fallback |\n\n---\n\n## ✨ Core Features\n\n### 🔬 Surgical XML-Based Code Edits\nEvery proposed change uses exact `\u003cSEARCH\u003e/\u003cREPLACE\u003e` blocks. PyOB utilizes a **Multi-Strategy Matcher**. If any block fails to align, the entire patch is rejected and auto-regenerated to prevent partial, broken edits.\n\n### 📚 GitHub \"Librarian\" \u0026 Cloud HUD\nPyOB acts as a professional developer. After verifying a fix, it:\n- Creates a unique feature branch.\n- Commits as **`pyob-bot`** to keep your history clean.\n- Opens a **Pull Request** for your review.\n- Provides a **Live Public URL** (via Pinggy) to monitor the HUD from your mobile device.\n\n### 🛡️ 5-Layer Verification Pipeline\n1. **Atomic XML Matching** — Strict anchor validation with **Smart Indent Alignment**.\n2. **Syntactic \"Broom\"** — `ruff format` and `ruff check --fix` automatically clear \"trash\" errors.\n3. **Symbolic Ripple Engine** — Automatically detects and queues downstream dependencies for updates.\n4. **Context-Aware Self-Healing (PIR)** — Feeds the *original goal + error* back to the AI for repair.\n5. **Runtime Smoke Test** — Launches the app for 10 seconds to monitor for tracebacks.\n\n### 🌀 Recursive Self-Evolution\nPyOB can target its own source code to optimize its engine logic. \n- **Recursive Safety Pods**: Shelters working source code in an external backup directory (`~/Documents/PYOB_Backups`).\n- **Verified Hot-Reboot**: The engine tests the importability of its new code before performing a live restart.\n\n### 🤝 Human-in-the-Loop Governance\nInteractive terminal checkpoints locally, or **Headless Auto-Approval** in the cloud.\n- **`AUGMENT_PROMPT`** — Inject instructions into the AI's mental process.\n- **`EDIT_CODE` / `EDIT_XML`** — Polish proposed changes in your terminal.\n- **`FULL_DIFF`** — View the complete unified diff in a pager.\n\n---\n\n### 🚀 Getting Started\n\nPyOB is a **GitHub Marketplace Action**. You can run it locally as a CLI or in the cloud as a service.\n\n#### **Option 1: The Cloud Service (Recommended)**\nAdd PyOB to any repository by creating `.github/workflows/pyob.yml`:\n```yaml\nuses: vicsanity623/PyOB@main\nwith:\n  gemini_keys: ${{ secrets.PYOB_GEMINI_KEYS }}\n```\n\n#### **Option 2: Running from Source (Developers)**\n1. **Setup Environment**:\n```bash\npython3.12 -m venv build_env\nsource build_env/bin/activate\npip install -e .\n```\n2. **Validate**: `./check.sh`\n3. **Launch**: `pyob .`\n4. **Dashboard**: `observer.HTML` or `http://localhost:5000/`\n---\n\n### 🎯 Quick Start Workflow\n\n1.  **Targeting:** Provide the path to the project you want PyOB to manage.\n2.  **Dashboard:** Open **`http://localhost:5000`** to watch the \"Observer\" dashboard in real-time.\n3.  **Approve:** When PyOB proposes a fix or feature, review the diff in your terminal and hit `ENTER`.\n4.  **Self-Evolution:** To have PyOB improve itself, target its own root directory: `pyob .`\n5.  **Verification:** The system runs a 4-layer pipeline (XML Match → Lint → Runtime Test → Downstream Ripple Check) to ensure the code is functional.\n6.  **Auto-Locking:** Any dependencies PyOB installs during auto-repair are automatically locked into your `requirements.txt`.\n\n### 🔄 The Autonomous Loop\nPyOB will:\n1. 🔍 **Bootstrap** — Generate `ANALYSIS.md` (project map) and `SYMBOLS.json` (symbolic ledger).\n2. 🎯 **Target** — Intelligently select the next file to review based on history and symbolic ripples.\n3. 🔬 **Analyze** — Scan for bugs, type errors, and architectural bloat (\u003e800 lines).\n4. 💡 **Propose** — Generate a `PEER_REVIEW.md` (fixes) or `FEATURE.md` (new logic).\n5. ✅ **Verify** — Perform a \"Dry Run\" and runtime check before finalizing any edit.\n6. 🔗 **Cascade** — Detect and queue downstream dependency impacts for immediate follow-up.\n7. 💾 **Persist** — Compress and update `MEMORY.md` to maintain context for the next iteration.\n\n---\n\n## 🏗️ Architecture\n\n### Modular Engine Design\nPyOB is built using a **Mixin-based architecture** to separate concerns and prevent context bloat:\n\n| Component | File | Role |\n|---|---|---|\n| **Entrance Controller** | `entrance.py` | Master loop, Symbolic targeting, and Recursive Forge management. |\n| **Auto Reviewer** | `autoreviewer.py` | Orchestrates the 6-phase pipeline and feature implementation. |\n| **Core Utilities** | `core_utils.py` | LLM streaming, Smart Python detection, and Cyberpunk Logging. |\n| **Prompts \u0026 Memory** | `prompts_and_memory.py` | 8 specialized prompt templates and Transactional Memory logic. |\n| **Structure Parser** | `structure_parser.py` | High-fidelity AST parsing for Python/JS signatures. |\n\n### System Overview\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│                     ENTRANCE CONTROLLER                         │\n│                        (entrance.py)                            │\n│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌────────────────┐   │\n│  │ Target   │  │ Symbolic │  │ GitHub   │  │ Remote Sync    │   │\n│  │ Selector │  │ Engine   │  │ Librarian│  │ (Auto-Reboot)  │   │\n│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └──────┬─────────┘   │\n│       │              │             │               │            │\n│       ▼              ▼             ▼               ▼            │\n│  ┌─────────────────────────────────────────────────────────┐    │\n│  │              TARGETED REVIEWER PIPELINE                 │    │\n│  │          (Orchestrates Multi-File Services)             │    │\n│  └─────────────────────┬───────────────────────────────────┘    │\n│                        │                                        │\n│       ┌────────────────┴────────────────┬────────────────┐      │\n│       ▼                                 ▼                ▼      │\n│ ┌──────────────┐                 ┌──────────────┐ ┌──────────────┐\n│ │ CODE PARSER  │                 │  DASHBOARD   │ │  AUTO-HEAL   │\n│ │ (ast_parser) │                 │  (Architect) │ │  (Runtime)   │\n│ └──────────────┘                 └──────────────┘ └──────────────┘\n└─────────────────────────────────────────────────────────────────┘\n                             │\n                             ▼\n┌─────────────────────────────────────────────────────────────────┐\n│                       AUTO REVIEWER ENGINE                      │\n│                        (autoreviewer.py)                        │\n│  ┌───────────┐  ┌────────────────────────────────────────────┐  │\n│  │  6-Phase  │  │          REVIEWER MIXINS                   │  │\n│  │ Pipeline  │  │        (reviewer_mixins.py)                │  │\n│  └─────┬─────┘  │ • Linter Fix Loop  • Runtime Verifier      │  │\n│        │        │ • Feature Logic    • XML Matcher           │  │\n│        │        └──────────────────────┬─────────────────────┘  │\n│        │                               │                        │\n│  ┌─────▼───────────────────────────────▼─────────────────────┐  │\n│  │                    CORE UTILITIES MIXIN                   │  │\n│  │                      (core_utils.py)                      │  │\n│  │  • Gemini / Ollama Streaming   • Smart Key Rotation       │  │\n│  │  • Headless Auto-Approval      • Workspace Backup/Restore │  │\n│  └─────────────────────────────────────┬─────────────────────┘  │\n│                                        │                        │\n│  ┌─────────────────────────────────────▼─────────────────────┐  │\n│  │                 PROMPTS \u0026 MEMORY MIXIN                    │  │\n│  │                 (prompts_and_memory.py)                   │  │\n│  │  • Template Management        • Rich Context Builder      │  │\n│  │  • Transactional Memory Update • Aggressive Refactoring    │  │\n│  └────────────────────────────────────────────────────────────┘  │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n### Persistent State Files\n\n| File | Purpose | Managed By |\n|---|---|---|\n| `ANALYSIS.md` | Recursive project map with file summaries and structural dropdowns | `entrance.py` |\n| `SYMBOLS.json` | Dependency graph: definitions → files, references → call sites | `entrance.py` |\n| `MEMORY.md` | Synthesized session memory; auto-refactored every 2 iterations | `prompts_and_memory.py` |\n| `HISTORY.md` | Append-only ledger of every unified diff applied to the project | `entrance.py` |\n| `PEER_REVIEW.md` | Generated bug fix proposals (created during Phase 1) | `autoreviewer.py` |\n| `FEATURE.md` | Generated feature proposals (created during Phase 2) | `autoreviewer.py` |\n\n---\n\n## 🔄 Pipeline Phases\n\n### Phase 1: Initial Assessment \u0026 Codebase Scan\nScans all supported files (`.py`, `.js`, `.ts`, `.html`, `.css`, `.json`, `.sh`), runs linters, detects lazy code patterns (e.g., `typing.Any`), and generates surgical patch proposals.\n\n### Phase 2: Feature Proposal\nIf no bugs were found in Phase 1, the AI analyzes a randomly selected file and proposes one interactive, user-facing feature with a `\u003cSNIPPET\u003e` code block.\n\n### Phase 3: Downstream Cascade Check\nAfter any modification, PyOB runs `mypy` across the workspace. If type errors surface in dependent files, it generates **cascade fixes** using the `PCF.md` prompt template.\n\n### Phase 4: Runtime Verification\nIdentifies the project entry point (`if __name__ == \"__main__\":` or `main.py`/`app.py`), launches it for 10 seconds, and monitors `stdout`/`stderr` for crashes. Auto-installs missing pip packages on `ModuleNotFoundError`.\n\n### Phase 5: Memory Update\nSynthesizes all session actions into `MEMORY.md` using the `UM.md` prompt template, preserving architectural decisions and dependency mappings.\n\n### Phase 6: Memory Refactoring (Every 3rd Iteration)\nAggressively summarizes `MEMORY.md` to prevent context bloat, consolidating repetitive logs into a concise knowledge base.\n\n---\n\n## 📋 Prompt Templates\n\nPyOB uses 8 specialized prompt templates, auto-generated as `.md` files in the target directory:\n\n| Template | Full Name | Purpose |\n|---|---|---|\n| `PP.md` | Patch Prompt | Code review and bug fix generation |\n| `PF.md` | Propose Feature | Interactive feature proposal |\n| `IF.md` | Implement Feature | Surgical feature implementation |\n| `ALF.md` | Auto Linter Fix | Syntax error repair |\n| `FRE.md` | Fix Runtime Error | Runtime crash diagnosis and repair |\n| `PIR.md` | Post-Implementation Repair | Context-aware error recovery (knows the original goal) |\n| `PCF.md` | Propose Cascade Fix | Cross-file dependency repair |\n| `UM.md` | Update Memory | Memory synthesis and consolidation |\n| `RM.md` | Refactor Memory | Aggressive memory summarization |\n\n---\n\n## ⚙️ Configuration\n\n### API Keys\nGemini API keys are configured in `core_utils.py` in the `GEMINI_API_KEYS` list. Multiple keys enable automatic rotation and rate-limit resilience.\n\n### Models\n| Setting | Default | Location |\n|---|---|---|\n| Gemini Model | `gemini-2.5-flash` | `core_utils.py` → `GEMINI_MODEL` |\n| Local Model | `qwen3-coder:30b` | `core_utils.py` → `LOCAL_MODEL` |\n| Temperature | `0.1` | `core_utils.py` → `stream_gemini()` / `stream_ollama()` |\n\n### Ignored Paths\nPyOB automatically skips certain directories and files to avoid self-modification and virtual environments:\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eIgnored Directories\u003c/b\u003e\u003c/summary\u003e\n\n`.git`, `autovenv`, `venv`, `.venv`, `code`, `.mypy_cache`, `.ruff_cache`, `patch_test`, `env`, `__pycache__`, `node_modules`, `.vscode`, `.idea`, `other_dir`\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eIgnored Files\u003c/b\u003e\u003c/summary\u003e\n\n`core_utils.py`, `prompts_and_memory.py`, `autoreviewer.py`, `entrance.py`, all prompt templates (`ALF.md`, `FRE.md`, etc.), `sw.js`, `manifest.json`, `package-lock.json`, `auto.py`, `any_other_file_to_ignore.filetype`\n\n\u003c/details\u003e\n\n### Supported File Types\n`.py` · `.js` · `.ts` · `.html` · `.css` · `.json` · `.sh`\n\n---\n\n## 🧪 How the XML Edit Engine Works\n\nPyOB's edit engine is a multi-strategy matcher that ensures reliable code modifications:\n\n```\n1. Exact Match        →  Direct string replacement\n2. Stripped Match     →  Leading/trailing whitespace tolerance\n3. Normalized Match   →  Ignores comments and collapses whitespace\n4. Regex Fuzzy Match  →  Line-by-line regex matching with indent tolerance\n5. Robust Line Match  →  Stripped line-by-line content comparison\n```\n\nIf all 5 strategies fail for any `\u003cSEARCH\u003e` block, the **entire multi-block edit is rejected** and the AI is asked to regenerate.\n\n### Smart Indent Alignment\nThe engine detects the base indentation of both the `\u003cSEARCH\u003e` and `\u003cREPLACE\u003e` blocks, then re-aligns the replacement to match the source file's indentation style — preventing whitespace corruption.\n\n---\n\n## 🛡️ Safety Mechanisms\n\n| Mechanism | Description |\n|---|---|\n| **Atomic Rollback** | Snapshots the entire workspace before every edit; instantly restores from backup if any verification layer fails. |\n| **Librarian Isolation** | Edits are never pushed directly to `main`. The \"Librarian\" creates unique feature branches and Pull Requests for safe review. |\n| **Remote Sync Guard** | Automatically fetches and merges updates from `origin/main` before every loop to prevent working on stale code. |\n| **Headless Auto-Approval** | Detects CI environments (GitHub Actions) and auto-proceeds through checkpoints while maintaining full verification. |\n| **Smart Sleep Backoff** | Dynamically calculates the exact seconds until the next Gemini API key is available, preventing \"API Spam\" and idle waste. |\n| **Import Preservation** | AST-based logic that ensures the AI doesn't accidentally drop crucial imports during surgical refactors. |\n| **Circular Safety** | Prevents \"Brain Loops\" by using `TYPE_CHECKING` guards during cross-module initialization. |\n\n---\n\n## 📺 The Architect HUD (Observer Dashboard)\n\nPyOB includes a built-in, real-time **Cyberpunk HUD**. While the engine runs in the terminal (locally or in the cloud), you can monitor the \"Ouroboros\" through a state-of-the-art web interface.\n\n- **Responsive SOTA UI**: A modern, glassmorphic HUD designed for both desktop and mobile monitoring.\n- **Manual Target Override**: Use the HUD to force the engine to target a specific file for the next iteration.\n- **Pending Patch Preview**: Real-time visualization of AI thoughts and proposed patches before they are committed.\n- **Symbolic Ledger Stats**: Live tracking of the dependency graph size and symbolic ripple counts.\n- **Cloud Tunneling**: When running on GitHub Actions, PyOB automatically generates a secure **Live Tunnel URL** (via Pinggy) so you can monitor your bot's progress from your phone.\n- **URL**: `http://localhost:5000` (Local) or a dynamic `.pinggy.link` (Cloud).\n\n---\n\n## 📖 Full Documentation\n\nFor in-depth technical documentation covering the verification pipeline, symbolic dependency management, prompt engineering, and more, see the **[Technical Documentation](docs/DOCUMENTATION.md)**.\n\n---\n\n## 📁 Project Structure\n\n```text\nPyOB/\n├── pyproject.toml           # ⚙️ Package config, dependencies, and CLI entry point\n├── check.sh                 # 🧪 5-layer validation suite (Ruff + Mypy + Pytest)\n├── Dockerfile               # 🐳 Cloud runtime environment for GitHub Actions\n├── action.yml               # 🏗️ GitHub Marketplace Action manifest\n├── src/\n│   └── pyob/\n│       ├── pyob_launcher.py     # 🚀 Main entry point \u0026 environment setup\n│       ├── entrance.py          # 🧠 Master loop \u0026 GitHub Librarian\n│       ├── autoreviewer.py      # 🔧 Pipeline orchestration\n│       ├── reviewer_mixins.py   # 🛠️ Implementation logic for linters \u0026 healing\n│       ├── pyob_code_parser.py  # 🔬 AST/Regex structure analysis\n│       ├── pyob_dashboard.py    # 📺 Architect HUD (Observer UI)\n│       ├── core_utils.py        # ⚙️ LLM streaming \u0026 XML edit engine\n│       └── prompts_and_memory.py # 📝 Template \u0026 persistence management\n└── tests/                   # 🧪 Engine unit tests\n```\n\n### Generated Files (The `.pyob/` Data Vault)\n\nTo keep your project root clean, PyOB now stores all its persistent metadata and prompt templates in a hidden directory.\n\n```text\nyour-project/\n├── .pyob/                   # 📂 Hidden Metadata Vault\n│   ├── ANALYSIS.md          # 🗺️ Intelligent Project Map \u0026 Summaries\n│   ├── SYMBOLS.json         # 🔗 Symbolic Dependency Ledger\n│   ├── MEMORY.md            # 🧠 Long-term AI Logic State\n│   ├── HISTORY.md           # 📜 Truncated Unified Diff Ledger\n│   ├── observer.html        # 📺 Local Dashboard HUD source\n│   └── [PP.md, IF.md...]    # 📋 8 Specialized Prompt Engines\n├── PEER_REVIEW.md           # 🔍 Active Bug Fix Proposals\n├── FEATURE.md               # 💡 Active Feature Proposals\n├── requirements.txt         # 🔒 Auto-locked dependencies\n└── [your source files]\n```\n\n---\n\n\u003cdiv align=\"center\"\u003e\n\n**Built with surgical precision.** 🦅\n\n\u003c/div\u003e\n\n# PyOB — Complete Technical Documentation\n\n\u003e **Version**: 0.3.1 · **Last Updated**: March 2026\n\u003e **Architecture**: Python 3.12+ · Mixin-Based Package · GitHub Marketplace Action\n\n---\n\n## Table of Contents\n\n1. [System Philosophy](#1-system-philosophy-constrained-surgical-autonomy)\n2. [Architecture Overview](#2-architecture-overview)\n3. [Module Reference](#3-module-reference)\n   - 3.1 [pyob_launcher.py — Entry Point](#31-pyob_launcherpy--main-cli-entry-point)\n   - 3.2 [entrance.py — The Entrance Controller](#32-entrancepy--the-entrance-controller)\n   - 3.3 [autoreviewer.py — The Pipeline Orchestrator](#33-autoreviewerpy--the-auto-reviewer)\n   - 3.4 [reviewer_mixins.py — Implementation Muscles](#34-reviewer_mixinspy--engine-implementations)\n   - 3.5 [pyob_code_parser.py — Structural Analysis](#35-pyob_code_parserpy--structural-analysis)\n   - 3.6 [pyob_dashboard.py — SOTA Architect HUD](#36-pyob_dashboardpy--the-architect-hud)\n   - 3.7 [core_utils.py — Cloud-Aware Foundation](#37-core_utilspy--core-utilities-mixin)\n4. [The Verification \u0026 Healing Pipeline](#4-the-verification--healing-pipeline)\n5. [Symbolic Dependency Management](#5-symbolic-dependency-management)\n6. [The XML Edit Engine](#6-the-xml-edit-engine)\n7. [The GitHub Librarian](#7-the-github-librarian-integration)\n8. [Headless \u0026 Cloud Autonomy](#8-headless--cloud-autonomy)\n9. [LLM Backend \u0026 Smart Sleep Backoff](#9-llm-backend--resilience)\n10. [Persistence \u0026 State Vault (.pyob/)](#10-persistence--state-management)\n11. [Safety \u0026 Rollback Mechanisms](#11-safety--rollback-mechanisms)\n12. [Marketplace \u0026 Docker Infrastructure](#12-marketplace--docker-infrastructure)\n13. [Internal Constants \u0026 Rulesets](#13-internal-constants--defaults)\n14. [Operational Workflow](#14-operational-workflow)\n15. [Troubleshooting](#15-troubleshooting)\n\n---\n\n## 1. System Philosophy: Constrained Surgical Autonomy\n\nPyOB is an autonomous agent built on **constrained agency**. Unlike chat-based assistants that require constant prompting, PyOB is a self-driven engine that operates within a strict \"Safety Cage\" defined by:\n\n1. **Surgical Patching** — Patches are applied via `\u003cSEARCH\u003e/\u003cREPLACE\u003e` blocks limited to 2-5 line anchors.\n2. **Atomic Commits** — Changes are isolated in unique Git branches and submitted as PRs via the Librarian.\n3. **Multi-Step Verification** — Every edit must pass a 5-layer gate (XML match → Linter → Mypy → PIR → Smoke Test).\n4. **Self-Evolution** — The engine is recursive; it can identify its own logic flaws and refactor its source code.\n\n---\n\n## 2. Architecture Overview\n\n### Modular Package Structure\nPyOB has transitioned from a script collection to a standardized Python package located in `src/pyob/`.\n\n```text\nCoreUtilsMixin (core_utils.py)\n├── Provides: Smart Sleep, Headless Approval, XML Engine, LLM Streaming\n│\nPromptsAndMemoryMixin (prompts_and_memory.py)\n├── Provides: Rule-based Templates (Rule 7: No src. imports), CRUD Memory\n│\nValidationMixin + FeatureOperationsMixin (reviewer_mixins.py)\n├── Provides: Ruff/Mypy validation, Runtime Auto-Heal, XML Implementation\n│\nAutoReviewer(All Mixins) (autoreviewer.py)\n├── Provides: 6-Phase orchestrator logic\n│\nEntranceController (entrance.py)\n├── Provides: Master loop, Remote Sync, Librarian PR logic, Reboot Flag\n```\n\n### System Data Flow (Cloud Service Mode)\n```\n[User / Schedule] ─▶ [GitHub Action] ─▶ [Docker Container]\n                                              │\n                    ┌─────────────────────────┴────────────────────────┐\n                    │      ENTRANCE CONTROLLER (Master Loop)           │\n                    │ 1. Sync Remote Main  2. Pick Target  3. Backup   │\n                    └───────────┬────────────────────────────┬─────────┘\n                                ▼                            ▼\n                    ┌──────────────────────┐      ┌────────────────────┐\n                    │   AUTO REVIEWER      │      │    LIBRARIAN       │\n                    │ (6-Phase Pipeline)   │      │ (Branch/Commit/PR) │\n                    └───────────┬──────────┘      └────────────────────┘\n                                ▼\n                    ┌──────────────────────────────────────────────────┐\n                    │           VERIFICATION \u0026 HEALING                 │\n                    │ [Ruff --fix] ─▶ [Mypy] ─▶ [10s Smoke Test]      │\n                    └──────────────────────────────────────────────────┘\n```\n\n---\n\n## 3. Module Reference\n\n### 3.1 `pyob_launcher.py` — Main CLI Entry Point\nThe environment bootstrapper. It configures the runtime, handles macOS terminal re-launching, and detects \"Headless\" environments.\n\n| Method | Description |\n|---|---|\n| `load_config` | Pulls keys from `~/.pyob_config` (Local) or `os.environ` (Cloud). Detects non-TTY to skip prompts. |\n| `ensure_terminal` | macOS-specific logic to force PyOB into a visible Terminal window for DMG users. |\n| `main` | Entry point. Detects macOS app bundle paths and ignores them to ensure clean targeting. |\n\n### 3.2 `entrance.py` — The Entrance Controller\nThe master orchestrator. Manages symbolic targeting, Git lifecycle, and Hot-Reboots.\n\n| Method | Description |\n|---|---|\n| `run_master_loop` | Infinite loop with `sync_with_remote` check. Manages the `self_evolved_flag`. |\n| `sync_with_remote` | Fetches `origin/main`. If behind, performs a merge. Triggers reboot if engine files change. |\n| `handle_git_librarian` | Creates branch `pyob-evolution-vX-timestamp`, commits as `pyob-bot`, and opens PR. |\n| `reboot_pyob` | **Verified Hot-Reboot:** Tests if new code is importable before calling `os.execv` to restart. |\n\n### 3.3 `autoreviewer.py` — The Auto Reviewer\nThe high-level pipeline orchestrator. Ties together the specialized mixins into the 6-phase autonomous cycle.\n\n### 3.4 `reviewer_mixins.py` — Engine Implementations\nSeparates \"Muscle\" from \"Brain.\"\n\n- **`ValidationMixin`**: Runs `ruff format`, then `ruff check --fix`. If errors remain, it triggers the PIR loop.\n- **`FeatureOperationsMixin`**: The heavy-duty XML matcher. Interprets AI proposals and writes them to `PEER_REVIEW.md`.\n\n### 3.5 `pyob_code_parser.py` — Structural Analysis\nA high-fidelity analysis tool that uses **AST (Python)** and **Regex (JS/CSS)** to map the project architecture. It generates the `\u003cdetails\u003e` dropdowns seen in `ANALYSIS.md`.\n\n### 3.6 `pyob_dashboard.py` — The Architect HUD\nA `BaseHTTPRequestHandler` that serves the SOTA Cyberpunk HUD. Features glassmorphism, responsive mobile layout, and real-time AJAX stats updates.\n\n---\n\n## 4. The Verification \u0026 Healing Pipeline\n\nPyOB follows a \"Proactive Defense\" model to ensure code stability.\n\n### Layer 1: Atomic XML Match\nEdits are binary: either every block in a response matches perfectly, or the entire iteration is discarded.\n\n### Layer 2: Syntactic \"Broom\"\n1. **`ruff format`**: Normalizes all whitespace.\n2. **`ruff check --fix`**: Automatically clears unused imports and variables without costing AI tokens.\n3. **Remaining Errors**: Grouped by file and fed into the AI for surgical repair.\n\n### Layer 3: Runtime Smoke Test\n- Locates the entry point via `_find_entry_file`.\n- Launches the process for 10 seconds.\n- **Auto-Dependency Locking**: If a `ModuleNotFoundError` is detected, PyOB runs `pip install` and immediately updates `requirements.txt`.\n\n---\n\n## 5. Symbolic Dependency Management\n\n### `SYMBOLS.json` Ledger\nPyOB maintains a mapping of **Definitions** (where a function/class is born) to **References** (where it is used).\n\n### Symbolic Ripple Engine\n1. When a file is edited, the engine identifies changed symbols.\n2. It looks up the ledger to see if those symbols are \"Definitions.\"\n3. It finds all \"References\" in other files.\n4. **Cascade Queue:** Impacted files are prioritized for the next iteration, with the original change-diff provided as mandatory context.\n\n---\n\n## 6. The XML Edit Engine\n\n### Multi-Strategy Matching\n`apply_xml_edits` attempts 5 strategies per block:\n1. **Exact** (Literal)\n2. **Stripped** (Newline tolerance)\n3. **Normalized** (Comment/Whitespace stripping)\n4. **Regex Fuzzy** (Indentation tolerance)\n5. **Robust Line Match** (Content-only line comparison)\n\n### Smart Indent Alignment\nThe engine detects the target line's indentation and re-aligns the AI's `\u003cREPLACE\u003e` block to match, preventing the \"Unexpected Indentation\" errors common in Python agents.\n\n---\n\n## 7. The GitHub Librarian Integration\n\nPyOB acts as a professional developer through the **Librarian** module:\n\n- **Isolated Branches:** Every change is pushed to a unique branch.\n- **Bot Identity:** Commits are attributed to `pyob-bot` using the `BOT_GITHUB_TOKEN`.\n- **Automated PRs:** Uses the GitHub CLI (`gh`) to open Pull Requests targeting `main`.\n- **PR Body:** Includes the AI's `\u003cTHOUGHT\u003e` process as the PR description for human review.\n\n---\n\n## 8. Headless \u0026 Cloud Autonomy\n\nPyOB detects when it is running in **GitHub Actions** (via the `GITHUB_ACTIONS=true` env var):\n\n- **Auto-Approval:** Bypasses \"Press ENTER to apply\" prompts.\n- **Non-TTY Safety:** Skips all `termios` and `input()` calls to prevent `EOFError` or `ioctl` crashes.\n- **Cloud Tunneling:** Starts a background **Pinggy** tunnel to provide a public URL for the dashboard HUD.\n\n---\n\n## 9. LLM Backend \u0026 Smart Sleep Backoff\n\n### Multi-Key Key Rotation\nPyOB rotates through a pool of up to 10 Gemini API keys. Keys that hit a `429 Rate Limit` are quarantined for 20 minutes.\n\n### Smart Sleep Backoff\nWhen all keys are rate-limited, the engine calculates:\n`sleep_duration = min(key_cooldowns) - current_time`\nThe bot \"naps\" for the exact number of seconds until the first key is available, ensuring zero waste of Cloud Runner minutes.\n\n---\n\n## 10. Persistence \u0026 State Management (.pyob/)\n\nAll project metadata is stored in the hidden `.pyob/` vault to prevent root directory clutter.\n\n| File | Purpose |\n|---|---|\n| `.pyob/ANALYSIS.md` | Persistent map used by the AI to select targets. |\n| `.pyob/SYMBOLS.json` | The symbolic dependency graph. |\n| `.pyob/MEMORY.md` | Transactional AI memory; refactored every 2 iterations to prevent context bloat. |\n| `.pyob/HISTORY.md` | Detailed ledger of applied patches. |\n\n---\n\n## 11. Safety \u0026 Rollback Mechanisms\n\n- **External Safety Pods:** Before editing an \"Engine File\" (like `entrance.py`), PyOB shelters a copy of the current source in `~/Documents/PYOB_Backups/`.\n- **Workspace Backup:** Every iteration starts with an in-memory snapshot of the entire project.\n- **Atomic Rollback:** If any verification layer (Linter, Mypy, or Runtime) fails 3 times, the entire workspace is restored to the backup.\n\n---\n\n## 12. Marketplace \u0026 Docker Infrastructure\n\n### Marketplace Action\nPyOB is a containerized GitHub Action (`action.yml`). It uses a `Dockerfile` based on `python:3.12-slim` with `git`, `curl`, and `gh` pre-installed.\n\n### Docker Environment\nThe Docker container maps the user's repository to `/github/workspace`, allowing PyOB to operate on the files as if it were a local CLI tool.\n\n---\n\n## 13. Internal Constants \u0026 Rulesets\n\n### Mandatory Import Rule (Rule 7)\nThe AI is strictly prohibited from using the `src.` prefix in imports.\n- **Correct:** `from pyob.core_utils import ...`\n- **Incorrect:** `from src.pyob.core_utils import ...`\n\n### Indentation Guard (Rule 6)\nDeletions must leave a placeholder comment (e.g., `# [Logic moved to new module]`) to maintain Python's indentation integrity.\n\n---\n\n## 14. Operational Workflow\n\n1. **Remote Sync:** Pull latest merges from GitHub.\n2. **Genesis / Update:** Build or refresh `ANALYSIS.md` and `SYMBOLS.json`.\n3. **Targeting:** Select file via AI or the `Cascade Queue`.\n4. **Pipeline:** Scan → Propose → Verify → Auto-Heal.\n5. **Librarian:** Push Branch → Open PR.\n6. **Self-Evolution:** If engine changed, verify importability and Hot-Reboot.\n\n---\n\n## 15. Troubleshooting\n\n### `ModuleNotFoundError: No module named 'src'`\n**Cause:** AI incorrectly added `src.` to an import statement.\n**Fix:** Remove the `src.` prefix. Ensure `pyproject.toml` is installed via `pip install -e .`.\n\n### `EOFError: EOF when reading a line`\n**Cause:** PyOB tried to call `input()` in a cloud environment.\n**Fix:** Ensure `sys.stdin.isatty()` checks are present in the launcher.\n\n### `termios.error: Inappropriate ioctl for device`\n**Cause:** `get_user_approval` tried to manipulate a non-existent keyboard.\n**Fix:** The \"Headless Auto-Approval\" logic in `core_utils.py` handles this.\n\n---\n\u003e **PyOB** — The engine that builds itself, with surgical precision. 🦅\n\n---\n\n## Star History\n\n\u003ca href=\"https://www.star-history.com/?repos=vicsanity623%2FPyOB\u0026type=date\u0026legend=top-left\"\u003e\n \u003cpicture\u003e\n   \u003csource media=\"(prefers-color-scheme: dark)\" srcset=\"https://api.star-history.com/image?repos=vicsanity623/PyOB\u0026type=date\u0026theme=dark\u0026legend=top-left\" /\u003e\n   \u003csource media=\"(prefers-color-scheme: light)\" srcset=\"https://api.star-history.com/image?repos=vicsanity623/PyOB\u0026type=date\u0026legend=top-left\" /\u003e\n   \u003cimg alt=\"Star History Chart\" src=\"https://api.star-history.com/image?repos=vicsanity623/PyOB\u0026type=date\u0026legend=top-left\" /\u003e\n \u003c/picture\u003e\n\u003c/a\u003e\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvicsanity623%2Fpyob","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvicsanity623%2Fpyob","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvicsanity623%2Fpyob/lists"}