Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 184 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
# Copilot Instructions for ChatApp Backend

## Project Overview

ChatApp is a real-time messaging platform backend built with Java 21 and Spring Boot. It enables registered users to receive and respond to messages from anonymous users using WebSocket technology for real-time communication.

## Tech Stack

- **Language**: Java 21
- **Framework**: Spring Boot 3.5.0
- **Build Tool**: Maven
- **Database**: PostgreSQL with Flyway migrations
- **Real-time**: Spring WebSocket
- **Security**: Spring Security with JWT and OAuth 2.0 (Google)
- **ORM**: Spring Data JPA
- **Utilities**: Lombok, Jackson
- **Monitoring**: Spring Boot Actuator with Prometheus metrics
- **Caching**: Redis (Spring Data Redis)

## Build and Test Commands

### Build
```bash
mvn clean install
```

### Run Application
```bash
mvn spring-boot:run
```

### Run Tests
```bash
mvn test
```

### Generate Coverage Report
```bash
mvn verify
```

The application runs on `http://localhost:8080` by default.

## Project Structure

```
src/main/java/com/fredmaina/chatapp/
├── ChatappApplication.java # Main application entry point with @EnableCaching
├── Auth/ # Authentication and authorization module
│ ├── controllers/ # REST controllers for auth endpoints
│ ├── Dtos/ # Data Transfer Objects (note capitalization)
│ ├── Models/ # Entity models
│ ├── Repositories/ # JPA repositories
│ ├── services/ # Business logic (JWT, Auth)
│ ├── configs/ # Security configurations
│ └── exceptions/ # Exception handling
└── core/ # Core chat functionality
├── Controllers/ # Chat REST controllers
├── DTOs/ # Data Transfer Objects
├── models/ # Chat entity models
├── Repositories/ # Chat repositories
├── Services/ # Chat and messaging services
└── config/ # WebSocket and other configs
```

## Coding Conventions

### General Practices
- Use **Lombok** annotations to reduce boilerplate (`@Slf4j`, `@Data`, `@Builder`, etc.)
- Follow Spring Boot best practices and conventions
- Use constructor injection with `@Autowired` (or prefer constructor injection without @Autowired)
- Use `@Valid` annotation for request body validation
- Log important operations using SLF4J (`@Slf4j`)

### Naming Conventions
- **Controllers**: Suffix with `Controller` (e.g., `AuthController`, `ChatController`)
- **Services**: Suffix with `Service` (e.g., `AuthService`, `ChatService`)
- **DTOs**: Place in `Dtos/` or `DTOs/` directories (note mixed case in existing code)
- **Repositories**: Suffix with `Repository` and extend Spring Data JPA interfaces
- **Models/Entities**: Use JPA annotations (`@Entity`, `@Table`, etc.)

### Package Structure
- **Auth module**: Uses lowercase `controllers`, `services`, but capitalized `Dtos`, `Models`, `Repositories`
- **Core module**: Uses capitalized `Controllers`, `Services`, `DTOs`, etc.
- Maintain consistency within each module when adding new files

### REST API Conventions
- Base paths: `/api/auth` for authentication, `/api` for chat operations
- Return `ResponseEntity<T>` with appropriate HTTP status codes
- Use standard HTTP status codes:
- 200 OK for successful GET
- 201 Created for successful POST (registration)
- 401 Unauthorized for authentication failures
- 409 Conflict for duplicate resources
- Use `@RequestBody` for request payloads
- Use `@PathVariable` and `@RequestParam` for URL parameters

### Security
- **JWT Authentication**: Use for API authentication
- **Google OAuth 2.0**: Supported for social login
- **WebSocket Security**: Token-based for authenticated users, session-based for anonymous
- Always validate and sanitize user input
- Use Spring Security for endpoint protection
- Store sensitive configuration in environment variables

## Database

### Flyway Migrations
- Located in: `src/main/resources/db/migration/`
- Naming: `V{number}__{description}.sql` (e.g., `V1__create_users_table.sql`)
- Always create migrations for schema changes
- Never modify existing migration files

### Configuration
Use environment variables for database connection:
- `SPRING_DATASOURCE_URL`
- `SPRING_DATASOURCE_USERNAME`
- `SPRING_DATASOURCE_PASSWORD`

## WebSocket

- **Endpoint**: `/ws/chat`
- **Authenticated users**: Connect with JWT token as query parameter (`?token=<JWT>`)
- **Anonymous users**: Connect with `anonSessionId` in cookie
- Message types: `ANON_TO_USER`, `USER_TO_ANON`, `MARK_AS_READ`

## Testing

- Tests located in: `src/test/java/com/fredmaina/chatapp/`
- Use JUnit and Spring Boot Test annotations
- Mock dependencies appropriately
- Follow existing test patterns in `AuthServiceTest.java`
- Code coverage tracked with JaCoCo

## Environment Configuration

Configuration is in `src/main/resources/application.properties`. Use environment variables:

