# CAW Server

The CAW server provides REST API, MCP server, WebSocket bridge, and core content management features.

## Overview

The server is the central component of CAW, providing:

- **REST API** - HTTP endpoints for web client and CLI
- **MCP Server** - HTTP MCP server for Claude Code integration
- **WebSocket Bridge** - Real-time communication with browser extension tabs
- **Core** - Business logic layer (services, stores, entities)
- **Static File Hosting** - Serves the web client

## Architecture

```
┌─────────────────────────────────────────┐
│         API Layer (REST/MCP)            │  HTTP routes, MCP tools
│  (api/, mcp/)                           │  Auth via Bearer tokens
└─────────────────────────────────────────┘
                  ↓
┌─────────────────────────────────────────┐
│            Server.js                    │  Express app setup
│  (main.js)                              │  Port management
└─────────────────────────────────────────┘
                  ↓
┌─────────────────────────────────────────┐
│             Core Facade                 │  Token resolution
│  (core/Core.js)                         │  Service caching
│                                         │  Flat API
└─────────────────────────────────────────┘
                  ↓
┌─────────────────────────────────────────┐
│            Services Layer               │  Orchestration
│  (core/services/)                       │  Business workflows
│                                         │  Multi-store coordination
└─────────────────────────────────────────┘
                  ↓
┌─────────────────────────────────────────┐
│             Stores Layer                │  Data access
│  (core/stores/)                         │  Identity Map caching
│                                         │  CRUD operations
└─────────────────────────────────────────┘
                  ↓
┌─────────────────────────────────────────┐
│            Database Layer               │  SQLite
│  (db/)                                  │  Kysely query builder
└─────────────────────────────────────────┘
```

## Directory Structure

```
server/
├── src/
│   ├── main.js              # Entry point, server initialization
│   ├── Server.js            # Express app factory
│   ├── api/                 # REST API routes
│   │   ├── ProjectRoutes.js
│   │   ├── FolderRoutes.js
│   │   ├── DocumentRoutes.js
│   │   ├── TemplateRoutes.js
│   │   ├── FieldRoutes.js
│   │   ├── ExportRoutes.js
│   │   └── EventRoutes.js
│   ├── core/                # Business logic layer
│   │   ├── Core.js          # Facade - token resolution, service caching
│   │   ├── entities/        # Domain objects (read-only)
│   │   ├── services/        # Orchestration layer
│   │   └── stores/          # Data access + caching
│   ├── db/                  # Database layer
│   │   ├── Connection.js    # Database connection factory
│   │   ├── schema.js        # Table definitions
│   │   └── seed.js          # Initial data seeding
│   ├── mcp/                 # MCP server implementation
│   ├── wss/                 # WebSocket server
│   ├── static/              # Static files for web client
│   └── common/              # Shared utilities
└── test/                    # Test suites
    ├── unit/                # In-memory unit tests
    ├── integration/         # Real database integration tests
    └── component/           # Black-box HTTP tests via subprocess
```

## Port Configuration

The server uses the `CAW_PORT` environment variable:

```bash
CAW_PORT=2229 caw-server   # Default: 2229
```

## Building

```bash
# Build server only
bun run build

# Build client + server
bun run build:all
```

Output: `dist/main.js` (ES6 module for Node.js)

## Running

```bash
# Development (uses source files)
bun run dev

# Production (uses built files)
node dist/main.js
```

## Testing

```bash
# Run all tests
bun test

# Run specific test suite
bun test test/unit/
bun test test/integration/
bun test test/component/
```

Test types:
- **Unit** - In-memory tests (entities, utilities)
- **Integration** - Real database tests (stores, services)
- **Component** - Black-box HTTP tests (API routes, MCP tools)

## Tech Stack

- **Pure JavaScript** - ES6 modules, factory functions only
- **Express** - HTTP server framework
- **Kysely** - SQL query builder (type-safe)
- **better-sqlite3** - SQLite driver
- **ws** - WebSocket server
- **MCP SDK** - Model Context Protocol implementation
- **Bun** - Build tool (development and bundling)

## Distribution

Published to npm as `@kelceyp/caw-server`:

```bash
# Global install
npm install -g @kelceyp/caw-server

# Run
caw-server
```

## Key Features

### Token-Based Authentication

All API and MCP requests use Bearer tokens:

```bash
Authorization: Bearer <project-token>
```

Core facade resolves tokens to project context and caches services per project.

### Multi-Store System

Projects use a hierarchical store structure:
- **DemuxStore** - Routes operations to child stores
- **LocalStore A** - Project-specific content
- **LocalStore B** - Shared content across projects

### Identity Map Caching

Stores cache entities to ensure single object instance per ID:
- Cache checked before database queries
- Mutations update cache after DB commit (via onSuccess callbacks)
- Referential equality guaranteed

### Field System

Entity fields provide metadata storage:
- In-memory only (not persisted)
- Store-level defaults
- Single-valued and multi-valued fields
- Accessed via FieldService

## Development

See individual component READMEs:
- `/core/README.md` - Core architecture
- `/core/entities/README.md` - Domain entities
- `/core/services/README.md` - Service layer
- `/core/stores/README.md` - Data access layer
- `/api/README.md` - REST API routes
- `/db/README.md` - Database layer
- `/test/README.md` - Testing guide
