diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ea05dbd --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,263 @@ +# AGENTS.md + +## Назначение проекта + +Проект представляет собой модульную платформу, к которой могут подключаться независимые функциональные модули. + +Платформа и модули должны иметь возможность поставляться: + +- отдельно; +- в составе пакетов; +- в произвольных комбинациях. + +--- + +# Основные принципы архитектуры + +## 1. Платформа не зависит от модулей + +Запрещено: + +```python +from request_module import RequestService +``` + +Разрешено: + +```python +module = registry.get("request") +module.install() +module.start() +``` + +--- + +## 2. Модули не должны быть жёстко связаны друг с другом + +Запрещено: + +```python +crm.create_customer() +warehouse.reserve_goods() +``` + +Предпочтительно: + +```python +event_bus.publish( + "customer.created", + payload +) +``` + +--- + +## 3. Бизнес-логика не должна находиться в ядре платформы + +Ядро платформы отвечает только за: + +- авторизацию; +- права доступа; +- реестр модулей; +- журналирование; +- аудит; +- маршрутизацию; +- события; +- уведомления. + +--- + +## Структура репозитория + +```text +platform-project/ + +├── platform/ +│ ├── backend/ +│ ├── frontend/ +│ └── frontend-user/ +│ +├── modules/ +│ ├── request-module/ +│ ├── crm-module/ +│ └── ... +│ +└── dev-doc/ +``` + +--- + +# Документация + +Вся документация хранится в каталоге: + +```text +/dev-doc/ +``` + +Структура: + +```text +dev-doc/ + +├── technical_task_001.txt +├── technical_task_002.txt +├── technical_task_003.txt +│ +├── implementation_report_001.md +├── implementation_report_002.md +├── implementation_report_003.md +│ +├── ADR/ +├── architecture/ +└── roadmap.md +``` + +--- + +# Технические задания + +Каждое техническое задание должно находиться в файле: + +```text +dev-doc/technical_task_XXX.txt +``` + +Например: + +```text +dev-doc/technical_task_001.txt +dev-doc/technical_task_002.txt +``` + +--- + +# Отчёт исполнителя + +После выполнения задачи исполнитель обязан создать файл: + +```text +dev-doc/implementation_report_XXX.md +``` + +Номер отчёта обязан совпадать с номером технического задания. + +Например: + +```text +technical_task_005.txt +implementation_report_005.md +``` + +--- + +# Обязательная структура отчёта + +## Общая информация + +- номер задачи; +- дата выполнения; +- исполнитель; +- ветка; +- коммит. + +--- + +## Выполненные работы + +Список реализованных функций. + +--- + +## Изменённые файлы + +Полный список изменённых файлов. + +--- + +## Новые файлы + +Полный список новых файлов и каталогов. + +--- + +## Архитектурные решения + +Описание принятых решений. + +--- + +## Технический долг + +Список известных ограничений. + +--- + +## Риски + +Потенциальные проблемы. + +--- + +## Проверка + +Команды для проверки результата. + +Например: + +```bash +pytest + +uvicorn app.main:app --reload +``` + +--- + +## Критерии завершения задачи + +Задача считается выполненной только в том случае, если: + +- код реализован; +- тесты проходят; +- создан implementation_report; +- обновлена документация; +- отсутствуют критические ошибки. + +--- + +# Правила работы агента + +Агент обязан: + +1. Изучить техническое задание. +2. Изучить предыдущий отчёт. +3. Не изменять бизнес-логику без отдельного указания. +4. Не изменять структуру базы данных без отдельного указания. +5. Не удалять существующий функционал. +6. Документировать архитектурные решения. +7. Создать implementation_report. + +--- + +# Запрещено + +Запрещается: + +- менять API без ТЗ; +- менять структуру БД без ТЗ; +- удалять существующие функции; +- игнорировать технический долг; +- завершать задачу без отчёта. + +--- + +# Приоритет документов + +Приоритет документов следующий: + +1. AGENTS.md +2. technical_task_XXX.txt +3. implementation_report_XXX.md +4. комментарии в коде + +При конфликте документов приоритет имеет документ с более высоким уровнем. \ No newline at end of file diff --git a/modular.patch b/modular.patch new file mode 100644 index 0000000..af0616f Binary files /dev/null and b/modular.patch differ diff --git a/modules/request-module/manifest.json b/modules/request-module/manifest.json new file mode 100644 index 0000000..3e574b0 --- /dev/null +++ b/modules/request-module/manifest.json @@ -0,0 +1,8 @@ +{ + "id": "request", + "name": "Request Management", + "version": "1.0.0", + "author": "Atlas-R", + "license_required": false, + "description": "Модуль управления заявками" +} diff --git a/modules/request-module/module.py b/modules/request-module/module.py index 4ab51ba..b6b25e0 100644 --- a/modules/request-module/module.py +++ b/modules/request-module/module.py @@ -1,6 +1,7 @@ """Request Management Module.""" -from typing import List +from pathlib import Path +from typing import List, Optional from fastapi import APIRouter from app.core.sdk.module import BaseModule @@ -18,7 +19,10 @@ class RequestModule(BaseModule): version = "1.0.0" description = "Модуль управления заявками" - def routes(self) -> List[APIRouter]: + def __init__(self): + self._module_dir = Path(__file__).parent + + def routers(self) -> List[APIRouter]: """Return API routers for the request module. Currently returns empty list - routes will be added @@ -34,6 +38,16 @@ class RequestModule(BaseModule): "request.delete", ] + def static_path(self) -> Optional[Path]: + """Return path to static files directory.""" + static = self._module_dir / "static" + return static if static.exists() else None + + def templates_path(self) -> Optional[Path]: + """Return path to templates directory.""" + templates = self._module_dir / "templates" + return templates if templates.exists() else None + async def startup(self) -> None: """Initialize request module resources.""" pass diff --git a/platform/backend/app/api/v1/platform_modules.py b/platform/backend/app/api/v1/platform_modules.py index f9f8d05..4b43b43 100644 --- a/platform/backend/app/api/v1/platform_modules.py +++ b/platform/backend/app/api/v1/platform_modules.py @@ -12,7 +12,7 @@ async def list_platform_modules(): Returns: List of module metadata including id, name, version, description, - and declared permissions. + enabled status, router count, and declared permissions. """ registry = get_module_registry() modules = registry.all() @@ -23,6 +23,8 @@ async def list_platform_modules(): "name": m.name, "version": m.version, "description": m.description, + "enabled": m.enabled, + "routers": len(m.routers()), "permissions": m.permissions(), } for m in modules diff --git a/platform/backend/app/core/module_loader.py b/platform/backend/app/core/module_loader.py index b4e1137..57d0a8e 100644 --- a/platform/backend/app/core/module_loader.py +++ b/platform/backend/app/core/module_loader.py @@ -2,9 +2,10 @@ import importlib.util import inspect +import json import sys from pathlib import Path -from typing import List +from typing import List, Optional from app.core.sdk.module import BaseModule from app.core.module_registry import get_module_registry, ModuleAlreadyRegisteredError @@ -41,18 +42,43 @@ def _find_module_classes(module_path: Path) -> List[type]: return classes +def _read_manifest(module_dir: Path) -> Optional[dict]: + """Read manifest.json from a module directory. + + Args: + module_dir: Path to the module directory. + + Returns: + Parsed manifest dict, or None if not found/invalid. + """ + manifest_path = module_dir / "manifest.json" + if not manifest_path.exists(): + return None + + try: + with open(manifest_path, "r", encoding="utf-8") as f: + return json.load(f) + except Exception: + return None + + def discover_modules(modules_dir: Path) -> List[BaseModule]: """Discover and instantiate modules from a directory. Scans the given directory for subdirectories containing module.py files. Each module.py should contain a class that extends BaseModule. + If a manifest.json exists in the module directory, its metadata will + be used to override the module's class attributes. + Directory structure: modules/ ├── request-module/ - │ └── module.py - ├── crm-module/ - │ └── module.py + │ ├── module.py + │ ├── manifest.json + │ ├── static/ + │ ├── templates/ + │ └── migrations/ └── ... Args: @@ -74,10 +100,28 @@ def discover_modules(modules_dir: Path) -> List[BaseModule]: if not module_file.exists(): continue + # Read manifest if available + manifest = _read_manifest(subdir) + classes = _find_module_classes(module_file) for cls in classes: try: instance = cls() + + # Apply manifest metadata + if manifest: + if "id" in manifest and manifest["id"]: + instance.id = manifest["id"] + if "name" in manifest and manifest["name"]: + instance.name = manifest["name"] + if "version" in manifest and manifest["version"]: + instance.version = manifest["version"] + if "description" in manifest and manifest["description"]: + instance.description = manifest["description"] + + # Set module directory for static/templates + instance._module_dir = subdir + discovered.append(instance) except Exception: pass # Skip modules that fail to instantiate diff --git a/platform/backend/app/core/sdk/module.py b/platform/backend/app/core/sdk/module.py index f36d0bb..ae86371 100644 --- a/platform/backend/app/core/sdk/module.py +++ b/platform/backend/app/core/sdk/module.py @@ -1,6 +1,7 @@ """Base module class for platform modules.""" from abc import ABC, abstractmethod +from pathlib import Path from typing import List, Optional from fastapi import APIRouter @@ -16,17 +17,22 @@ class BaseModule(ABC): name: Human-readable display name version: Semantic version string description: Brief description of the module + enabled: Whether the module is enabled """ id: str name: str version: str description: str = "" + enabled: bool = True - def routes(self) -> List[APIRouter]: - """Return FastAPI routers to be mounted by the platform. + def routers(self) -> List[APIRouter]: + """Return FastAPI routers to be auto-mounted by the platform. Override this method to expose API endpoints through the platform. + All routers returned here will be automatically included in the + FastAPI application without manual registration in main.py. + Default implementation returns an empty list. Returns: @@ -47,6 +53,32 @@ class BaseModule(ABC): """ return [] + def static_path(self) -> Optional[Path]: + """Return path to the module's static files directory. + + Override this method to serve static files (CSS, JS, images) + through the platform. The platform will mount this directory + at /modules/{module_id}/static + + Default implementation returns None. + + Returns: + Path to static directory, or None if not applicable. + """ + return None + + def templates_path(self) -> Optional[Path]: + """Return path to the module's templates directory. + + Override this method to serve HTML templates through the platform. + + Default implementation returns None. + + Returns: + Path to templates directory, or None if not applicable. + """ + return None + async def startup(self) -> None: """Lifecycle hook called when the platform starts. diff --git a/platform/backend/app/main.py b/platform/backend/app/main.py index 5de252e..5d3ad42 100644 --- a/platform/backend/app/main.py +++ b/platform/backend/app/main.py @@ -1,13 +1,16 @@ """Platform - Main Application.""" +from pathlib import Path from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse +from fastapi.staticfiles import StaticFiles from app.settings import get_settings from app.core.database import init_db from app.api.v1 import auth, users, roles, modules, health from app.api.v1 import platform_modules from app.core.module_loader import load_modules, startup_modules, shutdown_modules +from app.core.module_registry import get_module_registry from app.core.logging import logger app = FastAPI( @@ -27,7 +30,7 @@ app.add_middleware( allow_headers=["*"], ) -# Routes +# Platform Routes app.include_router(health.router, prefix="/api/v1") app.include_router(auth.router, prefix="/api/v1") app.include_router(users.router, prefix="/api/v1") @@ -47,6 +50,21 @@ async def startup(): except Exception as e: logger.error(f"Module loading error: {e}") + # Auto-connect module routers and static files + registry = get_module_registry() + for module in registry.all(): + # Mount routers + for router in module.routers(): + app.include_router(router) + logger.info(f"Mounted router from module '{module.id}'") + + # Mount static files + static = module.static_path() + if static and Path(static).exists(): + mount_path = f"/modules/{module.id}/static" + app.mount(mount_path, StaticFiles(directory=str(static)), name=f"{module.id}-static") + logger.info(f"Mounted static for module '{module.id}' at {mount_path}") + # Call module startup hooks try: await startup_modules() @@ -56,7 +74,6 @@ async def startup(): @app.on_event("shutdown") async def shutdown(): - # Call module shutdown hooks try: await shutdown_modules() except Exception as e: