Skip to content

Instantly share code, notes, and snippets.

@bouroo
Last active December 11, 2025 03:19
Show Gist options
  • Select an option

  • Save bouroo/cd7e71cdeb018e6010b3b5d726405612 to your computer and use it in GitHub Desktop.

Select an option

Save bouroo/cd7e71cdeb018e6010b3b5d726405612 to your computer and use it in GitHub Desktop.
AGENTS.md to let agentic coder better understand project and maintain context across coding sessions.
description globs alwaysApply
Express.js Project System Design Rules (with Bun)
*.ts
*.js
false

Architecture

  • Layered Architecture: Implement clean architecture with presentation, business logic, and data access layers
  • Modular Structure: Organize into modules that can transition to microservices
  • Mono-repo: Use mono-repo for consistent dependency management

Code Quality & Tooling

  • Linter: Use eslint with @typescript-eslint for all TypeScript code
  • Formatter: Use prettier for code formatting
  • Type Checking: Use tsc for type checking
  • API Documentation: Use swagger-jsdoc and swagger-ui for API documentation

Project Structure

  • API Layer: /src/api - Express routes and controllers
  • Domain Layer: /src/domains/{domain} - Business logic and use cases
    • /controllers - HTTP request handlers with validation
    • /services - Business logic layer
    • /repositories - Data access layer
  • Infrastructure: /src/infrastructure - Database, external services
  • SQL Structure: /sql/queries (TypeScript query builders), /sql/migrations (drizzle/kysely migrations)

Database

  • Selection: PostgreSQL (large), SQLite (small/medium), MongoDB (document)
  • ORM: Use drizzle-orm or mongoose for database access
  • Migrations: Use drizzle-kit or mongoose-auto-migrate for database migrations
  • IDs: Use uuid for unique identifiers

Dependencies

  • Framework: express for web framework
  • DI Container: Use awilix for dependency injection
  • Utilities: lodash for utilities, zod for validation
  • Auth: jsonwebtoken for JWT authentication
  • Mocking: jest or vitest for testing, mock-service-worker for API mocking

Security & Performance

  • Security: Rate limiting (express-rate-limit), input validation, HTTPS, structured error handling
  • Performance: Implement caching and connection pooling
  • Monitoring: Add metrics and health check endpoints
  • Configuration: Use dotenv with validation

Testing & Deployment

  • Testing: Use jest or vitest for unit/integration tests
  • Container Support: Use Docker for containerization
  • Runtime: Use Bun for execution and bunx for package management
  • Build: Use bun build for production builds

Development Workflow

  1. Write database queries with TypeScript query builders
  2. Run bun run lint to check code quality
  3. Run bun run type-check for type validation
  4. Run bun run test to execute tests
  5. Run bun run build for production build
  6. Run bun run migrate for database migrations
description globs alwaysApply
Flutter Project System Design Rules
*.dart
false

Architecture

  • Clean Architecture: MVVM/MVC pattern with clear separation between presentation, business logic, and data layers
  • Feature-based Modular: Organize code by features in lib/features/{feature_name}/ structure
  • Mono-repo: Use mono-repo for consistent versioning and dependency management

Code Quality & Generation

  • Linter: Use flutter_lints + dart_code_metrics with auto-fix
  • Code Generation: Use build_runner with injectable for DI and json_serializable for models
  • API Documentation: Add Dart doc comments with /// for all public APIs
  • Verification: After changes, run: dart pub get && dart pub run build_runner build && flutter analyze && flutter test

File Organization

  • Structure: lib/features/{feature}/, lib/core/, lib/data/, lib/presentation/
  • Feature Structure: Each feature contains presentation, business_logic, data, and models subfolders
  • Testing: test/ for unit/integration tests, test/features/ for feature-specific tests

Database

  • Selection: Supabase (cloud), SQLite (local), or Firebase (NoSQL)
  • Access: Use drift or sqflite for local, supabase for cloud
  • IDs: Use uuid package for unique identifiers
  • Transactions: Repository layer handles database transactions

Dependencies

  • DI Container: get_it + injectable for dependency injection
  • Utilities: collection, rxdart for reactive programming
  • State Management: flutter_bloc or riverpod
  • Mocking: mocktail for unit tests

Security & Performance

  • Security: Input validation, HTTPS, structured error handling
  • Performance: Follow Flutter performance optimization patterns
  • Monitoring: Add analytics and crash reporting
  • Configuration: Environment variables with .env files

Testing & Deployment

  • Coverage: Maintain high test coverage with flutter test --coverage
  • Multi-platform: Support iOS, Android, Web, and Desktop
  • Graceful Handling: Implement proper error handling and state management
  • CI/CD: Automated testing, code quality checks, and multi-platform builds

Development Workflow

  1. Write models and database schemas
  2. Run dart pub run build_runner build to generate code
  3. Run flutter analyze to check code quality
  4. Run flutter test to execute tests
  5. Run flutter build for platform-specific builds
description globs alwaysApply
Go Project System Design Rules
*.go
false

Architecture

  • Clean Architecture with DDD: Implement Domain-Driven Design principles with clear separation between domain, application, and infrastructure layers.
  • Modular Monolith: Structure code as a modular monolith, poised for future transition to microservices if needed.
  • Mono-repo: Use a mono-repo approach to ensure consistent versioning and dependency management across modules.

Code Quality & Generation

  • Linter: Use golangci-lint v2 for all Go code, always applying the --fix flag.
  • Interface Mocking: Annotate every interface with //go:generate mockgen -source=$GOFILE -destination=../mock/$GOFILE_mock.go to ensure consistent mock generation.
  • Swagger: Ensure all HTTP handlers include @Summary, @Description, and @Router Swagger annotations.
  • SQL Generation: Use sqlc to generate type-safe database code from SQL queries defined in the /sql/queries directory.
  • Verification: After making changes, execute: go generate ./... && golangci-lint run --fix ./... && go clean -testcache && go test -v -race ./... to verify code correctness and quality.

File Organization

  • SQL Structure: Organize SQL code in /sql/queries (for sqlc files) and /sql/migrations (for migrations).
  • Domain Structure: Each domain should contain:
    • /interface: Domain interfaces and contracts
    • /handler: HTTP handlers with Swagger docs
    • /usecase: Business logic with dependency injection
    • /repository: Data access using sqlc-generated code
    • /sqlc: Auto-generated SQL code
    • /mock: Generated mock implementations

Database

  • Selection:
    • PostgreSQL 18+ for large-scale deployments
    • MariaDB 11+ for small/medium projects
    • FerretDB 2.5+ for document stores
    • Valkey 9+ for key-value storage
  • Access: Interact with SQL databases using sqlc for type-safe queries and manage migrations with golang-migrate/migrate.
  • IDs: Use UUIDv7 for unique identifiers throughout the system.
  • Transactions: Handle database transactions in the repository layer using sqlc-generated code.

Dependencies

  • DI Container: Use samber/do for dependency injection.
  • Utilities: Use samber/lo for sync helpers and samber/ro for stream processing utilities.
  • Auth: Implement authentication with golang-jwt/jwt (primary) or zitadel/oidc (alternative).
  • Mocking: Use uber-go/mock and DATA-DOG/go-sqlmock for mocking dependencies in tests.

Security & Performance

  • Security: Enforce rate limiting, input validation, HTTPS, and structured error handling in all services.
  • Performance: Follow patterns from goperf.dev for optimal performance.
  • Monitoring: Implement metrics and health check endpoints for observability.
  • Configuration: Use environment variables for configuration, ensuring proper validation.

Testing & Deployment

  • Coverage: Maintain high test coverage across all architectural layers.
  • Container Support: Ensure all services are compatible with container environments.
  • Graceful Shutdown: Implement mechanisms for graceful shutdown of services.
  • CI/CD: Integrate automated testing, quality checks, security scanning, and container deployment within your CI/CD pipeline.

Development Workflow

  1. Write SQL queries with sqlc comments in /sql/queries.
  2. Run go generate ./... to regenerate mocks and SQL code.
  3. Run golangci-lint run --fix ./... to fix linting issues.
  4. Run go clean -testcache to clear the test cache.
  5. Run go test -v -race ./... to execute tests with race detection enabled.

Ambiguity Handling

When the task or provided inputs are ambiguous, ask targeted clarification questions before proceeding rather than guessing.

Tool Boundaries & Argument Validation

Use only tools and utilities specified in these rules. Validate arguments against required formats or tool interfaces before usage. If needed arguments are missing or unclear, request them explicitly rather than making assumptions.

description globs alwaysApply
Hono.js Project System Design Rules (with Bun)
*.ts
*.js
false

Architecture

  • Clean Architecture: Implement layered architecture with domain separation
  • Modular Structure: Organize into modules that can transition to microservices
  • Mono-repo: Use mono-repo for consistent dependency management

Code Quality & Tooling

  • Linter: Use eslint with @typescript-eslint for all JavaScript/TypeScript code
  • Formatter: Use prettier for code formatting
  • Type Checking: Use tsc for type checking and vitest for testing
  • Swagger: Add JSDoc comments to all API endpoints with OpenAPI specifications

Project Structure

  • API Layer: /src/api - Hono handlers and route definitions
  • Domain Layer: /src/domains/{domain} - Business logic and use cases
    • /handlers - HTTP handlers with validation
    • /services - Business logic layer
    • /repositories - Data access layer
  • Infrastructure: /src/infrastructure - Database, external services
  • SQL Structure: /sql/queries (TypeScript query builders), /sql/migrations (drizzle/kysely migrations)

Database

  • Selection: PostgreSQL (large), SQLite (small/medium), MongoDB (document)
  • ORM: Use drizzle-orm or kysely for type-safe database access
  • Migrations: Use drizzle-kit for database migrations
  • IDs: Use uuid for unique identifiers

Dependencies

  • Framework: hono for web framework
  • DI Container: Use inversify or awilix for dependency injection
  • Utilities: lodash for utilities, zod for validation
  • Auth: lucia-auth for authentication, openid-client for OIDC
  • Mocking: vitest with msw for API mocking

Security & Performance

  • Security: Rate limiting, input validation, HTTPS, structured error handling
  • Performance: Follow Node.js performance best practices
  • Monitoring: Add metrics and health check endpoints
  • Configuration: Use dotenv with validation

Testing & Deployment

  • Testing: Use vitest for unit/integration tests, playwright for E2E tests
  • Container Support: Use Docker for containerization
  • Runtime: Use Bun for execution and bunx for package management
  • Build: Use bun build for production builds

Development Workflow

  1. Write database queries with TypeScript query builders
  2. Run bun run lint to check code quality
  3. Run bun run type-check for type validation
  4. Run bun run test to execute tests
  5. Run bun run build for production build
  6. Run bun run migrate for database migrations
description globs alwaysApply
Rust Axum Project System Design Rules
*.rs
false

Architecture

  • Clean Architecture with DDD: Implement Domain-Driven Design principles with clear separation between domain, application, and infrastructure layers
  • Modular Monolith: Structure code as a modular monolith that can transition to microservices
  • Mono-repo: Use mono-repo for consistent versioning and dependency management

Code Quality & Generation

  • Linter: Use clippy for all Rust code with -- -D warnings
  • Formatter: Use rustfmt for code formatting
  • Interface Mocking: Every trait must include #[cfg(test)] mock implementations or use mockall crate
  • Swagger: Add OpenAPI documentation to all HTTP handlers using utoipa or axum-extra
  • SQL Generation: Use sqlx or diesel for type-safe database code
  • Verification: After any changes, run: cargo clippy -- -D warnings && cargo fmt --all && cargo test --lib -- --test-threads=1

File Organization

  • SQL Structure: /sql/queries (SQL files), /sql/migrations (database migrations)
  • Domain Structure: Each domain contains:
    • /interface - Domain traits and contracts
    • /handler - Axum handlers with OpenAPI docs
    • /usecase - Business logic with dependency injection
    • /repository - Data access using sqlx/diesel
    • /model - Domain models and entities

Database

  • Selection: PostgreSQL 15+ (large), SQLite 3.40+ (small/medium), MongoDB 6.0+ (document)
  • Access: Use sqlx for type-safe queries, sqlx-cli for migrations
  • IDs: Use uuid crate for unique identifiers
  • Transactions: Repository layer handles transactions through sqlx transactions

Dependencies

  • DI Container: Use async-trait and dependency injection patterns
  • Utilities: itertools for iterators, anyhow for error handling, thiserror for custom errors
  • Auth: jsonwebtoken for JWT, oauth2 for OAuth2/OIDC
  • Mocking: mockall for trait mocking, mockall_double for double mocking
  • Async: tokio for async runtime, futures for async utilities

Security & Performance

  • Security: Rate limiting, input validation, HTTPS, structured error handling
  • Performance: Follow Rust performance best practices, use tokio runtime efficiently
  • Monitoring: Add metrics and health check endpoints using metrics crate
  • Configuration: Use config crate with environment variables

Testing & Deployment

  • Coverage: Maintain high test coverage across all layers using cargo-tarpaulin
  • Container Support: All services must support container environments
  • Graceful Shutdown: Implement graceful shutdown using tokio::signal
  • CI/CD: Automated testing, quality checks, security scanning, container deployment

