# Kalika — Systems Deep Dive

> The `apps/kalika/` area: the deployable surface of Kalika, a computational
> mathematics/physics research-notebook workbench — a web client, a CLI, an
> auth-and-fan-out BFF, and three backing microservices (compute, notebooks,
> agents) that together turn symbolic/numeric computation, reactive notebooks,
> and multi-agent research into a runnable product.

## What this area is

Kalika is a notebook workbench for computational mathematics and physics. The
`apps/kalika/` directory holds its **runnable applications** — the things you
build, serve, and ship — as opposed to the `@kalika/*` libraries (notebooks,
research-agents, tensor-networks, sdk, training-data, citations, core,
knowledge-graph, typesetting) that the apps compose. There are six Nx projects
here, all tagged `scope:kalika`, `type:app`: one browser app (`@kalika/web`),
one command-line app (`@kalika/cli`), one backend-for-frontend (`@kalika/bff`),
and three domain microservices (`@kalika/svc-compute`, `@kalika/svc-notebooks`,
`@kalika/svc-agents`).

The three services are independent Fastify processes, each owning one slice of
the product and each with its own default port: compute on `3331`, agents on
`3332`, notebooks on `3333` (see the `KALIKA_*_PORT` defaults in each
`src/index.ts`). They do not call each other directly. Instead the **BFF**
(`@kalika/bff`, port `3330`) is the single front door: it authenticates the
caller, then fans requests out to the three services over HTTP via typed clients
in `apps/kalika/bff/src/clients.ts`, and multiplexes their push events back to
the browser over a single WebSocket (`apps/kalika/bff/src/realtime.ts`). The web
app talks only to the BFF; the CLI bypasses the network entirely and drives the
compute logic in-process through `@kalika/sdk`.

The split is by capability. `svc-compute` is the math kernel: a symbolic CAS
(simplify/differentiate/integrate/solve/series/limit), a recursive-descent
numeric expression evaluator, matrix and tensor (`einsum`) operations, a
priority job queue with in-memory and Redis/BullMQ backends, streaming
computation, and an embedded browser-WASM arithmetic kernel with REST fallback.
`svc-notebooks` is the document engine: it composes the reactive CAS notebook
runtime from `@kalika/notebooks` (dependency-graph reactive execution,
collaboration sessions, templates, multi-format export, on-disk file sync).
`svc-agents` is the research-orchestration plane: a lifecycle manager around the
`MultiAgentOrchestrator` from `@kalika/research-agents`, with per-owner
token/compute budget accounting and cost estimation. `@kalika/web` is the React

- Monaco + KaTeX workbench (the 12K-line `App.tsx` plus ~21 feature modules);
  `@kalika/cli` is the headless entry point for computation, notebook runs, and
  training-data corpus ingestion.

## How it fits the wider system

Kalika is largely a self-contained product cluster rather than a deep
participant in the cross-domain Oshun event bus. The dependency flow inside the
area is strict and one-directional: `@kalika/web` → `@kalika/bff` →
{`svc-compute`, `svc-notebooks`, `svc-agents`} over HTTP/WS; `@kalika/cli` →
`@kalika/sdk`/`@kalika/notebooks`/`@kalika/training-data` in-process. The one
cross-cutting Oshun dependency is `@oshun/auth`, which the BFF uses for JWT
verification, role hierarchy (`hasMinimumRole`), and permission resolution
(`getPermissions`) in `apps/kalika/bff/src/auth.ts`. Everything else the apps
import is a `@kalika/*` workspace library or a third-party package (`fastify`,
`@fastify/websocket`, `bullmq`, `react`, `three`, `monaco-editor`, `katex`).

The boundary contract between the BFF and the services is HTTP JSON with a small
header protocol — the BFF stamps `x-kalika-user-id`, `x-kalika-session-id`,
`x-request-id`, and `x-kalika-scopes` onto every upstream call
(`HttpJsonClient.headers` in `clients.ts`), so the services receive an
already-authenticated identity and never re-run auth themselves. Consumers of
this area are therefore: end users via the web/CLI front ends; and operators who
deploy the four server processes behind the BFF.

## Entity reference

### @kalika/bff

The backend-for-frontend and single front door for the Kalika workbench
(`apps/kalika/bff/src`). `buildKalikaBffApp` in `app.ts` wires a Fastify server
that authenticates every request (`createKalikaAuthHook` in `auth.ts`, accepting
both dev tokens and `@oshun/auth` HS256 JWTs), then exposes the unified
`/api/v1/*` surface — session/preferences, an aggregated `/workbench` payload
that `Promise.all`-fans-out to all three services, and full proxy routes for
compute, notebooks, agents, and research tasks. It owns the realtime layer
(`KalikaRealtimeHub` in `realtime.ts`): a per-user WebSocket hub with channel
subscriptions (`compute`, `notebook:*`, `agent:*`) that re-publishes upstream
events. Upstream calls go through typed clients in `clients.ts` over HTTP, with
`UpstreamServiceError` mapping 5xx to a 502. Sessions/preferences are held in an
`InMemoryKalikaSessionStore` (`session.ts`). Fully implemented, not a scaffold.

### @kalika/cli

