R&D prototype · synthetic data

Full AI Factory — Camera-First Manufacturing Platform

TL;DR. A 7-line factory platform on one thesis — when a legacy plant has no PLC sensors, replace each with a camera signal so both modes emit identical downstream events and the 19 backend modules and 14 agents never branch on factory mode. Those 14 logical agents (8 classes × line_id) run under a LangGraph 4-way fan-out -> Coordinator fan-in, with architectural invariants enforced by a pre-commit arch_check.sh. Scope is stated up front: a single-machine R&D demo on synthetic data calibrated against open datasets, not deployed in any factory, with demo-grade auth pending a documented JWT/OAuth swap.
14 logical agents 8 classes × line_id
156 REST endpoints 19 backend modules
189/189 frontend tests pass pytest backend/sim/ai/agent also pass
35/35 live health checks infra + app + module endpoints
Full AI Factory hero banner — seven isometric production line machines on the left with L1 alert glow, a fan-out and fan-in agent network in the middle converging into a Coordinator node, and three auto-generated document cards on the right
Hero banner: seven production lines feeding a fan-out / fan-in agent network that converges on a Coordinator and auto-generates documents.

Problem

Most "smart factory" platforms assume a brownfield retrofit: install dozens of new PLC-connected sensors, integrate them into the historian, build dashboards on top. That assumption fails on the line that needs help most — the small or aging auto-parts plant where every retrofit is a capex fight, where process changes are frequent enough that a fixed sensor topology gets stale within months, and where shop-floor paperwork still flows through clipboards and signed copies. The architectural question is whether you can replace each sensor signal with a camera-derived signal cheaply enough that the rest of the stack — MES, ERP, SPC, QMS, WMS, APS, CMMS, predictive maintenance, agent orchestration — doesn't have to know which mode is active. That's the gap this project investigates.

What I built

  • Built solo, end-to-end as the main developer — full stack (React/R3F UI, FastAPI backend, AI engine, LangGraph agents, simulator) plus the architecture-enforcement tooling, including Camera-First as a runtime-switchable mode (Mode B) that publishes the same Redis Streams topics and schema as Full Sensor mode (Mode A), so the 19 backend modules and 14 agents never branch on factoryMode.
  • A 14-logical-agent system built from 8 classes via line_id parametrization, orchestrated by a LangGraph 4-way fan-out -> Coordinator fan-in: every LLM verdict carries a confidence score, and timeout / exception / low-confidence (below the 0.3 default threshold) all converge on the same hand-authored Python rule-based codepath — no LLM-as-judge anywhere. The fan-in Coordinator also authors the Korean shop-floor documents (work log, daily report, handoff) in one synthesis step, so the paperwork never diverges from what the system understood.
  • Architectural invariants (Redis-Streams-only inter-module comms, 10 WS channels, audit_log on every CUD, source field on TimescaleDB inserts, ko/en i18n key parity) enforced by a 130-line pre-commit arch_check.sh hook running in <1s on every Edit/Write, with four physics-based degradation scenarios and open-dataset-calibrated line parameters (NASA C-MAPSS, Kaggle CNC tool-wear, RIAWELC/WDXI, MVTec AD) for repeatable end-to-end demonstration.

Approach

Full AI Factory 5-layer architecture with Redis Streams event bus
Five layers (presentation → application → AI/agents → data → simulator) all publish to one Redis Streams event bus; both factory modes (A Full Sensor / B Camera-First) emit identical events, so the 19 modules and 14 agents never branch on mode. Architectural invariants — Redis-Streams-only inter-module comms, 10 WebSocket channels, audit_log on every CUD, ko/en i18n parity — are enforced by the pre-commit arch_check.sh.

