Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FEATURE (guildlines): Update project guildlines docs

Rostislav Dugin12958e688f11
diff --git a/AGENTS.md b/AGENTS.md
deleted file mode 100644
index 656d9a9b..00000000
--- a/AGENTS.md
+++ /dev/null
@@ -1,1580 +0,0 @@
-# Agent Rules and Guidelines
-
-This document contains all coding standards, conventions and best practices recommended for the TgTaps project.
-This is NOT a strict set of rules, but a set of recommendations to help you write better code.
-
----
-
-## Table of Contents
-
-- [Engineering philosophy](#engineering-philosophy)
-- [Backend guidelines](#backend-guidelines)
- - [Boolean naming](#boolean-naming)
- - [Add reasonable new lines between logical statements](#add-reasonable-new-lines-between-logical-statements)
- - [Comments](#comments)
- - [Controllers](#controllers)
- - [Dependency injection (DI)](#dependency-injection-di)
- - [Migrations](#migrations)
- - [Refactoring](#refactoring)
- - [Testing](#testing)
- - [Time handling](#time-handling)
- - [Logging](#logging)
- - [CRUD examples](#crud-examples)
- - [Modern Go](#modern-go)
-- [Frontend guidelines](#frontend-guidelines)
- - [React component structure](#react-component-structure)
-
----
-
-## Engineering philosophy
-
-**Think like a skeptical senior engineer and code reviewer. Don't just do what was asked—also think about what should have been asked.**
-
-⚠️ **Balance vigilance with pragmatism:** Catch real issues, not theoretical ones. Don't let perfect be the enemy of good.
-
-### Task context assessment:
-
-**First, assess the task scope:**
-
-- **Trivial** (typos, formatting, simple field adds): Apply directly with minimal analysis
-- **Standard** (CRUD, typical features): Brief assumption check, proceed
-- **Complex** (architecture, security, performance-critical): Full analysis required
-- **Unclear** (ambiguous requirements): Always clarify assumptions first
-
-### For non-trivial tasks:
-
-1. **Restate the objective and list assumptions** (explicit + implicit)
- - If any assumption is shaky, call it out clearly
- - Distinguish between what's specified and what you're inferring
-
-2. **Propose appropriate solutions:**
- - For complex tasks: 2–3 viable approaches (including a simpler baseline)
- - Recommend one with clear tradeoffs
- - Consider: complexity, maintainability, performance, future extensibility
-
-3. **Identify risks proactively:**
- - Edge cases and boundary conditions
- - Security/privacy pitfalls
- - Performance risks and scalability concerns
- - Operational concerns (deployment, observability, rollback, monitoring)
-
-4. **Handle ambiguity:**
- - If requirements are ambiguous, make a reasonable default and proceed
- - Clearly label your assumptions
- - Document what would change under alternative assumptions
-
-5. **Deliver quality:**
- - Provide a solution that is correct, testable, and maintainable
- - Include minimal tests or validation steps
- - Follow project testing philosophy: prefer controller tests over unit tests
- - Follow all project guidelines from this document
-
-6. **Self-review before finalizing:**
- - Ask: "What could go wrong?"
- - Patch the answer accordingly
- - Verify edge cases are handled
-
-7. **Fix the reason, not the symptom:**
- - If you find a bug or issue, ask "Why did this happen?" and fix the root cause
- - Avoid quick fixes that don't address underlying problems
-
-### Application guidelines:
-
-**Scale your response to the task:**
-
-- **Trivial changes:** Steps 5-6 only (deliver quality + self-review)
-- **Standard features:** Steps 1, 5-6 (restate + deliver + review)
-- **Complex/risky changes:** All steps 1-6
-- **Ambiguous requests:** Steps 1, 4 mandatory
-
-**Be proportionally thorough—brief for simple tasks, comprehensive for risky ones. Avoid analysis paralysis.**
-
----
-
-## Backend guidelines
-
-### Naming
-
-Variables and functions naming are the most important part of code readability. Always choose descriptive and meaningful names that clearly indicate the purpose and intent of the code.
-
-Avoid abbreviations, unless they are widely accepted and unambiguous (e.g., `ID`, `URL`, `HTTP`). Use consistent naming conventions across the codebase.
-
-Do not use one-two letters. For example:
-
-Bad:
-
-```
- u := users.getUser()
-
- pr, pw := io.Pipe()
-
- r := bufio.NewReader(pr)
-```
-
-Good:
-
-```
- user := users.GetUser()
-
- pipeReader, pipeWriter := io.Pipe()
-
- bufferedReader := bufio.NewReader(pipeReader)
-```
-
-Exclusion: widely used variables like "db", "ctx", "req", "res", etc.
-
-### Boolean naming
-
-**Always prefix boolean variables with verbs like `is`, `has`, `was`, `should`, `can`, etc.**
-
-This makes the code more readable and clearly indicates that the variable represents a true/false state.
-
-#### Good examples:
-
-```go
-type User struct {
- IsActive bool
- IsVerified bool
- HasAccess bool
- WasNotified bool
-}
-
-type BackupConfig struct {
- IsEnabled bool
- ShouldCompress bool
- CanRetry bool
-}
-
-// Variables
-isInProgress := true
-wasCompleted := false
-hasPermission := checkPermissions()
-```
-
-#### Bad examples:
-
-```go
-type User struct {
- Active bool // Should be: IsActive
- Verified bool // Should be: IsVerified
- Access bool // Should be: HasAccess
-}
-
-type BackupConfig struct {
- Enabled bool // Should be: IsEnabled
- Compress bool // Should be: ShouldCompress
- Retry bool // Should be: CanRetry
-}
-
-// Variables
-inProgress := true // Should be: isInProgress
-completed := false // Should be: wasCompleted
-permission := true // Should be: hasPermission
-```
-
-#### Common boolean prefixes:
-
-- **is** - current state (IsActive, IsValid, IsEnabled)
-- **has** - possession or presence (HasAccess, HasPermission, HasError)
-- **was** - past state (WasCompleted, WasNotified, WasDeleted)
-- **should** - intention or recommendation (ShouldRetry, ShouldCompress)
-- **can** - capability or permission (CanRetry, CanDelete, CanEdit)
-- **will** - future state (WillExpire, WillRetry)
-
----
-
-### Add reasonable new lines between logical statements
-
-**Add blank lines between logical blocks to improve code readability.**
-
-Separate different logical operations within a function with blank lines. This makes the code flow clearer and helps identify distinct steps in the logic.
-
-#### Guidelines:
-
-- Add blank line before final `return` statement
-- Add blank line after variable declarations before using them
-- Add blank line between error handling and subsequent logic
-- Add blank line between different logical operations
-
-#### Bad example (without spacing):
-
-```go
-func (t *Task) BeforeSave(tx *gorm.DB) error {
- if len(t.Messages) > 0 {
- messagesBytes, err := json.Marshal(t.Messages)
- if err != nil {
- return err
- }
- t.MessagesJSON = string(messagesBytes)
- }
- return nil
-}
-
-func (t *Task) AfterFind(tx *gorm.DB) error {
- if t.MessagesJSON != "" {
- var messages []onewin_dto.TaskCompletionMessage
- if err := json.Unmarshal([]byte(t.MessagesJSON), &messages); err != nil {
- return err
- }
- t.Messages = messages
- }
- return nil
-}
-```
-
-#### Good example (with proper spacing):
-
-```go
-func (t *Task) BeforeSave(tx *gorm.DB) error {
- if len(t.Messages) > 0 {
- messagesBytes, err := json.Marshal(t.Messages)
- if err != nil {
- return err
- }
-
- t.MessagesJSON = string(messagesBytes)
- }
-
- return nil
-}
-
-func (t *Task) AfterFind(tx *gorm.DB) error {
- if t.MessagesJSON != "" {
- var messages []onewin_dto.TaskCompletionMessage
- if err := json.Unmarshal([]byte(t.MessagesJSON), &messages); err != nil {
- return err
- }
-
- t.Messages = messages
- }
-
- return nil
-}
-```
-
-#### More examples:
-
-**Service method with multiple operations:**
-
-```go
-func (s *UserService) CreateUser(request *CreateUserRequest) (*User, error) {
- // Validate input
- if err := s.validateUserRequest(request); err != nil {
- return nil, err
- }
-
- // Create user entity
- user := &User{
- ID: uuid.New(),
- Name: request.Name,
- Email: request.Email,
- }
-
- // Save to database
- if err := s.repository.Create(user); err != nil {
- return nil, err
- }
-
- // Send notification
- s.notificationService.SendWelcomeEmail(user.Email)
-
- return user, nil
-}
-```
-
-**Repository method with query building:**
-
-```go
-func (r *Repository) GetFiltered(filters *Filters) ([]*Entity, error) {
- query := storage.GetDb().Model(&Entity{})
-
- if filters.Status != "" {
- query = query.Where("status = ?", filters.Status)
- }
-
- if filters.CreatedAfter != nil {
- query = query.Where("created_at > ?", filters.CreatedAfter)
- }
-
- var entities []*Entity
- if err := query.Find(&entities).Error; err != nil {
- return nil, err
- }
-
- return entities, nil
-}
-```
-
-**Repository method with error handling:**
-
-Bad (without spacing):
-
-```go
-func (r *Repository) FindById(id uuid.UUID) (*models.Task, error) {
- var task models.Task
- result := storage.GetDb().Where("id = ?", id).First(&task)
- if result.Error != nil {
- if errors.Is(result.Error, gorm.ErrRecordNotFound) {
- return nil, errors.New("task not found")
- }
- return nil, result.Error
- }
- return &task, nil
-}
-```
-
-Good (with proper spacing):
-
-```go
-func (r *Repository) FindById(id uuid.UUID) (*models.Task, error) {
- var task models.Task
-
- result := storage.GetDb().Where("id = ?", id).First(&task)
- if result.Error != nil {
- if errors.Is(result.Error, gorm.ErrRecordNotFound) {
- return nil, errors.New("task not found")
- }
-
- return nil, result.Error
- }
-
- return &task, nil
-}
-```
-
----
-
-### Comments
-
-#### Guidelines
-
-1. **No obvious comments** - Don't state what the code already clearly shows
-2. **Functions and variables should have meaningful names** - Code should be self-documenting
-3. **Comments for unclear code only** - Only add comments when code logic isn't immediately clear
-
-#### Key principles:
-
-- **Code should tell a story** - Use descriptive variable and function names
-- **Comments explain WHY, not WHAT** - The code shows what happens, comments explain business logic or complex decisions
-- **Prefer refactoring over commenting** - If code needs explaining, consider making it clearer instead
-- **API documentation is required** - Swagger comments for all HTTP endpoints are mandatory
-- **Complex algorithms deserve comments** - Mathematical formulas, business rules, or non-obvious optimizations
-- **Do not write summary sections in .md files unless directly requested** - Avoid adding "Summary" or "Conclusion" sections at the end of documentation files unless the user explicitly asks for them
-
-#### Example of useless comments:
-
-**1. Obvious SQL comment:**
-
-```sql
-// Create projects table
-CREATE TABLE projects (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- name TEXT NOT NULL,
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-```
-
-**2. Obvious function call comment:**
-
-```go
-// Create test project
-project := CreateTestProject(projectName, user, router)
-```
-
-**3. Redundant function comment:**
-
-```go
-// CreateValidLogItems creates valid log items for testing
-func CreateValidLogItems(count int, uniqueID string) []logs_receiving.LogItemRequestDTO {
-```
-
----
-
-### Controllers
-
-#### Controller guidelines:
-
-1. **When we write controller:**
- - We combine all routes to single controller
- - Names them as `.WhatWeDo` (not "handlers") concept
-
-2. **We use gin and `*gin.Context` for all routes**
-
- Example:
-
- ```go
- func (c *TasksController) GetAvailableTasks(ctx *gin.Context) ...
- ```
-
-3. **We document all routes with Swagger in the following format:**
-
-```go
-package audit_logs
-
-import (
- "net/http"
-
- user_models "databasus-backend/internal/features/users/models"
-
- "github.com/gin-gonic/gin"
- "github.com/google/uuid"
-)
-
-type AuditLogController struct {
- auditLogService *AuditLogService
-}
-
-func (c *AuditLogController) RegisterRoutes(router *gin.RouterGroup) {
- // All audit log endpoints require authentication (handled in main.go)
- auditRoutes := router.Group("/audit-logs")
-
- auditRoutes.GET("/global", c.GetGlobalAuditLogs)
- auditRoutes.GET("/users/:userId", c.GetUserAuditLogs)
-}
-
-// GetGlobalAuditLogs
-// @Summary Get global audit logs (ADMIN only)
-// @Description Retrieve all audit logs across the system
-// @Tags audit-logs
-// @Accept json
-// @Produce json
-// @Security BearerAuth
-// @Param limit query int false "Limit number of results" default(100)
-// @Param offset query int false "Offset for pagination" default(0)
-// @Param beforeDate query string false "Filter logs created before this date (RFC3339 format)" format(date-time)
-// @Success 200 {object} GetAuditLogsResponse
-// @Failure 401 {object} map[string]string
-// @Failure 403 {object} map[string]string
-// @Router /audit-logs/global [get]
-func (c *AuditLogController) GetGlobalAuditLogs(ctx *gin.Context) {
- user, isOk := ctx.MustGet("user").(*user_models.User)
- if !isOk {
- ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid user type in context"})
- return
- }
-
- request := &GetAuditLogsRequest{}
- if err := ctx.ShouldBindQuery(request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid query parameters"})
- return
- }
-
- response, err := c.auditLogService.GetGlobalAuditLogs(user, request)
- if err != nil {
- if err.Error() == "only administrators can view global audit logs" {
- ctx.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
- return
- }
- ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve audit logs"})
- return
- }
-
- ctx.JSON(http.StatusOK, response)
-}
-
-// GetUserAuditLogs
-// @Summary Get user audit logs
-// @Description Retrieve audit logs for a specific user
-// @Tags audit-logs
-// @Accept json
-// @Produce json
-// @Security BearerAuth
-// @Param userId path string true "User ID"
-// @Param limit query int false "Limit number of results" default(100)
-// @Param offset query int false "Offset for pagination" default(0)
-// @Param beforeDate query string false "Filter logs created before this date (RFC3339 format)" format(date-time)
-// @Success 200 {object} GetAuditLogsResponse
-// @Failure 400 {object} map[string]string
-// @Failure 401 {object} map[string]string
-// @Failure 403 {object} map[string]string
-// @Router /audit-logs/users/{userId} [get]
-func (c *AuditLogController) GetUserAuditLogs(ctx *gin.Context) {
- user, isOk := ctx.MustGet("user").(*user_models.User)
- if !isOk {
- ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid user type in context"})
- return
- }
-
- userIDStr := ctx.Param("userId")
- targetUserID, err := uuid.Parse(userIDStr)
- if err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
- return
- }
-
- request := &GetAuditLogsRequest{}
- if err := ctx.ShouldBindQuery(request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid query parameters"})
- return
- }
-
- response, err := c.auditLogService.GetUserAuditLogs(targetUserID, user, request)
- if err != nil {
- if err.Error() == "insufficient permissions to view user audit logs" {
- ctx.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
- return
- }
- ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve audit logs"})
- return
- }
-
- ctx.JSON(http.StatusOK, response)
-}
-```
-
----
-
-### Dependency injection (DI)
-
-For DI files use **implicit fields declaration styles** (especially for controllers, services, repositories, use cases, etc., not simple data structures).
-
-#### Instead of:
-
-```go
-var orderController = &OrderController{
- orderService: orderService,
- botUserService: bot_users.GetBotUserService(),
- botService: bots.GetBotService(),
- userService: users.GetUserService(),
-}
-```
-
-#### Use:
-
-```go
-var orderController = &OrderController{
- orderService,
- bot_users.GetBotUserService(),
- bots.GetBotService(),
- users.GetUserService(),
-}
-```
-
-**This is needed to avoid forgetting to update DI style when we add new dependency.**
-
-#### Force such usage
-
-Please force such usage if file look like this (see some services\controllers\repos definitions and getters):
-
-```go
-var orderBackgroundService = &OrderBackgroundService{
- orderService: orderService,
- orderPaymentRepository: orderPaymentRepository,
- botService: bots.GetBotService(),
- paymentSettingsService: payment_settings.GetPaymentSettingsService(),
-
- orderSubscriptionListeners: []OrderSubscriptionListener{},
-}
-
-var orderController = &OrderController{
- orderService: orderService,
- botUserService: bot_users.GetBotUserService(),
- botService: bots.GetBotService(),
- userService: users.GetUserService(),
-}
-
-func GetUniquePaymentRepository() *repositories.UniquePaymentRepository {
- return uniquePaymentRepository
-}
-
-func GetOrderPaymentRepository() *repositories.OrderPaymentRepository {
- return orderPaymentRepository
-}
-
-func GetOrderService() *OrderService {
- return orderService
-}
-
-func GetOrderController() *OrderController {
- return orderController
-}
-
-func GetOrderBackgroundService() *OrderBackgroundService {
- return orderBackgroundService
-}
-
-func GetOrderRepository() *repositories.OrderRepository {
- return orderRepository
-}
-```
-
-#### SetupDependencies() pattern
-
-**All `SetupDependencies()` functions must use `sync.OnceFunc` to ensure idempotent execution.**
-
-This pattern allows `SetupDependencies()` to be safely called multiple times (especially in tests) while ensuring the actual setup logic executes only once.
-
-**Implementation pattern:**
-
-```go
-package feature
-
-import (
- "sync"
-)
-
-var SetupDependencies = sync.OnceFunc(func() {
- // Initialize dependencies here
- someService.SetDependency(otherService)
- anotherService.AddListener(listener)
-})
-```
-
-**Why this pattern:**
-
-- **Tests can call multiple times**: Test setup often calls `SetupDependencies()` multiple times without issues
-- **Thread-safe**: Works correctly with concurrent calls (nanoseconds or seconds apart)
-- **Idempotent**: Subsequent calls are no-ops
-- **No panics**: Does not break tests or production code on multiple calls
-- **Concise**: `sync.OnceFunc` (Go 1.21+) replaces the manual `sync.Once` + `atomic.Bool` + `Do()` boilerplate
-
-**Key Points:**
-
-1. Use `sync.OnceFunc` instead of manual `sync.Once` + `atomic.Bool` pattern
-2. All setup logic must be inside the `OnceFunc` closure
-3. The returned function is safe to call concurrently and multiple times
-
----
-
-### Background services
-
-**All background service `Run()` methods must panic if called multiple times to prevent corrupted states.**
-
-Background services run infinite loops and must never be started twice on the same instance. Multiple calls indicate a serious bug that would cause duplicate goroutines, resource leaks, and data corruption.
-
-**Implementation pattern:**
-
-```go
-package feature
-
-import (
- "context"
- "fmt"
- "sync"
- "sync/atomic"
-)
-
-type BackgroundService struct {
- // ... existing fields ...
- hasRun atomic.Bool
-}
-
-func (s *BackgroundService) Run(ctx context.Context) {
- if s.hasRun.Swap(true) {
- panic(fmt.Sprintf("%T.Run() called multiple times", s))
- }
-
- // Existing infinite loop logic
- ticker := time.NewTicker(1 * time.Minute)
- defer ticker.Stop()
-
- for {
- select {
- case <-ctx.Done():
- return
- case <-ticker.C:
- s.doWork()
- }
- }
-}
-```
-
-**Why panic instead of warning:**
-
-- **Prevents corruption**: Multiple `Run()` calls would create duplicate goroutines consuming resources
-- **Fails fast**: Catches critical bugs immediately in tests and production
-- **Clear indication**: Panic clearly indicates a serious programming error
-- **Applies everywhere**: Same protection in tests and production
-
-**When this applies:**
-
-- All background services with infinite loops
-- Registry services (BackupNodesRegistry, RestoreNodesRegistry)
-- Scheduler services (BackupsScheduler, RestoresScheduler)
-- Worker nodes (BackuperNode, RestorerNode)
-- Cleanup services (AuditLogBackgroundService, DownloadTokenBackgroundService)
-
-**Key Points:**
-
-1. Use `atomic.Bool.Swap(true)` to atomically check-and-set in one call — no need for `sync.Once`
-2. **Always panic** if already run (never just log warning)
-3. This pattern is **thread-safe** for any timing (concurrent or sequential calls)
-
----
-
-### Migrations
-
-When writing migrations:
-
-- Write them for PostgreSQL
-- For PRIMARY UUID keys use `gen_random_uuid()`
-- For time use `TIMESTAMPTZ` (timestamp with zone)
-- Split table, constraint and indexes declaration (table first, then other one by one)
-- Format SQL in pretty way (add spaces, align columns types), constraints split by lines
-
-#### Example:
-
-```sql
-CREATE TABLE marketplace_info (
- bot_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- title TEXT NOT NULL,
- description TEXT NOT NULL,
- short_description TEXT NOT NULL,
- tutorial_url TEXT,
- info_order BIGINT NOT NULL DEFAULT 0,
- is_published BOOLEAN NOT NULL DEFAULT FALSE
-);
-
-ALTER TABLE marketplace_info_images
- ADD CONSTRAINT fk_marketplace_info_images_bot_id
- FOREIGN KEY (bot_id)
- REFERENCES marketplace_info (bot_id);
-```
-
----
-
-### Refactoring
-
-When applying changes, **do not forget to refactor old code**.
-
-You can shortify, make more readable, improve code quality, etc. Common logic can be extracted to functions, constants, files, etc.
-
-**After each large change with more than ~50-100 lines of code:**
-
-- Always run `make lint` (from backend root folder)
-- If you change frontend, run `npm run format` (from frontend root folder)
-
----
-
-### Testing
-
-**After writing tests, always launch them and verify that they pass.**
-
-#### Test naming format
-
-Use these naming patterns:
-
-- `Test_WhatWeDo_WhatWeExpect`
-- `Test_WhatWeDo_WhichConditions_WhatWeExpect`
-
-#### Examples from real codebase:
-
-- `Test_CreateApiKey_WhenUserIsProjectOwner_ApiKeyCreated`
-- `Test_UpdateProject_WhenUserIsProjectAdmin_ProjectUpdated`
-- `Test_DeleteApiKey_WhenUserIsProjectMember_ReturnsForbidden`
-- `Test_GetProjectAuditLogs_WithDifferentUserRoles_EnforcesPermissionsCorrectly`
-- `Test_ProjectLifecycleE2E_CompletesSuccessfully`
-
-#### Testing philosophy
-
-**Prefer controllers over unit tests:**
-
-- Test through HTTP endpoints via controllers whenever possible
-- Avoid testing repositories, services in isolation - test via API instead
-- Only use unit tests for complex model logic when no API exists
-- Name test files `controller_test.go` or `service_test.go`, not `integration_test.go`
-
-**Extract common logic to testing utilities:**
-
-- Create `testing.go` or `testing/testing.go` files for shared test utilities
-- Extract router creation, user setup, models creation helpers (in API, not just structs creation)
-- Reuse common patterns across different test files
-
-**Refactor existing tests:**
-
-- When working with existing tests, always look for opportunities to refactor and improve
-- Extract repetitive setup code to common utilities
-- Simplify complex tests by breaking them into smaller, focused tests
-- Replace inline test data creation with reusable helper functions
-- Consolidate similar test patterns across different test files
-- Make tests more readable and maintainable for other developers
-
-**Clean up test data:**
-
-- If the feature supports cleanup operations (DELETE endpoints, cleanup methods), use them in tests
-- Clean up resources after test execution to avoid test data pollution
-- Use `defer` statements or explicit cleanup calls at the end of tests
-- Prioritize using API methods for cleanup (not direct database deletion)
-- Examples:
- - CRUD features: delete created records via DELETE endpoint
- - File uploads: remove uploaded files
- - Background jobs: stop schedulers or cancel running tasks
-- Skip cleanup only when:
- - Tests run in isolated transactions that auto-rollback
- - Cleanup endpoint doesn't exist yet
- - Test explicitly validates failure scenarios where cleanup isn't possible
-
-**Example:**
-
-```go
-func Test_BackupLifecycle_CreateAndDelete(t *testing.T) {
- router := createTestRouter()
- workspace := workspaces_testing.CreateTestWorkspace("Test", owner)
-
- // Create backup config
- config := createBackupConfig(t, router, workspace.ID, owner.Token)
-
- // Cleanup at end of test
- defer deleteBackupConfig(t, router, workspace.ID, config.ID, owner.Token)
-
- // Test operations...
- triggerBackup(t, router, workspace.ID, config.ID, owner.Token)
-
- // Verify backup was created
- backups := getBackups(t, router, workspace.ID, owner.Token)
- assert.NotEmpty(t, backups)
-}
-```
-
-#### Cloud testing
-
-If you are testing cloud, set isCloud = true before test run and defer isCloud = false after test run. Example helper function:
-
-```go
-func enableCloud(t *testing.T) {
- t.Helper()
- config.GetEnv().IsCloud = true
- t.Cleanup(func() {
- config.GetEnv().IsCloud = false
- })
-}
-```
-
-#### Testing utilities structure
-
-**Create `testing.go` or `testing/testing.go` files with common utilities:**
-
-```go
-package projects_testing
-
-// CreateTestRouter creates unified router for all controllers
-func CreateTestRouter(controllers ...ControllerInterface) *gin.Engine {
- gin.SetMode(gin.TestMode)
- router := gin.New()
- v1 := router.Group("/api/v1")
- protected := v1.Group("").Use(users_middleware.AuthMiddleware(users_services.GetUserService()))
-
- for _, controller := range controllers {
- if routerGroup, ok := protected.(*gin.RouterGroup); ok {
- controller.RegisterRoutes(routerGroup)
- }
- }
- return router
-}
-
-// CreateTestProjectViaAPI creates project through HTTP API
-func CreateTestProjectViaAPI(name string, owner *users_dto.SignInResponseDTO, router *gin.Engine) (*projects_models.Project, string) {
- request := projects_dto.CreateProjectRequestDTO{Name: name}
- w := MakeAPIRequest(router, "POST", "/api/v1/projects", "Bearer "+owner.Token, request)
- // Handle response...
- return project, owner.Token
-}
-
-// AddMemberToProject adds member via API call
-func AddMemberToProject(project *projects_models.Project, member *users_dto.SignInResponseDTO, role users_enums.ProjectRole, ownerToken string, router *gin.Engine) {
- // Implementation...
-}
-```
-
-#### Controller test examples
-
-**Permission-based testing:**
-
-```go
-func Test_CreateApiKey_WhenUserIsProjectOwner_ApiKeyCreated(t *testing.T) {
- router := CreateApiKeyTestRouter(GetProjectController(), GetMembershipController())
- owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
- project, _ := projects_testing.CreateTestProjectViaAPI("Test Project", owner, router)
-
- request := CreateApiKeyRequestDTO{Name: "Test API Key"}
- var response ApiKey
- test_utils.MakePostRequestAndUnmarshal(t, router, "/api/v1/projects/api-keys/"+project.ID.String(), "Bearer "+owner.Token, request, http.StatusOK, &response)
-
- assert.Equal(t, "Test API Key", response.Name)
- assert.NotEmpty(t, response.Token)
-}
-```
-
-**Cross-project security testing:**
-
-```go
-func Test_UpdateApiKey_WithApiKeyFromDifferentProject_ReturnsBadRequest(t *testing.T) {
- router := CreateApiKeyTestRouter(GetProjectController(), GetMembershipController())
- owner1 := users_testing.CreateTestUser(users_enums.UserRoleMember)
- owner2 := users_testing.CreateTestUser(users_enums.UserRoleMember)
- project1, _ := projects_testing.CreateTestProjectViaAPI("Project 1", owner1, router)
- project2, _ := projects_testing.CreateTestProjectViaAPI("Project 2", owner2, router)
-
- apiKey := CreateTestApiKey("Cross Project Key", project1.ID, owner1.Token, router)
-
- // Try to update via different project endpoint
- request := UpdateApiKeyRequestDTO{Name: &"Hacked Key"}
- resp := test_utils.MakePutRequest(t, router, "/api/v1/projects/api-keys/"+project2.ID.String()+"/"+apiKey.ID.String(), "Bearer "+owner2.Token, request, http.StatusBadRequest)
-
- assert.Contains(t, string(resp.Body), "API key does not belong to this project")
-}
-```
-
-**E2E lifecycle testing:**
-
-```go
-func Test_ProjectLifecycleE2E_CompletesSuccessfully(t *testing.T) {
- router := projects_testing.CreateTestRouter(GetProjectController(), GetMembershipController())
-
- // 1. Create project
- owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
- project := projects_testing.CreateTestProject("E2E Project", owner, router)
-
- // 2. Add member
- member := users_testing.CreateTestUser(users_enums.UserRoleMember)
- projects_testing.AddMemberToProject(project, member, users_enums.ProjectRoleMember, owner.Token, router)
-
- // 3. Promote to admin
- projects_testing.ChangeMemberRole(project, member.UserID, users_enums.ProjectRoleAdmin, owner.Token, router)
-
- // 4. Transfer ownership
- projects_testing.TransferProjectOwnership(project, member.UserID, owner.Token, router)
-
- // 5. Verify new owner can manage project
- finalProject := projects_testing.GetProject(project.ID, member.Token, router)
- assert.Equal(t, project.ID, finalProject.ID)
-}
-```
-
----
-
-### Time handling
-
-**Always use `time.Now().UTC()` instead of `time.Now()`**
-
-This ensures consistent timezone handling across the application.
-
----
-
-### Logging
-
-We use `log/slog` for structured logging. Follow these conventions to keep logs consistent, searchable, and useful for debugging.
-
-#### Scoped loggers for tracing
-
-Attach IDs via `logger.With(...)` as early as possible so every downstream log line carries them automatically. Common IDs: `database_id`, `subscription_id`, `backup_id`, `storage_id`, `user_id`.
-
-```go
-func (s *BillingService) CreateSubscription(logger *slog.Logger, user *users_models.User, databaseID uuid.UUID, storageGB int) {
- logger = logger.With("database_id", databaseID)
-
- // all subsequent logger calls automatically include database_id
- logger.Debug(fmt.Sprintf("creating subscription for storage %d GB", storageGB))
-}
-```
-
-For background services, create scoped loggers with `task_name` for each subtask in `Run()`:
-
-```go
-func (c *BackupCleaner) Run(ctx context.Context) {
- retentionLog := c.logger.With("task_name", "clean_by_retention_policy")
- exceededLog := c.logger.With("task_name", "clean_exceeded_backups")
-
- // pass scoped logger to each method
- c.cleanByRetentionPolicy(retentionLog)
- c.cleanExceededBackups(exceededLog)
-}
-```
-
-Within loops, scope further:
-
-```go
-for _, backupConfig := range enabledBackupConfigs {
- dbLog := logger.With("database_id", backupConfig.DatabaseID, "policy", backupConfig.RetentionPolicyType)
- // ...
-}
-```
-
-#### Values in message, IDs as kv pairs
-
-**Values and statuses** (sizes, counts, status transitions) go into the message via `fmt.Sprintf`:
-
-```go
-logger.Info(fmt.Sprintf("subscription renewed: %s -> %s, %d GB", oldStatus, newStatus, sub.StorageGB))
-logger.Info(
- fmt.Sprintf("deleted exceeded backup: backup size is %.1f MB, total size is %.1f MB, limit is %d MB",
- backup.BackupSizeMb, backupsTotalSizeMB, limitPerDbMB),
- "backup_id", backup.ID,
-)
-```
-
-**IDs** stay as structured kv pairs — never inline them into the message string. This keeps them searchable in log aggregation tools:
-
-```go
-// good
-logger.Info("deleted old backup", "backup_id", backup.ID)
-
-// bad — ID buried in message, not searchable
-logger.Info(fmt.Sprintf("deleted old backup %s", backup.ID))
-```
-
-**`error` is always a kv pair**, never inlined into the message:
-
-```go
-// good
-logger.Error("failed to save subscription", "error", err)
-
-// bad
-logger.Error(fmt.Sprintf("failed to save subscription: %v", err))
-```
-
-#### Key naming and message style
-
-- **snake_case for all log keys**: `database_id`, `backup_id`, `task_name`, `total_size_mb` — not camelCase
-- **Lowercase log messages**: start with lowercase, no trailing period
-
-```go
-// good
-logger.Error("failed to create checkout session", "error", err)
-
-// bad
-logger.Error("Failed to create checkout session.", "error", err)
-```
-
-#### Log level usage
-
-- **Debug**: routine operations, entering a function, query results count (`"getting subscription events"`, `"found 5 invoices"`)
-- **Info**: significant state changes, completed actions (`"subscription activated"`, `"deleted exceeded backup"`)
-- **Warn**: degraded but recoverable situations (`"oldest backup is too recent to delete"`, `"requested storage is the same as current"`)
-- **Error**: failures that need attention (`"failed to save subscription"`, `"failed to delete backup file"`)
-
----
-
-### CRUD examples
-
-This is an example of complete CRUD implementation structure:
-
-#### controller.go
-
-```go
-package audit_logs
-
-import (
- "net/http"
-
- user_models "databasus-backend/internal/features/users/models"
-
- "github.com/gin-gonic/gin"
-)
-
-type AuditLogController struct {
- auditLogService *AuditLogService
-}
-
-func (c *AuditLogController) RegisterRoutes(router *gin.RouterGroup) {
- auditRoutes := router.Group("/audit-logs")
-
- auditRoutes.GET("/global", c.GetGlobalAuditLogs)
- auditRoutes.GET("/users/:userId", c.GetUserAuditLogs)
-}
-
-// GetGlobalAuditLogs
-// @Summary Get global audit logs (ADMIN only)
-// @Description Retrieve all audit logs across the system
-// @Tags audit-logs
-// @Accept json
-// @Produce json
-// @Security BearerAuth
-// @Param limit query int false "Limit number of results" default(100)
-// @Param offset query int false "Offset for pagination" default(0)
-// @Success 200 {object} GetAuditLogsResponse
-// @Failure 401 {object} map[string]string
-// @Failure 403 {object} map[string]string
-// @Router /audit-logs/global [get]
-func (c *AuditLogController) GetGlobalAuditLogs(ctx *gin.Context) {
- user, isOk := ctx.MustGet("user").(*user_models.User)
- if !isOk {
- ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid user type in context"})
- return
- }
-
- request := &GetAuditLogsRequest{}
- if err := ctx.ShouldBindQuery(request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid query parameters"})
- return
- }
-
- response, err := c.auditLogService.GetGlobalAuditLogs(user, request)
- if err != nil {
- if err.Error() == "only administrators can view global audit logs" {
- ctx.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
- return
- }
- ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve audit logs"})
- return
- }
-
- ctx.JSON(http.StatusOK, response)
-}
-
-// GetUserAuditLogs follows the same pattern...
-```
-
-#### controller_test.go
-
-```go
-package audit_logs
-
-func Test_GetGlobalAuditLogs_AdminSucceedsAndMemberGetsForbidden(t *testing.T) {
- adminUser := users_testing.CreateTestUser(user_enums.UserRoleAdmin)
- memberUser := users_testing.CreateTestUser(user_enums.UserRoleMember)
- router := createRouter()
- service := GetAuditLogService()
-
- createAuditLog(service, "Test log with user", &adminUser.UserID, nil)
- createAuditLog(service, "Test log standalone", nil, nil)
-
- // Test ADMIN can access global logs
- var response GetAuditLogsResponse
- test_utils.MakeGetRequestAndUnmarshal(t, router,
- "/api/v1/audit-logs/global?limit=10", "Bearer "+adminUser.Token, http.StatusOK, &response)
-
- assert.GreaterOrEqual(t, len(response.AuditLogs), 2)
- messages := extractMessages(response.AuditLogs)
- assert.Contains(t, messages, "Test log with user")
-
- // Test MEMBER cannot access global logs
- resp := test_utils.MakeGetRequest(t, router, "/api/v1/audit-logs/global",
- "Bearer "+memberUser.Token, http.StatusForbidden)
- assert.Contains(t, string(resp.Body), "only administrators can view global audit logs")
-}
-
-func createRouter() *gin.Engine {
- gin.SetMode(gin.TestMode)
- router := gin.New()
- SetupDependencies()
-
- v1 := router.Group("/api/v1")
- protected := v1.Group("").Use(users_middleware.AuthMiddleware(users_services.GetUserService()))
- GetAuditLogController().RegisterRoutes(protected.(*gin.RouterGroup))
-
- return router
-}
-```
-
-#### di.go
-
-```go
-package audit_logs
-
-import (
- users_services "databasus-backend/internal/features/users/services"
- "databasus-backend/internal/util/logger"
-)
-
-var auditLogRepository = &AuditLogRepository{}
-var auditLogService = &AuditLogService{
- auditLogRepository,
- logger.GetLogger(),
-}
-var auditLogController = &AuditLogController{auditLogService}
-
-func GetAuditLogService() *AuditLogService {
- return auditLogService
-}
-
-func GetAuditLogController() *AuditLogController {
- return auditLogController
-}
-
-func SetupDependencies() {
- users_services.GetUserService().SetAuditLogWriter(auditLogService)
- users_services.GetSettingsService().SetAuditLogWriter(auditLogService)
- users_services.GetManagementService().SetAuditLogWriter(auditLogService)
-}
-```
-
-#### dto.go
-
-```go
-package audit_logs
-
-import "time"
-
-type GetAuditLogsRequest struct {
- Limit int `form:"limit" json:"limit"`
- Offset int `form:"offset" json:"offset"`
- BeforeDate *time.Time `form:"beforeDate" json:"beforeDate"`
-}
-
-type GetAuditLogsResponse struct {
- AuditLogs []*AuditLog `json:"auditLogs"`
- Total int64 `json:"total"`
- Limit int `json:"limit"`
- Offset int `json:"offset"`
-}
-```
-
-#### model.go
-
-```go
-package audit_logs
-
-import (
- "time"
-
- "github.com/google/uuid"
-)
-
-type AuditLog struct {
- ID uuid.UUID `json:"id" gorm:"column:id"`
- UserID *uuid.UUID `json:"userId" gorm:"column:user_id"`
- ProjectID *uuid.UUID `json:"projectId" gorm:"column:project_id"`
- Message string `json:"message" gorm:"column:message"`
- CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`
-}
-
-func (AuditLog) TableName() string {
- return "audit_logs"
-}
-```
-
-#### repository.go
-
-```go
-package audit_logs
-
-import (
- "databasus-backend/internal/storage"
- "time"
-
- "github.com/google/uuid"
-)
-
-type AuditLogRepository struct{}
-
-func (r *AuditLogRepository) Create(auditLog *AuditLog) error {
- if auditLog.ID == uuid.Nil {
- auditLog.ID = uuid.New()
- }
-
- return storage.GetDb().Create(auditLog).Error
-}
-
-func (r *AuditLogRepository) GetGlobal(limit, offset int, beforeDate *time.Time) ([]*AuditLog, error) {
- var auditLogs []*AuditLog
-
- query := storage.GetDb().Order("created_at DESC")
-
- if beforeDate != nil {
- query = query.Where("created_at < ?", *beforeDate)
- }
-
- err := query.
- Limit(limit).
- Offset(offset).
- Find(&auditLogs).Error
-
- return auditLogs, err
-}
-
-// GetByUser, GetByProject, CountGlobal follow the same pattern...
-```
-
-#### service.go
-
-```go
-package audit_logs
-
-import (
- "errors"
- "log/slog"
- "time"
-
- user_enums "databasus-backend/internal/features/users/enums"
- user_models "databasus-backend/internal/features/users/models"
-
- "github.com/google/uuid"
-)
-
-type AuditLogService struct {
- auditLogRepository *AuditLogRepository
- logger *slog.Logger
-}
-
-func (s *AuditLogService) WriteAuditLog(message string, userID *uuid.UUID, projectID *uuid.UUID) {
- auditLog := &AuditLog{
- UserID: userID,
- ProjectID: projectID,
- Message: message,
- CreatedAt: time.Now().UTC(),
- }
-
- if err := s.auditLogRepository.Create(auditLog); err != nil {
- s.logger.Error("failed to create audit log", "error", err)
- }
-}
-
-func (s *AuditLogService) GetGlobalAuditLogs(
- user *user_models.User,
- request *GetAuditLogsRequest,
-) (*GetAuditLogsResponse, error) {
- if user.Role != user_enums.UserRoleAdmin {
- return nil, errors.New("only administrators can view global audit logs")
- }
-
- limit := request.Limit
- if limit <= 0 || limit > 1000 {
- limit = 100
- }
-
- offset := max(request.Offset, 0)
-
- auditLogs, err := s.auditLogRepository.GetGlobal(limit, offset, request.BeforeDate)
- if err != nil {
- return nil, err
- }
-
- total, err := s.auditLogRepository.CountGlobal(request.BeforeDate)
- if err != nil {
- return nil, err
- }
-
- return &GetAuditLogsResponse{
- AuditLogs: auditLogs,
- Total: total,
- Limit: limit,
- Offset: offset,
- }, nil
-}
-
-// GetUserAuditLogs, GetProjectAuditLogs follow the same pattern...
-```
-
-#### service_test.go
-
-```go
-package audit_logs
-
-func Test_AuditLogs_ProjectSpecificLogs(t *testing.T) {
- service := GetAuditLogService()
- user1 := users_testing.CreateTestUser(user_enums.UserRoleMember)
- project1ID := uuid.New()
-
- createAuditLog(service, "Test project1 log first", &user1.UserID, &project1ID)
- createAuditLog(service, "Test project1 log second", &user1.UserID, &project1ID)
-
- request := &GetAuditLogsRequest{Limit: 10, Offset: 0}
-
- project1Response, err := service.GetProjectAuditLogs(project1ID, request)
- assert.NoError(t, err)
- assert.Equal(t, 2, len(project1Response.AuditLogs))
-
- messages := extractMessages(project1Response.AuditLogs)
- assert.Contains(t, messages, "Test project1 log first")
- assert.Contains(t, messages, "Test project1 log second")
-}
-
-func createAuditLog(service *AuditLogService, message string, userID, projectID *uuid.UUID) {
- service.WriteAuditLog(message, userID, projectID)
-}
-
-func extractMessages(logs []*AuditLog) []string {
- messages := make([]string, len(logs))
- for i, log := range logs {
- messages[i] = log.Message
- }
- return messages
-}
-```
-
----
-
-### Modern Go
-
-Prefer modern Go stdlib idioms over manual equivalents. Use these patterns consistently.
-
-#### `slices` package — avoid manual loops
-
-```go
-slices.Contains(items, x) // instead of manual loop
-slices.Index(items, x) // returns index or -1
-slices.IndexFunc(items, func(item T) bool { return item.ID == id })
-slices.SortFunc(items, func(a, b T) int { return cmp.Compare(a.X, b.X) })
-slices.Sort(items) // for ordered types
-slices.Max(items) / slices.Min(items) // instead of manual loop
-slices.Reverse(items) // in-place
-slices.Compact(items) // remove consecutive duplicates
-slices.Clone(s) // shallow copy
-slices.Clip(s) // trim unused capacity
-```
-
-#### `any` instead of `interface{}`
-
-```go
-// good
-func process(value any) {}
-
-// bad
-func process(value interface{}) {}
-```
-
-#### `sync.OnceFunc` / `sync.OnceValue`
-
-```go
-// instead of sync.Once + wrapper
-f := sync.OnceFunc(func() { initialize() })
-
-// compute-once getter
-getValue := sync.OnceValue(func() int { return expensiveComputation() })
-```
-
-#### `context` helpers
-
-```go
-stop := context.AfterFunc(ctx, cleanup) // run cleanup on cancellation
-ctx, cancel := context.WithTimeoutCause(parent, d, ErrTimeout) // timeout with cause
-ctx, cancel := context.WithDeadlineCause(parent, deadline, ErrDeadline) // deadline with cause
-```
-
-#### Range over integer
-
-```go
-// good
-for i := range len(items) { ... }
-
-// bad
-for i := 0; i < len(items); i++ { ... }
-```
-
-#### `t.Context()` in tests
-
-Always use `t.Context()` — it cancels automatically when the test ends.
-
-```go
-// good
-func TestFoo(t *testing.T) {
- ctx := t.Context()
- result := doSomething(ctx)
-}
-
-// bad
-func TestFoo(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- result := doSomething(ctx)
-}
-```
-
-#### `omitzero` instead of `omitempty`
-
-Use `omitzero` for `time.Duration`, `time.Time`, structs, slices, and maps — `omitempty` does not work correctly for these types.
-
-```go
-// good
-type Config struct {
- Timeout time.Duration `json:"timeout,omitzero"`
- CreatedAt time.Time `json:"createdAt,omitzero"`
-}
-
-// bad
-type Config struct {
- Timeout time.Duration `json:"timeout,omitempty"` // broken for Duration!
- CreatedAt time.Time `json:"createdAt,omitempty"`
-}
-```
-
-#### `wg.Go()` instead of `wg.Add(1)` + goroutine
-
-```go
-// good
-var wg sync.WaitGroup
-for _, item := range items {
- wg.Go(func() { process(item) })
-}
-wg.Wait()
-
-// bad
-var wg sync.WaitGroup
-for _, item := range items {
- wg.Add(1)
- go func() {
- defer wg.Done()
- process(item)
- }()
-}
-wg.Wait()
-```
-
-#### `new(val)` for pointer literals
-
-`new()` accepts expressions since Go 1.26 — avoids the temporary-variable pattern.
-
-```go
-// good
-cfg := Config{
- Timeout: new(30), // *int
- Debug: new(true), // *bool
-}
-
-// bad
-timeout := 30
-debug := true
-cfg := Config{Timeout: &timeout, Debug: &debug}
-```
-
----
-
-## Frontend guidelines
-
-### React component structure
-
-Write React components with the following structure:
-
-```typescript
-interface Props {
- someValue: SomeValue;
-}
-
-const someHelperFunction = () => {
- ...
-}
-
-export const ReactComponent = ({ someValue }: Props): JSX.Element => {
- // First put states
- const [someState, setSomeState] = useState<...>(...)
-
- // Then place functions
- const loadSomeData = async () => {
- ...
- }
-
- // Then hooks
- useEffect(() => {
- loadSomeData();
- });
-
- // Then calculated values
- const calculatedValue = someValue.calculate();
-
- return <div> ... </div>
-}
-```
-
-#### Structure order:
-
-1. **Props interface** - Define component props
-2. **Helper functions** (outside component) - Pure utility functions
-3. **Component declaration**
- - **States** - `useState` declarations
- - **Functions** - Event handlers and async operations
- - **Hooks** - `useEffect`, `useMemo`, `useCallback`, etc.
- - **Calculated values** - Derived data from props/state
- - **Return** - JSX markup
-
-### Clipboard operations
-
-Always use `ClipboardHelper` (`shared/lib/ClipboardHelper.ts`) for clipboard operations — never call `navigator.clipboard` directly.
-
-- **Copy:** `ClipboardHelper.copyToClipboard(text)` — uses `navigator.clipboard` with `execCommand('copy')` fallback for non-secure contexts (HTTP).
-- **Paste:** Check `ClipboardHelper.isClipboardApiAvailable()` first. If available, use `ClipboardHelper.readFromClipboard()`. If not, show `ClipboardPasteModalComponent` (`shared/ui`) which lets the user paste manually via a text input modal.
-
----
-
-## Summary
-
-This document consolidates all project rules and guidelines. These standards should be followed consistently across all code in the Databasus project to maintain code quality, readability, and maintainability.
diff --git a/CLAUDE.md b/CLAUDE.md
index cc1c7283..9d685779 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1 +1,56 @@
-Look at @AGENTS.md
\ No newline at end of file
+# Databasus — Agent Rules and Guidelines
+
+This document contains project-wide coding standards and best practices for Databasus.
+This is NOT a strict set of rules — it is a set of recommendations to help write better, more consistent code.
+
+Per-folder rules live next to the code they govern:
+
+- [`backend/CLAUDE.md`](backend/CLAUDE.md) — Go + Gin + GORM + PostgreSQL backend (controllers, migrations, CRUD, DI, testing, logging)
+- [`agent/CLAUDE.md`](agent/CLAUDE.md) — Go agent CLI (no HTTP server, no schema; shares Go conventions with the backend)
+- [`frontend/CLAUDE.md`](frontend/CLAUDE.md) — React 19 + TypeScript + Vite + Ant Design + Tailwind
+
+This root file holds the engineering philosophy that applies everywhere.
+
+---
+
+## Language in code
+
+**English only in code, comments, identifiers, log messages, API strings, test assertions, and commit messages.** No other language inside `backend/`, `agent/`, or `frontend/src/` — even for user-facing fallback copy or error messages.
+
+---
+
+## Engineering philosophy
+
+**Think like a skeptical senior engineer and code reviewer. Don't just do what was asked — also think about what should have been asked. Catch real issues, not theoretical ones.**
+
+### Task tiers (scale your response to the task)
+
+- **Trivial** (typos, formatting, single-field adds): apply directly. Steps 5 only.
+- **Standard** (CRUD, typical features): steps 1, 5.
+- **Complex** (architecture, security, performance-critical): all steps.
+- **Unclear** (ambiguous requirements): steps 1 and 4 are mandatory.
+
+### Steps for non-trivial tasks
+
+1. **Restate the objective**, list explicit + inferred assumptions, flag shaky ones.
+2. **Propose solutions** — for complex tasks, 2–3 approaches including a simpler baseline; recommend one with tradeoffs (complexity, maintainability, performance, extensibility).
+3. **Identify risks** — edge cases, security/privacy, performance, operational concerns (deployment, observability, rollback). Before finalizing, ask "what could go wrong?" and patch.
+4. **Handle ambiguity** — pick a reasonable default, label it, note what changes under alternative assumptions.
+5. **Deliver quality** — correct, testable, maintainable code with minimal tests/validation. Prefer controller tests over unit tests.
+6. **Fix root causes, not symptoms** — ask "why did this happen?" and address the underlying issue.
+
+### After each run: suggest refactorings
+
+Reread the diff with fresh eyes and **list** (don't silently apply) refactor suggestions: unclear names, duplication, dead code, deep nesting, misplaced responsibilities, leaky abstractions. Keep suggestions concrete (file + lines), behavior-preserving, and scoped to the current change. If the diff is already clean, say so in one line.
+
+### Naming
+
+Name variables and functions for **intent**, not mechanism. Naming is the biggest readability lever — avoid generic names like `data`, `handle`, `process`.
+
+Booleans take an `is` / `can` / `has` / `should` prefix (`isAllowed`, `canAccess`, `hasItems`, `shouldRetry`) — never bare nouns/verbs like `allowed` or `touches`.
+
+### Linting and formatting
+
+After each change run linting and formatting depending on folder you are working it.
+- backend and agent has `make lint` commands
+- frontend has `pnpm lint` and `pnpm format` commands
\ No newline at end of file
diff --git a/agent/CLAUDE.md b/agent/CLAUDE.md
new file mode 100644
index 00000000..0e6ffa01
--- /dev/null
+++ b/agent/CLAUDE.md
@@ -0,0 +1,261 @@
+# Agent guidelines (Go CLI)
+
+Coding standards for the Databasus agent — a Go CLI tool that runs alongside a managed Postgres instance and talks to the backend over HTTP. It uses `pgx` directly (no GORM), has no Gin HTTP server, and owns no database schema.
+
+For project-wide engineering philosophy, naming, and lint/format commands, see the root `CLAUDE.md`. For the backend (Gin/GORM/Swagger) ruleset, see `backend/CLAUDE.md`. Go conventions in this file overlap with `backend/CLAUDE.md` on purpose — both should stay in sync as conventions evolve.
+
+---
+
+## Table of Contents
+
+- [Spacing between logical statements](#spacing-between-logical-statements)
+- [Comments](#comments)
+- [Background services](#background-services)
+- [Testing](#testing)
+- [Time handling](#time-handling)
+- [Logging](#logging)
+- [Modern Go](#modern-go)
+
+---
+
+## Spacing between logical statements
+
+Add blank lines between logical blocks so the flow is visible at a glance:
+
+- before the final `return`
+- after variable declarations, before they're used
+- between error handling and subsequent logic
+- between distinct logical operations
+
+Bad:
+
+```go
+func encodeMessages(messages []Message) (string, error) {
+ if len(messages) > 0 {
+ messagesBytes, err := json.Marshal(messages)
+ if err != nil {
+ return "", err
+ }
+ return string(messagesBytes), nil
+ }
+ return "", nil
+}
+```
+
+Good:
+
+```go
+func encodeMessages(messages []Message) (string, error) {
+ if len(messages) > 0 {
+ messagesBytes, err := json.Marshal(messages)
+ if err != nil {
+ return "", err
+ }
+
+ return string(messagesBytes), nil
+ }
+
+ return "", nil
+}
+```
+
+---
+
+## Comments
+
+- **No obvious comments** — don't restate what the code already shows.
+- **Explain *why*, not *what*** — code shows what happens; comments explain business rules, hidden constraints, or non-obvious optimizations.
+- **Prefer refactoring over commenting** — better names or smaller functions usually beat a comment.
+- **Complex algorithms deserve comments** — formulas, business rules, non-obvious optimizations.
+- **No "Summary" / "Conclusion" sections in `.md` files** unless explicitly requested.
+
+Bad (each comment restates the function name):
+
+```go
+// Run pg_dump
+runPgDump(request)
+
+// CreateValidLogItems creates valid log items for testing
+func CreateValidLogItems(count int, uniqueID string) []LogItemRequestDTO {
+```
+
+---
+
+## Background services
+
+The agent ships at least one long-running goroutine (e.g. `BackgroundUpgrader`). Calling `Run()` twice on the same instance is always a bug — duplicate goroutines leak resources and corrupt state. **Always panic; never just log a warning.**
+
+```go
+type BackgroundUpgrader struct {
+ // ...
+ hasRun atomic.Bool
+}
+
+func (u *BackgroundUpgrader) Run(ctx context.Context) {
+ if u.hasRun.Swap(true) {
+ panic(fmt.Sprintf("%T.Run() called multiple times", u))
+ }
+
+ ticker := time.NewTicker(1 * time.Minute)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ u.checkAndUpgrade(ctx)
+ }
+ }
+}
+```
+
+`atomic.Bool.Swap(true)` does the check-and-set atomically — no `sync.Once` needed.
+
+---
+
+## Testing
+
+**Always run tests after writing them and verify they pass.**
+
+### Naming
+
+- `Test_WhatWeDo_WhatWeExpect`
+- `Test_WhatWeDo_WhichConditions_WhatWeExpect`
+
+Examples: `Test_RunFullBackup_WhenPgDumpSucceeds_UploadsToStorage`, `Test_StreamWAL_OnConnectionDrop_RetriesWithBackoff`, `Test_BackgroundUpgrader_WhenCalledTwice_Panics`.
+
+### Where tests live
+
+- **Unit / package tests**: alongside the code, named `*_test.go` (e.g. `agent/internal/features/full_backup/backuper_test.go`).
+- **End-to-end tests**: under `agent/e2e/`. Run via `make e2e` / `make e2e-clean`.
+
+The agent has no HTTP API of its own, so there are no controller tests — test exported functions of services, the CLI commands, and the streaming/IO logic directly.
+
+### Refactor tests as you touch them
+
+When editing existing tests, look for repetitive setup that should become a helper, oversized tests that should be split, and similar patterns across files that should be consolidated. Helpers live in a `testing.go` file inside the package.
+
+### Clean up test data
+
+If a test creates files, processes, or external state, clean it up via `t.Cleanup(...)` or `defer`. Skip cleanup only when the test uses an isolated tempdir the OS reclaims, or when it explicitly validates a failure path where cleanup isn't possible.
+
+---
+
+## Time handling
+
+Always use `time.Now().UTC()` instead of `time.Now()` to keep timezones consistent across the application.
+
+---
+
+## Logging
+
+We use `log/slog`. Three rules.
+
+### 1. Scope IDs early via `logger.With(...)`
+
+Attach `database_id`, `backup_id`, `wal_segment`, `upgrade_target`, etc. as soon as you know them so every downstream line carries them automatically.
+
+```go
+func (b *Backuper) RunFullBackup(logger *slog.Logger, databaseID, backupID uuid.UUID) {
+ logger = logger.With("database_id", databaseID, "backup_id", backupID)
+
+ logger.Debug("starting full backup")
+ // every subsequent log carries both IDs
+}
+```
+
+For background services, also scope `task_name` per subtask in `Run()`. Inside loops, scope further with the loop's identifying ID.
+
+### 2. Values in message, IDs and errors as kv pairs
+
+Sizes, counts, and status transitions go into the message via `fmt.Sprintf`. IDs and errors stay as structured kv pairs so they're searchable in log aggregation tools.
+
+```go
+// good
+logger.Info(fmt.Sprintf("uploaded backup chunk: %d / %d MB", uploadedMB, totalMB))
+logger.Info("uploaded backup", "backup_id", backupID)
+logger.Error("failed to upload backup", "error", err)
+
+// bad — ID buried in the message string, error formatted instead of attached
+logger.Info(fmt.Sprintf("uploaded backup %s", backupID))
+logger.Error(fmt.Sprintf("failed to upload backup: %v", err))
+```
+
+### 3. Style and level
+
+- All keys `snake_case` (`database_id`, `total_size_mb`) — never camelCase.
+- Messages start lowercase, no trailing period.
+- **Debug**: routine ops, function entry, query result counts.
+- **Info**: significant state changes, completed actions (`"backup uploaded"`, `"agent started"`).
+- **Warn**: degraded but recoverable (`"retrying after WAL stream drop"`, `"upgrade skipped: same version"`).
+- **Error**: failures that need attention (`"failed to upload backup"`, `"failed to spawn pg_dump"`).
+
+---
+
+## Modern Go
+
+Prefer modern stdlib idioms over manual equivalents.
+
+### `slices` package — avoid manual loops
+
+```go
+slices.Contains(items, x)
+slices.Index(items, x) // returns index or -1
+slices.IndexFunc(items, func(item T) bool { return item.ID == id })
+slices.SortFunc(items, func(a, b T) int { return cmp.Compare(a.X, b.X) })
+slices.Sort(items)
+slices.Max(items) / slices.Min(items)
+slices.Reverse(items) // in-place
+slices.Compact(items) // remove consecutive duplicates
+slices.Clone(s)
+slices.Clip(s)
+```
+
+### Quick wins
+
+- `any` instead of `interface{}`.
+- `for i := range len(items)` instead of `for i := 0; i < len(items); i++`.
+- `sync.OnceFunc(fn)` / `sync.OnceValue(fn)` instead of `sync.Once` + wrapper.
+- `t.Context()` in tests instead of `context.WithCancel(context.Background())` + `defer cancel()` — auto-cancels at test end.
+- `wg.Go(fn)` instead of `wg.Add(1)` + `go func() { defer wg.Done(); fn() }()`.
+
+### `context` helpers
+
+```go
+stop := context.AfterFunc(ctx, cleanup) // run cleanup on cancellation
+ctx, cancel := context.WithTimeoutCause(parent, d, ErrTimeout) // timeout with cause
+ctx, cancel := context.WithDeadlineCause(parent, deadline, ErrDeadline) // deadline with cause
+```
+
+### `omitzero` instead of `omitempty` for non-nullable types
+
+`omitempty` is broken for `time.Duration`, `time.Time`, structs, slices, and maps — it doesn't omit a zero value. Use `omitzero`:
+
+```go
+// good
+type Config struct {
+ Timeout time.Duration `json:"timeout,omitzero"`
+ CreatedAt time.Time `json:"createdAt,omitzero"`
+}
+
+// bad
+type Config struct {
+ Timeout time.Duration `json:"timeout,omitempty"` // broken for Duration!
+ CreatedAt time.Time `json:"createdAt,omitempty"`
+}
+```
+
+### `new(val)` for pointer literals (Go 1.26+)
+
+`new()` accepts expressions, eliminating the temp-variable pattern:
+
+```go
+// good
+cfg := Config{Timeout: new(30), Debug: new(true)}
+
+// bad
+timeout := 30
+debug := true
+cfg := Config{Timeout: &timeout, Debug: &debug}
+```
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
new file mode 100644
index 00000000..77c1b569
--- /dev/null
+++ b/backend/CLAUDE.md
@@ -0,0 +1,641 @@
+# Backend guidelines (Go + Gin + GORM)
+
+Coding standards for the Databasus backend (Go + Gin + GORM + PostgreSQL).
+For project-wide engineering philosophy, naming, and lint/format commands, see the root `CLAUDE.md`.
+
+---
+
+## Table of Contents
+
+- [Spacing between logical statements](#spacing-between-logical-statements)
+- [Comments](#comments)
+- [Controllers](#controllers)
+- [Dependency injection (DI)](#dependency-injection-di)
+- [Background services](#background-services)
+- [Migrations](#migrations)
+- [Testing](#testing)
+- [Time handling](#time-handling)
+- [Logging](#logging)
+- [CRUD examples](#crud-examples)
+- [Modern Go](#modern-go)
+
+---
+
+## Spacing between logical statements
+
+Add blank lines between logical blocks so the flow is visible at a glance:
+
+- before the final `return`
+- after variable declarations, before they're used
+- between error handling and subsequent logic
+- between distinct logical operations
+
+Bad:
+
+```go
+func (r *Repository) FindById(id uuid.UUID) (*models.Task, error) {
+ var task models.Task
+ result := storage.GetDb().Where("id = ?", id).First(&task)
+ if result.Error != nil {
+ if errors.Is(result.Error, gorm.ErrRecordNotFound) {
+ return nil, errors.New("task not found")
+ }
+ return nil, result.Error
+ }
+ return &task, nil
+}
+```
+
+Good:
+
+```go
+func (r *Repository) FindById(id uuid.UUID) (*models.Task, error) {
+ var task models.Task
+
+ result := storage.GetDb().Where("id = ?", id).First(&task)
+ if result.Error != nil {
+ if errors.Is(result.Error, gorm.ErrRecordNotFound) {
+ return nil, errors.New("task not found")
+ }
+
+ return nil, result.Error
+ }
+
+ return &task, nil
+}
+```
+
+---
+
+## Comments
+
+- **No obvious comments** — don't restate what the code already shows.
+- **Explain *why*, not *what*** — code shows what happens; comments explain business rules, hidden constraints, or non-obvious optimizations.
+- **Prefer refactoring over commenting** — if code needs explaining, consider clearer names or smaller functions first.
+- **Swagger comments are mandatory** for every HTTP endpoint.
+- **Complex algorithms deserve comments** — formulas, business rules, non-obvious optimizations.
+- **No "Summary" / "Conclusion" sections in `.md` files** unless explicitly requested.
+
+Bad (comments restate the function name):
+
+```go
+// Create test project
+project := CreateTestProject(projectName, user, router)
+
+// CreateValidLogItems creates valid log items for testing
+func CreateValidLogItems(count int, uniqueID string) []logs_receiving.LogItemRequestDTO {
+```
+
+---
+
+## Controllers
+
+- One controller per feature, combining all routes for that feature.
+- Method names express **what we do** (`GetAvailableTasks`), not the suffix `Handler`.
+- All routes use Gin and take `*gin.Context`.
+- Every route is documented with Swagger annotations — see [CRUD examples → controller.go](#controllergo) for the canonical annotation format.
+
+```go
+type AuditLogController struct {
+ auditLogService *AuditLogService
+}
+
+func (c *AuditLogController) RegisterRoutes(router *gin.RouterGroup) {
+ auditRoutes := router.Group("/audit-logs")
+
+ auditRoutes.GET("/global", c.GetGlobalAuditLogs)
+ auditRoutes.GET("/users/:userId", c.GetUserAuditLogs)
+}
+```
+
+---
+
+## Dependency injection (DI)
+
+For DI files (controllers, services, repositories, use cases — not plain data structs), use **implicit positional field declaration**. Adding a new dependency must force every callsite to update; named-field syntax silently accepts a missing field as zero.
+
+```go
+// good — positional, fails to compile if a field is added or reordered
+var orderController = &OrderController{
+ orderService,
+ bot_users.GetBotUserService(),
+ bots.GetBotService(),
+ users.GetUserService(),
+}
+
+// bad — named fields, silently accept new fields with zero values
+var orderController = &OrderController{
+ orderService: orderService,
+ botUserService: bot_users.GetBotUserService(),
+ botService: bots.GetBotService(),
+ userService: users.GetUserService(),
+}
+```
+
+Apply this anywhere you see the `var fooController = &FooController{...}` + `GetFooController()` getter shape.
+
+### `SetupDependencies()` pattern
+
+`SetupDependencies()` runs cross-feature wiring (e.g. registering audit-log writers on user services) and **must be idempotent** — tests call it many times. Use `sync.OnceFunc`:
+
+```go
+var SetupDependencies = sync.OnceFunc(func() {
+ users_services.GetUserService().SetAuditLogWriter(auditLogService)
+ users_services.GetSettingsService().SetAuditLogWriter(auditLogService)
+})
+```
+
+`sync.OnceFunc` (Go 1.21+) is concise and thread-safe — don't reinvent it with `sync.Once` + `atomic.Bool`.
+
+### Never inject another feature's repository
+
+A feature's repositories are its **private implementation detail**. When feature A needs data that lives under feature B, extend B's *service* with a public method and inject **that service** — not B's repository.
+
+The seam must live at the service layer so authorization, logging, and invariants stay auditable in one place, and so schema changes don't ripple across features. A feature injecting its **own** repository is unchanged.
+
+```go
+// good — cross-feature data access goes through the owning service
+var backupController = &BackupController{
+ backupService,
+ databases.GetDatabaseService(), // service, not repository
+}
+
+// bad — reaches into another feature's private layer
+var backupController = &BackupController{
+ backupService,
+ databases.GetDatabaseRepository(), // bypasses authz / logging / invariants
+}
+```
+
+---
+
+## Background services
+
+A background service runs an infinite loop in a goroutine. Calling `Run()` twice on the same instance is always a bug — duplicate goroutines leak resources and corrupt state. **Always panic; never just log a warning.**
+
+```go
+type BackgroundService struct {
+ // ...
+ hasRun atomic.Bool
+}
+
+func (s *BackgroundService) Run(ctx context.Context) {
+ if s.hasRun.Swap(true) {
+ panic(fmt.Sprintf("%T.Run() called multiple times", s))
+ }
+
+ ticker := time.NewTicker(1 * time.Minute)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ s.doWork()
+ }
+ }
+}
+```
+
+`atomic.Bool.Swap(true)` does the check-and-set atomically — no `sync.Once` needed. Applies to schedulers, registries, worker nodes, and cleanup services.
+
+---
+
+## Migrations
+
+- PostgreSQL only.
+- Primary UUID keys → `gen_random_uuid()`.
+- Time columns → `TIMESTAMPTZ` (timestamp with zone), never `TIMESTAMP`.
+- Tables, constraints, and indexes go in **separate** declarations (table first, then each constraint / index on its own statement).
+- Format SQL: align column types, put each constraint clause on its own line.
+
+```sql
+CREATE TABLE marketplace_info (
+ bot_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ title TEXT NOT NULL,
+ description TEXT NOT NULL,
+ short_description TEXT NOT NULL,
+ tutorial_url TEXT,
+ info_order BIGINT NOT NULL DEFAULT 0,
+ is_published BOOLEAN NOT NULL DEFAULT FALSE
+);
+
+ALTER TABLE marketplace_info_images
+ ADD CONSTRAINT fk_marketplace_info_images_bot_id
+ FOREIGN KEY (bot_id)
+ REFERENCES marketplace_info (bot_id);
+```
+
+---
+
+## Testing
+
+**Always run tests after writing them and verify they pass.**
+
+### Naming
+
+- `Test_WhatWeDo_WhatWeExpect`
+- `Test_WhatWeDo_WhichConditions_WhatWeExpect`
+
+Examples: `Test_CreateApiKey_WhenUserIsProjectOwner_ApiKeyCreated`, `Test_DeleteApiKey_WhenUserIsProjectMember_ReturnsForbidden`, `Test_GetProjectAuditLogs_WithDifferentUserRoles_EnforcesPermissionsCorrectly`, `Test_ProjectLifecycleE2E_CompletesSuccessfully`.
+
+### Prefer controller tests over unit tests
+
+- Test through HTTP endpoints whenever possible — that's the contract real callers see.
+- Avoid testing repositories or services in isolation; cover them via the API.
+- Use unit tests only for complex model logic with no API surface.
+- File names: `controller_test.go` or `service_test.go` — never `integration_test.go`.
+
+### Shared testing utilities
+
+Each feature creates a `testing.go` (or `testing/testing.go`) with router builders, model creation helpers, and request helpers used by other features' tests. Build creation helpers via the API (`POST /...`) — not direct DB inserts — so the helpers double as a sanity check on the create endpoint.
+
+### Refactor tests as you touch them
+
+When editing existing tests, look for: repetitive setup that should become a helper, oversized tests that should be split, inline test data that should reuse a helper, and similar patterns across files that should be consolidated.
+
+### Clean up test data
+
+If the feature has a DELETE endpoint or cleanup method, **use it** in the test (`defer` or `t.Cleanup`). Prefer API cleanup over direct DB delete. Skip cleanup only when the test runs in an auto-rollback transaction, the cleanup endpoint doesn't exist yet, or the test explicitly validates a failure path where cleanup isn't possible.
+
+### Cloud-mode tests
+
+Toggle `config.GetEnv().IsCloud` via a helper that auto-restores in `t.Cleanup`:
+
+```go
+func enableCloud(t *testing.T) {
+ t.Helper()
+ config.GetEnv().IsCloud = true
+ t.Cleanup(func() { config.GetEnv().IsCloud = false })
+}
+```
+
+### Canonical controller test
+
+```go
+func Test_CreateApiKey_WhenUserIsProjectOwner_ApiKeyCreated(t *testing.T) {
+ router := CreateApiKeyTestRouter(GetProjectController(), GetMembershipController())
+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
+ project, _ := projects_testing.CreateTestProjectViaAPI("Test Project", owner, router)
+
+ request := CreateApiKeyRequestDTO{Name: "Test API Key"}
+ var response ApiKey
+ test_utils.MakePostRequestAndUnmarshal(t, router,
+ "/api/v1/projects/api-keys/"+project.ID.String(),
+ "Bearer "+owner.Token, request, http.StatusOK, &response)
+
+ assert.Equal(t, "Test API Key", response.Name)
+ assert.NotEmpty(t, response.Token)
+}
+```
+
+The same shape extends to:
+- **Permission-failure tests** — assert `http.StatusForbidden` plus the error message body.
+- **Cross-tenant isolation tests** — create a second user/project, attempt to access the first via the second's endpoint, assert `http.StatusBadRequest`.
+- **E2E lifecycle tests** — chain create → mutate → transfer → verify, all via API.
+
+---
+
+## Time handling
+
+Always use `time.Now().UTC()` instead of `time.Now()` to keep timezones consistent across the application.
+
+---
+
+## Logging
+
+We use `log/slog`. Three rules.
+
+### 1. Scope IDs early via `logger.With(...)`
+
+Attach `database_id`, `backup_id`, `subscription_id`, etc. as soon as you know them so every downstream line carries them automatically.
+
+```go
+func (s *BillingService) CreateSubscription(logger *slog.Logger, databaseID uuid.UUID) {
+ logger = logger.With("database_id", databaseID)
+
+ logger.Debug("creating subscription")
+ // every subsequent log automatically carries database_id
+}
+```
+
+For background services, also scope `task_name` per subtask in `Run()`. Inside loops, scope further with the loop's identifying ID.
+
+### 2. Values in message, IDs and errors as kv pairs
+
+Sizes, counts, and status transitions go into the message via `fmt.Sprintf`. IDs and errors stay as structured kv pairs so they're searchable in log aggregation tools.
+
+```go
+// good
+logger.Info(fmt.Sprintf("subscription renewed: %s -> %s, %d GB", oldStatus, newStatus, sub.StorageGB))
+logger.Info("deleted old backup", "backup_id", backup.ID)
+logger.Error("failed to save subscription", "error", err)
+
+// bad — ID buried in the message string, error formatted instead of attached
+logger.Info(fmt.Sprintf("deleted old backup %s", backup.ID))
+logger.Error(fmt.Sprintf("failed to save subscription: %v", err))
+```
+
+### 3. Style and level
+
+- All keys `snake_case` (`database_id`, `total_size_mb`) — never camelCase.
+- Messages start lowercase, no trailing period.
+- **Debug**: routine ops, function entry, query result counts.
+- **Info**: significant state changes, completed actions.
+- **Warn**: degraded but recoverable.
+- **Error**: failures that need attention.
+
+### Required contextual fields
+
+Every log line must carry enough to reconstruct one entity's history:
+
+- **`request_id`** — auto-generated per HTTP request by Gin middleware and echoed back in the response. Attached to every log inside an HTTP request; do not add it manually.
+- **`user_id`, `database_id`, `backup_id`, `subscription_id`, etc.** — attach via `logger.With(...)` at the boundary where the entity becomes known so downstream logs inherit it.
+- **Background jobs / schedulers** (no HTTP request, no `request_id`): pass these inline on every log call:
+ - **`job_id`** — fresh UUID per execution; the correlation ID for one run.
+ - **`job_name`** — stable snake_case identifier of which job this is (e.g. `"backup_retention_cleanup"`, `"audit_log_cleanup"`). Define it as a `const` next to the service — never the struct's type name (renames break log queries). Lets you query "all runs of job X" or "all errors from job Y" across history.
+
+```go
+const jobName = "backup_retention_cleanup"
+
+func (c *BackupCleaner) Run(ctx context.Context) {
+ jobID := uuid.New()
+ logger := c.logger.With("job_id", jobID, "job_name", jobName)
+
+ logger.Info("job started")
+ // ...
+}
+```
+
+### What never goes into logs
+
+- **Passwords, tokens, API keys, full `Authorization` / `Cookie` headers** — centralize redaction at the logger config; don't redact ad-hoc at call sites.
+- **PII (email, phone)** — mask before logging (`r***@example.com`, `+7***1234`).
+- **Full request / response bodies** — log only the fields you actually need, never whole payloads.
+
+---
+
+## CRUD examples
+
+A complete feature has these files. The controller carries the canonical Swagger annotation format — that's the part to memorize.
+
+### controller.go
+
+```go
+package audit_logs
+
+type AuditLogController struct {
+ auditLogService *AuditLogService
+}
+
+func (c *AuditLogController) RegisterRoutes(router *gin.RouterGroup) {
+ auditRoutes := router.Group("/audit-logs")
+
+ auditRoutes.GET("/global", c.GetGlobalAuditLogs)
+ auditRoutes.GET("/users/:userId", c.GetUserAuditLogs)
+}
+
+// GetGlobalAuditLogs
+// @Summary Get global audit logs (ADMIN only)
+// @Description Retrieve all audit logs across the system
+// @Tags audit-logs
+// @Accept json
+// @Produce json
+// @Security BearerAuth
+// @Param limit query int false "Limit number of results" default(100)
+// @Param offset query int false "Offset for pagination" default(0)
+// @Param beforeDate query string false "Filter logs created before this date (RFC3339 format)" format(date-time)
+// @Success 200 {object} GetAuditLogsResponse
+// @Failure 401 {object} map[string]string
+// @Failure 403 {object} map[string]string
+// @Router /audit-logs/global [get]
+func (c *AuditLogController) GetGlobalAuditLogs(ctx *gin.Context) {
+ user, isOk := ctx.MustGet("user").(*user_models.User)
+ if !isOk {
+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid user type in context"})
+ return
+ }
+
+ request := &GetAuditLogsRequest{}
+ if err := ctx.ShouldBindQuery(request); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid query parameters"})
+ return
+ }
+
+ response, err := c.auditLogService.GetGlobalAuditLogs(user, request)
+ if err != nil {
+ if err.Error() == "only administrators can view global audit logs" {
+ ctx.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
+ return
+ }
+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve audit logs"})
+ return
+ }
+
+ ctx.JSON(http.StatusOK, response)
+}
+```
+
+### di.go
+
+```go
+var auditLogRepository = &AuditLogRepository{}
+var auditLogService = &AuditLogService{
+ auditLogRepository,
+ logger.GetLogger(),
+}
+var auditLogController = &AuditLogController{auditLogService}
+
+func GetAuditLogService() *AuditLogService { return auditLogService }
+func GetAuditLogController() *AuditLogController { return auditLogController }
+
+var SetupDependencies = sync.OnceFunc(func() {
+ users_services.GetUserService().SetAuditLogWriter(auditLogService)
+ users_services.GetSettingsService().SetAuditLogWriter(auditLogService)
+})
+```
+
+### dto.go
+
+```go
+type GetAuditLogsRequest struct {
+ Limit int `form:"limit" json:"limit"`
+ Offset int `form:"offset" json:"offset"`
+ BeforeDate *time.Time `form:"beforeDate" json:"beforeDate"`
+}
+
+type GetAuditLogsResponse struct {
+ AuditLogs []*AuditLog `json:"auditLogs"`
+ Total int64 `json:"total"`
+ Limit int `json:"limit"`
+ Offset int `json:"offset"`
+}
+```
+
+### model.go
+
+```go
+type AuditLog struct {
+ ID uuid.UUID `json:"id" gorm:"column:id"`
+ UserID *uuid.UUID `json:"userId" gorm:"column:user_id"`
+ ProjectID *uuid.UUID `json:"projectId" gorm:"column:project_id"`
+ Message string `json:"message" gorm:"column:message"`
+ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`
+}
+
+func (AuditLog) TableName() string { return "audit_logs" }
+```
+
+### repository.go
+
+```go
+type AuditLogRepository struct{}
+
+func (r *AuditLogRepository) Create(auditLog *AuditLog) error {
+ if auditLog.ID == uuid.Nil {
+ auditLog.ID = uuid.New()
+ }
+
+ return storage.GetDb().Create(auditLog).Error
+}
+
+func (r *AuditLogRepository) GetGlobal(limit, offset int, beforeDate *time.Time) ([]*AuditLog, error) {
+ var auditLogs []*AuditLog
+
+ query := storage.GetDb().Order("created_at DESC")
+ if beforeDate != nil {
+ query = query.Where("created_at < ?", *beforeDate)
+ }
+
+ err := query.Limit(limit).Offset(offset).Find(&auditLogs).Error
+
+ return auditLogs, err
+}
+```
+
+### service.go
+
+```go
+type AuditLogService struct {
+ auditLogRepository *AuditLogRepository
+ logger *slog.Logger
+}
+
+func (s *AuditLogService) WriteAuditLog(message string, userID, projectID *uuid.UUID) {
+ auditLog := &AuditLog{
+ UserID: userID,
+ ProjectID: projectID,
+ Message: message,
+ CreatedAt: time.Now().UTC(),
+ }
+
+ if err := s.auditLogRepository.Create(auditLog); err != nil {
+ s.logger.Error("failed to create audit log", "error", err)
+ }
+}
+
+func (s *AuditLogService) GetGlobalAuditLogs(
+ user *user_models.User,
+ request *GetAuditLogsRequest,
+) (*GetAuditLogsResponse, error) {
+ if user.Role != user_enums.UserRoleAdmin {
+ return nil, errors.New("only administrators can view global audit logs")
+ }
+
+ limit := request.Limit
+ if limit <= 0 || limit > 1000 {
+ limit = 100
+ }
+
+ offset := max(request.Offset, 0)
+
+ auditLogs, err := s.auditLogRepository.GetGlobal(limit, offset, request.BeforeDate)
+ if err != nil {
+ return nil, err
+ }
+
+ total, err := s.auditLogRepository.CountGlobal(request.BeforeDate)
+ if err != nil {
+ return nil, err
+ }
+
+ return &GetAuditLogsResponse{
+ AuditLogs: auditLogs,
+ Total: total,
+ Limit: limit,
+ Offset: offset,
+ }, nil
+}
+```
+
+For `controller_test.go`, see [Testing → Canonical controller test](#canonical-controller-test) above.
+
+---
+
+## Modern Go
+
+Prefer modern stdlib idioms over manual equivalents.
+
+### `slices` package — avoid manual loops
+
+```go
+slices.Contains(items, x)
+slices.Index(items, x) // returns index or -1
+slices.IndexFunc(items, func(item T) bool { return item.ID == id })
+slices.SortFunc(items, func(a, b T) int { return cmp.Compare(a.X, b.X) })
+slices.Sort(items) // ordered types
+slices.Max(items) / slices.Min(items)
+slices.Reverse(items) // in-place
+slices.Compact(items) // remove consecutive duplicates
+slices.Clone(s) // shallow copy
+slices.Clip(s) // trim unused capacity
+```
+
+### Quick wins
+
+- `any` instead of `interface{}`.
+- `for i := range len(items)` instead of `for i := 0; i < len(items); i++`.
+- `sync.OnceFunc(fn)` / `sync.OnceValue(fn)` instead of `sync.Once` + wrapper.
+- `t.Context()` in tests instead of `context.WithCancel(context.Background())` + `defer cancel()` — auto-cancels at test end.
+- `wg.Go(fn)` instead of `wg.Add(1)` + `go func() { defer wg.Done(); fn() }()`.
+
+### `context` helpers
+
+```go
+stop := context.AfterFunc(ctx, cleanup) // run cleanup on cancellation
+ctx, cancel := context.WithTimeoutCause(parent, d, ErrTimeout) // timeout with cause
+ctx, cancel := context.WithDeadlineCause(parent, deadline, ErrDeadline) // deadline with cause
+```
+
+### `omitzero` instead of `omitempty` for non-nullable types
+
+`omitempty` is broken for `time.Duration`, `time.Time`, structs, slices, and maps — it doesn't omit a zero value. Use `omitzero`:
+
+```go
+// good
+type Config struct {
+ Timeout time.Duration `json:"timeout,omitzero"`
+ CreatedAt time.Time `json:"createdAt,omitzero"`
+}
+
+// bad
+type Config struct {
+ Timeout time.Duration `json:"timeout,omitempty"` // broken for Duration!
+ CreatedAt time.Time `json:"createdAt,omitempty"`
+}
+```
+
+### `new(val)` for pointer literals (Go 1.26+)
+
+`new()` accepts expressions, eliminating the temp-variable pattern:
+
+```go
+// good
+cfg := Config{Timeout: new(30), Debug: new(true)}
+
+// bad
+timeout := 30
+debug := true
+cfg := Config{Timeout: &timeout, Debug: &debug}
+```
diff --git a/backend/README.md b/backend/README.md
index b7f4b022..9ee1a0d3 100644
--- a/backend/README.md
+++ b/backend/README.md
@@ -45,24 +45,4 @@ To generate swagger docs:
Swagger URL is:
-> http://localhost:4005/api/v1/docs/swagger/index.html#/
-
-# Project structure
-
-Default endpoint structure is:
-
-/feature
-/feature/controller.go
-/feature/service.go
-/feature/repository.go
-/feature/model.go
-/feature/dto.go
-
-If there are couple of models:
-/feature/models/model1.go
-/feature/models/model2.go
-...
-
-# Project rules
-
-Read .cursor/rules folder, it contains all the rules for the project.
+> http://localhost:4005/api/v1/docs/swagger/index.html#/
\ No newline at end of file
diff --git a/frontend/CLAUDE.md b/frontend/CLAUDE.md
new file mode 100644
index 00000000..184a9f17
--- /dev/null
+++ b/frontend/CLAUDE.md
@@ -0,0 +1,201 @@
+# Frontend guidelines (React + TypeScript)
+
+This document contains coding standards for the Databasus frontend (React 19 + TypeScript + Vite + Ant Design + TailwindCSS).
+For project-wide engineering philosophy, see the root `CLAUDE.md`.
+
+---
+
+## Table of Contents
+
+- [UI kit and icons](#ui-kit-and-icons)
+- [React component structure](#react-component-structure)
+- [Clipboard operations](#clipboard-operations)
+- [Forms](#forms)
+- [User-facing copy](#user-facing-copy)
+- [FSD (Feature-Sliced Design)](#fsd-feature-sliced-design)
+- [Refactoring](#refactoring)
+
+---
+
+## UI kit and icons
+
+- **AntD 5 only** for components. Don't pull in Mantine, MUI, Chakra, shadcn, or Radix directly. Use AntD primitives (`Button`, `Input`, `Modal`, `Form`, `Table`, `Menu`, `Tabs`, etc.) plus Tailwind utility classes for layout and spacing.
+- **`@ant-design/icons` only** for icons. Don't add `lucide-react`, `@heroicons/react`, `react-icons`, or FontAwesome.
+
+---
+
+## React component structure
+
+Write React components with the following structure:
+
+```typescript
+interface Props {
+ someValue: SomeValue;
+}
+
+const someHelperFunction = () => {
+ ...
+}
+
+export const ReactComponent = ({ someValue }: Props): JSX.Element => {
+ // First put states
+ const [someState, setSomeState] = useState<...>(...)
+
+ // Then place functions
+ const loadSomeData = async () => {
+ ...
+ }
+
+ // Then hooks
+ useEffect(() => {
+ loadSomeData();
+ });
+
+ // Then calculated values
+ const calculatedValue = someValue.calculate();
+
+ return <div> ... </div>
+}
+```
+
+### Structure order
+
+1. **Props interface** — Define component props
+2. **Helper functions** (outside component) — Pure utility functions
+3. **Component declaration**
+ - **States** — `useState` declarations
+ - **Functions** — Event handlers and async operations
+ - **Hooks** — `useEffect`, `useMemo`, `useCallback`, etc.
+ - **Calculated values** — Derived data from props/state
+ - **Return** — JSX markup
+
+---
+
+## Clipboard operations
+
+Always use `ClipboardHelper` (`shared/lib/ClipboardHelper.ts`) for clipboard operations — never call `navigator.clipboard` directly.
+
+- **Copy:** `ClipboardHelper.copyToClipboard(text)` — uses `navigator.clipboard` with `execCommand('copy')` fallback for non-secure contexts (HTTP).
+- **Paste:** Check `ClipboardHelper.isClipboardApiAvailable()` first. If available, use `ClipboardHelper.readFromClipboard()`. If not, show `ClipboardPasteModalComponent` (`shared/ui`) which lets the user paste manually via a text input modal.
+
+---
+
+## Forms
+
+### Progressive disclosure
+
+- Submit buttons (`Save`, `Update password`, etc.) render **only when the form is dirty**.
+- Dependent fields (e.g. `Confirm password`) render **only after the field they depend on has a value**.
+
+---
+
+## User-facing copy
+
+Use a plain hyphen `-` in any string the user will see — labels, descriptions, notifications, modal bodies, error messages. Reserve em dashes (`—`) and en dashes (`–`) for markdown docs and code comments only.
+
+---
+
+## FSD (Feature-Sliced Design)
+
+The project follows FSD v2.1. Layers in use: `app/`, `pages/`, `widgets/`, `features/`, `entities/`, `shared/`.
+
+### Import direction
+
+`app → pages → widgets → features → entities → shared`
+
+A module may only import from layers strictly **below** it. Cross-imports between slices on the **same** layer are forbidden.
+
+```tsx
+// ✅ Allowed
+import { useUser } from '@/entities/user';
+import { LoginForm } from '@/features/auth';
+// ❌ Violations
+import { loginUser } from '@/features/auth';
+// inside entities/
+import { likePost } from '@/features/like-post';
+// inside another feature
+import { ProfilePage } from '@/pages/profile';
+import { Button } from '@/shared/ui/Button';
+
+// inside a feature
+```
+
+### Where new code goes
+
+- Used in only one page → keep it in that `pages/` slice.
+- Reusable infrastructure, **no business logic** → `shared/` (UI kit, utils, API client, route constants, auth tokens, CRUD helpers).
+- User interaction reused in 2+ pages → `features/`.
+- Domain model reused in 2+ pages/features → `entities/`.
+- App-wide providers, router, theme → `app/`.
+
+**When in doubt — keep it in `pages/`.** Extract only when a second real consumer appears.
+
+### Quick placement table
+
+| Scenario | Single use | Reused in 2+ places |
+| ------------------------ | ------------------------------------- | --------------------------------------- |
+| Profile form | `pages/profile/ui/ProfileForm.tsx` | `features/profile-form/` |
+| Database card | `pages/databases/ui/DatabaseCard.tsx` | `entities/database/ui/DatabaseCard.tsx` |
+| Data fetching for backup | `pages/backup/api/fetch-backup.ts` | `entities/backup/api/` |
+| Auth token / session | `shared/auth/` (always) | `shared/auth/` (always) |
+| Login form | `pages/login/ui/LoginForm.tsx` | `features/auth/` |
+| CRUD helpers | `shared/api/` (always) | `shared/api/` (always) |
+| Date formatting util | — | `shared/lib/format-date.ts` |
+| Modal content | `pages/[page]/ui/SomeModal.tsx` | — |
+
+### MUST rules
+
+1. **Downward-only imports.** No upward imports, no same-layer cross-imports.
+2. **Public API via `index.ts`.** External consumers import only from a slice's `index.ts`, never its internal files.
+ ```tsx
+ // ✅
+ import { LoginForm } from '@/features/auth'
+ // ❌
+ import { LoginForm } from '@/features/auth/ui/LoginForm'
+ ```
+3. **Domain-based file names.** Name files by the domain they represent, not their technical role.
+ ```text
+ // ❌ model/types.ts, model/utils.ts, lib/helpers.ts
+ // ✅ model/user.ts, model/backup.ts, api/fetch-database.ts
+ ```
+4. **No business logic in `shared/`.** Shared holds only infrastructure. Domain calculations live in `entities/` or higher.
+
+### Segments inside a slice
+
+- `ui/` — components, styles
+- `model/` — state, types, domain logic, validation
+- `api/` — backend calls, request functions, API-specific types
+- `lib/` — internal helpers for this slice only
+- `config/` — slice-level config / feature flags
+
+`app/` and `shared/` have **segments only, no slices**. Segments within them may import from each other.
+
+### AVOID
+
+- Creating an entity prematurely (single consumer → keep it in the page).
+- Putting CRUD inside `entities/` — CRUD is infrastructure, goes to `shared/api/`.
+- Creating a `user` entity just for auth tokens/DTOs — those belong in `shared/auth/` or `shared/api/`.
+- Extracting single-use code "for future reuse."
+- God slices (`user-management/` covering auth + profile + password) — split by focused responsibility.
+- Importing UI segments of one entity from another entity. Entity UI may be imported only from features/widgets/pages.
+- Abusing the `@x` cross-import pattern — it is a last resort, not a tool.
+
+### Cross-imports between same-layer slices
+
+When two slices on the same layer need to share code, try **in order**:
+
+1. **Merge** — if they always change together, they are one slice.
+2. **Extract shared logic down to `entities/`** — keep UI in the features/widgets.
+3. **Compose in a higher layer (IoC)** — the parent page/widget imports both and wires them together via props/slots.
+4. **`@x` notation** — explicit, documented cross-import between entities only. Last resort.
+
+---
+
+## Refactoring
+
+When applying changes, **do not forget to refactor old code**. You can shortify, make more readable, improve code quality, etc. Common logic can be extracted to functions, constants, files, etc.
+
+**After each large change with more than ~50-100 lines of code:**
+
+- Run `pnpm format` (from `frontend/` root folder)
+- Run `pnpm lint` to verify the change