**Required**:
- `JWT_SECRET` - Secret key for JWT signing
- `GOOGLE_CLIENT_ID` - Google OAuth client ID
- `GOOGLE_SECRET_ID` - Google OAuth client secret
- `GOOGLE_REDIRECT_URI` - OAuth redirect URI

**Optional**:
- `security.allowed-origins` - CORS allowed origins
- `security.allowed-methods` - CORS allowed methods
- `security.allowed-headers` - CORS allowed headers

## Common Patterns

### Controller Pattern
```java
@Slf4j
@Controller
@RequestMapping("/api/...")
public class ExampleController {
@Autowired
private ExampleService service;

@PostMapping("/endpoint")
public ResponseEntity<ResponseDto> method(@Valid @RequestBody RequestDto request) {
// Implementation
}
}
```

### Service Pattern
- Business logic goes in services
- Services interact with repositories
- Use transactions where appropriate (`@Transactional`)

### Exception Handling
- Global exception handling is implemented
- Use custom exceptions when appropriate
- Return meaningful error messages in responses

## Additional Notes

- The application uses caching (Redis) - consider cache invalidation when modifying data
- Actuator endpoints available for monitoring
- Prometheus metrics exposed for observability
- Spring DevTools enabled for development
- Follow the contribution guidelines in `CONTRIBUTING.md`
61 changes: 61 additions & 0 deletions AGENTS.md
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the about this file just write its purpose. Use this AGENTS.md
A simple, open format for guiding coding agents,
used by over 60k open-source projects.

Think of AGENTS.md as a README for agents: a dedicated, predictable place to provide the context and instructions to help AI coding agents work on your project.

Explore Examples
View on GitHub

AGENTS.md

Setup commands

  • Install deps: pnpm install
  • Start dev server: pnpm dev
  • Run tests: pnpm test

Code style

  • TypeScript strict mode
  • Single quotes, no semicolons
  • Use functional patterns where possible
    Why AGENTS.md?
    README.md files are for humans: quick starts, project descriptions, and contribution guidelines.

AGENTS.md complements this by containing the extra, sometimes detailed context coding agents need: build steps, tests, and conventions that might clutter a README or aren’t relevant to human contributors.

We intentionally kept it separate to:

Give agents a clear, predictable place for instructions.

Keep READMEs concise and focused on human contributors.

Provide precise, agent-focused guidance that complements existing README and docs.

Rather than introducing another proprietary file, we chose a name and format that could work for anyone. If you’re building or using coding agents and find this helpful, feel free to adopt it.

One AGENTS.md works across many agents
Your agent definitions are compatible with a growing ecosystem of AI coding agents and tools:

Semgrep
Windsurf logo
Windsurf
from Cognition
goose
Gemini CLI
from Google
Jules
from Google
Ona logo
Ona
Codex
from OpenAI
VS Code logo
VS Code
Zed
Devin logo
Devin
from Cognition
Factory
Semgrep
Windsurf logo
Windsurf
from Cognition
goose
Gemini CLI
from Google
Jules
from Google
Ona logo
Ona
Codex
from OpenAI
VS Code logo
VS Code
Zed
Devin logo
Devin
from Cognition
Factory
Kilo Code
Cursor
Warp
Amp
Autopilot & Coded Agents
from UiPath
RooCode
Coding agent
from GitHub Copilot
opencode
Aider
Phoenix
Kilo Code
Cursor
Warp
Amp
Autopilot & Coded Agents
from UiPath
RooCode
Coding agent
from GitHub Copilot
opencode
Aider
Phoenix
View all supported agents
Examples

Sample AGENTS.md file

Dev environment tips

  • Use pnpm dlx turbo run where <project_name> to jump to a package instead of scanning with ls.
  • Run pnpm install --filter <project_name> to add the package to your workspace so Vite, ESLint, and TypeScript can see it.
  • Use pnpm create vite@latest <project_name> -- --template react-ts to spin up a new React + Vite package with TypeScript checks ready.
  • Check the name field inside each package's package.json to confirm the right name—skip the top-level one.

Testing instructions

  • Find the CI plan in the .github/workflows folder.
  • Run pnpm turbo run test --filter <project_name> to run every check defined for that package.
  • From the package root you can just call pnpm test. The commit should pass all tests before you merge.
  • To focus on one step, add the Vitest pattern: pnpm vitest run -t "<test name>".
  • Fix any test or type errors until the whole suite is green.
  • After moving files or changing imports, run pnpm lint --filter <project_name> to be sure ESLint and TypeScript rules still pass.
  • Add or update tests for the code you change, even if nobody asked.

PR instructions

  • Title format: [<project_name>] <Title>
  • Always run pnpm lint and pnpm test before committing.
    openai/codex
    General-purpose CLI tooling for AI coding agents.

Rust
Contributor avatarContributor avatarContributor avatar

  • 271
    apache/airflow
    Platform to programmatically author, schedule, and monitor workflows.

Python
Contributor avatarContributor avatarContributor avatar

  • 4023
    temporalio/sdk-java
    Java SDK for Temporal, workflow orchestration defined in code.

