# harshitk-cp/engram architecture

> Architecture diagram of the GitHub repository harshitk-cp/engram, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-25). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/harshitk-cp/engram
- Repository: https://github.com/harshitk-cp/engram

## Overview

1. **Repository shape**
   This is a Go backend centered on an AI memory service. It ships two runnable entry points: `cmd/server` for the HTTP API + admin console, and `cmd/engram-mcp` for a standalone MCP server. The same core packages are reused by both.

2. **Top-level runtime boundary**
   The main production boundary is the HTTP server. Requests enter through `internal/api/router.go`, pass through middleware, then dispatch to handler packages under `internal/api/handlers`, which call into `internal/service`. The MCP binary is a separate transport layer that exposes the same capabilities as tools instead of REST endpoints.

3. **Layering**
   The backend is organized in a fairly classic hexagonal style:
   - `internal/api` = transport, auth, rate limiting, quotas, request shaping
   - `internal/service` = business logic and memory algorithms
   - `internal/store` = persistence and transaction/unit-of-work boundaries
   - `internal/domain` = core entities and value logic
   - `internal/llm` and `internal/embedding` = external AI provider adapters

4. **Core data path**
   Memory writes and reads flow from API/MCP into the service layer, then into PostgreSQL via the store layer. The service layer performs the domain-specific work: confidence updates, contradiction handling, consolidation, decay, recall ranking, and working-memory activation before data is persisted or returned.

5. **Cognitive core**
   The distinctive subsystem is the “cognitive core” implemented in `internal/service`: semantic memories, episodic memories, procedural memories, working memory, schemas, metacognition, calibration, decay, and hybrid recall. These are not separate services; they are coordinated behaviors over the same database-backed model.

6. **Provenance Firewall and quarantine**
   Untrusted or externally extracted knowledge is not immediately treated as canonical. The codebase has a dedicated quarantine/review path in the API and service layers, with release/reject flows and audit logging. This is a hard boundary between raw ingestion and trusted memory.

7. **Audit and trust model**
   A major subsystem is the append-only audit chain. The README and migrations show a tamper-evident SHA-256 hash chain, audit verification/export endpoints, and mutation logging for every belief change. This means memory state is not just stored; its evolution is recorded as a verifiable history.

8. **Multi-subject isolation**
   The domain supports multiple “bindings” for the same agent: private, anchored, session, and canon. Anchors represent subject-level isolation, sessions represent short-lived conversational context, and canon represents tenant-wide shared knowledge. This isolation is enforced in the service/store layer and reflected in endpoints for anchors, sessions, and canon.

9. **Persistence model**
   PostgreSQL is the primary datastore, with pgvector support implied by the README and migrations. The `migrations` directory shows the schema evolving to support embeddings, graph retrieval, API keys, audit chain, tenant isolation, quarantine, billing, and tuning settings. The data model is therefore both relational and vector-enabled.

10. **Retrieval architecture**
    Recall is hybrid: vector similarity plus graph traversal. The service layer combines entity/graph data from `internal/store/graph.go` with embedding-backed search, then returns scored results with provenance. This is the main read path for agent context injection.

11. **External integrations**
    The code abstracts several external systems behind provider packages:
    - LLM providers: OpenAI, Anthropic, Gemini, Cerebras, plus mock/none modes
    - Embeddings: provider interface plus compatibility/mocks
    - Billing: Razorpay integration, enabled only when keys are configured
    These are optional adapters; the core system still functions in embedding-only or no-LLM modes.

12. **Admin console**
    The React console under `console/` is built with Vite and embedded into the Go binary (`console/embed.go`). It is not a separate deployment requirement. The console is an operator surface for agents, memories, contradictions, quarantine, audit, keys, billing, settings, and time-travel inspection.

13. **MCP surface**
    The `mcp/` package and `cmd/engram-mcp` expose the same memory system as MCP tools over stdio, HTTP, or SSE transports. This is a separate integration boundary for agent hosts like Claude Desktop or Cursor, but it reuses the same underlying business logic.