The headless command-line entry point (`apps/kalika/cli/src`). `runCli` in
`commands.ts` parses argv and dispatches to two families: in-process computation
via `@kalika/sdk` (`eval`, `simplify`, `solve`, plus `integrate` /
`differentiate` / `series` / `limit` parsed out of function-call syntax like
`integrate(sin(x)^2, x)`), and a large `training-data` subcommand delegated
wholesale to `runTrainingDataCommand` from `@kalika/training-data` (ingesting
proof-pile/formal-proof/arXiv-LaTeX/structured-DB corpora, synthetic generation,
math-classifier and quality-model training, dedup, domain balancing). It also
runs notebooks headlessly (`kalika notebook run file.kalika-nb`), deserializing
via `@kalika/notebooks` and executing each code/CAS cell through the SDK. The
CLI is the only app that does compute without touching the network. Fully
implemented.

### @kalika/svc-agents

The research-orchestration microservice (`apps/kalika/svc-agents/src`, default
port `3332`). `buildAgentServiceApp` (`app.ts`) exposes agent lifecycle and
research-task REST routes; the real logic lives in
`ResearchAgentLifecycleService` (`agent-service.ts`), which manages a pool of
`MultiAgentOrchestrator` instances from `@kalika/research-agents` and runs them
under `AbortController` budgets with pause/resume/terminate transitions. Its
distinguishing feature is genuine **budget accounting**: `buildCostEstimate`
computes per-task token and compute-ms estimates from request size and task
count (literature/computation/exploration/proof phases), enforces per-owner
remaining budget before a run (`reserveBudget` throws on violation), prices runs
with Anthropic Claude input/output per-million-token rates
(`estimateClaudeTextCostUsd`), and reconciles reserved vs. measured usage in
`recordUsage`. State is held in an injectable `AgentRepository`
(`InMemoryAgentRepository` by default). Fully implemented.

### @kalika/svc-compute

The computation kernel microservice (`apps/kalika/svc-compute/src`, default port
`3331`). `ComputeEngine` (`engine.ts`) is a real, self-contained CAS + numerics
implementation: a hand-written recursive-descent `NumericParser` for arithmetic
with functions/constants, symbolic simplify/differentiate/integrate over
additive terms, linear-equation solving with a linearity check, Taylor series
for `exp`/`sin`/`cos`, limit evaluation (direct + known forms +
finite-difference), Gaussian-elimination determinant/inverse, and tensor
`einsum` via `@kalika/tensor-networks`. `queue.ts` adds a priority job queue
with two backends — `InMemoryComputeQueueService` (sequence+priority scheduler,
SHA-256 result cache, abort/timeout) and `RedisComputeQueueService` (BullMQ
`Queue`/`Worker` mirroring the in-memory executor) — and two physics task kinds:
IBP integral reduction and a seeded 2-D Ising **lattice Monte Carlo** with
Metropolis updates. `browser.ts` ships an embedded WASM arithmetic kernel
(`add`/`sub`/`mul`/`div`, real bytes + SHA-256) with a server-REST fallback;
`streaming.ts` drives WebSocket streaming compute. Fully implemented.

### @kalika/svc-notebooks

The notebook-document microservice (`apps/kalika/svc-notebooks/src`, default
port `3333`). `NotebookService` (`notebook-service.ts`) composes the reactive
CAS notebook runtime from `@kalika/notebooks` — dependency-graph construction
(`buildNotebookDependencyGraph`), reactive and incremental execution planning
(`planReactiveExecution` / `planIncrementalReactiveExecution`), per-cell symbol
analysis and change detection, a CAS kernel context, and collaboration sessions
with locks/edits (`applyNotebookCollaborationEdit`, `releaseNotebookCellLock`).
It adds three local concerns on top: domain **templates** (`templates.ts` —
runnable starter notebooks like `getting-started-quantum-mechanics` and
`computing-feynman-diagrams`), multi-format **export** (`exports.ts` —
json/html/latex/pdf/ipynb/plain), and two-way **file sync** to disk
(`file-sync.ts` — `fs.watch`-based binding of a notebook to a
`.kalika`/`.kalika-nb` file with debounce/poll and external-change callbacks).
Fully implemented.

### @kalika/web

The browser workbench (`apps/kalika/web`), a Vite-built React app whose entry is
`src/main.tsx` mounting `App.tsx`. This is the largest entity in the area: a
~12K-line `App.tsx` plus ~21 feature modules under `src/`, each with a colocated
`.spec.ts`. The UI is built on Monaco (`@monaco-editor/react`), KaTeX/MathJax
for typesetting, `three` for 3-D, and OpenDyslexic fonts, and it composes the
`@kalika/notebooks`, `@kalika/citations`, `@kalika/core`,
`@kalika/knowledge-graph`, and `@kalika/typesetting` libraries. The feature
modules implement real workbench capabilities — `spatial-canvas.ts` (pan/zoom
spatial layout geometry), `ThreeDExplorer.tsx`/`three-d-explorer.ts`,
`ai-suggestions.ts`, `citation-sidebar.ts`, `knowledge-graph-browser.ts`,
`proof-exploration.ts`, `realtime-collaboration.ts`, `research-assistant.ts`,
`math-input.ts`/`accessible-math.ts`, and several end-to-end `*-workflow.ts`
orchestrators (compute-write/verify, paper-generation, literature-informed,
explore-conjecture, theory-observable). It also carries Playwright e2e specs
including an accessibility-compliance suite (`e2e/`, `ACCESSIBILITY_AUDIT.md`).
Fully implemented.
