From 0b0ca7df592a391bb2ce7d905c8d32d462ae422d Mon Sep 17 00:00:00 2001
From: Vic <125237471+vicsanity623@users.noreply.github.com>
Date: Sun, 22 Mar 2026 23:44:26 -0700
Subject: [PATCH 1/9] Update core_utils.py
---
src/pyob/core_utils.py | 12 +++++++-----
1 file changed, 7 insertions(+), 5 deletions(-)
diff --git a/src/pyob/core_utils.py b/src/pyob/core_utils.py
index 4613877..62c077d 100644
--- a/src/pyob/core_utils.py
+++ b/src/pyob/core_utils.py
@@ -351,14 +351,16 @@ def load_memory(self) -> str:
with open(directives_path, "r", encoding="utf-8") as f:
human_orders = f.read().strip()
if human_orders:
+ logger.info(f"🎯 BEACON ACTIVE: Injected {len(human_orders.splitlines())} lines from DIRECTIVES.md")
+
memory_content = (
- f"# HUMAN DIRECTIVES (PRIORITY)\n"
- f"{human_orders}\n\n"
- f"---\n\n"
- f"{memory_content}"
+ f"# CRITICAL HUMAN DIRECTIVES - PRIORITY 1\n"
+ f"{human_orders}\n"
+ f"\n# END CRITICAL DIRECTIVES\n"
+ f"---\n{memory_content}"
)
except Exception as e:
- logger.warning(f"Librarian could not read DIRECTIVES.md: {e}")
+ logger.warning(f"Could not read DIRECTIVES.md: {e}")
return memory_content
From a16d3ef2f30200a75614bf96c44e748a8100d96c Mon Sep 17 00:00:00 2001
From: vicsanity623 <125237471+vicsanity623@users.noreply.github.com>
Date: Mon, 23 Mar 2026 06:49:38 +0000
Subject: [PATCH 2/9] =?UTF-8?q?=F0=9F=AA=84=20PyOB:=20Automated=20Lint=20&?=
=?UTF-8?q?=20Format=20Fixes?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/pyob/core_utils.py | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/src/pyob/core_utils.py b/src/pyob/core_utils.py
index 62c077d..515c5ef 100644
--- a/src/pyob/core_utils.py
+++ b/src/pyob/core_utils.py
@@ -351,8 +351,10 @@ def load_memory(self) -> str:
with open(directives_path, "r", encoding="utf-8") as f:
human_orders = f.read().strip()
if human_orders:
- logger.info(f"🎯 BEACON ACTIVE: Injected {len(human_orders.splitlines())} lines from DIRECTIVES.md")
-
+ logger.info(
+ f"🎯 BEACON ACTIVE: Injected {len(human_orders.splitlines())} lines from DIRECTIVES.md"
+ )
+
memory_content = (
f"# CRITICAL HUMAN DIRECTIVES - PRIORITY 1\n"
f"{human_orders}\n"
From ecbb7c314081a1be19dc8a9420069bf1289ee676 Mon Sep 17 00:00:00 2001
From: Vic <125237471+vicsanity623@users.noreply.github.com>
Date: Sun, 22 Mar 2026 23:51:24 -0700
Subject: [PATCH 3/9] Update core_utils.py
---
src/pyob/core_utils.py | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/pyob/core_utils.py b/src/pyob/core_utils.py
index 515c5ef..363a14a 100644
--- a/src/pyob/core_utils.py
+++ b/src/pyob/core_utils.py
@@ -55,6 +55,7 @@
"node_modules",
".vscode",
".idea",
+ "tests",
}
IGNORE_FILES = {
From 0a8f9dffa5d2b7922655b335d78b139b4a78836e Mon Sep 17 00:00:00 2001
From: Vic <125237471+vicsanity623@users.noreply.github.com>
Date: Sun, 22 Mar 2026 23:53:01 -0700
Subject: [PATCH 4/9] Update entrance_mixins.py
---
src/pyob/entrance_mixins.py | 257 ++++++++----------------------------
1 file changed, 57 insertions(+), 200 deletions(-)
diff --git a/src/pyob/entrance_mixins.py b/src/pyob/entrance_mixins.py
index 2b5ccd5..587f9c4 100644
--- a/src/pyob/entrance_mixins.py
+++ b/src/pyob/entrance_mixins.py
@@ -3,180 +3,57 @@
import logging
import os
import shutil
-import threading
import time
-import urllib.parse
-from http.server import HTTPServer
from pathlib import Path
-from typing import Any
-
-from .dashboard_html import OBSERVER_HTML
-from .pyob_dashboard import ObserverHandler
-from .targeted_reviewer import TargetedReviewer
+from typing import Any, Callable, Optional
logger = logging.getLogger(__name__)
-
-# [TargetedReviewer class moved to targeted_reviewer.py]
-
-
class EntranceMixin:
- def start_dashboard(self: Any):
- # 1. Save to the internal .pyob folder
- obs_path = os.path.join(self.pyob_dir, "observer.html")
-
- # Dynamically modify OBSERVER_HTML string to inject manual target UI and logic
- modified_html_content = OBSERVER_HTML
-
- # Insert HTML block for manual target selection
- html_to_insert = """
-
-
-
Manual Target Selection
-
-
-
-
-"""
- # Assuming OBSERVER_HTML has a structure like: ... \n\n Live Log
- insertion_marker_html = " \n\n Live Log
"
- if insertion_marker_html in modified_html_content:
- modified_html_content = modified_html_content.replace(
- insertion_marker_html, html_to_insert + "\n" + insertion_marker_html
- )
- else:
- logger.warning(
- "HTML insertion marker not found in OBSERVER_HTML. Manual target UI may not be visible."
- )
-
- # Insert JavaScript for manual target form submission handling
- js_to_insert = """
- // Handle manual target form submission
- document.getElementById('set-target-form').addEventListener('submit', function(event) {
- event.preventDefault(); // Prevent default form submission
-
- const filePathInput = document.getElementById('target-file-path');
- const filePath = filePathInput.value;
- const targetMessage = document.getElementById('target-message');
-
- if (!filePath) {
- targetMessage.textContent = 'Please enter a file path.';
- targetMessage.style.color = 'red';
- return;
- }
-
- fetch('/set_target', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- body: `file_path=${encodeURIComponent(filePath)}`
- })
- .then(response => {
- const isOk = response.ok; // Capture response.ok status
- return response.json().then(data => ({ data, isOk })); // Pass data and status
- })
- .then(({ data, isOk }) => { // Destructure to get both
- targetMessage.textContent = data.message;
- // Check response.ok from the original fetch response, not data
- targetMessage.style.color = isOk ? '#6a9955' : 'red';
- if (isOk) {
- filePathInput.value = ''; // Clear input on success
- }
- })
- .catch(error => {
- console.error('Error setting manual target:', error);
- targetMessage.textContent = 'An error occurred while setting target.';
- targetMessage.style.color = 'red';
- });
- });
-"""
- # Assuming OBSERVER_HTML has a script tag ending with ' '
- insertion_marker_js = " "
- if insertion_marker_js in modified_html_content:
- modified_html_content = modified_html_content.replace(
- insertion_marker_js, js_to_insert + "\n" + insertion_marker_js
- )
- else:
- logger.warning(
- "JavaScript insertion marker not found in OBSERVER_HTML. Manual target logic may not be functional."
- )
-
- with open(obs_path, "w", encoding="utf-8") as f:
- f.write(modified_html_content)
-
- # 2. Initialize and Start the Live Server
-
- # Dynamically add do_POST method for manual target handling
- def _dynamic_do_POST_method(handler_instance: ObserverHandler):
- if handler_instance.path == "/set_target":
- try:
- content_length = int(
- handler_instance.headers.get("Content-Length", 0)
- )
- except (ValueError, TypeError):
- content_length = 0 # Default to 0 if header is malformed
-
- if content_length > 0:
- post_data = handler_instance.rfile.read(content_length).decode(
- "utf-8"
- )
- parsed_data = urllib.parse.parse_qs(post_data)
- file_path = parsed_data.get("file_path", [""])[0]
- else:
- file_path = "" # No content, no file_path
-
- if file_path and handler_instance.controller:
- handler_instance.controller.set_manual_target_file(file_path)
- message = f"Manual target set to: {file_path}"
- status_code = 200
- else:
- message = (
- "Error: No file path provided or controller not available."
- )
- status_code = 400
-
- handler_instance.send_response(status_code)
- handler_instance.send_header("Content-type", "application/json")
- handler_instance.end_headers()
- handler_instance.wfile.write(
- json.dumps({"message": message}).encode("utf-8")
- )
- else:
- handler_instance.send_error(404)
-
- # Fix: Use setattr to bypass Mypy [method-assign] error
- setattr(ObserverHandler, "do_POST", _dynamic_do_POST_method)
-
- ObserverHandler.controller = self
-
- def run_server():
- try:
- server = HTTPServer(("localhost", 5000), ObserverHandler)
- server.serve_forever()
- except Exception as e:
- logger.error(f"Dashboard failed to start: {e}")
-
- threading.Thread(target=run_server, daemon=True).start()
-
- print("\n" + "=" * 60)
- print("PyOuroBoros (PyOB) OBSERVER IS LIVE")
- print("URL: http://localhost:5000")
- print(f"FILE: {obs_path}")
- print("=" * 60 + "\n")
-
- def execute_targeted_iteration(self: Any, iteration: int):
+ """
+ Mixin providing core iteration logic.
+ Attributes are declared here to satisfy strict Mypy checks.
+ """
+ # --- TYPE ANNOTATIONS FOR MYPY (Fixes 23 errors) ---
+ target_dir: str
+ pyob_dir: str
+ ENGINE_FILES: list[str]
+ llm_engine: Any
+ code_parser: Any
+ cascade_queue: list[str]
+ cascade_diffs: dict[str, str]
+ session_pr_count: int
+ self_evolved_flag: bool
+ memory_path: str
+ history_path: str
+ analysis_path: str
+ symbols_path: str
+ manual_target_file: Optional[str]
+ key_cooldowns: dict[str, float]
+
+ def pick_target_file(self) -> str: return ""
+ def _read_file(self, path: str) -> str: return ""
+ def _extract_path_from_llm_response(self, text: str) -> str: return ""
+ def get_valid_llm_response(self, p: str, v: Callable[[str], bool], context: str) -> str: return ""
+ def update_analysis_for_single_file(self, abs_p: str, rel_p: str): pass
+ def update_ledger_for_file(self, rel_p: str, code: str): pass
+ def detect_symbolic_ripples(self, o: str, n: str, p: str) -> list[str]: return []
+ def _run_final_verification_and_heal(self, b: dict) -> bool: return False
+ def handle_git_librarian(self, p: str, i: int): pass
+ def append_to_history(self, p: str, o: str, n: str): pass
+ def wrap_up_evolution_session(self): pass
+ def generate_pr_summary(self, rel_path: str, diff_text: str) -> dict: return {}
+ # ---------------------------------------------------
+
+ def execute_targeted_iteration(self, iteration: int):
+ """Orchestrates a single targeted evolution step."""
backup_state = self.llm_engine.backup_workspace()
target_diff = ""
+
if self.cascade_queue:
target_rel_path = self.cascade_queue.pop(0)
target_diff = self.cascade_diffs.get(target_rel_path, "")
- logger.warning(
- f"SYMBOLIC CASCADE: Targeting impacted file: {target_rel_path}"
- )
+ logger.warning(f"SYMBOLIC CASCADE: Targeting impacted file: {target_rel_path}")
is_cascade = True
else:
target_rel_path = self.pick_target_file()
@@ -192,23 +69,18 @@ def execute_targeted_iteration(self: Any, iteration: int):
project_name = os.path.basename(self.target_dir)
base_backup_path = Path.home() / "Documents" / "PYOB_Backups" / project_name
pod_path = base_backup_path / f"safety_pod_v{iteration}_{timestamp}"
-
try:
pod_path.mkdir(parents=True, exist_ok=True)
- logger.warning(
- f"SELF-EVOLUTION: Sheltering engine source EXTERNALLY in {pod_path}"
- )
for f_name in self.ENGINE_FILES:
src = os.path.join(self.target_dir, "src", "pyob", f_name)
- if os.path.exists(src):
- shutil.copy(src, str(pod_path))
+ if os.path.exists(src): shutil.copy(src, str(pod_path))
except Exception as e:
- logger.error(f"Failed to create external safety pod: {e}")
+ logger.error(f"Failed to create safety pod: {e}")
target_abs_path = os.path.join(self.target_dir, target_rel_path)
self.llm_engine.session_context = []
if is_cascade and target_diff:
- msg = f"CRITICAL SYMBOLIC RIPPLE: This file depends on code that was just modified. Ensure this file is updated to support these changes:\n\n### DEPDENDENCY CHANGE DIFF:\n{target_diff}"
+ msg = f"CRITICAL SYMBOLIC RIPPLE: This file depends on code that was just modified.\n### CHANGE DIFF:\n{target_diff}"
self.llm_engine.session_context.append(msg)
old_content = ""
@@ -216,11 +88,16 @@ def execute_targeted_iteration(self: Any, iteration: int):
with open(target_abs_path, "r", encoding="utf-8", errors="ignore") as f:
old_content = f.read()
+ from pyob.targeted_reviewer import TargetedReviewer
reviewer = TargetedReviewer(self.target_dir, target_abs_path)
reviewer.session_context = self.llm_engine.session_context[:]
+ if hasattr(self, 'key_cooldowns'): reviewer.key_cooldowns = self.key_cooldowns
+ if hasattr(self, 'session_pr_count'): reviewer.session_pr_count = self.session_pr_count
+
reviewer.run_pipeline(iteration)
self.llm_engine.session_context = reviewer.session_context[:]
+ if hasattr(reviewer, 'session_pr_count'): self.session_pr_count = reviewer.session_pr_count
new_content = ""
if os.path.exists(target_abs_path):
@@ -232,43 +109,23 @@ def execute_targeted_iteration(self: Any, iteration: int):
self.update_ledger_for_file(target_rel_path, new_content)
if old_content != new_content:
- logger.info(
- f"Edit successful. Checking ripples and running final verification for {target_rel_path}..."
- )
+ logger.info(f"Edit successful. Verifying {target_rel_path}...")
self.append_to_history(target_rel_path, old_content, new_content)
-
- current_diff = "".join(
- difflib.unified_diff(
- old_content.splitlines(keepends=True),
- new_content.splitlines(keepends=True),
- )
- )
-
- ripples = self.detect_symbolic_ripples(
- old_content, new_content, target_rel_path
- )
+ current_diff = "".join(difflib.unified_diff(old_content.splitlines(keepends=True), new_content.splitlines(keepends=True)))
+ ripples = self.detect_symbolic_ripples(old_content, new_content, target_rel_path)
if ripples:
- logger.warning(
- f"CROSS-FILE DEPTH TRIGGERED! Queuing {len(ripples)} files."
- )
for r in ripples:
if r not in self.cascade_queue:
self.cascade_queue.append(r)
self.cascade_diffs[r] = current_diff
- logger.info("\n" + "=" * 20 + " FINAL VERIFICATION " + "=" * 20)
if not self._run_final_verification_and_heal(backup_state):
- logger.error(
- "Final verification failed and could not be auto-repaired. Iteration changes have been rolled back."
- )
+ logger.error("Final verification failed. Changes rolled back.")
else:
- logger.info("Final verification successful. Application is stable.")
self.handle_git_librarian(target_rel_path, iteration)
+ if is_engine_file: self.self_evolved_flag = True
- if is_engine_file:
- logger.warning(
- f"SELF-EVOLUTION: `{target_rel_path}` was successfully updated."
- )
- self.self_evolved_flag = True
-
- logger.info("=" * 60 + "\n")
+ # --- THE FINAL WRAP-UP GATE ---
+ if getattr(self, "session_pr_count", 0) >= 8 and not getattr(self, "cascade_queue", []):
+ logger.info(f"🏆 MISSION ACCOMPLISHED: {self.session_pr_count} PRs achieved.")
+ self.wrap_up_evolution_session()
From 22c3a7acba4a19dbfdd9a2aab20e7527dc6e96ea Mon Sep 17 00:00:00 2001
From: Vic <125237471+vicsanity623@users.noreply.github.com>
Date: Mon, 23 Mar 2026 00:05:53 -0700
Subject: [PATCH 5/9] Update prompts_and_memory.py
---
src/pyob/prompts_and_memory.py | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/pyob/prompts_and_memory.py b/src/pyob/prompts_and_memory.py
index 3f4be73..24ed632 100644
--- a/src/pyob/prompts_and_memory.py
+++ b/src/pyob/prompts_and_memory.py
@@ -29,15 +29,15 @@ def _ensure_prompt_files(self) -> None:
data_dir = os.path.join(self.target_dir, ".pyob")
os.makedirs(data_dir, exist_ok=True)
templates = {
- "UM.md": "You are the PyOB Memory Manager. Your job is to update MEMORY.md.\n\n### Current Memory:\n{current_memory}\n\n### Recent Actions:\n{session_summary}\n\n### INSTRUCTIONS:\n1. Update the memory with the Recent Actions.\n2. TRANSACTIONAL RECORDING: Only record changes as 'Implemented' if the actions specifically state 'SUCCESSFUL CHANGE'. If you see 'CRITICAL: FAILED' or 'ROLLED BACK', record this as a 'Failed Attempt' with the reason, so the engine knows to try a different approach next time.\n3. BREVITY: Keep the ENTIRE document under 200 words. Be ruthless. Delete old, irrelevant details.\n4. FORMAT: Keep lists strictly to bullet points. No long paragraphs.\n5. Respond EXCLUSIVELY with the raw markdown for MEMORY.md. Do not use ```markdown fences or blocks.",
+ "UM.md": "You are the PyOB Memory Manager. Your job is to update MEMORY.md.\n\n### Current Memory:\n{current_memory}\n\n### Recent Actions:\n{session_summary}\n\n### INSTRUCTIONS:\n1. Update the memory with the Recent Actions.\n2. TRANSACTIONAL RECORDING: Only record changes as 'Implemented' if the actions specifically state 'SUCCESSFUL CHANGE'. If you see 'CRITICAL: FAILED' or 'ROLLED BACK', record this as a 'Failed Attempt' with the reason, so the engine knows to try a different approach next time.\n3. BREVITY: Keep the ENTIRE document under 200 words. Be ruthless. Delete old, irrelevant details.\n4. FORMAT: Keep lists strictly to bullet points. No long paragraphs.\n5. **HUMAN DIRECTIVES**: If the current memory contains a section titled "HUMAN DIRECTIVES", you are strictly FORBIDDEN from deleting or altering it. Prepend all new session summaries BELOW that section.\n6. Respond EXCLUSIVELY with the raw markdown for MEMORY.md. Do not use ```markdown fences or blocks.",
"RM.md": "You are the PYOB Memory Manager. The current MEMORY.md is too bloated and is breaking the AI context window.\n\n### Bloated Memory:\n{current_memory}\n\n### INSTRUCTIONS:\n1. AGGRESSIVELY COMPRESS this memory. \n2. Delete duplicate information, repetitive logs, and obvious statements.\n3. Keep ONLY the core architectural rules and crucial file dependencies.\n4. The final output MUST BE UNDER 150 WORDS.\n5. Respond EXCLUSIVELY with the raw markdown. No fences, no thoughts.",
- "PP.md": "You are an elite PYOB Software Engineer. Analyze the code for bugs or architectural gaps.\n\n{memory_section}{ruff_section}{mypy_section}{custom_issues_section}### Source Code:\n```{lang_tag}\n{content}\n```\n\n### CRITICAL RULES:\n1. **ITERATION BUDGET**: \n - IF iteration < 5: Focus ONLY on bug fixes, linting, and minor performance tweaks. Do NOT create new files, move classes, or extract logic. \n - IF iteration >= 5: You may propose architectural refactors, file extractions, and logic movement.\n2. **SURGICAL FIXES**: Every block must be exactly 2-5 lines. Only provide ONE block per response.\n3. **NO HALLUCINATIONS**: Do not invent bugs. If the code is functional, state 'The code looks good.'\n4. **ARCHITECTURAL BLOAT**: Only flag bloat for future planning until iteration 5.\n5. **MISSING IMPORTS**: If you use a new module/type, you MUST add an block to import it at the top.\n6. **INDENTATION IS SYNTAX**: Your blocks must have perfect, absolute indentation.\n7. **DEFEATING MYPY**: If fixing a `[union-attr]` error, use `assert variable is not None` or `# type: ignore`.\n8. **IMPORT PATHS (MANDATORY)**: Never use the prefix `src.` in any import statement. The root of the package is `pyob`. (Example: Use `from pyob.core_utils import ...`, NOT `from src.pyob.core_utils import ...`).\n9. **TYPE HINTS (CRITICAL)**: Never use the `|` operator with quoted class names (Forward References). Use `Any` for objects that create circular dependencies.\n10. **ATOMIC REFACTORING**: If you are beyond iteration 5 and need to move logic, use a 3-step process: A) Add new file/imports. B) Update call sites. C) Remove old code in a subsequent turn.\n\n### HOW TO RESPOND (CHOOSE ONE):\n\n**SCENARIO A: Code has bugs/bloat and needs edits:**\n\nSummary: ...\nEvaluation: [Address bloat here if flagged]\nImports Required: ...\nAction: I will fix X by doing Y.\n\n\n\nExact lines to replace (2-5 lines max)\n\n\nNew lines\n\n\n\n**SCENARIO B: Code is perfect. NO EDITS NEEDED:**\n\nSummary: ...\nEvaluation: ...\nAction: The code looks good. No fixes needed.\n",
+ "PP.md": "You are an elite PYOB Software Engineer. Analyze the code for bugs or architectural gaps.\n\n{memory_section}{ruff_section}{mypy_section}{custom_issues_section}### Source Code:\n```{lang_tag}\n{content}\n```\n\n### CRITICAL RULES:\n1. **ITERATION BUDGET**: \n - IF iteration < 5: Focus ONLY on bug fixes, linting, and minor performance tweaks. Do NOT create new files, move classes, or extract logic. \n - IF iteration >= 5: You may propose architectural refactors, file extractions, and logic movement.\n2. **SURGICAL FIXES**: Every block must be exactly 2-5 lines. Only provide ONE block per response.\n3. **NO HALLUCINATIONS**: Do not invent bugs. If the code is functional, state 'The code looks good.'\n4. **ARCHITECTURAL BLOAT**: Only flag bloat for future planning until iteration 5.\n5. **MISSING IMPORTS**: If you use a new module/type, you MUST add an block to import it at the top.\n6. **INDENTATION IS SYNTAX**: Your blocks must have perfect, absolute indentation.\n7. **DEFEATING MYPY**: If fixing a `[union-attr]` error, use `assert variable is not None` or `# type: ignore`.\n8. **IMPORT PATHS (MANDATORY)**: Never use the prefix `src.` in any import statement. The root of the package is `pyob`. (Example: Use `from pyob.core_utils import ...`, NOT `from src.pyob.core_utils import ...`).\n9. **TYPE HINTS (CRITICAL)**: Never use the `|` operator with quoted class names (Forward References). Use `Any` for objects that create circular dependencies.\n10. **ATOMIC REFACTORING**: If you are beyond iteration 5 and need to move logic, use a 3-step process: A) Add new file/imports. B) Update call sites. C) Remove old code in a subsequent turn.\n11. **NO SCAFFOLDING (CRITICAL)**: Never include bot-specific text, logs, or status tags (like \"APPROVED\" or \"LIBRARIAN\") inside the code blocks. Your output must be 100% valid code for the target language.\n\n### HOW TO RESPOND (CHOOSE ONE):\n\n**SCENARIO A: Code has bugs/bloat and needs edits:**\n\nSummary: ...\nEvaluation: [Address bloat here if flagged]\nImports Required: ...\nAction: I will fix X by doing Y.\n\n\n\nExact lines to replace (2-5 lines max)\n\n\nNew lines\n\n\n\n**SCENARIO B: Code is perfect. NO EDITS NEEDED:**\n\nSummary: ...\nEvaluation: ...\nAction: The code looks good. No fixes needed.\n",
"ALF.md": "You are an elite developer fixing syntax errors.\nThe file `{rel_path}` failed validation with these exact errors:\n{err_text}\n\n### Current Code:\n```\n{code}\n```\n\n### Instructions:\n1. Fix the syntax errors (like stray brackets, unexpected tokens, or indentation) using surgical XML edits.\n2. Respond EXCLUSIVELY with a block followed by ONE OR MORE blocks.\n3. Ensure your edits perfectly align with the surrounding brackets.",
"FRE.md": "You are an elite PYOB developer fixing runtime crashes.\n{memory_section}The application crashed during a test run.\n\n### Crash Logs & Traceback:\n{logs}\n\nThe traceback indicates the error occurred in `{rel_path}`.\n\n### Current Code of `{rel_path}`:\n```python\n{code}\n```\n\n### Instructions:\n1. Identify the EXACT root cause of the crash.\n2. Fix the error using surgical XML edits.\n3. Respond EXCLUSIVELY with a block followed by ONE OR MORE blocks.\n\n### REQUIRED XML FORMAT:\n\nExplanation of root cause...\nImports Needed: [List new imports required or 'None']\n\n\n\nExact lines to replace\n\n\nNew replacement lines\n\n",
"PF.md": "You are the PYOB Product Architect. Review the source code and suggest ONE highly useful, INTERACTIVE feature.\n\n{memory_section}### Source Code:\n```{lang_tag}\n{content}\n```\n\n### CRITICAL RULES:\n1. Suggest an INTERACTIVE feature (UI elements, buttons, menus).\n2. **ARCHITECTURAL SPLIT (MANDATORY)**: If the source code is over 800 lines, you ARE NOT ALLOWED to propose a new feature. You MUST propose an 'Architectural Split'. Identify a logical module (like a Mixin) to move to a NEW file.\n3. **SINGLE FILE LIMIT**: If you are proposing an Architectural Split, you are ONLY allowed to create ONE new file per iteration. Do not attempt to split multiple modules at once. Focus on the largest logical block first.\n4. **NEW FILE FORMAT**: If proposing a split, your block MUST use this format: [Full Code for New File]. Your must then explain how to update the original file to import this new module.\n5. MULTI-FILE ORCHESTRATION: Explicitly list filenames of other files that will need updates in your .\n6. The block MUST contain ONLY the new logic or the block.\n\n### REQUIRED XML FORMAT:\n\n...\n\n\n# New logic OR tag here\n",
- "IF.md": "You are an elite PYOB Implementation Engineer. Implement the APPROVED feature into `{rel_path}`.\n\n{memory_section}### Feature Proposal Details:\n{feature_content}\n\n### Current Source Code:\n```{lang_tag}\n{source_code}\n```\n\n### CRITICAL INSTRUCTIONS:\n1. **SURGICAL EDITS ONLY**: Every block must be EXACTLY 2-5 lines.\n2. **MISSING IMPORTS**: If your feature introduces a new class/function, add a separate block to import it.\n3. **BLOCK INTEGRITY (CRITICAL)**: Python relies on indentation. If you add an `if`, `try`, or `def` statement, you MUST indent the code beneath it. If you remove one, you MUST dedent the code. Do not leave orphaned indents.\n4. **ABSOLUTE SPACES**: The spaces in your block must match the absolute margin of the source code.\n5. **VARIABLE SCOPE**: Ensure variables are accessible (use `self.` for class states).\n6. **DELETING CODE (CRITICAL)**: If your goal is to remove a block of code (e.g., when moving logic to a new file), DO NOT leave an empty block. Instead, provide a block containing a comment such as `# [Logic moved to new module]` to ensure the surrounding code remains syntactically valid.\n7. **IMPORT PATHS (MANDATORY)**: Never use the prefix `src.` in any import statement. The root of the package is `pyob`. (Example: Use `from pyob.entrance import Controller`, NOT `from src.pyob.entrance import Controller`).\n8. **TYPE HINTS (CRITICAL)**: Never use the `|` operator with quoted class names (Forward References). Use `Any` for objects that create circular dependencies.\n9. **ATOMIC REFACTORING**: Do not move large blocks or classes to new files in a single turn. Focus ONLY on logic improvements or bug fixes within the current file.\n10. **SURGICAL MOVEMENT**: If moving logic, use a 3-step process: A) Add new file/imports. B) Update call sites. C) Remove old code in a subsequent turn.\n11. **NO MASS DELETIONS**: You are strictly forbidden from replacing a large block of code with a smaller one unless you include the surrounding class/method structure in your block. If you cannot fit the structure in 5 lines, use multiple blocks.\n12. **INDENTATION LOCK**: Every block must have the exact same indentation level as the block.\n13. **PRESERVE STRUCTURE**: Never use a block that cuts off a class or method definition. Always include the full line you are matching.\n14. **NO EMOJIS (MANDATORY)**: Never use emojis or non-ASCII characters in logger messages, print statements, or source comments. Use plain ASCII text only. Emojis cause encoding errors and git diff corruption.\n\n### REQUIRED XML FORMAT:\n\n1. Lines to change: ...\n2. New imports needed: [List them or state 'None']\n3. Strategy: ...\n\n\n\nExact 2-5 lines\n\n\nNew code\n\n",
+ "IF.md": "You are an elite PYOB Implementation Engineer. Implement the APPROVED feature into `{rel_path}`.\n\n{memory_section}### Feature Proposal Details:\n{feature_content}\n\n### Current Source Code:\n```{lang_tag}\n{source_code}\n```\n\n### CRITICAL INSTRUCTIONS:\n1. **SURGICAL EDITS ONLY**: Every block must be EXACTLY 2-5 lines.\n2. **MISSING IMPORTS**: If your feature introduces a new class/function, add a separate block to import it.\n3. **BLOCK INTEGRITY (CRITICAL)**: Python relies on indentation. If you add an `if`, `try`, or `def` statement, you MUST indent the code beneath it. If you remove one, you MUST dedent the code. Do not leave orphaned indents.\n4. **ABSOLUTE SPACES**: The spaces in your block must match the absolute margin of the source code.\n5. **VARIABLE SCOPE**: Ensure variables are accessible (use `self.` for class states).\n6. **DELETING CODE (CRITICAL)**: If your goal is to remove a block of code (e.g., when moving logic to a new file), DO NOT leave an empty block. Instead, provide a block containing a comment such as `# [Logic moved to new module]` to ensure the surrounding code remains syntactically valid.\n7. **IMPORT PATHS (MANDATORY)**: Never use the prefix `src.` in any import statement. The root of the package is `pyob`. (Example: Use `from pyob.entrance import Controller`, NOT `from src.pyob.entrance import Controller`).\n8. **TYPE HINTS (CRITICAL)**: Never use the `|` operator with quoted class names (Forward References). Use `Any` for objects that create circular dependencies.\n9. **ATOMIC REFACTORING**: Do not move large blocks or classes to new files in a single turn. Focus ONLY on logic improvements or bug fixes within the current file.\n10. **SURGICAL MOVEMENT**: If moving logic, use a 3-step process: A) Add new file/imports. B) Update call sites. C) Remove old code in a subsequent turn.\n11. **NO MASS DELETIONS**: You are strictly forbidden from replacing a large block of code with a smaller one unless you include the surrounding class/method structure in your block. If you cannot fit the structure in 5 lines, use multiple blocks.\n12. **INDENTATION LOCK**: Every block must have the exact same indentation level as the block.\n13. **PRESERVE STRUCTURE**: Never use a block that cuts off a class or method definition. Always include the full line you are matching.\n14. **NO EMOJIS (MANDATORY)**: Never use emojis or non-ASCII characters in logger messages, print statements, or source comments. Use plain ASCII text only. Emojis cause encoding errors and git diff corruption.\n15. **NO INTERNAL TESTS**: Never write test suites (Jest/Pytest/describe blocks) inside a source file logic. Use the dedicated Phase 0 system for tests.\n16. **JAVASCRIPT STANDARDS**: If editing `.js` files, use `const` and `let` (avoid `var`), and always include the `.js` extension in `import` statements. Ensure logic is encapsulated in the correct class or module.\n### REQUIRED XML FORMAT:\n\n1. Lines to change: ...\n2. New imports needed: [List them or state 'None']\n3. Strategy: ...\n\n\n\nExact 2-5 lines\n\n\nNew code\n\n",
"PCF.md": 'You are the PYOB Symbolic Fixer taking over Phase 3 Cascaded Edits.\n{memory_section}We just modified `{trigger_file}`, and it broke a dependency downstream: `{rel_broken_path}`.\n\n### Linter Errors for `{rel_broken_path}`:\n{mypy_errors}\n\n### Source Code of `{rel_broken_path}`:\n```python\n{broken_code}\n```\n\n### Instructions:\n1. Respond EXCLUSIVELY with a block followed by ONE block to fix the broken references.\n2. **DEFEATING MYPY (CRITICAL)**: If the error contains `[union-attr]` or states `Item "None" of ... has no attribute`, adding a type hint will fail. You MUST fix this by either inserting `assert variable is not None` before the operation, or adding `# type: ignore` to the end of the failing line.\n\n### REQUIRED XML FORMAT:\n\nExplanation of cascade fix...\n\n\n\nExact lines to replace\n\n\nNew replacement lines\n\n',
- "PIR.md": "You are an elite PYOB developer performing a post-implementation repair.\nAn automated attempt to implement a feature or bugfix has failed, resulting in the following errors.\n\n### Original Goal / Change Request:\n{context_of_change}\n\n### The Resulting Errors (Linter/Runtime):\n{err_text}\n\n### The Broken Code in `{rel_path}`:\n```\n{code}\n```\n\n### Instructions:\n1. Analyze the 'Original Goal' and the 'Resulting Errors' together.\n2. CRITICAL INDENTATION CHECK: If the error says `Unexpected indentation`, rewrite the block with PERFECT absolute indentation.\n3. CRITICAL IMPORT CHECK: If the error is `F821 Undefined name`, you MUST create an block at the top of the file to add the missing `import` statement.\n4. DEFEATING MYPY: If the error is a `[union-attr]` or `None` type error, simply adding a type hint will fail the linter again. You MUST insert `assert object is not None` right before it is used, or append `# type: ignore` to the failing line.\n5. Create a surgical XML edit to fix the code.\n6. **DELETING CODE**: If you are removing logic, never use an empty block. Always include a placeholder comment to maintain valid Python syntax.\n\n### REQUIRED XML FORMAT:\n\nRoot Cause: ...\nImports Needed: ...\nIndentation Fix Needed: [Yes/No]\nAction: ...\n\n\n\nExact lines to replace\n\n\nNew replacement lines\n\n",
+ "PIR.md": "You are an elite PYOB developer performing a post-implementation repair.\nAn automated attempt to implement a feature or bugfix has failed, resulting in the following errors.\n\n### Original Goal / Change Request:\n{context_of_change}\n\n### The Resulting Errors (Linter/Runtime):\n{err_text}\n\n### The Broken Code in `{rel_path}`:\n```\n{code}\n```\n\n### Instructions:\n1. Analyze the 'Original Goal' and the 'Resulting Errors' together.\n2. CRITICAL INDENTATION CHECK: If the error says `Unexpected indentation`, rewrite the block with PERFECT absolute indentation.\n3. CRITICAL IMPORT CHECK: If the error is `F821 Undefined name`, you MUST create an block at the top of the file to add the missing `import` statement.\n4. DEFEATING MYPY: If the error is a `[union-attr]` or `None` type error, simply adding a type hint will fail the linter again. You MUST insert `assert object is not None` right before it is used, or append `# type: ignore` to the failing line.\n5. Create a surgical XML edit to fix the code.\n6. **DELETING CODE**: If you are removing logic, never use an empty block. Always include a placeholder comment to maintain valid Python syntax.\n7. **VISUAL LEAK CHECK**: If the error logs or context suggest that raw code is visible to the user on the screen, this is a CRITICAL UI FAILURE. Locate the stray text and wrap it in the correct tags or delete it immediately.\n\n### REQUIRED XML FORMAT:\n\nRoot Cause: ...\nImports Needed: ...\nIndentation Fix Needed: [Yes/No]\nAction: ...\n\n\n\nExact lines to replace\n\n\nNew replacement lines\n\n",
}
for filename, content in templates.items():
filepath = os.path.join(data_dir, filename) # Use data_dir here
From bb04b979be5151869ed80c29bae4cc7912bbef15 Mon Sep 17 00:00:00 2001
From: Vic <125237471+vicsanity623@users.noreply.github.com>
Date: Mon, 23 Mar 2026 00:10:46 -0700
Subject: [PATCH 6/9] Update prompts_and_memory.py
---
src/pyob/prompts_and_memory.py | 16 ++++++++--------
1 file changed, 8 insertions(+), 8 deletions(-)
diff --git a/src/pyob/prompts_and_memory.py b/src/pyob/prompts_and_memory.py
index 24ed632..a397d5e 100644
--- a/src/pyob/prompts_and_memory.py
+++ b/src/pyob/prompts_and_memory.py
@@ -29,15 +29,15 @@ def _ensure_prompt_files(self) -> None:
data_dir = os.path.join(self.target_dir, ".pyob")
os.makedirs(data_dir, exist_ok=True)
templates = {
- "UM.md": "You are the PyOB Memory Manager. Your job is to update MEMORY.md.\n\n### Current Memory:\n{current_memory}\n\n### Recent Actions:\n{session_summary}\n\n### INSTRUCTIONS:\n1. Update the memory with the Recent Actions.\n2. TRANSACTIONAL RECORDING: Only record changes as 'Implemented' if the actions specifically state 'SUCCESSFUL CHANGE'. If you see 'CRITICAL: FAILED' or 'ROLLED BACK', record this as a 'Failed Attempt' with the reason, so the engine knows to try a different approach next time.\n3. BREVITY: Keep the ENTIRE document under 200 words. Be ruthless. Delete old, irrelevant details.\n4. FORMAT: Keep lists strictly to bullet points. No long paragraphs.\n5. **HUMAN DIRECTIVES**: If the current memory contains a section titled "HUMAN DIRECTIVES", you are strictly FORBIDDEN from deleting or altering it. Prepend all new session summaries BELOW that section.\n6. Respond EXCLUSIVELY with the raw markdown for MEMORY.md. Do not use ```markdown fences or blocks.",
- "RM.md": "You are the PYOB Memory Manager. The current MEMORY.md is too bloated and is breaking the AI context window.\n\n### Bloated Memory:\n{current_memory}\n\n### INSTRUCTIONS:\n1. AGGRESSIVELY COMPRESS this memory. \n2. Delete duplicate information, repetitive logs, and obvious statements.\n3. Keep ONLY the core architectural rules and crucial file dependencies.\n4. The final output MUST BE UNDER 150 WORDS.\n5. Respond EXCLUSIVELY with the raw markdown. No fences, no thoughts.",
- "PP.md": "You are an elite PYOB Software Engineer. Analyze the code for bugs or architectural gaps.\n\n{memory_section}{ruff_section}{mypy_section}{custom_issues_section}### Source Code:\n```{lang_tag}\n{content}\n```\n\n### CRITICAL RULES:\n1. **ITERATION BUDGET**: \n - IF iteration < 5: Focus ONLY on bug fixes, linting, and minor performance tweaks. Do NOT create new files, move classes, or extract logic. \n - IF iteration >= 5: You may propose architectural refactors, file extractions, and logic movement.\n2. **SURGICAL FIXES**: Every block must be exactly 2-5 lines. Only provide ONE block per response.\n3. **NO HALLUCINATIONS**: Do not invent bugs. If the code is functional, state 'The code looks good.'\n4. **ARCHITECTURAL BLOAT**: Only flag bloat for future planning until iteration 5.\n5. **MISSING IMPORTS**: If you use a new module/type, you MUST add an block to import it at the top.\n6. **INDENTATION IS SYNTAX**: Your blocks must have perfect, absolute indentation.\n7. **DEFEATING MYPY**: If fixing a `[union-attr]` error, use `assert variable is not None` or `# type: ignore`.\n8. **IMPORT PATHS (MANDATORY)**: Never use the prefix `src.` in any import statement. The root of the package is `pyob`. (Example: Use `from pyob.core_utils import ...`, NOT `from src.pyob.core_utils import ...`).\n9. **TYPE HINTS (CRITICAL)**: Never use the `|` operator with quoted class names (Forward References). Use `Any` for objects that create circular dependencies.\n10. **ATOMIC REFACTORING**: If you are beyond iteration 5 and need to move logic, use a 3-step process: A) Add new file/imports. B) Update call sites. C) Remove old code in a subsequent turn.\n11. **NO SCAFFOLDING (CRITICAL)**: Never include bot-specific text, logs, or status tags (like \"APPROVED\" or \"LIBRARIAN\") inside the code blocks. Your output must be 100% valid code for the target language.\n\n### HOW TO RESPOND (CHOOSE ONE):\n\n**SCENARIO A: Code has bugs/bloat and needs edits:**\n\nSummary: ...\nEvaluation: [Address bloat here if flagged]\nImports Required: ...\nAction: I will fix X by doing Y.\n\n\n\nExact lines to replace (2-5 lines max)\n\n\nNew lines\n\n\n\n**SCENARIO B: Code is perfect. NO EDITS NEEDED:**\n\nSummary: ...\nEvaluation: ...\nAction: The code looks good. No fixes needed.\n",
- "ALF.md": "You are an elite developer fixing syntax errors.\nThe file `{rel_path}` failed validation with these exact errors:\n{err_text}\n\n### Current Code:\n```\n{code}\n```\n\n### Instructions:\n1. Fix the syntax errors (like stray brackets, unexpected tokens, or indentation) using surgical XML edits.\n2. Respond EXCLUSIVELY with a block followed by ONE OR MORE blocks.\n3. Ensure your edits perfectly align with the surrounding brackets.",
+ "UM.md": "You are the PyOB Memory Manager. Your job is to update MEMORY.md.\n\n### Current Memory:\n{current_memory}\n\n### Recent Actions:\n{session_summary}\n\n### INSTRUCTIONS:\n1. Update the memory with the Recent Actions.\n2. TRANSACTIONAL RECORDING: Only record changes as 'Implemented' if the actions specifically state 'SUCCESSFUL CHANGE'. If you see 'CRITICAL: FAILED' or 'ROLLED BACK', record this as a 'Failed Attempt' with the reason, so the engine knows to try a different approach next time.\n3. BREVITY: Keep the ENTIRE document under 200 words. Be ruthless. Delete old, irrelevant details.\n4. FORMAT: Keep lists strictly to bullet points. No long paragraphs.\n5. **HUMAN DIRECTIVES**: If the current memory contains a section titled HUMAN DIRECTIVES, you are strictly FORBIDDEN from deleting or altering it. Prepend all new session summaries BELOW that section.\n6. Respond EXCLUSIVELY with the raw markdown for MEMORY.md. Do not use ```markdown fences or blocks.\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
+ "RM.md": "You are the PYOB Memory Manager. The current MEMORY.md is too bloated and is breaking the AI context window.\n\n### Bloated Memory:\n{current_memory}\n\n### INSTRUCTIONS:\n1. AGGRESSIVELY COMPRESS this memory. \n2. Delete duplicate information, repetitive logs, and obvious statements.\n3. Keep ONLY the core architectural rules and crucial file dependencies.\n4. The final output MUST BE UNDER 150 WORDS.\n5. Respond EXCLUSIVELY with the raw markdown. No fences, no thoughts.\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
+ "PP.md": "You are an elite PYOB Software Engineer. Analyze the code for bugs or architectural gaps.\n\n{memory_section}{ruff_section}{mypy_section}{custom_issues_section}### Source Code:\n```{lang_tag}\n{content}\n```\n\n### CRITICAL RULES:\n1. **ITERATION BUDGET**: \n - IF iteration < 5: Focus ONLY on bug fixes, linting, and minor performance tweaks. Do NOT create new files, move classes, or extract logic. \n - IF iteration >= 5: You may propose architectural refactors, file extractions, and logic movement.\n2. **SURGICAL FIXES**: Every block must be exactly 2-5 lines. Only provide ONE block per response.\n3. **NO HALLUCINATIONS**: Do not invent bugs. If the code is functional, state 'The code looks good.'\n4. **ARCHITECTURAL BLOAT**: Only flag bloat for future planning until iteration 5.\n5. **MISSING IMPORTS**: If you use a new module/type, you MUST add an block to import it at the top.\n6. **INDENTATION IS SYNTAX**: Your blocks must have perfect, absolute indentation.\n7. **DEFEATING MYPY**: If fixing a `[union-attr]` error, use `assert variable is not None` or `# type: ignore`.\n8. **IMPORT PATHS (MANDATORY)**: Never use the prefix `src.` in any import statement. The root of the package is `pyob`. (Example: Use `from pyob.core_utils import ...`, NOT `from src.pyob.core_utils import ...`).\n9. **TYPE HINTS (CRITICAL)**: Never use the `|` operator with quoted class names (Forward References). Use `Any` for objects that create circular dependencies.\n10. **ATOMIC REFACTORING**: If you are beyond iteration 5 and need to move logic, use a 3-step process: A) Add new file/imports. B) Update call sites. C) Remove old code in a subsequent turn.\n11. **NO SCAFFOLDING (CRITICAL)**: Never include bot-specific text, logs, or status tags (like \"APPROVED\" or \"LIBRARIAN\") inside the code blocks. Your output must be 100% valid code for the target language.\n\n### HOW TO RESPOND (CHOOSE ONE):\n\n**SCENARIO A: Code has bugs/bloat and needs edits:**\n\nSummary: ...\nEvaluation: [Address bloat here if flagged]\nImports Required: ...\nAction: I will fix X by doing Y.\n\n\n\nExact lines to replace (2-5 lines max)\n\n\nNew lines\n\n\n\n**SCENARIO B: Code is perfect. NO EDITS NEEDED:**\n\nSummary: ...\nEvaluation: ...\nAction: The code looks good. No fixes needed.\n\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
+ "ALF.md": "You are an elite developer fixing syntax errors.\nThe file `{rel_path}` failed validation with these exact errors:\n{err_text}\n\n### Current Code:\n```\n{code}\n```\n\n### Instructions:\n1. Fix the syntax errors (like stray brackets, unexpected tokens, or indentation) using surgical XML edits.\n2. Respond EXCLUSIVELY with a block followed by ONE OR MORE blocks.\n3. Ensure your edits perfectly align with the surrounding brackets.\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
"FRE.md": "You are an elite PYOB developer fixing runtime crashes.\n{memory_section}The application crashed during a test run.\n\n### Crash Logs & Traceback:\n{logs}\n\nThe traceback indicates the error occurred in `{rel_path}`.\n\n### Current Code of `{rel_path}`:\n```python\n{code}\n```\n\n### Instructions:\n1. Identify the EXACT root cause of the crash.\n2. Fix the error using surgical XML edits.\n3. Respond EXCLUSIVELY with a block followed by ONE OR MORE blocks.\n\n### REQUIRED XML FORMAT:\n\nExplanation of root cause...\nImports Needed: [List new imports required or 'None']\n\n\n\nExact lines to replace\n\n\nNew replacement lines\n\n",
- "PF.md": "You are the PYOB Product Architect. Review the source code and suggest ONE highly useful, INTERACTIVE feature.\n\n{memory_section}### Source Code:\n```{lang_tag}\n{content}\n```\n\n### CRITICAL RULES:\n1. Suggest an INTERACTIVE feature (UI elements, buttons, menus).\n2. **ARCHITECTURAL SPLIT (MANDATORY)**: If the source code is over 800 lines, you ARE NOT ALLOWED to propose a new feature. You MUST propose an 'Architectural Split'. Identify a logical module (like a Mixin) to move to a NEW file.\n3. **SINGLE FILE LIMIT**: If you are proposing an Architectural Split, you are ONLY allowed to create ONE new file per iteration. Do not attempt to split multiple modules at once. Focus on the largest logical block first.\n4. **NEW FILE FORMAT**: If proposing a split, your block MUST use this format: [Full Code for New File]. Your must then explain how to update the original file to import this new module.\n5. MULTI-FILE ORCHESTRATION: Explicitly list filenames of other files that will need updates in your .\n6. The block MUST contain ONLY the new logic or the block.\n\n### REQUIRED XML FORMAT:\n\n...\n\n\n# New logic OR tag here\n",
- "IF.md": "You are an elite PYOB Implementation Engineer. Implement the APPROVED feature into `{rel_path}`.\n\n{memory_section}### Feature Proposal Details:\n{feature_content}\n\n### Current Source Code:\n```{lang_tag}\n{source_code}\n```\n\n### CRITICAL INSTRUCTIONS:\n1. **SURGICAL EDITS ONLY**: Every block must be EXACTLY 2-5 lines.\n2. **MISSING IMPORTS**: If your feature introduces a new class/function, add a separate block to import it.\n3. **BLOCK INTEGRITY (CRITICAL)**: Python relies on indentation. If you add an `if`, `try`, or `def` statement, you MUST indent the code beneath it. If you remove one, you MUST dedent the code. Do not leave orphaned indents.\n4. **ABSOLUTE SPACES**: The spaces in your block must match the absolute margin of the source code.\n5. **VARIABLE SCOPE**: Ensure variables are accessible (use `self.` for class states).\n6. **DELETING CODE (CRITICAL)**: If your goal is to remove a block of code (e.g., when moving logic to a new file), DO NOT leave an empty block. Instead, provide a block containing a comment such as `# [Logic moved to new module]` to ensure the surrounding code remains syntactically valid.\n7. **IMPORT PATHS (MANDATORY)**: Never use the prefix `src.` in any import statement. The root of the package is `pyob`. (Example: Use `from pyob.entrance import Controller`, NOT `from src.pyob.entrance import Controller`).\n8. **TYPE HINTS (CRITICAL)**: Never use the `|` operator with quoted class names (Forward References). Use `Any` for objects that create circular dependencies.\n9. **ATOMIC REFACTORING**: Do not move large blocks or classes to new files in a single turn. Focus ONLY on logic improvements or bug fixes within the current file.\n10. **SURGICAL MOVEMENT**: If moving logic, use a 3-step process: A) Add new file/imports. B) Update call sites. C) Remove old code in a subsequent turn.\n11. **NO MASS DELETIONS**: You are strictly forbidden from replacing a large block of code with a smaller one unless you include the surrounding class/method structure in your block. If you cannot fit the structure in 5 lines, use multiple blocks.\n12. **INDENTATION LOCK**: Every block must have the exact same indentation level as the block.\n13. **PRESERVE STRUCTURE**: Never use a block that cuts off a class or method definition. Always include the full line you are matching.\n14. **NO EMOJIS (MANDATORY)**: Never use emojis or non-ASCII characters in logger messages, print statements, or source comments. Use plain ASCII text only. Emojis cause encoding errors and git diff corruption.\n15. **NO INTERNAL TESTS**: Never write test suites (Jest/Pytest/describe blocks) inside a source file logic. Use the dedicated Phase 0 system for tests.\n16. **JAVASCRIPT STANDARDS**: If editing `.js` files, use `const` and `let` (avoid `var`), and always include the `.js` extension in `import` statements. Ensure logic is encapsulated in the correct class or module.\n### REQUIRED XML FORMAT:\n\n1. Lines to change: ...\n2. New imports needed: [List them or state 'None']\n3. Strategy: ...\n\n\n\nExact 2-5 lines\n\n\nNew code\n\n",
- "PCF.md": 'You are the PYOB Symbolic Fixer taking over Phase 3 Cascaded Edits.\n{memory_section}We just modified `{trigger_file}`, and it broke a dependency downstream: `{rel_broken_path}`.\n\n### Linter Errors for `{rel_broken_path}`:\n{mypy_errors}\n\n### Source Code of `{rel_broken_path}`:\n```python\n{broken_code}\n```\n\n### Instructions:\n1. Respond EXCLUSIVELY with a block followed by ONE block to fix the broken references.\n2. **DEFEATING MYPY (CRITICAL)**: If the error contains `[union-attr]` or states `Item "None" of ... has no attribute`, adding a type hint will fail. You MUST fix this by either inserting `assert variable is not None` before the operation, or adding `# type: ignore` to the end of the failing line.\n\n### REQUIRED XML FORMAT:\n\nExplanation of cascade fix...\n\n\n\nExact lines to replace\n\n\nNew replacement lines\n\n',
- "PIR.md": "You are an elite PYOB developer performing a post-implementation repair.\nAn automated attempt to implement a feature or bugfix has failed, resulting in the following errors.\n\n### Original Goal / Change Request:\n{context_of_change}\n\n### The Resulting Errors (Linter/Runtime):\n{err_text}\n\n### The Broken Code in `{rel_path}`:\n```\n{code}\n```\n\n### Instructions:\n1. Analyze the 'Original Goal' and the 'Resulting Errors' together.\n2. CRITICAL INDENTATION CHECK: If the error says `Unexpected indentation`, rewrite the block with PERFECT absolute indentation.\n3. CRITICAL IMPORT CHECK: If the error is `F821 Undefined name`, you MUST create an block at the top of the file to add the missing `import` statement.\n4. DEFEATING MYPY: If the error is a `[union-attr]` or `None` type error, simply adding a type hint will fail the linter again. You MUST insert `assert object is not None` right before it is used, or append `# type: ignore` to the failing line.\n5. Create a surgical XML edit to fix the code.\n6. **DELETING CODE**: If you are removing logic, never use an empty block. Always include a placeholder comment to maintain valid Python syntax.\n7. **VISUAL LEAK CHECK**: If the error logs or context suggest that raw code is visible to the user on the screen, this is a CRITICAL UI FAILURE. Locate the stray text and wrap it in the correct tags or delete it immediately.\n\n### REQUIRED XML FORMAT:\n\nRoot Cause: ...\nImports Needed: ...\nIndentation Fix Needed: [Yes/No]\nAction: ...\n\n\n\nExact lines to replace\n\n\nNew replacement lines\n\n",
+ "PF.md": "You are the PYOB Product Architect. Review the source code and suggest ONE highly useful, INTERACTIVE feature.\n\n{memory_section}### Source Code:\n```{lang_tag}\n{content}\n```\n\n### CRITICAL RULES:\n1. Suggest an INTERACTIVE feature (UI elements, buttons, menus).\n2. **ARCHITECTURAL SPLIT (MANDATORY)**: If the source code is over 800 lines, you ARE NOT ALLOWED to propose a new feature. You MUST propose an 'Architectural Split'. Identify a logical module (like a Mixin) to move to a NEW file.\n3. **SINGLE FILE LIMIT**: If you are proposing an Architectural Split, you are ONLY allowed to create ONE new file per iteration. Do not attempt to split multiple modules at once. Focus on the largest logical block first.\n4. **NEW FILE FORMAT**: If proposing a split, your block MUST use this format: [Full Code for New File]. Your must then explain how to update the original file to import this new module.\n5. MULTI-FILE ORCHESTRATION: Explicitly list filenames of other files that will need updates in your .\n6. The block MUST contain ONLY the new logic or the block.\n\n### REQUIRED XML FORMAT:\n\n...\n\n\n# New logic OR tag here\n\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
+ "IF.md": "You are an elite PYOB Implementation Engineer. Implement the APPROVED feature into `{rel_path}`.\n\n{memory_section}### Feature Proposal Details:\n{feature_content}\n\n### Current Source Code:\n```{lang_tag}\n{source_code}\n```\n\n### CRITICAL INSTRUCTIONS:\n1. **SURGICAL EDITS ONLY**: Every block must be EXACTLY 2-5 lines.\n2. **MISSING IMPORTS**: If your feature introduces a new class/function, add a separate block to import it.\n3. **BLOCK INTEGRITY (CRITICAL)**: Python relies on indentation. If you add an `if`, `try`, or `def` statement, you MUST indent the code beneath it. If you remove one, you MUST dedent the code. Do not leave orphaned indents.\n4. **ABSOLUTE SPACES**: The spaces in your block must match the absolute margin of the source code.\n5. **VARIABLE SCOPE**: Ensure variables are accessible (use `self.` for class states).\n6. **DELETING CODE (CRITICAL)**: If your goal is to remove a block of code (e.g., when moving logic to a new file), DO NOT leave an empty block. Instead, provide a block containing a comment such as `# [Logic moved to new module]` to ensure the surrounding code remains syntactically valid.\n7. **IMPORT PATHS (MANDATORY)**: Never use the prefix `src.` in any import statement. The root of the package is `pyob`. (Example: Use `from pyob.entrance import Controller`, NOT `from src.pyob.entrance import Controller`).\n8. **TYPE HINTS (CRITICAL)**: Never use the `|` operator with quoted class names (Forward References). Use `Any` for objects that create circular dependencies.\n9. **ATOMIC REFACTORING**: Do not move large blocks or classes to new files in a single turn. Focus ONLY on logic improvements or bug fixes within the current file.\n10. **SURGICAL MOVEMENT**: If moving logic, use a 3-step process: A) Add new file/imports. B) Update call sites. C) Remove old code in a subsequent turn.\n11. **NO MASS DELETIONS**: You are strictly forbidden from replacing a large block of code with a smaller one unless you include the surrounding class/method structure in your block. If you cannot fit the structure in 5 lines, use multiple blocks.\n12. **INDENTATION LOCK**: Every block must have the exact same indentation level as the block.\n13. **PRESERVE STRUCTURE**: Never use a block that cuts off a class or method definition. Always include the full line you are matching.\n14. **NO EMOJIS (MANDATORY)**: Never use emojis or non-ASCII characters in logger messages, print statements, or source comments. Use plain ASCII text only. Emojis cause encoding errors and git diff corruption.\n15. **NO INTERNAL TESTS**: Never write test suites (Jest/Pytest/describe blocks) inside a source file logic. Use the dedicated Phase 0 system for tests.\n16. **JAVASCRIPT STANDARDS**: If editing `.js` files, use `const` and `let` (avoid `var`), and always include the `.js` extension in `import` statements. Ensure logic is encapsulated in the correct class or module.\n### REQUIRED XML FORMAT:\n\n1. Lines to change: ...\n2. New imports needed: [List them or state 'None']\n3. Strategy: ...\n\n\n\nExact 2-5 lines\n\n\nNew code\n\n\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
+ "PCF.md": "You are the PYOB Symbolic Fixer taking over Phase 3 Cascaded Edits.\n{memory_section}We just modified `{trigger_file}`, and it broke a dependency downstream: `{rel_broken_path}`.\n\n### Linter Errors for `{rel_broken_path}`:\n{mypy_errors}\n\n### Source Code of `{rel_broken_path}`:\n```python\n{broken_code}\n```\n\n### Instructions:\n1. Respond EXCLUSIVELY with a block followed by ONE block to fix the broken references.\n2. **DEFEATING MYPY (CRITICAL)**: If the error contains `[union-attr]` or states `Item `None` of ... has no attribute`, adding a type hint will fail. You MUST fix this by either inserting `assert variable is not None` before the operation, or adding `# type: ignore` to the end of the failing line.\n\n### REQUIRED XML FORMAT:\n\nExplanation of cascade fix...\n\n\n\nExact lines to replace\n\n\nNew replacement lines\n\n\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
+ "PIR.md": "You are an elite PYOB developer performing a post-implementation repair.\nAn automated attempt to implement a feature or bugfix has failed, resulting in the following errors.\n\n### Original Goal / Change Request:\n{context_of_change}\n\n### The Resulting Errors (Linter/Runtime):\n{err_text}\n\n### The Broken Code in `{rel_path}`:\n```\n{code}\n```\n\n### Instructions:\n1. Analyze the 'Original Goal' and the 'Resulting Errors' together.\n2. CRITICAL INDENTATION CHECK: If the error says `Unexpected indentation`, rewrite the block with PERFECT absolute indentation.\n3. CRITICAL IMPORT CHECK: If the error is `F821 Undefined name`, you MUST create an block at the top of the file to add the missing `import` statement.\n4. DEFEATING MYPY: If the error is a `[union-attr]` or `None` type error, simply adding a type hint will fail the linter again. You MUST insert `assert object is not None` right before it is used, or append `# type: ignore` to the failing line.\n5. Create a surgical XML edit to fix the code.\n6. **DELETING CODE**: If you are removing logic, never use an empty block. Always include a placeholder comment to maintain valid Python syntax.\n7. **VISUAL LEAK CHECK**: If the error logs or context suggest that raw code is visible to the user on the screen, this is a CRITICAL UI FAILURE. Locate the stray text and wrap it in the correct tags or delete it immediately.\n\n### REQUIRED XML FORMAT:\n\nRoot Cause: ...\nImports Needed: ...\nIndentation Fix Needed: [Yes/No]\nAction: ...\n\n\n\nExact lines to replace\n\n\nNew replacement lines\n\n\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
}
for filename, content in templates.items():
filepath = os.path.join(data_dir, filename) # Use data_dir here
From 965c4a7f4f476c08fcfa8e5beb37288304827fe1 Mon Sep 17 00:00:00 2001
From: Vic <125237471+vicsanity623@users.noreply.github.com>
Date: Mon, 23 Mar 2026 00:13:57 -0700
Subject: [PATCH 7/9] Update entrance_mixins.py
---
src/pyob/entrance_mixins.py | 41 ++++++++++++++++++++++---------------
1 file changed, 25 insertions(+), 16 deletions(-)
diff --git a/src/pyob/entrance_mixins.py b/src/pyob/entrance_mixins.py
index 587f9c4..fe36f89 100644
--- a/src/pyob/entrance_mixins.py
+++ b/src/pyob/entrance_mixins.py
@@ -11,10 +11,9 @@
class EntranceMixin:
"""
- Mixin providing core iteration logic.
+ Mixin providing core iteration logic.
Attributes are declared here to satisfy strict Mypy checks.
"""
- # --- TYPE ANNOTATIONS FOR MYPY (Fixes 23 errors) ---
target_dir: str
pyob_dir: str
ENGINE_FILES: list[str]
@@ -31,20 +30,30 @@ class EntranceMixin:
manual_target_file: Optional[str]
key_cooldowns: dict[str, float]
- def pick_target_file(self) -> str: return ""
- def _read_file(self, path: str) -> str: return ""
- def _extract_path_from_llm_response(self, text: str) -> str: return ""
- def get_valid_llm_response(self, p: str, v: Callable[[str], bool], context: str) -> str: return ""
- def update_analysis_for_single_file(self, abs_p: str, rel_p: str): pass
- def update_ledger_for_file(self, rel_p: str, code: str): pass
- def detect_symbolic_ripples(self, o: str, n: str, p: str) -> list[str]: return []
- def _run_final_verification_and_heal(self, b: dict) -> bool: return False
- def handle_git_librarian(self, p: str, i: int): pass
- def append_to_history(self, p: str, o: str, n: str): pass
- def wrap_up_evolution_session(self): pass
- def generate_pr_summary(self, rel_path: str, diff_text: str) -> dict: return {}
- # ---------------------------------------------------
-
+ def pick_target_file(self) -> str:
+ return ""
+ def _read_file(self, path: str) -> str:
+ return ""
+ def _extract_path_from_llm_response(self, text: str) -> str:
+ return ""
+ def get_valid_llm_response(self, p: str, v: Callable[[str], bool], context: str) -> str:
+ return ""
+ def update_analysis_for_single_file(self, abs_p: str, rel_p: str):
+ pass
+ def update_ledger_for_file(self, rel_p: str, code: str):
+ pass
+ def detect_symbolic_ripples(self, o: str, n: str, p: str) -> list[str]:
+ return []
+ def _run_final_verification_and_heal(self, b: dict) -> bool:
+ return False
+ def handle_git_librarian(self, p: str, i: int):
+ pass
+ def append_to_history(self, p: str, o: str, n: str):
+ pass
+ def wrap_up_evolution_session(self):
+ pass
+ def generate_pr_summary(self, rel_path: str, diff_text: str) -> dict:
+ return {}
def execute_targeted_iteration(self, iteration: int):
"""Orchestrates a single targeted evolution step."""
backup_state = self.llm_engine.backup_workspace()
From e15fe1ff2ee32ad1f0862c48714b5ec544e255a1 Mon Sep 17 00:00:00 2001
From: Vic <125237471+vicsanity623@users.noreply.github.com>
Date: Mon, 23 Mar 2026 00:17:06 -0700
Subject: [PATCH 8/9] Update entrance_mixins.py
---
src/pyob/entrance_mixins.py | 15 ++++++++++-----
1 file changed, 10 insertions(+), 5 deletions(-)
diff --git a/src/pyob/entrance_mixins.py b/src/pyob/entrance_mixins.py
index fe36f89..a6bf229 100644
--- a/src/pyob/entrance_mixins.py
+++ b/src/pyob/entrance_mixins.py
@@ -82,7 +82,8 @@ def execute_targeted_iteration(self, iteration: int):
pod_path.mkdir(parents=True, exist_ok=True)
for f_name in self.ENGINE_FILES:
src = os.path.join(self.target_dir, "src", "pyob", f_name)
- if os.path.exists(src): shutil.copy(src, str(pod_path))
+ if os.path.exists(src):
+ shutil.copy(src, str(pod_path))
except Exception as e:
logger.error(f"Failed to create safety pod: {e}")
@@ -100,13 +101,16 @@ def execute_targeted_iteration(self, iteration: int):
from pyob.targeted_reviewer import TargetedReviewer
reviewer = TargetedReviewer(self.target_dir, target_abs_path)
reviewer.session_context = self.llm_engine.session_context[:]
- if hasattr(self, 'key_cooldowns'): reviewer.key_cooldowns = self.key_cooldowns
- if hasattr(self, 'session_pr_count'): reviewer.session_pr_count = self.session_pr_count
+ if hasattr(self, 'key_cooldowns'):
+ reviewer.key_cooldowns = self.key_cooldowns
+ if hasattr(self, 'session_pr_count'):
+ reviewer.session_pr_count = self.session_pr_count
reviewer.run_pipeline(iteration)
self.llm_engine.session_context = reviewer.session_context[:]
- if hasattr(reviewer, 'session_pr_count'): self.session_pr_count = reviewer.session_pr_count
+ if hasattr(reviewer, 'session_pr_count'):
+ self.session_pr_count = reviewer.session_pr_count
new_content = ""
if os.path.exists(target_abs_path):
@@ -132,7 +136,8 @@ def execute_targeted_iteration(self, iteration: int):
logger.error("Final verification failed. Changes rolled back.")
else:
self.handle_git_librarian(target_rel_path, iteration)
- if is_engine_file: self.self_evolved_flag = True
+ if is_engine_file:
+ self.self_evolved_flag = True
# --- THE FINAL WRAP-UP GATE ---
if getattr(self, "session_pr_count", 0) >= 8 and not getattr(self, "cascade_queue", []):
From fa8fc396329e7cf7e9c912874c1229c7c950bc70 Mon Sep 17 00:00:00 2001
From: vicsanity623 <125237471+vicsanity623@users.noreply.github.com>
Date: Mon, 23 Mar 2026 07:17:32 +0000
Subject: [PATCH 9/9] =?UTF-8?q?=F0=9F=AA=84=20PyOB:=20Automated=20Lint=20&?=
=?UTF-8?q?=20Format=20Fixes?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/pyob/entrance_mixins.py | 49 +++++++++++++++++++++++++++-------
src/pyob/prompts_and_memory.py | 2 +-
2 files changed, 40 insertions(+), 11 deletions(-)
diff --git a/src/pyob/entrance_mixins.py b/src/pyob/entrance_mixins.py
index a6bf229..ab12d08 100644
--- a/src/pyob/entrance_mixins.py
+++ b/src/pyob/entrance_mixins.py
@@ -1,5 +1,4 @@
import difflib
-import json
import logging
import os
import shutil
@@ -9,11 +8,13 @@
logger = logging.getLogger(__name__)
+
class EntranceMixin:
"""
Mixin providing core iteration logic.
Attributes are declared here to satisfy strict Mypy checks.
"""
+
target_dir: str
pyob_dir: str
ENGINE_FILES: list[str]
@@ -32,28 +33,42 @@ class EntranceMixin:
def pick_target_file(self) -> str:
return ""
+
def _read_file(self, path: str) -> str:
return ""
+
def _extract_path_from_llm_response(self, text: str) -> str:
return ""
- def get_valid_llm_response(self, p: str, v: Callable[[str], bool], context: str) -> str:
+
+ def get_valid_llm_response(
+ self, p: str, v: Callable[[str], bool], context: str
+ ) -> str:
return ""
+
def update_analysis_for_single_file(self, abs_p: str, rel_p: str):
pass
+
def update_ledger_for_file(self, rel_p: str, code: str):
pass
+
def detect_symbolic_ripples(self, o: str, n: str, p: str) -> list[str]:
return []
+
def _run_final_verification_and_heal(self, b: dict) -> bool:
return False
+
def handle_git_librarian(self, p: str, i: int):
pass
+
def append_to_history(self, p: str, o: str, n: str):
pass
+
def wrap_up_evolution_session(self):
pass
+
def generate_pr_summary(self, rel_path: str, diff_text: str) -> dict:
return {}
+
def execute_targeted_iteration(self, iteration: int):
"""Orchestrates a single targeted evolution step."""
backup_state = self.llm_engine.backup_workspace()
@@ -62,7 +77,9 @@ def execute_targeted_iteration(self, iteration: int):
if self.cascade_queue:
target_rel_path = self.cascade_queue.pop(0)
target_diff = self.cascade_diffs.get(target_rel_path, "")
- logger.warning(f"SYMBOLIC CASCADE: Targeting impacted file: {target_rel_path}")
+ logger.warning(
+ f"SYMBOLIC CASCADE: Targeting impacted file: {target_rel_path}"
+ )
is_cascade = True
else:
target_rel_path = self.pick_target_file()
@@ -99,17 +116,18 @@ def execute_targeted_iteration(self, iteration: int):
old_content = f.read()
from pyob.targeted_reviewer import TargetedReviewer
+
reviewer = TargetedReviewer(self.target_dir, target_abs_path)
reviewer.session_context = self.llm_engine.session_context[:]
- if hasattr(self, 'key_cooldowns'):
+ if hasattr(self, "key_cooldowns"):
reviewer.key_cooldowns = self.key_cooldowns
- if hasattr(self, 'session_pr_count'):
+ if hasattr(self, "session_pr_count"):
reviewer.session_pr_count = self.session_pr_count
reviewer.run_pipeline(iteration)
self.llm_engine.session_context = reviewer.session_context[:]
- if hasattr(reviewer, 'session_pr_count'):
+ if hasattr(reviewer, "session_pr_count"):
self.session_pr_count = reviewer.session_pr_count
new_content = ""
@@ -124,8 +142,15 @@ def execute_targeted_iteration(self, iteration: int):
if old_content != new_content:
logger.info(f"Edit successful. Verifying {target_rel_path}...")
self.append_to_history(target_rel_path, old_content, new_content)
- current_diff = "".join(difflib.unified_diff(old_content.splitlines(keepends=True), new_content.splitlines(keepends=True)))
- ripples = self.detect_symbolic_ripples(old_content, new_content, target_rel_path)
+ current_diff = "".join(
+ difflib.unified_diff(
+ old_content.splitlines(keepends=True),
+ new_content.splitlines(keepends=True),
+ )
+ )
+ ripples = self.detect_symbolic_ripples(
+ old_content, new_content, target_rel_path
+ )
if ripples:
for r in ripples:
if r not in self.cascade_queue:
@@ -140,6 +165,10 @@ def execute_targeted_iteration(self, iteration: int):
self.self_evolved_flag = True
# --- THE FINAL WRAP-UP GATE ---
- if getattr(self, "session_pr_count", 0) >= 8 and not getattr(self, "cascade_queue", []):
- logger.info(f"🏆 MISSION ACCOMPLISHED: {self.session_pr_count} PRs achieved.")
+ if getattr(self, "session_pr_count", 0) >= 8 and not getattr(
+ self, "cascade_queue", []
+ ):
+ logger.info(
+ f"🏆 MISSION ACCOMPLISHED: {self.session_pr_count} PRs achieved."
+ )
self.wrap_up_evolution_session()
diff --git a/src/pyob/prompts_and_memory.py b/src/pyob/prompts_and_memory.py
index a397d5e..043bc32 100644
--- a/src/pyob/prompts_and_memory.py
+++ b/src/pyob/prompts_and_memory.py
@@ -31,7 +31,7 @@ def _ensure_prompt_files(self) -> None:
templates = {
"UM.md": "You are the PyOB Memory Manager. Your job is to update MEMORY.md.\n\n### Current Memory:\n{current_memory}\n\n### Recent Actions:\n{session_summary}\n\n### INSTRUCTIONS:\n1. Update the memory with the Recent Actions.\n2. TRANSACTIONAL RECORDING: Only record changes as 'Implemented' if the actions specifically state 'SUCCESSFUL CHANGE'. If you see 'CRITICAL: FAILED' or 'ROLLED BACK', record this as a 'Failed Attempt' with the reason, so the engine knows to try a different approach next time.\n3. BREVITY: Keep the ENTIRE document under 200 words. Be ruthless. Delete old, irrelevant details.\n4. FORMAT: Keep lists strictly to bullet points. No long paragraphs.\n5. **HUMAN DIRECTIVES**: If the current memory contains a section titled HUMAN DIRECTIVES, you are strictly FORBIDDEN from deleting or altering it. Prepend all new session summaries BELOW that section.\n6. Respond EXCLUSIVELY with the raw markdown for MEMORY.md. Do not use ```markdown fences or blocks.\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
"RM.md": "You are the PYOB Memory Manager. The current MEMORY.md is too bloated and is breaking the AI context window.\n\n### Bloated Memory:\n{current_memory}\n\n### INSTRUCTIONS:\n1. AGGRESSIVELY COMPRESS this memory. \n2. Delete duplicate information, repetitive logs, and obvious statements.\n3. Keep ONLY the core architectural rules and crucial file dependencies.\n4. The final output MUST BE UNDER 150 WORDS.\n5. Respond EXCLUSIVELY with the raw markdown. No fences, no thoughts.\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
- "PP.md": "You are an elite PYOB Software Engineer. Analyze the code for bugs or architectural gaps.\n\n{memory_section}{ruff_section}{mypy_section}{custom_issues_section}### Source Code:\n```{lang_tag}\n{content}\n```\n\n### CRITICAL RULES:\n1. **ITERATION BUDGET**: \n - IF iteration < 5: Focus ONLY on bug fixes, linting, and minor performance tweaks. Do NOT create new files, move classes, or extract logic. \n - IF iteration >= 5: You may propose architectural refactors, file extractions, and logic movement.\n2. **SURGICAL FIXES**: Every block must be exactly 2-5 lines. Only provide ONE block per response.\n3. **NO HALLUCINATIONS**: Do not invent bugs. If the code is functional, state 'The code looks good.'\n4. **ARCHITECTURAL BLOAT**: Only flag bloat for future planning until iteration 5.\n5. **MISSING IMPORTS**: If you use a new module/type, you MUST add an block to import it at the top.\n6. **INDENTATION IS SYNTAX**: Your blocks must have perfect, absolute indentation.\n7. **DEFEATING MYPY**: If fixing a `[union-attr]` error, use `assert variable is not None` or `# type: ignore`.\n8. **IMPORT PATHS (MANDATORY)**: Never use the prefix `src.` in any import statement. The root of the package is `pyob`. (Example: Use `from pyob.core_utils import ...`, NOT `from src.pyob.core_utils import ...`).\n9. **TYPE HINTS (CRITICAL)**: Never use the `|` operator with quoted class names (Forward References). Use `Any` for objects that create circular dependencies.\n10. **ATOMIC REFACTORING**: If you are beyond iteration 5 and need to move logic, use a 3-step process: A) Add new file/imports. B) Update call sites. C) Remove old code in a subsequent turn.\n11. **NO SCAFFOLDING (CRITICAL)**: Never include bot-specific text, logs, or status tags (like \"APPROVED\" or \"LIBRARIAN\") inside the code blocks. Your output must be 100% valid code for the target language.\n\n### HOW TO RESPOND (CHOOSE ONE):\n\n**SCENARIO A: Code has bugs/bloat and needs edits:**\n\nSummary: ...\nEvaluation: [Address bloat here if flagged]\nImports Required: ...\nAction: I will fix X by doing Y.\n\n\n\nExact lines to replace (2-5 lines max)\n\n\nNew lines\n\n\n\n**SCENARIO B: Code is perfect. NO EDITS NEEDED:**\n\nSummary: ...\nEvaluation: ...\nAction: The code looks good. No fixes needed.\n\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
+ "PP.md": 'You are an elite PYOB Software Engineer. Analyze the code for bugs or architectural gaps.\n\n{memory_section}{ruff_section}{mypy_section}{custom_issues_section}### Source Code:\n```{lang_tag}\n{content}\n```\n\n### CRITICAL RULES:\n1. **ITERATION BUDGET**: \n - IF iteration < 5: Focus ONLY on bug fixes, linting, and minor performance tweaks. Do NOT create new files, move classes, or extract logic. \n - IF iteration >= 5: You may propose architectural refactors, file extractions, and logic movement.\n2. **SURGICAL FIXES**: Every block must be exactly 2-5 lines. Only provide ONE block per response.\n3. **NO HALLUCINATIONS**: Do not invent bugs. If the code is functional, state \'The code looks good.\'\n4. **ARCHITECTURAL BLOAT**: Only flag bloat for future planning until iteration 5.\n5. **MISSING IMPORTS**: If you use a new module/type, you MUST add an block to import it at the top.\n6. **INDENTATION IS SYNTAX**: Your blocks must have perfect, absolute indentation.\n7. **DEFEATING MYPY**: If fixing a `[union-attr]` error, use `assert variable is not None` or `# type: ignore`.\n8. **IMPORT PATHS (MANDATORY)**: Never use the prefix `src.` in any import statement. The root of the package is `pyob`. (Example: Use `from pyob.core_utils import ...`, NOT `from src.pyob.core_utils import ...`).\n9. **TYPE HINTS (CRITICAL)**: Never use the `|` operator with quoted class names (Forward References). Use `Any` for objects that create circular dependencies.\n10. **ATOMIC REFACTORING**: If you are beyond iteration 5 and need to move logic, use a 3-step process: A) Add new file/imports. B) Update call sites. C) Remove old code in a subsequent turn.\n11. **NO SCAFFOLDING (CRITICAL)**: Never include bot-specific text, logs, or status tags (like "APPROVED" or "LIBRARIAN") inside the code blocks. Your output must be 100% valid code for the target language.\n\n### HOW TO RESPOND (CHOOSE ONE):\n\n**SCENARIO A: Code has bugs/bloat and needs edits:**\n\nSummary: ...\nEvaluation: [Address bloat here if flagged]\nImports Required: ...\nAction: I will fix X by doing Y.\n\n\n\nExact lines to replace (2-5 lines max)\n\n\nNew lines\n\n\n\n**SCENARIO B: Code is perfect. NO EDITS NEEDED:**\n\nSummary: ...\nEvaluation: ...\nAction: The code looks good. No fixes needed.\n\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.',
"ALF.md": "You are an elite developer fixing syntax errors.\nThe file `{rel_path}` failed validation with these exact errors:\n{err_text}\n\n### Current Code:\n```\n{code}\n```\n\n### Instructions:\n1. Fix the syntax errors (like stray brackets, unexpected tokens, or indentation) using surgical XML edits.\n2. Respond EXCLUSIVELY with a block followed by ONE OR MORE blocks.\n3. Ensure your edits perfectly align with the surrounding brackets.\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",
"FRE.md": "You are an elite PYOB developer fixing runtime crashes.\n{memory_section}The application crashed during a test run.\n\n### Crash Logs & Traceback:\n{logs}\n\nThe traceback indicates the error occurred in `{rel_path}`.\n\n### Current Code of `{rel_path}`:\n```python\n{code}\n```\n\n### Instructions:\n1. Identify the EXACT root cause of the crash.\n2. Fix the error using surgical XML edits.\n3. Respond EXCLUSIVELY with a block followed by ONE OR MORE blocks.\n\n### REQUIRED XML FORMAT:\n\nExplanation of root cause...\nImports Needed: [List new imports required or 'None']\n\n\n\nExact lines to replace\n\n\nNew replacement lines\n\n",
"PF.md": "You are the PYOB Product Architect. Review the source code and suggest ONE highly useful, INTERACTIVE feature.\n\n{memory_section}### Source Code:\n```{lang_tag}\n{content}\n```\n\n### CRITICAL RULES:\n1. Suggest an INTERACTIVE feature (UI elements, buttons, menus).\n2. **ARCHITECTURAL SPLIT (MANDATORY)**: If the source code is over 800 lines, you ARE NOT ALLOWED to propose a new feature. You MUST propose an 'Architectural Split'. Identify a logical module (like a Mixin) to move to a NEW file.\n3. **SINGLE FILE LIMIT**: If you are proposing an Architectural Split, you are ONLY allowed to create ONE new file per iteration. Do not attempt to split multiple modules at once. Focus on the largest logical block first.\n4. **NEW FILE FORMAT**: If proposing a split, your block MUST use this format: [Full Code for New File]. Your must then explain how to update the original file to import this new module.\n5. MULTI-FILE ORCHESTRATION: Explicitly list filenames of other files that will need updates in your .\n6. The block MUST contain ONLY the new logic or the block.\n\n### REQUIRED XML FORMAT:\n\n...\n\n\n# New logic OR tag here\n\n FINAL WARNING: Only output XML and code. If you add conversational text outside of or , the system will ROLLBACK.",