Skip to main content
This is your reference library. Copy, adapt, and use these examples in your projects.

Dev Container Examples

Node.js + TypeScript + PostgreSQL

{
  "name": "Node.js Full Stack",
  "image": "mcr.microsoft.com/devcontainers/typescript-node:20",
  "features": {
    "ghcr.io/devcontainers/features/docker-in-docker:2": {},
    "ghcr.io/devcontainers/features/github-cli:1": {},
    "ghcr.io/devcontainers-contrib/features/postgres-asdf:1": {
      "version": "15"
    }
  },
  "customizations": {
    "vscode": {
      "extensions": [
        "dbaeumer.vscode-eslint",
        "esbenp.prettier-vscode",
        "bradlc.vscode-tailwindcss"
      ],
      "settings": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "esbenp.prettier-vscode",
        "editor.codeActionsOnSave": {
          "source.fixAll.eslint": true
        }
      }
    }
  },
  "forwardPorts": [3000, 5432],
  "postCreateCommand": "npm install && npm run db:migrate",
  "remoteUser": "node"
}

Python + Data Science Tools

{
  "name": "Python Data Science",
  "image": "mcr.microsoft.com/devcontainers/python:3.11",
  "features": {
    "ghcr.io/devcontainers/features/common-utils:2": {
      "installZsh": true
    }
  },
  "customizations": {
    "vscode": {
      "extensions": [
        "ms-python.python",
        "ms-python.vscode-pylance",
        "ms-toolsai.jupyter",
        "charliermarsh.ruff"
      ],
      "settings": {
        "python.defaultInterpreterPath": "/usr/local/bin/python",
        "python.linting.enabled": true,
        "python.formatting.provider": "black"
      }
    }
  },
  "postCreateCommand": "pip install -r requirements.txt",
  "forwardPorts": [8888]
}

Go + Kubernetes Tools

{
  "name": "Go + Kubernetes",
  "image": "mcr.microsoft.com/devcontainers/go:1.21",
  "features": {
    "ghcr.io/devcontainers/features/docker-in-docker:2": {},
    "ghcr.io/devcontainers/features/kubectl-helm-minikube:1": {
      "version": "latest"
    },
    "ghcr.io/devcontainers-contrib/features/gh-cli:1": {}
  },
  "customizations": {
    "vscode": {
      "extensions": [
        "golang.go",
        "ms-kubernetes-tools.vscode-kubernetes-tools"
      ]
    }
  },
  "postCreateCommand": "go mod download"
}

React + Next.js

{
  "name": "Next.js App",
  "image": "mcr.microsoft.com/devcontainers/typescript-node:20",
  "features": {
    "ghcr.io/devcontainers/features/github-cli:1": {}
  },
  "customizations": {
    "vscode": {
      "extensions": [
        "dbaeumer.vscode-eslint",
        "esbenp.prettier-vscode",
        "bradlc.vscode-tailwindcss",
        "dsznajder.es7-react-js-snippets"
      ],
      "settings": {
        "editor.formatOnSave": true,
        "typescript.tsdk": "node_modules/typescript/lib",
        "typescript.enablePromptUseWorkspaceTsdk": true
      }
    }
  },
  "forwardPorts": [3000],
  "postCreateCommand": "npm install"
}

Rust Development

{
  "name": "Rust",
  "image": "mcr.microsoft.com/devcontainers/rust:1",
  "features": {
    "ghcr.io/devcontainers/features/docker-in-docker:2": {}
  },
  "customizations": {
    "vscode": {
      "extensions": [
        "rust-lang.rust-analyzer",
        "tamasfe.even-better-toml",
        "serayuzgur.crates"
      ]
    }
  },
  "postCreateCommand": "cargo build"
}

Multi-Container: Backend + Frontend

.devcontainer/docker-compose.yml:
version: '3.8'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - ../:/workspace:cached
    command: sleep infinity
    depends_on:
      - postgres
      - redis

  postgres:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: devdb
    volumes:
      - postgres-data:/var/lib/postgresql/data

  redis:
    image: redis:7

volumes:
  postgres-data:
.devcontainer/devcontainer.json:
{
  "name": "Multi-Container App",
  "dockerComposeFile": "docker-compose.yml",
  "service": "app",
  "workspaceFolder": "/workspace",
  "forwardPorts": [3000, 5432, 6379],
  "customizations": {
    "vscode": {
      "extensions": ["ms-azuretools.vscode-docker"]
    }
  }
}

Automation Examples

Full-Stack App with Database

services:
  postgres:
    name: PostgreSQL
    description: PostgreSQL database
    triggeredBy:
      - postDevcontainerStart
    runsOn:
      docker:
        image: postgres:15
        environment:
          - POSTGRES_PASSWORD=postgres
          - POSTGRES_DB=appdb
          - POSTGRES_USER=postgres
    commands:
      start: postgres
      ready: pg_isready -h localhost

  redis:
    name: Redis Cache
    description: Redis cache
    triggeredBy:
      - postDevcontainerStart
    runsOn:
      docker:
        image: redis:7-alpine
    commands:
      start: redis-server
      ready: redis-cli ping

  backend:
    name: API Server
    description: API server
    triggeredBy:
      - postDevcontainerStart
    commands:
      start: npm run server
      ready: curl -sf http://localhost:3000/health

tasks:
  install:
    name: Install Dependencies
    description: Install dependencies
    triggeredBy:
      - postDevcontainerStart
    command: npm install

  migrate:
    name: Run Migrations
    description: Run database migrations
    dependsOn:
      - install
    command: npm run db:migrate

  seed:
    name: Seed Data
    description: Seed database with test data
    triggeredBy:
      - manual
    dependsOn:
      - migrate
    command: npm run db:seed

  test:
    name: Run Tests
    description: Run test suite
    triggeredBy:
      - manual
    dependsOn:
      - install
    command: npm test

Python + Flask + PostgreSQL

services:
  postgres:
    name: PostgreSQL
    triggeredBy:
      - postDevcontainerStart
    runsOn:
      docker:
        image: postgres:15
        environment:
          - POSTGRES_PASSWORD=dev
          - POSTGRES_DB=flaskapp
    commands:
      start: postgres
      ready: pg_isready -h localhost

  flask:
    name: Flask Server
    triggeredBy:
      - postDevcontainerStart
    commands:
      start: flask run --host=0.0.0.0 --port=5000
      ready: curl -sf http://localhost:5000/health

tasks:
  install:
    name: Install Dependencies
    triggeredBy:
      - postDevcontainerStart
    command: pip install -r requirements.txt

  init-db:
    name: Initialize Database
    dependsOn:
      - install
    command: flask db upgrade

  test:
    name: Run Tests
    triggeredBy:
      - manual
    command: pytest

Monorepo: Frontend + Backend + Services

services:
  postgres:
    name: PostgreSQL
    triggeredBy:
      - postDevcontainerStart
    runsOn:
      docker:
        image: postgres:15
        environment:
          - POSTGRES_PASSWORD=pw
    commands:
      start: postgres
      ready: pg_isready -h localhost

  rabbitmq:
    name: RabbitMQ
    triggeredBy:
      - postDevcontainerStart
    runsOn:
      docker:
        image: rabbitmq:3-management
    commands:
      start: rabbitmq-server
      ready: rabbitmqctl status

  backend:
    name: Backend
    triggeredBy:
      - postDevcontainerStart
    commands:
      start: cd backend && npm run dev
      ready: curl -sf http://localhost:3001/health

  frontend:
    name: Frontend
    triggeredBy:
      - postDevcontainerStart
    commands:
      start: cd frontend && npm run dev
      ready: curl -sf http://localhost:3000

  worker:
    name: Worker
    triggeredBy:
      - postDevcontainerStart
    commands:
      start: cd worker && npm run start

tasks:
  install-all:
    name: Install All Dependencies
    triggeredBy:
      - postDevcontainerStart
    command: |
      npm install &&
      cd backend && npm install &&
      cd ../frontend && npm install &&
      cd ../worker && npm install

  build-all:
    name: Build All
    triggeredBy:
      - manual
    command: npm run build:all

Microservices with Docker Compose

services:
  compose:
    name: Docker Compose Stack
    description: Start all microservices
    triggeredBy:
      - postDevcontainerStart
    commands:
      start: docker-compose up
      stop: docker-compose down

