ContextOS is a TypeScript monorepo (Turborepo + npm workspaces) providing an intelligence layer for autonomous AI agents. It publishes three npm packages (core, cli, mcp) and ships one private dashboard app.
Four workspaces under one root (package.json workspaces):
packages/core(@context-os/core) — Shared intelligence: SQLite indexer + vector search (better-sqlite3+ sqlite-vec), embeddings (@xenova/transformers), tree-sitter parsing, schema validation (Ajv), resilience and orchestration.workspace-cli(@context-os/cli) — Terminal interface (context-osbinary). Commands insrc/commands/(Commander, Chalk, Ora).workspace-mcp(@context-os/mcp) — Model Context Protocol server (context-os-mcpbinary). Dual transport: stdio (default,server.ts) and HTTP/SSE (server-http.ts). Tools insrc/tools/.workspace-dashboard(private) — React 19 + Vite + Tailwind v4 + Three.js spatial UI (Aether HUD). Not published.
Build order: Core -> CLI/MCP/Dashboard (Turbo resolves via ^build). CLI and MCP import core's built dist/, so rebuild core before they see new exports.
The core package wires services through a dependency injection container (src/container/): container.ts (scoped resolution), tokens.ts (~45 typed Symbol injection keys), defaults.ts (default graph). factory.ts exposes createContextOS(), re-exported from src/index.ts. New modules register in the default container and export from src/index.ts.
Subsystems (each a src/ subdirectory):
events/—WorkspaceEventBus, typed payloads, error-isolated handlers (one failure does not cascade).agents/—AgentRegistry(lifecycle, heartbeat, stale quarantine) +MessageBus(direct/broadcast/correlation).orchestration/—TaskGraph(DAG/cycle detection),TaskScheduler,ConflictResolver(read/write lock upgrades),SwarmOrchestrator, consensus + negotiation.resilience/—CircuitBreaker, Merkle-linkedAuditLog, predictive-failure (CUSUM change-point detection).cognitive/— memory stream, reflection, skill library, LATS tree search.governance/— capability tokens, trust scoring, policy engine, anomaly detection.streaming/— CEP event processing, predictive health, knowledge distillation, hierarchical memory.services/— domain services:git-intelligence,fusion-scoring,graph-rag,temporal-graph,knowledge-graph,embedding,locking,mission,repair, etc.database/+metrics/— SQLite schema/vectors; Prometheus metrics export.
npm run build # Turbo: tsc for core/cli/mcp, tsc+vite for dashboard
npm run test # Turbo: mocha (core/cli/mcp); vitest (dashboard)
npm run validate # Turbo: build + workspace validation (uncached)
npm run sync:assets # Copy templates to dist (scripts/sync-templates.js)
npm run link:all # Build + npm link cli and mcp for local devPer-workspace:
cd workspace-dashboard && npm run dev # Vite dev server
cd workspace-dashboard && npm run lint # ESLint (dashboard only)
cd workspace-cli && npm run watch # tsc watch mode
cd workspace-mcp && npm run watch # tsc watch modeRun a single test (Mocha workspaces compile to dist/ first):
cd packages/core && npx mocha dist/tests/some-file.test.js
cd packages/core && npx mocha 'dist/tests/**/*.test.js' --grep "circuit breaker"Coverage (core only): cd packages/core && npm run test:coverage (c8, text + lcov).
| Variable | Required | Description |
|---|---|---|
GEMINI_API_KEY |
No | AI embeddings/repairs. Without it, local transformers are used. |
CONTEXTOS_LOG_LEVEL |
No | debug / info / warn / error. Defaults to info. |
MCP_AUTH_TOKEN |
For HTTP | Bearer token for MCP HTTP transport. |
MCP_HTTP_PORT |
No | MCP HTTP port. Defaults to 3001. |
MCP_CORS_ORIGINS |
No | Comma-separated CORS origins for MCP HTTP. |
- ESM only — every package is
"type": "module"withNodeNextresolution. - TypeScript strict —
"strict": trueacross all tsconfigs; targetESNext. - ESLint — dashboard only (
eslint.config.js:typescript-eslint,react-hooks,react-refresh), enforced at zero warnings via lint-staged. - No shared formatter — no Prettier or
.editorconfigin the repo. - Immutability preferred — create new objects; avoid in-place mutation.
- Spawn over exec — use
spawnfor subprocesses to prevent shell injection.
- Frameworks: Mocha + Chai (core, cli, mcp); Vitest (dashboard).
- Mocha tests live in
src/tests/as.tsand run fromdist/tests/after build. - Core tests use per-test temp databases (
.context-db-test-*— gitignored). - Integration tests may need extended timeouts (5000ms) for full-workspace scans.
How AI agent teams (Claude Code sub-agents, Cursor background agents, or any multi-agent system) should divide work on this codebase.
| Agent Role | Scope | Files Touched | Model Tier |
|---|---|---|---|
| Architect | System design, DI container, new subsystem planning | packages/core/src/container/, docs/architecture.md |
Opus |
| Core Engineer | Core logic: orchestration, resilience, cognitive, governance, streaming, services | packages/core/src/** |
Sonnet/Opus |
| CLI Developer | Commands, flags, output formatting | workspace-cli/src/** |
Sonnet |
| MCP Developer | Tools, transports, protocol compliance | workspace-mcp/src/** |
Sonnet |
| Dashboard Dev | React components, Three.js scenes, Tailwind | workspace-dashboard/src/** |
Sonnet |
| Test Engineer | Coverage, regression tests, test infra | */src/tests/** |
Sonnet |
| Security Reviewer | Auth, input validation, injection, secrets | Any auth/PII/upload file | Opus |
| Release Manager | Version bumps, CHANGELOG, publish pipeline | package.json (all), CHANGELOG.md |
Haiku/Sonnet |
PARALLEL OK:
- CLI agent + MCP agent (different workspaces, no shared source)
- Test engineer + Dashboard dev (no file overlap)
- Core engineer (events/) + Core engineer (orchestration/) — different subdirs
SEQUENTIAL REQUIRED:
- Core changes -> then CLI/MCP updates (they import core dist/)
- Schema changes -> then validation updates -> then tests
- Any architect decision -> then implementation agents
Every sub-agent MUST, before writing code:
- Read
AGENTS_LEARNING.md— avoid repeating past mistakes. - Read this file (
AGENTS.md) — understand scope and conventions. - Build core first if touching core:
npm run build -w @context-os/core. - Run existing tests in scope before modifying.
- After completing work: update
AGENTS_LEARNING.mdwith new learnings.
## Task: [brief title]
- **Scope**: [workspace/directory]
- **Files**: [specific paths to read/modify]
- **Depends on**: [other agent outputs, if any]
- **Acceptance**: [verify command or behavior check]- Each agent works only in its designated workspace/subdirectory.
- Cross-workspace changes are sequenced by the orchestrating agent.
- Never modify
packages/core/src/index.tsexports without coordinating — all workspaces depend on it. package-lock.jsonis modified by only one agent per session.
After implementation, route in order: Code Reviewer (correctness, immutability) -> Security Reviewer (if auth/PII/uploads/env-vars, auto-triggered) -> Test Analyzer (coverage, regression).
Strict version parity: all four package.json files (root, core, cli, mcp) share one version (currently 1.13.2). CLI and MCP pin @context-os/core to the exact version. Publish order: Core -> CLI -> MCP (sequential), triggered by pushing a v* tag (publish.yml).
Prerequisites: Node 22+, npm 11+, C++ toolchain (native SQLite compilation).
- Husky
pre-commitrunsnpx lint-staged: per-packagetsc --noEmit --skipLibCheck(core/cli/mcp) and dashboard ESLint (--max-warnings=0) +tsc -b. Runnpm run prepareafter a fresh clone to install hooks. - Husky
pre-pushrunsnpm run validate(full build + validation). - GitHub Actions (
.github/workflows/):validate.yml— build + test + validate on PRs/pushes; test matrix Node 20 and 22.security.yml— CodeQL, dependency-review, OSSF Scorecard; weekly cron + PR/push.publish.yml— npm publish onv*tags (Core -> CLI -> MCP).preview-deploy.yml/preview-cleanup.yml— ephemeral PR preview deploys + teardown.bundle-analysis.yml— dashboard bundle-size report (sticky PR comment).release-preview.yml— next-version preview via semantic-release.docs.yml— build + publish docs (gh-pages) on push / manual dispatch.
Conventional Commits with scoped prefixes:
feat(scope): description # New functionality
fix(scope): description # Bug fixes
test(scope): description # Adding/updating tests
perf(scope): description # Performance improvements
refactor(scope): description # Restructuring without behavior change
docs: description # Documentation only
chore: description # Tooling, deps, config
ci: description # CI/workflow changes
Scopes are workspace or subsystem names: core, cli, mcp, dashboard, governance, streaming, predictive, swarm, temporal. Omit scope for cross-cutting changes.