File size: 5,998 Bytes
0b2210a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Initialization Engine - пассивная инициализация проекта.
Только читает и валидирует файлы, НЕ вызывает модели.
"""

import json
import yaml
from pathlib import Path
from typing import Dict, Optional, Tuple, List
from datetime import datetime
import logging

logger = logging.getLogger(__name__)

class ProjectInitializationError(Exception):
    """Ошибка инициализации проекта."""
    pass

async def initialize_project(project_path: str) -> Dict:
    """
    Пассивная инициализация проекта.
    
    Args:
        project_path: Путь к директории проекта
        
    Returns:
        Информация об инициализированном проекте
        
    Raises:
        ProjectInitializationError: Если проект невозможно инициализировать
    """
    project_dir = Path(project_path)
    
    # 1. Проверка существования директории проекта
    if not project_dir.exists() or not project_dir.is_dir():
        raise ProjectInitializationError(f"Директория проекта не существует: {project_path}")
    
    required_files = [
        project_dir / "project_info.json",
        project_dir / "config" / "roles_current.json",
        project_dir / "prompts" / "ceo_system.txt",
        project_dir / "prompts" / "chief_system.txt",
        project_dir / "prompts" / "doctor_system.txt",
    ]
    
    # 2. Проверка обязательных файлов
    missing_files = []
    for file_path in required_files:
        if not file_path.exists():
            missing_files.append(str(file_path.relative_to(project_dir)))
    
    if missing_files:
        raise ProjectInitializationError(
            f"Отсутствуют обязательные файлы: {', '.join(missing_files)}"
        )
    
    try:
        # 3. Чтение и валидация project_info.json
        with open(project_dir / "project_info.json", 'r', encoding='utf-8') as f:
            project_info = json.load(f)
        
        # 4. Чтение и базовая валидация roles_current.json
        with open(project_dir / "config" / "roles_current.json", 'r', encoding='utf-8') as f:
            roles_config = json.load(f)
        
        # 5. Проверка промптов (только что они не пустые)
        prompts_dir = project_dir / "prompts"
        prompt_files = list(prompts_dir.glob("*.txt")) + list(prompts_dir.glob("*.md"))
        
        empty_prompts = []
        for prompt_file in prompt_files:
            if prompt_file.stat().st_size == 0:
                empty_prompts.append(prompt_file.name)
        
        if empty_prompts:
            logger.warning(f"Пустые промпты: {', '.join(empty_prompts)}")
        
        # 6. Создание папок для логов (если не существуют)
        logs_dir = project_dir / "logs"
        for subdir in ["sessions", "reflections", "medical", "battles"]:
            (logs_dir / subdir).mkdir(parents=True, exist_ok=True)
        
        # 7. Сбор информации о проекте
        project_data = {
            "project_path": str(project_dir.absolute()),
            "project_id": project_info.get("project_id", "unknown"),
            "name": project_info.get("name", "Unnamed Project"),
            "status": "READY_FOR_EXAMINATION",
            "config_files_ok": True,
            "prompts_ok": len(empty_prompts) == 0,
            "empty_prompts": empty_prompts,
            "roles_configured": list(roles_config.get("departments", {}).keys()) if isinstance(roles_config, dict) else [],
            "initialized_at": datetime.now().isoformat()
        }
        
        logger.info(f"Проект инициализирован: {project_data['name']} ({project_data['project_id']})")
        
        return project_data
        
    except json.JSONDecodeError as e:
        raise ProjectInitializationError(f"Ошибка JSON в конфигурационных файлах: {e}")
    except IOError as e:
        raise ProjectInitializationError(f"Ошибка чтения файлов проекта: {e}")
    except Exception as e:
        raise ProjectInitializationError(f"Неожиданная ошибка при инициализации: {e}")

async def validate_project_structure(project_path: str) -> Tuple[bool, List[str]]:
    """
    Валидация структуры проекта.
    
    Args:
        project_path: Путь к проекту
        
    Returns:
        (is_valid, list_of_issues)
    """
    project_dir = Path(project_path)
    issues = []
    
    if not project_dir.exists():
        return False, ["Директория проекта не существует"]
    
    # Проверка обязательной структуры
    required_dirs = ["config", "prompts", "data/input", "logs"]
    for dir_path in required_dirs:
        full_path = project_dir / dir_path
        if not full_path.exists():
            issues.append(f"Отсутствует директория: {dir_path}")
    
    # Проверка обязательных файлов
    required_files = {
        "project_info.json": "Основной файл проекта",
        "config/roles_current.json": "Конфигурация ролей",
        "prompts/ceo_system.txt": "Промпт СЕО",
        "prompts/chief_system.txt": "Промпт Шефа",
        "prompts/doctor_system.txt": "Промпт Доктора"
    }
    
    for file_path, description in required_files.items():
        full_path = project_dir / file_path
        if not full_path.exists():
            issues.append(f"Отсутствует файл: {file_path} ({description})")
    
    return len(issues) == 0, issues