-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsystem_improver.py.bak
More file actions
2530 lines (2041 loc) · 102 KB
/
system_improver.py.bak
File metadata and controls
2530 lines (2041 loc) · 102 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
system_improver.py - Meta-improvement system that analyzes and enhances the Agentic Learning System
Usage:
python system_improver.py [--backup]
This script:
1. Inspects the current state of the Agentic Learning System
2. Analyzes performance history and identifies improvement opportunities
3. Makes targeted code changes to enhance performance
4. Tracks changes and validates improvements
USAGE INSTRUCTIONS:
------------------
1. STAGING WORKFLOW (Recommended):
a) Generate and stage changes for review:
python system_improver.py --stage-only
b) Review staged changes:
cat staged_changes.json
c) Apply staged changes if approved:
python system_improver.py --apply-staged
2. AUTOMATIC WORKFLOW:
a) Generate, apply and validate changes:
python system_improver.py
b) Generate and apply changes without validation:
python system_improver.py --skip-validation
"""
import os
import sys
import json
import time
import argparse
import datetime
import difflib
import re
import shutil
import subprocess
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple
# Import required dependencies for LLM calling
from google import genai
from google.genai import types
class SystemImprover:
"""
Autonomous improvement system for the Agentic Learning System.
Reviews performance and makes code changes to enhance the system.
"""
def __init__(self,
create_backup: bool = True):
"""
Initialize the system improver.
Args:
create_backup: Whether to create a backup before making changes
"""
# System paths
self.root_dir = Path(".")
self.archive_dir = self.root_dir / "archive"
self.scripts_dir = self.root_dir / "scripts"
self.diffs_dir = self.root_dir / "diffs"
self.backup_dir = self.root_dir / "backups"
# Create required directories
self.diffs_dir.mkdir(exist_ok=True)
self.backup_dir.mkdir(exist_ok=True)
# Core code files to analyze and potentially modify
self.code_files = [
"agent_system.py",
"dataset_loader.py",
"run_script.py",
"system_prompt.md"
]
# Settings
self.create_backup = create_backup
self.improvement_timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
# Initialize LLM client
try:
self.client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
print("Initialized Gemini API client successfully")
except Exception as e:
print(f"Error initializing Gemini API client: {e}")
print("Make sure to set the GEMINI_API_KEY environment variable")
sys.exit(1)
def generate_changes_only(self) -> Dict:
"""
Generate system improvement changes without applying them.
These changes can be reviewed and applied later.
Returns:
Dict containing proposed changes and system analysis
"""
print("\n" + "="*80)
print(f"System Improver - Generating Changes - {self.improvement_timestamp}")
print("="*80)
# 1. Inspect the current system state
system_data = self._inspect_system()
# 2. Analyze performance and identify improvement areas
improvement_plan = self._analyze_for_improvements(system_data)
# 3. Save the improvement plan
staged_changes = {
"timestamp": self.improvement_timestamp,
"system_state": {
"current_iteration": improvement_plan.get("current_iteration", 0)
},
"analysis_summary": improvement_plan.get("analysis", ""),
"improvement_history_analysis": improvement_plan.get("improvement_history_analysis", ""),
"proposed_changes": improvement_plan.get("changes", []),
"generated_by": "system_improver.py"
}
# 4. Create a human-readable report
report_path = self.diffs_dir / f"proposed_changes_{self.improvement_timestamp}.md"
report_content = f"""# Proposed System Changes - {self.improvement_timestamp}
## Summary
- **Timestamp:** {self.improvement_timestamp}
- **Current Iteration:** {improvement_plan.get("current_iteration", 0)}
- **Proposed Changes:** {len(improvement_plan.get("changes", []))}
## System Analysis
{improvement_plan.get("analysis", "")}
## Improvement History Analysis
{improvement_plan.get("improvement_history_analysis", "")}
## Proposed Changes
"""
for i, change in enumerate(improvement_plan.get("changes", [])):
report_content += f"""### Change {i+1}: {change['file']}
**Description:** {change['description']}
```diff
{change['diff']}
```
"""
with open(report_path, 'w') as f:
f.write(report_content)
print(f"\nGenerated {len(improvement_plan.get('changes', []))} proposed changes.")
print(f"Changes staged for review in: staged_changes.json")
print(f"Report available at: {report_path}")
return staged_changes
def apply_changes(self, staged_changes: Dict) -> List[Dict]:
"""
Apply previously staged changes.
Args:
staged_changes: Dict containing the staged changes to apply
Returns:
List of changes that were successfully applied
"""
print("\n" + "="*80)
print(f"System Improver - Applying Staged Changes - {self.improvement_timestamp}")
print("="*80)
# Create a backup if requested
if self.create_backup:
self._create_system_backup()
# Extract the changes to apply
changes_to_apply = staged_changes.get("proposed_changes", [])
if not changes_to_apply:
print("No changes to apply - staged_changes.json has no proposed_changes")
return []
# Implement the changes
changes_made = []
# Sort changes by priority
sorted_changes = sorted(
changes_to_apply,
key=lambda x: 0 if x["priority"] == "high" else 1
)
for change in sorted_changes:
file_path = change["file"]
full_path = self.root_dir / file_path
if not full_path.exists():
print(f"Warning: File not found: {file_path}, skipping change")
continue
# Standard approach for applying changes
try:
# Load current file content
with open(full_path, 'r', encoding='utf-8') as f:
current_content = f.read()
# Apply the diff if provided
if change.get("diff"):
print(f"Applying diff to {file_path}")
new_content = self._apply_diff(current_content, change["diff"])
else:
# Fallback to LLM for direct file modification
print(f"No diff found, using LLM to modify {file_path}")
new_content = self._generate_modified_file(file_path, current_content, change["description"])
# Check if there was an actual change
if new_content == current_content:
print(f"Warning: No changes made to {file_path} - content identical after applying changes")
print("Trying alternative approach with direct LLM modification...")
new_content = self._generate_modified_file(file_path, current_content, change["description"])
# Only write if there's an actual change now
if new_content != current_content:
# Generate the real diff for record-keeping
diff = self._generate_diff(current_content, new_content, file_path)
# Print a summary of changes for debugging
diff_lines = diff.splitlines()
added = sum(1 for line in diff_lines if line.startswith('+'))
removed = sum(1 for line in diff_lines if line.startswith('-'))
print(f"Changes to write: {added} lines added, {removed} lines removed")
# Check if we have write permission
if not os.access(full_path, os.W_OK):
print(f"⚠️ WARNING: No write permission for {file_path}")
# Try to make the file writable
try:
os.chmod(full_path, os.stat(full_path).st_mode | 0o200) # Add write permission
print(f" Attempted to add write permission to {file_path}")
except Exception as perm_e:
print(f" Could not change permissions: {perm_e}")
# Create a backup of the specific file before modifying it
backup_dir = self.backup_dir / f"backup_file_{self.improvement_timestamp}"
backup_dir.mkdir(exist_ok=True, parents=True)
backup_path = backup_dir / file_path
backup_path.parent.mkdir(exist_ok=True, parents=True)
shutil.copy2(full_path, backup_path)
print(f"Backed up {file_path} to {backup_path}")
# Now write the changes
try:
with open(full_path, 'w', encoding='utf-8') as f:
f.write(new_content)
print(f"✅ Successfully wrote changes to {file_path}")
except Exception as write_e:
print(f"❌ ERROR WRITING FILE {file_path}: {write_e}")
# Try writing with different approach
try:
temp_path = self.root_dir / f"temp_{file_path}"
with open(temp_path, 'w', encoding='utf-8') as f:
f.write(new_content)
# If successful, rename the file
import shutil
shutil.move(temp_path, full_path)
print(f"✅ Successfully wrote changes using alternative approach")
except Exception as alt_e:
print(f"❌ Alternative writing approach also failed: {alt_e}")
continue
change_record = {
"file": file_path,
"description": change["description"],
"diff": diff,
"timestamp": datetime.datetime.now().isoformat()
}
changes_made.append(change_record)
else:
print(f"❌ No changes could be made to {file_path} (content remains identical)")
except Exception as e:
print(f"❌ Error implementing change for {file_path}: {e}")
import traceback
traceback.print_exc()
if not changes_made:
print("No changes were successfully implemented.")
else:
print(f"\nSuccessfully applied {len(changes_made)} of {len(changes_to_apply)} changes.")
# Optionally run validation
if os.environ.get("SKIP_VALIDATION") != "1":
self._validate_changes()
return changes_made
def run(self) -> bool:
"""
Run the system improvement process.
Returns:
bool: True if improvements were made, False otherwise
"""
print("\n" + "="*80)
print(f"System Improver - Running at {self.improvement_timestamp}")
print("="*80)
# Create a backup before making changes if requested
if self.create_backup:
self._create_system_backup()
# 1. Inspect the current system state
system_data = self._inspect_system()
# 2. Analyze performance and identify improvement areas
improvement_plan = self._analyze_for_improvements(system_data)
# 3. Generate and apply code modifications
changes_made = self._implement_improvements(improvement_plan)
# 4. Validate the changes
validation_results = self._validate_changes()
# 5. Record the changes and results
self._record_improvement_results(
improvement_plan,
changes_made,
validation_results
)
print("\nSystem improvement complete!")
print(f"Changes recorded in: {self.diffs_dir}/changes_{self.improvement_timestamp}.json")
print(f"Report available at: {self.diffs_dir}/report_{self.improvement_timestamp}.md")
return len(changes_made) > 0
def _inspect_system(self) -> Dict:
"""
Inspect the current state of the system, including:
- Current code files
- Performance history
- Learnings file
- Best script
- Common error patterns
- Previous system improvements and their effects
Returns:
Dict containing all system data
"""
print("\nInspecting system state...")
system_data = {
"code_files": {},
"performance_history": [],
"learnings": "",
"best_script": None,
"error_patterns": [],
"current_iteration": 0,
"timestamp": self.improvement_timestamp,
"improvement_history": [] # Will contain previous improvements
}
# Read all code files
for file_path in self.code_files:
path = self.root_dir / file_path
if path.exists():
try:
with open(path, 'r', encoding='utf-8') as f:
system_data["code_files"][file_path] = f.read()
print(f"Loaded {file_path}: {len(system_data['code_files'][file_path])} chars")
except Exception as e:
print(f"Error reading {file_path}: {e}")
# Get learnings file
learnings_path = self.root_dir / "learnings.txt"
if learnings_path.exists():
try:
with open(learnings_path, 'r', encoding='utf-8') as f:
system_data["learnings"] = f.read()
print(f"Loaded learnings.txt: {len(system_data['learnings'])} chars")
except Exception as e:
print(f"Error reading learnings.txt: {e}")
# Get performance history
summaries_path = self.archive_dir / "summaries.json"
if summaries_path.exists():
try:
with open(summaries_path, 'r') as f:
summaries = json.load(f)
system_data["performance_history"] = summaries
# Get the current iteration
if summaries:
sorted_summaries = sorted(summaries, key=lambda x: x.get("iteration", 0))
system_data["current_iteration"] = sorted_summaries[-1].get("iteration", 0)
print(f"Loaded {len(summaries)} iteration summaries")
except Exception as e:
print(f"Error reading summaries.json: {e}")
# Get recent iterations for detailed analysis
iterations = []
for i in range(max(0, system_data["current_iteration"] - 5), system_data["current_iteration"] + 1):
iteration_path = self.archive_dir / f"iteration_{i}.json"
if iteration_path.exists():
try:
with open(iteration_path, 'r') as f:
iteration_data = json.load(f)
iterations.append(iteration_data)
except Exception as e:
print(f"Error reading iteration_{i}.json: {e}")
system_data["recent_iterations"] = iterations
# Extract common error patterns
error_patterns = []
for summary in system_data["performance_history"]:
if "performance" in summary and "error_analysis" in summary["performance"]:
patterns = summary["performance"]["error_analysis"].get("error_patterns", [])
error_patterns.extend(patterns)
# Deduplicate error patterns
system_data["error_patterns"] = list(set(error_patterns))
# Get previous improvement history from diffs directory
self._load_improvement_history(system_data)
return system_data
def _load_improvement_history(self, system_data: Dict):
"""
Load and analyze previous improvement attempts from the diffs directory.
Args:
system_data: Current system data dictionary to update
"""
print("Analyzing previous system improvements...")
# Find all change records in chronological order
change_files = sorted(self.diffs_dir.glob("changes_*.json"))
improvement_history = []
performance_before_after = []
# Track iterations where improvements were made
improved_iterations = []
# Process each improvement record
for change_file in change_files:
try:
with open(change_file, 'r') as f:
change_record = json.load(f)
# Extract basic improvement data
timestamp = change_record.get("timestamp", "unknown")
iteration = change_record.get("system_state", {}).get("current_iteration", "unknown")
changes = change_record.get("changes_made", [])
# Skip if no actual changes were made
if not changes:
continue
improved_iterations.append(iteration)
# Find performance data from before and after this improvement
if iteration != "unknown":
# Find summaries before and after this improvement
before_perf = None
after_perf = None
for summary in system_data["performance_history"]:
if summary.get("iteration") == iteration:
before_perf = summary.get("performance", {}).get("accuracy", 0)
elif summary.get("iteration") == iteration + 1:
after_perf = summary.get("performance", {}).get("accuracy", 0)
if before_perf is not None and after_perf is not None:
perf_change = after_perf - before_perf
performance_before_after.append({
"improvement_timestamp": timestamp,
"iteration": iteration,
"before_accuracy": before_perf,
"after_accuracy": after_perf,
"change": perf_change,
"success": perf_change > 0
})
# Create a summary of this improvement
files_changed = [change.get("file") for change in changes]
change_descriptions = [change.get("description") for change in changes]
improvement_history.append({
"timestamp": timestamp,
"iteration": iteration,
"files_changed": files_changed,
"num_changes": len(changes),
"descriptions": change_descriptions,
"validation_success": change_record.get("validation_results", {}).get("success", False)
})
print(f"Found improvement at iteration {iteration} with {len(changes)} changes")
except Exception as e:
print(f"Error processing improvement record {change_file}: {e}")
# Add improvement history to system data
system_data["improvement_history"] = improvement_history
system_data["performance_impact"] = performance_before_after
system_data["improved_iterations"] = improved_iterations
print(f"Loaded {len(improvement_history)} previous improvement records")
# Analyze effectiveness of previous improvements
if performance_before_after:
successful = sum(1 for p in performance_before_after if p.get("success", False))
print(f"Previous improvements: {successful}/{len(performance_before_after)} led to performance gains")
def _analyze_for_improvements(self, system_data: Dict) -> Dict:
"""
Analyze the system data and identify improvement opportunities.
Uses LLM to generate a comprehensive improvement plan.
Args:
system_data: System inspection data
Returns:
Dict containing improvement plan
"""
print("\nAnalyzing system for improvement opportunities...")
# DEBUG: Let's see what files are loaded
print(f"Available files in system_data: {list(system_data.get('code_files', {}).keys())}")
# CRITICAL FIX: Ensure agent_system.py is loaded, even if not in the initial set
for key_file in ["agent_system.py", "dataset_loader.py", "system_prompt.md"]:
if key_file not in system_data.get("code_files", {}):
file_path = self.root_dir / key_file
if file_path.exists():
try:
with open(file_path, 'r', encoding='utf-8') as f:
if "code_files" not in system_data:
system_data["code_files"] = {}
system_data["code_files"][key_file] = f.read()
print(f"Added missing key file: {key_file}")
except Exception as e:
print(f"Error loading key file {key_file}: {e}")
# Prepare LLM prompt for system analysis
prompt = self._create_analysis_prompt(system_data)
# Call LLM for improvement analysis
system_instruction = """You are an Expert System Designer and Improvement Specialist.
Your task is to analyze a machine learning system's code and performance data,
identify limitations, and propose specific, actionable code changes to improve the system."""
print("Calling LLM for improvement analysis...")
improvement_analysis = self._call_llm(prompt, system_instruction)
# Save the raw response for debugging
debug_path = self.diffs_dir / f"raw_llm_response_{self.improvement_timestamp}.txt"
with open(debug_path, 'w', encoding='utf-8') as f:
f.write(improvement_analysis)
print(f"Raw LLM response saved to {debug_path}")
# Parse the improvement plan
try:
# Look for specific sections in the response
improvement_plan = {
"analysis": "",
"improvement_history_analysis": "",
"changes": [],
"current_iteration": system_data.get("current_iteration", 0)
}
# Extract the system analysis section
analysis_section = re.search(r"## SYSTEM ANALYSIS(.*?)(?:##|$)", improvement_analysis, re.DOTALL)
if analysis_section:
improvement_plan["analysis"] = analysis_section.group(1).strip()
print(f"Extracted system analysis: {len(improvement_plan['analysis'])} chars")
else:
print("WARNING: Could not extract system analysis section from LLM response")
# Extract the improvement history analysis section
history_analysis_section = re.search(r"## IMPROVEMENT HISTORY ANALYSIS(.*?)(?:##|$)", improvement_analysis, re.DOTALL)
if history_analysis_section:
improvement_plan["improvement_history_analysis"] = history_analysis_section.group(1).strip()
print(f"Extracted improvement history analysis: {len(improvement_plan['improvement_history_analysis'])} chars")
else:
print("WARNING: Could not extract improvement history analysis section from LLM response")
# Extract the changes section
changes_section = re.search(r"##\s*PROPOSED\s*CODE\s*CHANGES(.*?)(?:##|$)", improvement_analysis, re.DOTALL | re.IGNORECASE)
if changes_section:
changes_text = changes_section.group(1).strip()
print(f"Extracted proposed code changes section: {len(changes_text)} chars")
# Parse each change specification
change_blocks = re.findall(r"###\s*Change\s*(\d+)\s*:(.*?)(?=###\s*Change\s*\d+\s*:|$)", changes_text, re.DOTALL)
print(f"Found {len(change_blocks)} change blocks")
for i, (change_num, change_block) in enumerate(change_blocks):
print(f"Processing change block {i+1}: {len(change_block)} chars")
# Extract the file, description, and diff
file_match = re.search(r"File:[ \t]*[`'\"]?([\w./]+\.\w+)[`'\"]?", change_block, re.MULTILINE)
description_match = re.search(r"Description\s*:(.*?)(?:```diff|```|Diff\s*:|$)", change_block, re.DOTALL | re.IGNORECASE)
diff_match = re.search(r"```diff\n(.*?)```", change_block, re.DOTALL)
# If no diff match found, try alternative patterns
if not diff_match:
# Try without the 'diff' marker
diff_match = re.search(r"```\n(.*?)```", change_block, re.DOTALL)
if not diff_match:
# Try code block without newline
diff_match = re.search(r"```(.*?)```", change_block, re.DOTALL)
# Print debug info for each part
if file_match:
file_path = file_match.group(1).strip()
print(f" Found file path: {file_path}")
else:
print(" WARNING: Could not extract file path")
if description_match:
description = description_match.group(1).strip()
print(f" Found description: {len(description)} chars")
else:
print(" WARNING: Could not extract description")
if diff_match:
diff = diff_match.group(1)
print(f" Found diff: {len(diff)} chars")
else:
print(" WARNING: Could not extract diff")
file_path = file_match.group(1).strip() if file_match else None
description = description_match.group(1).strip() if description_match else ""
diff = diff_match.group(1) if diff_match else ""
# Check if we have a file path and it exists in the data
if file_path:
exists_in_data = file_path in system_data["code_files"]
exists_on_disk = os.path.exists(file_path)
print(f" File '{file_path}' exists in system data: {exists_in_data}")
print(f" File '{file_path}' exists on disk: {exists_on_disk}")
# CRITICAL FIX: Always check if the file exists on disk, even if not in system_data
if not exists_in_data and exists_on_disk:
try:
with open(file_path, 'r', encoding='utf-8') as f:
system_data["code_files"][file_path] = f.read()
print(f" Added file {file_path} to system data")
exists_in_data = True
except Exception as e:
print(f" Error reading file {file_path}: {e}")
# CRITICAL FIX: Allow changes even if the file isn't in system_data but exists on disk
if exists_in_data or exists_on_disk:
if not exists_in_data:
# Create a placeholder if we couldn't read the file
system_data["code_files"][file_path] = ""
improvement_plan["changes"].append({
"change_id": i+1,
"file": file_path,
"description": description,
"diff": diff,
"original_content": system_data["code_files"][file_path],
"priority": "high" if "high priority" in description.lower() else "medium"
})
print(f" Added change for file {file_path}")
else:
print(f" WARNING: File {file_path} not found in system data or on disk, skipping change")
else:
print(" WARNING: No file path specified, skipping change")
else:
print("WARNING: Could not extract proposed code changes section from LLM response")
# Try more generic patterns to find changes
print("Trying alternative approaches to extract changes...")
# Look for file paths and descriptions without explicit sections
file_matches = re.findall(r"(?:In|For|Update|Modify|Change) [`']?([\w./]+\.py)[`']?", improvement_analysis)
if file_matches:
print(f"Found potential file references: {file_matches}")
for i, file_path in enumerate(file_matches):
if file_path in system_data["code_files"]:
# Extract nearby text as description
context = re.search(r"(.{100})" + re.escape(file_path) + r"(.{200})", improvement_analysis)
description = f"Extracted from context around file mention: {context.group(1) if context else ''} {file_path} {context.group(2) if context else ''}"
improvement_plan["changes"].append({
"change_id": i+1,
"file": file_path,
"description": description,
"diff": "", # No diff found, will use LLM to generate changes
"original_content": system_data["code_files"][file_path],
"priority": "medium"
})
print(f"Added change for file {file_path} via alternative detection")
print(f"Identified {len(improvement_plan['changes'])} proposed code changes")
# If we have analysis but no changes, try to generate changes from the analysis
if improvement_plan["analysis"] and not improvement_plan["changes"]:
print("Analysis found but no changes, asking LLM to generate specific changes...")
improvement_plan["changes"] = self._generate_changes_from_analysis(
improvement_plan["analysis"],
system_data
)
return improvement_plan
except Exception as e:
print(f"Error parsing improvement plan: {e}")
import traceback
traceback.print_exc()
return {
"analysis": improvement_analysis,
"changes": [],
"current_iteration": system_data.get("current_iteration", 0)
}
def _generate_changes_from_analysis(self, analysis: str, system_data: Dict) -> List[Dict]:
"""
Generate specific code changes from system analysis when none were provided.
Args:
analysis: System analysis text
system_data: System data including code files
Returns:
List of change specifications
"""
print("Generating specific code changes from analysis...")
# Get the files we have available
available_files = list(system_data["code_files"].keys())
if not available_files:
print("No files available to modify")
return []
# Create a prompt to generate specific changes
change_gen_system_instruction = """You are an Expert Code Improvement Specialist.
Your task is to translate a system analysis into specific, actionable code changes."""
change_gen_prompt = f"""
Based on the system analysis below, I need you to propose 2-3 specific code changes to improve the system.
# SYSTEM ANALYSIS
{analysis}
# AVAILABLE FILES
{', '.join(available_files)}
For each change, specify:
1. Which specific file to modify
2. What specific changes to make
3. A detailed diff showing the exact changes
# REQUIRED OUTPUT FORMAT
## PROPOSED CODE CHANGES
### Change 1:
File: `filename.py`
Description: Clear description of the improvement
```diff
- Original line
+ Modified line
```
### Change 2:
[etc...]
The changes should be specific, focused improvements that address the issues identified in the analysis.
Make sure each change includes a clear diff showing exactly what lines to change.
"""
# Call LLM to generate specific changes
try:
response = self._call_llm(change_gen_prompt, change_gen_system_instruction)
# Save the response for debugging
debug_path = self.diffs_dir / f"generated_changes_{self.improvement_timestamp}.txt"
with open(debug_path, 'w', encoding='utf-8') as f:
f.write(response)
print(f"Generated changes saved to {debug_path}")
# Parse the response to extract changes
changes = []
# Extract the changes section
changes_section = re.search(r"##\s*PROPOSED\s*CODE\s*CHANGES(.*?)(?:##|$)", response, re.DOTALL | re.IGNORECASE)
if changes_section:
changes_text = changes_section.group(1).strip()
# Parse each change specification
change_blocks = re.findall(r"###\s*Change\s*(\d+)\s*:(.*?)(?=###\s*Change\s*\d+\s*:|$)", changes_text, re.DOTALL)
for i, (change_num, change_block) in enumerate(change_blocks):
# Extract the file, description, and diff
file_match = re.search(r"File: [`']?(.*?)[`']?$", change_block, re.MULTILINE)
description_match = re.search(r"Description\s*:(.*?)(?:```diff|```|Diff\s*:|$)", change_block, re.DOTALL | re.IGNORECASE)
diff_match = re.search(r"```diff\n(.*?)```", change_block, re.DOTALL)
# If no diff match found, try alternative patterns
if not diff_match:
# Try without the 'diff' marker
diff_match = re.search(r"```\n(.*?)```", change_block, re.DOTALL)
if not diff_match:
# Try code block without newline
diff_match = re.search(r"```(.*?)```", change_block, re.DOTALL)
file_path = file_match.group(1).strip() if file_match else None
description = description_match.group(1).strip() if description_match else ""
diff = diff_match.group(1) if diff_match else ""
if file_path and file_path in system_data["code_files"]:
changes.append({
"change_id": i+1,
"file": file_path,
"description": description,
"diff": diff,
"original_content": system_data["code_files"][file_path],
"priority": "high" if "high priority" in description.lower() else "medium"
})
print(f"Generated {len(changes)} specific changes from analysis")
return changes
except Exception as e:
print(f"Error generating changes from analysis: {e}")
return []
def _implement_improvements(self, improvement_plan: Dict) -> List[Dict]:
"""
Implement the proposed code changes.
Args:
improvement_plan: The improvement plan with proposed changes
Returns:
List of changes that were successfully implemented
"""
print("\nImplementing code improvements...")
changes_made = []
# Check if we have changes to implement
if not improvement_plan["changes"]:
print("No changes to implement - generating changes from analysis...")
if improvement_plan["analysis"]:
improvement_plan["changes"] = self._generate_changes_from_analysis(
improvement_plan["analysis"],
{"code_files": self._load_all_code_files()}
)
else:
print("No analysis available to generate changes")
return []
# Check again if we have changes
if not improvement_plan["changes"]:
print("No changes could be generated - implementation aborted")
return []
# Sort changes by priority
sorted_changes = sorted(
improvement_plan["changes"],
key=lambda x: 0 if x["priority"] == "high" else 1
)
for change in sorted_changes:
file_path = change["file"]
full_path = self.root_dir / file_path
if not full_path.exists():
print(f"Warning: File not found: {file_path}, skipping change")
continue
# Determine if this is a large file that needs special handling
try:
file_size = full_path.stat().st_size
is_large_file = file_size > 100000 # ~100KB threshold
print(f"File size: {file_size/1024:.1f}KB ({'LARGE' if is_large_file else 'standard'} file)")
# For Python files, try to identify specific functions/sections to modify
if is_large_file and file_path.endswith('.py'):
result = self._targeted_file_modification(full_path, change)
if result["success"]:
changes_made.append(result["change_record"])
continue
else:
print(f"Targeted modification failed: {result['error']}")
print("Falling back to standard modification approach")
except Exception as e:
print(f"Error determining file size: {e}")
# Standard approach for normal-sized files or if targeted modification failed
try:
# Load current file content
with open(full_path, 'r', encoding='utf-8') as f:
current_content = f.read()
# Apply the diff if provided
if change.get("diff"):
print(f"Applying diff to {file_path}")
new_content = self._apply_diff(current_content, change["diff"])
else:
# Fallback to LLM for direct file modification
print(f"No diff found, using LLM to modify {file_path}")
new_content = self._generate_modified_file(file_path, current_content, change["description"])
# Check if there was an actual change
if new_content == current_content:
print(f"Warning: No changes made to {file_path} - content identical after applying changes")
print("Trying alternative approach with direct LLM modification...")
new_content = self._generate_modified_file(file_path, current_content, change["description"])
# Only write if there's an actual change now
if new_content != current_content:
# Generate the real diff for record-keeping
diff = self._generate_diff(current_content, new_content, file_path)
# Print a summary of changes for debugging
diff_lines = diff.splitlines()
added = sum(1 for line in diff_lines if line.startswith('+'))
removed = sum(1 for line in diff_lines if line.startswith('-'))
print(f"Changes to write: {added} lines added, {removed} lines removed")
# Write the updated file - this is where the actual file modification happens
try:
# Check if we have write permission
if not os.access(full_path, os.W_OK):
print(f"⚠️ WARNING: No write permission for {file_path}")
# Try to make the file writable
try:
os.chmod(full_path, os.stat(full_path).st_mode | 0o200) # Add write permission
print(f" Attempted to add write permission to {file_path}")
except Exception as perm_e:
print(f" Could not change permissions: {perm_e}")
# Create a backup of the specific file before modifying it
backup_dir = self.backup_dir / f"backup_file_{self.improvement_timestamp}"
backup_dir.mkdir(exist_ok=True, parents=True)
backup_path = backup_dir / file_path
backup_path.parent.mkdir(exist_ok=True, parents=True)
shutil.copy2(full_path, backup_path)
print(f"Backed up {file_path} to {backup_path}")
# Now write the changes
with open(full_path, 'w', encoding='utf-8') as f:
f.write(new_content)
print(f"✅ Successfully wrote changes to {file_path}")
# Verify the changes were actually written
time.sleep(0.1) # Small delay to ensure file system is updated
with open(full_path, 'r', encoding='utf-8') as f:
after_content = f.read()
if after_content == new_content:
print(f" Verified: Changes were successfully written to {file_path}")
else:
print(f"⚠️ WARNING: File was written but content doesn't match expected changes!")
except Exception as write_e:
print(f"❌ ERROR WRITING FILE {file_path}: {write_e}")
# Try writing with different approach
try:
temp_path = self.root_dir / f"temp_{file_path}"
with open(temp_path, 'w', encoding='utf-8') as f:
f.write(new_content)
# If successful, rename the file
import shutil
shutil.move(temp_path, full_path)
print(f"✅ Successfully wrote changes using alternative approach")
except Exception as alt_e:
print(f"❌ Alternative writing approach also failed: {alt_e}")
continue
change_record = {
"file": file_path,
"description": change["description"],
"diff": diff,
"timestamp": datetime.datetime.now().isoformat()
}