-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoresearch.py
More file actions
1158 lines (929 loc) · 42.6 KB
/
autoresearch.py
File metadata and controls
1158 lines (929 loc) · 42.6 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 python3
"""
AutoResearch - Autonomous AI-Powered Research and Project Improvement System
Universal tool for running AI agent on any project for autonomous research,
improvement, and self-development.
Cross-platform support: Windows, Linux, macOS
See INSTALL.md for platform-specific setup instructions.
Usage:
python autoresearch.py # Interactive mode
python autoresearch.py --project /path/to/proj # Specify project
python autoresearch.py --project . --iter 10 # 10 iterations
python autoresearch.py --project . --iter 5 --timeout 2 # 2 min interval
Platform Detection:
This script auto-detects the OS and uses appropriate commands.
For manual setup or troubleshooting, see INSTALL.md.
"""
import os
import sys
import json
import time
import subprocess
import uuid
import argparse
from pathlib import Path
from datetime import datetime
from typing import Dict, Any, Optional, List
# Добавляем utils в путь
UTILS_DIR = Path(__file__).parent / "utils"
sys.path.insert(0, str(UTILS_DIR))
# =============================================================================
# CONFIG
# =============================================================================
AUTORESEARCH_HOME = Path(__file__).parent.resolve()
DEFAULT_PROJECT = Path.cwd()
DEFAULT_ITERATIONS = 10
DEFAULT_TIMEOUT = 5 # минут
# Директории
CONFIG_DIR = AUTORESEARCH_HOME / "config"
PROMPTS_DIR = AUTORESEARCH_HOME / "prompts"
UTILS_DIR = AUTORESEARCH_HOME / "utils"
# Файлы конфигурации
PROJECT_CONFIG_FILE = ".autoresearch.json"
GLOBAL_CONFIG_FILE = AUTORESEARCH_HOME / "config" / "global.json"
# =============================================================================
# LOGGING
# =============================================================================
def get_next_experiment_number(exp_dir: Path) -> int:
"""Автоматически определяет следующий номер эксперимента.
Проверяет существующие output_N.md файлы и возвращает следующий свободный номер.
Args:
exp_dir: Директория с экспериментами
Returns:
int: Следующий номер эксперимента
"""
if not exp_dir.exists():
return 1
# Ищем все output_N.md И prompt_N.md файлы
existing = []
for pattern in ["output_*.md", "prompt_*.md"]:
for file in exp_dir.glob(pattern):
match = file.stem.split("_")[1]
try:
num = int(match)
existing.append(num)
except (ValueError, TypeError):
continue
if not existing:
return 1
max_num = max(existing)
return max_num + 1
def log(msg: str, level: str = "INFO", project_dir: Optional[Path] = None):
"""Логирование в консоль и файл."""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
prefix = f"{timestamp} | {level:8s} |"
print(f"{prefix} {msg}")
# Лог в файл если указана директория проекта
if project_dir:
log_dir = project_dir / ".autoresearch" / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
log_file = log_dir / "autoresearch.log"
with open(log_file, "a", encoding="utf-8") as f:
f.write(f"{prefix} {msg}\n")
def read_last_entries(path: Path, max_entries: int = 5) -> str:
"""Читает ТОЛЬКО записи помеченные [CRITICAL] или [IMPORTANT].
Логика:
1. Включаются только записи с метками [CRITICAL] или [IMPORTANT]
2. Обычные записи без меток НЕ включаются
3. Это ограничивает контекст до 30-50 KB вместо 200+ KB
Args:
path: Путь к файлу памяти (lessons.md, patterns.md, architecture.md)
max_entries: Игнорируется (для совместимости с вызовами)
Returns:
str: Содержимое только помеченных записей
"""
if not path.exists():
return ""
content = path.read_text(encoding="utf-8")
# Разбиваем по ## заголовкам
lines = content.split("\n")
entries = []
current_entry = []
current_header = ""
for line in lines:
if line.startswith("## "):
# Сохраняем предыдущую запись
if current_entry:
entries.append({"header": current_header, "content": "\n".join(current_entry)})
current_header = line
current_entry = [line]
else:
if current_entry is not None:
current_entry.append(line)
# Сохраняем последнюю запись
if current_entry:
entries.append({"header": current_header, "content": "\n".join(current_entry)})
# Берем только помеченные записи
marked_entries = []
for entry in entries:
header = entry["header"]
if "[CRITICAL]" in header or "[IMPORTANT]" in header:
marked_entries.append(entry)
return "\n".join(e["content"] for e in marked_entries)
# =============================================================================
# CLAUDE CLI DETECTION
# =============================================================================
# See INSTALL.md for platform-specific installation instructions
# The code below auto-detects the OS and uses appropriate commands
def get_claude_command() -> str:
"""Auto-detects the command to run Claude CLI on any platform.
Cross-platform implementation following INSTALL.md guidelines:
- Windows: Uses PowerShell with ExecutionPolicy Bypass
- Linux/macOS: Uses direct 'claude' command
- Falls back to trying all available methods
Returns:
str: Command string to run Claude CLI
"""
# Auto-detect OS and use appropriate method
if sys.platform == "win32":
# Windows: Try PowerShell (see INSTALL.md Step 2 - Windows)
try:
result = subprocess.run(
["powershell.exe", "-Command", "Get-Command claude | Select-Object -ExpandProperty Source"],
capture_output=True,
text=True,
timeout=10,
check=False
)
if result.returncode == 0 and result.stdout.strip():
ps1_path = result.stdout.strip()
if ps1_path.endswith(".ps1"):
return f'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "{ps1_path}"'
except (subprocess.SubprocessError, OSError):
pass
# Fallback: Try cmd.exe where command
try:
result = subprocess.run(
["cmd", "/c", "where claude.ps1"],
capture_output=True,
text=True,
timeout=10,
check=False
)
if result.returncode == 0 and result.stdout.strip():
ps1_path = result.stdout.strip().split('\n')[0].strip()
return f'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "{ps1_path}"'
except (subprocess.SubprocessError, OSError):
pass
# Unix-like systems (Linux, macOS) - see INSTALL.md Step 2
return "claude"
def check_claude_cli() -> bool:
"""Checks if Claude CLI is installed and accessible.
Validates installation following INSTALL.md Step 5 (Validation).
Works on all platforms: Windows, Linux, macOS.
Returns:
bool: True if Claude CLI is found and working
"""
claude_cmd = get_claude_command()
# Platform-specific validation
if sys.platform == "win32" and "powershell.exe" in claude_cmd:
import re
match = re.search(r'-File\s+"([^"]+)"', claude_cmd)
if not match:
match = re.search(r'-File\s+(\S+)', claude_cmd)
if match:
ps1_path = match.group(1)
if Path(ps1_path).exists():
return True
# Cross-platform: try running --version
result = subprocess.run(
claude_cmd.split() + ["--version"],
capture_output=True,
text=True,
timeout=15,
check=False
)
return result.returncode == 0
# =============================================================================
# PROJECT CONFIG
# =============================================================================
class ProjectConfig:
"""Конфигурация проекта для AutoResearch."""
DEFAULT_CONFIG = {
"name": "",
"description": "",
"goals": [],
"constraints": [],
"tech_stack": [],
"memory_files": [],
"context_files": []
}
def __init__(self, project_dir: Path):
self.project_dir = project_dir
self.config_file = project_dir / PROJECT_CONFIG_FILE
self.config = self.DEFAULT_CONFIG.copy()
def load(self) -> bool:
"""Загружает конфигурацию из файла."""
if not self.config_file.exists():
return False
try:
with open(self.config_file, "r", encoding="utf-8") as f:
saved_config = json.load(f)
self.config.update(saved_config)
return True
except Exception as e:
log(f"Error loading config: {e}", "ERROR", self.project_dir)
return False
def save(self):
"""Сохраняет конфигурацию в файл."""
self.config_file.parent.mkdir(parents=True, exist_ok=True)
with open(self.config_file, "w", encoding="utf-8") as f:
json.dump(self.config, f, indent=2, ensure_ascii=False)
def is_configured(self) -> bool:
"""Проверяет, настроен ли проект."""
# Сначала загружаем конфигурацию если файл существует
if self.config_file.exists():
self.load()
return bool(
self.config_file.exists() and
self.config.get("name") and
self.config.get("goals")
)
# =============================================================================
# INTERACTIVE SETUP
# =============================================================================
def run_interactive_setup(project_dir: Path) -> ProjectConfig:
"""Запускает интерактивную настройку с помощью AI."""
log("=" * 70, project_dir=project_dir)
log("AutoResearch - First Time Setup", project_dir=project_dir)
log("=" * 70, project_dir=project_dir)
log("", project_dir=project_dir)
config = ProjectConfig(project_dir)
# Если есть частичная конфигурация, загружаем её
config.load()
# Опросник через Claude CLI
questionnaire = PROMPTS_DIR / "setup_questionnaire.md"
setup_script = UTILS_DIR / "cli_setup.py"
if setup_script.exists():
# Запускаем Python скрипт настройки
result = subprocess.run(
[sys.executable, str(setup_script), str(project_dir)],
cwd=AUTORESEARCH_HOME
)
if result.returncode == 0:
config.load()
return config
# Fallback: базовая настройка
log("Запуск базовой настройки...", project_dir=project_dir)
print(f"\nПроект: {project_dir}")
print("\nДавайте настроим AutoResearch для вашего проекта.\n")
name = input("Название проекта: ").strip() or project_dir.name
config.config["name"] = name
desc = input("Краткое описание (одна строка): ").strip()
if desc:
config.config["description"] = desc
print("\nВведите цели проекта (по одной на строку, пустая строка для завершения):")
goals = []
while True:
goal = input(" Цель: ").strip()
if not goal:
break
goals.append(goal)
config.config["goals"] = goals
print("\nВведите ограничения/оговорки (опционально, Enter для пропуска):")
constraints = []
while True:
constraint = input(" Ограничение: ").strip()
if not constraint:
break
constraints.append(constraint)
config.config["constraints"] = constraints
# Автоопределение tech stack
tech_stack = detect_tech_stack(project_dir)
if tech_stack:
config.config["tech_stack"] = tech_stack
log(f"Обнаружен tech stack: {', '.join(tech_stack)}", "INFO", project_dir)
config.save()
log("\nКонфигурация сохранена!", "INFO", project_dir)
return config
def detect_tech_stack(project_dir: Path) -> List[str]:
"""Автоопределение tech stack по файлам проекта."""
tech = []
# Проверяем основные файлы
files_to_check = [
("package.json", ["JavaScript", "TypeScript", "Node.js"]),
("requirements.txt", ["Python"]),
("pyproject.toml", ["Python"]),
("Gemfile", ["Ruby"]),
("go.mod", ["Go"]),
("Cargo.toml", ["Rust"]),
("pom.xml", ["Java", "Maven"]),
("build.gradle", ["Java", "Gradle"]),
("composer.json", ["PHP"]),
]
for filename, technologies in files_to_check:
if (project_dir / filename).exists():
tech.extend(technologies)
return list(set(tech))
# =============================================================================
# QUALITY GATE
# =============================================================================
def run_quality_gate(project_dir: Path) -> Dict[str, Any]:
"""Запускает Quality Gate тесты для проекта.
Returns:
Dict с результатами тестов:
{
"score": 0.85,
"passed": True,
"results": [...],
"decision": "KEEP"
}
"""
try:
# Импортируем QualityLoop
from quality_loop import QualityLoop
log("Запуск Quality Gate...", "INFO", project_dir)
loop = QualityLoop(project_dir)
state = loop.run(
max_iterations=2, # Quick check
threshold_a=0.6,
threshold_b=0.7
)
decision = "KEEP" if state.score >= 0.6 else "REVIEW"
result = {
"score": state.score,
"passed": state.score >= 0.6,
"phase": state.phase.value,
"iterations": state.iteration - 1,
"stop_reason": state.stop_reason,
"results": [
{
"name": r.name,
"passed": r.passed,
"score": r.score,
"duration": r.duration
}
for r in state.results
],
"decision": decision
}
log(f"Quality Gate: {decision} (score: {state.score:.2f})", "INFO", project_dir)
return result
except ImportError:
# quality_loop не доступен - возвращаем нейтральный результат
log("Quality Loop module not found, skipping...", "WARNING", project_dir)
return {
"score": 0.5,
"passed": None,
"decision": "MANUAL_REVIEW"
}
except Exception as e:
log(f"Quality Gate error: {e}", "WARNING", project_dir)
return {
"score": 0.5,
"passed": None,
"error": str(e),
"decision": "MANUAL_REVIEW"
}
# =============================================================================
# PROMPT GENERATION
# =============================================================================
def build_agent_prompt(config: ProjectConfig, iteration: int, total: int, strategy: str = "default") -> str:
"""Строит промпт для AI-агента."""
# Выбираем шаблон по стратегии
strategy_files = {
"execution": "prompt_execution.md",
"quality": "prompt_quality.md",
}
template_name = strategy_files.get(strategy, "default_prompt.md")
template_file = CONFIG_DIR / template_name
if template_file.exists():
template = template_file.read_text(encoding="utf-8")
else:
template = """# AutoResearch Experiment {iteration}/{total}
Вы — автономный исследователь, улучшающий проект "{project_name}".
## Проект
{description}
## Цели
{goals}
## Технический стек
{tech_stack}
## Задача на эксперимент {iteration}
Проведите исследование и улучшение проекта. Результаты сохраните в:
- `.autoresearch/experiments/accumulation_context.md` — полный контекст
- `.autoresearch/experiments/changes_log.md` — лог изменений
## Формат отчёта
В конце эксперимента предоставьте отчёт:
```markdown
## Experiment Report
**Number:** {iteration}
**Title:** [краткое название]
**Hypothesis:** [что тестировали]
**Files Modified:** [список]
**Changes Made:** [описание]
**Results:** [результаты]
**Notes for Next:** [заметки для следующей итерации]
>>>EXPERIMENT_COMPLETE<<<
```
## Ограничения
{constraints}
Начинайте эксперимент {iteration}.
"""
# Читаем последний эксперимент (accumulation_context.md только для человека, не для агента!)
last_experiment = ""
project_dir = config.project_dir
exp_dir = project_dir / ".autoresearch" / "experiments"
if exp_dir.exists():
last_exp_file = exp_dir / "last_experiment.md"
if last_exp_file.exists():
last_experiment = last_exp_file.read_text(encoding="utf-8")
# Заполняем переменные
cfg = config.config
context = {
"iteration": iteration,
"total": total,
"project_name": cfg.get("name", "Unknown"),
"description": cfg.get("description", "Нет описания"),
"goals": "\n".join(f"- {g}" for g in cfg.get("goals", [])) or "- Не указаны",
"completed_goals": "\n".join(f"- {g}" for g in cfg.get("completed_goals", [])) or "",
"tech_stack": ", ".join(cfg.get("tech_stack", [])) or "Не определён",
"constraints": "\n".join(f"- {c}" for c in cfg.get("constraints", [])) or "- Нет",
"agent_instructions": cfg.get("agent_instructions", ""),
}
prompt = template.format(**context)
# Добавляем контекст для агента (НЕ весь accumulation_context - он для человека!)
memory_dir = project_dir / ".claude" / "memory"
# Читаем память проекта с приоритетами (только [CRITICAL] и [IMPORTANT])
project_memory = ""
if memory_dir.exists():
lessons = read_last_entries(memory_dir / "lessons.md", 5)
patterns = read_last_entries(memory_dir / "patterns.md", 5)
architecture = read_last_entries(memory_dir / "architecture.md", 5)
if lessons or patterns or architecture:
project_memory += "\n\n## Память проекта\n\n"
if lessons:
project_memory += f"### Lessons Learned\n{lessons}\n\n"
if patterns:
project_memory += f"### Patterns Found\n{patterns}\n\n"
if architecture:
project_memory += f"### Architecture Decisions\n{architecture}\n\n"
# Добавляем ТОЛЬКО последний эксперимент (не весь лог!)
if last_experiment:
project_memory += "## Последний эксперимент\n\n"
project_memory += last_experiment + "\n\n"
# Добавляем REWORK remarks от судей (если предыдущий эксперимент получил REWORK)
if exp_dir.exists():
last_judge = None
# Find the latest judge file
judge_files = sorted(exp_dir.glob("judge_*_all.json"), key=lambda p: p.stat().st_mtime, reverse=True)
if judge_files:
try:
import json as _json_for_rework
judge_data = _json_for_rework.loads(judge_files[0].read_text(encoding="utf-8"))
if judge_data.get("consensus") == "REWORK" and judge_data.get("rework_remarks"):
last_judge = judge_data
except Exception:
pass
if last_judge:
project_memory += "## Замечания судей (REWORK)\n\n"
project_memory += "Предыдущий эксперимент получил вердикт REWORK. "
project_memory += "Судьи указали следующие проблемы, которые нужно исправить:\n"
for remark in last_judge["rework_remarks"]:
project_memory += f"- {remark}\n"
project_memory += "\n**Важно:** Учитывай эти замечания при выборе и выполнении текущего эксперимента.\n\n"
# Добавляем текущее состояние проекта (git status)
try:
result = subprocess.run(
["git", "status", "--short"],
cwd=project_dir,
capture_output=True,
text=True,
check=False
)
if result.stdout.strip():
project_memory += "## Текущее состояние проекта\n\n"
project_memory += "### Изменённые файлы (git status)\n```\n"
project_memory += result.stdout.strip()
project_memory += "\n```\n\n"
except (subprocess.SubprocessError, OSError) as e:
log(f"Git status failed: {e}", "DEBUG", project_dir)
if project_memory:
prompt += project_memory
return prompt
def parse_experiment_report(output: str, iteration: int) -> Dict[str, Any]:
"""Парсит отчет эксперимента из вывода агента.
Args:
output: Вывод Claude CLI
iteration: Номер эксперимента
Returns:
Dict с данными эксперимента
"""
import re
# Извлекаем данные из отчета
title = "Untitled"
what_done = "N/A"
files_modified = []
results = "N/A"
notes_next = "N/A"
# Ищем Title
match = re.search(r'\*\*Title:\*\*\s*(.+?)(?:\n|\*)', output)
if match:
title = match.group(1).strip()
# Ищем секции
sections = re.split(r'\n#{1,3}\s+', output)
for section in sections:
if "What Was Done" in section or "Changes Made" in section:
what_done = section.strip()[:500] # Ограничиваем размер
elif "Files Modified" in section:
# Извлекаем список файлов
for line in section.split('\n'):
if '-' in line and '.' in line:
files_modified.append(line.strip('- *').strip())
elif "Evaluation Results" in section or "Results" in section:
results = section.strip()[:500]
elif "Notes for Next" in section:
notes_next = section.strip()[:500]
return {
"number": iteration,
"title": title,
"what_done": what_done,
"files_modified": files_modified[:10], # Максимум 10 файлов
"results": results,
"notes_next": notes_next,
"date": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
def save_last_experiment_summary(project_dir: Path, experiment: Dict[str, Any]):
"""Сохраняет краткую сводку ТОЛЬКО последнего эксперимента для агента.
Этот файл перезаписывается каждой итерацией — в контекст попадает только последний!
Args:
project_dir: Директория проекта
experiment: Данные эксперимента
"""
exp_dir = project_dir / ".autoresearch" / "experiments"
last_exp_file = exp_dir / "last_experiment.md"
summary = f"""# Last Experiment Summary
**Experiment #{experiment['number']}** — {experiment.get('title', 'Untitled')}
**Date:** {experiment.get('date', '')}
## What Was Done
{experiment.get('what_done', 'N/A')}
## Files Modified
{chr(10).join(f"- {f}" for f in experiment.get('files_modified', [])) if experiment.get('files_modified') else '- None'}
## Key Results
{experiment.get('results', 'N/A')}
## For Next Iteration
{experiment.get('notes_next', 'N/A')}
"""
last_exp_file.write_text(summary, encoding="utf-8")
log(f"Saved last_experiment.md", "DEBUG", project_dir)
def save_accumulation_context(project_dir: Path, experiment: Dict[str, Any]):
"""Добавляет эксперимент в полный лог всех экспериментов.
Args:
project_dir: Директория проекта
experiment: Данные эксперимента
"""
exp_dir = project_dir / ".autoresearch" / "experiments"
context_file = exp_dir / "accumulation_context.md"
entry = f"""
## Experiment {experiment['number']} — {experiment.get('title', 'Untitled')}
**Date:** {experiment.get('date', '')}
### What Was Done
{experiment.get('what_done', 'N/A')}
### Files Modified
{chr(10).join(f"- {f}" for f in experiment.get('files_modified', [])) if experiment.get('files_modified') else '- None'}
### Results
{experiment.get('results', 'N/A')}
### Notes for Next
{experiment.get('notes_next', 'N/A')}
---
"""
if context_file.exists():
content = context_file.read_text(encoding="utf-8")
content += entry
else:
content = f"# AutoResearch Experiment Log\n\n{entry}"
context_file.write_text(content, encoding="utf-8")
log(f"Updated accumulation_context.md", "DEBUG", project_dir)
def save_changes_log(project_dir: Path, experiment: Dict[str, Any]):
"""Добавляет запись в хронологию изменений.
Args:
project_dir: Директория проекта
experiment: Данные эксперимента
"""
exp_dir = project_dir / ".autoresearch" / "experiments"
changes_log_file = exp_dir / "changes_log.md"
entry = f"""## Experiment {experiment['number']} — {experiment.get('title', 'Untitled')}
**Time:** {experiment.get('date', '')}
**Files:** {', '.join(experiment.get('files_modified', [])) if experiment.get('files_modified') else 'None'}
**What was done:**
{experiment.get('what_done', 'N/A')}
**Results:**
{experiment.get('results', 'N/A')}
"""
if changes_log_file.exists():
content = changes_log_file.read_text(encoding="utf-8")
content += entry
else:
content = f"# AutoResearch Changes Log\n\n{entry}"
changes_log_file.write_text(content, encoding="utf-8")
log(f"Updated changes_log.md", "DEBUG", project_dir)
# =============================================================================
# EXPERIMENT LOOP
# =============================================================================
def run_single_experiment(config: ProjectConfig, iteration: int, total: int, strategy: str = "default") -> Dict[str, Any]:
"""Запускает один эксперимент."""
project_dir = config.project_dir
exp_dir = project_dir / ".autoresearch" / "experiments"
exp_dir.mkdir(parents=True, exist_ok=True)
log(f"Запуск эксперимента {iteration}/{total}", "INFO", project_dir)
# Строим промпт
prompt = build_agent_prompt(config, iteration, total, strategy)
# Сохраняем промпт
prompt_file = exp_dir / f"prompt_{iteration}.md"
prompt_file.write_text(prompt, encoding="utf-8")
# Проверяем размер промпта
prompt_size = len(prompt.encode('utf-8'))
log(f"Prompt size: {prompt_size:,} bytes ({prompt_size // 1024} KB)", "DEBUG", project_dir)
# Запускаем Claude CLI
claude_cmd = get_claude_command()
output_file = exp_dir / f"output_{iteration}.md"
try:
# Parse command based on platform (see INSTALL.md Step 2)
if sys.platform == "win32" and "powershell.exe" in claude_cmd:
# Windows: Extract .ps1 path and build PowerShell command
import re
match = re.search(r'-File\s+"([^"]+)"', claude_cmd)
if match:
ps1_path = match.group(1)
cmd_args = [
"powershell.exe",
"-NoProfile",
"-ExecutionPolicy", "Bypass",
"-File", ps1_path,
"--print",
]
else:
raise ValueError("Cannot parse PowerShell command")
else:
# Unix-like (Linux, macOS): direct command
cmd_args = claude_cmd.split() + ["--print"]
env = os.environ.copy()
env['PYTHONIOENCODING'] = 'utf-8'
# CRITICAL: Отключаем CLAUDECODE чтобы избежать nested session check
# Claude CLI нельзя запускать изнутри другой сессии Claude Code
env.pop('CLAUDECODE', None)
env.pop('CLAUDE_SESSION_ID', None)
log(f"Running: {cmd_args}", "DEBUG", project_dir)
# Используем subprocess.Popen для контроля над процессом
process = subprocess.Popen(
cmd_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=project_dir,
text=True,
encoding='utf-8',
errors='replace',
env=env
)
try:
# communicate с timeout - возвращает (stdout, stderr)
stdout, stderr = process.communicate(input=prompt, timeout=7200)
if process.returncode != 0:
log(f"Claude CLI error (code {process.returncode}): {stderr}", "ERROR", project_dir)
return {"status": "error", "error": stderr}
# Логируем stderr для отладки (даже при успехе)
if stderr.strip():
log(f"Claude CLI stderr: {stderr[:500]}", "DEBUG", project_dir)
# Сохраняем вывод
output_file.write_text(stdout, encoding="utf-8")
# Проверяем маркер завершения
if ">>>EXPERIMENT_COMPLETE<<<" in stdout:
log(f"Эксперимент {iteration} завершён", "INFO", project_dir)
return {"status": "success", "output": stdout}
else:
log(f"Эксперимент {iteration} завершён без маркера", "WARNING", project_dir)
return {"status": "incomplete", "output": stdout}
except subprocess.TimeoutExpired:
# При timeout сначала убиваем процесс, потом получаем остатки вывода
process.kill()
stdout, stderr = process.communicate()
log(f"Claude CLI timeout after 2 hours!", "ERROR", project_dir)
log(f"Experiment {iteration} timed out - may be stuck on permission prompt or hanging", "ERROR", project_dir)
return {"status": "error", "error": f"Timeout after 2 hours. Claude CLI may be waiting for permission approval or stuck."}
except Exception as e:
log(f"Ошибка запуска: {e}", "ERROR", project_dir)
return {"status": "error", "error": str(e)}
finally:
# Гарантированная очистка процесса
if 'process' in locals() and process is not None:
if process.poll() is None:
try:
process.kill()
process.wait(timeout=5)
log(f"Process {process.pid} forcefully terminated", "DEBUG", project_dir)
except (OSError, ProcessLookupError):
pass
def run_autoresearch(project_dir: Path, iterations: int, timeout: int, config: Optional[ProjectConfig] = None, start_from: int = 1, max_time: Optional[int] = None, strategy: str = "default"):
"""Главный цикл AutoResearch."""
# Вычисляем конечный номер эксперимента
max_experiment_number = start_from + iterations - 1
# Засекаем время старта
start_wall = time.time()
deadline = start_wall + max_time if max_time else None
log("=" * 70, project_dir=project_dir)
log("AutoResearch - запуск", project_dir=project_dir)
log("=" * 70, project_dir=project_dir)
log(f"Проект: {project_dir}", project_dir=project_dir)
log(f"Начинаем с: Experiment {start_from}", project_dir=project_dir)
log(f"Всего итераций: {iterations}", project_dir=project_dir)
log(f"Завершить на: Experiment {max_experiment_number}", project_dir=project_dir)
log(f"Интервал: {timeout} мин", project_dir=project_dir)
if max_time:
log(f"Максимальное время: {max_time} сек ({max_time // 60} мин)", project_dir=project_dir)
log(f"Стратегия: {strategy}", project_dir=project_dir)
log("", project_dir=project_dir)
# Проверка Claude CLI
if not check_claude_cli():
log("Claude CLI не найден!", "ERROR", project_dir=project_dir)
log("Установите: npm install -g @anthropic-ai/claude-code", "INFO", project_dir=project_dir)
return 1
# Конфигурация проекта
if config is None:
config = ProjectConfig(project_dir)
if not config.is_configured():
log("Проект не настроен. Запуск интерактивной настройки...", "INFO", project_dir=project_dir)
config = run_interactive_setup(project_dir)
# Создаём backup branch
try:
branch = f"autoresearch-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
subprocess.run(
["git", "checkout", "-b", branch],
cwd=project_dir,
capture_output=True,
check=True
)
log(f"Создана ветка: {branch}", "INFO", project_dir)
except Exception as e:
log(f"Не удалось создать ветку: {e}", "WARNING", project_dir)
# Главный цикл
results = []
for i in range(start_from, max_experiment_number + 1):
# Проверяем лимит общего времени
if deadline and time.time() >= deadline:
log(f"Превышен лимит времени ({max_time} сек). Остановка.", "WARNING", project_dir=project_dir)
break
log("", project_dir=project_dir)
log(f"=" * 70, project_dir=project_dir)
log(f"Эксперимент {i}/{max_experiment_number}", project_dir=project_dir)
log("=" * 70, project_dir=project_dir)
result = run_single_experiment(config, i, max_experiment_number, strategy)
results.append(result)
# Сохраняем last_experiment.md и accumulation_context.md после успешного эксперимента
if result.get("status") in ["success", "incomplete"]:
output = result.get("output", "")
if output and ">>>EXPERIMENT_COMPLETE<<<" in output:
# Парсим отчет эксперимента
exp_data = parse_experiment_report(output, i)
# Сохраняем краткую сводку для агента (перезаписывается)
save_last_experiment_summary(project_dir, exp_data)
# Добавляем в полный лог (добавляется)
save_accumulation_context(project_dir, exp_data)
# Добавляем в хронологию изменений
save_changes_log(project_dir, exp_data)
# Пауза перед следующей итерацией
if i < max_experiment_number and timeout > 0:
log(f"Ожидание {timeout} минут до следующей итерации...", "INFO", project_dir)
log(f"Следующий эксперимент в {datetime.now().strftime('%H:%M:%S')}", "INFO", project_dir)
time.sleep(timeout * 60)
# Итоги
log("", project_dir=project_dir)
log("=" * 70, project_dir=project_dir)
log("AutoResearch завершён", project_dir=project_dir)
log("=" * 70, project_dir=project_dir)
successful = sum(1 for r in results if r.get("status") == "success")
log(f"Успешно: {successful}/{iterations}", project_dir=project_dir)