Development Workflow

  1. Write SQL queries with sqlx macros in /sql/queries
  2. Run cargo clippy -- -D warnings to check code quality
  3. Run cargo fmt --all to format code
  4. Run cargo test --lib -- --test-threads=1 to execute tests
  5. Run cargo tarpaulin --out Html for test coverage
  6. Run cargo build --release for production build

Key Rust-Specific Considerations

  • Use Result<T, E> for error handling throughout the application
  • Implement proper trait bounds for generic code
  • Use async/await patterns consistently
  • Leverage Rust's ownership system for memory safety
  • Use Arc<Mutex<T>> or RwLock<T> for shared state when needed
  • Implement proper error types using thiserror crate
  • Use serde for serialization/deserialization
  • Follow Rust's naming conventions (snake_case for functions, PascalCase for types)
description globs alwaysApply
Spring Boot 4 System Design Rules
*.java
*.kt
false

Architecture

  • Clean Architecture with DDD: Domain-Driven Design with layered architecture (domain, application, infrastructure)
  • Modular Monolith: Modular structure supporting microservices transition
  • Mono-repo: Consistent versioning and dependency management

Code Quality & Generation

  • Linter: Checkstyle/SpotBugs with Maven/Gradle plugins
  • Interface Mocking: Mockito for all interfaces with @MockBean
  • API Documentation: SpringDoc OpenAPI with @Operation, @ApiResponse
  • Database Access: Spring Data JPA or QueryDSL for type-safe queries
  • Verification: mvn clean verify or gradle build with quality gates

File Organization

  • SQL Structure: /src/main/resources/db/migration (Flyway), /src/main/resources/sql (queries)
  • Domain Structure: Each domain contains:
    • /domain - Domain entities and value objects
    • /application - Use cases and services
    • /infrastructure - Repositories, external integrations
    • /interfaces - REST controllers, DTOs

Database

  • Selection: PostgreSQL (large), H2 (dev/test), MySQL (medium)
  • Access: Spring Data JPA with Hibernate, Flyway for migrations
  • IDs: @GeneratedValue with UUID strategy
  • Transactions: @Transactional at service layer

Dependencies

  • DI: Spring Framework IoC container
  • Utilities: Lombok, Apache Commons
  • Auth: Spring Security with JWT
  • Testing: JUnit 5, Mockito, Spring Test

Security & Performance

  • Security: Spring Security with JWT, input validation, HTTPS
  • Performance: Spring caching, async processing, connection pooling
  • Monitoring: Actuator endpoints, Micrometer metrics
  • Configuration: @ConfigurationProperties with validation

Testing & Deployment

  • Coverage: JaCoCo with minimum thresholds
  • Container: Docker with multi-stage builds
  • Shutdown: @PreDestroy hooks, graceful shutdown
  • CI/CD: Maven/Gradle pipelines, quality gates

Development Workflow

  1. Define entities and domain models
  2. Create repositories with Spring Data JPA
  3. Implement services with @Transactional
  4. Build REST controllers with validation
  5. Write integration tests with Testcontainers
  6. Run mvn verify or gradle build
  7. Deploy with Docker profiles
globs alwaysApply description
true
AI Coder Unified Ruleset, The Memory Bank is a persistent knowledge system storing long‑term project understanding. It removes the need to repeatedly scan the entire codebase. All architectural, design, and requirements knowledge lives here. It is the primary reference for the AI Coder Agent.

Memory Bank System

Structure

Memory Bank lives in .agents/rules/memory-bank/.

Files:

  • brief.md (user‑only)
  • product.md
  • architecture.md
  • tech.md
  • context.md
  • tasks.md (optional)

brief.md: High‑level project description (read‑only for AI).
product.md: Goals, UX, features, requirements, roadmap.
architecture.md: System architecture, boundaries, flows, module rules.
tech.md: Coding standards, patterns, performance rules, testing rules.
context.md: Evolving decisions, key terms, domain rules, file summaries.
tasks.md: Repetitive workflows (test, refactor, review pipelines).

Startup Behavior

At the beginning of each task:

  1. Load all Memory Bank files.
  2. Print Memory Bank: Active if Memory Bank files loaded, otherwise Memory Bank: Missing.
  3. Summarize project in 3–6 bullets, using Memory Bank only.
  4. Use this reconstructed context for all reasoning.
  5. Do not scan project files unless user approves.

When the AI Must Use Memory Bank