14. **Operational concerns**
    Middleware handles auth, CORS, logging, request IDs, metrics, rate limiting, and quota enforcement. Configuration lives in `internal/config` and `internal/buildconfig`, and deployment is containerized via `Dockerfile`, `docker-compose.yml`, and migration scripts. The architecture is therefore a single Go service with multiple interfaces, backed by PostgreSQL and enriched by optional AI and billing providers.

Main entry points: [`internal/service`](https://github.com/harshitk-cp/engram/tree/main/internal/service) (Service Core), [`internal/api/router.go`](https://github.com/harshitk-cp/engram/blob/main/internal/api/router.go) (Router), [`internal/store`](https://github.com/harshitk-cp/engram/tree/main/internal/store) (Store), [`cmd/server/main.go`](https://github.com/harshitk-cp/engram/blob/main/cmd/server/main.go) (Server)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Runtimes"]
  node_cmd_server["Server<br/>HTTP API entrypoint<br/>[main.go]"]
  node_cmd_mcp["MCP Server<br/>MCP entrypoint<br/>[main.go]"]
  node_router["Router<br/>HTTP routing<br/>[router.go]"]
  node_middleware["Middleware<br/>HTTP filters"]
  node_api_handlers["Handlers"]
  node_mcp_pkg["MCP Tools<br/>tool surface"]
end

subgraph group_core["Core Layers"]
  node_service_core["Service Core<br/>business logic"]
  node_domain["Domain Model<br/>entities"]
  node_store[("Store<br/>persistence")]
  node_cognitive{{"Cognitive Core<br/>memory algorithms"}}
  node_recall(("Hybrid Recall<br/>retrieval<br/>[hybrid_recall.go]"))
  node_provenance{{"Provenance Firewall<br/>quarantine"}}
  node_audit["Audit Chain<br/>tamper-evident log"]
  node_auth["Trust & Auth<br/>identity<br/>[auth.go]"]
  node_config["Config<br/>settings"]
end

subgraph group_integrations["Integrations"]
  node_llm["LLM Adapters<br/>provider adapters"]
  node_embeddings["Embeddings<br/>vector adapters"]
  node_billing["Billing<br/>payment adapter<br/>[razorpay.go]"]
end

subgraph group_ui["Console"]
  node_console_app["Console UI<br/>React admin app<br/>[App.tsx]"]
  node_embed["Embed Console<br/>asset embed<br/>[embed.go]"]
end

node_cmd_server -->|"starts"| node_router
node_cmd_server -->|"serves UI"| node_embed
node_cmd_mcp -->|"starts"| node_mcp_pkg
node_router -->|"wraps"| node_middleware
node_router -->|"dispatches"| node_api_handlers
node_api_handlers -->|"calls"| node_service_core
node_mcp_pkg -->|"invokes"| node_service_core
node_service_core -->|"orchestrates"| node_cognitive
node_service_core -->|"queries"| node_recall
node_service_core -->|"routes"| node_provenance
node_service_core -->|"records"| node_audit
node_service_core -->|"persists"| node_store
node_service_core -->|"models"| node_domain
node_store -->|"maps"| node_domain
node_store -->|"writes"| node_audit
node_service_core -->|"uses"| node_llm
node_service_core -->|"uses"| node_embeddings
node_service_core -->|"checks"| node_billing
node_middleware -->|"enforces"| node_auth
node_config -->|"configures"| node_cmd_server
node_config -->|"configures"| node_cmd_mcp
node_console_app -->|"calls"| node_api_handlers
node_embed -->|"packages"| node_console_app

click node_cmd_server "https://github.com/harshitk-cp/engram/blob/main/cmd/server/main.go"
click node_cmd_mcp "https://github.com/harshitk-cp/engram/blob/main/cmd/engram-mcp/main.go"
click node_router "https://github.com/harshitk-cp/engram/blob/main/internal/api/router.go"
click node_middleware "https://github.com/harshitk-cp/engram/tree/main/internal/api/middleware"
click node_api_handlers "https://github.com/harshitk-cp/engram/tree/main/internal/api/handlers"
click node_mcp_pkg "https://github.com/harshitk-cp/engram/tree/main/mcp"
click node_service_core "https://github.com/harshitk-cp/engram/tree/main/internal/service"
click node_domain "https://github.com/harshitk-cp/engram/tree/main/internal/domain"
click node_store "https://github.com/harshitk-cp/engram/tree/main/internal/store"
click node_cognitive "https://github.com/harshitk-cp/engram/tree/main/internal/service"
click node_recall "https://github.com/harshitk-cp/engram/blob/main/internal/service/hybrid_recall.go"
click node_provenance "https://github.com/harshitk-cp/engram/tree/main/internal/service/contradiction"
click node_audit "https://github.com/harshitk-cp/engram/tree/main/internal/store"
click node_auth "https://github.com/harshitk-cp/engram/blob/main/internal/api/middleware/auth.go"
click node_config "https://github.com/harshitk-cp/engram/tree/main/internal/config"
click node_llm "https://github.com/harshitk-cp/engram/tree/main/internal/llm"
click node_embeddings "https://github.com/harshitk-cp/engram/tree/main/internal/embedding"
click node_billing "https://github.com/harshitk-cp/engram/blob/main/internal/billing/razorpay.go"
click node_console_app "https://github.com/harshitk-cp/engram/blob/main/console/src/App.tsx"
click node_embed "https://github.com/harshitk-cp/engram/blob/main/console/embed.go"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_cmd_server,node_cmd_mcp,node_router,node_middleware,node_api_handlers,node_mcp_pkg toneBlue
class node_service_core,node_domain,node_store,node_cognitive,node_recall,node_provenance,node_audit,node_auth,node_config toneAmber
class node_llm,node_embeddings,node_billing toneMint
class node_console_app,node_embed toneRose
```

## Components

### Runtimes

Runnable entry points and transport surfaces

- [Server](https://github.com/harshitk-cp/engram/blob/main/cmd/server/main.go): HTTP API entrypoint · Main production binary for the API and admin console · `cmd/server/main.go`
- [MCP Server](https://github.com/harshitk-cp/engram/blob/main/cmd/engram-mcp/main.go): MCP entrypoint · Standalone binary exposing memory tools over MCP transports · `cmd/engram-mcp/main.go`
- [Router](https://github.com/harshitk-cp/engram/blob/main/internal/api/router.go): HTTP routing · HTTP route registration and request dispatch · `internal/api/router.go`
- [Middleware](https://github.com/harshitk-cp/engram/tree/main/internal/api/middleware): HTTP filters · Auth, CORS, logging, metrics, quotas, and rate limits · `internal/api/middleware`
- [Handlers](https://github.com/harshitk-cp/engram/tree/main/internal/api/handlers): REST handlers · API endpoints for memories, agents, audit, quarantine, and admin flows · `internal/api/handlers`
- [MCP Tools](https://github.com/harshitk-cp/engram/tree/main/mcp): tool surface · Shared memory capabilities exposed as MCP resources and tools · `mcp`

### Core Layers

Shared business logic and persistence boundaries

- [Service Core](https://github.com/harshitk-cp/engram/tree/main/internal/service): business logic · Central memory orchestration and cognitive behaviors · `internal/service`
- [Domain Model](https://github.com/harshitk-cp/engram/tree/main/internal/domain): entities · Core entities, bindings, policies, memories, and settings · `internal/domain`
- [Store](https://github.com/harshitk-cp/engram/tree/main/internal/store): persistence · Database access and unit-of-work boundaries · `internal/store`
- [Cognitive Core](https://github.com/harshitk-cp/engram/tree/main/internal/service): memory algorithms · Semantic, episodic, procedural, working-memory, metacognition, decay, and consolidation behaviors · `internal/service`
- [Hybrid Recall](https://github.com/harshitk-cp/engram/blob/main/internal/service/hybrid_recall.go): retrieval · Vector similarity plus graph traversal with provenance-ranked results · `internal/service/hybrid_recall.go`
- [Provenance Firewall](https://github.com/harshitk-cp/engram/tree/main/internal/service/contradiction): quarantine · Quarantine, review, release, reject, and audit-gated ingestion path · `internal/service/contradiction`
- [Audit Chain](https://github.com/harshitk-cp/engram/tree/main/internal/store): tamper-evident log · Mutation logging and SHA-256 hash-chain verification of memory changes · `internal/store`
- [Trust & Auth](https://github.com/harshitk-cp/engram/blob/main/internal/api/middleware/auth.go): identity · API keys, tenants, sessions, anchors, and access control · `internal/api/middleware/auth.go`
- [Config](https://github.com/harshitk-cp/engram/tree/main/internal/config): settings · Runtime and build configuration · `internal/config`

### Integrations

External AI, billing, and transport adapters

- [LLM Adapters](https://github.com/harshitk-cp/engram/tree/main/internal/llm): provider adapters · OpenAI, Anthropic, Gemini, Cerebras, mock, and none modes · `internal/llm`
- [Embeddings](https://github.com/harshitk-cp/engram/tree/main/internal/embedding): vector adapters · Embedding provider interface and compatibility mocks · `internal/embedding`
- [Billing](https://github.com/harshitk-cp/engram/blob/main/internal/billing/razorpay.go): payment adapter · Razorpay integration for tenant billing and plan state · `internal/billing/razorpay.go`

### Console

Embedded operator interface

- [Console UI](https://github.com/harshitk-cp/engram/blob/main/console/src/App.tsx): React admin app · Embedded operator console for memories, audit, quarantine, keys, billing, and settings · `console/src/App.tsx`
- [Embed Console](https://github.com/harshitk-cp/engram/blob/main/console/embed.go): asset embed · Build-time embedding of the React console into the Go binary · `console/embed.go`

## Connections

- Server → Router: starts · Server boots the HTTP router
- Server → Embed Console: serves UI · Server includes the embedded console assets
- MCP Server → MCP Tools: starts · Standalone binary exposes MCP surface
- Router → Middleware: wraps · Router applies cross-cutting request middleware
- Router → Handlers: dispatches · Routes map to API handlers
- Handlers → Service Core: calls · Handlers delegate to business logic
- MCP Tools → Service Core: invokes · MCP tools reuse the same service layer
- Service Core → Cognitive Core: orchestrates · Service layer coordinates memory behaviors
- Service Core → Hybrid Recall: queries · Service performs hybrid recall for context injection
- Service Core → Provenance Firewall: routes · Untrusted knowledge enters quarantine and review flows
- Service Core → Audit Chain: records · Memory mutations are appended to the audit chain
- Service Core → Store: persists · Business logic writes and reads through the store
- Service Core → Domain Model: models · Service logic operates on domain entities and value rules
- Store → Domain Model: maps · Persistence follows the core domain model
- Store → Audit Chain: writes · Store layer participates in mutation logging and verification
- Service Core → LLM Adapters: uses · Optional LLM-backed classification and reasoning
- Service Core → Embeddings: uses · Embedding-backed similarity and retrieval support
- Service Core → Billing: checks · Billing state gates quota and tenant behavior
- Middleware → Trust & Auth: enforces · Request middleware applies auth, quotas, and tenant controls
- Config → Server: configures · Configuration drives server startup and feature flags
- Config → MCP Server: configures · Configuration drives MCP startup and transport selection
- Console UI → Handlers: calls · Console interacts with the HTTP API
- Embed Console → Console UI: packages · Console is embedded into the Go binary
