Files
samreshu_backend/AGENT_TASKS.md
2026-03-04 18:17:38 +03:00

17 KiB
Raw Permalink Blame History

Распределение задач по агентам (MVP 0)

Документ для параллельной работы нескольких агентов. Каждый агент работает в отдельной сессии Cursor (отдельное окно чата). После выполнения каждой задачи — отдельный коммит по conventional commits.

Как запустить агента

  1. Открыть новую сессию чата (новое окно Composer/Chat в Cursor)
  2. Скопировать промпт для нужного агента из раздела ниже
  3. Агент выполнит свои задачи и сделает коммиты
  4. Повторить для следующего агента

Промпты для запуска агентов

Agent A (Infrastructure):

Implement Agent A tasks from AGENT_TASKS.md. Work in branch feat/infra-core. 
Do tasks A1A9 in order. After EACH task, run: git add -A && git commit -m "<message from table>".
Use conventional commits. Do not touch schema or auth/tests/profile/llm/admin code.

Agent B (DB Schema):

Implement Agent B tasks from AGENT_TASKS.md. Work in branch feat/db-schema. 
Do tasks B1B7. After EACH task, commit with the message from the table.
Assume Agent A has created plugins. Generate migrations with npm run db:generate.

Agent C (Auth):

Implement Agent C tasks from AGENT_TASKS.md. Work in branch feat/auth. 
Merge or rebase from dev first. Do tasks C1C7, commit after each.

Agent D (Profile):

Implement Agent D tasks from AGENT_TASKS.md. Work in branch feat/profile-subscription.
Merge dev first. Do tasks D1D5, commit after each.

Agent E (Tests & Questions):

Implement Agent E tasks from AGENT_TASKS.md. Work in branch feat/tests-questions.
Requires Auth, Profile, LLM done. Do E1E5, commit after each.

Agent F (LLM):

Implement Agent F tasks from AGENT_TASKS.md. Work in branch feat/llm-service.
Do F1F5, commit after each. Export LlmService interface for QuestionService.

Agent G (Admin):

Implement Agent G tasks from AGENT_TASKS.md. Work in branch feat/admin-qa.
Do G1G4, commit after each.

Agent H (Testing):

Implement Agent H tasks from AGENT_TASKS.md. Work in branch feat/testing. 
Do H1H7, commit after each. Target ≥70% coverage on services.

Agent A2 (Progressive Login Lockout):

Implement Agent A2 task from AGENT_TASKS.md. Work in branch feat/progressive-login-lockout.
Branch from dev. Do task A2-1. Commit with the message from the table.

Agent A2-2 (Fix Login Lockout Tests):

Implement Agent A2-2 task from AGENT_TASKS.md. Work in branch fix/login-lockout-test-mock.
Branch from dev. Do task A2-2. Commit with the message from the table.
Ensure tests/integration/auth.routes.test.ts passes.

Текущее состояние репозитория

Часть работы уже выполнена одним агентом:

  • Infra (A): package.json, config, plugins (database, redis, security, rateLimit), app.ts, server.ts, utils/errors, utils/uuid, docker-compose, .env.example
  • Schema (B): все схемы в src/db/schema, drizzle.config, migrate.ts. Миграции ещё не сгенерированы (нужен npm run db:generate)

Агентам BH при старте: проверить, что уже есть, и дописать недостающее. Не дублировать сделанное. Коммитить только свои изменения.


Формат коммитов

Использовать conventional commits:

  • feat: — новый функционал
  • fix: — исправление бага
  • refactor: — рефакторинг
  • chore: — инфраструктура, зависимости, конфиг
  • test: — тесты

Примеры: feat: add auth register endpoint, chore: add database plugin, test: add auth service unit tests.


Волны запуска и зависимости

Волна 1 (старт сразу, параллельно):
  Agent A ────────────────────────────►
  Agent B ────────────────────────────►

Волна 2 (после завершения A + B):
  Agent C ────────────────────────────►
  Agent D ────────────────────────────►
  Agent F ────────────────────────────►

Волна 3 (после C, D, F):
  Agent E ────────────────────────────►
  Agent G ────────────────────────────►
  Agent H ────────────────────────────► (может стартовать частично после C)

Agent A: Infrastructure & Core Backend

Зависимости: нет (запускать первым)

Ветка: feat/infra-core (создать от main/dev)

Задачи и коммиты:

