Context Optimization Setup

Project context that persists across sessions in agentic_context/

What is Context Optimization?

Context Optimization is a structured directory (agentic_context/) that contains everything agents need to understand your project. Unlike conversation history that vanishes between sessions, optimized context persists—it's your project's institutional knowledge in a format agents can consume.

Key Opinion: Good context optimization = agents that understand your project. Poor context optimization = repeated explanations every session. The time you invest here pays dividends on every future interaction.

Think of Context Optimization as the onboarding documentation you'd give a new senior engineer, but optimized for AI consumption: structured, explicit, and free of assumptions.

Standard Structure

The recommended context structure covers all aspects of project context:

agentic_context/
├── project-overview.md     # What you're building
├── technical-setup.md      # Stack, environment, tools
├── current-work.md         # Active context and priorities
├── domain-expert.md        # Business domain knowledge
├── decisions/              # Architecture Decision Records
│   ├── 001-database-choice.md
│   ├── 002-auth-strategy.md
│   └── ...
├── implementations/        # Implementation guides
│   ├── feature-flags.md
│   ├── error-handling.md
│   └── ...
└── debt/                   # Technical debt tracking
    ├── known-issues.md
    └── refactoring-queue.md

Core Files

project-overview.md

The single most important file. Every agent reads this first.

# Project Overview

## What We're Building
[Product name] is a [type of product] that helps [target users]
to [core value proposition].

## Current State
- **Stage**: [MVP / Beta / Production / Scale]
- **Users**: [Active user count or range]
- **Team**: [Team size and structure]

## Architecture Summary
[2-3 sentence high-level description]

## Key Technologies
- **Frontend**: [Framework, key libraries]
- **Backend**: [Language, framework, key services]
- **Database**: [Type, hosted where]
- **Infrastructure**: [Cloud provider, key services]

## Repository Structure
```
/src
  /api        - Backend API handlers
  /web        - Frontend React app
  /shared     - Shared types and utilities
  /services   - Business logic services
/infra        - Terraform/Pulumi configs
/scripts      - Build and deployment scripts
```

## Getting Started
```bash
# Install dependencies
npm install

# Start development
npm run dev

# Run tests
npm test
```
Keep it current: Update project-overview.md whenever you make significant architecture changes, add major features, or change the tech stack.

technical-setup.md

Environment configuration and development setup details.

# Technical Setup

## Development Environment

### Prerequisites
- Node.js 20+ (recommend using nvm)
- Docker Desktop
- PostgreSQL 15+ (or use Docker)
- Redis 7+ (or use Docker)

### Environment Variables
```bash
# .env.local (copy from .env.example)
DATABASE_URL=postgresql://localhost:5432/myapp
REDIS_URL=redis://localhost:6379
STRIPE_SECRET_KEY=sk_test_...
SENDGRID_API_KEY=SG...
```

### Local Services
```bash
# Start all dependencies
docker-compose up -d

# Services available at:
# - PostgreSQL: localhost:5432
# - Redis: localhost:6379
# - MailHog (email testing): localhost:8025
```

## Build & Test

### Commands
| Command | Description |
|---------|-------------|
| npm run dev | Start development server |
| npm run build | Production build |
| npm test | Run unit tests |
| npm run test:e2e | Run E2E tests |
| npm run lint | Lint code |
| npm run typecheck | TypeScript check |

### CI Pipeline
Tests run on every PR:
1. Lint + Typecheck
2. Unit tests (Jest)
3. Integration tests (against test DB)
4. E2E tests (Playwright)

## Deployment

