Service Architecture
**Status Legend**: โ **Live** (production-ready) | ๐ง **Beta** (functional, incomplete) | ๐ฎ **Planned** (designed but not built)
Full Public Reader
Service Architecture
Status Legend: โ Live (production-ready) | ๐ง Beta (functional, incomplete) | ๐ฎ Planned (designed but not built)
System Overview
TrajectoryOS is built as a microservices architecture with clear separation of concerns:
graph TB
Client[Web Dashboard / Mobile]
Gateway[API Gateway :8080]
Client -->|HTTP/WS| Gateway
Gateway -->|REST| Core[Trajectory Core :3003]
Gateway -->|REST| Agent[Agent Orchestrator :3004]
Gateway -->|REST| Bridge[Echelon Bridge :3005]
Core -->|HTTP| SkillModel[Skill Graph Model :5001]
Core -->|HTTP| AlignModel[Alignment Scorer :5002]
Core -->|HTTP| GravityModel[Gravity/Mass :5003]
Core -->|HTTP| StateModel[Life State Model :5004]
Core -->|Query| DB[(PostgreSQL/SQLite)]
Core -->|Query| Vector[(Vector Store)]
Agent -->|LLM API| OpenAI[OpenAI/Anthropic]
Agent -->|Store| Vector
Bridge -.->|WS| Echelon[Echelon Engine]
Bridge -->|Store| DB
Gateway -->|Pub/Sub| Redis[(Redis)]
Core -->|Pub/Sub| Redis
Agent -->|Pub/Sub| Redis
style Echelon stroke-dasharray: 5 5
style Redis fill:#ffcccc
style DB fill:#ccf
f
style Vector fill:#ccfService Descriptions
1. API Gateway (`:8080`)
Status: ๐ฎ Planned - Currently requests go directly to services
Technology: Node.js + Express/Fastify
Responsibility: Unified entry point for all client requests
Features:
- REST API proxying to backend services
- WebSocket server for real-time updates
- Authentication (JWT validation)
- Rate limiting
- Request logging
Endpoints:
GET /health โ Health check
POST /auth/login โ User authentication
POST /auth/refresh โ Token refresh
/api/trajectory/* โ Proxy to trajectory-core
/api/agent/* โ Proxy to agent-orchestrator
/api/echelon/* โ Proxy to echelon-bridgeWebSocket Events:
- `state_updated` - Life state changed
- `interview_message` - Agent sent message
- `evidence_added` - New skill evidence
- `escape_index_changed` - ฮท crossed threshold
- `analysis_ready` - Background insights available
---
2. Trajectory Core (`:3003`)
Status: โ Live - Core physics, state management, and API fully functional
Technology: Node.js + TypeScript + Prisma ORM
Database: SQLite (currently used) | PostgreSQL (documented for production)
Responsibility: Core life physics engine and state management
Key Modules:
#### Domain Layer (`src/domain/`)
- `types.ts` - TypeScript interfaces for core models
- `physics.ts` - Physics computations (thrust, ฮท, escape velocity)
- `skillGraph.ts` - Skill graph with Bayesian tracking
#### Service Layer (`src/services/`)
- `LifeStateService.ts` - State persistence and retrieval
- `SkillService.ts` - Skill graph operations
- `ProjectService.ts` - Project management
- `EvidenceService.ts` - Evidence integration
#### API Layer (`src/index.ts`)
- Express server
- REST endpoints
- Error handling
- Validation (Zod)
Key Endpoints:
# Life State
GET /api/state/:userId โ Current life state
GET /api/state/:userId/history โ State history
POST /api/state/:userId/update โ Manual state update
# Skills
GET /api/skills โ All skills
GET /api/skills/graph โ Skill graph
POST /api/skills/:id/evidence โ Add evidence
GET /api/skills/:id/belief โ Bayesian posterior
# Projects
GET /api/projects/:userId โ User's projects
POST /api/projects โ Create project
PUT /api/projects/:id โ Update project
DELETE /api/projects/:id โ Archive project
# Physics
GET /api/physics/:userId โ Current physics snapshot
GET /api/physics/:userId/breakdown โ Detailed breakdown
POST /api/physics/simulate โ Scenario simulationIntegration with Python Models:
- HTTP calls to Python microservices
- Caching layer (Redis) for expensive computations
- Async job queue for batch updates
---
3. Agent Orchestrator (`:3004`)
Status: ๐ง Beta - Basic endpoints exist, LLM integration pending
Technology: Node.js + TypeScript + OpenAI/Anthropic SDK (planned)
Responsibility: LLM-powered interview and planning
Current Reality: Interview endpoints (`/start`, `/message`, `/complete`) exist and return mock responses. No actual LLM integration yet. Planned for Q1 2026.
Key Modules:
#### Agents (`src/agents/`)
- `InterviewAgent.ts` - Conversational interviewer
- `PlannerAgent.ts` - Background analysis and planning
- `EvidenceExtractor.ts` - Structured output parsing
#### Flows (`src/flows/`)
- `SkillDiscoveryFlow.ts` - Skill interview flow
- `ProjectAssessmentFlow.ts` - Project alignment flow
- `ConstraintMappingFlow.ts` - Gravity identification
#### Scheduler (`src/scheduler/`)
- `BackgroundJobs.ts` - Periodic analysis tasks
- Job queue (Bull/BullMQ)
Key Endpoints:
# Interview
POST /api/interview/start โ Start session
POST /api/interview/:id/message โ Send user message
POST /api/interview/:id/complete โ End session
GET /api/interview/:id โ Get session details
# Background Analysis
POST /api/analysis/trigger โ Trigger analysis
GET /api/analysis/:id โ Get results
GET /api/analysis/:userId/latest โ Latest insights
# Planning
POST /api/plans/generate โ Generate action plan
GET /api/plans/:userId โ User's plans
PUT /api/plans/:id/progress โ Update progressLLM Integration:
- Prompt templates with versioning
- Structured output (instructor library)
- Token usage tracking
- Fallback handling
---
4. Echelon Bridge (`:3005`)
Status: ๐ง Beta - Stub service with basic endpoints, integration planned Q1-Q2 2026
Technology: Node.js + TypeScript
Responsibility: Interface to Echelon engine (computational choreography integration)
Current Reality: Stub service returning mock session data. Awaiting Echelon production deployment.
Future Integration:
#### Real-Time Stream (`src/stream.ts`)
- WebSocket client to Echelon
- Signal buffering and aggregation
- Session summary generation
#### Fusion (`src/fusion.ts`)
- Map embodied signals to life physics
- Validate verbal claims
- Detect contradictions
Key Endpoints:
GET /health โ Status (Echelon enabled?)
GET /sessions/:id/summary โ Session summary
POST /sessions/:id/tag โ Tag session context
GET /sessions/:userId/untagged โ List untagged sessionsWebSocket Events (future):
- `echelon_signal` - Real-time signal from Echelon
- `session_started` - New session begun
- `session_ended` - Session completed
---
5. Python ML Models (`:5001-5004`)
Status: ๐ฎ Planned Q1 2026 - Currently not implemented
Technology: Python + FastAPI + NumPy/PyTorch (planned)
Responsibility: Probabilistic and ML models
Current Reality: These services do not exist yet. Physics calculations are currently done in TypeScript within Trajectory Core. The models below represent the planned architecture for offloading complex ML computations.
5.1 Skill Graph Model (`:5001`)
File: `models/skill_graph/main.py`
from fastapi import FastAPI
from .bayesian_model import BayesianSkillModel
app = FastAPI()
model = BayesianSkillModel()
@app.post("/update")
def update_belief(skill_id: str, evidence: SkillEvidence):
"""Update skill belief using Bayesian inference"""
return model.update_belief(skill_id, evidence)
@app.post("/propagate")
def propagate_update(skill_id: str, graph: SkillGraph):
"""Propagate belief through graph"""
return model.propagate(skill_id, graph)
@app.post("/sample")
def sample_posterior(skill_id: str, n_samples: int = 1000):
"""Monte Carlo sampling"""
return model.sample_posterior(skill_id, n_samples)5.2 Alignment Scorer (`:5002`)
File: `models/alignment/main.py`
@app.post("/compute")
def compute_alignment(projects: List[Project], skills: List[SkillBelief]):
"""Compute alignment score"""
return scorer.compute_alignment(projects, skills)
@app.post("/detect-conflicts")
def detect_conflicts(projects: List[Project]):
"""Find conflicting projects"""
return scorer.detect_conflicts(projects)5.3 Gravity/Mass Estimator (`:5003`)
File: `models/gravity_mass/main.py`
@app.post("/gravity")
def estimate_gravity(constraints: List[Constraint]):
"""Estimate gravity from constraints"""
return estimator.estimate_gravity(constraints)
@app.post("/mass")
def estimate_mass(projects: List[Project], skills: List[SkillBelief]):
"""Estimate system mass"""
return estimator.estimate_mass(projects, skills)5.4 Life State Model (`:5004`)
File: `models/life_state/main.py`
@app.post("/predict")
def predict_next_state(current: LifeState, actions: List[Action]):
"""Predict future state"""
return dynamics.predict_next_state(current, actions)
@app.post("/escape-time")
def estimate_escape_time(current: LifeState):
"""Estimate time to ฮท > 1"""
return dynamics.estimate_escape_time(current)---
6. Vector Store (`:6000`)
Status: ๐ฎ Planned Q1 2026 - Semantic search not yet implemented
Technology: Node.js + Pinecone/Weaviate/ChromaDB (planned)
Responsibility: Semantic memory and search
Features:
- Document embedding (OpenAI text-embedding-3)
- Vector similarity search
- Metadata filtering
- Batch operations
Endpoints:
POST /embed โ Generate embedding
POST /store โ Store document
POST /search โ Semantic search
DELETE /:id โ Delete document
GET /stats โ Storage statistics---
7. Artifact Ingestor (Background Service)
Status: ๐ฎ Planned Q2 2026 - Document processing not yet implemented
Technology: Node.js + Bull queue (planned)
Responsibility: Process uploaded documents
Processors:
- PDF โ text extraction + chunking
- Notion โ API import
- Google Calendar โ commitment extraction
- GitHub โ code analysis
Flow:
Upload โ Queue โ Process โ Extract โ Embed โ Store (Vector DB)
โโ Evidence โ trajectory-core
โโ Metadata โ database---
Client Applications
Web Dashboard (`:3000`)
Status: โ Live - Production web application
Technology: Next.js + React + Tailwind CSS
Deployment: Vercel / Fly.io
Responsibility: Primary user interface
Features:
- Real-time physics dashboard
- Interview conversational UI
- Skills & projects management
- Interactive scenario simulator
- Dark mode support
Integration:
- REST API calls to trajectory-core (`:3003`)
- WebSocket connection to API gateway (planned)
- JWT authentication
---
Tauri Desktop App
Status: ๐ฎ Planned - Starter implementation available
Technology: Rust + React + Tauri
Platforms: macOS, Windows, Linux
Responsibility: Cross-platform native desktop application
Architecture Modes:
1. Standalone Mode (Offline-First)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Tauri Desktop App โ
โ โโโโโโโโโโโ โโโโโโโโโโโโ โ
โ โ React โโโโ Rust โ โ
โ โ UI โ โ Physics โ โ
โ โโโโโโโโโโโ โโโโโโโโโโโโ โ
โ โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Local SQLite DB โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโFeatures:
- โ
Life Physics calculations (Rust implementation)
- โ
Skills & projects management
- โ
Local persistence (SQLite)
- โ
Scenario simulation
- โ
Offline-first operation
- โ Interview system (no LLM)
- โ Background analysis
Performance: ~0.2ms physics calculations (Rust), ~50MB memory
2. Hybrid Mode (Full Features)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Tauri Desktop App โ
โ โโโโโโโโโโโ โโโโโโโโโโโโ โ
โ โ React โโโโ Rust โ โ
โ โ UI โ โ IPC โ โ
โ โโโโโโโโโโโ โโโโโโโโโโโโ โ
โ โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ HTTP Client โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ
โ
[Backend Services]Features:
- โ
All standalone features
- โ
Interview system (via Agent Orchestrator)
- โ
Background analysis & insights
- โ
Cloud sync & multi-device
- โ
RAG++ search
Use Cases:
- Standalone: Personal use, offline-first, privacy-focused
- Hybrid: Team use, cloud sync, AI-powered features
Documentation: See [Tauri Integration Guide](../guides/tauri-integration.md)
Implementation: [`/apps/tauri-desktop/`](../../apps/tauri-desktop/)
Key Benefits vs Web:
- 6-7x faster physics calculations (Rust vs TypeScript)
- Native OS integration (notifications, system tray)
- Offline-first operation
- Lower memory footprint (50MB vs 200MB+ web stack)
- No browser overhead
---
Mobile Apps
EchelonCapture (iOS)
Status: โ Live - MVP functional with Strudel integration
Technology: Swift + SwiftUI + Strudel.js
Platform: iOS 17+
Responsibility: Embodied signal capture & music generation
Features:
- โ
Motion capture (CoreMotion)
- โ
Beat generation (heartbeat โ rhythm)
- โ
Gesture recognition
- โ
Music synthesis (Strudel.js)
- โ
Phrase library & composition
- ๐ง TrajectoryOS sync (planned)
Integration with TrajectoryOS (๐ฎ Planned Q1-Q2 2026):
- Embodied signals โ Alignment estimation
- Movement patterns โ Energy/Thrust metrics
- Gesture events โ Life state updates
- Real-time WebSocket connection
Documentation: See [Echelon Integration](echelon_integration.md)
TrajectoryOS Mobile (Future)
Status: ๐ฎ Planned Q2-Q3 2026
Technology: React Native / Flutter
Platforms: iOS, Android
Responsibility: Full TrajectoryOS experience on mobile
Features (Planned):
- Life physics dashboard
- Quick skill/project updates
- Interview on-the-go
- Notifications & insights
- Sync with desktop/web
---
Data Flow Examples
Interview Flow
1. User sends message
Dashboard โ Gateway โ Agent :3004
2. Agent processes
Agent โ LLM API โ Extract evidence
3. Evidence stored
Agent โ Core :3003 โ Database
4. State updated
Core โ Python Models โ Bayesian update โ Database
5. Client notified
Core โ Redis (pub) โ Gateway (sub) โ WebSocket โ DashboardBackground Analysis
1. Scheduled job triggers
Cron โ Agent :3004
2. Fetch user state
Agent โ Core :3003 โ Database
3. Run analysis
Agent โ LLM API โ Generate insights
4. Store results
Agent โ Database
5. Notify user
Agent โ Redis (pub) โ Gateway โ WebSocket โ DashboardEchelon Session (Future)
1. Echelon session active
Echelon Engine โ Bridge :3005 (WebSocket)
2. Signals aggregated
Bridge โ Session summary
3. User tags session
Dashboard โ Gateway โ Bridge โ Database
4. Fusion with life state
Bridge โ Core :3003 โ Python Fusion Model โ State update
5. Physics recomputed
Core โ Physics engine โ Escape index updated---
Deployment Architecture
Development
Local machine:
- All services running via `pnpm dev`
- PostgreSQL/SQLite database
- Redis (optional, can stub)Production
Fly.io / Railway / AWS:
- Docker containers for each service
- Managed PostgreSQL (Fly.io Postgres / AWS RDS)
- Redis (Upstash / ElastiCache)
- Vector DB (Pinecone / Weaviate Cloud)
- S3 for file uploadsScaling Strategy
Current (MVP, <1000 users):
- Single instance per service
- Shared database
- No caching
Growth (1k-100k users):
- Horizontal scaling (multiple instances)
- Redis cache layer
- Read replicas for database
- CDN for static assets
Scale (>100k users):
- Auto-scaling groups
- Database sharding (by userId)
- Message queue (RabbitMQ/Kafka)
- Dedicated Python model cluster
---
Security & Auth
Authentication Flow
1. User logs in
Dashboard โ Gateway โ /auth/login
2. Verify credentials
Gateway โ Database (check user)
3. Generate tokens
Gateway โ JWT access token (15min) + refresh token (7 days)
4. Return to client
Gateway โ Dashboard (store in httpOnly cookie)
5. Subsequent requests
Dashboard โ Gateway (JWT in header) โ Verify โ Proxy to servicesService-to-Service Auth
Each service has an API key:
- Stored in environment variable
- Passed in `X-API-Key` header
- Validated by receiving serviceData Access Control
Every request includes userId:
- Gateway extracts from JWT
- Services validate ownership before returning data
- Admin role can access all (for support)---
Monitoring & Observability
Metrics (Prometheus)
Each service exposes `/metrics`:
- Request count, latency (p50, p95, p99)
- Error rate
- Database query time
- LLM API calls
- Memory/CPU usage
Logging (Structured JSON)
{
"timestamp": "2025-11-26T19:30:00Z",
"level": "info",
"service": "trajectory-core",
"requestId": "abc123",
"userId": "user-456",
"action": "state_updated",
"escapeIndex": 1.05,
"latency_ms": 42
}Alerting
- PagerDuty / Slack
- Triggers:
- Service down (health check fails)
- Error rate > 5
- Latency p95 > 1s
- Database connection errors
---
Technology Choices
| Component | Technology | Why |
|---|---|---|
| Core Services | Node.js + TypeScript | Fast, type-safe, great ecosystem |
| ML Models | Python + FastAPI | Best ML libraries, fast API framework |
| Database | PostgreSQL | Reliable, rich query language, good ORM support |
| Vector DB | Pinecone | Managed, fast, easy integration |
| LLM | OpenAI GPT-4 | Best quality for evidence extraction |
| Queue | Bull (Redis) | Simple, reliable, good monitoring |
| Deployment | Fly.io | Easy, global edge network, affordable |
---
Next: See [Data Models](data-models.md) for database schema details.
Promotion Decision
Promote into a technical note or architecture paper with implementation anchors.
Source Anchor
Comp-Core/backend/cc-trajectory/docs/architecture/services.md
Detected Structure
Method ยท Evaluation ยท Code Anchors ยท Architecture