Technical Architecture — Agent Forge v29

How Agent Forge
was engineered

A full-stack AI training platform built in TypeScript from first principles — covering system design, architectural decisions, data models, and the engineering rationale behind every major choice.

21,766 lines of TypeScript
12 automated tests
19 database tables
7 product modules
17 languages
5 AI agents

System Architecture

Agent Forge is a monorepo with a shared TypeScript codebase. The frontend and backend run as a single Node.js process in production, with Vite handling the client bundle. All API traffic flows through tRPC procedures — there are no REST endpoints for feature logic.


  Browser (React 19 + Tailwind 4)
  │
  ├── tRPC Client (TanStack Query)  ──────────────────────────────┐
  │   └── trpc.*.useQuery / useMutation                          │
  │                                                               ▼
  ├── Web Speech API (real-time STT)          Express Server (Node.js)
  │   └── SpeechRecognition → interim text    │
  │                                           ├── tRPC Router
  └── Audio playback (base64 MP3)             │   ├── auth.*        (OAuth, session)
                                              │   ├── simulation.*  (scenarios, sessions)
                                              │   ├── courses.*     (AI authoring)
                                              │   ├── sandbox.*     (flags, personas)
                                              │   ├── agentic.*     (5-agent system)
                                              │   └── coaching.*    (personas, chat, TTS, report)
                                              │
                                              ├── LLM (GPT-4 class)
                                              │   └── invokeLLM()
                                              │
                                              ├── ElevenLabs TTS
                                              │   └── elevenLabsTTS() → MP3 buffer
                                              │
                                              ├── Drizzle ORM
                                              │   └── TiDB Serverless (MySQL)
                                              │
                                              └── AWS S3
                                                  └── storagePut() / storageGet()

Voice Simulation Data Flow

The voice simulation loop was redesigned from a 4-step manual process (record → stop → transcribe → send) to a fully automatic cycle. The user speaks; the AI responds. No buttons, no waiting, no decisions.

1

User speaks

Web Speech API captures audio in real time, streaming interim results to a live transcript bubble in the UI.

2

Silence detected

After 1.5s of silence, the final transcript is sent to the tRPC speakText procedure via a useMutation call.

3

AI generates response

The server calls invokeLLM() with the scenario system prompt, conversation history, and user message. The LLM returns a text response.

4

TTS synthesis

The response text is passed to elevenLabsTTS() with the persona-matched voice ID. The server returns an MP3 buffer as a base64 data URL.

5

Audio playback

The client decodes the base64 URL into an Audio object and plays it. The animated orb transitions to 'speaking' state with sound-wave animation.

6

Auto-restart

When audio ends, the orb returns to 'listening' state and the Web Speech API restarts automatically — no user action required.

7

Real-time scoring

In parallel, the server calls the scoring LLM with the user's message and appends a score object to the session's messages array in TiDB.

Technology Stack

Every dependency was chosen for a specific reason — not defaults or familiarity. The table below maps each library to the problem it solves.

Frontend
React 19UI rendering with concurrent features
TypeScript 5End-to-end type safety
Tailwind CSS 4Utility-first styling with OKLCH tokens
tRPC 11 ClientType-safe RPC calls — no REST boilerplate
TanStack Query 5Server state, caching, optimistic updates
WouterLightweight client-side routing
RechartsAnalytics charts and radar visualisations
Framer MotionMicro-interactions and state transitions
react-i18next17-language internationalisation
Web Speech APIReal-time browser-native STT (no upload)
Backend
Node.js + Express 4HTTP server and middleware layer
tRPC 11 ServerProcedure-based API with Zod validation
Drizzle ORMType-safe SQL queries against TiDB/MySQL
SuperjsonSerialises Date/BigInt across the wire
Jose (JWT)Session cookie signing and verification
OAuth 2.0 / SSOZero-config single sign-on — no password storage
Vite (SSR bridge)Dev-server proxy and HMR
AI & Voice
LLM (GPT-4 class)Scenario roleplay, feedback generation, course authoring
ElevenLabs Turbo v2.5Persona-matched TTS — 32 languages, <400ms latency
Whisper APIFallback STT for browsers without Web Speech API
D-ID SDKTalking-head avatar for persona simulation
Infrastructure
TiDB ServerlessMySQL-compatible distributed database
AWS S3Audio recordings, persona avatars, course assets
Cloud Run (Autoscale)Serverless Node.js deployment, min-instances=0
Vitest12 automated unit tests across routers and integrations