tasks:
  rebuild:
    name: Rebuild Services
    description: Rebuild and restart services
    triggeredBy:
      - manual
    command: docker-compose up --build -d

Testing & Linting Pipeline

tasks:
  install:
    name: Install Dependencies
    triggeredBy:
      - postDevcontainerStart
    command: npm install

  lint:
    name: Lint
    description: Run ESLint
    triggeredBy:
      - manual
    command: npm run lint

  format:
    name: Format
    description: Format code with Prettier
    triggeredBy:
      - manual
    command: npm run format

  type-check:
    name: Type Check
    description: TypeScript type checking
    triggeredBy:
      - manual
    command: npm run type-check

  test-unit:
    name: Unit Tests
    description: Run unit tests
    triggeredBy:
      - manual
    command: npm run test:unit

  test-integration:
    name: Integration Tests
    description: Run integration tests
    triggeredBy:
      - manual
    command: npm run test:integration

  test-e2e:
    name: E2E Tests
    description: Run end-to-end tests
    triggeredBy:
      - manual
    command: npm run test:e2e

AGENTS.md Examples

Next.js + React App

# Agent Context for MyApp

## Tech Stack

- Next.js 14 (App Router, not Pages Router)
- React 18 with TypeScript
- Tailwind CSS for styling
- Prisma ORM with PostgreSQL
- tRPC for type-safe APIs

## Project Structure

/app              - Next.js app router pages
/components       - Reusable React components
/lib              - Utilities and helpers
/server           - Backend code (tRPC routers, database)
/prisma           - Database schema and migrations

## Code Conventions

**Components:**
- Use named exports: `export function Button() {}`
- Server Components by default; add `"use client"` only when needed
- Co-locate styles: Button.tsx and Button.module.css together

**API Layer:**
- All database queries through tRPC procedures
- Never call Prisma directly from components
- Procedures in `/server/routers/[domain].ts`

**Error Handling:**
- Use `TRPCError` for API errors
- Use error boundaries for React errors
- Log errors to console in dev, monitoring service in prod

**Styling:**
- Tailwind utility classes preferred
- Custom CSS only for complex animations
- Mobile-first responsive design

## Testing

- Unit tests: `*.test.ts` (Vitest)
- Component tests: `*.spec.tsx` (React Testing Library)
- E2E tests: `/e2e/*.spec.ts` (Playwright)

Run before committing:
```bash
npm run lint
npm test
npm run type-check
```

## Common Tasks

**Adding a new page:**
1. Create `/app/[route]/page.tsx`
2. Use Server Components by default
3. Fetch data with tRPC server-side

**Adding an API endpoint:**
1. Create procedure in `/server/routers/[domain].ts`
2. Add to router exports
3. Write integration test
4. Update API docs

**Database changes:**
1. Edit `prisma/schema.prisma`
2. Run `npm run db:migrate`
3. Update seed data if needed

## Before Pushing

- Ensure tests pass
- Check TypeScript compiles
- Verify build succeeds: `npm run build`
- Preview changes in dev: `npm run dev`

Python FastAPI Backend

# Agent Context for API Service

## Tech Stack

- Python 3.11 with FastAPI
- SQLAlchemy ORM with PostgreSQL
- Pydantic for validation
- Pytest for testing
- Docker for deployment

## Project Structure

/app
  /api           - API route handlers
  /models        - SQLAlchemy models
  /schemas       - Pydantic schemas
  /services      - Business logic
  /db            - Database connection and migrations
/tests           - Test files mirror /app structure

## Code Conventions

**Naming:**
- snake_case for functions, variables, files
- PascalCase for classes
- SCREAMING_SNAKE_CASE for constants

**Imports:**
```python
# Standard library
import os
from datetime import datetime

# Third-party
from fastapi import FastAPI
from sqlalchemy import select

# Local
from app.models import User
from app.services import auth_service
```

**Type Hints:**
Always use type hints:
```python
def get_user(user_id: int) -> User | None:
    ...
```

**Error Handling:**
```python
from fastapi import HTTPException

raise HTTPException(status_code=404, detail="User not found")
```

## Testing

```python
# /tests/test_users.py
def test_get_user_success():
    # Arrange
    ...
    # Act
    ...
    # Assert
    ...
```

Run tests:
```bash
pytest
pytest --cov  # with coverage
```

## Common Tasks

**New endpoint:**
1. Add route in `/app/api/[domain].py`
2. Create schema in `/app/schemas/[domain].py`
3. Add service logic in `/app/services/[domain].py`
4. Write tests in `/tests/test_[domain].py`

**Database changes:**
1. Update models in `/app/models/`
2. Generate migration: `alembic revision --autogenerate -m "description"`
3. Review and edit migration file
4. Apply: `alembic upgrade head`

## Before Committing

```bash
black .           # Format code
ruff check .      # Lint
mypy app/         # Type check
pytest            # Run tests
```

Go Microservice

# Agent Context for User Service

## Tech Stack

- Go 1.21
- Gin web framework
- GORM for database
- PostgreSQL
- Docker + Kubernetes

## Project Structure

/cmd/server      - Main application entry
/internal
  /handlers      - HTTP handlers
  /models        - Data models
  /services      - Business logic
  /repository    - Database layer
/pkg             - Public libraries
/tests           - Integration tests

## Code Conventions

**Naming:**
- Exported: PascalCase (public)
- Unexported: camelCase (private)
- Interfaces: end with -er (Reader, Writer)

**Error Handling:**
```go
if err != nil {
    return fmt.Errorf("failed to get user: %w", err)
}
```

**Package Organization:**
Each package has a clear responsibility. Don't mix concerns.

## Testing

```go
func TestGetUser(t *testing.T) {
    // Setup
    // Execute
    // Assert
    // Cleanup
}
```

Run tests:
```bash
go test ./...
go test -cover ./...
```

## Common Tasks

**New endpoint:**
1. Add handler in `/internal/handlers/`
2. Add service method in `/internal/services/`
3. Add repository method if needed
4. Register route in `/cmd/server/main.go`
5. Write test

**Database migration:**
We use GORM AutoMigrate for dev, manual SQL for production.

## Before Pushing

```bash
go fmt ./...
go vet ./...
golangci-lint run
go test ./...
```

Skill Examples

These prompts can be used as organization-level skills. Create each one in Settings > Agents > New Skill, and optionally enable the slash command toggle with the trigger shown.

/pr - Create Pull Request

Create a pull request for the current branch:

1. Run `!git status` to see changes
2. Run `!git log origin/main..HEAD --oneline` to see commits
3. Create a concise PR title following our convention:
   - Format: `type(scope): description`
   - Types: feat, fix, docs, refactor, test, chore
   - Example: `feat(auth): add password reset flow`
4. Write a PR description with:
   - **Summary**: What changed (2-3 sentences)
   - **Why**: Why this change was needed
   - **Testing**: How it was tested
5. Run `gh pr create --title "[title]" --body "[body]"`
6. Share the PR URL

/review - Code Review

Review the code changes in the current branch:

1. Run `!git diff main...HEAD` to see all changes
2. Review for:
   - **Security**: SQL injection, XSS, auth bypass, secret exposure
   - **Bugs**: Logic errors, edge cases, null handling
   - **Performance**: N+1 queries, unnecessary loops, memory leaks
   - **Maintainability**: Complex code, missing docs, inconsistent style
   - **Tests**: Missing test coverage for new code
3. Provide specific feedback with:
   - File names and line numbers
   - What's wrong
   - How to fix it
4. Highlight what's done well
5. Rate severity: Critical / Important / Nice-to-have

/test - Generate Tests

Generate comprehensive tests for the code I specify.

Process:
1. Ask me which file or function to test
2. Read the code to understand its behavior
3. Check existing tests to match our style
4. Write tests covering:
   - Happy path (normal use)
   - Edge cases (empty inputs, max values)
   - Error cases (invalid inputs, exceptions)
   - Boundary conditions
5. Mock external dependencies (APIs, databases, file system)
6. Run the tests: `npm test` or `pytest` or appropriate command
7. Show results and coverage

Follow our testing conventions in existing test files.

/docs - Update Documentation