Design decisions

  1. 1. Camera-First is a product mode, not a fallback.

    Mode A (Full Sensor) and Mode B (Camera-First) are first-class, runtime-switchable factory modes. The contract is that both publish the same Redis Streams topics with the same schema — sensor:{lineId}, event:production:{lineId}, event:quality:{lineId}, camera:{lineId} are interchangeable from a consumer's perspective. The 19 backend modules and 14 agents do not branch on factoryMode; they treat any incoming event as ground truth and only the simulator + camera pipeline differ. This means Mode B doesn't just "degrade gracefully" — it produces the exact same operational picture the rest of the platform consumes. Mode switch is a single API call: POST /api/v1/integration/factory-mode with {"mode":"A"} or {"mode":"B"}.

    SCADA HMI in Sensor Mode showing actual sensor values on the injection machine diagram
    Mode A — Full Sensor. SCADA HMI for L1 in Sensor Mode. Each sensor point on the injection machine diagram (Z1..Z4 heater zones, hydraulic pressure, cooling, cycle time) shows the live numeric value with status-coded color. The header pill reads "Sensor Mode" in blue.
    SCADA HMI in Camera-First Mode showing camera-derived signals replacing each sensor value
    Mode B — Camera-First. Same SCADA HMI, same machine, Mode B active. Every sensor label is now a "Camera" placeholder — the camera pipeline produces the equivalent operational signal (signal-tower color, line-count, WIP estimate, OCR) and the downstream consumers don't see the difference. Header pill reads "Camera-First" in amber. The "Backend unstable" banner at the top of the capture is a transient connectionStore mock-fallback alert that fired during the mode transition — not part of the captured flow.
  2. 2. line_id parametrization, not class duplication.

    Seven production lines could have been seven monitor classes. They are not. A single LineMonitorAgent class is invoked seven times per agent-loop tick (~30 s interval), once per line_id, via a Redis Streams dispatcher. Results land in a single agent:response:line_monitor stream with line_id as a discriminator field. The invariant is enforced in three places — backend/app/main.py:ACTIVE_LINE_CODES, backend/app/modules/integration/agent_loop.py:DEFAULT_LINE_CODES, and the simulator publish loop — and called out explicitly in the project rules. Adding L8 means changing three constants, not authoring an L8MonitorAgent class. This is the kind of decision that looks small until you imagine maintaining seven near-identical agent files.

  3. 3. Confidence is the routing key, not LLM accuracy.

    Every BaseAgent.run() call wraps the LLM verdict in an AgentResult with an explicit confidence float and provider tag. A deterministic helper needs_rule_fallback() in agent/agents/base_agent.py evaluates: (a) provider == "fallback" — the LLM call already failed mechanically (all providers exhausted); (b) confidence < settings.confidence_threshold (default 0.3). Either condition routes the case to that agent's _fallback() implementation — a hand-authored Python classifier in agent/fallback/rules.py — and the result is re-wrapped with provider="rule_fallback" and an explicit fallback_reason. The same path catches LLM timeouts and exceptions: timeout, exception, and low-confidence all converge on the same deterministic codepath. There is no LLM-as-judge anywhere in the orchestration; the only thing an LLM can do is propose a verdict that a Python rule then accepts or replaces.

  4. 4. Inter-module communication is Redis Streams only — enforced at hook time.

    Backend modules (backend/app/modules/{mes,erp,spc,qms,wms,aps,cmms,energy,safety,...}) cannot import each other directly. The sole permitted cross-module channel is the Redis Streams event bus. A scripts/arch_check.sh script — wired to run automatically on every file edit — greps for cross-module imports, verifies the WS channel set is exactly the 10 documented channels, checks audit_log coverage on every CUD, checks source-field presence on TimescaleDB inserts (sensor_data / spc_measurements), and checks both hardcoded-Korean-literal absence and ko<->en i18n key-count parity. Five rules, 130 lines of bash, runs in <1 s on every file change. (The Zustand 7-store ceiling is a documented project rule but is enforced by convention, not by this script.) Documented exceptions live in docs/ARCH_EXCEPTIONS.md with explicit # arch-allow markers in code — four entries, each with a written rationale.

  5. 5. The Coordinator is the document author.

    In most multi-agent designs, document generation is a separate concern bolted onto the orchestrator. Here it is the Coordinator's natural fan-in output. After the LangGraph 4-way fan-out (Quality / Maintenance / Planning / Energy) joins, the Coordinator flattens each domain's (severity, summary) into the next AgentInput.context and synthesizes work log, daily report, and handoff document directly. The Document agent then handles routing, approval workflow, e-signature, and CAPA registration — but it inherits a fully-authored payload from the Coordinator rather than re-summarizing the agent traces itself. This means the operator never sees a difference between "what the system understood" and "what the paperwork says": there is exactly one synthesis step, and it produces both the operational alert and the document.

  6. End-to-End Flow — Heater Degradation Scenario (physics-based, not random noise)

    A single L1 anomaly traverses all five layers. simulator/scenarios/heater_degradation.py applies a quadratic drift curve to L1 Zone 1 (nozzle) over 72 simulated hours: degradation = (elapsed_h / 72)^2, accelerating slowly. After hour 48, the model adds a sympathetic compensation on Zones 2-3 (operators on real injection lines do this reflexively), and yield decays in three steps: 99.5% -> 94% -> 90%. Severity transitions through NORMAL -> INFO -> WARNING -> CRITICAL in lockstep with the curve. The seven-stage flow runs simulator -> SPC Westgard rule -> LineMonitor (with confidence-routed fallback) -> LangGraph 4-way fan-out -> Coordinator fan-in -> Document agent -> WS-pushed UI updates across four channels. The other three scenarios (die_wear on L2, electrode_wear on L5, safety_intrusion across all lines) follow the same pattern: a real degradation mode rendered as a parameterizable curve, not stochastic ground-truth labels.

    Heater degradation event flow: simulator → SPC → agent fan-out → Coordinator fan-in → document → UI
    Seven-stage flow from simulator/scenarios/heater_degradation.py → SPC Westgard rule → LineMonitor (with confidence-routed fallback) → LangGraph 4-way fan-out → Coordinator fan-in → Document agent → WS-pushed UI updates across four channels. Numbers (e.g. confidence 0.42) illustrate one example tick.

In operation

Agent Console showing LangGraph topology graph, 14 agents panel, and log feed with confidence and fallback labels
Agent Console — LangGraph topology + 14-agent state + log feed. The header shows the loop is alive: 178 ticks · 5,958 publishes · L1..L7. Center: the LangGraph topology mirrors the architecture diagram exactly — Line Monitor → 4-way fan-out (Quality / Maintenance / Planning / Energy) → Coordinator → Document, with Safety as a parallel node. Right: 14 agents (4 active in this snapshot) with confidence per agent. Bottom: the log feed shows FALLBACK, DECISION, and INFO events in real time — the rule-based fallback firing on Line Monitor is the routing decision from Design Decision #3 happening live.
Document Center pending approval queue with a coordinator-generated maintenance request modal open
Coordinator output — auto-generated maintenance request + approval modal. Document Center, Pending Approval queue (28 items in this snapshot). The open modal is a 정비요청서 (maintenance request) for Line L4, Created by: document agent, trigger: coordinator, with the structured payload (window, data_hint, description) the Coordinator flattened from the four fan-out results. Approval Flow shows Step 1 / supervisor / Pending. The "Backend unstable" banner at top is the connectionStore mock-fallback alert — not part of the captured flow, an artifact of this particular capture session.
3D digital twin view of all 7 lines with PdM overlays, alert labels, and live KPI header
3D Digital Twin — main view (ceiling toggled off). React Three Fiber scene with all 7 lines rendered, animated personnel and AGVs from the simulator's tracking events, and live PdM / alert overlays driven by ws/digital-twin. The header strip shows live KPIs (yield, OEE, cycle count, downtime). L1 (foreground left) carries a red RUL CRIT alert from the predictive-maintenance overlay — the same heater_degradation drift visualized in the architecture diagram, here rendered on the actual machine. Toggleable layers (ceiling truss, lighting, personnel, AGVs, WIP, overlay labels) live in the dedicated vizStore; this capture has the ceiling truss toggled off so the seven lane layout is fully readable.
SPC chart showing out-of-control points and a violation table
SPC out-of-control — Westgard rule trigger on L1 Zone 1. SPC page during the heater scenario: red dots mark Westgard-rule violations on the temperature chart. Each violation publishes event:quality:L1 on Redis Streams, which the agent loop picks up on the next 5-second tick.
Same 3D digital twin scene with the ceiling truss layer toggled on, showing the actual factory enclosure
Same scene, ceiling truss on. The exact same scene with the vizStore ceiling-truss layer enabled — what an operator sees standing on the shop floor. Same PdM overlays, same alert labels, but the seven lanes are partly occluded by the truss. The "Backend unstable" banner at the top is a transient connectionStore mock-fallback alert — an artifact of this capture session, not a property of the digital twin.

Engineering foothold

ClaimEvidence
Production lines: 7 (Injection / Press / Assembly / Painting / Welding / CNC / Final Inspection)simulator/lines/ — 7 line files (injection/press/assembly/painting/welding/cnc/inspection)
Backend modules: 19 (same router/service/models/schemas/events shape)backend/app/modules/ — all 19 dirs verified to have identical 5-file shape
REST endpoints: 156grep ^@router.(get|post|put|delete|patch) backend/app/modules/ = 156; matches files/reviews/W42_B_Functional.md tally
WebSocket channels: 10 (fixed, enforced)10 @app.websocket routes in backend/app/main.py; arch_check.sh Rule 4
Frontend pages: 20 (code-split)20 lazy() route imports in frontend/src/App.tsx (no frontend/src/pages/ dir exists; pages are lazy-loaded component index files)
Frontend components: 111documented in files/reviews/W42_D_Quality.md and README (excludes shadcn ui/ primitives)
Zustand stores: 7 (5 domain + 2 infrastructure, fixed)frontend/src/stores/ = 7 .ts files (project rule; NOT enforced by arch_check.sh)
Logical agents: 14 = 8 classes × line_id parametrizationagent/agents/ — 8 BaseAgent subclasses (LineMonitor/Quality/Maintenance/Planning/Energy/Safety/Coordinator/Document); parametrization documented in the project's agent spec.
MCP tools: 22agent/factory_mcp/tools.py — 22 @mcp_tool functions; agent/factory_mcp/server.py — 22 mcp.tool() registrations
TimescaleDB hypertables: 4 (sensor_data / spc_measurements / energy_readings / camera_detections, source field present)backend/scripts/init_timescaledb.py — 4 create_hypertable calls, all with a source column
Alembic revisions: 9 (linear chain, downgrade implemented for each)backend/app/migrations/versions/ — 001..009, each down_revision chains to prior, each has downgrade()
Demo scenarios: 4 physics-based (heater_degradation L1 / die_wear L2 / electrode_wear L5 / safety_intrusion)simulator/scenarios/ — 4 named scenario files present (plus tool_wear, camera_demo, base, degradation_curve)
Frontend tests: vitest 189/189 passfiles/reviews/2026-06-10_full-project-audit.md (current); raw grep = 72 test files / ~192 cases (W42's 18 files/54 tests is a stale earlier snapshot)
Backend tests: pytest pass — backend 147 / simulator 177 / ai-engine 76 / agent 350files/reviews/2026-06-10_full-project-audit.md (8/8 gates PASS; note 18 backend integration tests skip without TEST_DATABASE_URL)
Architectural invariants: 0 violationsscripts/arch_check.sh; documented in README + files/reviews/W42_Final.md
TypeScript strict: 0 errorstsc --noEmit; documented in README + 2026-06-10 audit (tsc 0err)
Live health checks: 35 / 35 pass (4 infra + 3 app + 28 module endpoints)scripts/health_check.sh = 35 check calls; files/reviews/2026-06-15_live-runtime-verification.md reports 35/35 PASS
Documented arch exceptions: 4 (each with # arch-allow + written rationale)docs/ARCH_EXCEPTIONS.md '현재 예외 (4건)' — 4 entries; 6 # arch-allow markers in code (entry 4 spans 2 import lines)
VRAM budget enforced at 11 GB ceiling (static per-model estimates, not a measured trace)ai-engine/serving/model_registry.py — ModelRegistry(max_vram_mb=11_000.0) budget enforcer + VRAM_ESTIMATES per-model table; estimates/budget, not a published measured runtime trace
i18n bundles: ko + en, key parity enforcedfrontend/src/i18n/locales/{ko,en}/ — 9 namespaces each; arch_check.sh Rule 5 (key-count parity)
End-to-end captures: 8 dashboard + terminal verificationsimages/full_factory_*.png (figures handled separately)
Terminal output of health_check.sh showing 34 passed, 0 failed
Native stack health — all checks passing. scripts/health_check.sh on the native Windows VM: 4 infrastructure services (PG × 2 / Redis / Ollama), 2 application services (Backend API / Frontend), and 28 backend module endpoint smoke checks — all checks passing. Run after ./scripts/start_dev.sh in every dev session.

Tech stack

Frontend
React 18, TypeScript, Vite, TailwindCSS, shadcn/ui, React Three Fiber + Three.js, Recharts, ReactFlow, React Query, Zustand (7-store ceiling), i18next (ko/en, key-parity enforced)
Backend
FastAPI, Python 3.12, SQLAlchemy 2, Alembic (9 linear revisions), asyncpg, structlog
AI Engine
PyTorch / ONNX Runtime (FP16), gRPC serving, PatchCore / EfficientAD (anomaly), YOLOv8n × 4 (person / pose / safety-gear / line-counting), ArcFace (face recognition), LSTM-Attention (press), CNN-GRU (CNC), TimesFM (injection), LSTM-AE, Bayesian Optimization (GPO), Chronos (energy)
Agent / LLM
LangGraph (StateGraph + 4-way fan-out + fan-in), Ollama Qwen 2.5 3B (local default), Anthropic Claude SDK (cloud fallback, single env-var swap), ChromaDB embedded (RAG), MCP (22 factory tools)
Data
PostgreSQL 16 (operational, ~48 tables), TimescaleDB 2.17 (4 hypertables, source field present), Redis 7 (cache + Streams + Pub/Sub), ChromaDB embedded, Synthetic simulation data calibrated against open datasets (NASA C-MAPSS, Kaggle CNC tool-wear, RIAWELC/WDXI, MVTec AD)

← All projects