Key Engineering Decisions

The decisions below reflect deliberate trade-off analysis — each one had a clear problem, a considered solution, and an acknowledged downside. This is the kind of reasoning that distinguishes architecture from assembly.

tRPC over REST

Problem

Traditional REST APIs require duplicated type definitions on client and server, leading to runtime type mismatches and verbose boilerplate.

Decision

tRPC 11 with Superjson serialisation provides end-to-end TypeScript inference. Procedures defined in server/routers.ts are consumed directly in React components via trpc.*.useQuery/useMutation — no shared contract files, no Axios wrappers, no manual type casting.

Trade-off

Tighter client-server coupling. Acceptable for a single-team product where both layers evolve together.

Web Speech API for real-time STT

Problem

The original voice flow required four manual steps: tap Record → speak → tap Stop → tap Send. This created cognitive friction that broke the simulation immersion.

Decision

The browser-native Web Speech API provides continuous real-time transcription with zero upload latency. A 1.5-second silence detector automatically submits the transcript, creating a zero-decision voice loop. Whisper API is used as a fallback for Safari and Firefox.

Trade-off

Web Speech API is Chrome/Edge-only for full support. The fallback path preserves functionality across all browsers at the cost of higher latency.

ElevenLabs Turbo v2.5 for TTS

Problem

Browser-native TTS (SpeechSynthesis API) produces flat, robotic output that undermines the realism of a sales or interview simulation.

Decision

ElevenLabs eleven_turbo_v2_5 model is called server-side, returning MP3 audio streamed to the client. Voice IDs are mapped to scenario personas by name and category — Sarah Chen gets Bella (warm female), board executives get Arnold (crisp male). The model handles all 32 supported languages automatically based on text content.

Trade-off

API cost per character. Mitigated by a 500-character cap per response and server-side fallback to built-in TTS when quota is exhausted.

Drizzle ORM over Prisma

Problem

Prisma's query engine is a native binary that does not run in Cloud Run's Node-only build image without additional configuration.

Decision

Drizzle ORM is a pure TypeScript/JavaScript library with no native binary dependency. It compiles to raw SQL, is fully compatible with TiDB's MySQL wire protocol, and produces typed query results that flow directly into tRPC procedures without additional mapping.

Trade-off

Drizzle's migration tooling is less mature than Prisma's. Migrations are applied manually via webdev_execute_sql to maintain explicit control over schema changes.

Serverless (Autoscale) hosting

Problem

A training platform used episodically (not 24/7) would waste cost on always-on reserved instances.

Decision

Cloud Run Autoscale with min-instances=0 means the platform costs nothing when idle and scales to handle concurrent users during active sessions. The 180-second request timeout is sufficient for all LLM and TTS operations.

Trade-off

Cold starts of 2–4 seconds on first request after idle. Acceptable for a training tool; not suitable for real-time financial or safety-critical systems.

Role-based access via database enum

Problem

Admin features (scenario creation, user management, agentic dashboard) must be gated without introducing a separate auth service.

Decision

The users table includes a role enum (user | admin). Every protected tRPC procedure checks ctx.user.role before executing. adminProcedure is a middleware layer that throws FORBIDDEN before any business logic runs. Frontend conditionally renders admin nav items based on useAuth().user?.role.

Trade-off

Role promotion requires a direct SQL update. Intentional — it prevents accidental privilege escalation and keeps the permission model auditable.

Database Schema

19 tables in TiDB Serverless (MySQL-compatible), defined in drizzle/schema.ts with full TypeScript inference. All timestamps are stored as UTC; all scores are stored as floats to support fractional precision.

