# mikechwu/nanotoybox architecture

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

- Interactive diagram: https://gitdiagram.com/mikechwu/nanotoybox
- Repository: https://github.com/mikechwu/nanotoybox

## Overview

1. **Overall shape**
   - Atom Dojo is a multi-entrypoint repository: browser apps for interactive simulation and playback, Cloudflare serverless endpoints for sharing/account/privacy, a Python reference engine for validation, and a small companion Worker for retention tasks.
   - The architecture is centered on a physics simulation core that can be driven locally in the browser or restored from shared “capsules” and histories.

2. **Primary browser products**
   - `lab/` is the main interactive playground: React UI, Three.js rendering, simulation runtime, worker orchestration, timeline recording, and handoff/export flows.
   - `watch/` is the read-only playback app: it opens capsule/history documents, interpolates frames for smooth playback, and supports “Interact From Here” to transfer the current state into Lab.
   - `viewer/` is a minimal static trajectory viewer for simple file-based viewing.
   - `account/`, `privacy/`, `terms/`, and `privacy-request/` are separate static or semi-static entrypoints for user/account/legal/privacy flows.

3. **Physics runtime boundary**
   - The simulation engine is browser-side and designed to avoid main-thread blockage.
   - Default execution is WebAssembly (`lab/wasm/tersoff.wasm` + JS glue) inside a Web Worker; there is a JavaScript fallback and a synchronous fallback if the worker stalls.
   - The physics layer is responsible for atom positions, velocities, force calculation, integration, bond topology changes, and optional damping; the renderer/UI do not own physics state directly.

4. **Lab runtime decomposition**
   - `lab/js/runtime/` contains the major runtime subsystems: scene setup, camera, interaction, onboarding, overlay/UI hints, placement, timeline recording, handoff, and worker lifecycle.
   - State is mediated through `lab/js/store/` and selectors, while rendering is handled by `lab/js/renderer.ts` and Three.js-oriented code.
   - This separation makes the Lab app a composition of small runtime controllers rather than a single monolith.

5. **Watch playback architecture**
   - `watch/js/document/` loads capsule/history files into a document model.
   - `watch/js/playback/` reconstructs or interpolates trajectories, including topology sources that can come from stored data or reconstructed bonds.
   - `watch/js/view/` owns camera input, cinematic camera behavior, renderer integration, and layout for playback-specific UI.
   - The key boundary here is that Watch never mutates the source capsule; it derives a playback model and then hands off a selected frame/state to Lab.

6. **Capsules, histories, and shared data model**
   - Shared types and topology/history logic live in `src/`, especially `src/history/`, `src/topology/`, `src/share/`, `src/types/`, and `src/ui/`.
   - Capsule files are compact share artifacts: they preserve the simulation state needed for replay/remix, including atoms, velocities, bonds, and authored appearance metadata.
   - Full-history files are a richer format used by Watch and validation paths when complete simulation context is available.
   - The shared library is the main boundary preventing Lab, Watch, Functions, and tests from drifting on schema, code formats, and share-code rules.

7. **Share-link backend and trust boundaries**
   - `functions/` is the Cloudflare Pages Functions backend for publishing, session/auth, account APIs, capsule delivery, and privacy requests.
   - Storage is split between **D1** for relational/account/session/audit metadata and **R2** for capsule bodies and related binary objects.
   - The backend enforces auth middleware, age confirmation, CSRF-style intent/nonce flows, rate limiting, and admin gates.
   - Share codes are short, human-friendly identifiers; backend endpoints map these to stored capsule records and manage publish/delete/report flows.

8. **Account, policy, and privacy flows**
   - Account APIs in `functions/api/account/` support “me”, capsule listing, deletion, age confirmation, and account cleanup.
   - Privacy requests have a dedicated entrypoint and server-side nonce flow; the system is designed for data-access and deletion requests.
   - Policy acceptance and age gating are first-class server-enforced concerns, not just UI prompts, which matters for the route and data-flow diagram.

9. **Operational retention and cleanup**
   - `workers/cron-sweeper/` is a separate scheduled Worker that runs cleanup/audit passes against the shared backend state.
   - It handles session expiration, orphaned object sweeps, and audit-retention maintenance.
   - This is an operational subsystem, not part of the interactive app path, but it closes the loop on storage hygiene and privacy retention.

10. **Reference science and validation layer**
   - `sim/` is a Python reference implementation of the carbon simulation stack: atoms, velocity Verlet integration, Tersoff potential, minimization, and structure generation.
   - `tests/test_*.py` validate physics behavior against this reference engine, ensuring the browser implementation matches the intended model.
   - `sim/wasm/` contains C source and build assets for low-level Tersoff experimentation/reference, separate from the browser Wasm bundle used by the app.

11. **Research and future-facing ML work**
   - `ml/` contains force-decomposition and surrogate-model experimentation; it is explicitly research/deferred rather than part of the product runtime.
   - It sits beside the main codebase as a parallel scientific pipeline, useful to know for architecture diagrams only as a non-production subsystem.

12. **Canonical assets and structure library**
   - `structures/` contains the pre-relaxed canonical geometries used by Lab and tests: buckyballs, nanotubes, graphene, diamond, and sample fixtures.
   - A manifest ties these assets together as the source of initial scenes and benchmark cases.
   - These assets are part of the product model because they seed both simulation entry and watch replay examples.

13. **Testing and quality gates**
   - The repository has three major test surfaces: Vitest unit tests, Playwright end-to-end tests, and Python scientific tests.
   - Unit tests cover shared logic, app runtimes, APIs, and worker behavior; E2E tests exercise browser flows like lab entry, watch playback, and Pages-dev integration; Python tests validate physics correctness.
   - This reflects the repo’s architecture: browser simulation, serverless sharing, and scientific correctness each have their own verification path.

14. **Build/deploy boundary**
   - The front end is built with Vite, while Cloudflare Pages/Functions and Workers provide deployment/runtime hosting.
   - The app runs locally in a frontend-only mode or in a full-stack Pages-dev mode with D1 and R2 bindings.
   - For diagramming, it helps to show three deployment planes: browser apps, Cloudflare serverless backend, and offline/reference science tooling.

Main entry points: [`functions`](https://github.com/mikechwu/nanotoybox/tree/main/functions) (Pages Functions), [`src/history`](https://github.com/mikechwu/nanotoybox/tree/main/src/history) (History & topology), [`lab/index.html`](https://github.com/mikechwu/nanotoybox/blob/main/lab/index.html) (Lab), [`watch/index.html`](https://github.com/mikechwu/nanotoybox/blob/main/watch/index.html) (Watch)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_browser_apps["Browser apps"]
  node_lab_app["Lab<br/>React sim app<br/>[index.html]"]
  node_watch_app["Watch<br/>Playback app<br/>[index.html]"]
  node_viewer_app["Viewer<br/>[index.html]"]
  node_account_page["Account<br/>Static page<br/>[index.html]"]
  node_privacy_page["Privacy<br/>Static page<br/>[index.html]"]
  node_terms_page["Terms<br/>Static page<br/>[index.html]"]
  node_privacy_request_page["Privacy request<br/>Request page<br/>[index.html]"]
  node_lab_runtime["Lab runtime<br/>UI/runtime"]
  node_lab_timeline["Timeline<br/>Recording subsystem"]
  node_lab_worker["Worker bridge<br/>Simulation bridge"]
  node_watch_document["Watch docs<br/>Document loader"]
  node_watch_playback["Playback<br/>Trajectory engine"]
  node_watch_view["Watch view<br/>Render/UI"]
end

subgraph group_shared_core["Shared core"]
  node_shared_types["Shared types<br/>Schema layer"]
  node_history_topology["History & topology<br/>Domain logic"]
  node_share_core["Share core<br/>Publishing logic"]
  node_watch_handoff["Handoff utils<br/>Transfer helpers"]
end

subgraph group_cloud_backend["Cloud backend"]
  node_functions_api[("Pages Functions<br/>Serverless API")]
  node_cron_sweeper["Cron sweeper<br/>Scheduled worker<br/>[index.ts]"]
end

subgraph group_science["Science tooling"]
  node_sim_ref["Python sim<br/>Reference engine"]
  node_ml_research["ML research<br/>Experimental pipeline"]
  node_structures_lib["Structures<br/>Asset library"]
end

node_lab_app -->|"uses"| node_lab_runtime
node_lab_runtime -->|"records"| node_lab_timeline
node_lab_runtime -->|"simulates"| node_lab_worker
node_lab_app -->|"shares schema"| node_shared_types
node_lab_app -->|"reads/writes"| node_history_topology
node_lab_app -->|"seeds"| node_structures_lib
node_watch_app -->|"loads"| node_watch_document
node_watch_app -->|"derives"| node_watch_playback
node_watch_app -->|"renders"| node_watch_view
node_watch_app -->|"hands off"| node_watch_handoff
node_watch_document -->|"parses"| node_history_topology
node_watch_playback -->|"interprets"| node_history_topology
node_watch_view -->|"shares schema"| node_shared_types
node_functions_api -->|"publishes"| node_share_core
node_functions_api -->|"validates"| node_shared_types
node_functions_api -->|"stores capsules"| node_history_topology
node_functions_api -->|"maintains"| node_cron_sweeper
node_cron_sweeper -->|"sweeps"| node_share_core
node_sim_ref -->|"benchmarks"| node_structures_lib
node_sim_ref -->|"validates model"| node_history_topology
node_ml_research -.->|"experiments on"| node_sim_ref
node_privacy_request_page -->|"submits"| node_functions_api
node_account_page -->|"calls"| node_functions_api
node_privacy_page -->|"policy flow"| node_functions_api
node_terms_page -->|"policy flow"| node_functions_api

click node_lab_app "https://github.com/mikechwu/nanotoybox/blob/main/lab/index.html"
click node_watch_app "https://github.com/mikechwu/nanotoybox/blob/main/watch/index.html"
click node_viewer_app "https://github.com/mikechwu/nanotoybox/blob/main/viewer/index.html"
click node_account_page "https://github.com/mikechwu/nanotoybox/blob/main/account/index.html"
click node_privacy_page "https://github.com/mikechwu/nanotoybox/blob/main/privacy/index.html"
click node_terms_page "https://github.com/mikechwu/nanotoybox/blob/main/terms/index.html"
click node_privacy_request_page "https://github.com/mikechwu/nanotoybox/blob/main/privacy-request/index.html"
click node_lab_runtime "https://github.com/mikechwu/nanotoybox/tree/main/lab/js/runtime"
click node_lab_timeline "https://github.com/mikechwu/nanotoybox/tree/main/lab/js/runtime/timeline"
click node_lab_worker "https://github.com/mikechwu/nanotoybox/tree/main/lab/js/runtime/worker"
click node_watch_document "https://github.com/mikechwu/nanotoybox/tree/main/watch/js/document"
click node_watch_playback "https://github.com/mikechwu/nanotoybox/tree/main/watch/js/playback"
click node_watch_view "https://github.com/mikechwu/nanotoybox/tree/main/watch/js/view"
click node_shared_types "https://github.com/mikechwu/nanotoybox/tree/main/src/types"
click node_history_topology "https://github.com/mikechwu/nanotoybox/tree/main/src/history"
click node_share_core "https://github.com/mikechwu/nanotoybox/tree/main/src/share"
click node_watch_handoff "https://github.com/mikechwu/nanotoybox/tree/main/src/watch-lab-handoff"
click node_functions_api "https://github.com/mikechwu/nanotoybox/tree/main/functions"
click node_cron_sweeper "https://github.com/mikechwu/nanotoybox/blob/main/workers/cron-sweeper/src/index.ts"
click node_sim_ref "https://github.com/mikechwu/nanotoybox/tree/main/sim"
click node_ml_research "https://github.com/mikechwu/nanotoybox/tree/main/ml"
click node_structures_lib "https://github.com/mikechwu/nanotoybox/tree/main/structures"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_lab_app,node_watch_app,node_viewer_app,node_account_page,node_privacy_page,node_terms_page,node_privacy_request_page,node_lab_runtime,node_lab_timeline,node_lab_worker,node_watch_document,node_watch_playback,node_watch_view toneBlue
class node_shared_types,node_history_topology,node_share_core,node_watch_handoff toneAmber
class node_functions_api,node_cron_sweeper toneMint
class node_sim_ref,node_ml_research,node_structures_lib toneRose
```

## Components

### Browser apps

Client-side entrypoints for simulation, playback, and static policy/account pages.

- [Lab](https://github.com/mikechwu/nanotoybox/blob/main/lab/index.html): React sim app · Main interactive playground for editing, simulating, recording, and exporting capsules. · `lab/index.html`
- [Watch](https://github.com/mikechwu/nanotoybox/blob/main/watch/index.html): Playback app · Read-only capsule/history playback app with interpolation and Lab handoff. · `watch/index.html`
- [Viewer](https://github.com/mikechwu/nanotoybox/blob/main/viewer/index.html): Static viewer · Minimal trajectory viewer for simple file-based inspection. · `viewer/index.html`
- [Account](https://github.com/mikechwu/nanotoybox/blob/main/account/index.html): Static page · Account entrypoint for user profile and related flows. · `account/index.html`
- [Privacy](https://github.com/mikechwu/nanotoybox/blob/main/privacy/index.html): Static page · Public privacy policy entrypoint. · `privacy/index.html`
- [Terms](https://github.com/mikechwu/nanotoybox/blob/main/terms/index.html): Static page · Public terms entrypoint. · `terms/index.html`
- [Privacy request](https://github.com/mikechwu/nanotoybox/blob/main/privacy-request/index.html): Request page · Dedicated privacy-request entrypoint with server-side nonce flow. · `privacy-request/index.html`
- [Lab runtime](https://github.com/mikechwu/nanotoybox/tree/main/lab/js/runtime): UI/runtime · Scene, camera, interaction, onboarding, overlay, placement, and worker orchestration. · `lab/js/runtime`
- [Timeline](https://github.com/mikechwu/nanotoybox/tree/main/lab/js/runtime/timeline): Recording subsystem · History capture, export, restart-state adaptation, and transfer workflows. · `lab/js/runtime/timeline`
- [Worker bridge](https://github.com/mikechwu/nanotoybox/tree/main/lab/js/runtime/worker): Simulation bridge · Web Worker lifecycle, reconciled steps, snapshot recovery, and stall handling. · `lab/js/runtime/worker`
- [Watch docs](https://github.com/mikechwu/nanotoybox/tree/main/watch/js/document): Document loader · Loads capsule and full-history documents into a playback model. · `watch/js/document`
- [Playback](https://github.com/mikechwu/nanotoybox/tree/main/watch/js/playback): Trajectory engine · Frame search, interpolation, and topology source selection for replay. · `watch/js/playback`
- [Watch view](https://github.com/mikechwu/nanotoybox/tree/main/watch/js/view): Render/UI · Camera input, cinematic view, renderer integration, and watch-specific layout. · `watch/js/view`

### Shared core

Common schemas, topology, history, policy, and UI primitives used across runtimes.

- [Shared types](https://github.com/mikechwu/nanotoybox/tree/main/src/types): Schema layer · Common domain and worker protocol types shared across apps and backend. · `src/types`
- [History & topology](https://github.com/mikechwu/nanotoybox/tree/main/src/history): Domain logic · Capsule/history schema, bond policy, connected components, and topology resolution. · `src/history`
- [Share core](https://github.com/mikechwu/nanotoybox/tree/main/src/share): Publishing logic · Share-code generation, publish/delete primitives, rate limits, and record/audit helpers. · `src/share`
- [Handoff utils](https://github.com/mikechwu/nanotoybox/tree/main/src/watch-lab-handoff): Transfer helpers · Normalizes watch seeds and builds watch-to-lab transfer URLs. · `src/watch-lab-handoff`

### Cloud backend

Cloudflare Functions and scheduled Worker for sharing, auth, privacy, and retention.

- [Pages Functions](https://github.com/mikechwu/nanotoybox/tree/main/functions): Serverless API · Cloudflare backend for auth, publishing, account APIs, capsule delivery, and privacy requests. · `functions`
- [Cron sweeper](https://github.com/mikechwu/nanotoybox/blob/main/workers/cron-sweeper/src/index.ts): Scheduled worker · Retention worker for session cleanup, orphan sweeps, and audit maintenance. · `workers/cron-sweeper/src/index.ts`

### Science tooling

Reference simulation and experimental research tooling outside the browser product runtime.

- [Python sim](https://github.com/mikechwu/nanotoybox/tree/main/sim): Reference engine · Reference physics implementation for atoms, integration, potentials, minimization, and I/O. · `sim`
- [ML research](https://github.com/mikechwu/nanotoybox/tree/main/ml): Experimental pipeline · Surrogate-model and force-decomposition experiments kept separate from product runtime. · `ml`
- [Structures](https://github.com/mikechwu/nanotoybox/tree/main/structures): Asset library · Canonical relaxed geometries and manifest used by Lab, Watch, and tests. · `structures`

## Connections

- Lab → Lab runtime: uses · Lab composes runtime controllers for scene, camera, interaction, and overlays.
- Lab runtime → Timeline: records · Runtime feeds timeline capture, export, and transfer orchestration.
- Lab runtime → Worker bridge: simulates · Runtime delegates physics execution and recovery to the worker bridge.
- Lab → Shared types: shares schema · Lab depends on shared types and worker protocol definitions.
- Lab → History & topology: reads/writes · Lab creates and exports capsule/history data through the shared domain model.
- Lab → Structures: seeds · Initial scenes and benchmarks come from the canonical structure library.
- Watch → Watch docs: loads · Watch turns capsule/history files into a document model.
- Watch → Playback: derives · Watch reconstructs and interpolates trajectories for playback.
- Watch → Watch view: renders · Watch view owns camera, renderer, and playback UI layout.
- Watch → Handoff utils: hands off · Watch transfers selected state into Lab via shared handoff utilities.
- Watch docs → History & topology: parses · Document loading relies on shared history and topology formats.
- Playback → History & topology: interprets · Playback uses shared topology/history rules to reconstruct frames.
- Watch view → Shared types: shares schema · Watch view uses the same domain and protocol shapes as Lab.
- Pages Functions → Share core: publishes · Backend exposes publish, delete, report, and lookup flows using shared share logic.
- Pages Functions → Shared types: validates · Server endpoints and auth flows rely on shared schema types.
- Pages Functions → History & topology: stores capsules · Capsule records and previews are tied to the shared history/topology model.
- Pages Functions → Cron sweeper: maintains · Backend state is periodically cleaned and audited by the scheduled worker.
- Cron sweeper → Share core: sweeps · Retention tasks reuse shared delete/audit primitives.
- Python sim → Structures: benchmarks · Python reference code loads canonical structures for validation and generation.
- Python sim → History & topology: validates model · Scientific tests compare browser behavior against the reference physics model.
- ML research → Python sim: experiments on · Research scripts build on the reference simulation stack.
- Privacy request → Pages Functions: submits · Privacy request UI depends on server-side nonce and request handling.
- Account → Pages Functions: calls · Account entrypoint is backed by account/session APIs.
- Privacy → Pages Functions: policy flow · Policy acceptance and privacy-related flows are enforced server-side.
- Terms → Pages Functions: policy flow · Terms entrypoint participates in the overall policy boundary.
