prashantmatlani commited on
Commit
0dd3e86
Β·
1 Parent(s): 8e09430

add-on -> dream mode

Browse files
Files changed (2) hide show
  1. app.py +68 -0
  2. dream_agent.py +120 -0
app.py CHANGED
@@ -109,6 +109,23 @@ with gr.Blocks() as demo:
109
  gr.Markdown("#### πŸ“Š Deployment Telemetry Logs")
110
  output_log = gr.Markdown("_Awaiting local environment staging completion..._")
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  # --- UI ROUTING HANDLERS ---
113
  def process_login_validation(password_attempt):
114
  """Step 1: Authenticates strings and updates layout toggles and browser session state."""
@@ -191,6 +208,38 @@ with gr.Blocks() as demo:
191
  result = manage_github_repo(repo_name.strip(), commit_msg, files)
192
  yield f"{result}"
193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  # ==================== BIND EVENT LISTENER LIFECYCLES ====================
195
 
196
  # Decoupled sequence: Click validates credentials and captures token -> THEN queries data array conditionally
@@ -258,4 +307,23 @@ with gr.Blocks() as demo:
258
  outputs=[output_log]
259
  )
260
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  demo.launch(theme=gr.themes.Soft(), css="styles.css")
 
109
  gr.Markdown("#### πŸ“Š Deployment Telemetry Logs")
110
  output_log = gr.Markdown("_Awaiting local environment staging completion..._")
111
 
112
+ # --- πŸ’€ COGNITIVE DREAM CORE ADDITION ---
113
+ # 1. Dedicated dynamic UI layer addition to house the Dream mode, reconsolidation telemetry logic
114
+ gr.Markdown("---")
115
+ gr.Markdown("### πŸ’€ Cognitive Dream Core")
116
+ dream_btn = gr.Button("πŸŒ™ Trigger Autonomous Audit", variant="secondary")
117
+
118
+ # This hidden box holds the human-in-the-loop verification gate controls
119
+ with gr.Box(visible=False) as review_gate_panel:
120
+ gr.Markdown("### 🚨 Pending Architectural Patch Proposal")
121
+ proposal_display = gr.Markdown() # Renders the audit analysis report
122
+
123
+ with gr.Row():
124
+ apply_patch_btn = gr.Button("βœ… Apply Changes", variant="primary")
125
+ discard_patch_btn = gr.Button("❌ Discard", variant="stop")
126
+
127
+ dream_status_log = gr.Markdown("_System operating at nominal capacities._")
128
+
129
  # --- UI ROUTING HANDLERS ---
130
  def process_login_validation(password_attempt):
131
  """Step 1: Authenticates strings and updates layout toggles and browser session state."""
 
208
  result = manage_github_repo(repo_name.strip(), commit_msg, files)
209
  yield f"{result}"
210
 
211
+ # ==================== BIND COGNITIVE DREAM LIFECYCLES ====================
212
+ # A hidden internal string tracking state to isolate the raw proposal across loops
213
+ active_proposal_state = gr.State("")
214
+
215
+ def run_background_dream_cycle():
216
+ """Triggers the non-destructive reflection loop and reveals the confirmation buttons."""
217
+ yield gr.update(value="β—Œ _Cognitive pipeline active: Running simulation audit on core_logic.py..._"), gr.update(visible=False), ""
218
+
219
+ from dream_agent import execute_dream_reflection
220
+ raw_proposal = execute_dream_reflection(target_file="core_logic.py")
221
+
222
+ # Clean up XML tags from the markdown display presentation so it reads cleanly to the user
223
+ user_report_view = raw_proposal.replace("<proposed_patch>", "```python\n[PROPOSED SOURCE CODE CHANGES]").replace("</proposed_patch>", "\n```")
224
+
225
+ yield (
226
+ gr.update(value="🟒 **Simulation Audit Complete.** Review proposal below before authorizing deployment."),
227
+ gr.update(visible=True), # Reveal the action validation confirmation buttons
228
+ user_report_view, # Send text report to the markdown viewing element
229
+ raw_proposal # Lock raw payload text into state memory buffer
230
+ )
231
+
232
+ def commit_authorized_dream_patch(proposal_buffer):
233
+ """Executes patch write operations once explicit user verification is asserted."""
234
+ from dream_agent import apply_authorized_patch
235
+ result_msg = apply_authorized_patch(proposal_buffer, target_file="core_logic.py")
236
+ return gr.update(visible=False), result_msg
237
+
238
+ def discard_dream_patch():
239
+ """Declines updates cleanly and zeroes out layout states."""
240
+ return gr.update(visible=False), "_Proposal safely discarded. Local file state left unchanged._"
241
+
242
+
243
  # ==================== BIND EVENT LISTENER LIFECYCLES ====================
244
 
245
  # Decoupled sequence: Click validates credentials and captures token -> THEN queries data array conditionally
 
307
  outputs=[output_log]
308
  )
309
 
310
+ # Event Assignments
311
+ dream_btn.click(
312
+ fn=run_background_dream_cycle,
313
+ inputs=[],
314
+ outputs=[dream_status_log, review_gate_panel, proposal_display, active_proposal_state]
315
+ )
316
+
317
+ apply_patch_btn.click(
318
+ fn=commit_authorized_dream_patch,
319
+ inputs=[active_proposal_state],
320
+ outputs=[review_gate_panel, dream_status_log]
321
+ )
322
+
323
+ discard_patch_btn.click(
324
+ fn=discard_dream_patch,
325
+ inputs=[],
326
+ outputs=[review_gate_panel, dream_status_log]
327
+ )
328
+
329
  demo.launch(theme=gr.themes.Soft(), css="styles.css")
