Skip to content

Commit ccf52ea

Browse files
authored
Merge pull request #16 from vicsanity623/pyob-evolution-v2-1773003270
Pyob evolution v2 1773003270
2 parents 13c4026 + b7a9674 commit ccf52ea

3 files changed

Lines changed: 77 additions & 77 deletions

File tree

src/pyob/entrance.py

Lines changed: 38 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,33 @@ def sync_with_remote(self) -> bool:
128128
return False
129129

130130
def reboot_pyob(self):
131-
"""Standard Hot-Reboot: Replaces the current process with a fresh one."""
132-
logger.warning("🔄 SELF-EVOLUTION COMPLETE: Rebooting fresh PYOB engine...")
133-
os.execv(sys.executable, [sys.executable] + sys.argv)
131+
"""Verified Hot-Reboot: Checks for syntax/import errors before restarting."""
132+
logger.info("🧪 PRE-FLIGHT: Verifying engine integrity before reboot...")
133+
134+
# Test if the new code can actually be loaded
135+
test_cmd = [sys.executable, "-c", "import pyob.entrance; print('SUCCESS')"]
136+
env = os.environ.copy()
137+
# Ensure 'src' is in the path for the test
138+
env["PYTHONPATH"] = os.path.join(self.target_dir, "src")
139+
140+
try:
141+
result = subprocess.run(test_cmd, capture_output=True, text=True, env=env)
142+
if "SUCCESS" in result.stdout:
143+
logger.warning(
144+
"🔄 SELF-EVOLUTION COMPLETE: Rebooting fresh PYOB engine..."
145+
)
146+
os.execv(
147+
sys.executable,
148+
[sys.executable, "-m", "pyob.pyob_launcher", self.target_dir],
149+
)
150+
else:
151+
logger.error(
152+
f"🚫 REBOOT ABORTED: The evolved code has import/syntax errors:\n{result.stderr}"
153+
)
154+
self.self_evolved_flag = False # Cancel reboot to stay alive
155+
except Exception as e:
156+
logger.error(f"❌ Pre-flight check failed: {e}")
157+
self.self_evolved_flag = False
134158

135159
def trigger_production_build(self):
136160
"""Advanced Build: Compiles PYOB into a DMG and replaces the system version."""
@@ -195,52 +219,44 @@ def run_master_loop(self):
195219
iteration = 1
196220
while True:
197221
self.current_iteration = iteration
198-
self.self_evolved_flag = False # Reset flag for the current loop
222+
self.self_evolved_flag = False
199223

200-
# 1. Check for remote updates (sets flag if remote changed engine)
201224
if self.sync_with_remote():
202225
res = subprocess.run(
203226
["git", "diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD"],
204227
cwd=self.target_dir,
205228
capture_output=True,
206229
text=True,
207230
)
231+
208232
if any(ef in res.stdout for ef in self.ENGINE_FILES):
209233
logger.warning(
210-
"🧠 REMOTE EVOLUTION: Engine updated via sync. Rebooting..."
234+
"🧠 REMOTE EVOLUTION: Engine files updated via sync. Rebooting..."
211235
)
212236
self.self_evolved_flag = True
213237

214-
# 2. Check if we need to reboot from Sync before starting work
215238
if self.self_evolved_flag:
216-
self.reboot_pyob()
239+
if getattr(sys, "frozen", False):
240+
logger.warning(
241+
"💎 COMPILED ENGINE EVOLVED: Initiating Forge Build."
242+
)
243+
self.trigger_production_build()
244+
else:
245+
logger.warning("🐍 SCRIPT ENGINE EVOLVED: Initiating Hot-Reboot.")
246+
self.reboot_pyob()
217247

218248
logger.info(
219249
f"\n\n{'=' * 70}\nTargeted Pipeline Loop (Iteration {iteration})\n{'=' * 70}"
220250
)
221251