Java
Contributor avatarContributor avatarContributor avatar

  • 115
    PlutoLang/Pluto
    A superset of Lua 5.4 with a focus on general-purpose programming.

C++
Contributor avatarContributor avatarContributor avatar

  1. Add AGENTS.md
    Create an AGENTS.md file at the root of the repository. Most coding agents can even scaffold one for you if you ask nicely.
  2. Cover what matters
    Add sections that help an agent work effectively with your project. Popular choices:

Project overview
Build and test commands
Code style guidelines
Testing instructions
Security considerations
3. Add extra instructions
Commit messages or pull request guidelines, security gotchas, large datasets, deployment steps: anything you’d tell a new teammate belongs here too.
4. Large monorepo? Use nested AGENTS.md files for subprojects
Place another AGENTS.md inside each package. Agents automatically read the nearest file in the directory tree, so the closest one takes precedence and every subproject can ship tailored instructions. For example, at time of writing the main OpenAI repo has 88 AGENTS.md files.
About
AGENTS.md emerged from collaborative efforts across the AI software development ecosystem, including OpenAI Codex, Amp, Jules from Google, Cursor, and Factory.

We’re committed to helping maintain and evolve this as an open format that benefits the entire developer community, regardless of which coding agent you use.

FAQ
Are there required fields?
No. AGENTS.md is just standard Markdown. Use any headings you like; the agent simply parses the text you provide.
What if instructions conflict?
The closest AGENTS.md to the edited file wins; explicit user chat prompts override everything.
Will the agent run testing commands found in AGENTS.md automatically?
Yes—if you list them. The agent will attempt to execute relevant programmatic checks and fix failures before finishing the task.
Can I update it later?
Absolutely. Treat AGENTS.md as living documentation.
How do I migrate existing docs to AGENTS.md?
Rename existing files to AGENTS.md and create symbolic links for backward compatibility:

mv AGENT.md AGENTS.md && ln -s AGENTS.md AGENT.md
How do I configure Aider?
Configure Aider to use AGENTS.md in .aider.conf.yml:

read: AGENTS.md
How do I configure Gemini CLI?
Configure Gemini CLI to use AGENTS.md in .gemini/settings.json:

{ "contextFileName": "AGENTS.md" }
AGENTS.md
An open community standard stewarded by the Agentic AI Foundation (AAIF)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplified AGENTS.md following the agents.md format (commit c501e6d). Removed the "About This File" section and restructured with concise, practical sections: Setup commands, Tech stack, Code style, Project structure, Database migrations, API conventions, WebSocket, Security, and Testing. Also fixed environment variable names to use underscores (commit 3100eff).

Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# AGENTS.md

A guide for AI coding agents working on this repository.

## Setup commands
- Install dependencies: `mvn clean install`
- Start dev server: `mvn spring-boot:run`
- Run tests: `mvn test`
- Generate coverage report: `mvn verify`

## Tech stack
- Java 21
- Spring Boot 3.5.0
- PostgreSQL with Flyway migrations
- Spring Security with JWT and OAuth 2.0
- Spring WebSocket for real-time messaging
- Redis for caching
- Maven for build management

## Code style
- Use Lombok annotations (`@Slf4j`, `@Data`, `@Builder`) to reduce boilerplate
- Follow Spring Boot best practices and conventions
- Use constructor injection for dependencies
- Use `@Valid` annotation for request body validation
- Log important operations using SLF4J

## Project structure
- `src/main/java/com/fredmaina/chatapp/Auth/` - Authentication module (lowercase `controllers/`, `services/` but capitalized `Dtos/`, `Models/`, `Repositories/`)
- `src/main/java/com/fredmaina/chatapp/core/` - Core chat functionality (capitalized `Controllers/`, `Services/`, `DTOs/`)
- `src/main/resources/db/migration/` - Flyway database migrations
- `src/test/java/` - Test files

## Database migrations
- Location: `src/main/resources/db/migration/`
- Naming: `V{number}__{description}.sql` (e.g., `V1__create_users_table.sql`)
- Never modify existing migration files
- Always create new migrations for schema changes

## API conventions
- Auth endpoints: `/api/auth`
- Chat endpoints: `/api`
- Return `ResponseEntity<T>` with appropriate HTTP status codes
- Use standard status codes: 200 OK, 201 Created, 401 Unauthorized, 409 Conflict

## WebSocket
- Endpoint: `/ws/chat`
- Authenticated users: JWT token as query parameter (`?token=<JWT>`)
- Anonymous users: Session ID in cookie
- Message types: `ANON_TO_USER`, `USER_TO_ANON`, `MARK_AS_READ`

## Security
- JWT authentication for API endpoints
- Google OAuth 2.0 for social login
- Store sensitive config in environment variables (`JWT_SECRET`, `GOOGLE_CLIENT_ID`, etc.)
- Always validate and sanitize user input

## Testing
- Tests in: `src/test/java/com/fredmaina/chatapp/`
- Use JUnit 5 and Spring Boot Test annotations
- Mock dependencies with Mockito
- Follow existing patterns in `AuthServiceTest.java`