Update documentation for recent code changes:

1. Run `!git diff main...HEAD --name-only` to see changed files
2. Identify user-facing or API changes
3. Check if these changes are documented:
   - README.md
   - API docs
   - Code comments
   - CHANGELOG.md
4. Update documentation:
   - Match existing doc style
   - Include code examples
   - Note breaking changes
   - Update version numbers if needed
5. Commit docs with message: `docs: update for [feature/fix]`

/fix-ci - Fix Failing CI

The CI build is failing. Debug and fix it:

1. Run `!gh pr checks` to see failing checks
2. Get details: `!gh pr checks --json name,conclusion,detailsUrl`
3. Read error logs (check GitHub Actions tab or use URL from above)
4. Identify root cause:
   - Test failures?
   - Lint errors?
   - Type errors?
   - Build failure?
5. Fix the issue
6. Test locally:
   - Tests: `npm test`
   - Lint: `npm run lint`
   - Types: `npm run type-check`
   - Build: `npm run build`
7. Commit fix
8. Push and verify CI passes

Explain what was wrong and how you fixed it.

/security - Security Audit

Perform a security audit of the specified code:

Focus on:
1. **Input validation**: Are user inputs sanitized?
2. **SQL injection**: Are queries parameterized?
3. **XSS**: Is user content escaped in UI?
4. **Authentication**: Are protected routes actually protected?
5. **Authorization**: Can users access others' data?
6. **Secrets**: Are API keys/passwords hardcoded?
7. **Dependencies**: Any known vulnerable packages?
8. **Rate limiting**: Are expensive operations rate-limited?
9. **CORS**: Is CORS configured correctly?
10. **Error messages**: Do errors leak sensitive info?

For each issue found:
- File and line number
- Vulnerability type
- Risk level (Critical/High/Medium/Low)
- How to exploit it
- How to fix it

Run security tools if available: `npm audit`, `snyk test`, etc.

/optimize - Performance Optimization

Analyze and optimize performance of the specified code:

1. Identify the file/function to optimize
2. Profile if possible:
   - Node.js: `node --prof`
   - Python: `py-spy`
   - Browser: Chrome DevTools
3. Look for:
   - **Database**: N+1 queries, missing indexes, large payloads
   - **Loops**: Nested loops, array methods inside loops
   - **Memory**: Leaks, unnecessary data retention
   - **Network**: Too many requests, large responses, no caching
   - **Rendering**: Unnecessary re-renders, large DOMs
4. Propose optimizations with:
   - Current performance metrics
   - Expected improvement
   - Trade-offs (complexity vs speed)
5. Implement optimizations
6. Measure improvement

/refactor - Code Refactoring

Refactor the specified code to improve maintainability:

1. Identify the code to refactor
2. Current issues:
   - Too long/complex?
   - Duplicated logic?
   - Poor naming?
   - Mixed concerns?
3. Refactoring plan:
   - Extract functions/classes
   - Rename for clarity
   - Simplify logic
   - Remove duplication
4. **Important**: Keep behavior identical
5. Run tests after each change
6. Commit incrementally: `refactor: [what you improved]`

Use these techniques:
- Extract function
- Extract variable
- Inline function/variable
- Rename
- Move to appropriate file

Agent Prompt Examples

Debugging

Find the bug:
The login form submits but nothing happens. Debug /components/LoginForm.tsx:
1. Check if the submit handler is called
2. Check if the API call is made
3. Check error handling
4. Add console.logs to trace execution
5. Identify and fix the issue
Reproduce and fix:
Users report clicking "Save" multiple times creates duplicate records.
Reproduce this issue, find the root cause, and fix it.
Add protection against double-submissions.

Feature Development

Complete feature:
Implement "forgot password" flow:
1. Add form at /forgot-password with email input
2. Create API endpoint POST /api/auth/forgot-password
3. Generate password reset token (expires in 1 hour)
4. Send email with reset link (use existing email service)
5. Create /reset-password/[token] page
6. Add API endpoint POST /api/auth/reset-password
7. Validate token, update password, invalidate token
8. Write tests for both endpoints
9. Update AGENTS.md with this flow
Enhance existing:
Enhance the search feature:
1. Add fuzzy matching (tolerate typos)
2. Add filters for date range, status, category
3. Highlight matched terms in results
4. Add "Did you mean..." suggestions for no results
5. Show search result count
6. Add loading state while searching