222252
try:
223-
# 3. Perform the actual work (sets flag if engine edited itself locally)
224253
self.execute_targeted_iteration(iteration)
225254
except KeyboardInterrupt:
226255
logger.info("\nExiting Entrance Controller...")
227256
break
228257
except Exception as e:
229258
logger.error(f"Unexpected error in master loop: {e}", exc_info=True)
230259

231-
# --- MOVE THE REBOOT CHECK HERE ---
232-
# This catches local evolution immediately after the work is done
233-
if self.self_evolved_flag:
234-
if getattr(sys, "frozen", False):
235-
logger.warning(
236-
"💎 COMPILED ENGINE EVOLVED: Initiating Forge Build."
237-
)
238-
self.trigger_production_build()
239-
else:
240-
logger.warning("🐍 SCRIPT ENGINE EVOLVED: Initiating Hot-Reboot.")
241-
self.reboot_pyob()
242-
# -----------------------------------
243-
244260
iteration += 1
245261
logger.info("Iteration complete. Waiting for system cooldown...")
246262
time.sleep(120)

src/pyob/prompts_and_memory.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ def _ensure_prompt_files(self) -> None:
1717
templates = {
1818
"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 <THOUGHT> blocks.",
1919
"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.",
20-
"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. **SURGICAL FIXES**: Every <SEARCH> block must be exactly 2-5 lines.\n2. **NO HALLUCINATIONS**: Do not invent bugs. If the code is functional, state 'The code looks good.'\n3. **ARCHITECTURAL BLOAT**: If 'Code Quality Issues' flags bloat (>800 lines), your Evaluation MUST prioritize identifying which classes or methods can be moved to a new file to restore modularity.\n4. **MISSING IMPORTS**: If you use a new module/type, you MUST add an <EDIT> block to import it at the top.\n5. **INDENTATION IS SYNTAX**: Your <REPLACE> blocks must have perfect, absolute indentation.\n6. **DEFEATING MYPY**: If fixing a `[union-attr]` error, use `assert variable is not None` or `# type: ignore`.\n\n### HOW TO RESPOND (CHOOSE ONE):\n\n**SCENARIO A: Code has bugs/bloat and needs edits:**\n<THOUGHT>\nSummary: ...\nEvaluation: [Address bloat here if flagged]\nImports Required: ...\nAction: I will fix X by doing Y.\n</THOUGHT>\n<EDIT>\n<SEARCH>\nExact lines to replace\n</SEARCH>\n<REPLACE>\nNew lines\n</REPLACE>\n</EDIT>\n\n**SCENARIO B: Code is perfect. NO EDITS NEEDED:**\n<THOUGHT>\nSummary: ...\nEvaluation: ...\nAction: The code looks good. No fixes needed.\n</THOUGHT>",
20+
"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. **SURGICAL FIXES**: Every <SEARCH> block must be exactly 2-5 lines.\n2. **NO HALLUCINATIONS**: Do not invent bugs. If the code is functional, state 'The code looks good.'\n3. **ARCHITECTURAL BLOAT**: If 'Code Quality Issues' flags bloat (>800 lines), your Evaluation MUST prioritize identifying which classes or methods can be moved to a new file to restore modularity.\n4. **MISSING IMPORTS**: If you use a new module/type, you MUST add an <EDIT> block to import it at the top.\n5. **INDENTATION IS SYNTAX**: Your <REPLACE> blocks must have perfect, absolute indentation.\n6. **DEFEATING MYPY**: If fixing a `[union-attr]` error, use `assert variable is not None` or `# type: ignore`.\n7. **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 ...`).\n\n### HOW TO RESPOND (CHOOSE ONE):\n\n**SCENARIO A: Code has bugs/bloat and needs edits:**\n<THOUGHT>\nSummary: ...\nEvaluation: [Address bloat here if flagged]\nImports Required: ...\nAction: I will fix X by doing Y.\n</THOUGHT>\n<EDIT>\n<SEARCH>\nExact lines to replace\n</SEARCH>\n<REPLACE>\nNew lines\n</REPLACE>\n</EDIT>\n\n**SCENARIO B: Code is perfect. NO EDITS NEEDED:**\n<THOUGHT>\nSummary: ...\nEvaluation: ...\nAction: The code looks good. No fixes needed.\n</THOUGHT>",
2121
"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 <THOUGHT> block followed by ONE OR MORE <EDIT> blocks.\n3. Ensure your edits perfectly align with the surrounding brackets.",
2222
"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 <THOUGHT> block followed by ONE OR MORE <EDIT> blocks.\n\n### REQUIRED XML FORMAT:\n<THOUGHT>\nExplanation of root cause...\nImports Needed: [List new imports required or 'None']\n</THOUGHT>\n<EDIT>\n<SEARCH>\nExact lines to replace\n</SEARCH>\n<REPLACE>\nNew replacement lines\n</REPLACE>\n</EDIT>",
2323
"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 <SNIPPET> block MUST use this format: <CREATE_FILE path=\"new_filename.py\">[Full Code for New File]</CREATE_FILE>. Your <THOUGHT> 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 <THOUGHT>.\n6. The <SNIPPET> block MUST contain ONLY the new logic or the <CREATE_FILE> block.\n\n### REQUIRED XML FORMAT:\n<THOUGHT>\n...\n</THOUGHT>\n<SNIPPET>\n# New logic OR <CREATE_FILE> tag here\n</SNIPPET>",
24-
"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 <SEARCH> block must be EXACTLY 2-5 lines.\n2. **MISSING IMPORTS**: If your feature introduces a new class/function, add a separate <EDIT> 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 <REPLACE> 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 <REPLACE> block. Instead, provide a <REPLACE> block containing a comment such as `# [Logic moved to new module]` to ensure the surrounding code remains syntactically valid.\n\n### REQUIRED XML FORMAT:\n<THOUGHT>\n1. Lines to change: ...\n2. New imports needed: [List them or state 'None']\n3. Strategy: ...\n</THOUGHT>\n<EDIT>\n<SEARCH>\nExact 2-5 lines\n</SEARCH>\n<REPLACE>\nNew code\n</REPLACE>\n</EDIT>",
24+
"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 <SEARCH> block must be EXACTLY 2-5 lines.\n2. **MISSING IMPORTS**: If your feature introduces a new class/function, add a separate <EDIT> 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 <REPLACE> 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 <REPLACE> block. Instead, provide a <REPLACE> 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`).\n\n### REQUIRED XML FORMAT:\n<THOUGHT>\n1. Lines to change: ...\n2. New imports needed: [List them or state 'None']\n3. Strategy: ...\n</THOUGHT>\n<EDIT>\n<SEARCH>\nExact 2-5 lines\n</SEARCH>\n<REPLACE>\nNew code\n</REPLACE>\n</EDIT>",
2525
"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 <THOUGHT> block followed by ONE <EDIT> 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<THOUGHT>\nExplanation of cascade fix...\n</THOUGHT>\n<EDIT>\n<SEARCH>\nExact lines to replace\n</SEARCH>\n<REPLACE>\nNew replacement lines\n</REPLACE>\n</EDIT>',
2626
"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 <EDIT> block with PERFECT absolute indentation.\n3. CRITICAL IMPORT CHECK: If the error is `F821 Undefined name`, you MUST create an <EDIT> 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 <REPLACE> block. Always include a placeholder comment to maintain valid Python syntax.\n\n### REQUIRED XML FORMAT:\n<THOUGHT>\nRoot Cause: ...\nImports Needed: ...\nIndentation Fix Needed: [Yes/No]\nAction: ...\n</THOUGHT>\n<EDIT>\n<SEARCH>\nExact lines to replace\n</SEARCH>\n<REPLACE>\nNew replacement lines\n</REPLACE>\n</EDIT>",
2727
}

0 commit comments

Comments
 (0)