dream_agent.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # ./dream_agent.py
3
+
4
+ """
5
+ 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.
6
+
7
+ 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.
8
+
9
+ 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.
10
+
11
+ """
12
+
13
+ import os
14
+ import re
15
+ from groq import Groq # Substituted automatically if utilizing alternative client wrappers
16
+
17
+ def execute_dream_reflection(target_file="core_logic.py"):
18
+ """
19
+ Phase 1: Deep Cognitive Audit Run
20
+ Reads local workspace files and drafts optimized changes without writing them to disk.
21
+ """
22
+ # 1. Verification Guardrails
23
+ if not os.path.exists(target_file):
24
+ return f"### ❌ Audit Aborted\nTarget workspace asset `{target_file}` could not be located for tracing."
25
+
26
+ if not os.path.exists("dream.md"):
27
+ return "### ❌ Audit Aborted\nCognitive ruleset configuration `dream.md` is missing from root."
28
+
29
+ # 2. Ingest Environment Source Files
30
+ with open(target_file, "r", encoding="utf-8") as f:
31
+ source_code = f.read()
32
+
33
+ with open("dream.md", "r", encoding="utf-8") as f:
34
+ dream_rules = f.read()
35
+
36
+ # 3. Initialize Independent Client API
37
+ # Uses the same environment token configuration pattern as core_logic/storage
38
+ #client = Groq(api_key=os.getenv("GROQ_API_KEY") or os.getenv("HF_TOKEN"))
39
+ client = Groq(api_key=os.getenv("GROQ_API_KEY") or os.getenv("HF_TOKEN"))
40
+
41
+ # 4. Construct Isolated Simulation Prompt
42
+ simulation_prompt = f"""{dream_rules}
43
+
44
+ You are running a deep structural code simulation. Analyze the following live Python file for efficiency bottlenecks, redundant structures, or logic holes.
45
+
46
+ LIVE WORKSPACE CODE TARGET: `{target_file}`
47
+ ```python
48
+ {source_code}
49
+
50
+ CRITICAL COMPILATION MATRIX FOR YOUR OUTPUT:
51
+
52
+ Provide a clear Markdown analysis of what you found under "πŸ‘οΈ ANALYSIS SUMMARY".
53
+
54
+ Provide the complete, production-ready replacement code under "πŸ“ TARGET PATCH PROPOSAL".
55
+
56
+ Wrap your replacement code EXACTLY within structural <proposed_patch> and </proposed_patch> tags.
57
+
58
+ YOUR RESPONSE MUST FOLLOW THIS EXACT TEMPLATE:
59
+ πŸ‘οΈ ANALYSIS SUMMARY
60
+ [Detail the exact code gaps, risks, or performance debt you identified here]
61
+
62
+ πŸ“ TARGET PATCH PROPOSAL
63
+ <proposed_patch>
64
+
65
+ Complete, modified ready-to-run replacement code block goes here
66
+ </proposed_patch>
67
+ """
68
+
69
+ try:
70
+ completion = client.chat.completions.create(
71
+ model="llama-3.1-8b-instant",
72
+ messages=[{"role": "user", "content": simulation_prompt}],
73
+ temperature=0.1 # Low temperature to preserve structural discipline
74
+ )
75
+
76
+ proposal_payload = completion.choices[0].message.content
77
+ return proposal_payload
78
+
79
+ except Exception as simulation_error:
80
+ return f"### ❌ Cognitive Run Exception\nAPI interaction layer encountered an execution fault: {str(simulation_error)}"
81
+
82
+ def apply_authorized_patch(proposal_text, target_file="core_logic.py"):
83
+ """
84
+ Phase 2: Gated Confirmation Commit Execution
85
+ Extracts code from XML tags, creates a rollback backup, and overwrites the target file.
86
+ """
87
+ try:
88
+ # Extract content between <proposed_patch> tags
89
+ patch_match = re.search(r"<proposed_patch>([\s\S]*?)</proposed_patch>", proposal_text)
90
+
91
+ if not patch_match:
92
+ return "❌ **Patch Aborted:** Could not extract structural `<proposed_patch>` bounds from model proposal."
93
+
94
+ clean_extracted_code = patch_match.group(1).strip()
95
+
96
+ # Strip away markdown code block wrappers if the model wrapped them inside the XML tags
97
+ if clean_extracted_code.startswith("```python"):
98
+ clean_extracted_code = clean_extracted_code[9:]
99
+ if clean_extracted_code.startswith("```"):
100
+ clean_extracted_code = clean_extracted_code[3:]
101
+ if clean_extracted_code.endswith("```"):
102
+ clean_extracted_code = clean_extracted_code[:-3]
103
+
104
+ clean_extracted_code = clean_extracted_code.strip()
105
+
106
+ # Safety Step: Establish a recovery point backup before committing changes
107
+ if os.path.exists(target_file):
108
+ backup_path = f"{target_file}.bak"
109
+ import shutil
110
+ shutil.copy2(target_file, backup_path)
111
+ print(f"[+] Local rollback checkpoint generated at: {backup_path}")
112
+
113
+ # Execute File Writing Commit Transaction
114
+ with open(target_file, "w", encoding="utf-8") as f:
115
+ f.write(clean_extracted_code)
116
+
117
+ return f"βœ… **Environment Patched Successfully:** `{target_file}` has been updated. Rollback backup preserved at `{target_file}.bak`."
118
+
119
+ except Exception as write_fault:
120
+ return f"❌ **Systemic Write Failure:** Execution aborted while updating file system: {str(write_fault)}"