XL1200-EMU Symbolics XL1200 Emulator
Plans & Roadmap SpecsDONE docs/gui-scripting-windows-plan.md

Portable Host I/O, MinGW-w64 & Wine CI, s7 Scripting & microui Workbench Plan

Status: Implemented

All four phases of this specification have been implemented in emu/ and verified across native Linux, MinGW-w64 cross-builds, Wine 11 CI, and Nix packages. For live user and contributor documentation, see docs/emulator/README.md and docs/emulator/gui-scripting-and-debug.md.

Historical Specification: Approved technical specification that guided phased implementation (Phase 1 -> Phase 2 -> Phase 3 -> Phase 4).
Companion Specification: Coordinates directly with cpu-acceleration-plan.md, genera-8.3-cdrom-install.md, emu/AGENTS.md, and AGENTS.md.


1. Executive Summary & Settled Architectural Decisions

This specification extends the from-scratch C11 Symbolics XL1200 hardware emulator (emu/) with four cohesive, minimal-dependency capabilities while preserving a 100% OS-agnostic ISO C11 core (libivory_core.so / libivory_core.dll):

  1. Portable Host I/O, MinGW-w64 Windows Build & Headless Wine CI (Phase 1):
    • Purifies libivory_core by extracting Linux-only TAP/AF_PACKET networking out of eth_82586.c into a host-shell unit (eth_tap_linux.c) and replacing POSIX-only file/thread/loader calls with ~145 LOC of header-only shims (emu_os.h, emu_io.h).
    • Collapses the emulator shell from 3 threads + 2 POSIX wake pipes down to a strict 2-thread architecture (Main Thread = SDL3 + microui + s7 + non-blocking debug_ctl & serial_host; emu_thread = pure CPU slice runner).
    • Provides multi-transport debug_ctl IPC: Win32 Named Pipes (\\.\pipe\ivory-xl1200-<pid>, default on Windows), AF_UNIX (/tmp/ivory-xl1200-<pid>.sock, default on Linux), and dual-stack IPv4/IPv6 TCP (--debug-tcp <[addr]:port>) on both OSes.
    • Adds first-class NixOS cross-compilation (nix build .#windows, devShells.mingw, make -C emu dist-win producing ivory-xl1200.exe + hot-reloadable libivory_core.dll + self-contained DLL bundle) and persistent-wineserver headless wine64 test execution (make -C emu test-win test-e2e-win).
  2. Vendored s7 Scheme Machine Configuration & Cooperative call/cc Workbench (Phase 2):
    • Vendors Stanford CCRMA s7 Scheme (emu/vendor/s7/{s7.c,s7.h}, 0-BSD) into SHELL_SRCS.
    • Unifies machine configuration and automation in .scm files: declarative (define-machine ...) configures full hardware identity (Main Board serial & mfg date, I/O Board #0 serial/part/rev/mfg-date/monitor/MAC, persistent MK48T02 .nvram file & RTC offset, ROM/kernel/snapshot, RAM size, SCSI 0..6, Ethernet slirp/tap/veth + hostfwds, Serial Ch.A/B backends, display/keymap, checkpoints), while GUI Save Config splices only the top-level (define-machine ...) byte span so user comments, macros, and custom actions in the same file remain untouched.
    • Provides convenience macros (define-action, with-paused-cpu), lifecycle/debug hooks (on-boot, on-halt, on-break, on-watch), fast typed C accessors + (emu/cmd "...") over an in-process DebugCtlSink, and a pure-Scheme call/cc cooperative task scheduler paired with rt->script_step_ceiling for cycle-exact multi-million-step automation without blocking the 60 FPS GUI.
    • Ports the hardware E2E test suite (test_e2e_puppet.sh) to a cross-platform s7 script (emu/tests/e2e_suite.scm) executed identically on Linux and wine64.
  3. Integrated Disk Management (fep_convert) & Portable Serial Host Backends (Phase 3):
    • Links fep_convert.c (-DFEP_CONVERT_NO_MAIN) into the emulator shell (ivory_fep_tools.h) for in-process blank disk creation, native XL1200 1280B/sector Initial FEPFS formatting (LABL + FEPD + bootstrap FEPFs), blank SIMH .tap creation, FEPFS/tape inspection, MacIvory big-endian conversion, and COW .ovl overlay commit-to-base / reset.
    • Wires DUSCC/8237 Serial Channel A (console/diagnostic) and Channel B (bulkhead RS-232) via Xl1200SerialCallbacks (serial_host.c) to non-blocking dual-stack IPv4/IPv6 TCP, Named Pipe / AF_UNIX, and file capture backends.
  4. Vendored microui Top Menu Bar & Floating Workbenches on SDL3 SDL_Renderer (Phase 4):
    • Vendors rxi/microui (emu/vendor/microui/{microui.c,microui.h}, MIT) rendered in SDL_Renderer window space: a dedicated 22px top menu bar above the letterboxed VRAM canvas (auto-hidden in fullscreen) + crisp floating windows (Machine Setup, Disk & Media Manager, Net & Serial, Checkpoints & Debugger, Actions, and Interactive s7 REPL).
    • Deletes ~500+ LOC of custom pixel-hitbox popovers (MENU_CDROM, MENU_TAPE, MENU_KEYMAP, MENU_RESET) from sdl_console.c, retaining the bottom 28px strip strictly as a passive XL1200 hardware LED bezel (preserving bit-exact 1084×840 / 1152×924 .y4m recordings and dump-panel PPMs).
    • Enables zero-argument GUI startup (double-clicking ivory-xl1200.exe): auto-loads <exe_dir>/xl1200.scm (or ./xl1200.scm) if present; otherwise opens paused directly in the Machine Setup window instead of exiting with an error.
flowchart TB
    subgraph MainThread["Host Shell — Main Thread (Sole Owner of SDL3, microui, s7, debug_ctl, serial_host)"]
        UI["SDL3 Window + SDL_Renderer (sdl_console.c + ui_workbench.c)<br/>• 22px microui Top Menu Bar (auto-hide fullscreen)<br/>• Letterboxed Console Texture (1084x840 trim / 1152x924 full)<br/>• Floating microui Windows + SDL_ShowOpen/SaveFileDialog"]
        S7["s7 Scheme Engine (emu_script.c)<br/>• (define-machine ...) + Byte-Span Save Config<br/>• (define-action ...) -> Menu + Hotkeys<br/>• Pure-Scheme call/cc *emu-tasks* Scheduler<br/>• on-boot / on-halt / on-break / on-watch Hooks"]
        CTL["Unified Command Kernel (debug_ctl.c)<br/>• DebugCtlSink (In-Memory Buffer | Socket | Pipe)<br/>• Replaces 480-LOC duplicate PuppetContext in main.c"]
        HOSTIO["Non-Blocking Host I/O (emu_ipc.c / serial_host.c / eth_slirp.c)<br/>• Win32 PIPE_NOWAIT \\\\.\\pipe\\ivory-xl1200-<pid> (Win default)<br/>• AF_UNIX /tmp/ivory-xl1200-<pid>.sock (Linux default)<br/>• Dual-Stack IPv4/IPv6 TCP (--debug-tcp & Serial Ch.A/B)<br/>• libslirp NAT + Linux-only eth_tap_linux.c"]
        DISK["Embedded Disk Tools (fep_convert.c -DFEP_CONVERT_NO_MAIN)<br/>• Create Blank / Initial FEPFS / SIMH .tap<br/>• Inspect LABL/FEPD / Convert MacIvory / Commit .ovl"]
    end

    subgraph EmuThread["Emulator Worker Thread (emu_thread)"]
        LOOP["CPU Slice Runner (state_mu + wake_cv)<br/>• Slice clamped to min(slice, next_auto_ckpt, script_step_ceiling)<br/>• Sets pending_hooks bitmask on break/watch/halt & wakes Main"]
    end

    subgraph CoreDLL["Hot-Reloadable Core (libivory_core.so / libivory_core.dll)"]
        CORE["100% Pure ISO C11 (0 writable .data / 0 .bss)<br/>• IvoryCoreApi v4 (exports ivory_core_get_api only)<br/>• IvoryCpu (4096B) | IvoryMem (32768B) | MerlinBoard (278528B)<br/>• Reset-safe Main & IO0 ID ROMs + MK48T02 NVRAM"]
    end

    UI <--> S7
    UI <--> DISK
    S7 <--> CTL
    HOSTIO <--> CTL
    CTL <-->|"state_mu"| LOOP
    S7 <-->|"script_step_ceiling + pending_hooks"| LOOP
    LOOP <-->|"IvoryCoreApi v4"| CORE
    HOSTIO <-->|"EthHostCallbacks / Xl1200SerialCallbacks"| CORE

2. Source-Provenance, Frozen-ABI & Companion-Plan Coordination Invariants

IMPORTANT

Mandatory Invariants (emu/AGENTS.md & AGENTS.md §6):

  1. Reference Sources Only: Consult only emu/, docs/, genera-original/, and I_Machine/. Never read, inspect, grep, or cite linux-vlm/, xl1200-emu/, or archive/.
  2. No Synthetic Guest Code: All tests (e2e_suite.scm, test_s7_config.c, Wine CI) must execute genuine ROM/kernel binaries (ivory-fep-roms/fep330/rom.dump, macivory/macivory_cdrom.iso) or isolated single-instruction unit checks.
  3. Frozen Struct Sizes Across Linux (LP64) and Windows x64 (LLP64):
    • sizeof(IvoryCpu) == 4096U
    • sizeof(IvoryMem) == 32768U
    • sizeof(MerlinBoard) == 278528U All bitfields in ivory_hw.h use uniform uint32_t/uint64_t storage units; retain explicit _Static_assert checks so MinGW -mms-bitfields never alters layout.
  4. Zero .data/.bss & Single-Symbol Export Hygiene:
    • Linux ELF: readelf -WS emu/build/obj/core/*.o must report 0 bytes in writable .data and .bss, and nm -D --defined-only emu/build/libivory_core.so exports only ivory_core_get_api.
    • Windows PE/COFF: x86_64-w64-mingw32-objdump -h emu/build-win/obj/core/*.o must show zero writable .data/.bss payload, and x86_64-w64-mingw32-objdump -p emu/build-win/libivory_core.dll must list only ivory_core_get_api in the export table.

Disjoint Coordination with cpu-acceleration-plan.md

To ensure zero merge conflicts regardless of execution order between this plan and cpu-acceleration-plan.md:

  • Reserved Padding Allocation:
    • cpu-acceleration-plan.md carves IvoryMem._reserved[938] -> _reserved[937] for IvoryDcache *dcache.
    • This plan touches zero bytes of IvoryMem._reserved or IvoryCpu._reserved, carving 1 uint64_t slot from MerlinBoard._reserved[1055] -> _reserved[1054] in ivory_emu.h to persist Main Board identity across cold power resets:
      /* Inside struct MerlinBoard, immediately before _reserved: */
      uint32_t                  main_serial;    /* Default 1200 (0x000004B0) LE at #o777400040 */
      uint16_t                  main_mfg_days;  /* Days since 1982-01-01 LE at #o777400044     */
      uint16_t                  main_id_flags;  /* Bit 0: custom main_serial/mfg_days active   */
      uint64_t                  _reserved[1054];
      
  • Single Coordinated IvoryCoreApi Bump (IVORY_CORE_ABI_VERSION = 4U):
    • Remove Linux-specific eth_82586_open_tap and eth_82586_open_packet from ivory_core_api.h (keeping int fd; int if_index; as inert fields inside struct Eth82586 so sizeof(MerlinBoard) stays 278528U).
    • Add merlin_set_identity and console_hw_set_serial_callbacks to IvoryCoreApi:
      typedef struct MerlinIdentityConfig {
          uint32_t main_serial;        /* #o777400040 & #o777400060 bytes 0..3 LE (si:machine-model) */
          uint16_t main_mfg_days;      /* #o777400040 & #o777400060 bytes 4..5 LE                    */
          uint32_t io0_serial;         /* #o10400260000 rom[7..10] LE (merlin-io-board)              */
          uint32_t io0_part_number;    /* rom[3..6] LE (default 170082 = 0x00029862)                 */
          uint8_t  io0_mfg_rev;        /* rom[11] (default 1)                                        */
          uint8_t  io0_func_rev;       /* rom[12] (default 1)                                        */
          uint8_t  io0_minor_rev;      /* rom[13] (default 0)                                        */
          uint16_t io0_mfg_days;       /* rom[14..15] LE (default 3650 = 0x0E42)                     */
          uint8_t  monitor_type;       /* rom[22]: 0 = Philips, 1 = Sony                             */
          uint8_t  mac_addr[6];        /* rom[16..21], nvram[0x20..0x25], eth.mac_addr & eth.ia_addr */
          uint32_t eco_reg;            /* board->vme_timeout (0 = keep MERLIN_ECO_DEFAULT)           */
          int64_t  rtc_offset_sec;     /* board->nvram.time_offset_sec                               */
          bool     update_rtc_offset;
      } MerlinIdentityConfig;
      
    • Reset-Safety Fix in mem.c:405-419: ivory_boot_comm_init_xl1200(IvoryMem *mem) is called during ivory_mem_reset() and debug_ctl_power_reset(). Update it to read serial = (mem->board && (mem->board->main_id_flags & 1U)) ? mem->board->main_serial : 1200U and mfg = (mem->board && (mem->board->main_id_flags & 1U)) ? mem->board->main_mfg_days : 3650U, writing bytes 0..5 as DTP_FIXNUM byte words into both mem->boot_comm[0x20..0x25] (#o777400040) and fallback mem->boot_comm[0x30..0x35] (#o777400060) per local genera-original/sys.sct/i-sys/configuration.lisp:107-123, 400-414.
  • PE/COFF Export Macro in ivory_core_api.h:
    #if defined(_WIN32)
    #  if defined(IVORY_BUILDING_CORE_DLL)
    #    define IVORY_CORE_EXPORT __declspec(dllexport)
    #  else
    #    define IVORY_CORE_EXPORT
    #  endif
    #elif defined(__GNUC__) || defined(__clang__)
    #  define IVORY_CORE_EXPORT __attribute__((visibility("default")))
    #else
    #  define IVORY_CORE_EXPORT
    #endif
    
    WARNING

    On x86_64-w64-mingw32-gcc, passing -fvisibility=hidden or __attribute__((visibility("default"))) triggers -Wattributes warnings that fail under -Werror, and omitting __declspec(dllexport) causes GNU ld to enable --export-all-symbols by default. Defining __declspec(dllexport) on ivory_core_get_api alone (with -DIVORY_BUILDING_CORE_DLL=1 when building CORE_OBJS on Windows) keeps -Werror clean and restricts the DLL export table to that single symbol.


3. Phase 1: Portable I/O, 2-Thread Runtime, MinGW-w64 Build & Headless Wine CI

3.1 Purifying libivory_core (eth_82586.c -> eth_tap_linux.c)

  • Remove all POSIX/Linux includes (<arpa/inet.h>, <fcntl.h>, <linux/if_ether.h>, <linux/if_packet.h>, <linux/if_tun.h>, <net/if.h>, <sys/ioctl.h>, <sys/socket.h>, <unistd.h>) and _GNU_SOURCE from eth_82586.c.
  • eth_82586.c retains only #include "ivory_emu.h" and #include <string.h>, routing all TX/RX exclusively through eth->host_cb (EthHostCallbacks).
  • Move TAP (/dev/net/tun) and AF_PACKET socket setup/teardown/read/write into emu/src/eth_tap_linux.c in SHELL_SRCS, guarded by #ifdef __linux__ (with clean IVORY_ERR_INVALID_ARG stubs reporting "TAP/AF_PACKET requires Linux; use --eth-user" on non-Linux hosts).

3.2 Header-Only OS & 64-Bit File Shims (emu_os.h & emu_io.h)

emu/include/emu_os.h (~65 LOC — Zero SDL Dependency)

Keeping OS threading/alignment/DLL primitives independent of SDL3 ensures non-GUI unit tests (test_loader, test_mem, test_cpu_core, test_isa_ops, test_merlin, test_snapshot_reload) remain 100% free of SDL3.dll and libwinpthread-1.dll:

  • Synchronization & Threads:
    • POSIX: pthread_mutex_t, pthread_cond_t (CLOCK_MONOTONIC), pthread_t.
    • _WIN32: SRWLOCK (InitializeSRWLock, AcquireSRWLockExclusive, ReleaseSRWLockExclusive), CONDITION_VARIABLE (SleepConditionVariableSRW taking relative DWORD timeout_ms = (DWORD)((wait_us + 999U) / 1000U)), and _beginthreadex / WaitForSingleObject / CloseHandle.
  • Aligned Allocation & Memory Locking:
    • emu_aligned_alloc(size_t align, size_t sz) / emu_aligned_free(void *p): wraps posix_memalign + free on POSIX, and _aligned_malloc(sz, align) + memset + _aligned_free(p) on _WIN32 (never pass _aligned_malloc pointers to plain free() on MSVCRT/UCRT!).
    • emu_mlock(p, sz) / emu_munlock(p, sz): mlock/munlock on POSIX, VirtualLock/VirtualUnlock on _WIN32.
  • Clocks, Paths & Dynamic Loader:
    • emu_mono_ns(): clock_gettime(CLOCK_MONOTONIC) on POSIX; QueryPerformanceCounter / QueryPerformanceFrequency cached via InitOnceExecuteOnce on _WIN32.
    • emu_sleep_us(uint32_t us): nanosleep on POSIX; Sleep(us >= 1000U ? us / 1000U : 1U) on _WIN32.
    • emu_pid(): (uint32_t)getpid() vs (uint32_t)GetCurrentProcessId().
    • emu_exe_dir(buf, cap) & emu_temp_dir(buf, cap): readlink("/proc/self/exe") + "/tmp" on Linux; GetModuleFileNameA(NULL, ...) + GetTempPathA(...) on _WIN32.
    • emu_dlopen / emu_dlsym / emu_dlclose: dlopen(..., RTLD_NOW | RTLD_LOCAL) on POSIX; UINT old = SetErrorMode(SEM_FAILCRITICALERRORS); HMODULE h = LoadLibraryA(path); SetErrorMode(old); + GetProcAddress + FreeLibrary on _WIN32.
    • Update core_loader.c, test_debug_ctl.c, and test_snapshot_reload.c to copy IVORY_CORE_FILENAME ("libivory_core.dll" on _WIN32, "libivory_core.so" on POSIX) to <temp_dir>/ivory-core-<pid>-<gen>.<ext> using stdio/CopyFileA, ensuring FreeLibrary runs before DeleteFileA(active_tmp_path).

emu/include/emu_io.h (~80 LOC — 64-Bit Clean Past 2 GiB on LLP64)

CAUTION

Critical LLP64 Bug in Current scsi_wd33c93.c:

  1. Lines 296–346 call POSIX pread(fileno(t->fp), ...) and pwrite(...), which do not exist on MinGW-w64.
  2. Line 1687 calls fseek(fp, 0L, SEEK_END) + long sz = ftell(fp). On Windows x64 (LLP64), long is signed 32-bit, overflowing at 2 GiB (breaking MacIvory_Virginal_9GB.img).

emu_io.h replaces all fseek/ftell/fseeko/ftello/ftruncate/pread/pwrite/rename calls in scsi_wd33c93.c, snapshot.c, fep_convert.c, and emu_script.c:

  • emu_fseek64(FILE *fp, uint64_t off, int whence) / int64_t emu_ftell64(FILE *fp): fseeko/ftello (_FILE_OFFSET_BITS=64) on POSIX; _fseeki64/_ftelli64 on _WIN32.
  • emu_ftruncate64(FILE *fp, uint64_t size): fflush(fp) + ftruncate(fileno(fp), (off_t)size) on POSIX; fflush(fp) + _chsize_s(_fileno(fp), (int64_t)size) on _WIN32.
  • emu_pread(FILE *fp, void *dst, size_t len, uint64_t off) / emu_pwrite(...): pread/pwrite on POSIX; on _WIN32, synchronous ReadFile/WriteFile on (HANDLE)_get_osfhandle(_fileno(fp)) passing OVERLAPPED ov = { .Offset = (DWORD)off, .OffsetHigh = (DWORD)(off >> 32) } (thread-safe, stateless file-pointer semantics matching pread/pwrite across 64-bit offsets).
  • emu_atomic_replace(const char *tmp_path, const char *dst_path): rename(tmp_path, dst_path) on POSIX; MoveFileExA(tmp_path, dst_path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) on _WIN32 (since Windows rename() fails with EEXIST when dst_path already exists).

3.3 Non-Blocking Local Named Pipe / AF_UNIX + IPv4/IPv6 TCP Layer (emu_ipc.{h,c})

Implement a ~140-LOC non-blocking byte-stream helper shared by debug_ctl.c and serial_host.c:

  1. Default Local IPC (EmuLocalServer / EmuEndpoint):
    • POSIX: AF_UNIX SOCK_STREAM (O_NONBLOCK | FD_CLOEXEC), default /tmp/ivory-xl1200-<pid>.sock.
    • Windows (_WIN32): Native Win32 Named Pipe (\\.\pipe\ivory-xl1200-<pid> by default; --debug-pipe <\\.\pipe\name> or --no-debug-pipe; if user passes a bare name foo, normalize to \\.\pipe\foo):
      • Create with CreateNamedPipeA(pipe_name, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, NULL).
      • Maintain 1 pre-allocated listening HANDLE alongside active client HANDLEs (<= DEBUG_CTL_MAX_CLIENTS). On each poll: call ConnectNamedPipe(listen_h, NULL) — under PIPE_NOWAIT, it returns immediately:
        • GetLastError() == ERROR_PIPE_CONNECTED -> promote listen_h to an active client slot and immediately CreateNamedPipeA a fresh listen_h so concurrent clients never hit ERROR_PIPE_BUSY.
        • GetLastError() == ERROR_PIPE_LISTENING -> no new client yet (0 µs block).
      • Non-blocking read: ReadFile under PIPE_NOWAIT returns FALSE with ERROR_NO_DATA when empty (0 bytes available) and ERROR_BROKEN_PIPE on client disconnect — zero OVERLAPPED state machines or HANDLE event leaks!
  2. Dual-Stack IPv4/IPv6 TCP (--debug-tcp <[addr]:port>):
    • Address parser supports 127.0.0.1:4200, [::1]:4200, :4200 / [::]:4200 (dual-stack wildcard), 0.0.0.0:4200, localhost:4200, and port 0 (ephemeral OS port for parallel tests; expose uint16_t emu_ipc_bound_port(const EmuTcpListener *)).
    • Uses getaddrinfo(host_or_null, port_str, &hints, &res) with AF_UNSPEC, SOCK_STREAM, AI_PASSIVE. When binding an AF_INET6 socket with empty/wildcard host, set int v6only = 0; setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&v6only, sizeof(v6only)); before bind() so both IPv4 and IPv6 clients connect cleanly.
    • Enables SO_REUSEADDR (POSIX only — never SO_REUSEADDR on Windows TCP listeners, where it allows port hijacking!), TCP_NODELAY, and non-blocking mode (fcntl(O_NONBLOCK) / ioctlsocket(FIONBIO)).
  3. Simultaneous Active Listeners:
    • DebugCtlServer holds both local_listener (AF_UNIX on Linux, \\.\pipe\... on Windows) and optional tcp_listener (--debug-tcp), polling both into the shared clients[] array (DEBUG_CTL_MAX_CLIENTS = 8U).

3.4 Winsock2 Fixes in eth_slirp.c

  1. Under #ifdef _WIN32, include <winsock2.h> and <ws2tcpip.h> before <slirp/libslirp.h>, and call an idempotent emu_winsock_init() (WSAStartup(MAKEWORD(2, 2), &wsa)) inside eth_slirp_create() and emu_ipc.c.
  2. In slirp_add_poll_cb() (eth_slirp.c:139): change if (!b || fd < 0) to if (!b || fd == (slirp_os_socket)-1) (SOCKET is unsigned uintptr_t on _WIN64).
  3. Critical Winsock2 WSAPoll Fix (eth_slirp.c:157): On Windows, passing POLLPRI (POLLRDBAND edge conflict) in WSAPOLLFD.events causes WSAPoll() to fail immediately with SOCKET_ERROR (WSAEINVAL = 10022) on every call. Guard SLIRP_POLL_PRI -> POLLPRI with #ifndef _WIN32, and call WSAPoll(b->pfds, (ULONG)b->pfds_len, 0) on _WIN32.

3.5 Strict 2-Thread Runtime & DebugCtlSink Unification (debug_ctl.c & main.c)

  1. Refactor debug_ctl.c Output to DebugCtlSink:
    typedef struct DebugCtlSink {
        bool  (*write)(void *ctx, const char *buf, size_t len);
        void   *ctx;
    } DebugCtlSink;
    
    Expose bool debug_ctl_exec(DebugCtlServer *srv, const DebugCtlSink *sink, const char *line, IvoryCpu *cpu, MerlinBoard *board, IvoryMem *mem, bool sdl_opened, bool batch_mode);.
  2. Three Mandatory --puppet Parity Updates Before Deleting PuppetContext:
    • Append vram_nonzero=%zu vram_nonbg=%zu video_ctrl=0x%08X to send_state_reply() in debug_ctl.c (required by test_e2e_puppet.sh Checks 1–5).
    • Add wait-vram <max_steps> [chunk] to debug_ctl_exec().
    • In step [N]: when batch_mode is true (used by --puppet*), call debug_ctl_run_budget() instead of single-stepping 1-by-1 and do not force srv->paused = true afterward; in interactive debug mode (!batch_mode), use ivory_cpu_run slices when num_breakpoints == 0 && num_watchpoints == 0 and pause upon completion as today.
    • Delete struct PuppetContext and all ~480 lines of duplicate puppet command parsing in main.c:1081-1560: --puppet, --puppet-file, and --puppet-stdio simply feed lines into debug_ctl_exec(..., &stdout_sink, ..., /*batch_mode=*/true).
  3. Eliminate dbg_thread, main_stop_pipe, and dbg_wake_pipe in main.c:
    • Main Thread runs at ~60–200 Hz (SDL_WaitEventTimeout(..., 8) when SDL is open; emu_sleep_us(5000) when --headless continuous):
      • Acquires rt_lock_state(&rt) briefly to poll sdl_console_poll_events(), debug_ctl_poll(..., sdl_opened), serial_host_poll(), drain pending_hooks & tick ready s7 tasks (emu_script_tick()), and prepare the dirty console frame; releases state_mu and calls sdl_console_flush_present().
    • emu_thread remains a pure CPU + device slice runner synchronized solely by rt.state_mu (EmuMutex) + rt.wake_cv (EmuCond) + atomic_bool stop_requested (SIGINT/SIGTERM handler sets g_stop_requested = 1; on _WIN32, SetConsoleCtrlHandler sets g_stop_requested = 1 and calls WakeAllConditionVariable(&rt.wake_cv)).

3.6 NixOS Cross-Compilation (flake.nix) & Headless wine64 CI (emu/Makefile)

IMPORTANT

Two Verified NixOS / pkgsCross.mingwW64 Pitfalls & Solutions:

  1. Never pass src = self; to Nix derivations in this repo: copying . hashes MacIvory_Virginal_9GB.img + genera-original/ (>10 GiB) into /nix/store. Always scope src = pkgs.lib.fileset.toSource { root = ./.; fileset = ./emu; };.
  2. pkgsCross.mingwW64.libslirp evaluation fix on nixos-unstable: upstream libslirp sets meta.platforms = platforms.unix, and mingwW64.glib pulls cross-python3 (marked broken on mingwW64). Override glib to use native build-host pkgs.python3 with withIntrospection = false:
    mingwPkgs = pkgs.pkgsCross.mingwW64;
    glibWin = (mingwPkgs.glib.override {
      python3 = pkgs.python3;
      python3Packages = pkgs.python3Packages;
      withIntrospection = false;
    }).overrideAttrs { outputs = [ "bin" "out" "dev" ]; postFixup = ""; };
    slirpWin = (mingwPkgs.libslirp.override { glib = glibWin; }).overrideAttrs (old: {
      separateDebugInfo = false;
      meta = old.meta // { platforms = pkgs.lib.platforms.all; };
    });
    sdl3Win = mingwPkgs.sdl3;
    
  • flake.nix Outputs:
    • packages.default: native Linux ivory-xl1200 + libivory_core.so + ivory-fep-convert.
    • packages.windows: cross-compiled self-contained Windows distribution (ivory-xl1200.exe, libivory_core.dll, ivory-fep-convert.exe, runtime .dlls, sample xl1200.scm).
    • devShells.mingw: extends default shell with mingwPkgs.stdenv.cc, mingwPkgs.windows.pthreads (headers unused if emu_os.h uses native Win32, but available for toolchain), sdl3Win, slirpWin, and pkgs.wineWow64Packages.minimal (wine64 + wineserver).
  • emu/Makefile Targets (TARGET_OS ?= native):
    • TARGET_OS=windows sets BUILD_DIR := build-win, CC := x86_64-w64-mingw32-gcc, EXE_EXT := .exe, DLL_EXT := .dll, CORE_SO := $(BUILD_DIR)/libivory_core.dll, omits -fPIC/-fvisibility=hidden/-ldl/-pthread, adds -DIVORY_BUILDING_CORE_DLL=1 to CORE_CFLAGS, and appends -lws2_32 -liphlpapi to shell LDFLAGS.
    • make -C emu dist-win: builds TARGET_OS=windows all and populates build-win/dist/ by recursively resolving non-system DLL imports via x86_64-w64-mingw32-objdump -p against SDL3/libslirp/GCC runtime search paths (excluding Windows OS DLLs like KERNEL32.dll, USER32.dll, WS2_32.dll, ADVAPI32.dll, UCRTBASE.dll, MSVCRT.dll, GDI32.dll, SHELL32.dll, OLE32.dll, IMM32.dll, WINMM.dll, SETUPAPI.dll, VERSION.dll, IPHLPAPI.dll).
    • make -C emu test-win & test-e2e-win (Persistent wineserver Runner):
      CAUTION

      Never wrap wine64 in prlimit --as=1GB (RLIMIT_AS): wine64-preloader reserves 3–6 GiB of PROT_NONE | MAP_NORESERVE virtual address space before main() (~25 MiB actual RSS) and immediately aborts under RLIMIT_AS=1GB.

      WINEPREFIX="$(mktemp -d /tmp/ivory-wine-XXXXXX)" \
      WINEDEBUG=-all DISPLAY= \
      SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
      WINEPATH="$(wine_dll_search_path);$(pwd)/build-win" \
      bash -c '
        trap "wineserver -k 2>/dev/null || true; rm -rf \"$WINEPREFIX\"" EXIT
        wineserver -p1
        for t in build-win/test_*.exe; do
          echo "=== [Wine] $t ==="
          wine64 "$t" || exit 1
        done
      '
      
      Using wineserver -p1 keeps one background wineserver alive across all .exe binaries, cutting total Wine test runtime from ~45s to ~2.5s.

4. Phase 2: s7 Configuration, Convenience Macros, call/cc Workbench & Portable E2E

4.1 Vendoring & Compiling s7 (emu/vendor/s7/)

  • Vendor upstream CCRMA s7.h and s7.c (0-BSD license; document upstream revision & license in emu/vendor/s7/README.md).
  • Compile as a dedicated object $(OBJ_DIR)/vendor/s7.o with:
    S7_CFLAGS := -std=c11 -O2 -g -DWITH_MAIN=0 -DWITH_C_LOADER=0 -DDISABLE_DEPRECATED=1
    
    • -DWITH_C_LOADER=0 disables dlopen-based runtime C compilation inside s7 (eliminating <dlfcn.h> on MinGW-w64).
    • Compiling s7.o without -Wall -Wextra -Werror isolates upstream compiler warnings while keeping -Wall -Wextra -Werror strictly enforced on emu/src/emu_script.c and all project files.
  • Strict Thread-Ownership Rule: s7_scheme *sc is created, evaluated, and destroyed exclusively on the Main Thread. emu_thread never calls any s7_* function.

4.2 Hybrid Declarative (define-machine ...) + Non-Destructive Save Config

Declarative Profile Form

(define-machine &key ...) populates EmuMachineConfig in C (paths inside (define-machine ...) resolve relative to the directory containing the .scm config file unless absolute):

;;; xl1200.scm — Machine Configuration & Custom Lisp Workbench
(define-machine
  :name         "XL1200 — Genera 8.3"
  ;; Hardware Identity (Main Board #o777400040 + IO0 #o10400260000 + MK48T02 NVRAM + 82586)
  :serial       12042                    ; 32-bit Main Board s/n (si:machine-model)
  :mfg-days     3650                     ; Days since 1982-01-01
  :io-serial    12042                    ; 32-bit I/O Board #0 s/n (rom[7..10])
  :io-part      170082                   ; Part number (rom[3..6])
  :io-rev       '(1 1 0)                 ; (mfg-rev func-rev minor-rev)
  :monitor      :philips                 ; :philips (0) | :sony (1)
  :mac          "08:00:05:12:34:56"      ; Symbolics IEEE OUI 08:00:05
  :nvram        "disks/xl1200.nvram"     ; Loaded on boot/power-reset; saved on clean exit
  :rtc-offset   0                        ; Seconds offset from host UTC (or (emu/rtc-year 1993))
  ;; Memory, Firmware & Pacing
  :ram-mw       8                        ; Default 8 MW
  :rom          "../ivory-fep-roms/fep330/rom.dump"
  :kernel       #f                       ; Optional IFEP-Kernel path
  :snapshot     #f                       ; Optional .snap file to load after boot init
  :clock        :realtime                ; :realtime | :deterministic
  :idle-yield   #t
  :overscan     :trim                    ; :trim (1084x812) | :full (1152x896)
  :keymap       :xl1200
  :mouse-mode   :capture                 ; :capture | :relative
  ;; SCSI Targets 0..6
  :scsi         '((0 :disk  "disks/genera83.raw" :mode :overlay :overlay "disks/genera83.ovl")
                  (4 :cdrom "../macivory/macivory_cdrom.iso")
                  (5 :tape  "disks/backup.tap"   :mode :rw))
  ;; Networking & Serial Host Backends
  :net          '(:mode :user :cidr "10.0.2.0/24"
                  :hostfwd ("tcp:127.0.0.1:2323-:23"))
  :serial-a     '(:mode :none)
  :serial-b     '(:mode :tcp-listen :addr "[::1]:4210")
  ;; External Debug IPC & Checkpoints
  :debug-local  #t                       ; Auto AF_UNIX / \\.\pipe\ivory-xl1200-<pid>
  :debug-tcp    #f                       ; Optional e.g. "[::1]:4200"
  :ckpt         '(:interval 0 :max 16 :ttl 0))

Startup Precedence & Zero-Argument GUI Launch

  1. Initialize EmuMachineConfig defaults (serial = 1200, mac = 08:00:05:00:00:01, ram_mw = 8, keymap = xl1200, overscan = trim).
  2. If --config <file.scm> is passed, evaluate <file.scm> in s7.
  3. Otherwise, if argc == 1 (zero CLI flags — e.g. double-clicking ivory-xl1200.exe):
    • Check <exe_dir>/xl1200.scm, then ./xl1200.scm. If found, set active_config_path and evaluate it.
    • If neither exists and !cfg.headless: enter Unconfigured Paused GUI Mode (dbg.paused = true, rt.unconfigured = true, ui.machine_setup_open = true) so the user can configure or load a machine from the microui Machine menu and click Save & Power On (in --headless mode with no args and no default config, print usage and exit 1).
  4. Apply any explicit CLI flags (--rom, --disk*, --eth-*, --debug-*, --headless, --steps, etc.) on top of (define-machine ...) so CLI overrides always win.
  5. Apply --script <file.scm> and repeatable --eval <expr> after machine initialization.
  6. Persistent NVRAM Lifecycle: If :nvram (or --nvram <path>) is configured:
    • If <path> exists on disk, load via api->nvram_mk48t02_load_file(&board->nvram, path) (and if :mac was explicitly set, synchronize nvram[0x20..0x25] to match :mac so NVRAM and io0_id_rom never disagree); if <path> does not exist yet, initialize fresh NVRAM with :mac and create <path> via nvram_mk48t02_save_file on clean shutdown (and on (emu/nvram-save) / GUI Save NVRAM). Also reload <path> inside debug_ctl_power_reset().

Non-Destructive Byte-Span Splice for GUI Save Config (~40 LOC)

When saving from the GUI to an existing .scm file, never overwrite user code outside (define-machine ...):

  1. Format the canonical (define-machine ...) S-expression string from the current EmuMachineConfig.
  2. Scan the existing file bytes at top level (skipping ;...\n line comments, nested #|...|# block comments, and "..." string literals with \" escapes) to locate the first top-level list whose head symbol is define-machine, recording [span_start, span_end).
  3. Write [0 .. span_start) + formatted_define_machine + [span_end .. EOF) (or prepend formatted_define_machine + "\n\n" if no define-machine form exists) to <path>.tmp and commit atomically via emu_atomic_replace().

4.3 s7 Primitives, Convenience Macros & call/cc Cooperative Scheduler

Cycle-Exact script_step_ceiling Coordination with emu_thread

At 150–250 MIPS (cpu-acceleration-plan.md), a single 16.6 ms GUI frame executes ~3–4M guest instructions. To make (emu/wait-steps N) and key-edge pacing cycle-accurate in both 60 FPS GUI mode and headless batch mode:

  • Add uint64_t script_step_ceiling (UINT64_MAX when no step-bounded s7 task is waiting) and uint32_t pending_hooks (EMU_HOOK_BOOT | EMU_HOOK_HALT | EMU_HOOK_BREAK | EMU_HOOK_WATCH) to EmuRuntime.
  • In emu_thread_main() (main.c:1943-1950):
    • If cpu->instr_count >= rt->script_step_ceiling, emu_thread wakes Main Thread and waits on rt->wake_cv (until Main Thread ticks s7 and raises or clears script_step_ceiling).
    • Otherwise, clamp slice = min(slice, rt->script_step_ceiling - cpu->instr_count) identically to ckpts->next_auto_instr!

Pure-Scheme call/cc Scheduler Prelude (Zero C s7_gc_protect Bookkeeping)

Keeping *emu-tasks*, *emu-actions*, and *emu-hooks* in top-level s7 globals ensures s7's garbage collector traces every live continuation and closure automatically, and call/cc never crosses a C stack frame:

(define *emu-tasks* '())   ; list of (id label resume-thunk ready?-thunk ceiling-thunk)
(define *emu-actions* '()) ; alist of registered GUI/hotkey custom actions
(define *emu-hooks* (make-hash-table 8))
(define *emu-next-task-id* 1)
(define *emu-yield-esc* #f)

(define (emu/spawn label thunk)
  (let ((id *emu-next-task-id*))
    (set! *emu-next-task-id* (+ id 1))
    (set! *emu-tasks*
          (append *emu-tasks*
                  (list (list id label thunk (lambda () #t) (lambda () 0)))))
    (emu/%recompute-ceiling!)
    id))

(define (emu/cancel-task! id-or-all)
  (set! *emu-tasks*
        (if (eq? id-or-all #t)
            '()
            (let loop ((xs *emu-tasks*) (acc '()))
              (cond ((null? xs) (reverse acc))
                    ((= (caar xs) id-or-all) (loop (cdr xs) acc))
                    (else (loop (cdr xs) (cons (car xs) acc)))))))
  (emu/%recompute-ceiling!))

(define (emu/yield-until label ready? ceiling-fn)
  (if *emu-yield-esc*
      (call/cc
        (lambda (k)
          (let ((id *emu-next-task-id*))
            (set! *emu-next-task-id* (+ id 1))
            (set! *emu-tasks*
                  (append *emu-tasks*
                          (list (list id label (lambda () (k #t)) ready? ceiling-fn))))
            (emu/%recompute-ceiling!)
            (*emu-yield-esc* 'yielded))))
      ;; Synchronous batch fallback (--script headless runner): drive slices directly
      (emu/%run-sync-until! ready? ceiling-fn)))

Core C Primitives & Convenience Macro Library

Categorys7 Binding / MacroBehavior
Universal debug_ctl Bridge(emu/cmd str)Executes any debug_ctl command string via in-memory DebugCtlSink; returns trimmed reply string (or signals 'emu-error on ERR ...).
Fast State & Memory(emu/state) / (emu/instr-count) / (emu/pc) / (emu/reg sym)Zero-parse plist/value accessors (:pc, :phase, :sp, :fp, :lp, :instr, :leds, :halted, :paused, :vram-hash, :vram-nonbg, :scsi-act, :eth-rx, :eth-tx).
40-Bit Tagged Words(emu/vma addr [count]) / (emu/pma addr [count]) / (emu/word dtp ptr [cdr])Reads/constructs 40-bit IvoryWords using s7's native 64-bit s7_int (#o octal & #x hex literals work natively: (emu/vma #o370001011000) -> '(:dtp 0 :cdr 0 :ptr #x... :raw #x...)).
Execution & Reset(emu/pause) / (emu/resume) / (emu/nmi) / (emu/warm-reset) / (emu/power-reset [unpause?]) / (with-paused-cpu body ...)Direct lifecycle control; with-paused-cpu uses dynamic-wind to pause during body and restore prior run state on exit.
Cooperative Waits(emu/wait-steps N)
(emu/wait-until pred? :max-steps M :slice S)
(emu/wait-pc vma :max-steps M)
(emu/wait-leds mask val :max-steps M)
(emu/wait-vram-change :max-steps M)
(emu/wait-vram-stable :quiet-steps Q :max-steps M)
(emu/wait-genera-idle :quiet-steps Q :max-steps M)
Built on emu/yield-until + script_step_ceiling. Note: emu/wait-genera-idle checks scsi_act stability + Merlin run-light (zero? (logand leds #x02)) so Genera's animated who-line clock never causes false non-idle timeouts!
Console Input Helpers(emu/key name) / (emu/type-line str :gap 50000) / (emu/send-keys item ...) / (emu/mouse dx dy [buttons])Pushes SLB key/chord/ASCII packets and yields :gap (50,000) guest instructions between edges so DUSCC/8237 RX DMA never overruns; records events into IvoryCheckpointStore for deterministic time-travel replay.
Custom GUI Actions(define-action sym (:label "..." :menu "..." :hotkey "Ctrl+F5") body ...)Registers sym in *emu-actions*; microui automatically populates the Actions menu and dispatches :hotkey (when mouse is uncaptured) by spawning body via emu/spawn.
Event Hooks(emu/on-boot fn) / (emu/on-halt fn) / (emu/on-break vma fn) / (emu/on-watch kind addr fn)Registers hardware breakpoints/watchpoints via IvoryCoreApi and invokes fn on the Main Thread when pending_hooks fires.
RTC Date Helper(emu/rtc-year year [month day hour min sec])Computes :rtc-offset relative to host UTC (e.g. (emu/rtc-year 1993) satisfies unpatched Genera 8.3's pre-Y2K RTC check automatically!).

4.4 Portable s7 Hardware E2E Suite (emu/tests/e2e_suite.scm)

Port all checks from emu/tests/test_e2e_puppet.sh into emu/tests/e2e_suite.scm (invoked via ivory-xl1200(.exe) --headless --rom ../ivory-fep-roms/fep330/rom.dump --script tests/e2e_suite.scm):

  1. Unattended 45M-step boot past ESDI init (halted == #f, leds == #x04, vram-nonbg > 2000).
  2. Interactive Device PROM menu via SLB + 8237 RX DMA (Space, emu/wait-vram-change).
  3. COW checkpoint capture, state mutation, deterministic rewind, and sparse .snap save/load round-trip.
  4. CD-ROM (macivory_cdrom.iso when present) SCSI target 4 attach + Device PROM IFEP Kernel load verification.
  5. Panel PPM / VRAM PBM export verification (1084×840 trim / 1152×924 full).

5. Phase 3: Integrated Disk Management (fep_convert) & Portable Serial Backends

5.1 Embedded Disk & FEPFS Toolkit (emu/include/ivory_fep_tools.h)

  • Compile fep_convert.c with -DFEP_CONVERT_NO_MAIN into SHELL_SRCS (while keeping the standalone ivory-fep-convert(.exe) binary target).
  • Replace fseeko/ftello in fep_convert.c with emu_fseek64/emu_ftell64.
  • Expose structured C functions (writing human-readable errors to char *err_buf, size_t err_cap rather than stderr when called from GUI/s7):
    typedef enum FepImageFormat {
        FEP_IMG_UNKNOWN       = 0,
        FEP_IMG_XL1200_FEPFS  = 1, /* 'LABL' little-endian 1280B/block */
        FEP_IMG_MACIVORY_FEPFS= 2, /* 'LBAL' big-endian (+ optional 0x400 prefix) */
        FEP_IMG_SIMH_TAP      = 3, /* SIMH .tap sequential tape */
        FEP_IMG_BLANK_1280B   = 4  /* Unformatted 1280B-aligned raw disk */
    } FepImageFormat;
    
    typedef struct FepDirEntryInfo {
        char     name[36];
        char     type[8];
        uint32_t version;
        uint32_t byte_length;
        uint32_t first_dpn;
        uint32_t page_count;
    } FepDirEntryInfo;
    
    typedef struct FepImageInfo {
        FepImageFormat  format;
        uint64_t        file_bytes;
        uint64_t        total_pages;
        uint32_t        cylinders;
        uint32_t        heads;
        uint32_t        pages_per_track;
        uint32_t        root_dir_dpn;
        uint32_t        fep_dpn;
        size_t          num_entries;
        FepDirEntryInfo entries[64];
    } FepImageInfo;
    
    IvoryStatus fep_tools_probe(const char *path, FepImageInfo *out, char *err, size_t err_cap);
    IvoryStatus fep_tools_create_fepfs(const char *path, uint64_t size_mb, char *err, size_t err_cap);
    IvoryStatus fep_tools_create_blank(const char *path, uint64_t size_mb, char *err, size_t err_cap);
    IvoryStatus fep_tools_create_tape(const char *path, char *err, size_t err_cap);
    IvoryStatus fep_tools_convert_macivory(const char *src_path, const char *dst_path,
                                           char *err, size_t err_cap);
    
  • Host-Shell COW Overlay Commit & Reset (scsi_overlay_commit_to_base / scsi_overlay_reset):
    • Reset/Discard Overlay: calls existing api->scsi_wd33c93_import_overlay(&board->scsi, target_id, NULL, 0U) (already truncates .ovl and clears RAM hash table in scsi_wd33c93.c:1960-2026).
    • Commit Overlay to Base Image: exports dirty blocks via api->scsi_wd33c93_export_overlay, detaches target_id, opens base_path r+b, writes each ScsiOverlayBlock at lba * block_size via emu_pwrite, fflush+fclose, re-attaches scsi_wd33c93_attach_disk_overlay, and clears the overlay via import_overlay(..., NULL, 0U) (~25 LOC in shell, zero IvoryCoreApi growth).
  • Expose matching debug_ctl subcommands (scsi commit <id>, scsi reset-overlay <id>, disk create-fepfs <path> <mb>, disk info <path>) and s7 wrappers (emu/overlay-commit, emu/overlay-reset, emu/fep-create, emu/fep-info).

5.2 Portable Serial Channel A & Channel B Host Backends (serial_host.{h,c})

Wire api->console_hw_set_serial_callbacks(&board->console, &cb) to a 2-channel host adapter (ch 0 = Console/Diagnostic Ch.A, ch 1 = Bulkhead RS-232 Ch.B):

  • Each channel uses two 4096-byte SPSC rings (tx_ring written by emu_thread in on_tx_byte, drained by Main Thread in serial_host_poll; rx_ring filled by Main Thread from EmuEndpoint, popped by emu_thread in poll_rx_byte) plus an atomic_uint_fast8_t modem_bits (DCD | CTS | DSR asserted whenever a TCP/pipe peer is connected, 0 when disconnected).
  • Supported backend specs (--serial-a <spec>, --serial-b <spec>, :serial-a / :serial-b in define-machine, and live switching in microui / debug_ctl serial <a|b> <spec>):
    • none (default)
    • tcp-listen:<[addr]:port> (dual-stack IPv4/IPv6 single-client listener via emu_ipc.c)
    • tcp:<[addr]:port> (non-blocking outbound TCP client via emu_ipc.c)
    • pipe:<name_or_path> (\\.\pipe\<name> on Windows; AF_UNIX stream socket on POSIX)
    • file:<path> (append-only TX capture file for boot/diagnostic logs)

6. Phase 4: microui Top Menu Bar & Floating Workbenches (ui_workbench.c)

6.1 Vendoring microui & Window-Space SDL_Renderer Composition

  • Vendor rxi/microui (emu/vendor/microui/{microui.c,microui.h}, MIT license) compiled as $(OBJ_DIR)/vendor/microui.o.
  • Clean Layer Separation in sdl_console.c:
    • state->pixels / state->texture (sdl_console_compose_frame) renders only the 1084×812 (trim) or 1152×896 (full) 1bpp VRAM + the passive 28px hardware LED bezel (1084×840 or 1152×924 total).
    • Delete Legacy Pixel Popovers (~500+ LOC removed): remove SdlPopoverMenu, PopoverLayout, BadgeHitboxes, clickable PAUSE/OFF/NMI/RST/KM/CD/TAPE hitboxes, and sdl_console_set_popover_for_test from sdl_console.c. Keep the passive status LEDs (PWR, RUN, HLT, PAU, CAP, KM tag, SCSI 0..6, ETH RX/TX/CD) intact.
    • Window Viewport & Top Menu Bar:
      • Define #define XL1200_TOP_MENUBAR_HEIGHT 22.
      • Default window creation height increases by +22 px (total_h + XL1200_TOP_MENUBAR_HEIGHT) so the console starts at 1:1 pixel scale with zero vertical squeeze.
      • On each sdl_console_flush_present():
        bool is_fullscreen = (SDL_GetWindowFlags(state->window) & SDL_WINDOW_FULLSCREEN) != 0U;
        int top_h = is_fullscreen ? 0 : XL1200_TOP_MENUBAR_HEIGHT;
        /* Letterbox console texture strictly inside (0, top_h, out_w, out_h - top_h) */
        compute_letterbox_rect_offset(0.0f, (float)top_h,
                                      (float)out_w, (float)(out_h - top_h),
                                      state->width, state->height, &dst_rect);
        SDL_RenderClear(state->renderer);
        SDL_RenderTexture(state->renderer, state->texture, NULL, &dst_rect);
        ui_workbench_render(state->renderer, out_w, out_h, is_fullscreen);
        SDL_RenderPresent(state->renderer);
        
      • Because microui draws directly in SDL_Renderer window coordinates via SDL_RenderFillRect, SDL_SetRenderClipRect, and one SDL_SCALEMODE_NEAREST embedded 8×14 ASCII monospace bitmap font + icon texture, UI text stays razor-sharp at any window size while dump-panel PPMs and .y4m recordings remain 100% pure hardware captures!

6.2 Input Routing, Mouse Capture & SDL3 TextInput Rules

  1. Captured Mode (con->mouse_captured == true):
    • All keyboard and mouse events go exclusively to the Symbolics console (ivory_keymap + hardware mouse). microui receives zero input events.
    • Tapping Right-Ctrl alone releases mouse capture (displayed on the right side of the 22px menu bar: [Mouse Captured — Right-Ctrl to release]).
  2. Uncaptured Mode (con->mouse_captured == false):
    • Feed mouse motion/buttons/wheel and keyboard navigation/editing keys (Backspace, Return, Tab, arrows, Ctrl+C/Ctrl+V via SDL_GetClipboardText / SDL_SetClipboardText) to mu_Context.
    • SDL3 Text Input Gate: SDL3 suppresses SDL_EVENT_TEXT_INPUT unless explicitly enabled. After mu_end(ctx) each frame:
      • If !con->mouse_captured && ctx->focus != 0 and !text_input_active: call SDL_StartTextInput(window).
      • If (con->mouse_captured || ctx->focus == 0) and text_input_active: call SDL_StopTextInput(window).
    • Action Hotkeys: When ctx->focus == 0 and no dropdown is open, check registered (define-action ... :hotkey ...) bindings (plus F11 fullscreen toggle) before forwarding uncaptured keys.
    • Entering Mouse Capture: Left-clicking inside dst_rect (VRAM area) enters SDL_SetWindowRelativeMouseMode(window, true) only when !con->cpu_paused && !rt->unconfigured && ctx->hover_root == NULL && !ui_menubar_open().

6.3 Top Menu Bar & Floating Workbench Specification

22px Top Menu Bar Layout

  • Left menus: Machine | Media | Net & Serial | Actions | Debug | View
  • Right inline status/quick-controls: active s7 task spinner + [Stop Task] (when *emu-tasks* is non-empty), [Pause/Resume], keymap indicator [KM: XL1200], and mouse capture hint.

Floating Windows (microui Resizable/Draggable Containers)

  1. Machine Setup (Machine -> Configure Machine..., auto-opened on unconfigured zero-arg launch):
    • Profile bar: current .scm path, Open .scm..., Save, Save As..., Save & Cold Boot (applies staged config + runs debug_ctl_power_reset(..., unpause=true)).
    • Identity & NVRAM Tab: Main Board Serial (uint32), Main Mfg Days, I/O Board #0 Serial, Part #, Revs, Monitor (Philips/Sony), MAC address (08:00:05:xx:xx:xx validator + Generate Symbolics MAC button), .nvram file picker + Save NVRAM Now, RTC mode (Host UTC vs Historical Year 1993 / custom offset).
    • Firmware & Memory Tab: Boot PROM path (Browse...), optional IFEP Kernel path (Browse...), RAM size (8 MW default), Clock mode (Realtime / Deterministic), Idle Yield checkbox.
    • Control Actions (Machine menu): Pause / Resume, Send NMI (Drop to FEP), Warm VME Reset, Cold Power Reset, Quit.
  2. Disk & Media Manager (Media -> SCSI & Disk Manager... + quick CD/Tape eject/attach in Media menu):
    • SCSI Bus Table (Targets 0..6, showing FEP unit 7 + id): kind (Disk / CD-ROM / Tape / Empty), path basename, size/geometry, mode (RO / RW / COW Overlay with live dirty-block count), Attach..., Detach, and (when overlay_enabled) Commit to Base & Reset Overlay (with two-click confirmation).
    • FEPFS & Image Creation Tool:
      • Create Initialized XL1200 FEPFS Disk (256 MiB, 512 MiB, 1024 MiB, or custom MiB -> SDL_ShowSaveFileDialog -> fep_tools_create_fepfs, with option to immediately attach on Target 0).
      • Create Blank SIMH .tap Tape / Create Blank Raw Disk.
      • Convert MacIvory Disk to XL1200 (src -> dst).
      • Inspect Image (fep_tools_probe displaying LABL geometry, fep_dpn, and root FEPD directory files).
  3. Network & Serial Window (Net & Serial -> Configure...):
    • Ethernet backend status (User NAT (libslirp) / Linux TAP / Off), subnet CIDR, live TX/RX/CD counters, and hostfwd table (Add / Remove rules, applied on reset or slirp recreate).
    • Serial Ch.A & Ch.B live backend selectors (None, TCP Listen, TCP Connect, Named Pipe / Socket, Log to File), address/path textbox, Apply, live DTR/RTS/DCD/CTS indicators, and TX/RX byte counters.
  4. Actions Menu & Custom Workflows:
    • Dynamically lists every (define-action ...) grouped by :menu with its :hotkey label; clicking spawns the action on *emu-tasks*. Includes Load Script (.scm)... and Cancel Running Actions.
  5. Debug, Snapshots & s7 REPL Windows (Debug menu):
    • Snapshots & Time-Travel Checkpoints: Save .snap..., Load .snap..., Take Checkpoint (with optional label + Pin checkbox), scrollable checkpoint list (ID, Instr, Label, Pinned, Rewind, Pin, Delete), unique COW pages / KiB meter, and auto-checkpoint interval controls.
    • CPU & Capture Tools: live PC/SP/FP/LP/LEDs readout, Breakpoint (0..7) & Watchpoint (0..3) add/clear controls, .y4m video recording Start/Stop, PBM/PPM screenshot save, and Hot-Reload Core (libivory_core) button.
    • s7 Lisp REPL Window: scrollable output transcript + single-line S-expression input (Enter evaluates in s7 on Main Thread; Up/Down recalls history; output of (display ...) / (format #t ...) captured via s7_open_output_string port and appended to transcript).

7. Implementation Phasing, /swarm Ownership Map & Verification Gates

TIP

Running with /swarm in This Jujutsu (JJ_Git) Repository: Per workspace orchestration rules, use workspace: "inherit" with strictly disjoint per-worker file ownership within each phase, run per-worker gcc -fsyntax-only checks during parallel authoring, and serialize full make + Linux/Wine test gates through a single @verifier.

PhaseNew / Modified FilesDisjoint Worker Split (Optional /swarm)Mandatory Verification Gates
Phase 1: Portable I/O, 2-Thread Runtime, MinGW-w64 & Wine CI• emu/include/{ivory_emu.h,ivory_core_api.h,emu_os.h,emu_io.h,emu_ipc.h}
• emu/src/{merlin.c,mem.c,core_api.c,eth_82586.c,eth_tap_linux.c,scsi_wd33c93.c,snapshot.c,core_loader.c,eth_slirp.c,emu_ipc.c,debug_ctl.c,main.c,sdl_console.c}
• emu/tests/{test_debug_ctl.c,test_snapshot_reload.c,test_merlin.c}
• flake.nix, emu/Makefile
• Worker A (Core & Shims): emu_os.h, emu_io.h, ivory_emu.h, ivory_core_api.h, merlin.c, mem.c, core_api.c, eth_82586.c, eth_tap_linux.c, scsi_wd33c93.c, snapshot.c
• Worker B (Shell IPC & 2-Thread Loop): emu_ipc.{h,c}, core_loader.c, eth_slirp.c, debug_ctl.c, main.c, sdl_console.c (pthread->emu_os.h)
• Worker C (Build & Wine Tests): flake.nix, emu/Makefile, test_debug_ctl.c, test_snapshot_reload.c, test_merlin.c
1. nix develop --command make -C emu clean all test test-e2e
2. readelf -WS emu/build/obj/core/*.o -> 0 bytes writable .data/.bss
3. nix build .#windows & make -C emu dist-win
4. x86_64-w64-mingw32-objdump -p emu/build-win/libivory_core.dll -> exports only ivory_core_get_api
5. make -C emu test-win passes all 11 .exe unit suites under wine64 (verifying \\.\pipe\ivory-xl1200-*, IPv4 127.0.0.1 + IPv6 [::1] TCP, and live .dll reload).
Phase 2: s7 Config, Macros, call/cc Workbench & Portable E2E• emu/vendor/s7/{s7.c,s7.h,README.md}
• emu/include/ivory_script.h
• emu/src/emu_script.c
• emu/src/main.c (--config, --script, --eval, script_step_ceiling, pending_hooks, .nvram lifecycle)
• emu/tests/{test_s7_config.c,e2e_suite.scm}, emu/Makefile
• Worker A (s7 Engine & Prelude): emu/vendor/s7/*, ivory_script.h, emu_script.c
• Worker B (main.c Wiring & Suites): main.c, Makefile, test_s7_config.c, e2e_suite.scm
1. test_s7_config (Linux) & test_s7_config.exe (wine64) verify (define-machine ...) serial/MAC/NVRAM survival across power-reset, CLI override precedence, byte-span Save Config preserving user define-actions, and cycle-exact call/cc script_step_ceiling.
2. Native ./emu/build/ivory-xl1200 --headless --rom ivory-fep-roms/fep330/rom.dump --script emu/tests/e2e_suite.scm and make -C emu test-e2e-win (wine64) pass all authentic Boot PROM + SLB DMA + COW checkpoint + CD-ROM checks.
Phase 3: Disk Toolkit (fep_convert) & Portable Serial Host• emu/include/{ivory_fep_tools.h,ivory_serial_host.h}
• emu/src/{fep_convert.c,serial_host.c}
• emu/src/{debug_ctl.c,emu_script.c,main.c}
• emu/tests/{test_fep_convert.c,test_serial_host.c}, emu/Makefile
• Worker A (FEPFS & Overlay Commit): ivory_fep_tools.h, fep_convert.c, test_fep_convert.c
• Worker B (Serial Host & Bindings): ivory_serial_host.h, serial_host.c, debug_ctl.c, emu_script.c, main.c, test_serial_host.c, Makefile
1. test_fep_convert(.exe) verifies in-process fep_tools_create_fepfs, fep_tools_probe (LABL/FEPD), MacIvory conversion, and COW .ovl commit-to-base & reset.
2. test_serial_host(.exe) verifies Ch.A/Ch.B TX/RX + DCD/CTS status across IPv4/IPv6 TCP, Named Pipe/AF_UNIX, and file capture on both Linux and wine64.
Phase 4: microui Top Menu Bar & Floating Workbenches• emu/vendor/microui/{microui.c,microui.h,README.md}
• emu/include/ivory_ui.h
• emu/src/{ui_workbench.c,sdl_console.c,main.c}
• emu/tests/{test_console.c,test_ui_workbench.c}, emu/Makefile
• Worker A (microui Atlas & Workbenches): emu/vendor/microui/*, ivory_ui.h, ui_workbench.c
• Worker B (sdl_console.c Popover Removal & Tests): sdl_console.c, main.c (zero-arg GUI launch), test_console.c, test_ui_workbench.c, Makefile
1. test_console(.exe) & test_ui_workbench(.exe) (SDL_VIDEODRIVER=dummy) verify 1084×840 / 1152×924 .y4m & dump-panel dimensions are unchanged, 22px menu bar never overlaps VRAM, fullscreen auto-hides menu bar, mouse-capture click-through guard holds, SDL_StartTextInput toggles with mu_ctx->focus, and zero-arg launch opens paused Machine Setup.
2. Full gate: make -C emu clean all test test-e2e dist-win test-win test-e2e-win exits 0.
Related Chip Datasheets (5)All Component Datasheets →