Maintenance

Update dependencies:
Update all npm dependencies safely:
1. Run `npm outdated` to see what's outdated
2. Check CHANGELOGs for breaking changes
3. Update patch/minor versions first: `npm update`
4. Test that everything still works
5. Update major versions one at a time
6. Run full test suite after each major update
7. Fix any breaking changes
8. Commit: `chore: update dependencies`
Clean up code:
Clean up /lib/utils.ts:
1. Remove unused functions (search for references)
2. Add missing type annotations
3. Add JSDoc comments for exported functions
4. Extract complex logic into smaller functions
5. Improve function names for clarity
6. Run tests to ensure nothing breaks

Documentation

Generate API docs:
Generate API documentation for all endpoints in /api:
1. List all endpoints (method + path)
2. For each endpoint document:
   - Description
   - Request parameters
   - Request body schema
   - Response schema
   - Error responses
   - Example request/response
3. Save to docs/API.md in markdown format
4. Use code examples in curl and JavaScript
Architecture diagram:
Create a Mermaid diagram showing our system architecture:
1. Read codebase to understand components
2. Identify: frontend, backend, databases, external services
3. Show data flow between components
4. Label technologies used (Next.js, PostgreSQL, Redis, etc.)
5. Add to docs/ARCHITECTURE.md with explanation

Common Workflows

Morning Startup

1. Start environment from GitHub issue
2. Agent reads issue and asks clarifying questions
3. Agent creates plan
4. You review and approve plan
5. Agent implements
6. You review code
7. Agent creates PR
8. You merge

Bug Triage

1. Create environment for bug report
2. Agent reproduces the bug
3. Agent identifies root cause
4. Agent proposes fix
5. You approve approach
6. Agent implements fix
7. Agent writes regression test
8. You verify fix works

Parallel Feature Work

1. Start 3 environments for 3 features
2. Assign each agent a feature
3. All agents work simultaneously
4. Review each PR independently
5. Merge when ready (no waiting for others)

Code Review Session

1. Start environment from PR branch
2. Agent: `/review` - comprehensive review
3. Agent identifies 5 issues
4. You: "Fix the critical and important ones"
5. Agent makes fixes
6. Agent commits: `fix: address code review feedback`
7. You approve PR

Weekly Maintenance

Environment 1: `Update dependencies and run tests`
Environment 2: `Find all TODO comments and create GitHub issues`
Environment 3: `Update API docs for recent changes`

All run in parallel. Review results at end.

Quick Reference

Environment Classes

  • Standard: 4 cores, 8GB RAM (most development)
  • Large: 8 cores, 16GB RAM (large builds, heavy tests)
  • GPU: NVIDIA T4 (ML training, GPU workloads)

Port Forwarding

# In devcontainer.json
"forwardPorts": [3000, 5432, 6379]

# Or via CLI
gitpod environment port open 8080
gitpod environment port list

Automation Commands

gitpod automations update              # Apply .ona/automations.yaml
gitpod automations service list        # List services and their status
gitpod automations service start <id>  # Start a service
gitpod automations service stop <id>   # Stop a service
gitpod automations service logs <id>   # View service logs
gitpod automations task list           # List tasks
gitpod automations task start <id>     # Run a task
gitpod automations task logs <id>      # View task logs

Secrets Commands

gitpod user secret create --name VAR --value "value"      # Create user secret
gitpod user secret list                                   # List user secrets
gitpod project secret create --name VAR --value "val"     # Create project secret
gitpod project secret list                                # List project secrets

Starting Environments

From the dashboard:
1. Go to app.ona.com
2. Click "New Environment" or select a Project
3. Enter repository URL, choose branch, select environment class
4. Click "Create"
From browser extension:
Install Ona browser extension on GitHub/GitLab/Bitbucket
Click "Open in Ona" button on any repository page
From Projects:
Navigate to Projects at app.ona.com
Click "Launch Environment" on your project

Pro tip: Bookmark this page for quick reference while working!