TablePurpose
usersAuth identity, role, streak tracking, aggregate stats
scenariosSimulation blueprints — persona, system prompt, channel, language lock, folder
sessionsPractice session lifecycle — status, per-dimension scores, feedback summary
messagesIndividual conversation turns with per-message scores and AI feedback
walkthroughsStep-by-step product walkthrough definitions
walkthrough_completionsPer-user walkthrough progress tracking
coursesAI-generated eLearning courses from uploaded documents
lessonsOrdered lesson units within a course
content_blocksAtomic content units — text, key-concept, quiz, summary
course_enrollmentsLearner progress and completion state per course
sandbox_instancesProduct sandbox environments with status and preview URLs
feature_flagsRollout percentage, targeting rules, kill switches
test_runsSynthetic conversation test scripts and pass/fail results
personasReusable AI persona definitions with version history
sandbox_eventsFull event stream per sandbox for replay and audit
agent_eventsAgentic system events — nudges, interventions, orchestration logs
coaching_nudgesAI-generated coaching interventions per learner
learning_pathsAdaptive learning path recommendations per user
difficulty_adjustmentsDynamic difficulty tuning records per session

Product Modules

Agent Forge is composed of 7 independent product modules, each with its own routes, tRPC router, and database tables. Modules are loosely coupled — a user can use the course builder without ever touching the simulation engine.

🎭

Communication Simulation

5 scenario categories, 5 AI personas, real-time scoring across 5 dimensions, session replay.

/scenarios/simulate/:sessionId/session/:id/result/session/:id/replay
📚

eLearning Course Builder

Document upload → AI course generation → block editor → SCORM export → public learner view.

/courses/courses/new/courses/:id/edit/learn/:slug
🗺️

Tool Walkthrough Player

Guided spotlight walkthrough with step tooltips, progress tracking, and completion certificates.

/walkthroughs/walkthroughs/:id
🔬

Product Sandbox

Engineering control plane — feature flags, AI behaviour tester, synthetic test runner, persona lab, event log.

/sandbox/sandbox/flags/sandbox/ai-tester/sandbox/test-runner/sandbox/personas/sandbox/events
🤖

Agentic Dashboard

5-agent orchestration system — Readiness Predictor, Coaching Nudge, Difficulty Adjuster, Content Curator, Engagement Monitor.

/agentic-dashboard
📊

Analytics & Progress

Recharts radar/trend/bar visualisations, streak tracking, leaderboard, readiness predictions.

/dashboard/analytics/leaderboard/readiness
🧠

AI Coaching

4 coach personas (Socratic, GROW, Solution-Focused, Directive) — voice-enabled 1:1 sessions, session arc tracking, post-session coaching report. Beta.

/coaching

Testing & Code Quality

All server-side logic is covered by Vitest unit tests. TypeScript strict mode is enabled across the entire monorepo. The CI check runs tsc --noEmit and vitest run before every deployment.

12 / 12 tests passing

Vitest — simulation, auth, ElevenLabs

0 TypeScript errors

strict mode, noImplicitAny, strictNullChecks

50-criterion QA scoring

Automated per-message evaluation by LLM

Security Model

No password storage

Authentication is delegated entirely to OAuth 2.0 SSO. The platform stores only an openId reference — never a password hash.

Server-side API keys

ElevenLabs, LLM, and S3 credentials are injected as server-side environment variables. No API key is ever sent to the browser.

JWT session cookies

Sessions are signed with HS256 using a platform-injected JWT_SECRET. Cookies are HttpOnly and SameSite=Lax.

Role-gated procedures

Every admin operation is wrapped in adminProcedure middleware that throws FORBIDDEN before executing any business logic.

S3 path randomisation

File keys include nanoid random suffixes to prevent enumeration attacks on uploaded assets.

Zod input validation

All tRPC procedure inputs are validated with Zod schemas before reaching any database or LLM call.

Agentic Orchestration System

Agent Forge includes a 5-agent orchestration layer that operates autonomously on learner data. Each agent has a single responsibility and writes its outputs to dedicated database tables, which the Agentic Dashboard reads in real time.

