File size: 6,249 Bytes
0dd3e86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41190ed
 
 
 
0dd3e86
 
 
 
41190ed
 
 
0dd3e86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

# ./dream_agent.py

"""
By design, the dream_agent will only inspect, analyze, and report. It operates like an engineering consultant presenting a formal change proposal. It will generate a clear visual report of what it wants to optimize, but it is programmatically barred from altering a single character of the source code until the end-user explicitly clicks 'Apply Changes'. If clicked 'Discard', the proposal is immediately deleted from memory, leaving files completely untouched.

To achieve this cleanly, dream_agent.py is built to extract code modifications using structured XML tags (<proposed_patch>...</proposed_patch>). The app will display the text outside these tags as the review proposal, while storing the raw code safely inside a hidden Gradio State component until chosen to authorize or kill the transaction.

The standalone module - dream_agent.py - reads the workspace targets, consults dream.md protocols, executes a non-destructive simulation via llama-3.1-8b-instant, and formats the actionable proposal layout.

"""

import os
import re
from groq import Groq  # Substituted automatically if utilizing alternative client wrappers

def execute_dream_reflection(target_file="core_logic.py"):
    """
    Phase 1: Deep Cognitive Audit Run
    Reads local workspace files and drafts optimized changes without writing them to disk.
    """
    # 1. Verification Guardrails
    if not os.path.exists(target_file):
        return f"### ❌ Audit Aborted\nTarget workspace asset `{target_file}` could not be located for tracing."

    if not os.path.exists("dream.md"):
        return "### ❌ Audit Aborted\nCognitive ruleset configuration `dream.md` is missing from root."

    # 2. Ingest Environment Source Files
    with open(target_file, "r", encoding="utf-8") as f:
        source_code = f.read()

    with open("dream.md", "r", encoding="utf-8") as f:
        dream_rules = f.read()

    # 3. Initialize Independent Client API
    # Uses the same environment token configuration pattern as core_logic/storage
    #client = Groq(api_key=os.getenv("GROQ_API_KEY") or os.getenv("HF_TOKEN"))
    client = Groq(api_key=os.getenv("GROQ_API_KEY") or os.getenv("HF_TOKEN"))
    
    # 4. Construct Isolated Simulation Prompt
    simulation_prompt = f"""{dream_rules}

    You are running a deep structural code simulation. Analyze the following live Python file for efficiency bottlenecks, redundant structures, or logic holes.

    LIVE WORKSPACE CODE TARGET: `{target_file}`
    ```python
    {source_code}

    CRITICAL COMPILATION MATRIX FOR YOUR OUTPUT:

    Provide a clear Markdown analysis of what you found under "πŸ‘οΈ ANALYSIS SUMMARY".

    Provide the complete, production-ready replacement code under "πŸ“ TARGET PATCH PROPOSAL".

    Wrap your replacement code EXACTLY within structural <proposed_patch> and </proposed_patch> tags.

    YOUR RESPONSE MUST FOLLOW THIS EXACT TEMPLATE:
    πŸ‘οΈ ANALYSIS SUMMARY
    [Detail the exact code gaps, risks, or performance debt you identified here]

    πŸ“ TARGET PATCH PROPOSAL
    <proposed_patch>

    Complete, modified ready-to-run replacement code block goes here
    </proposed_patch>
    """

    """
    Note on max_tokens -> When making an API call to Groq without a max_tokens parameter, the server does not leave the window wide open. Instead, it applies a provider-side default cap. For most execution endpoints running Llama 3.1 models, if no parameter is specified, the engine typically cuts off or caps the generation token pool automatically (often default-limited at around 1024 or 2048 tokens).
    """

    try:
        completion = client.chat.completions.create(
            model="llama-3.1-8b-instant",
            messages=[{"role": "user", "content": simulation_prompt}],
            temperature=0.0,       # Force absolute deterministic logic pathing
            max_tokens=4096,       # Allots enough context space to prevent truncation loops
            top_p=1.0              # Works alongside temp=0.0 to focus token selection tightly
        )
        
        proposal_payload = completion.choices[0].message.content
        return proposal_payload

    except Exception as simulation_error:
        return f"### ❌ Cognitive Run Exception\nAPI interaction layer encountered an execution fault: {str(simulation_error)}"
    
def apply_authorized_patch(proposal_text, target_file="core_logic.py"):
    """
    Phase 2: Gated Confirmation Commit Execution
    Extracts code from XML tags, creates a rollback backup, and overwrites the target file.
    """
    try:
        # Extract content between <proposed_patch> tags
        patch_match = re.search(r"<proposed_patch>([\s\S]*?)</proposed_patch>", proposal_text)

        if not patch_match:
            return "❌ **Patch Aborted:** Could not extract structural `<proposed_patch>` bounds from model proposal."
            
        clean_extracted_code = patch_match.group(1).strip()
        
        # Strip away markdown code block wrappers if the model wrapped them inside the XML tags
        if clean_extracted_code.startswith("```python"):
            clean_extracted_code = clean_extracted_code[9:]
        if clean_extracted_code.startswith("```"):
            clean_extracted_code = clean_extracted_code[3:]
        if clean_extracted_code.endswith("```"):
            clean_extracted_code = clean_extracted_code[:-3]
            
        clean_extracted_code = clean_extracted_code.strip()

        # Safety Step: Establish a recovery point backup before committing changes
        if os.path.exists(target_file):
            backup_path = f"{target_file}.bak"
            import shutil
            shutil.copy2(target_file, backup_path)
            print(f"[+] Local rollback checkpoint generated at: {backup_path}")

        # Execute File Writing Commit Transaction
        with open(target_file, "w", encoding="utf-8") as f:
            f.write(clean_extracted_code)

        return f"βœ… **Environment Patched Successfully:** `{target_file}` has been updated. Rollback backup preserved at `{target_file}.bak`."

    except Exception as write_fault:
        return f"❌ **Systemic Write Failure:** Execution aborted while updating file system: {str(write_fault)}"