Architecture

This page is the technical map of AgentGem: how a request flows from a client, through the contract surface, into the framework-agnostic Gem core, and out to archives, targets, and local testbeds and runs. For the conceptual "why," read Concepts first.

The big picture

AgentGem system architecture

Diagram: diagrams/system-architecture.svg · PNG · interactive HTML (Copy / PNG / PDF export)

Two subsystems get their own detail diagrams: the memory-sync bridge and the benchmark feedback loop; the desktop client/server split is in its own diagram.

There are four main horizontal bands:

  1. Hosts / clients — the web UI (src/public/index.html), any local coding agent, and the Desktop app, which runs the same core in client mode in Electron (tray + auto-update).
  2. Contract surface — one Zod definition per operation, surfaced as a REST endpoint, an MCP tool, and an OpenAPI 3.1 document. See the one-contract model.
  3. Gem core (the @agentgem/* packages) — pure, framework-agnostic functions: introspectredactbuildGemarchive. See the build pipeline.
  4. Distribution — the neutral Gem feeds targets (materialize), the marketplace, and local testbeds/runs. See distribution below.

An optional workflow-aware recommendation path sits in front of the core: POST /workflow/analyze (plus an SSE progress stream) scans a project's Claude transcripts into a deterministic WorkflowSignal, then runs two local ACP agents concurrently — one clusters and names candidate Gems (degrading to a frequency ranking if the agent is unavailable), the other distills new draft skills from the recurring builtin procedure the scan would otherwise discard. It emits a WorkflowAnalysis of pre-checked GemCandidate[] plus DistilledSkill[] drafts; both feed buildGem (an accepted draft is staged into the inventory by name). The recommender only ranks what introspection already found; distillation is the deliberate exception — brand-new drafts behind a human-review gate. See Analyze.

A parallel session-intelligence surface reads the same transcripts for a different purpose: search (Recall), context-hygiene scoring, an aggregates-only chat/MCP, and Play mini-games. It's described in Session intelligence below and is independent of the Gem-build spine.

A bottom band — the community marketplace (app.agentgem.ai) — is a separate hosted service (operated by ninemind, shared by both editions) that the console signs into and publishes to: better-auth identity (GitHub / Google / X / passkeys) with /@handle profiles, the catalog and its publish scopes / versioning, and stars / reviews. Contributing to the opt-in, k-anonymized benchmark feedback loop is available to any core; groups, orgs, review-gating, and benchmark governance are Enterprise. The console (and the desktop app) carry none of this in-process — they talk to the service as a pure client (see the client/server split).

Server-side state lives under ~/.agentgem (workspaces, recents, credentials) — never inside a Gem.

The one-contract model

AgentGem is built on AgentBack. The entry point src/index.ts wires a single RestApplication with both an HTTP server and an MCP server:

const app = new RestApplication({});
app.configure("servers.RestServer").to({ port, host: "127.0.0.1" });
app.component(MCPComponent);
app.configure("servers.MCPServer").to({ name: "agentgem", version: "0.1.0", transports: { stdio: false } });
app.restController(GemController);   // REST  → /api/*
app.service(GemTools);              // MCP   → /mcp
await installExplorer(app, { title: "agentgem API" }); // OpenAPI + Swagger → /explorer
await installMcpHttp(app);
Boundary Surfaced by Path Notes
REST GemController (@api) /api/* 35+ endpoints; the stateful surface (workspaces, run, publish)
MCP GemTools (@mcpServer) /mcp 6 tools; read + plan operations for agents
OpenAPI / Swagger installExplorer /explorer Derived from the same Zod schemas
Web UI Express route / Serves the single-page builder

REST and MCP are not parallel re-implementations: both call the same helper functions (e.g. introspectAll, buildGem) and validate against the same schemas in src/schemas.ts. The REST surface simply adds the stateful operations (workspace CRUD, run, publish) that a UI needs; MCP focuses on the read-and-plan operations an agent needs. See the full list in the API reference.

Because every operation is decorator-defined, the build must compile with experimentalDecorators + emitDecoratorMetadata — see Development.

The Gem core (@agentgem/* packages)

The kernel is decomposed into 15 acyclic @agentgem/* workspace packages (pnpm workspaces + TypeScript project references) — 14 framework-agnostic kernel packages (below) plus the @agentgem/console UI SPA. The server layer in src/ stays thin and consumes them via @agentgem/*. They are framework-agnostic — no HTTP, no decorators, just functions over plain data — which is what lets the same code back a web request, an MCP tool call, and a test. The pipeline is in The build pipeline; the on-disk result in Archive format; the trust boundary in Redaction; the full dependency graph + rationale in the decomposition proposal.

Package Responsibility
@agentgem/model Core types (Gem, GemArtifact, ConfigInventory, GemCheck, …), channels, canonicalize, target specs, MCP proxy, identity, config-dir resolution
@agentgem/capture introspect ~/.claude/plugins/~/.agents/~/.codex/~/.hermes + project dirs → ConfigInventory; credentials, recents, usage, draft staging
@agentgem/base Cross-cutting helpers: redaction (redact, secret patterns, leak canary), workspaces, ACP session
@agentgem/build buildGem — select artifacts by name → a Gem (+ checks, requiredSecrets); behavioral + external (skillspector) check scaffolding
@agentgem/archive Lay a Gem out as gem.json (manifest) + gem.lock and verify integrity; serialize to a directory or a deterministic .tar.gz
@agentgem/insight Analyze: transcript scan → WorkflowSignal, default-deny scrub, distill draft skills, ACP recommender, attestation + ingest; context-hygiene detectors + bloat curve + deterministic boundarySegments (cut-here), rubrics
@agentgem/recall Cross-session transcript search: a BM25/FTS5 index (node:sqlite) over scrubbed turns → ranked cross-session moments, proven-use aware (a separate outcomes store boosts artifacts with good downstream results)
@agentgem/memory Two-way sync bridge to external AI memory providers (mem0, supermemory): pull their memories into recall, push scrubbed, consent-gated candidates out through a review outbox
@agentgem/play Mini-games as game Gems: the git-backed ~/.agentgem/miniapps/ registry, scaffolds, the save-time seal + portability gates
@agentgem/distribute Marketplace publish, share/search, curated skill sources, SSRF-guarded fetch
@agentgem/contract The neutral wire contract for the hosted marketplace API — types, signing payloads, zod schemas
@agentgem/run Run/verify a Gem; local OS sandbox + ACP run; run a materialized project locally
@agentgem/testbed Install a Gem into a local .claude/.codex/.hermes testbed; flavor detection
@agentgem/transfer NATS store-and-forward Gem transfer: seal, ticket, mint, object store

The conceptual pipeline introspect → redact → buildGem → archive therefore spans capture → base → build → archive; the optional Analyze / workflow-aware path (scan → distill drafts → recommend, see Analyze) lives in @agentgem/insight.

Session intelligence (Recall, hygiene, chat, Play)

Alongside Gem-building, AgentGem reads, searches, and grades your session history. This half is served from src/goldmine/* and src/warm/*, backed by @agentgem/recall, @agentgem/insight, and @agentgem/play, and surfaced in the console under the Observe and Build phases. See Recall, Context hygiene, Chat, and Play.

AgentGem memory sync

Diagram: diagrams/memory-sync.svg · PNG · interactive HTML (Copy / PNG / PDF export)

Distribution

The Gem is a neutral source, consumed by targets and the marketplace, plus local testbeds and runs.

AgentGem distribution

Diagram: diagrams/distribution.svg · PNG · interactive HTML

Source layout

The published npm package is CLI-only (agentgem, agentgem-distill); at pack time scripts/bundle-bins.mjs esbuild-inlines the @agentgem/* packages into the bins so the tarball is self-contained (the in-repo build uses loose dist/ + workspace links).

src/                  # the thin server layer — consumes @agentgem/* via workspace deps
  index.ts            # AgentBack wiring: REST + MCP + Explorer on one app (server entry)
  client.ts           # desktop client-mode entry — no auth/DB, benchmark proxy
  cli.ts              # `agentgem` bin — starts the server
  gem.controller.ts   # REST surface (@api) — /api/*
  gem.tools.ts        # MCP-over-HTTP surface (@mcpServer) — /mcp
  share.proxy.controller.ts · benchmark.proxy.controller.ts   # proxies to the hosted marketplace
  schemas.ts          # Zod schemas shared across surfaces
  *.stream.schema.ts · sse/pump.ts   # SSE via agentback streamOf routes (insights, workflow, rubric, scorecard, gem run/verify)
  distill/mcpServer.ts # `agentgem-distill` bin — stdio MCP (MCPApplication + @tool)
  goldmine/           # session intelligence — recall search, chat, and the
    mcpServer.ts      #   `agentgem-goldmine` bin (aggregates-only MCP over past sessions)
    recallRoutes.ts · chatRoutes.ts
  warm/               # `agentgem warm` precompute daemon + launchd/systemd service + hygiene nudge
  play.controller.ts  # Play miniapps REST surface — /api/play/*
  bind/               # `agentgem bind` device-flow auth
packages/             # the Gem core — 15 @agentgem/* workspace packages (see table above)
  console/            # the React console SPA
  memory/             # two-way memory-provider sync (mem0, supermemory)
desktop/              # Electron host — forks a client-mode core (tray + auto-update)
docs/
  diagrams/           # .svg (for docs), .png (fallback), .html (interactive export)

Where to go next