# gurkalra/labta architecture

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

- Interactive diagram: https://gitdiagram.com/gurkalra/labta
- Repository: https://github.com/gurkalra/labta

## Overview

**LabTA** is a **full-stack web application** whose core value is a **closed-loop “code execution → diagnostics → AI hint/patch” pipeline** for programming labs, plus a **teacher analytics view**.

##### Agent “Brain” (Gemini + RAG over local JSON knowledge)

Additionally there is a **Knowledge/Data layer** (JSON files) used for both **RAG context** and **problem/test definitions** and **session analytics persistence**.

- **Runtime request/data flows** (student submits code → container run → diagnostics → optional LLM → response w/ hints + git-diff patch)
- **Static/module boundaries** (what lives where in the repo and why)

##### Backend (Orchestration Layer) — `backend/`
- `app.py` (FastAPI entry + routes)
- `agent.py` (Gemini calls, RAG retrieval, patch generation)
- `sandbox.py` (Docker lifecycle + execute)
- `diagnostics.py` (error parsing/prioritization)
- `__init__.py`

- Inside it (or adjacent subcomponents), explicitly split:
- “Request Router / Session Coordinator” (`app.py`)
- “Diagnostics Engine” (`diagnostics.py`)
- “Sandbox Executor” (`sandbox.py`)
- “AI Agent (RAG + Patch Logic)” (`agent.py`)

- Router → Sandbox Executor (run code)
- Sandbox Executor → Diagnostics Engine (stderr/stdout + exit code → classified errors)
- Router → AI Agent (conditional / “only when necessary”)
- AI Agent ↔ Knowledge JSONs (RAG inputs)
- Router ↔ Sessions store (read/write analytics)

##### Knowledge/Data Layer — `data/`
- `problems.json` (problem definitions + hidden tests per README)
- `error_dictionary.json` (weighted error priority rules)
- `lab_manual_index.json` (course material index for RAG)
- `sessions.json` (persistent student analytics)

- “Problem Bank + Hidden Tests (JSON)”
- “Error Priority Rules (JSON)”
- “RAG Index / Course KB (JSON)”
- “Session Analytics Store (JSON file)”

- Backend reads `problems.json` to serve problem list + to assemble sandbox run context (tests)
- Diagnostics reads `error_dictionary.json`
- Agent reads `lab_manual_index.json`
- Backend reads/writes `sessions.json` (for dashboard)

(Important: since these are JSON files in-repo, represent as **local storage** rather than a DB; optionally annotate “future: DB”.)

##### Sandbox / Infrastructure Layer — `runner/`
- `runner/Dockerfile` builds `lab-ta-runner`

- “Docker Host (Codespaces)” (or “Backend Host”)
- “Ephemeral Runner Container: lab-ta-runner”

- Backend → Docker Engine API (spawn container, mount code+tests)
- Container → Backend (logs, exit status)
- Container lifecycle note: “destroy after execution”
- Execution limits annotation: “256MB, 0.5 CPU, 5s timeout”

- “Google Gemini 2.5 Flash API” (external SaaS)
- “LLM_API_KEY from .env” (secret/config)

- AI Agent → Gemini API (prompt + context)
- Gemini API → AI Agent (hint + patch/diff)

##### Backend composes execution payload
- fetches problem + hidden tests from `data/problems.json`
##### Backend executes in Docker sandbox via `backend/sandbox.py`
- creates `lab-ta-runner` container
- mounts student code + tests
- runs with CPU/RAM/time limits
##### Diagnostics (`backend/diagnostics.py`) classifies
- Syntax vs Runtime vs Logic (as per README)
- uses `data/error_dictionary.json` to prioritize messaging
##### Decision gate: “AI needed?”
- If trivial/known: backend returns deterministic hint
- If complex/stuck: call **Agent**
##### Agent (`backend/agent.py`) does RAG
- pulls relevant snippets/index entries from `data/lab_manual_index.json`
- crafts prompt, calls **Gemini**
- returns: structured hints + optionally a **git-diff patch**
##### Frontend renders result and if patch present
- **Apply Fix Engine** parses diff and applies to editor buffer

**For the teacher dashboard flow**
- `dashboard.html` → Backend → reads `sessions.json` → returns aggregates → Chart.js renders heatmap/trends.

These two flows (student closed-loop + teacher analytics) should be separately visible.