### Environments
| Environment | Branch | URL |
|-------------|--------|-----|
| Development | feature/* | Auto-deployed PR previews |
| Staging | main | staging.example.com |
| Production | release/* | app.example.com |

### Deploy Process
1. Merge to main → auto-deploy to staging
2. Create release branch → manual deploy to production
3. Rollback: `./scripts/rollback.sh <version>`

current-work.md

Active context that changes frequently. What's happening right now.

# Current Work

## Active Sprint (Sprint 23: Nov 11-22)

### Goals
1. Launch user notifications feature
2. Fix performance issues on dashboard
3. Migrate to new payment provider

### In Progress
- [ ] TASK-456: NotificationService implementation (@backend-agent)
- [ ] TASK-457: Notification UI components (@frontend-agent)
- [ ] TASK-458: Stripe → PaymentProvider migration (@backend-agent)

### Blocked
- TASK-459: E2E tests for notifications
  - Blocked by: TASK-456, TASK-457
  - Expected unblock: Nov 15

## Recent Context

### Just Completed (last 7 days)
- Upgraded to React 19
- Implemented rate limiting on public APIs
- Fixed memory leak in WebSocket handler

### Key Decisions Made
- Decided to use SendGrid over Postmark for email (see ADR-015)
- Postponed mobile app to Q1 (focus on web stability)

## Known Issues
- Dashboard slow for users with >1000 orders (optimization planned)
- Intermittent 504s on /api/reports (investigating)

## Upcoming
- Black Friday traffic prep (Nov 25-29)
- Annual security audit (Dec 1-15)
Update frequently: current-work.md should reflect reality. Stale context causes agents to make decisions based on outdated priorities. Update it at least weekly, ideally daily.

Decisions Directory (ADRs)

Architecture Decision Records capture the "why" behind significant choices.

# decisions/001-database-choice.md

# ADR-001: PostgreSQL for Primary Database

## Status
Accepted (2024-01-15)

## Context
We need a primary database for user data, orders, and product catalog.
Options considered: PostgreSQL, MySQL, MongoDB, DynamoDB.

## Decision
Use PostgreSQL with the following reasoning:
- Strong ACID guarantees for financial transactions
- Excellent JSON support for flexible schemas where needed
- Rich ecosystem of tools and extensions
- Team familiarity

## Consequences

### Positive
- Reliable transactions for payment processing
- JSONB columns give schema flexibility without losing structure
- PgBouncer handles connection pooling well

### Negative
- Need to manage connection limits carefully
- Complex migrations require planning
- No built-in horizontal sharding (may need Citus later)

## Related
- ADR-003: Connection pooling strategy
- ADR-007: Read replica setup

Implementations Directory

How-to guides for recurring patterns in your codebase.

# implementations/feature-flags.md

# Feature Flags Implementation

## Overview
We use LaunchDarkly for feature flags with a local fallback.

## Adding a New Flag

### 1. Define in LaunchDarkly
Create flag in LaunchDarkly dashboard with:
- Key: `feature-{name}` (kebab-case)
- Type: Boolean (most common) or Multivariate
- Default: false (off)

### 2. Add Type Definition
```typescript
// src/config/feature-flags.ts
export const FLAGS = {
  FEATURE_NOTIFICATIONS: 'feature-notifications',
  FEATURE_NEW_CHECKOUT: 'feature-new-checkout',
  // Add new flag here
} as const;
```

### 3. Use in Code
```typescript
import { useFlag } from '@/hooks/useFeatureFlag';

function MyComponent() {
  const showNotifications = useFlag('feature-notifications');

  if (!showNotifications) return null;
  return <NotificationBell />;
}
```

### 4. Backend Usage
```typescript
import { isEnabled } from '@/services/feature-flags';

if (await isEnabled('feature-notifications', user.id)) {
  // Feature-specific logic
}
```

## Rollout Process
1. Enable for internal users (email @company.com)
2. Enable for beta users (user.isBeta = true)
3. Enable for 10% → 50% → 100%
4. Remove flag after 2 weeks at 100%

Debt Directory

Track technical debt explicitly so agents know what to avoid or fix.

# debt/known-issues.md

# Known Issues

## Critical (Fix ASAP)

### Memory leak in WebSocket handler
- **Location**: src/services/websocket/handler.ts
- **Impact**: Server OOMs after ~48 hours
- **Workaround**: Restart pods daily (automated)
- **Fix**: Proper cleanup in disconnect handler
- **Owner**: @backend-team
- **ETA**: Sprint 24

## High (Fix Soon)

### N+1 queries on orders list
- **Location**: src/api/orders/list.ts
- **Impact**: Slow response for users with many orders
- **Workaround**: Pagination limits impact
- **Fix**: Implement DataLoader pattern
- **Owner**: Unassigned

## Medium (Scheduled)

### Legacy auth tokens still supported
- **Location**: src/middleware/auth.ts
- **Impact**: Technical debt, security surface
- **Workaround**: None needed
- **Fix**: Remove legacy token support after migration
- **Owner**: @security-team
- **ETA**: Q1 2025

## Low (When Convenient)

### Inconsistent error messages
- **Location**: Various API handlers
- **Impact**: Inconsistent client experience
- **Fix**: Standardize error format per API conventions

How Agents Use Context Optimization

When an agent receives a task, it loads relevant context files:

Task: "Add email notifications for order status changes"

Agent loads:
1. project-overview.md → Understand the project
2. current-work.md → Check if related work in progress
3. domain-expert.md → Understand order states and notification rules
4. implementations/feature-flags.md → How to gate the feature
5. decisions/008-email-provider.md → Which email service to use

Agent then executes with full context, making decisions consistent
with existing architecture and conventions.

Best Practices

Do

  • Be explicit: State assumptions, don't assume agents know conventions
  • Include examples: Code snippets are worth a thousand words
  • Explain why: Context behind decisions helps agents make similar choices
  • Keep files focused: One topic per file, under 2000 lines
  • Use headers: Well-structured docs are easier for agents to navigate

Don't

  • Don't duplicate: Reference existing docs instead of copying
  • Don't be vague: "Follow best practices" isn't actionable
  • Don't include secrets: No API keys, passwords, or tokens
  • Don't let it rot: Outdated docs are worse than no docs
Litmus test: Could a new senior engineer understand your project from these docs alone? If not, add what's missing.

Getting Started Checklist

Minimum viable context setup to get started:

  1. Create agentic_context/ directory
    mkdir -p agentic_context/decisions agentic_context/implementations agentic_context/debt
  2. Write project-overview.md (30 minutes)
  3. Write technical-setup.md (30 minutes)
  4. Write current-work.md (15 minutes)
  5. Document your top 3 architectural decisions (45 minutes)
  6. List known technical debt (15 minutes)

Total investment: ~2-3 hours for a solid foundation that will save you hours on every future agent interaction.

Next Steps

With your Memory Bank set up, you can automate Fulcrum in your CI/CD pipeline. Learn about CI/CD Integration to run automated reviews and quality checks on every PR.