# Craft++ → BYOND Full Replication: Implementation Roadmap

**Goal:** Achieve feature and ability parity with BYOND Dream Maker through systematic design replication.

**Status:** Planning Phase  
**Estimated Duration:** 12-16 weeks (depending on team size)

---

## Phase Architecture Overview

```
┌─────────────────────────────────────────────────────────────┐
│              Craft++ Full BYOND Replication                │
├─────────────────────────────────────────────────────────────┤
│ PHASE 1: Language Parity (Weeks 1-2)                        │
│ ├─ Complete operator support (bitwise, power, etc.)        │
│ ├─ Weak/strict type coercion semantics                     │
│ ├─ Relative path operators (.. and .)                      │
│ ├─ Complete preprocessor (function macros, conditionals)   │
│ └─ All missing built-in procs                              │
├─────────────────────────────────────────────────────────────┤
│ PHASE 2: Architecture Refactor (Weeks 3-4)                 │
│ ├─ Split into Dream Daemon (server) + Dream Seeker (client)│
│ ├─ Implement bytecode IR/VM backend                        │
│ ├─ Network protocol layer (TCP/binary)                     │
│ └─ DreamCodec (serialization for game state)               │
├─────────────────────────────────────────────────────────────┤
│ PHASE 3: Server-Side Runtime (Weeks 5-7)                   │
│ ├─ Dream Daemon executable (.NET console app)              │
│ ├─ Tick-based game loop (tick scheduling)                  │
│ ├─ Bytecode execution engine                               │
│ ├─ Networking server (accept Dream Seeker connections)     │
│ ├─ World persistence and state management                  │
│ └─ Proc scheduling (spawn, sleep, timing)                  │
├─────────────────────────────────────────────────────────────┤
│ PHASE 4: Client-Side Runtime (Weeks 8-9)                   │
│ ├─ Standalone Dream Seeker (WPF app)                       │
│ ├─ Network protocol client                                 │
│ ├─ Tile rendering engine (software rasterization)          │
│ ├─ Input handling (verbs, movement, click events)          │
│ ├─ HUD rendering (stat panels, inventory)                  │
│ └─ Client-side interpolation & prediction                  │
├─────────────────────────────────────────────────────────────┤
│ PHASE 5: IDE Enhancement (Weeks 10-11)                     │
│ ├─ Debugger integration (breakpoints, watches, call stack) │
│ ├─ Bytecode disassembler                                   │
│ ├─ Profiler (CPU, memory, object counts)                   │
│ ├─ Live object inspector during execution                  │
│ ├─ Dream Maker-like verb panel                             │
│ └─ Map editor enhancement (tile placement, layers)         │
├─────────────────────────────────────────────────────────────┤
│ PHASE 6: Polish & Testing (Weeks 12-16)                    │
│ ├─ Regression test suite (100+ test cases)                 │
│ ├─ Performance optimization                                │
│ ├─ Documentation & examples                                │
│ ├─ Artifact (.dmb/.rsc) compatibility                      │
│ └─ Distribution packaging                                  │
└─────────────────────────────────────────────────────────────┘
```

---

## PHASE 1: Language Parity (Weeks 1-2)

### 1.1 Missing Operators

**Current Status:** Arithmetic, comparison, logical, bitwise, power, and compound bitwise/shift assignments implemented; conformance expansion continues.

**TODO:**
- [x] Bitwise: `&`, `|`, `^`, `~`, `<<`, `>>`
- [ ] Power: `**` (x to the power of y)
- [ ] Modulo assignment: `%=`
- [x] Bitwise assignment: `&=`, `|=`, `^=`, `<<=`, `>>=`
- [ ] String concatenation auto-coercion
- [ ] List/string indexing with negative indices (BYOND: -1 = last element)
- [ ] Associative list keys (dict-like access)

**Files to Modify:**
- `Tokens.cs` — Add missing token types
- `Lexer.cs` — Tokenize new operators
- `Parser.cs` — Build binary/unary expr nodes
- `Interpreter.cs` — Evaluate operators

### 1.2 Type Coercion Semantics

**Current:** Strict type checking  
**Target:** BYOND weak typing (auto-coerce where sensible)

**Examples:**
```
"hello" + 5 → "hello5"           // String concatenation coercion
5 + "10" → 15                     // Numeric addition coercion
null + 5 → 5                      // Null is neutral element
list + item → appends to list
```