##### Architectural patterns to highlight (because they’re central to LabTA)
- **Closed-loop execution & diagnosis**: deterministic execution first, AI second
- **Modular decoupling**: UI / Orchestration / Execution / AI reasoning / Knowledge
- **Policy & safety boundary**: Docker sandbox as a hard isolation barrier
- **Conditional AI routing**: “AI calls only when necessary” decision node
- **Patch-based assistance**: output format includes **git-diff** enabling selective application

Actors: Student, Instructor
Systems: Frontend (Vercel), Backend (Codespaces), Gemini API

Containers: Browser UI, FastAPI service, Docker runner container, JSON data store(s), External Gemini.
This is where you show Docker isolation and data JSONs clearly.

Components: `app.py` routes, `sandbox.py`, `diagnostics.py`, `agent.py`, “data access layer (JSON)”.
“AI needed?” decision node here.

##### “Don’t overthink it”: maximally separate components (what “detailed” means here)
To be very detailed (as requested), separate these items into distinct nodes instead of lumping them:
- Student Portal pages (index/selection/problem) vs Teacher Dashboard
- Backend router vs diagnostics vs sandbox vs agent
- Each JSON store as its own datastore node
- Docker “host runtime” vs “ephemeral runner container”
- “Hidden tests” as a labeled artifact mounted into the container (even if sourced from problems.json)

## Diagram (Mermaid)

