Перейти к содержимому
arckep.ru — все нейросети в одном месте без VPN Перейти
>AISTUDY_
Поддержать
AUTHORСвежий выпуск №024 → Куда внедрять агентов: фронт или тыл

Модуль 2.6 · Урок 4

Урок 4: GEMINI.md и .cursorrules

Практика
2.6 / Урок 4 из 5

Чему вы научитесь

  • Как писать GEMINI.md для Google Gemini CLI
  • Структуру и особенности .cursorrules для Cursor IDE
  • Различия между всеми форматами документации
  • Стратегию выбора нужного формата для вашего проекта

GEMINI.md — инструкции для Google Gemini

GEMINI.md — аналог CLAUDE.md, но оптимизирован для Google Gemini CLI.

Формат: Markdown
Размер: 200-300 строк
Расположение: корень проекта
Поддержка: Google Gemini CLI
Структура: похожа на CLAUDE.md

Полный пример GEMINI.md для Python проекта

# GEMINI.md

## Project Overview

REST API for task management system with real-time collaboration.

## Technology Stack

- **Backend:** Python 3.11+, FastAPI 0.104
- **Database:** PostgreSQL 15, SQLAlchemy
- **Caching:** Redis
- **Testing:** pytest, pytest-asyncio
- **Package Manager:** pip + poetry

## Development Standards

### Code Organization

app/ ├── api/ # API routes ├── models/ # SQLAlchemy models ├── schemas/ # Pydantic schemas ├── services/ # Business logic ├── middleware/ # FastAPI middleware ├── utils/ # Utilities ├── tests/ ├── main.py # App entry point └── config.py # Configuration


### Code Style
- Language: Python 3.11+
- Formatter: Black (88 chars)
- Linter: pylint
- Type hints: required (mypy strict)
- Docstrings: Google format

### Naming Conventions
- Functions/variables: snake_case
- Classes: PascalCase
- API endpoints: /api/v1/lowercase-with-dashes
- Database models: plural, snake_case (e.g., users, tasks)
- Constants: UPPER_SNAKE_CASE

## Commands