🎯

Readiness Predictor

Analyses session history and score trends to predict whether a learner is ready to advance to the next difficulty tier. Writes to difficulty_adjustments.

💬

Coaching Nudge Agent

Detects learners who have not practised in 48+ hours or whose scores are declining. Generates personalised coaching messages. Writes to coaching_nudges.

⚖️

Difficulty Adjuster

Dynamically modifies the AI persona's behaviour mid-session based on real-time scoring — making the simulation harder or easier without interrupting the conversation.

📖

Content Curator

Recommends scenarios and walkthroughs based on a learner's weakest scoring dimensions. Writes to learning_paths.

📡

Engagement Monitor

Tracks session abandonment patterns, time-to-first-message, and response latency to identify at-risk learners. Writes to agent_events.

Learning Science Foundations

Agent Forge's architecture is grounded in three evidence-based learning science frameworks. Each framework directly informs a distinct technical component — the connection between pedagogy and engineering is explicit, not incidental.

01

Ericsson's Deliberate Practice Theory

Informs: Unlimited Repetition with Immediate Feedback

Expert-level performance is not the result of innate talent but of sustained, focused practice with immediate feedback. Agent Forge implements this through unlimited repetition of targeted scenarios with real-time coaching interventions — the digital equivalent of Rapid Cycle Deliberate Practice (RCDP) used in medical simulation training.

02

Vygotsky's Zone of Proximal Development

Informs: Adaptive Difficulty Calibration

Learning occurs most effectively in the zone between what a learner can accomplish independently and what they can achieve with guidance. The Adaptive Difficulty Agent functions as a digital scaffold, continuously calibrating challenge levels to maintain each learner within their personal ZPD — never so easy that learning stalls, never so difficult that confidence collapses.

03

Bloom's Revised Taxonomy

Informs: Higher-Order Assessment Design

Rather than testing recall (Level 1) or comprehension (Level 2), Agent Forge evaluates at the higher-order levels: Application, Analysis, and Evaluation. This ensures training transfers to production performance rather than merely testing memorisation of procedures. Most platforms assess at Bloom's Level 1–2 via multiple-choice quizzes; Agent Forge assesses at Levels 3–6 through authentic performance.

50-Point Competency Rubric

Every simulation session is automatically scored across 6 competency domains by the Evaluation Agent. The rubric satisfies three requirements simultaneously: pedagogical validity (scores reflect genuine competency), production alignment (categories map to enterprise QA frameworks), and predictive power (simulation scores correlate with real-world performance).

Scoring uses a criterion-referenced approach — scores reflect absolute competency against defined standards, not relative performance against peers. The rubric deliberately targets Bloom's Levels 3–6 (Apply, Analyse, Evaluate, Create) — not recall or comprehension.

DomainPointsWeightBloom's LevelExample Assessment
Decision Quality1530%Analyse / Evaluate (L4–L5)Did the agent identify root cause from multiple symptoms?
Process Adherence1020%Apply (L3)Did the agent apply the correct verification procedure?
Communication1020%Evaluate / Create (L5–L6)Did the agent synthesise a coherent case summary?
Tool Proficiency510%Apply (L3)Did the agent use the CRM tools correctly and efficiently?
Documentation510%Create (L6)Did the agent produce accurate, complete case notes?
Time Efficiency510%Apply (L3)Did the agent resolve the issue within the target handle time?

Kirkpatrick 4-Level Alignment

The evaluation framework maps to all four levels of Kirkpatrick's training evaluation model — a distinction from most platforms that only measure Levels 1 and 2. Level 1 (Reaction): post-session satisfaction score. Level 2 (Learning): 50-point rubric domain breakdown. Level 3 (Behaviour): score trajectory and coaching dependency reduction over time. Level 4 (Results): Predictive Readiness Score estimating time-to-production-threshold.

Coaching Agent — 3-Tier Intervention System

The Coaching Agent monitors learner actions in real time and delivers contextual interventions calibrated to avoid disrupting simulation flow. Research shows that forced scaffolding creates dependency — so interventions are severity-tiered and non-intrusive by design.