# Задача Коммит
A1 package.json, tsconfig, .nvmrc, .gitignore chore: init project with Fastify and TypeScript
A2 src/config/env.ts с Zod-валидацией chore: add env config with validation
A3 src/plugins/redis.ts feat: add Redis plugin
A4 src/plugins/database.ts feat: add database plugin with Drizzle
A5 src/plugins/security.ts (helmet + cors) feat: add security plugin
A6 src/plugins/rateLimit.ts feat: add rate limit plugin with Redis
A7 src/utils/errors.ts, src/utils/uuid.ts chore: add error utils and uuid7 helper
A8 src/app.ts — error handler, логирование feat: add Fastify app with error handler
A9 src/server.ts, docker-compose.dev.yml, .env.example chore: add server entry and dev docker compose

Итого: 9 коммитов. После завершения — PR в dev.


Agent A2: Progressive Login Lockout

Зависимости: Agent A (redis, rateLimit), Agent C (auth routes). Уже есть Auth и rateLimit.

Ветка: feat/progressive-login-lockout

Контекст: Сейчас POST /auth/login использует фиксированный лимит через @fastify/rate-limit (N попыток на 15 мин). По security.md нужен прогрессивный lockout — считаются только неудачные попытки входа, с нарастающим временем блокировки:

Неудачных попыток Блокировка
5 за 15 мин 15 минут
10 за 1 час 1 час
20 за 24 часа 24 часа

Счётчики в Redis по ключу lockout:<ip>. При успешном логине — сброс счётчиков.

Задача A2-1:

  1. Создать src/utils/loginLockout.ts — утилита для работы с Redis:

    • checkBlocked(redis, ip: string){ blocked: boolean, retryAfter?: number } — проверяет lockout:blocked:<ip>; если ключ есть и TTL > 0, возвращает { blocked: true, retryAfter }.
    • recordFailedAttempt(redis, ip: string) — INCR по ключам lockout:15m:<ip>, lockout:1h:<ip>, lockout:24h:<ip> с TTL 15m/1h/24h; при достижении порогов (5/10/20) устанавливает lockout:blocked:<ip> с соответствующим TTL.
    • clearOnSuccess(redis, ip: string) — DEL всех ключей lockout:*:<ip> и lockout:blocked:<ip>.
  2. Обновить src/plugins/rateLimit.ts — убрать login из rateLimitOptions (больше не используется для login). Остальные endpoints без изменений.

  3. Обновить src/routes/auth.ts — для POST /login:

    • Убрать config: { rateLimit: rateLimitOptions.login }.
    • Добавить preValidation: вызвать checkBlocked(app.redis, req.ip); если blockedreply.status(429).send({ error: { code: 'RATE_LIMIT_EXCEEDED', message: '...', retryAfter } }).
    • В handler: обернуть authService.login(...) в try/catch; при успехе — clearOnSuccess(app.redis, ip); при throw (например unauthorized) — recordFailedAttempt(app.redis, ip), затем rethrow.
  4. Опционально — вынести пороги (5, 10, 20) и окна в env.ts или оставить константами в loginLockout.ts (документация security.md указывает фиксированные значения).

Коммит: feat: replace fixed login rate limit with progressive lockout

Итого: 1 коммит. После — PR в dev.


Agent A2-2: Fix Login Lockout Tests (после A2)

Зависимости: Agent A2 выполнен.

Ветка: fix/login-lockout-test-mock

Проблема: Auth routes используют app.redis для checkBlocked, recordFailedAttempt, clearOnSuccess. В buildAuthTestApp Redis не подключён — тесты POST /auth/login падают с 500.

Задача A2-2:

  1. Добавить mock Redis в tests/helpers/build-test-app.ts:

    • Создать объект, реализующий минимальный интерфейс ioredis для loginLockout: ttl, setex, del, eval.
    • ttl(key) → -2 (ключ не существует) или -1/положительное значение для тестов.
    • setex, del → no-op или простая in-memory имитация.
    • eval(script, keysCount, ...keys, ...args) → вернуть [0, 0, 0] (счётчики не достигли порога).
    • app.decorate('redis', mockRedis) перед регистрацией auth routes.
  2. Обновить rateLimitOptions в buildAuthTestApp — убрать login (его больше нет в типе из rateLimit.ts).

Коммит: test: add mock Redis for auth integration tests with login lockout

Итого: 1 коммит. Проверить: npm run test -- tests/integration/auth.routes.test.ts проходит.


Agent B: Data Model & Drizzle Schema

Зависимости: Agent A (нужен database plugin). Может стартовать после A4.

Ветка: feat/db-schema

Задачи и коммиты:

# Задача Коммит
B1 src/db/schema/enums.ts feat: add Drizzle enums for schema
B2 src/db/schema/users.ts, sessions.ts, subscriptions.ts feat: add users and auth tables schema
B3 src/db/schema/tests.ts, testQuestions.ts feat: add tests and test_questions schema
B4 src/db/schema/questionBank.ts, questionCacheMeta.ts, questionReports.ts feat: add question bank schema
B5 src/db/schema/userStats.ts, auditLogs.ts, userQuestionLog.ts, verificationTokens.ts feat: add user_stats, audit_logs and verification tokens schema
B6 src/db/schema/index.ts, drizzle.config.ts, migrate.ts chore: wire schema and migrations
B7 Генерация миграций (npm run db:generate), seed скрипт chore: add initial migration and seed script