**Implementation:**
- Modify `BinaryExpr.Evaluate()` to handle coercion rules
- Add `ToNumber()`, `ToText()`, `ToList()` helpers to CraftValue
- Implement auto-casting for operator operands

### 1.3 Relative Path Operators — CORRECTED (was based on inaccurate assumptions)

**Status:** Already implemented; no further work needed here.

Real BYOND DM does **not** have a generic "relative variable access" operator like
`..danger` (read parent type's var) or `../river` (sibling type path) as this section
previously claimed. Verified against DM grammar/tooling (SpacemanDMM/dreamchecker):

- `..()` — calls the parent proc. **Implemented** in Craft++ (`Interpreter.Expressions.cs`).
- Bare `.` in an expression — the implicit return-value pseudo-variable of the current
  proc. **Implemented** (`Parser.cs` `VariableExpr(".")`, `Interpreter.Invoke.cs` `.` slot).
- `:` — the lax/type-unsafe dereference operator. **Implemented** (`Parser.cs` `Call()`,
  disambiguated from labels/switch/ternary via same-line checks).
- Type path declarations (`/mob/player`) are always **absolute** in real DM — there is no
  `../sibling` relative path literal for type references. Do not implement this; it would
  be a Craft++-only invention, not BYOND compatibility.

~~**Current:** Absolute paths only (`/mob/player`)~~
~~**Target:** Relative paths (`.`, `..`, `../sibling`)~~
~~(superseded — see corrected note above)~~


### 1.4 Complete Preprocessor

**Current:** Basic `#define`, `#undef`, `#include`  
**Target:** Full DM preprocessor parity

**Missing:**
- `#ifdef`, `#ifndef`, `#else`, `#elif` conditional compilation
- Function-like macros: `#define ADD(x, y) (x + y)`
- Predefined macros: `__LINE__`, `__FILE__`, `__TIMESTAMP__`
- `#error`, `#warn` directives

**Files:**
- `Preprocessor.cs` — Expand to handle conditionals and function macros

### 1.5 Missing Built-in Procs

**High Priority (frequently used):**

| Proc | Category | Signature | Purpose |
|------|----------|-----------|---------|
| `input()` | I/O | `input(msg, list/options)` | Prompt user for input |
| `alert()` | UI | `alert(text, title, button1, ...)` | Show modal dialog |
| `prompt()` | UI | `prompt(msg, default)` | Text input prompt |
| `walk()` | Movement | `walk(obj, direction, speed)` | Animated movement |
| `walk_to()` | Movement | `walk_to(obj, target, dist)` | Path-find to target |
| `step()` | Movement | `step(obj, direction)` | Single tile step |
| `get_dist()` | Spatial | `get_dist(a, b)` | Manhattan/Euclidean distance |
| `get_dir()` | Spatial | `get_dir(a, b)` | Direction from A to B |
| `turn()` | Spatial | `turn(dir, angle)` | Rotate direction |
| `view()` | Spatial | `view(dist, center)` | Objects in view range |
| `orange()` | Spatial | `orange(dist, center)` | Objects (excluding center) |
| `range()` | Spatial | `range(dist, center)` | Rectangular region |
| `new()` | Object | `new /path(args)` | Create instance |
| `del()` | Object | `del(obj)` | Destroy instance |
| `locate()` | Object | `locate(x, y, z)` | Find obj at position |
| `locate_in_type()` | Object | `locate_in_type(/path)` | Find instance of type |
| `json_encode()` | Data | `json_encode(value)` | JSON serialization |
| `json_decode()` | Data | `json_decode(text)` | JSON deserialization |
| `time2text()` | String | `time2text(time, format)` | Format timestamp |
| `text2num()` | String | `text2num(text)` | Parse number from text |
| `dir()` | File | `dir(path)` | List files in directory |
| `file()` | File | `file(path)` | Create file reference |
| `throw()` | Exception | `throw(value)` | Raise exception |

**Implementation Strategy:**
- Create `BuiltinProcs.cs` class with static method per proc
- Register in interpreter's proc table during init
- Add unit tests for each

### 1.6 Language Features Not Yet Tested

- **Variable Modifiers:** `tmp`, `static`, `const`, `global` — verify all work correctly
- **Type Casting:** `as` operator — edge cases with null, inheritance
- **Datum Creation:** `new /path(args)` with constructor args
- **Savefiles:** Full `savefile` type support (read/write, indexing)
- **Color/Matrix:** Advanced math operations
- **Try/Catch:** Exception handling with multiple catch blocks
- **List Comprehension:** `filter()`, `map()`, `reduce()` (if planned)

---

## PHASE 2: Architecture Refactor (Weeks 3-4)

### 2.1 Project Structure

**New Directory Layout:**
```
codelanguage/
├── Craft.Common/                    // Shared types
│   ├── CraftValue.cs
│   ├── Token.cs
│   ├── ParseError.cs
│   └── DmCodec.cs                  // Serialization format
├── Craft.Language/                  // Parser + AST
│   ├── Lexer.cs
│   ├── Parser.cs
│   ├── Preprocessor.cs
│   ├── AST/
│   │   ├── Stmt.cs
│   │   ├── Expr.cs
│   │   └── Visitor.cs
│   └── Keywords.cs
├── Craft.Bytecode/                  // IR + code generation
│   ├── BytecodeGenerator.cs
│   ├── Bytecode.cs
│   ├── Opcode.cs                   // Enum of VM instructions
│   └── Disassembler.cs
├── Craft.Runtime/                   // Execution engine
│   ├── Interpreter.cs               // Keep for AST execution
│   ├── VirtualMachine.cs            // New bytecode VM
│   ├── Environment.cs
│   ├── CraftValue.cs
│   ├── BuiltinProcs.cs
│   ├── WorldRegistry.cs
│   ├── WorldScheduler.cs
│   └── DreamCodec.cs               // Network serialization
├── Craft.Network/                   // New layer
│   ├── DreamDaemon.cs              // Server
│   ├── DreamClient.cs               // Client protocol
│   ├── NetworkMessage.cs
│   └── DreamProtocol.cs
├── Craft.IDE/                       // IDE (current MainWindow)
│   ├── MainWindow.xaml(.cs)
│   ├── DmCompiler.cs
│   ├── DmLiveAnalyzer.cs
│   └── BrowserService.cs
├── Craft.DreamSeeker/               // Standalone client
│   ├── DreamSeekerApp.xaml(.cs)
│   ├── DreamSeekerWindow.xaml(.cs)
│   └── RenderEngine.cs
└── Craft.Daemon/                    // Standalone server
    ├── Program.cs
    └── DaemonConfiguration.cs
```

### 2.2 Bytecode VM Architecture

**VM Instructions (Opcode):**
```csharp
public enum Opcode : byte
{
    // Constants & variables
    LoadConst,                       // arg: constant pool index
    LoadVar,                         // arg: variable name hash
    StoreVar,                        // arg: variable name hash
    LoadField,                       // arg: field name hash
    StoreField,                      // arg: field name hash
    
    // Operators
    Add, Sub, Mul, Div, Mod, Power,
    And, Or, Not,
    BitwiseAnd, BitwiseOr, BitwiseXor, BitwiseNot, ShiftLeft, ShiftRight,
    Equal, NotEqual, Less, LessEq, Greater, GreaterEq,
    
    // Control flow
    Jump,                            // arg: jump offset
    JumpIfFalse,                     // arg: jump offset
    JumpIfTrue,                      // arg: jump offset
    Call,                            // arg: proc name hash, arg count
    CallBuiltin,                     // arg: builtin id
    Return,
    
    // Object creation
    New,                             // arg: type path hash
    Del,
    
    // List operations
    ListCreate,                      // arg: element count
    ListIndex,                       // stack: list, index
    ListSet,                         // stack: list, index, value
    
    // Special
    Spawn,                           // arg: delay in ticks
    Sleep,                           // arg: or stack
    Nop,
    Halt,
}
```

**VM Stack Frame:**
```csharp
public class StackFrame
{
    public int InstructionPointer { get; set; }
    public Environment Environment { get; set; }
    public CraftValue Self { get; set; }
    public Stack<CraftValue> LocalStack { get; set; } = new();
    public string ProcName { get; set; }
    public int ReturnAddress { get; set; }
}
```

### 2.3 Network Protocol

**Dream Protocol (Binary, TCP/IP):**

```
MessageType (1 byte)
├─ ServerHello (server → client)
│  ├─ ProtocolVersion (4 bytes)
│  ├─ WorldName (length-prefixed string)
│  └─ WorldSize (x, y, z as 4-byte ints)
├─ ClientHello (client → server)
│  ├─ ClientVersion (4 bytes)
│  ├─ Username (length-prefixed string)
│  └─ Key (auth token, 16 bytes)
├─ StateUpdate (server → client)
│  ├─ Tick (4 bytes)
│  ├─ UpdateCount (2 bytes)
│  └─ UpdateList[]
│     ├─ ObjID (4 bytes)
│     ├─ X, Y, Z (4 bytes each)
│     ├─ Icon (2-byte string ref)
│     ├─ Color (4 bytes: RGBA)
│     └─ Layer (2 bytes)
├─ InputEvent (client → server)
│  ├─ Tick (4 bytes)
│  ├─ EventType (Click, Move, Verb, Input)
│  └─ Payload (event-specific)
├─ VerbCall (client → server)
│  ├─ VerbName (length-prefixed string)
│  ├─ TargetID (4 bytes)
│  └─ Arg count + args
├─ TextOutput (server → client)
│  ├─ Channel (world, atom, usr, debug)
│  └─ Message (length-prefixed string)
└─ Disconnect
   └─ Reason (length-prefixed string)
```

**Files to Create:**
- `Craft.Network/DreamProtocol.cs` — Protocol constants
- `Craft.Network/NetworkMessage.cs` — Message serialization
- `Craft.Network/DreamDaemon.cs` — TCP server listener
- `Craft.Network/DreamClient.cs` — TCP client connector

---

## PHASE 3: Server-Side Runtime (Weeks 5-7)

### 3.1 Dream Daemon Architecture

**New Project: `Craft.Daemon` (.NET 8 Console App)**

```csharp
public class DreamDaemon
{
    private TcpListener _listener;
    private Dictionary<int, ClientConnection> _connections = new();
    private WorldRegistry _world = new();
    private WorldScheduler _scheduler = new();
    private BytecodeEngine _engine = new();
    private volatile bool _running = true;
    
    public async Task Start(int port = 25565)
    {
        _listener = new TcpListener(IPAddress.Any, port);
        _listener.Start();
        Console.WriteLine($"Dream Daemon listening on port {port}");
        
        while (_running)
        {
            var client = await _listener.AcceptTcpClientAsync();
            _ = HandleClientAsync(client);           // Fire and forget
        }
    }
    
    private async Task HandleClientAsync(TcpClient client)
    {
        var conn = new ClientConnection(client, _world, _scheduler);
        int id = Interlocked.Increment(ref _nextClientId);
        _connections[id] = conn;
        
        try
        {
            await conn.RunAsync();
        }
        finally
        {
            _connections.Remove(id);
        }
    }
    
    public async Task RunGameLoop()
    {
        const int TickMs = 100;                      // 10 ticks/second
        var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(TickMs));
        
        try
        {
            while (_running)
            {
                await timer.WaitForNextTickAsync();
                
                // Execute pending world procs (spawn, timers)
                _scheduler.Tick();
                
                // Broadcast world state to all connected clients
                await BroadcastWorldState();
            }
        }
        finally
        {
            timer.Dispose();
        }
    }
    
    private async Task BroadcastWorldState()
    {
        var updates = _world.GetDirtyObjects();
        var message = new StateUpdateMessage(_world.CurrentTick, updates);
        
        foreach (var conn in _connections.Values)
            await conn.SendMessageAsync(message);
    }
}
```

**ClientConnection.cs:**
```csharp
public class ClientConnection
{
    private NetworkStream _stream;
    private CraftValue _usr;                         // Player object
    private CraftValue _player;                      // Client object
    
    public async Task RunAsync()
    {
        // Receive ClientHello
        var hello = await ReceiveMessageAsync();
        if (!(hello is ClientHello ch))
        {
            await SendMessageAsync(new DisconnectMessage("Protocol error"));
            return;
        }
        
        // Create player mob
        _usr = new CraftValue { Type = "/mob/player", ... };
        _player = new CraftValue { Type = "/client", ... };
        
        // Send ServerHello
        await SendMessageAsync(new ServerHello(...));
        
        // Main loop: receive input events
        while (_stream.DataAvailable || ...)
        {
            var msg = await ReceiveMessageAsync();
            await HandleMessageAsync(msg);
        }
    }
    
    private async Task HandleMessageAsync(NetworkMessage msg)
    {
        switch (msg)
        {
            case VerbCallMessage vcm:
                await HandleVerbCall(vcm);
                break;
            case InputEventMessage iem:
                await HandleInputEvent(iem);
                break;
            // ... etc
        }
    }
}
```

### 3.2 Tick-Based Scheduler

**WorldScheduler.cs Enhancement:**

```csharp
public class WorldScheduler
{
    private PriorityQueue<ScheduledProc> _procQueue = new();
    private int _currentTick = 0;
    
    public void Schedule(CraftValue obj, Proc proc, CraftValue[] args, int delayTicks = 0)
    {
        _procQueue.Enqueue(new ScheduledProc
        {
            ExecuteTick = _currentTick + delayTicks,
            Object = obj,
            Proc = proc,
            Args = args
        });
    }
    
    public void Tick()
    {
        _currentTick++;
        
        while (_procQueue.Count > 0 && _procQueue.Peek().ExecuteTick <= _currentTick)
        {
            var scheduled = _procQueue.Dequeue();
            scheduled.Proc.Execute(scheduled.Object, scheduled.Args);
        }
    }
}
```

### 3.3 Bytecode Compilation Pipeline

**DmCompiler.cs Enhancement:**

```csharp
public class DmCompiler
{
    public BytecodeModule CompileToByteode(string source)
    {
        // 1. Preprocess
        var preprocessed = _preprocessor.Process(source);
        
        // 2. Lex
        var lexer = new Lexer(preprocessed);
        var tokens = lexer.Tokenize();
        
        // 3. Parse
        var parser = new Parser(tokens);
        var ast = parser.Parse();
        
        // 4. Generate bytecode
        var gen = new BytecodeGenerator();
        var bytecode = gen.Generate(ast);
        
        // 5. Emit module
        return new BytecodeModule
        {
            Code = bytecode.Instructions,
            Constants = bytecode.Constants,
            StringPool = bytecode.Strings,
            ProcTable = bytecode.Procs,
        };
    }
}
```

---

## PHASE 4: Client-Side Runtime (Weeks 8-9)

### 4.1 Standalone Dream Seeker

**New Project: `Craft.DreamSeeker` (WPF App)**

```csharp
public partial class DreamSeekerApp : Application
{
    private DreamSeekerWindow _window;
    private NetworkClient _client;
    
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        
        _window = new DreamSeekerWindow();
        _window.Show();
        
        if (e.Args.Length > 0)
        {
            var server = e.Args[0];
            var port = e.Args.Length > 1 ? int.Parse(e.Args[1]) : 25565;
            _window.Connect(server, port);
        }
    }
}
```

**DreamSeekerWindow.xaml(.cs):**
```csharp
public partial class DreamSeekerWindow : Window
{
    private NetworkClient _client;
    private RenderEngine _renderer;
    private InputHandler _input;
    private WorldState _localWorld;           // Cached state
    
    public DreamSeekerWindow()
    {
        InitializeComponent();
        _renderer = new RenderEngine(MainCanvas);
        _input = new InputHandler(_renderer, OnMouseClick, OnKeyPress);
        _localWorld = new WorldState();
    }
    
    public async Task Connect(string server, int port)
    {
        _client = new NetworkClient(server, port);
        _client.OnStateUpdate += HandleStateUpdate;
        
        await _client.ConnectAsync();
        
        // Start render loop
        StartRenderLoop();
    }
    
    private void HandleStateUpdate(StateUpdateMessage msg)
    {
        // Update local world copy
        foreach (var update in msg.Updates)
            _localWorld.UpdateObject(update);
        
        // Renderer will read from _localWorld on next frame
    }
    
    private void StartRenderLoop()
    {
        var timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromMilliseconds(16.67);   // ~60 FPS
        timer.Tick += (s, e) => _renderer.Render(_localWorld);
        timer.Start();
    }
    
    private void OnMouseClick(int x, int y, MouseButton button)
    {
        var tileX = x / 32;
        var tileY = y / 32;
        var objs = _localWorld.GetObjectsAt(tileX, tileY);
        
        if (button == MouseButton.Left && objs.Count > 0)
        {
            // Send verb call or movement
            var msg = new InputEventMessage
            {
                Type = InputEventType.Click,
                X = tileX,
                Y = tileY,
                TargetID = objs[0].ID
            };
            
            _client.SendAsync(msg);
        }
    }
}
```

### 4.2 Tile Rendering Engine

**RenderEngine.cs (New):**

```csharp
public class RenderEngine
{
    private Canvas _canvas;
    private Dictionary<int, UIElement> _tileCache = new();
    
    public void Render(WorldState world)
    {
        _canvas.Children.Clear();
        
        // Render all visible tiles
        var viewRect = GetViewport();
        var objs = world.GetObjectsInRect(viewRect);
        
        foreach (var obj in objs)
        {
            var tile = RenderObject(obj);
            Canvas.SetLeft(tile, obj.X * 32);
            Canvas.SetTop(tile, obj.Y * 32);
            _canvas.Children.Add(tile);
        }
    }
    
    private UIElement RenderObject(CraftObject obj)
    {
        var image = new Image
        {
            Source = LoadIconState(obj.Icon, obj.IconState),
            Width = 32,
            Height = 32,
            Stretch = Stretch.UniformToFill,
        };
        
        // Apply color overlay
        if (obj.Color != null)
        {
            var brush = new SolidColorBrush(obj.Color.ToWpfColor());
            image.OpacityMask = brush;
        }
        
        return image;
    }
}
```

---

## PHASE 5: IDE Enhancement (Weeks 10-11)

### 5.1 Integrated Debugger

**DebuggerService.cs Enhancement:**

```csharp
public class DebuggerService
{
    private VirtualMachine _vm;
    private Dictionary<string, Breakpoint> _breakpoints = new();
    private bool _stepping = false;
    private bool _paused = false;
    
    public void SetBreakpoint(string filePath, int line)
    {
        _breakpoints[$"{filePath}:{line}"] = new Breakpoint { Active = true };
    }
    
    public void StepOver()
    {
        _stepping = true;
        _paused = false;
        Resume();
    }
    
    public void Resume()
    {
        _vm.Run(_paused ? StopReason.Breakpoint : StopReason.Start);
    }
    
    public StackFrame[] GetCallStack()
    {
        return _vm.CallStack.ToArray();
    }
    
    public Dictionary<string, CraftValue> GetLocalVariables()
    {
        var frame = _vm.CallStack.Peek();
        return frame.Environment.GetAllVariables();
    }
}
```

### 5.2 Profiler

**ProfilerService.cs (New):**

```csharp
public class ProfilerService
{
    private Dictionary<string, ProcStats> _procStats = new();
    
    public void RecordProcCall(string procName, long durationMs)
    {
        if (!_procStats.ContainsKey(procName))
            _procStats[procName] = new ProcStats();
        
        _procStats[procName].TotalTime += durationMs;
        _procStats[procName].CallCount++;
    }
    
    public ProfilingReport GenerateReport()
    {
        return new ProfilingReport(_procStats);
    }
}
```

### 5.3 Bytecode Disassembler

**BytecodeDisassembler.cs (New):**

```csharp
public class BytecodeDisassembler
{
    public string Disassemble(BytecodeModule module)
    {
        var sb = new StringBuilder();
        var offset = 0;
        
        while (offset < module.Code.Length)
        {
            var opcode = (Opcode)module.Code[offset];
            var args = module.Code.Skip(offset + 1).Take(4).ToArray();
            
            sb.AppendLine($"{offset:X4}  {opcode,-16} {FormatArgs(opcode, args)}");
            offset += 5;
        }
        
        return sb.ToString();
    }
}
```

---

## PHASE 6: Polish & Testing (Weeks 12-16)

### 6.1 Regression Test Suite

**File: `Craft.Tests/RegressionTests.cs`**

```csharp
[TestClass]
public class LanguageRegressionTests
{
    [TestMethod]
    public void TestOperators_BitwiseAnd()
    {
        var result = Interpret("var/x = 5 & 3; world << x");
        Assert.AreEqual(1, result);
    }
    
    [TestMethod]
    public void TestOperators_Power()
    {
        var result = Interpret("var/x = 2 ** 3; world << x");
        Assert.AreEqual(8, result);
    }
    
    [TestMethod]
    public void TestTypeCoercion_StringConcat()
    {
        var result = Interpret("var/x = \"hello\" + 5; world << x");
        Assert.AreEqual("hello5", result);
    }
    
    [TestMethod]
    public void TestTypeCast_As()
    {
        var result = Interpret(@"
            datum/obj
            var/obj/o = new
            if (o as /datum) world << 1
        ");
        Assert.AreEqual(1, result);
    }
    
    [TestMethod]
    public void TestNetworking_ClientServerHandshake()
    {
        // Start daemon
        var daemon = new DreamDaemon();
        daemon.Start();
        
        // Connect client
        var client = new NetworkClient("localhost", 25565);
        client.ConnectAsync().Wait();
        
        Assert.IsTrue(client.IsConnected);
    }
    
    [TestMethod]
    public void TestBytecodeGeneration_SimpleExpression()
    {
        var compiler = new DmCompiler();
        var bytecode = compiler.CompileToByteode("var/x = 5 + 3");
        
        Assert.IsNotNull(bytecode);
        Assert.IsTrue(bytecode.Code.Length > 0);
    }
}
```

### 6.2 Performance Benchmarks

**File: `Craft.Benchmarks/Program.cs`**

```csharp
[MemoryDiagnoser]
public class ExecutionBenchmarks
{
    [Benchmark]
    public void TreeWalkInterpreterLoop()
    {
        var source = @"
            var/x = 0
            while (x < 10000) x++
        ";
        Interpret(source);
    }
    
    [Benchmark]
    public void BytecodeVMLoop()
    {
        var source = @"
            var/x = 0
            while (x < 10000) x++
        ";
        ExecuteBytecode(source);
    }
}
```

### 6.3 Artifact Compatibility

**Test:** Can Craft++ bytecode run with both tree-walk and VM?

```csharp
[TestMethod]
public void TestArtifactCompatibility()
{
    var source = LoadDmFile("test.dm");
    
    // Compile to bytecode
    var bytecode = _compiler.CompileToByteode(source);
    
    // Save artifact
    var artifact = new DmArtifact(bytecode);
    artifact.Save("test.dmb");
    
    // Load and execute with tree-walk
    var astResult = InterpretFile("test.dm");
    
    // Load and execute with VM
    var vmResult = ExecuteBytecodeArtifact("test.dmb");
    
    Assert.AreEqual(astResult, vmResult);
}
```

---

## Implementation Priority Matrix

| Phase | Complexity | Impact | Priority |
|-------|-----------|--------|----------|
| **Language Parity** | Medium | High | 🔴 CRITICAL |
| **Architecture Refactor** | High | High | 🔴 CRITICAL |
| **Server Runtime** | High | High | 🟠 HIGH |
| **Client Runtime** | High | Medium | 🟠 HIGH |
| **IDE Enhancement** | Medium | Medium | 🟡 MEDIUM |
| **Testing & Polish** | Low | High | 🟡 MEDIUM |

---

## Risk Analysis

| Risk | Mitigation |
|------|-----------|
| **Network latency ruins gameplay** | Implement client-side prediction & interpolation |
| **Bytecode VM too slow** | Profile early, optimize hotspots, consider JIT |
| **Protocol compatibility issues** | Start with simple messages, test extensively |
| **Breaking changes upset users** | Major version bump (Craft++ 2.0), migration guide |
| **Debugging in network mode hard** | Implement remote debugger protocol |

---

## Success Criteria

- [ ] 100% of BYOND DM language features implemented
- [ ] Client-server architecture fully working
- [ ] Bytecode VM executes all test programs correctly
- [ ] Dream Seeker standalone app fully functional
- [ ] Regression test suite: 200+ passing tests
- [ ] Performance: VM execution within 2x of native bytecode
- [ ] Documentation: Full API reference + examples
- [ ] Community: First successful BYOND game port to Craft++

---

## Next Steps

1. **IMMEDIATE (This Week):**
   - [ ] Create project structure (split into Craft.Common, Craft.Language, etc.)
   - [ ] Implement missing operators in Parser + Interpreter
   - [ ] Add missing built-in procs (input, alert, walk, etc.)

2. **WEEK 2:**
   - [x] Implement preprocessor conditionals
   - [x] `..()`, `.` return-slot, `:` lax-dereference (relative-path notion resolved — see §1.3)
   - [ ] Begin bytecode IR design

3. **WEEK 3-4:**
   - [ ] Bytecode generator skeleton
   - [ ] Network protocol definition
   - [ ] Dream Daemon console app bootstrap

---

**Estimated Team Effort:** 1 full-time developer, 16 weeks  
**Estimated Timeline:** Q3 2026–Q4 2026 (if starting immediately)

---

