Trajectory Core Service
The core service powering TrajectoryOS. Implements the Life Physics model, manages state persistence, and provides REST API for all physics calculations.
Full Public Reader
Trajectory Core Service
Status: ✅ Live - Production-ready life physics engine and state management
The core service powering TrajectoryOS. Implements the Life Physics model, manages state persistence, and provides REST API for all physics calculations.
---
Quick Start
### Prerequisites
- Node.js 20+
- pnpm
- SQLite (included)
Installation
# From repository root
cd services/trajectory-core
# Install dependencies
pnpm install
# Set up database
pnpm prisma generate
pnpm prisma migrate dev
# Seed with sample data (optional)
pnpm prisma db seedDevelopment
# Start development server (with hot reload)
pnpm dev
# Server runs at http://localhost:3003Testing
# Run all tests
pnpm test
# Run tests in watch mode
pnpm test:watch
# Run with coverage
pnpm test:coverageBuild
# Build for production
pnpm build
# Run production build
pnpm start---
Architecture
Directory Structure
trajectory-core/
├── src/
│ ├── domain/ # Core business logic (pure functions)
│ │ ├── types.ts # TypeScript interfaces
│ │ ├── physics.ts # Physics calculations (T, A, G, M, η)
│ │ └── skillGraph.ts # Skill graph operations
│ │
│ ├── services/ # Application services
│ │ ├── LifeStateService.ts # State management
│ │ ├── StateEstimator.ts # State estimation & transitions
│ │ ├── SkillService.ts # Skill graph CRUD
│ │ ├── ProjectService.ts # Project management
│ │ ├── PlannerService.ts # Scenario planning
│ │ ├── TransitionBuilder.ts # State transition logic
│ │ └── UnifiedSearchService.ts # Multi-dimensional search
│ │
│ ├── routes/ # Express route handlers
│ │ ├── state.ts # /api/state/*
│ │ ├── skills.ts # /api/skills/*
│ │ ├── projects.ts # /api/projects/*
│ │ ├── physics.ts # /api/physics/*
│ │ └── ragpp.ts # /api/ragpp/*
│ │
│ ├── evaluation/ # Testing & quality assurance
│ │ ├── SampleDataGenerator.ts
│ │ ├── StateAwarenessEval.ts
│ │ └── RecommendationQualityEval.ts
│ │
│ ├── scripts/ # Utility scripts
│ │ └── ragpp-demo.ts # RAG++ demonstration
│ │
│ └── index.ts # Express server setup
│
├── prisma/
│ ├── schema.prisma # Database schema
│ ├── migrations/ # Migration history
│ └── seed.ts # Sample data seeding
│
├── tests/ # Test files
│ ├── unit/
│ └── integration/
│
└── package.json---
Core Concepts
Life Physics Model
The heart of trajectory-core is the Life Physics calculation engine:
import { computeEscapeIndex, computeThrust } from './domain/physics';
// Compute thrust from skills and alignment
const thrust = computeThrust(
skills, // SkillBelief[]
utilization, // Map<skillId, utilizationRate>
alignment, // 0-1
weights // Optional skill weights
);
// Compute escape index
const eta = computeEscapeIndex(
thrust, // Productive power
gravity, // Environmental constraints
mass // System complexity
);
// η = T / (G × M)See: [Life Physics Concept Doc](../../docs/concepts/life-physics.md)
---
Data Models
Core Entities (Prisma schema):
model User {
id String @id @default(cuid())
email String @unique
name String
createdAt DateTime @default(now())
}
model SkillBelief {
id String @id @default(cuid())
userId String
skillName String
level Float // 0-10
confidence Float // 0-1 (Bayesian confidence)
evidence String[] // Supporting evidence
updatedAt DateTime @updatedAt
}
model Project {
id String @id @default(cuid())
userId String
name String
description String
status ProjectStatus // active, paused, completed, archived
alignment Float // Computed alignment score
createdAt DateTime @default(now())
}
model LifeState {
id String @id @default(cuid())
userId String
thrust Float
alignment Float
gravity Float
mass Float
escapeIndex Float // η
regime String // falling, approaching, threshold, escaping, free
timestamp DateTime @default(now())
}Full schema: [prisma/schema.prisma](./prisma/schema.prisma)
---
API Reference
Base URL
http://localhost:3003Endpoints
Life State
GET `/api/state/:userId`
- Get current life state for user
- Response: `LifeState` object with physics metrics
GET `/api/state/:userId/history`
- Get historical state snapshots
- Query params: `?limit=30&offset=0`
- Response: Array of `LifeState` objects
POST `/api/state/:userId/update`
- Manually trigger state recalculation
- Body: `{ reason?: string }`
- Response: Updated `LifeState`
---
Skills
GET `/api/skills`
- List all skills for authenticated user
- Response: `SkillBelief[]`
GET `/api/skills/graph`
- Get skill graph with relationships
- Response: `{ nodes: SkillBelief[], edges: SkillEdge[] }`
POST `/api/skills/:id/evidence`
- Add new evidence for a skill
- Body: `{ evidence: string, source: string }`
- Response: Updated `SkillBelief` with new confidence
GET `/api/skills/:id/belief`
- Get Bayesian posterior for skill
- Response: `{ mean: number, variance: number, credibleInterval: [number, number] }`
---
Projects
GET `/api/projects/:userId`
- Get all projects for user
- Query params: `?status=active`
- Response: `Project[]`
POST `/api/projects`
- Create new project
- Body: `{ name: string, description: string, timeAllocation?: number }`
- Response: Created `Project`
PUT `/api/projects/:id`
- Update project
- Body: Partial `Project` fields
- Response: Updated `Project`
DELETE `/api/projects/:id`
- Archive project (soft delete)
- Response: `{ success: true }`
---
Physics
GET `/api/physics/:userId`
- Get current physics snapshot
- Response: `{ thrust, alignment, gravity, mass, escapeIndex, regime }`
GET `/api/physics/:userId/breakdown`
- Detailed breakdown of physics components
- Response: Granular metrics for each variable
POST `/api/physics/simulate`
- Run scenario simulation
- Body: `{ userId, changes: { thrust?: number, alignment?: number, ... } }`
- Response: `{ current: LifePhysics, simulated: LifePhysics, delta: number }`
---
RAG++ (State-Based Retrieval)
POST `/api/ragpp/search`
- Multi-dimensional search
- Body: `{ query: string, userId: string, filters?: {...} }`
- Response: `SearchResult[]` with semantic + topological + physics scoring
GET `/api/ragpp/neighbors/:eventId`
- Find topologically similar events
- Response: `Event[]` sorted by 5D distance
---
Configuration
Environment Variables
Create `.env` file in service root:
# Database
DATABASE_URL="file:./dev.db" # SQLite (dev)
# DATABASE_URL="postgresql://user:pass@localhost:5432/trajectoryos" # PostgreSQL (prod)
# Server
PORT=3003
NODE_ENV=development
# Python ML Services (when available)
SKILL_MODEL_URL=http://localhost:5001
ALIGNMENT_MODEL_URL=http://localhost:5002
GRAVITY_MASS_URL=http://localhost:5003
LIFE_STATE_MODEL_URL=http://localhost:5004
# IRCP Service
IRCP_SERVICE_URL=http://localhost:8001
# Redis (optional, for caching)
REDIS_URL=redis://localhost:6379
# CORS
CORS_ORIGIN=http://localhost:3000---
Development
Running Locally
# Terminal 1: Start trajectory-core
cd services/trajectory-core
pnpm dev
# Terminal 2: Start web dashboard (optional)
cd apps/web
pnpm dev
# Terminal 3: Watch tests
cd services/trajectory-core
pnpm test:watchDatabase Management
# Create a new migration
pnpm prisma migrate dev --name descriptive_migration_name
# Reset database (⚠️ destroys data)
pnpm prisma migrate reset
# Open Prisma Studio (database GUI)
pnpm prisma studio
# Visit http://localhost:5555Code Style
# Lint
pnpm lint
# Format
pnpm format
# Type check
pnpm type-check---
Testing
Test Structure
tests/
├── unit/
│ ├── physics.test.ts # Pure physics functions
│ ├── skillGraph.test.ts # Skill graph logic
│ └── stateEstimator.test.ts
│
├── integration/
│ ├── api.test.ts # API endpoint tests
│ ├── database.test.ts # Prisma operations
│ └── services.test.ts # Service layer integration
│
└── e2e/
└── scenarios.test.ts # End-to-end user scenariosRunning Tests
# All tests
pnpm test
# Specific test file
pnpm test physics.test.ts
# With coverage
pnpm test:coverage
# Update snapshots
pnpm test -uWriting Tests
Example test:
import { computeEscapeIndex } from '../src/domain/physics';
describe('Life Physics', () => {
it('calculates escape index correctly', () => {
const eta = computeEscapeIndex(
10, // thrust
2, // gravity
5 // mass
);
expect(eta).toBe(1.0); // 10 / (2 × 5) = 1.0
});
it('detects escaping regime', () => {
const eta = computeEscapeIndex(15, 2, 5); // 1.5
const regime = interpretEscapeIndex(eta);
expect(regime.status).toBe('free');
});
});---
Deployment
Production Build
# Build
pnpm build
# Output in dist/
ls dist/
# Run production server
NODE_ENV=production pnpm startDocker
# Dockerfile included in service directory
FROM node:20-alpine
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN npm install -g pnpm && pnpm install --frozen-lockfile
COPY . .
RUN pnpm prisma generate && pnpm build
EXPOSE 3003
CMD ["pnpm", "start"]Build and run:
docker build -t trajectoryos-core .
docker run -p 3003:3003 trajectoryos-core---
Troubleshooting
Common Issues
Issue: `Error: P1001: Can't reach database server`
- Solution: Check DATABASE_URL in `.env`. For SQLite, ensure directory exists.
Issue: `Prisma Client could not be generated`
- Solution: Run `pnpm prisma generate`
Issue: Port 3003 already in use
- Solution: Change PORT in `.env` or kill process: `lsof -ti:3003 | xargs kill`
Issue: Tests failing with database errors
- Solution: Run `pnpm prisma migrate reset` to reset test database
Issue: CORS errors from web dashboard
- Solution: Ensure CORS_ORIGIN in `.env` matches your frontend URL
---
Performance
Current Benchmarks
- Physics calculation: ~0.5ms average
- State update: ~10ms (includes DB write)
- API response time: ~50ms p95
- Concurrent requests: Handles 1000+ req/s on single instance
Optimization Tips
1. Enable Redis caching for expensive computations
2. Use connection pooling for PostgreSQL in production
3. Index frequently queried fields (userId, timestamp)
4. Batch skill updates instead of individual calls
---
Future Enhancements
Planned Q1 2026:
- [ ] Python ML model integration (Bayesian inference offloading)
- [ ] WebSocket support for real-time state updates
- [ ] GraphQL API alongside REST
- [ ] Event sourcing for state history
Planned Q2 2026:
- [ ] Horizontal scaling with Redis-based state sharing
- [ ] Advanced caching strategies (multi-level)
- [ ] Performance monitoring/observability (Prometheus metrics)
---
Related Documentation
- [Life Physics Concept](../../docs/concepts/life-physics.md) - Mathematical foundations
- [Service Architecture](../../docs/architecture/services.md) - Overall system design
- [API Documentation](../../docs/api/README.md) - Complete API reference
- [Data Models](../../docs/architecture/data-models.md) - Database schema details
---
Contributing
1. Fork the repository
2. Create a feature branch: `git checkout -b feature/my-feature`
3. Make changes and add tests
4. Run tests: `pnpm test`
5. Commit: `git commit -m "Add my feature"`
6. Push: `git push origin feature/my-feature`
7. Create Pull Request
---
License
MIT
---
Maintained by: TrajectoryOS Core Team
Last Updated: December 21, 2025
Service Version: 1.0.0
Status: ✅ Production-Ready
Promotion Decision
Attach run IDs, datasets, metrics, and reproduction commands.
Source Anchor
Comp-Core/backend/cc-trajectory/services/trajectory-core/README.md
Detected Structure
Method · Evaluation · Code Anchors · Architecture