```mermaid
flowchart TD

%% =========================
%% View 1: Context (C4 L1)
%% =========================
subgraph ContextL1["Context (C4 L1)"]
direction TB
Student["Student"]:::actor
Instructor["Instructor"]:::actor

FrontendSys["Frontend (Vercel/static)"]:::frontend
BackendSys["Backend Orchestrator API (Codespaces)"]:::backend
Gemini["Google Gemini 2.5 Flash API"]:::external

Student -->|"uses"| FrontendSys
Instructor -->|"uses"| FrontendSys

FrontendSys -->|"REST/JSON"| BackendSys
BackendSys -->|"LLMrequest"| Gemini
Gemini -->|"hints+patch"| BackendSys
end

%% =========================
%% View 2: Containers (C4 L2)
%% =========================
subgraph ContainersL2["Containers (C4 L2)"]
direction TB

subgraph FrontendLayer["Frontend (Presentation Layer) — frontend/"]
direction TB
StudentPortal["Student Portal (static pages)"]:::frontend
TeacherDash["Teacher Dashboard (Chart.js)"]:::frontend
Editor["CodeMirror Editor + Diff Apply Engine"]:::frontend
end

subgraph BackendLayer["Backend (Orchestration Layer) — backend/"]
direction TB
FastAPI["FastAPI API Server (Uvicorn)"]:::backend
end

subgraph DataLayer["Knowledge/Data (Local JSON) — data/"]
direction TB
Problems[("Problem Bank + Hidden Tests (problems.json)")]:::data
Rules[("Error Priority Rules (error_dictionary.json)")]:::data
RAGKB[("RAG Index / Course KB (lab_manual_index.json)")]:::data
Sessions[("Session Analytics Store (sessions.json)")]:::data
end

subgraph InfraLayer["Sandbox / Infrastructure — runner/"]
direction TB
DockerHost["Docker Host Runtime (Codespaces)"]:::infra
subgraph DockerBoundary["Isolation Boundary: Docker Sandbox"]
direction TB
Runner["Ephemeral Runner Container: lab-ta-runner"]:::sandbox
Limits["Limits: 256MB,0.5CPU,5s timeout\nLifecycle: destroy after execution"]:::note
end
end

EnvKey["Config Secret: LLM_API_KEY (.env)"]:::secret
Gemini2["Google Gemini 2.5 Flash API"]:::external

%% Container-level flows (student loop)
StudentPortal -->|"submitCode (REST/JSON)"| FastAPI
Editor -->|"submitCode+sessionId"| FastAPI
FastAPI -->|"serveProblemList"| StudentPortal
FastAPI -->|"results+diagnostics+hints+git-diff"| Editor

%% Teacher analytics flow
TeacherDash -->|"fetchAnalytics"| FastAPI
FastAPI -->|"aggregates"| TeacherDash

%% Data access (dashed)
FastAPI -.->|"readProblems+hiddenTests"| Problems
FastAPI -.->|"read/write"| Sessions
FastAPI -.->|"readRules (via diagnostics)"| Rules
FastAPI -.->|"RAGread"| RAGKB

%% Sandbox exec
FastAPI -->|"dockerExec/spawn+mount code+tests"| DockerHost
DockerHost -->|"runs"| Runner
Runner -->|"stdout/stderr+exitCode"| DockerHost
DockerHost -->|"execResult"| FastAPI
Runner --> Limits

%% External AI
FastAPI -.->|"usesKey"| EnvKey
FastAPI -->|"prompt+context"| Gemini2
Gemini2 -->|"hint+patch(diff)"| FastAPI

end

%% =========================
%% View 3: Backend Components (C4 L3)
%% =========================
subgraph BackendComponentsL3["Backend Components (C4 L3) — backend/"]
direction TB

Router["Request Router / Session Coordinator (app.py)"]:::backend
SandboxExec["Sandbox Executor (sandbox.py)"]:::backend
Diag["Diagnostics Engine (diagnostics.py)"]:::backend
Decision{"AI needed?"}:::decision
Agent["AI Agent: RAG + Patch Logic (agent.py)"]:::backend

DAL["JSON Data Access (local file I/O)"]:::backend2

subgraph LocalJSON["Local JSON Stores (data/)"]
direction TB
P2[("problems.json\nProblems+HiddenTests")]:::data
R2[("error_dictionary.json\nWeightedRules")]:::data
K2[("lab_manual_index.json\nRAGIndex")]:::data
S2[("sessions.json\nAnalytics")]:::data
end

Runner2["Docker Runner Container (lab-ta-runner)"]:::sandbox
Gemini3["Google Gemini API"]:::external
Key2["LLM_API_KEY (.env)"]:::secret

%% Closed-loop execution & diagnosis
Router -->|"composeRunPayload"| DAL
DAL -.->|"read"| P2
Router -->|"execute"| SandboxExec
SandboxExec -->|"spawnContainer+mount code+tests"| Runner2
Runner2 -->|"stdout/stderr+status"| SandboxExec
SandboxExec -->|"execOutput"| Diag
Diag -.->|"readRules"| R2
Diag -->|"classifiedErrors"| Router

Router -->|"route"| Decision
Decision -->|"no: deterministicHint"| Router
Decision -->|"yes: callAgent"| Agent

%% Agent RAG + Gemini
Agent -.->|"retrieveContext"| K2
Agent -.->|"usesKey"| Key2
Agent -->|"prompt+RAGcontext"| Gemini3
Gemini3 -->|"structuredHint+git-diffPatch"| Agent
Agent -->|"hint+patch"| Router

%% Persistence
Router -->|"persistSession"| DAL
DAL -.->|"read/write"| S2

%% Response shaping
Router -->|"returnResults+diagnostics+hints+git-diff"| FrontendSys

%% Pattern callouts
ClosedLoop["Pattern: deterministic execution first, AI second\nClosed-loop: execute→diagnose→(optional)AI→patch"]:::note
Safety["Policy & safety boundary: Docker sandbox isolates untrusted code"]:::note
PatchFmt["Patch-based assistance: git-diff enables selective apply in editor"]:::note

Router -.-> ClosedLoop
Runner2 -.-> Safety
Agent -.-> PatchFmt
end

%% =========================
%% Sequence: Submission Loop (rendered as flow)
%% =========================
subgraph SubmissionLoop["Sequence: Submission Loop"]
direction TB

SeqS["Student (Browser)"]:::actor
SeqUI["Frontend (CodeMirror + Apply Fix)"]:::frontend
SeqAPI["FastAPI Router (app.py)"]:::backend
SeqJ["JSON Stores (data/*.json)"]:::data
SeqD["Docker Sandbox (lab-ta-runner)"]:::sandbox
SeqDX["Diagnostics (diagnostics.py)"]:::backend
SeqA["Agent (agent.py)"]:::backend
SeqG["Gemini API"]:::external

SeqS -->|"Edit code in problem.html"| SeqUI
SeqUI -->|"POST /submit (problemId,code,lang,sessionId)"| SeqAPI
SeqAPI -->|"Read problems.json (hidden tests)"| SeqJ
SeqAPI -->|"Spawn container + mount code+tests\n(limits,timeout)"| SeqD
SeqD -->|"stdout/stderr/exitCode"| SeqAPI
SeqAPI -->|"Classify diagnostics"| SeqDX
SeqDX -->|"Read error_dictionary.json (priority rules)"| SeqJ
SeqDX -->|"Syntax/Runtime/Logic + prioritized messages"| SeqAPI

SeqDecision{"Decide: AI needed?"}:::decision
SeqAPI --> SeqDecision
SeqDecision -->|"AI not needed"| SeqUI
SeqDecision -->|"AI needed"| SeqA

SeqUI -->|"Deterministic hint + results"| SeqUI

SeqA -->|"RAG retrieve from lab_manual_index.json"| SeqJ
SeqA -->|"Prompt + context"| SeqG
SeqG -->|"Hint + git-diff patch"| SeqA
SeqA -->|"Structured hint + diff"| SeqAPI
SeqAPI -->|"Results + hints + git-diff patch"| SeqUI
SeqUI -->|"Apply Fix Engine parses diff and updates buffer"| SeqUI

SeqAPI -->|"Write sessions.json (analytics)"| SeqJ
SeqUI -->|"Teacher dashboard fetch (optional)"| SeqAPI
SeqAPI -->|"Aggregated analytics for Chart.js"| SeqUI

end

%% =========================
%% Click Events (mapped components)
%% =========================
click StudentPortal "https://github.com/gurkalra/labta/blob/main/frontend/index.html"
click TeacherDash "https://github.com/gurkalra/labta/blob/main/frontend/dashboard.html"
click Editor "https://github.com/gurkalra/labta/blob/main/frontend/script.js"
click FrontendSys "https://github.com/gurkalra/labta/tree/main/frontend/"
click Router "https://github.com/gurkalra/labta/blob/main/backend/app.py"
click Agent "https://github.com/gurkalra/labta/blob/main/backend/agent.py"
click SandboxExec "https://github.com/gurkalra/labta/blob/main/backend/sandbox.py"
click Diag "https://github.com/gurkalra/labta/blob/main/backend/diagnostics.py"
click FastAPI "https://github.com/gurkalra/labta/tree/main/backend/"
click Problems "https://github.com/gurkalra/labta/blob/main/data/problems.json"
click Rules "https://github.com/gurkalra/labta/blob/main/data/error_dictionary.json"
click RAGKB "https://github.com/gurkalra/labta/blob/main/data/lab_manual_index.json"
click Sessions "https://github.com/gurkalra/labta/blob/main/data/sessions.json"
click P2 "https://github.com/gurkalra/labta/blob/main/data/problems.json"
click R2 "https://github.com/gurkalra/labta/blob/main/data/error_dictionary.json"
click K2 "https://github.com/gurkalra/labta/blob/main/data/lab_manual_index.json"
click S2 "https://github.com/gurkalra/labta/blob/main/data/sessions.json"
click DAL "https://github.com/gurkalra/labta/tree/main/data/"
click DockerHost "https://github.com/gurkalra/labta/tree/main/runner/"
click Runner "https://github.com/gurkalra/labta/tree/main/runner/Dockerfile"
click Runner2 "https://github.com/gurkalra/labta/tree/main/runner/Dockerfile"

%% =========================
%% Styles
%% =========================
classDef actor fill:#E8F1FF,stroke:#2B6CB0,stroke-width:2px,color:#0B2545
classDef frontend fill:#D6ECFF,stroke:#1E5AA8,stroke-width:2px,color:#0B2545
classDef backend fill:#DFF7E6,stroke:#2F855A,stroke-width:2px,color:#123524
classDef backend2 fill:#CFF3DA,stroke:#2F855A,stroke-width:1.5px,color:#123524
classDef data fill:#F0E6FF,stroke:#6B46C1,stroke-width:2px,color:#2D1B69
classDef sandbox fill:#FFE5CC,stroke:#C05621,stroke-width:2px,color:#4A2A0A
classDef infra fill:#FFEAD7,stroke:#9C4221,stroke-width:1.5px,color:#4A2A0A
classDef external fill:#F3F4F6,stroke:#374151,stroke-width:2px,color:#111827
classDef decision fill:#FFF7CC,stroke:#B7791F,stroke-width:2px,color:#4A2A0A
classDef note fill:#FFF,stroke:#A0AEC0,stroke-dasharray:4 3,stroke-width:1.5px,color:#1A202C
classDef secret fill:#FFE0E0,stroke:#C53030,stroke-width:2px,color:#5A0B0B
```
