R&D prototype · synthetic data
Full AI Factory — Camera-First Manufacturing Platform

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
Design decisions
-
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"}.

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. 
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. 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. 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. 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. 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.
-
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.
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





Engineering foothold
| Claim | Evidence |
|---|---|
| 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: 156 | grep ^@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: 111 | documented 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 parametrization | agent/agents/ — 8 BaseAgent subclasses (LineMonitor/Quality/Maintenance/Planning/Energy/Safety/Coordinator/Document); parametrization documented in the project's agent spec. |
| MCP tools: 22 | agent/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 pass | files/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 350 | files/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 violations | scripts/arch_check.sh; documented in README + files/reviews/W42_Final.md |
| TypeScript strict: 0 errors | tsc --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 enforced | frontend/src/i18n/locales/{ko,en}/ — 9 namespaces each; arch_check.sh Rule 5 (key-count parity) |
| End-to-end captures: 8 dashboard + terminal verifications | images/full_factory_*.png (figures handled separately) |

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)