```bash
# Development
poetry run uvicorn app.main:app --reload

# Testing
poetry run pytest                # All tests
poetry run pytest --cov=app      # With coverage
poetry run pytest tests/test_api.py  # Specific file

# Code Quality
poetry run black .               # Format
poetry run pylint app/           # Lint
poetry run mypy app/             # Type check

# Database
poetry run alembic upgrade head  # Migrations
poetry run python -m app.seed    # Seed data

Guidelines

DO:

[+] Use async/await (FastAPI is async-first) [+] Validate input with Pydantic models [+] Use dependency injection (FastAPI Depends) [+] Add type hints to all functions [+] Handle exceptions explicitly [+] Log important operations

DON’T:

[-] Don’t use synchronous code in FastAPI handlers [-] Don’t skip input validation [-] Don’t hardcode configuration [-] Don’t log sensitive data [-] Don’t make blocking I/O calls [-] Don’t commit .env files

Examples

Good API Endpoint

from fastapi import APIRouter, HTTPException, Depends

router = APIRouter(prefix="/tasks", tags=["tasks"])

@router.get("/{task_id}")
async def get_task(
    task_id: str,
    session: AsyncSession = Depends(get_db)
) -> TaskResponse:
    """Retrieve a task by ID."""
    try:
        task = await service.get_task(session, task_id)
        if not task:
            raise HTTPException(status_code=404, detail="Not found")
        return TaskResponse.from_orm(task)
    except Exception as e:
        logger.error(f"Failed to get task: {e}")
        raise HTTPException(status_code=500, detail="Internal error")

Good Service Function

async def update_task(
    session: AsyncSession,
    task_id: str,
    data: TaskUpdate
) -> Optional[Task]:
    """Update task with validation."""
    task = await session.get(Task, task_id)
    if not task:
        return None

    for key, value in data.dict(exclude_unset=True).items():
        setattr(task, key, value)

    await session.commit()
    await session.refresh(task)
    return task

## Project Rules (.cursor/rules/*.mdc) — актуальный формат для Cursor IDE

<Callout type="warning" title=".cursorrules больше не документируется">
Cursor перешёл на **Project Rules** в папке `.cursor/rules/` (файлы `.md` или `.mdc`). `.mdc`-файлы поддерживают frontmatter с полями `description`, `globs` и `alwaysApply` для управления применением правил (glob-паттерны и `alwaysApply: true`). Файл `.cursorrules` больше не рекомендуется и не документируется.
</Callout>

**.cursorrules** (устаревший) / **Project Rules** (актуальный) — специализированный формат для Cursor IDE.

Актуальный формат: .cursor/rules/*.mdc (с glob паттернами) Устаревший формат: .cursorrules (корень проекта) Размер: 100-300 строк на файл правил Поддержка: Cursor IDE только Иерархия: Да (через glob-паттерны в .mdc файлах)


### Полный пример .cursorrules для fullstack проекта

Cursor Rules for TaskApp

Project Type

  • Fullstack web application
  • Frontend: Next.js 14, React 18, TypeScript
  • Backend: Express API
  • Database: PostgreSQL with Prisma
  • Styling: Tailwind CSS
  • Package Manager: npm

Frontend Rules

Components & Styling

  • Use functional components with hooks only
  • Use TypeScript strictly (no any)
  • Styling: Tailwind CSS only (no inline styles)
  • File naming: PascalCase (e.g., UserCard.tsx)
  • Component organization: keep focused, <300 lines

State & Data Fetching

  • Use React hooks (useState, useContext)
  • Global state: React Context or Zustand
  • Data fetching: SWR or React Query (with caching)
  • Always handle errors and loading states

File Structure

src/
  components/     # React components
  pages/          # Page components
  hooks/          # Custom hooks
  utils/          # Utility functions
  types/          # TypeScript types
  styles/         # Global styles only
  __tests__/      # Tests

TypeScript Rules

  • Enable strict mode
  • Add types to all parameters and returns
  • No any types (use unknown if needed)
  • Create types for API responses

Example:

interface User {
  id: string;
  email: string;
  name: string;
}

export async function fetchUser(id: string): Promise<User> {
  // implementation
}

Backend Rules

Express API

  • Use TypeScript for all code
  • Organize routes by feature
  • Use middleware for cross-cutting concerns
  • Return JSON with consistent structure
  • Always handle errors and return proper status codes

API Response Format

Always return:

{
  "success": true,
  "data": {...},
  "error": null
}

Or on error:

{
  "success": false,
  "data": null,
  "error": "Error message"
}

Database (Prisma)

  • Define models in schema.prisma
  • Use migrations: npx prisma migrate dev
  • Generate types: npx prisma generate
  • Query with Prisma client (type-safe)

Testing

  • Framework: Jest
  • Write tests for critical paths
  • Mock external services
  • Place tests next to source (.test.ts)

Code Quality

Do’s

  • [+] Write tests for critical functionality
  • [+] Use TypeScript strictly
  • [+] Handle errors explicitly
  • [+] Use environment variables for config
  • [+] Keep API responses consistent
  • [+] Use async/await
  • [+] Comment complex code

Don’ts

  • [-] Don’t hardcode values
  • [-] Don’t use console.log in production
  • [-] Don’t commit secrets or .env
  • [-] Don’t skip error handling
  • [-] Don’t write logic in components
  • [-] Don’t use relative imports (use absolute: @/)
  • [-] Don’t modify database directly

Commands Reference

npm run dev # Start dev servers npm test # Run tests npm run build # Production build npm run lint # Check code npm run format # Format code


## Сравнительная таблица всех форматов

| Параметр | AGENTS.md | CLAUDE.md | GEMINI.md | .cursor/rules/*.mdc |
|---|---|---|---|---|
| **Стандарт** | Agentic AI Foundation (Linux Foundation) | Anthropic | Google | Cursor |
| **Инструменты** | Все CLI (60,000+ проектов) | Claude Code | Gemini CLI | Cursor IDE |
| **Формат** | Markdown | Markdown | Markdown | MDC (Markdown+meta) |
| **Размер** | 300-500 | 200-300 | 200-300 | 100-300 на файл |
| **Структура** | Рекомендуемая | Гибкая | Рекомендуемая | Свободная с glob |
| **Иерархия** | Да | Да | Да | Да (glob-паттерны) |
| **Примеры** | Много | Несколько | Несколько | Опционально |
| **Обновление** | Редко | Часто | Средне | Часто |

## Когда использовать какой файл?

```mermaid
graph TD
    A["Выбирай инструменты<br/>для разработки"] --> B{Используешь<br/>Cursor IDE?}

    B -->|ДА| C["[+] Project Rules<br/>(.cursor/rules/)"]

    B -->|НЕТ| D{Используешь<br/>Claude Code?}

    D -->|ДА| E["[+] CLAUDE.md"]

    D -->|НЕТ| F{Используешь<br/>Gemini CLI?}

    F -->|ДА| G["[+] GEMINI.md"]

    F -->|НЕТ| H["[+] AGENTS.md<br/>для всех"]

    style C fill:#fff9c4
    style E fill:#c8e6c9
    style G fill:#b3e5fc
    style H fill:#f0f4c3

Практика: тройная документация

Если используешь несколько инструментов:

project/
├── AGENTS.md        # Основная документация (для всех)
├── CLAUDE.md        # Дополнение для Claude Code
├── GEMINI.md        # Дополнение для Gemini CLI
├── .cursor/rules/   # Для Cursor IDE (Project Rules)

Как избежать дублирования:

# CLAUDE.md
See AGENTS.md for base documentation.
This file adds Claude-specific rules only.

[Claude-specific rules, ~100-150 строк]

Ключевые выводы

  1. GEMINI.md — аналог CLAUDE.md для Google Gemini, структура похожа.

  2. Project Rules (.cursor/rules/*.mdc) — актуальный формат для Cursor IDE. Файл .cursorrules больше не документируется — используй новый формат.

  3. Сравнительная таблица помогает выбрать: начни с AGENTS.md, добавь специфичные файлы для используемых инструментов.

  4. Один файл для всех: AGENTS.md может быть основой, остальное — дополнение.

  5. Не усложняй: даже AGENTS.md + CLAUDE.md лучше, чем все четыре файла с дублированием.

Следующий урок

Урок 5: Шаблоны для типовых проектов

Получишь 4 готовых шаблона для копирования и адаптации!

Мы размещаем рекламу, так как это позволяет нам готовить для вас свежие материалы и покрывать наши расходы. Рекламодателей выбираем адекватных.

Скачать урок

Есть идея или нашли ошибку?

// Обсуждение

Можно писать анонимно. Укажите email, чтобы получать уведомления об ответах.