Tier

Hint

Trigger

Missed opportunity

UX Pattern

Non-blocking notification badge

Tier

Warning

Trigger

Procedural error

UX Pattern

Slide-in panel, requires acknowledgement

Tier

Critical

Trigger

Compliance violation

UX Pattern

Full overlay, requires correction before continuing

Inter-Agent Communication — Cascade Example

The orchestration layer manages a shared state bus where agents publish events and subscribe to relevant signals. A single learner action can trigger a coordinated cascade across all five agents simultaneously. The example below shows what happens when a critical compliance error is detected.

1

Submits response

Learner

The learner's message is sent to the tRPC speakText procedure.

2

Generates customer reply

Simulation Agent

Produces the AI customer's next response within persona constraints.

3

Evaluates for intervention triggers

Coaching Agent

Analyses the response against compliance rules and best-practice benchmarks.

4

Publishes CRITICAL_ERROR event

Coaching Agent

If a critical error is detected, broadcasts to the shared state bus.

5

Reduces persona complexity by 0.2

Adaptive Difficulty Agent

Subscribes to CRITICAL_ERROR — softens the customer persona to prevent confidence collapse.

6

Logs error with timestamp

Evaluation Agent

Records the error for post-session 50-point rubric scoring.

7

Updates competency map

Planning Agent

Receives session-end summary and adjusts the learner's personalised learning path.

AI Coaching Module Beta

The AI Coaching module is a distinct pillar from simulation — where simulation trains performance through repetition, coaching develops the person through reflection. The module is built on four coach personas, each grounded in a real coaching framework, with a voice-first session experience and a structured post-session report.

CoachStyleFrameworkFocusElevenLabs Voice
Maya ChenSocratic / ReflectiveClean Language + Appreciative InquiryLeadership identity, self-awareness, valuesBella (warm female)
James WhitfieldGROW ModelGoal → Reality → Options → WillSales performance, career targets, goalsAdam (deep male)
Priya SharmaSolution-FocusedSFBC + Narrative CoachingCareer transitions, confidence, imposter syndromeGrace (calm female)
Marcus ReidDirective / ChallengeGestalt + Ontological CoachingExecutive presence, stakeholder influenceArnold (crisp male)

Session Arc

Every coaching session follows a 5-phase arc tracked implicitly through conversation history. The LLM system prompt instructs the coach to move through phases naturally — no explicit state machine required.

1
Check-in
2
Exploration
3
Insight
4
Action
5
Close

Post-Session Coaching Report

At session end, the full conversation transcript is passed to the LLM with a structured JSON schema. The report is personalised — it references specific things the coachee said, not generic feedback.

sessionSummary

2–3 sentence essence of the session

keyInsight

The single most important realisation

breakthroughMoment

The exchange that created most movement

commitment

Specific action with timeframe

strengthsObserved

Array of strengths the coach noticed

growthEdge

One area most ripe for development

reflectionQuestions

3 questions to sit with before next session

nextSessionFocus

Recommended focus for next session

coachNote

Personal note from the coach to the coachee

Competitive Differentiation

Agent Forge occupies a unique position — combining multi-agent AI simulation with adaptive difficulty, a 50-point automated rubric, and zero license cost. No existing commercial platform implements all of these capabilities in a single product.

PlatformApproachLimitation vs Agent Forge
Second NatureAI role-play for salesSingle-agent, sales-only, no CRM simulation or multi-agent orchestration
SolidroadAI conversation practiceNo multi-agent orchestration, no adaptive difficulty, no 50-point rubric
MindtickleRevenue enablementSales-focused, no customer service depth, no real-time coaching tiers
WalkMeDigital adoption platformGuidance overlays only, not simulation-based training — no AI roleplay or scoring
Articulate RiseeLearning authoringStatic content, no AI, no real-time interaction or adaptive difficulty

Explore the live platform

Every architectural decision described on this page is visible in the running product. No login required to explore scenarios, walkthroughs, or the agentic dashboard.

Built by Samir Das · agentforge.org.uk