Always reference Memory Bank before:

  • Designing or modifying architecture
  • Naming decisions
  • Implementing features
  • Applying coding standards
  • Testing
  • Refactoring
  • Reviewing for compliance
  • Preventing regressions

Memory Bank is the authoritative source of project rules.

When the AI Must NOT Read the Codebase

Do not scan files unless:

  • User says update memory bank
  • User says initialize memory bank
  • AI asks: I need to inspect files—OK to update Memory Bank?

This protects performance and context window.

Updating the Memory Bank

Triggered by explicit user commands or new essential info.

Update rules:

  1. Scan project directory (scoped or full).
  2. Extract only long‑term knowledge (not code).
  3. Update context.md first.
  4. Update architecture.md, tech.md, product.md if needed.
  5. Ask before overwriting major sections.
  6. Never store raw code, each file limit 300 lines.

Files the AI May Modify

Allowed: context.md, architecture.md, tech.md, product.md, tasks.md.
Forbidden (need user approval): brief.md.

Thread & Context Window Rules

If conversation drifts, AI should suggest:
Update Memory Bank and start a fresh thread?

A new thread must always reload Memory Bank.

Consistency Enforcement

AI must enforce consistency with:

  • architecture.md
  • tech.md
  • product.md
  • context.md

If user requests a conflicting change:

  • AI asks for confirmation
  • AI issues a consistency warning

Goals of the Memory Bank System

  • Reduce repetitive context loading
  • Prevent architectural drift
  • Maintain long‑term understanding
  • Improve coding quality
  • Minimize token overhead
  • Enable stable agentic workflows

Generic Programming Guidelines

These rules apply across languages, frameworks, and systems.

Performance Patterns

  • Use object pooling to reduce allocations.
  • Preallocate collections to avoid resizing.
  • Optimize data layout for cache locality.
  • Avoid unnecessary type conversions.
  • Use zero‑copy techniques when possible.
  • Minimize heap usage; prefer stack allocation.
  • Ensure escape analysis keeps values local.

Concurrency Guidelines

  • Limit concurrency with controlled pools.
  • Use atomic operations over locks for simple counters.
  • Apply lazy initialization for expensive work.
  • Share immutable data safely.
  • Use cancellation tokens for timeouts.

I/O Optimization

  • Use buffered I/O.
  • Batch reads/writes.
  • Use proper pooling for connections.

Generic Programming Principles

  • Use generics/templates for reusable, type‑safe code.
  • Apply type constraints to enforce correctness.
  • Use generic interfaces for polymorphism.
  • Prefer generic collections.
  • Reuse generic algorithms.

SOLID Principles

  • SRP: One responsibility per component.
  • OCP: Extend without modifying.
  • LSP: Subtypes must behave as base types.
  • ISP: Favor small, focused interfaces.
  • DIP: Depend on abstractions.

Idiomatic Practices

  • Keep functions small and focused.
  • Use descriptive names.
  • Avoid global state.
  • Favor composition over inheritance.
  • Keep interfaces minimal.
  • Maintain consistent abstraction levels.

Error Handling Best Practices

  • Always handle errors explicitly.
  • Don’t use exceptions for normal flow.
  • Use typed errors/enums.
  • Wrap errors with context.
  • Implement robust recovery paths.

Testing Strategies

  • Write unit tests for critical logic.
  • Use table‑driven tests.
  • Benchmark performance‑critical code.
  • Use mocks/stubs for external dependencies.
  • Use property‑based tests for generic logic.

Anti‑Patterns

  • Excessive concurrency
  • Large “god” interfaces
  • Ignoring errors
  • Overuse of reflection/dynamic typing
  • Tight coupling
  • Premature optimization

Generic Design Patterns

  • Factory
  • Strategy
  • Observer
  • Decorator
  • Command
  • Template Method

Memory Management

  • Understand target platform memory model.
  • Reduce object creation in hot paths.
  • Use value types where appropriate.
  • Dispose/close resources properly.
  • Profile memory usage.

Additional Best Practices

  • Design for composition and extensibility.
  • Use strong typing intentionally.
  • Balance generic vs. specific implementations.
  • Clearly document interfaces.
  • Maintain consistent coding conventions.

Combined Agent Behavior Summary

The AI Coder Agent must:

  • Load Memory Bank on every task.
  • Use Memory Bank as primary context.
  • Follow all programming best practices above.
  • Ensure architectural, naming, and coding consistency.
  • Avoid reading source unless asked.
  • Update Memory Bank only when user authorizes.
  • Warn about contradictions.
  • Never store raw code in Memory Bank.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment