> ## Documentation Index
> Fetch the complete documentation index at: https://hyperscape-ai-mintlify-docs-update.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude Development Guide

> Working with Claude Code on Hyperscape

# Claude Development Guide

This guide provides instructions for working with [Claude Code](https://claude.ai/code) on the Hyperscape codebase.

<Info>
  This is a companion to `CLAUDE.md` in the main repository. See the [Hyperscape repository](https://github.com/HyperscapeAI/hyperscape/blob/main/CLAUDE.md) for the complete development guide.
</Info>

***

## Quick Reference

### Essential Commands

```bash theme={"theme":{"light":"github-light","dark":"tokyo-night"}}
# Install dependencies
bun install

# Build all packages (required before first run)
bun run build

# Development mode with hot reload
bun run dev

# Run all tests
npm test

# Lint codebase
npm run lint
```

### Package-Specific Commands

```bash theme={"theme":{"light":"github-light","dark":"tokyo-night"}}
# Build individual packages
bun run build:shared    # Core engine (must build first)
bun run build:client    # Web client
bun run build:server    # Game server

# Development mode for specific packages
bun run dev:shared      # Shared package with watch mode
bun run dev:client      # Client with Vite HMR
bun run dev:server      # Server with auto-restart
```

***

## Critical Development Rules

### TypeScript Strong Typing

**NO `any` types are allowed** — ESLint will reject them.

```typescript theme={"theme":{"light":"github-light","dark":"tokyo-night"}}
// ❌ FORBIDDEN
const player: any = getEntity(id);
if ('health' in player) { ... }

// ✅ CORRECT
const player = getEntity(id) as Player;
player.health -= damage;
```

**Rules:**

* Prefer classes over interfaces for type definitions
* Use type assertions when you know the type
* Share types from `types.ts` files - don't recreate them
* Use `import type` for type-only imports
* Make strong type assumptions based on context

### File Management

**Don't create new files unless absolutely necessary.**

* Revise existing files instead of creating `_v2.ts` variants
* Delete old files when replacing them
* Update all imports when moving code
* Clean up test files immediately after use
* Don't create temporary `check-*.ts`, `test-*.mjs`, `fix-*.js` files

### Testing Philosophy

**NO MOCKS** - Use real Hyperscape instances with Playwright.

Every feature MUST have tests that:

1. Start a real Hyperscape server
2. Open a real browser with Playwright
3. Execute actual gameplay actions
4. Verify with screenshots + Three.js scene queries
5. Save error logs to `/logs/` folder

***

## Architecture Overview

### Monorepo Structure

```
packages/
├── shared/              # Core 3D engine (ECS, Three.js, PhysX, networking, React UI)
├── server/              # Game server (Fastify, WebSockets, PostgreSQL)
├── client/              # Web client (Vite, React)
├── plugin-hyperscape/   # ElizaOS AI agent plugin
├── physx-js-webidl/     # PhysX WASM bindings
├── asset-forge/         # AI asset generation tools
└── website/             # Marketing website (Next.js 15)
```

### Build Dependency Graph

Packages must build in this order:

1. **physx-js-webidl** — PhysX WASM (takes longest, \~5-10 min first time)
2. **shared** — Depends on physx-js-webidl
3. **All other packages** — Depend on shared

The `turbo.json` configuration handles this automatically.

***

## Recent Features

### Ranged Combat (PR #691)

Complete ranged combat system with:

* Bows and arrows (Bronze → Adamant)
* Projectile rendering with 3D arrow meshes
* OSRS-accurate hit delay formulas
* Ammunition consumption (100% loss rate)
* Combat styles: Accurate, Rapid, Longrange

**Key Files:**

* `packages/shared/src/systems/shared/combat/RangedDamageCalculator.ts`
* `packages/shared/src/systems/shared/combat/AmmunitionService.ts`
* `packages/shared/src/systems/shared/combat/ProjectileService.ts`
* `packages/client/src/game/systems/ProjectileRenderer.ts`

### Magic Combat (PR #691)

Complete magic combat system with:

* Combat spells (Strike and Bolt tiers)
* Rune consumption with elemental staff support
* Autocast spell selection
* Spell projectile rendering
* OSRS-accurate magic damage formulas

**Key Files:**

* `packages/shared/src/systems/shared/combat/MagicDamageCalculator.ts`
* `packages/shared/src/systems/shared/combat/RuneService.ts`
* `packages/shared/src/systems/shared/combat/SpellService.ts`
* `packages/client/src/game/panels/SpellsPanel.tsx`
* `packages/shared/src/data/spell-visuals.ts`

### Persistence Improvements (PR #695)

Robust persistence layer with:

* Transactional equipment/bank saves
* Immediate persistence for critical operations
* Reduced auto-save intervals (30s → 5s)
* EventBus async handler tracking
* Write-ahead logging (Phase 2 scaffolding)

**Key Files:**

* `packages/server/src/persistence/PersistenceService.ts`
* `packages/server/src/database/repositories/EquipmentRepository.ts`
* `packages/server/src/database/repositories/BankRepository.ts`
* `packages/shared/src/systems/shared/infrastructure/EventBus.ts`

### Security Enhancements (PR #687)

Comprehensive security improvements:

* URL parameter validation (authToken via postMessage)
* Configurable auth storage (localStorage/sessionStorage/memory)
* CSP violation monitoring
* Timestamp validation for replay attack prevention
* Type guards for event payloads

**Key Files:**

* `packages/client/src/auth/PrivyAuthManager.ts`
* `packages/client/src/types/embeddedConfig.ts`
* `packages/client/src/lib/error-reporting.ts`
* `packages/server/src/systems/ServerNetwork/services/InputValidation.ts`

### UI/UX Improvements (PR #687)

Major UI enhancements:

* Minimap overhaul with independent width/height resizing
* Cached projection matrix for pip synchronization
* Extracted overlay controls (compass, teleport, stamina)
* Viewport scaling system with design resolution
* Combat panel 1×3 row layout for better mobile UX

**Key Files:**

* `packages/client/src/game/hud/Minimap.tsx`
* `packages/client/src/game/hud/MinimapOverlayControls.tsx`
* `packages/client/src/ui/core/responsive/ViewportScaler.tsx`
* `packages/client/src/game/interface/useViewportResize.ts`

***

## Port Allocation

| Port | Service        | Environment Variable   | Started By            |
| ---- | -------------- | ---------------------- | --------------------- |
| 3333 | Game Client    | `VITE_PORT`            | `bun run dev`         |
| 3334 | Website        | -                      | `bun run dev:website` |
| 3400 | AssetForge UI  | `ASSET_FORGE_PORT`     | `bun run dev:forge`   |
| 3401 | AssetForge API | `ASSET_FORGE_API_PORT` | `bun run dev:forge`   |
| 3402 | Documentation  | -                      | `bun run docs:dev`    |
| 4001 | ElizaOS API    | `ELIZAOS_PORT`         | `bun run dev:elizaos` |
| 5555 | Game Server    | `PORT`                 | `bun run dev`         |
| 5432 | PostgreSQL     | -                      | Docker                |
| 8080 | Asset CDN      | -                      | Docker                |

***

## Common Patterns

### Getting Systems

```typescript theme={"theme":{"light":"github-light","dark":"tokyo-night"}}
const combatSystem = world.getSystem('combat') as CombatSystem;
const inventorySystem = world.getSystem('inventory') as InventorySystem;
```

### Entity Queries

```typescript theme={"theme":{"light":"github-light","dark":"tokyo-night"}}
const players = world.getEntitiesByType('Player');
const mobs = world.getEntitiesByType('Mob');
```

### Event Handling

```typescript theme={"theme":{"light":"github-light","dark":"tokyo-night"}}
world.on('inventory:add', (event: InventoryAddEvent) => {
  // Handle event - assume properties exist
});
```

***

## Troubleshooting

### Build Issues

```bash theme={"theme":{"light":"github-light","dark":"tokyo-night"}}
# Clean everything and rebuild
npm run clean
rm -rf node_modules packages/*/node_modules
bun install
bun run build
```

### PhysX Build Fails

PhysX is pre-built and committed. If it needs rebuilding:

```bash theme={"theme":{"light":"github-light","dark":"tokyo-night"}}
cd packages/physx-js-webidl
./make.sh  # Requires emscripten toolchain
```

### Port Conflicts

```bash theme={"theme":{"light":"github-light","dark":"tokyo-night"}}
# Kill processes on common Hyperscape ports
lsof -ti:3333 | xargs kill -9  # Game Client
lsof -ti:5555 | xargs kill -9  # Game Server
```

### Tests Failing

* Ensure server is not running before tests
* Check `/logs/` folder for error details
* Tests spawn their own Hyperscape instances
* Visual tests require headless browser support

***

## Related Documentation

* [Architecture](/architecture)
* [Development Guide](/guides/development)
* [Testing](/guides/development#testing)
* [Deployment](/guides/deployment)