Итого: 7 коммитов. После завершения — PR в dev.


Agent C: Auth & Sessions Service

Зависимости: A, B завершены.

Ветка: feat/auth

Задачи и коммиты:

# Задача Коммит
C1 src/utils/password.ts (argon2id), src/utils/jwt.ts feat: add password hashing and JWT utils
C2 src/services/auth/auth.service.ts feat: add AuthService
C3 src/plugins/auth.ts (JWT verify, request.user) feat: add auth plugin
C4 src/routes/auth.ts — register, login, logout, refresh feat: add auth routes
C5 verify-email, forgot-password, reset-password feat: add email verification and password reset
C6 Rate limiting на auth-роуты feat: add rate limiting to auth endpoints
C7 Регистрация auth routes в app feat: register auth routes in app

Итого: 7 коммитов. После завершения — PR в dev.


Agent D: Profile & Subscription Middleware

Зависимости: A, B, C.

Ветка: feat/profile-subscription

Задачи и коммиты:

# Задача Коммит
D1 src/plugins/subscription.ts feat: add subscription middleware
D2 src/services/user/user.service.ts feat: add UserService
D3 src/routes/profile.ts — GET, PATCH, GET :username feat: add profile routes
D4 Интеграция user_stats в профиль feat: add stats to profile response
D5 Регистрация profile routes в app feat: register profile routes

Итого: 5 коммитов. После завершения — PR в dev.


Agent E: Question Bank & Tests Service

Зависимости: A, B, C, D, F (контракт LlmService).

Ветка: feat/tests-questions

Задачи и коммиты:

# Задача Коммит
E1 src/services/questions/question.service.ts feat: add QuestionService
E2 src/services/tests/tests.service.ts — создание теста, снепшот feat: add TestsService create flow
E3 tests.service — answer, finish, history feat: add test answer and finish flow
E4 src/routes/tests.ts feat: add tests routes
E5 Регистрация tests routes feat: register tests routes

Итого: 5 коммитов. После завершения — PR в dev.


Agent F: LLM Service & Fallback Logic

Зависимости: A, B.

Ветка: feat/llm-service

Задачи и коммиты:

# Задача Коммит
F1 src/services/llm/llm.service.ts — конфиг, HTTP client feat: add LlmService base
F2 generateQuestions с JSON Schema валидацией feat: add LLM question generation
F3 Retry и fallback логика feat: add LLM retry and fallback
F4 Интеграция question_cache_meta feat: log LLM metadata to question_cache_meta
F5 Экспорт интерфейса для QuestionService feat: export LlmService interface

Итого: 5 коммитов. После завершения — PR в dev.


Agent G: Admin QA for Questions

Зависимости: A, B, C, E (модель question_bank).

Ветка: feat/admin-qa

Задачи и коммиты:

# Задача Коммит
G1 src/services/admin/admin-question.service.ts feat: add AdminQuestionService
G2 src/routes/admin/questions.ts feat: add admin questions routes
G3 audit_logs при approve/reject/edit feat: add audit logging to admin actions
G4 Регистрация admin routes feat: register admin routes

Итого: 4 коммита. После завершения — PR в dev.


Agent H: Tests & Quality

Зависимости: Может стартовать после C (auth), наращивать по мере готовности других агентов.

Ветка: feat/testing

Задачи и коммиты:

# Задача Коммит
H1 Vitest config, test-utils test: add Vitest config and test utils
H2 AuthService unit tests test: add auth service tests
H3 Auth routes integration tests test: add auth routes integration tests
H4 TestsService и QuestionService tests test: add tests and questions service tests
H5 LlmService unit tests (с моком) test: add LLM service tests
H6 Admin routes integration tests test: add admin routes tests
H7 Coverage ≥70%, npm script test: add coverage config

Итого: 7 коммитов. После завершения — PR в dev.


Рекомендуемый порядок запуска

  1. Сразу: Agent A и Agent B (в двух отдельных сессиях Cursor)
  2. После A и B: Agent C, D, F (три сессии)
  3. После C, D, F: Agent E, G (две сессии)
  4. Параллельно волне 23: Agent H (тесты по мере готовности API)

Чеклист для каждого агента

Перед каждым коммитом:

  • npm run typecheck проходит
  • Сообщение коммита по conventional commits
  • Нет console.log, только logger
  • Нет any без необходимости

После завершения всех задач агента:

  • Создать PR в dev
  • Проверить, что не сломаны существующие тесты (если есть)