CS technical publication · 16 chapters · 4 parts

Computer System Field Manual

Canonical operator, programming, architecture, and recovery guidance for CS-Linux, CS-DOS, CS486DX, CS486DX2, and CS386SX machines.

Choose a route

Start with the work you need to finish.

First program

Choose, connect, save, and run a CS486 program.

  1. 01 System orientation & machine choice
  2. 02 Terminal, Web access, and editors
  3. 03 Filesystem, storage, and persistence
  4. 05 Computer System Python on CS486

Python + Redstone

Build and verify an event-driven world controller.

  1. 01 System orientation & machine choice
  2. 02 Terminal, Web access, and editors
  3. 03 Filesystem, storage, and persistence
  4. 05 Computer System Python on CS486
  5. 06 Redstone, peripherals, and events
  6. 07 Worked project: build, test, measure, deploy

CS-Linux operator

Operate the terminal, filesystem, shell, and recovery tools.

  1. 01 System orientation & machine choice
  2. 02 Terminal, Web access, and editors
  3. 03 Filesystem, storage, and persistence
  4. 04 CS-Linux shell and utilities
  5. 15 Faults, diagnostics, and recovery

Build and play NetHack

Rebuild the guest-authored game, play it, and manage saves safely.

  1. 01 System orientation & machine choice
  2. 02 Terminal, Web access, and editors
  3. 03 Filesystem, storage, and persistence
  4. 04 CS-Linux shell and utilities
  5. 12 CS C/C++ 1.0

Native development

Understand, compile, inspect, and optimize native programs.

  1. 01 System orientation & machine choice
  2. 03 Filesystem, storage, and persistence
  3. 09 Machine architecture and execution model
  4. 10 CS ASM 1.0
  5. 11 CS QBASIC 1.0
  6. 12 CS C/C++ 1.0
  7. 13 Optimization workshop

Portable / CS-DOS

Operate and program the Portable Computer System.

  1. 01 System orientation & machine choice
  2. 02 Terminal, Web access, and editors
  3. 14 CS-DOS 1.0 on CS386SX
  4. 09 Machine architecture and execution model
  5. 10 CS ASM 1.0
  6. 11 CS QBASIC 1.0
  7. 12 CS C/C++ 1.0

Diagnose a problem

Start from an observed symptom and finish at a bounded outcome.

  1. 15 Faults, diagnostics, and recovery
  2. 16 Limits, compatibility, glossary, and indexes
01 / 16
PreviousNext

Chapter 01 · Operator orientation

From powered block to running program

A Computer is a persistent, sandboxed machine. The desktop runs Computer System Linux 1.0 (CS-Linux 1.0); the portable runs Computer System DOS 1.0 (CS-DOS 1.0). Its terminal, files, redstone state, CPU budget, and RAM belong to its identity and survive normal world reloads.

ComputerComputer System Deskpro 486DX · 33 MHz · 2 MiBAdvancedComputer System Deskpro 486DX2 · 66 MHz · 8 MiBPortableComputer System LTE 386SX · 16 MHz · 2 MiB

1.1 Choose a machine

MachineDefault profileDiskDisplayLanguages
Computer System Deskpro 486DX
Computer
CS486DX · CS-Linux 1.040 MiB IDEBuilt-in 640x480 CRTComputer System Python, CS ASM 1.0, CS C/C++ 1.0; no BASIC
Computer System Deskpro 486DX2
Advanced
CS486DX2 · CS-Linux 1.080 MiB IDEBuilt-in 640x480 CRTComputer System Python, CS ASM 1.0, CS C/C++ 1.0; no BASIC
Computer System LTE 386SX
Portable
CS386SX · CS-DOS 1.020 MiB IDEBuilt-in; held or placedCS ASM 1.0, CS C/C++ 1.0, CS QBASIC 1.0; no user Python

The initial CS-Linux image allocates roughly 2–4 MiB and CS-DOS roughly 0.5–1 MiB. These are real guest files with sizes, permissions, and inode identities. Hardware identity, OS profile, storage, and the permanent browser connection number persist with the Computer identity.

1.2 Power on, connect, and sign in

  1. Power on. CSBIOS reports the persisted hardware, then hands control to the selected OS.
  2. Connect. Activate the eligible machine and enter its four-digit number on the Web Terminal entry page.
  3. Initialize credentials. A new CS-Linux installation asks for and confirms the password of its initial cs account before exposing the shell.
  4. Authenticate later boots. Existing CS-Linux installations show /etc/issue, ask for a username at <computer-id> login:, and then ask for that account's password; CS-DOS presents C:\> after its bounded startup files finish.

cs is UID/GID 1000 with home /home/cs and membership in sudo. UID 1000 is the protected boot-service account: its name and home may be changed while it is inactive, but it cannot be deleted. Root is UID/GID 0 and initially password-locked. Each OS boot resets the display but does not format the guest disk. Password plaintext is never stored or written to terminal history.

1.3 Operating cycle

  1. Inspect. Run cpuinfo, free -h, and quota.
  2. Edit. Use vi for source files. Desktop Computer System Python starts at /startup.py; the portable DOS profile uses AUTOEXEC.BAT.
  3. Build. Use as, cc, or c++; add -c for an object and combine objects with ld. On CS-DOS, use QBASIC for BASIC source.
  4. Measure. Run compiled programs with run --stats.
  5. Optimize. Compare instructions, cycles, output, and memory use—not host wall time.

Persistent

/etc, /usr, home files, executables, terminal snapshot, identity, and configured hardware.

Volatile or bounded

/tmp, active VM frames, event queues, compiler work, terminal output, retries, and each direct machine run.

1.4 First inspection

whoami
pwd
cpuinfo
free -h
df
quota
ls -la /

1.5 Choose a reading route

GoalRoute
First program01 → 02 → 03 → 05
Python + Redstone01 → 02 → 03 → 05 → 06 → 07
CS-Linux operator01 → 02 → 03 → 04 → 15
Build and play NetHack01 → 02 → 03 → 04 → 12
Native development01 → 03 → 09 → 10 / 11 / 12 → 13
Portable / CS-DOS01 → 02 → 14 → 09 → 10 / 11 / 12
Diagnose a problem15 → 16

Reference chapters are destinations, not prerequisites. Follow one route, then use manual search to jump directly to a command, API, instruction, fault, or concept.

Chapter 02 · Operator console

Terminal control and source editing

The terminal is a fixed-cell machine display. The Web Terminal keeps the guest grid at 80x25, scales its glyphs with the browser viewport, and centers the complete CLI or TUI display frame horizontally and vertically while preserving the same cells, cursor, colors, input semantics, and guest-rendered scrollbars. One blank raster row above and below the active cells provides period-appropriate CRT vertical blanking without becoming part of the guest grid. Options applies a tab-only CRT profile and independent glass shape after that canonical frame is rendered.

2.1 Web access and session states

When the published numeric address belongs to the companion host, no custom public origin is configured, and automatic opening is not explicitly disabled, clicking an eligible Computer prepares a viewer session. The companion opens its loopback handoff only after Bedrock acknowledges that exact attachment. The handoff GET redirects without consuming authentication state; the stable page removes its handoff flag from history, exchanges the four-digit activation with one same-origin POST, and then claims the writer lease. This opens the server host's browser, not a remote player's browser; the four-digit entry page remains available to remote players. Operators may set WEB_COMPANION_AUTO_OPEN=0 to disable opening or 1 to enable it explicitly while retaining listener-reachability checks.

A host administrator may persist a different listener port, advertised origin, worker count, and worker CPU engine with npm run web:config -- set --port 80 --url http://server-address --runtime-workers 2. Worker count defaults to 2 and accepts integers from 1 through 16. --cpu-engine selects which CS486 implementation those workers run. typescript, the production interpreter, is the only accepted value: it is the single CS486 implementation, so a worker and the Bedrock pack execute the same code. Any other value fails companion startup explicitly rather than being substituted. Use npm run web:config -- show to inspect the active file and restart the companion after changing it. Environment variables remain one-start overrides. The CPU badge reports a stable Wn/N assignment and whether active work is on a worker, local Bedrock, or both. Plain HTTP is for a trusted LAN only; Internet publication requires an HTTPS reverse proxy.

StateWhat the operator can doTerminal outcome
WriterType, paste, submit, interrupt, and edit after the handoff exchange or an explicit takeover.Input is accepted at both transport boundaries.
ViewerSelect and copy. Use Take control to reclaim the single writer lease.Viewer input is rejected explicitly.
out_of_rangeReturn to 2.75 blocks or nearer after leaving the three-block radius.The live stream pauses without destroying the session; the deadband prevents boundary flapping.
DisconnectedReconnect with the remembered four-digit number.The bearer token rotates; retries are bounded, honor rate limits, and stop when a new activation is required.
ClosedNo further input is accepted.Only the final detached session emits terminal_closed.

2.2 Keyboard map

KeyShell actionvi action
EnterSubmit commandInsert newline
TabComplete command or pathInsert indentation
Ctrl+N / Ctrl+PN/ANext / previous completion
Ctrl+ELinux end of line; DOS unchangedCancel active completion
↑ / ↓Linux history; DOS after bare DOSKEYMove cursor
F3DOS recalls the latest submitted lineGuest-defined action
Ctrl+CCopy a selection; otherwise interrupt foreground work or abort the idle lineUse the current guest-defined action
Ctrl+VPaste clipboard textPaste in insert mode

Linux retains Ctrl+A/E/U/K/W/D line editing. The DOS prompt does not inherit those Emacs shortcuts. An idle Ctrl+C prints ^C, redraws the prompt, and leaves shell history and Computer lifecycle unchanged.

2.3 Normal mode

Move h j k l, arrows, gg/G, PageUp/PageDown

Definition gd; return with Ctrl+O

Edit i/I, a/A, o/O, x, dd, >>/<<

History u

Save + quit Shift+ZZ

Discard + quit Shift+ZQ

Leave insert Esc or Ctrl+[

2.4 Command mode

Save :w

Name and save :w path

Quit :q

Save + quit :wq, :wq!, or :x

Discard :q!

Syntax :syntax on / :syntax off

Display :set number rainbow list wrap

Indent :set autoindent expandtab tabstop=N shiftwidth=N

Language :set ft=auto|python|c|cpp|asm|shell|json|text

Completion :set complete completecase=smart completeprefix=2

Sources :set completesources=current,buffers,symbols,keywords

Definitions :set definitionsources=current,buffers

Symbols :symbols

Inspect :set, :set all, :set option?

Guest command :!command / :!!

Insert output :r !command

Cancel empty : Backspace

The editor begins with content on the first row and a cell-wide block cursor. Normal mode has no persistent mode banner or fixed shortcut help. The reverse-video penultimate row shows the file name, [+] only for unsaved changes, cursor position, and viewport position. The final row is reserved for commands and messages, and shows -- INSERT -- while inserting. Bare vi opens [No Name]. It must be named with :w path before an unnamed save can succeed.

Documents are capped at 999 lines, and enabled line numbers use a fixed three-digit gutter with the active number brighter than inactive numbers. Syntax, numbers, rainbow indentation, autoindent, whitespace markers, and wrapping start off. expandtab, tabstop=2, and shiftwidth=2 are the initial tab settings; numeric values are limited to 1 through 16. Prefix a Boolean option with no to disable it.

Completion starts on with a two-character prefix and smart case. Ctrl+N/Ctrl+P cycle at most 64 candidates; Ctrl+E restores the original text and Tab remains indentation. Priority is current-file words, words from eight recently visited buffers, lightweight function/type/macro/ASM-label symbols, language keywords, then optional direct includes. Add includes to completesources or definitionsources to opt in. Direct include lookup is non-recursive, reads at most eight credentialed guest files and 32 KiB total, and never starts an LSP or reads the host. The current-file index scans at most 256 KiB or 16,384 lines and retains at most 2,048 word occurrences and 512 symbols.

gd uses the same bounded symbol index; Ctrl+O returns through at most 16 jumps. External jumps require a clean current buffer. filetype=auto detects Python, C, C++, CS ASM, shell, JSON, or text; ft is its short name.

Linux reads a bounded ~/.vimrc; DOS reads C:\_VIMRC. The file accepts only the documented syntax and set commands, at most 4,096 characters and 32 lines. An invalid line rejects the open atomically.

:! uses the sandboxed guest shell, never the host. Background, asynchronous, session-control, foreground-process, and TUI commands fail explicitly. :r ! inserts at most 128 lines or 4,096 characters as one undoable edit, and the parent shell state is restored before editing resumes.

2.5 DOS-style EDIT

On the DOS profile, EDIT [path] opens the shared CS QBASIC 1.0 editor in /EDITOR mode. Bare EDIT starts an UNTITLED buffer and F2 saves it as C:\NONAME.TXT. Linux does not expose EDIT and uses vi. The top bar leaves one gray cell before the plain File, Edit, Search, and Options headings and keeps Help right-aligned; no (F)-style suffix is printed. Plain EDIT's File menu contains New, Open, Save, Save As, a separator, Print, a separator, and Exit without inline shortcut labels. Print remains visible for layout compatibility but reports that CS-DOS has no printer. The next row centers the filename, the blue body uses ↑/↓ on its vertical scrollbar, and the gray horizontal track uses ←/→. The cyan footer also keeps one leading cell, uses black text, and shows contextual help or status with only the zero-padded line/column, such as 00001:001, at the right. Menus and dialogs use gray chrome, black reversed selection, a two-cell-right/one-row-down black shadow, and explicit keyboard focus. In the Web Terminal this DOS presentation uses IBM VGA 9x16 at weight 400 with unit line spacing and five-color palette: bright white #FFFFFF for the active line number, gray #a8a8a8, blue #0000AA, cyan #00AAAA, and black #000000.

At 80x25, Ctrl+O starts with selected *.TXT, separate bounded Files and Dirs/Drives panes, a horizontal file track, a vertical directory track, and OK, Cancel, and Help. Ctrl+Shift+S uses the same guest-only C:/A: browser for Save As; narrower terminals retain the compact fallback. The provider lists at most 256 strict DOS 8.3 entries, filters with DOS */?, supports keyboard and primary-mouse selection, and revalidates directory/media generation before Open or Save. Clicking outside the visible menu box cancels it and never activates an item by row alone. Display exposes only Scroll Bars and the plain-EDIT default Tab Stops: 8; the fixed editor colors are not configurable. Tab and Shift+Tab traverse every field and OK, Cancel, and Help; Cancel and Esc restore the opening values.

KeyAction
F1Open or close bounded editor help
F2 / Ctrl+SSave only if the opened snapshot still matches; otherwise choose Overwrite, Reopen, or Cancel
Ctrl+O / Ctrl+Shift+SBrowse Open / Save As; an existing destination requires Replace or Cancel
F10 / Alt / Alt+FOpen File or another keyboard/mouse menu; arrows and Enter select. Bare Alt provides a Web fallback when Chrome reserves an Alt chord.
Ctrl+F / F3Find text / find next with bounded forward search
Ctrl+C / Ctrl+X / Ctrl+VCopy, cut, or paste the bounded current selection
Ctrl+Home / Ctrl+EndMove to the start or end of the document
Ctrl+Left / Ctrl+RightMove by word
Ctrl+Y / Ctrl+ZDelete the current line / undo
InsertToggle insert and overwrite modes
Alt+F, XExit; a dirty buffer requires Save, Discard, or Cancel

Documents are capped at 999 lines with fixed three-digit line numbers. Text loads reject NUL/Ctrl+Z binary data and capacity-plus-one input without partial mutation. Successful writes use DOS CRLF. A failed read, save, or media refresh leaves the current buffer owned by EDIT.

The browser retains up to 1,024 editor keys until Bedrock returns a correlated admission result. It sends at most 16 keys per relay, retries explicit busy responses, transient companion 5xx responses, and fetch disconnects at most five times with bounded exponential backoff, and removes a batch only after acceptance. If those retries are exhausted, Retry input resumes the same unacknowledged batch instead of silently dropping it. Capacity overflow and unacknowledged keys discarded by session replacement or close are reported explicitly; input is never silently truncated.

2.6 Editing procedure

  1. On DOS, use EDIT C:\WORK\PROGRAM.C for direct full-screen editing. On Linux, use vi program.py.
  2. In EDIT, type directly and navigate with arrows, Home/End, or PageUp/PageDown. Save with F2.
  3. In vi, press i, enter source, press Escape, type :w, and press Enter.
  4. Run or compile from the shell. Reopen the file to correct reported lines.

2.7 Static GitHub Pages reference

The project GitHub Pages site publishes this same canonical 16-chapter field manual as a static reference. Chapter and section links use stable URL fragments, search remains bounded to 24 section results, and the complete publication remains readable with JavaScript unavailable.

The Pages site is documentation only. It cannot connect to BDS, accept a four-digit Computer number, obtain a bearer token, display a live terminal, submit guest input, or prove that a Web Terminal session is available. To operate a Computer, start the local companion with npm run dev:bds:web and use the address activated from Minecraft. Never enter a Computer connection number or terminal credential into the Pages site.

2.8 Pagers: more and less

more PATH and less PATH are bounded, document-resident full-screen viewers, structurally close to vi's file view but read-only and much smaller. Both require a real file path; like vi, neither reads stdin or runs in a pipeline or redirect. The reverse-video final row shows a status indicator instead of a command line, and the cursor is a block positioned at its end.

Keymoreless
Space / PageDownNext screenNext screen
EnterNext lineNext line (also j / ArrowDown)
PageUp / bNot supportedPrevious screen
ArrowUp / kNot supportedPrevious line
g / GNot supportedJump to top / bottom
qQuitQuit

more's status line reads --More--(NN%), then --More--(END) at the last screen, matching traditional forward-only more. less shows path (Top|Bot|All|NN%), matching real less's indicator. Documents are capped at 999 lines like vi; long lines truncate at the terminal width rather than wrapping, and there is no horizontal scroll or search in this bounded reimplementation.

Chapter 03 · Filesystem interface

Filesystem and storage

Minecraft behavior is exposed through bounded adapters. The domain/runtime core does not import Minecraft APIs.

3.1 Linux layout

PathRole
/etcRoot-owned system configuration, account files, MOTD, and Bash startup
/etc/inittabSysV init: sysinit/wait/respawn/initdefault entries selecting the boot runlevel
/etc/init.d, /etc/rcN.dReal per-service start/stop/restart/status scripts and the SNN/KNN symlink farm per runlevel
/etc/crontabSandboxed system crontab, re-read on cron service start/restart
/devState-backed guest device identities
/procDynamic CPU, memory, process, service, device, version, uptime, load, and mount views
/runVolatile runtime mount
/tmpVolatile mode-1777 sticky working files
/usr/share/manInstalled versioned manual index notice
/var/logBounded messages and authentication journal views
/startup.pyMode-0644 desktop boot source owned and executed by the authoritative UID 1000 account
/home/csInitial UID/GID 1000 user home and mode-0600 shell history
/rootUID/GID 0 superuser home

CS-Linux persists mode, UID, GID, modification time, symbolic links, hard-link groups, deletion tombstones, and a cold OS-runtime projection. Older snapshots without these optional fields remain readable and receive safe defaults on boot; they never resurrect a stale process, job, mount, or authenticated session.

3.2 Terminal state

The fixed-cell model is the source of truth. Web and Resource Pack UIs render snapshots. A newly opened Web Terminal receives control immediately and demotes the previous writer; a viewer may reclaim control explicitly.

3.3 World state

Inputs and outputs are side-addressed. Digital and analog observations enter through bounded events; output state persists with the Computer record.

3.4 Storage model

The guest filesystem maps paths to inodes and content-addressed blobs. Immutable OS images are shared by all Computers; each machine persists only its copy-on-write files, metadata changes, hard links, and deletion tombstones. Linux utilities are executable files under /usr/bin, /sbin, or /usr/sbin; DOS external utilities are under C:\DOS. Deleting one makes that command unavailable until its file is restored. Linux built-ins share /bin/bash, while DOS internal commands share root C:\COMMAND.COM. Bedrock World Dynamic Properties remain canonical and retain the current and previous complete generations with checksum-backed, content-addressed pages.

HDD requests model controller setup, CHS seek, 3,600 RPM rotation, PIO transfer, and write settling. The removable computer_system:floppy_disk item adds a 1.44 MiB FAT12 medium with stable identity, media generation, 300 RPM, 500 ms spin-up, 3 ms per-track seek, 62,500 B/s transfer, write settling, write protection, and ejection cancellation. FDD requests are split at 36 sectors. The Web Terminal synthesizes bounded insert, eject, motor, seek, read, and write sounds after a browser gesture and stops them when the session closes or leaves range. While a disk is present, the writer may press the Web Terminal Eject button; the button stays unavailable for viewers and reports completion only after Bedrock returns the medium to the connected player.

sudo mkfs.fat -F 12 -n SHARED /dev/fd0
sudo mount -t vfat /dev/fd0 /mnt/floppy
cp README.TXT /mnt/floppy/
sudo umount /mnt/floppy
sudo eject /dev/fd0

df -h
du -sh /home/cs
quota
stat /startup.py

3.5 CS-Linux command surface

AreaCommands
Identitywhoami, id, groups, login, logout, passwd, su, sudo, getent
Accountsuseradd, userdel, usermod, groupadd, groupdel
Processes and jobsps, top, kill, pgrep, pkill, killall, jobs, fg, bg, wait
Sessions and servicestty, who, w, last, service, telinit, runlevel
Manual and logsman, apropos, dmesg
Files and metadatals, stat, chmod, chown, chgrp, ln, readlink, realpath, rmdir, umask
Text and inspectiontee, cmp, diff, file, sha256sum, md5sum, base64, nl, od, hexdump, xargs
Pagersmore, less
Systemhostname, uname, date, uptime, vmstat, free, df, du, mount, sync, mktemp, shutdown, reboot
Bash builtinsalias, unalias, command, read, local, shift, getopts

Linux-facing commands use LF, Linux-style labels, and observable nonzero status for errors. date --game and date --virtual remain documented CS-Linux extensions. yes, xargs, dumps, hashes, and diffs stop at explicit sandbox limits.

3.6 Dynamic proc files

cat /proc/cpuinfo
cat /proc/meminfo
cat /proc/version
cat /proc/uptime
cat /proc/loadavg
cat /proc/mounts
cat /proc/devices
cat /proc/services
cat /proc/self/status
cat /proc/1/cmdline

These entries are read-only views generated from the Computer identity, hardware, clock, process, service, device, and mount model. Every live PID exposes bounded cmdline, stat, and status views. They are not host Linux files. Directory and hard-link indexes keep ordinary listings O(N); no command scans the host filesystem.

3.7 Ownership, DAC, and umask

Every guest-facing file operation uses one credentialed filesystem boundary. Owner, group, and other bits control reading, writing, execution, and directory traversal; effective UID/GID and supplementary groups determine the selected class. New entries inherit the caller's effective UID/GID after the active umask, initially 022. Owners may make permitted mode and group changes; ownership transfer remains superuser work. The mode-1777 /tmp directory enforces sticky deletion, hard-link creation is protected, symbolic-link traversal is bounded, and setuid/setgid bits never grant hidden credentials.

These checks also apply to editors, compilers, Computer System Python imports and fs calls, startup programs, and MCP shell execution. Root may perform administrative filesystem work, but no guest path bypasses the account and DAC boundary to reach host files.

3.8 Complete legacy account migration

A recognized older installation with the default computer account is migrated once to cs. The user, primary group, supplementary memberships, and shadow key are renamed, and /home/computer moves to /home/cs. The old username and path are then absent: there is no alias and no compatibility symlink.

The conversion preserves the exact password payload, UID/GID 1000, file contents, modes, ownership, mtimes, symbolic-link targets, hard-link identities and shared contents, and deletion tombstones. Restarting is idempotent. If an unrelated /home/cs or incompatible account record makes the result ambiguous, migration fails explicitly instead of merging or discarding data.

Chapter 04 · Command environment

Computer System Bash

A bounded compatibility shell implemented inside the application layer. It is not host Bash and cannot escape to a native process.

4.1 Grammar

FeatureSyntax
Descriptorsstdin 0, stdout 1, stderr 2
Pipelinea | b, a |& b
Redirection<, >, >>, 2>, 2>>, 2>&1, &>, <<WORD
Control&&, ||, ;
Expansion$VAR, $?, positional parameters
Scriptsif/else, for, while, functions, break, continue, return, source

At a terminal, stdin (fd 0), stdout (fd 1), and stderr (fd 2) begin at the guest terminal. | passes only stdout to the next command's stdin; |& passes stdout and stderr. Redirections are applied from left to right. Thus probe >all 2>&1 or probe &>all shares one destination, while probe 2>&1 >out leaves stderr on the original stdout destination. An explicit redirect can override a pipe; |& performs its implicit stderr duplication after explicit redirects. tee log retains pipeline stdout on screen while writing the same bytes to a guest file. A literal <<WORD here-document supplies stdin without a file; submitted input ends at its terminator and scripts continue with the following line.

4.2 Command families

Files pwd cd ls cat mkdir touch rm cp mv find stat df du quota

Text echo printf head tail wc grep rg jq sed awk perl sort uniq tr cut seq tee nl md5sum base64 xargs

Archives tar gzip gunzip zip unzip

Viewers more less

Shell sh bash source env export unset which type history time umask

Identity whoami id groups login logout passwd su sudo getent

Accounts useradd userdel usermod groupadd groupdel

Processes and sessions ps top kill pgrep pkill killall jobs fg bg wait nice nohup watch tty who w last

System hostname uname date uptime vmstat sleep crontab service telinit runlevel man apropos sync shutdown reboot

4.3 Startup

/etc/profile
/etc/bash.bashrc
~/.bashrc

Files are created non-destructively and loaded in that order only after authentication succeeds.

4.4 Example

for name in alpha beta alpha; do
  echo "$name"
done | sort | uniq

4.5 Boot and first login

  1. Reset the display. Each OS boot clears the terminal cells, colors, and cursor before printing one boot banner. This does not format the guest disk.
  2. Restore the system. Files under /etc, /home, and /usr, including the account database, remain persisted; volatile /tmp is rebuilt.
  3. Initialize credentials. On a new CS-Linux installation, the boot banner and New password: prompt each appear once for cs. No simulated first-boot notice or startup transcript is printed. Enter 8–64 UTF-8 characters, then confirm at Retype new password:.
  4. Authenticate later boots. Existing installations show the readable /etc/issue, stop at <computer-id> login:, accept an unlocked username, and then ask for Password:. Three failures add a two-second guest delay.

The password is not reversibly encrypted. CS-Linux stores a salted, bounded 512-round one-way SHA-256 payload in root-readable /etc/shadow; plaintext is never stored. Secret Web input is masked and excluded from history and Tab completion. User startup files run only after authentication succeeds.

4.6 Users and superuser

Identity or commandContract
csInitial administrator and protected boot-service identity, UID/GID 1000, home /home/cs, member of sudo.
rootThe only UID 0 superuser. Its password starts locked and must be deliberately assigned before password login or su can select it.
passwdChanges a permitted account's password without echoing or retaining plaintext.
sudoAvailable only to sudo members; authenticates the caller and grants scoped effective privilege for the requested work.
suAuthenticates the target account and enters that account context until the nested session exits.
useradd, userdel, usermodSuperuser-only bounded user management backed by the account files; UID 1000 cannot be deleted, and active identities cannot be renamed or have their home moved.
groupadd, groupdelSuperuser-only bounded group management with referential checks.
sudo useradd alice
sudo passwd alice
sudo usermod -aG sudo alice
getent passwd alice
sudo -i
exit
su - alice
sudo userdel -r alice

useradd creates a mode-0700 home by default; use -M to skip it. userdel -r removes the home after the bounded account transaction. sudo -i enters a nested login context and exit restores the caller. A successful caller-password check is cached for five guest minutes; sudo -k clears it, while sudo -n command succeeds only when no prompt is needed. Scripts and pipelines cannot own login/logout or open a password prompt. MCP accepts only that non-interactive sudo -n form and never consumes a secret prompt. The final terminal disconnect cancels any secret prompt, clears the timestamp and nested identity state, cancels foreground, compiler, and queued MCP work that captured the session credentials, and returns to login:. That boundary behaves like a real getty on both the disconnect path and a guest exit/logout: the tty is cleared before /etc/issue and the login prompt, so the previous session's commands and output stay unreadable from the built-in CRT and from the next Web session, and the released terminal accepts that next login without a Computer power cycle. A login-disabled development session and CS-DOS have no login boundary to return to, so their screens are preserved. Runtime finalization applies even when user Python ignores terminal_closed, so reconnecting cannot inherit an unattended root shell or stale elevated process.

/etc/passwd, /etc/group, and /etc/shadow are the authoritative account database. Direct writes, links, moves, metadata changes, and deletion are rejected even for root; use the account commands so all three validated records commit together. A failed mutation leaves an explicit nonzero result and never a knowingly partial account. Leaving an elevated or switched session restores the caller, including after failure or cancellation.

4.7 Prompt, MOTD, and persistent history

An authenticated prompt uses login@computer-id:path$; effective UID 0 uses #. A later login reads the real /etc/motd, then shows the previous tty and stored wall-clock timestamp. Legacy records without wall time omit that one-time line instead of fabricating a date from guest ticks; who and last retain those records with a tick N fallback. The user's mode-0600 .bash_history retains at most 100 entries, 512 UTF-8 bytes per line, and 32 KiB total across logout, disconnect, and reboot. Password conversations never enter history.

cs@c-xxxxxx:~$ tty
/dev/tty1
cs@c-xxxxxx:~$ who
cs@c-xxxxxx:~$ last

4.8 Processes, signals, and jobs

PID 1 is /sbin/cs-init; cs-login owns a waiting getty, and the authenticated shell and admitted Python/CS486 work become explicit child processes. Every admitted compiler and CS process receives one physical memory reservation before it starts and binds that reservation to its PID. ps -f shows PID, PPID, UID, state, modeled cycles, start tick, and command. top is one bounded snapshot, not a refresh loop; its VIRT and RES columns are the same per-process virtual and resident values reported as VmSize and VmRSS in /proc/<pid>/status. kill supports HUP, INT, TERM, KILL, STOP, and CONT with guest ownership checks and protects PID 1.

sleep 30 &
jobs
ps -f
kill -STOP 4
bg %1
wait %1

Only one interactive sleep, python/micropython, or run command may end in &. Redirects, pipelines, scripts, aliases, functions, TUI or secret-prompt work, lifecycle commands, MCP submissions, and unsupported commands fail before side effects. Completed jobs remain zombies only until wait or foreground consumption reaps them.

4.9 SysV init: inittab, runlevels, and rc.d

/sbin/cs-init (PID 1) reads /etc/inittab at boot: its initdefault entry selects the target runlevel, and the matching respawn entry owns the tty1 getty behind cs-login. The S-prefixed symlinks in that runlevel's /etc/rcN.d directory (N is 0-6; S aliases 1) start real rc.d services — today syslog and cron — before the login prompt appears, and each shows a genuine Starting NAME... [ OK ] or [FAIL] boot line. Runlevels 2-5 are identical multi-user aliases; telinit 0 and telinit 6 reuse the ordinary shutdown/reboot lifecycle, and telinit 1 (or S) stops rc.d services for single-user mode.

runlevel
sudo telinit 1
sudo telinit 3
sudo /etc/init.d/cron restart
service cron status

runlevel prints PREVIOUS CURRENT (N when no change has occurred yet). telinit {0-6|S} (superuser only; init is its alias) switches runlevels and starts/stops the rc.d services listed for the target level. Service mutation itself flows only through /etc/init.d/NAME start|stop|restart, a real interpretable script for each service; deleting a script or removing its execute bit makes that one service's direct invocation fail explicitly (127/126) without disturbing any other service. service --status-all and service NAME status remain read-only. /etc/crontab is the sandboxed system crontab (minute hour day-of-month month day-of-week user command, standard */range/list/step syntax); the cron service re-reads it only when it starts or restarts.

4.10 Proc, devices, and journals

man TOPIC and apropos WORD use the installed versioned guest index, never host man pages or the Internet.

One boot-scoped memory manager owns resident kernel, services, reclaimable buffers, and every guest process grant. free, /proc/meminfo, process status, and top render the same immutable bounded snapshot. MemAvailable equals free RAM plus buffers that admission can reclaim; a release refills those buffers toward their boot target. Requests above that value fail explicitly and do not leave a partial allocation.

cat /proc/devices
cat /proc/services
cat /proc/self/status
cat /proc/4/cmdline
dmesg
sudo cat /var/log/messages
sudo cat /var/log/auth.log

/proc/<pid>/cmdline, stat, and status, plus /proc/self/*, loadavg, and mount/device/service views all come from one per-Computer OS state. The journal defaults to 256 records, 32 KiB total, and 1 KiB per record. It is a rotating log, not a fixed table: reaching a limit drops the oldest records instead of failing the append, so a full journal never blocks a login, a shutdown, or a boot. Every view that renders it — dmesg, /var/log/messages, and /var/log/auth.log — then begins with one -- N earlier record(s) dropped by journal rotation -- line, so the loss is stated rather than silent. Retained records keep their original order and the count survives cold restore; restoring a snapshot whose journal is larger than the current limits truncates the oldest records the same way. The device registry includes tty/console/null/zero, the fixed disk, and the removable state-backed floppy; none are host device files.

4.11 Sync, graceful stop, and safe recovery

sync crosses the real Computer persistence boundary. Shutdown and reboot stop new admission, signal owned work, drain already-admitted block I/O, save data, unmount, stop services/devices, then record final sync requested and that the intent is prepared for final persistence before saving the final cold projection. Only then may the machine power off or reboot. The two neutral terminal records survive cold restore exactly once; no unsaved success line is added after the callback. If marker creation or the callback fails, only that attempt's provisional markers are removed before the fault is published. A later automatic dirty save can retain the fault but cannot turn the failed final boundary into apparent success. Each phase has a 200-tick deadline, and a durability or drain failure faults visibly instead of claiming a clean stop.

A boot that fails, and a shutdown that fails, both leave the reason on screen. A failed power-on or safe boot replaces the screen with a CSBIOS halt screen: the POST rows the machine actually reached, a Boot Error row naming the failing phase, the reason wrapped into at most two rows, and a final row naming the recovery that machine really has. A failed shutdown instead appends Halt failed during <phase>., the reason, and the same halt line under the guest's own shutdown output, so nothing already on screen is destroyed. A halted machine accepts no input, so it shows no cursor. The block face stays dark in both cases because a fault releases VRAM; open the Computer, or attach the Web Terminal, to read the screen.

The runtime has a one-shot safe-boot boundary. It is available only while the Computer is crashed. In Minecraft, open the crashed Computer normally to see the recovery instruction, then sneak while opening it to safe boot. On an attached Web Terminal, the crashed-state power control changes to safe boot. Safe boot is unavailable from the guest shell and MCP command path.

What safe boot changes depends on the machine. On a Desktop or Advanced Desktop running CS-Linux it preserves but bypasses a broken /startup.py and records that choice in the boot journal; the exact startup file is never reset, renamed, or edited. A Portable CS386SX has no user MicroPython, so it has no /startup.py to bypass: there, safe boot only retries without bootable floppy media, and the halt screen, the in-game recovery line, and the boot journal all say so instead of claiming a bypass.

4.12 CS Make 1.0 and static libraries

Current CS-Linux rootfs v19 installs /usr/bin/make, guest ar/ranlib, legacy word archives under /usr/lib, and model-matched libc.csa/libcurses.csa/libm.csa under /usr/lib/cs-word32-v1 and /usr/lib/cs-byte8-v1. Current CS486AR v2 is a versioned bounded container with explicit data-model identity; v1 remains readable as the legacy word profile. It is not Unix ar, ELF, OMF, or a native library. cc and ld preserve ordered -L/-l operands and extract only demanded same-model members. CS-DOS does not install MAKE or these CS-Linux archive commands; its separate bounded project workflow remains CS PROGRAM LIST and PWB. Run man make, man ar, or man ranlib for exact limits.

CC = cc
CFLAGS = -std=c11 -O1 -Wall -Werror -Iinclude
OBJECTS = main.o parser.o render.o
DEPS = main.d parser.d render.d

app: main.o libport.csa
	ld main.o -L. -lport -o $@
libport.csa: parser.o render.o
	ar rcs $@ $^
	ranlib $@
-include $(DEPS)
%.o: %.c
	$(CC) $(CFLAGS) -MMD -MF $*.d -c $< -o $@

CS Make accepts an explicit Makefile or makefile, a project directory, dry-run, force-rebuild, and silent options, command-line variable overrides, explicit and indexed pattern rules, required or optional includes, ifeq/ifneq/ifdef/ifndef with else/endif, the four assignment forms, .PHONY, doubled dollar signs, and $@/$</$^/$*. Guest mtimes and bounded CSMAKE2 records skip a target only while SHA-256 input, output, recipe, dependency, and toolchain identities match. A generated .d file enters the first successful target commit, so an identical second build is a no-op. Missing, evicted, legacy, or foreign-toolchain records rebuild safely; malformed state fails explicitly.

Planning is bounded to an aggregate 32,768 source characters, 256 lines, 64 included files at depth 8, 128 rules/patterns, 256 graph nodes, 512 edges, 64 prerequisites per rule, graph depth 32, 256 recipe lines, and 16 MiB of fingerprint input. Pattern lookup is indexed by target suffix and reports examined candidates and traversed edges. Parsing, planning, and fingerprint reads begin after one make PID and one 128 KiB guest RAM lease are admitted. At most one isolated recipe advances per scheduler admission; an inadmissible next build retains its fair queue position. The allowlist includes as, cc, c++, ar, ranlib, ld, inspection tools, and bounded filesystem/output utilities. Pipelines, redirects, chains, background or TUI/session/lifecycle work, recursive make, arbitrary configure scripts, parallel jobs, and every host command fail explicitly. Use a checked-in or pre-generated config.h; Autoconf, CMake, native configure processes, and host compilers are not available.

4.13 CS System Git 1.0

CS-Linux rootfs v12 installs /usr/bin/git; CS-DOS does not. This is an independent bounded Git-like VCS, not native Git. It supports local init, status, add, rm, commit, log, show, diff, branch, switch, checkout, merge, tag, remote, and local config. Repositories use .git, but the required computerSystemVcs extension, object encoding, and index intentionally prevent native-Git interoperability.

mkdir project && cd project
git init
printf 'build/
*.tmp
' > .gitignore
git add . && git commit -m base
git switch -c feature
git log --oneline

SHA-256 blob, tree, and commit objects retain binary contents, executable mode, and symbolic-link targets. They do not retain uid/gid, mtime, hard-link identity, devices, or empty directories. .gitignore, .git/info/exclude, anchored and negated rules, **, character classes, and git add -f are bounded. Hooks, helpers, filters, submodules, LFS, signing, shallow history, alternate stores, config includes, and host execution are unavailable. Ownership, every .git symlink, object hash, checksum, path, and file/directory collision are validated before use; a conflicting merge reports failure without changing the index, refs, or worktree.

A repository tracks 256 paths, scans 512 entries, stores 2,048 objects, reads 256 history commits, and caps one object at 384 KiB. Each command owns a 1 MiB transient RAM lease; bounded payload, hash, object, and transaction buffers are processed sequentially, and bytes route through credentialed guest block I/O. git remote stores credential-free cs+tcp://, ssh://, or https:// metadata. clone, fetch, pull, and push fail explicitly until authenticated guest TCP/IP exists; no host Git or host socket is used. The future port separates guest peer verification, scoped challenge-response credentials, capability negotiation, per-tick and total transfer ceilings, chunked object readers, quarantine verification/promotion, and compare-and-swap ref updates. Every terminal path releases credentials, readers, quarantine, and transport state exactly once; uncertain acknowledgement ends in unknown for ref reconciliation before retry.

4.14 Bounded text processing and archives

sed -n '/error/p' system.log
awk -F : '$3 == 0 { print $1 }' /etc/passwd
perl -lane 'print "$F[0]:$F[2]"' /etc/passwd
tar -cf project.tar project
tar -tf project.tar
gzip -k project.tar
zip project.zip project
unzip -l project.zip

sed supports -n, -e, numeric, last-line, and pattern addresses, plus bounded p, d, and s commands. awk supports -F, BEGIN/END, pattern and comparison rules, print/printf, $0-$64, NR, and NF. Both use the guest's own bounded pattern parser—literals, dot, star, anchors, and character classes—not host JavaScript regular expressions. Programs are limited to 4,096 bytes and 32 rules; input is limited to 256,000 bytes and 4,096 records.

CS-Linux rootfs v20 installs /usr/bin/perl; CS-DOS does not. It is a bounded interpreter for a Perl 5.40 surface, not a port of upstream perl and not a CPAN or POSIX conformance claim. It supports use strict, use warnings, use v5.40, say, scalars, arrays, hashes, my scoping, subroutines and recursion, statement modifiers, foreach aliasing, sort/grep/map blocks, sprintf/printf, split, join, tr///, m//, s///, eval BLOCK with $@, die/warn/exit, here-documents including <<~, loop labels with next/last, s///e and s///r, tr///cdrs, real undef with //, and the -e -n -p -l -a -F -c -w -v switches. Three-argument open reads and writes guest files only, through the same credentialed filesystem as every other command.

Matching uses a guest-owned backtracking engine with alternation, groups and captures, greedy and non-greedy * + ? {n,m}, classes, escapes, anchors, \b, and the g/i/m/s flags under a fixed step budget—never a host regular expression. Program text is limited to 64 KiB and 4,096 statements; a run is limited to 1,000,000 steps, 1 MiB of input, 1 MiB of output, 8 open handles, and a call depth of 64, and exceeding one fails explicitly with exit status 2. Hash iteration is insertion-ordered and there is no wall clock, so a program's output is a deterministic function of its input. Modules outside the pragma allowlist, references and nested data structures, bless and ->, eval STRING, local, prototypes, goto, tie, format, backticks, fork, exec, and system are rejected at compile time instead of approximated.

The filesystem stores and accounts arbitrary bytes, so archive members survive snapshot and copy without UTF-8 conversion. tar creates, lists, and atomically extracts bounded ustar archives. gzip/gunzip use deterministic RFC 1952 stored-DEFLATE streams; other DEFLATE block methods fail explicitly. zip/unzip support standard UTF-8, unencrypted method-0 archives; encryption, ZIP64, and compressed methods fail explicitly. One archive is at most 1 MiB, with 512 entries, 32 operands, path depth 32, and 4 MiB expanded data. Extraction rejects absolute paths, traversal, duplicates, symlink pivots, conflicts, and malformed checksums before committing any entry.

4.15 Cron, priority, detachment, and bounded watching

crontab -l
sudo crontab -e
sudo /etc/init.d/cron restart
nice -n 10 run worker
nohup sleep 300 &
watch -n 2 -c 10 -- service cron status

crontab deliberately has no per-user spool: -l reads the single /etc/crontab, and root -e opens that file in the existing vi. The cron service parses at most 64 seven-field system entries when it starts or restarts, resolves the named account through the authoritative account database, uses the deterministic guest calendar, bounds its pending queue to 64, and admits at most one due command per tick.

nice accepts values -20 through 19; only root may request a negative value. Its NI value appears in ps/top and scales the process's scheduler slice without bypassing the global budget. nohup is admitted only as a wrapper around the shell's supported bounded background jobs ending in &; it reparents them to PID 1 and protects them from terminal SIGHUP, while shutdown signals still finalize them. watch requires a finite -c count (default 300, maximum 3,600), runs at most once per guest interval from 1 to 3,600 seconds, and uses the foreground cancellation/finalization path. It is not an unbounded screen refresh loop.

4.16 NetHack for CS-Linux

Rootfs v14 ships the reduced guest-authored /usr/games/nethack, built from the same nine CS C 2.0 modules, nethack.h, and explicit-rule Makefile stored under /usr/src/nethack. It is not an unmodified upstream NetHack port and does not use a native TypeScript game session, Python script, host compiler, or host filesystem.

nethack --help
man 6 nethack
mkdir ~/nethack
cp /usr/src/nethack/* ~/nethack/
cd ~/nethack && make
sudo make install PREFIX=/usr/local
nethack

The game has ten bounded dungeon depths, the Amulet goal, depth-gated monsters and items, hunger and experience, deterministic random state, and a 78 by 21 dungeon view. Move with hjklyubn; items remain on the floor until , picks them up. The full 80 by 25 inventory keeps stable a–p slots: i displays it, e eats, q quaffs, r reads, w wields (w- unwields), W wears armor, T takes armor off, and d drops a stack. In a selector, ? or * redisplays the inventory and Esc cancels. Display, cancel, invalid choices, and rejected capacity changes spend no turn; each successful item mutation spends exactly one. Use </> for stairs, press ? for the in-game key help screen, press uppercase S to save and exit, and enter the complete #quit command to abandon unsaved progress. The bottom row is a persistent status line showing Dlvl, HP, Lv, XP, turn count, hunger stage, and Amulet possession, and explored walls render as - and |.

Only explicit S saves. The path comes from the immutable hosted-process HOME snapshot and is ~/.nethack.sav, mode 0600. Save version 3 retains stable inventory slots, stack quantities, and equipped weapon and armor. Exact version 2 records remain loadable and migrate on the next explicit save; malformed records are rejected before live game state changes. A sibling temporary file is closed and atomically renamed over the canonical record; missing or invalid HOME, malformed records, disk capacity, DAC, interruption, disconnect, and terminal close never become an implicit save. Each account resolves its own HOME with its launch credentials. User PATH checks /usr/local/games before /usr/games, so an administrator-installed guest build shadows the stock binary. Use sha256sum to compare the clean guest build with the shipped artifact.

4.17 Standard streams, pipes, redirects, and practical filters

StreamDescriptorNormal terminal destination
stdin0command input
stdout1normal results
stderr2errors and warnings
# Search normal output and diagnostics together
command 2>&1 | rg 'ERROR|WARN'

# Keep stdout on screen and save it in the guest filesystem
./run.sh 2>&1 | tee run.log

# Keep results and errors separate
./run.sh > success.log 2> error.log

# Feed literal data to stdin
cat <<EOF
one
two
EOF

| sends stdout to the next command's stdin; stderr stays at its current destination. 2>&1 | and |& send both streams through the pipeline. > overwrites, >> appends, 2> redirects only stderr, and &> is ordered shorthand for stdout followed by stderr-to-stdout. Use 2> /dev/null to discard diagnostics, or > /dev/null 2>&1 to discard both streams. A literal shell here-document is capped at eight documents and 64 KiB per command; unsupported substitutions and syntax fail before execution.

grep supports bounded alternatives and -F -i -n -v. rg adds -l, but reads only stdin or explicitly named guest files; it never performs recursive discovery. jq [-r] supports the documented bounded JSON lookup, iteration, collection, and simple selection subset. cut -c 1,3-5 extracts characters, cut -d : -f 1,3 extracts fields, and tr -d ' ' removes a character set. find, which, type, xargs, and tee all run inside the guest filesystem and shell; none dispatches a host shell or utility.

4.18 Byte pipelines, descriptors, and pagers

dmesg | less
yes | head -n 10
probe >all 2>&1
probe 2>&1 >out
probe 2>err |& more

Every foreground stage is a scheduler-owned process in one process group. Adjacent stages exchange Uint8Array data through a fixed 4 KiB ring: empty readers and full writers yield, every writer reference must close before EOF, and writing after the final reader closes produces SIGPIPE status 141. The pipeline status is the last stage status; pipefail and background pipelines are unavailable. Redirect setup is validated and committed before a stage starts, > truncates at shell-open time, repeated operations are bounded to 16 per stage, and later runtime disk failure may leave only the bytes already committed.

less and more are supported only as the final terminal-owned stage. They accept one file, </pipe stdin, or -; navigation keys remain on the controlling-terminal channel and never become document bytes. Live input reports an unfinished length honestly and retains at most 64 KiB. q or Escape closes the reader, lets an active producer observe SIGPIPE, and resumes a saved &&/||/; continuation exactly once. Parent-mutating commands and other terminal-exclusive programs are single-stage-only.

Chapter 05 · Desktop language runtime

Computer System Python on CS486

On the desktop CS486DX and CS486DX2 profiles, Computer System Python compiles to the same resumable guest process as CS C/C++ 1.0 and CS ASM 1.0; there is no separate Python VM. Computer System Python 1.0 is targeting Python 3.14 syntax and core semantics under the Python 3.14 CS Profile, while the current implementation remains a bounded partial subset. Source in /startup.py starts when the Computer powers on. The portable CS386SX DOS profile does not expose user Python and returns status 127.

5.1 Edit and boot

vi /startup.py
        reboot

Normal completion powers the program down. Infinite work remains preemptible by the common scheduler.

CS-Linux can also compile and run a source file as a foreground process from the normal Web Terminal:

python /tmp/program.py
python --stats /tmp/program.py
micropython /tmp/program.py

python is the canonical command; micropython remains a compatibility alias for existing worlds and scripts. The shell waits while the process runs, routes guest events to it, and restores the prompt after completion, failure, or Ctrl+C. Add --stats to print machine instructions, modeled CPU cycles, virtual time, host wall elapsed time, guest cycles per host second, and the modeled-real-time ratio. Host delay is observational and never changes guest cycle counts. Foreground Python output can use a CS-Linux pipeline or redirect through the same process-scoped endpoint path; scripts and unsupported terminal-control chains remain rejected. Desktop boot creates an empty mode-0644 /startup.py owned by the current UID 1000 service account while keeping / root-owned. Empty source selects the built-in shell boot program; after cs saves non-empty source with vi, later boots execute it with UID 1000's current primary and supplementary groups. The native shell module is internal to that built-in empty-startup program and is unavailable to user-authored /startup.py, foreground Python, and MCP Python. The MCP form remains a bounded non-TUI debug probe.

5.2 Core language

The current subset supports variables, strings, booleans, lists, tuples, dictionaries, bounded mutable sets, functions, imports, conditionals, loops, exceptions, assertions, formatting, Unicode XID/NFKC names, lexical closures, all five parameter kinds, bounded */** calls, short-circuit comparison chains, condition-first single-branch conditional expressions, expression-only lambda functions on the shared closure/call path, identifier-only assignment expressions on the same lexical binding path, single-RHS left-to-right chained assignment, single-evaluation augmented assignment, starred list/tuple/set displays, dictionary mapping unpacking, eager list/set/dictionary comprehensions, nested destructuring with one starred remainder list per level, built-in string/list/tuple slicing, bounded list slice assignment, and bounded arbitrary-precision integers with base literals, floor/modulo, powers, shifts, and bitwise operators through shared call/jump control flow and allowlisted managed-runtime syscalls. Assignment expressions evaluate one RHS and return the stored value; restricted subexpressions require parentheses. Comprehensions evaluate their leftmost iterable in the enclosing scope, then run synchronous or asynchronous for/if clauses left to right in an implicit scope whose iteration targets do not leak; a contained assignment expression binds in the containing non-comprehension scope. Sets provide explicit/starred displays, bounded set(), deterministic iteration, membership, len, equality, and bounded primitive/tuple hashing; mutable elements raise TypeError. Assertions evaluate one condition, skip their message on success, and raise AssertionError on failure; the profile has no -O mode and __debug__ is always true. Slices accept omitted, clipped, and positive/negative-step integer components; strings use Unicode code points, while list stores preflight replacement arity and final capacity before mutation. Expanded collections default to 4,096 items. Integer magnitude defaults to 262,144 bits; float semantics remain partial IEEE 754 binary64. Class-scope comprehension behavior and custom data-model protocols remain outside this implemented phase.

The final profile targets the Python 3.14 grammar and observable core-language semantics. This is not yet a Python 3.14 compatibility claim. pip, ensurepip, venv, PyPI, and wheel installation are deliberately unavailable; source packages remain in scope and guest native extensions use versioned CS486OBJ, not the CPython extension ABI.

Persistent terminal REPL

python
>>> value = 40
>>> value + 2
42

Bare python (or the micropython alias) opens a bounded >>>/... session. Every cell is compiled into the same validated CS486 process, so globals, imports, functions, classes, closures, and generators persist with one PID, scheduler entry, and RAM grant. A final expression is displayed once. Syntax and ordinary Python runtime errors return to >>> without replacing the process.

At an input prompt, Ctrl+D exits and Ctrl+C discards only the pending cell. During execution, Ctrl+C terminates that REPL explicitly. Interactive source is excluded from shell history and capped at 512,000 UTF-8 bytes. Redirects, pipelines, background use, shell scripts, MCP debug use, and --stats are unavailable for the interactive form; file execution retains those existing capabilities. CS386SX continues to return status 127.

Iterators and generator functions

iter() creates independent cursors for strings, lists, tuples, dictionaries, and sets; passing an existing iterator returns that same object at its current position. next() advances once, raises catchable StopIteration at stable exhaustion, or returns its optional default. for, unpacking, starred displays, iterable call expansion, slice replacement, and set() all consume that same built-in cursor position instead of restarting an iterator. Built-in advancement is O(1), and whole consumption is bounded by the source and managed-memory limits.

User-defined iteration resolves inherited __iter__ and __next__ through the class path and ignores instance-only special methods. Both run through bounded managed Python calls. __iter__ may return a built-in cursor, generator, self-iterator, or separate class-backed iterator. iter, next, for, unpacking, starred displays, iterable call expansion, slice replacement, set(), synchronous comprehensions, generator expressions, and yield from share this path. Materializing consumers resume every user-iterator or generator step through ordinary bounded CS486 calls. They retain the current iterator, accumulated values, pending operands, arguments, or targets, and the original physical return slot in one reachable continuation. A callee is not invoked, unpack targets are not stored, slices are not mutated, and new results are not published until iteration and all arity/capacity checks succeed. StopIteration ends traversal, an optional next default is returned exactly, and other faults propagate unchanged.

When no class-level __iter__ exists, inherited __getitem__ supplies the legacy sequence protocol. Each independent cursor requests integer indexes from zero and advances only after a successful item; IndexError ends it while other faults propagate. Any class-level __iter__, including explicit None, takes precedence and prevents fallback.

iter(callable, sentinel) evaluates both operands once, then invokes the callable with no arguments through the ordinary bounded CS486 path. Managed functions and lambdas, bound methods, classes, native functions including waits, and filesystem-loaded CS486 extension exports are supported. A result equal under the current CS Profile == semantics is consumed as the sentinel and makes exhaustion stable; a callable-raised StopIteration does the same. Another fault propagates without exhausting the cursor. The callable, sentinel, and exhaustion state stay reachable in one accounted internal iterator shared by every lazy and materializing consumer.

A directly containing def or lambda with yield creates a lazy generator. Calling it binds arguments without running the body. next(), for, and send(None) resume its compiled CS486 target and make the suspended yield expression evaluate to None; send(value) supplies that exact managed value. Sending non-None before the first yield raises TypeError without consuming the generator. Yield is valid throughout try, except, and finally; active handlers, handled faults, pending finalizers, locals, closure cells, and the managed value stack survive together.

throw(exception) raises at the suspended yield and returns the next yielded value when caught. The bounded legacy type/value form accepts only a None traceback. close() injects GeneratorExit, runs pending finally suites, and returns a handled generator return value. Yielding during close raises RuntimeError and closes the generator; another exception propagates. GeneratorExit derives from BaseException, so except Exception does not catch it. Stored bound send, throw, and close methods remain in the same reachable heap. Return or an escaping fault owns closure; no second Python VM or scheduler is introduced.

yield from expression evaluates one iterable once and passes its values to the caller lazily. A subgenerator return becomes the expression result; built-in iterator exhaustion supplies None, while user-iterator exhaustion supplies the exact StopIteration.value. send, throw, and close forward to a generator delegate through nested calls on the same CS486 process. A built-in or user iterator has no delegated methods in this phase, so a non-None send reports the missing send method and a thrown exception is raised at the yield-from point. Delegates and their suspended children remain in the same reachable heap.

A synchronous generator expression such as (value * 2 for value in values if value) uses the same implicit comprehension scope and generator protocol. Its leftmost iterable expression and iter() run once when the expression is constructed, so a non-iterable fails immediately. Elements, filters, and later iterables remain lazy. Iteration targets do not leak, a contained := binds in the containing non-comprehension scope, and the sole argument to a call may omit one extra pair of parentheses. Independent expressions reuse next, send, throw, close, call-depth admission, and reachable heap accounting.

Custom __call__, custom __eq__, automatic garbage-collection close, and other generator consumers remain later phases.

A sequence-fallback cursor keeps its source instance and current index reachable. An escaping StopIteration also makes exhaustion sticky; any other fault leaves the index unchanged. Every __getitem__ request uses the ordinary bounded managed-CS486 call path.

Exception groups and except-star

try:
    raise ExceptionGroup("batch", (ValueError("left"), TypeError("right")))
except* ValueError as errors:
    print(errors.message, errors.exceptions)
except* TypeError:
    pass

BaseExceptionGroup and ExceptionGroup retain a non-empty nested exception tree. Read-only message and exceptions fields expose its shape; derive(), subgroup(), and split() preserve matching branches and their cause, context, notes, and profile traceback metadata. A BaseExceptionGroup whose leaves all derive from Exception automatically becomes an ExceptionGroup.

An except* clause recursively receives only its matching subgroup. Ordinary except and except* cannot appear in the same try, a type is required, and return, break, and continue are forbidden in the handler suite. A plain exception is wrapped only while matching; an unmatched one propagates without that temporary group. Newly raised exceptions merge deterministically with unmatched leaves, while a bare raise retains the original subgroup identity and tree.

subgroup() and split() accept an exception type or a managed Python function, lambda, or managed bound method. Managed predicates run node-by-node through ordinary bounded CS486 calls, and predicate faults use the normal exception path. Native, class, extension, and scheduler-yielding callable predicates are not available in this profile phase.

Exception trees default to at most 64 levels and 4,096 admitted nodes. The tree, active handler, unmatched leaves, new faults, and callable state remain in the reachable managed heap across generator or coroutine suspension and low instruction slices. Runtime traceback objects remain outside this phase; pip and venv remain unavailable.

Synchronous context managers

with Lock("outer") as first, Lock("inner") as second:
    print(first, second)

A synchronous with statement accepts one or more items, optional assignment targets, and a parenthesized item list. Managers enter from left to right and successfully entered managers exit exactly once from right to left. The runtime resolves class-backed __enter__ and __exit__, retains the bound exit before calling enter, and treats an as assignment failure as a protected suite fault.

Normal completion, return, break, and continue call __exit__(None, None, None) and ignore its result. A fault supplies its stable type, exact value, and the CS Profile traceback value None. A truthy exit result suppresses the fault; a false result reraises that same value, and a new exit fault routes through already-entered outer managers. Bound exits remain reachable across generator suspension and close(). The runtime preflights the implicit receiver plus all three explicit exit arguments before entering, so a capacity rejection cannot strand an entered manager.

contextlib, generator-based context-manager decorators, descriptor or metaclass customization of special-method lookup, and runtime traceback objects remain later work.

Coroutines and async protocols

async def read_all(source, manager):
    async with manager as opened:
        total = 0
        async for value in opened:
            total = total + await source.transform(value)
        return total

Calling async def binds its arguments and returns an unstarted coroutine without running the body. await resumes native coroutines through ordinary CS486 call and return targets; a class-backed __await__ iterator is accepted when it completes without yielding work to an external scheduler. Results and faults propagate exactly through the awaiting coroutine, and completion or close() makes later reuse fail explicitly.

The low-level driver surface is coroutine.send(None), coroutine.throw(exception), and coroutine.close(). There is no hidden asyncio event loop or second Python scheduler. async for resolves class-backed __aiter__ and __anext__, awaits every step, consumes StopAsyncIteration, and preserves break/continue. async with awaits class-backed __aenter__ and __aexit__; multiple managers enter left-to-right and exit exactly once right-to-left, including return and fault paths, and a truthy exit result suppresses the exact fault.

An async def containing yield returns an unstarted asynchronous generator. __anext__(), asend(), athrow(), and aclose() each return a single-use awaitable operation on the same CS486 process. Normal completion raises StopAsyncIteration, while aclose() injects GeneratorExit, runs pending finalizers exactly once, and rejects a yielded value. Eager asynchronous list, set, and dictionary comprehensions run inside a coroutine; asynchronous generator expressions remain lazy and can mix synchronous and asynchronous clauses.

Created coroutine and asynchronous-generator frames, locals, closure cells, handlers, pending control, protocol owners, and operation arguments remain in the same reachable managed heap and share the 64-call-depth, 4,096-item, and resumable instruction-slice limits. Custom awaitables that yield an external scheduler token and asyncio loops, tasks, futures, or host-I/O integration remain unavailable in this phase.

Classes and instances

Bounded class definitions evaluate zero or more bases exactly once from left to right in the enclosing scope. The suite runs in an isolated class namespace, then bounded C3 MRO construction and every authored __set_name__ notification complete before the class name is published. Calling a class resolves inherited __new__ through its C3 MRO. A plain def __new__ is an implicit static method and receives the requested class plus original arguments exactly once. Strict object.__new__(cls) allocates a heap-accounted bare instance. If custom __new__ returns an instance of the requested class or subclass, the returned instance type resolves __init__ with the original arguments and must return None; any other value is returned unchanged without initialization. object, isinstance, and issubclass are available. Classes expose __name__, __base__, and stable read-only __bases__/__mro__ tuples; instances expose __class__. Class and instance namespaces share the 4,096-entry collection ceiling and managed heap, and each C3 MRO admits 64 classes including the class itself and object.

Cooperative super and class cells

Methods and lambdas that reference __class__ or builtin super capture one hidden class cell distinct from authored class-body, outer, and parameter bindings. Successful completion initializes it to the exact class after C3 and heap admission and before __set_name__; a rejected set-name completion clears it. super(), super(type), and super(type, instance-or-subclass) continue after the named class in the receiver C3 MRO and reuse ordinary managed function, property, custom descriptor, and classmethod binding. Proxies expose stable read-only __thisclass__, __self__, and __self_class__; cooperative initialization may terminate at object.__init__.

Function and class decorator expressions run in the containing scope from top to bottom before defaults or class construction, then apply from bottom to top through the same bounded call path. The definition name is bound only after every decorator succeeds, with at most 4,096 decorators per definition.

Descriptors and method variants

Instance reads follow Python descriptor precedence: data descriptor, instance attribute, non-data descriptor, then inherited class value. Class-owned __get__ receives the descriptor, the instance or None, and the most-derived accessed class; inherited __set__ owns a store before the instance map changes.

class Reading:
    def __set_name__(self, owner, name):
        self.name = name
    def __get__(self, instance, owner):
        return owner.__name__ if instance is None else instance._value
    def __set__(self, instance, value):
        instance._value = value

class Sensor:
    reading = Reading()

    @property
    def doubled(self):
        return self.reading * 2

    @staticmethod
    def clamp(value):
        return value if value > 0 else 0

    @classmethod
    def model(cls):
        return cls.__name__

Ordinary managed functions remain non-data descriptors. A method found through an instance class lookup binds its receiver and exposes read-only __self__ and __func__; a function stored directly on an instance remains unbound. property supports getter, setter, and deleter replacement decorators, read-only fget/fset/fdel reflection, class access returning the property itself, and explicit AttributeError when an accessor is absent. staticmethod returns its wrapped value unchanged. classmethod binds the most-derived accessed class from either class or instance access. A class-owned __delete__ or property deleter owns deletion before the instance map changes.

Attribute hooks and deletion

class Config:
    def __getattr__(self, name):
        return "missing:" + name
    def __setattr__(self, name, value):
        object.__setattr__(self, name, value)

config = Config()
setattr(config, "cache", 41)
del config.cache
print(getattr(config, "cache", 42))

Inherited __getattribute__ runs for each explicit instance read. Only AttributeError, including one raised by a descriptor getter, proceeds to inherited __getattr__. Inherited __setattr__ and __delattr__ own explicit writes and deletions; the three object methods provide bounded base delegation. getattr, setattr, and delattr use the same path. A getattr default is returned only after lookup and __getattr__ both end in AttributeError. Implicit special-method lookup remains class-owned and bypasses instance attribute hooks.

del supports names, attributes, built-in list/dictionary items, list slices including extended slices, and nested list/tuple target lists. Targets delete left to right: a later fault retains earlier deletions and stops the remaining targets.

Descriptor and hook calls, pending stores/deletions/defaults, names, wrappers, owner classes, receivers, and bound methods use the ordinary CS486 call/return, exception, 64-call-depth, 4,096-item namespace ceiling, managed heap, and resumable instruction-slice paths. Metaclasses, custom generic subscription hooks, __slots__, module/metaclass attribute hooks, user-defined __delitem__, arbitrary native/asynchronous descriptor or attribute hooks, object-lifetime __del__, and operator protocols remain later work.

Deferred annotations

def decode(packet: Packet) -> Result:
    return Result(packet)

class Packet:
    payload: Payload

function_types = decode.__annotations__
field_types = Packet.__annotations__

Parameter, return, and simple module/class variable annotations follow the Python 3.14 deferred model: the annotation expressions do not run when the definition or assignment executes. The first successful __annotations__ access evaluates them in authored order and caches one mutable dictionary. Forward names may therefore be defined before access. If evaluation faults, no dictionary is cached and a later access retries. A circular importer that inspects a partially initialized module receives a fresh dictionary containing only annotation statements executed so far.

Annotation scopes may retain enclosing function cells. Class and method annotations may also read the completed immediately enclosing class namespace. A function-local annotation only makes a simple name local; it is never evaluated or stored. Non-simple attribute or subscript annotations preserve target and optional RHS behavior but never evaluate the annotation. Results share the 4,096-entry collection ceiling, 1,024-scope/64-nesting frontend ceilings, managed heap, call depth, resumable CS486 slices, and modeled cycle debt.

Generic functions, classes, and soft-keyword type aliases accept T, *Ts, and **P parameters. The completed object exposes one stable authored-order __type_params__ tuple while the names remain private to its annotation scope. Function defaults and decorators use the containing scope; annotations, class bodies/bases, and alias values may retain the parameter cells. Bounds, tuple constraints, defaults, and alias __value__ evaluate on first access through ordinary managed CS486 calls. Success caches with stable identity after heap admission; faults publish no cache and retry. Missing defaults share a typing.NoDefault-shaped sentinel.

Generic classes and aliases support bounded subscription such as Box[int], Alias[str], list[int], and dict[str, int]. Each process caches a stable type-erased alias with read-only __origin__, __args__, and __parameters__. Open and nested aliases may be subscribed again; ordinary and ParamSpec defaults evaluate through managed CS486 calls, while one TypeVarTuple consumes a bounded variable-width argument segment. An explicit ParamSpec accepts list or tuple form; when it is the sole type parameter, expanded arguments normalize to one tuple-shaped slot. Parameterized class calls construct the original class, but parameterized aliases are rejected in isinstance/issubclass checks. The cache, nested substitution, and reachable heap share the 4,096-item and 64-level ceilings.

The runtime-owned typing core is available without a guest module file or host Python. It provides stable Any, Never, NoReturn, Self, LiteralString, and NoDefault values; bounded Union, Optional, Literal, Annotated, Callable, qualifier, guard, unpack, and concatenate forms; and runtime TypeVar, ParamSpec, and TypeVarTuple constructors. get_origin and get_args expose aliases, Annotated.__metadata__ is read-only, and cast/assert_type preserve the supplied value without enforcing its type. Optional[T] reflects a canonical Union origin with T and a stable NoneType token.

from typing import Annotated, Optional, TypeVar, get_args, get_origin

T = TypeVar("T", default=str)
maybe = Optional[int]
tagged = Annotated[int, "user-id"]
print(get_origin(maybe), get_args(maybe), tagged.__metadata__)

The name typing is reserved before guest-file lookup, so a guest typing.py cannot shadow this intrinsic module.

Static-checker behavior, get_type_hints/ForwardRef evaluation, TypedDict/NamedTuple generation, overload registries, structural Protocol checks, runtime_checkable, annotationlib alternate formats, arbitrary __class_getitem__/metaclass hooks, from __future__ import annotations stringization, and writable/deletable reflection descriptors remain later work. This support does not add pip or venv.

Structural pattern matching

match packet:
    case {"kind": "point", "x": x, "y": y} if x >= 0:
        print(x, y)
    case [head, *middle, tail]:
        print(head, middle, tail)
    case _:
        print("unsupported")

match, case, and _ are soft keywords. The subject runs once, cases run from top to bottom, and a guard runs only after its complete pattern succeeds. Literal/singleton, dotted value, capture/wildcard, OR/AS, list-or-tuple sequence, built-in dictionary mapping with **rest, and C3 multiple-inheritance class patterns are supported. Class positional patterns use inherited __match_args__; keyword patterns use ordinary instance/class lookup.

A failed pattern or failed OR alternative publishes no partial captures. Successful captures are preflighted and published together before the guard; Python-visible bindings remain after a false or faulting guard. Patterns are limited to 4,096 nodes, nesting 64, and 4,096 items per construct. Custom sequence/mapping protocols and descriptor/metaclass customization remain unavailable.

Template strings and string.templatelib

from string.templatelib import Interpolation, Template, convert
precision = 2
template = t"left={3!s:.{precision}f}; debug={ precision = }"

Python 3.14 t/T and raw tr/rt literals evaluate each replacement and nested format field once from left to right, but retain the resulting value instead of formatting it. Authored expression text, debug equals, s/r/a conversion, escaped braces, and nested format text remain available through each interpolation.

The intrinsic string.templatelib module exposes read-only Template fields strings, interpolations, and values, plus read-only Interpolation fields value, expression, conversion, and format_spec. Direct constructors, convert(), iteration that omits empty strings, Template-to-Template concatenation, and the documented four-position Interpolation pattern are available without host Python, pip, or venv.

One parse admits 256 replacements including nested format fields. Runtime strings admit 65,536 code units, Template collections admit 4,096 items, and retained values, metadata, iteration state, and reflected tuples remain in the reachable managed heap under the 64-call-depth and outer CS486 slice limits. Custom __format__, the complete format mini-language, and descriptor/metaclass customization remain later work.

Descriptors and method variants

class Reading:
    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, replacement):
        self._value = replacement

    @classmethod
    def create(cls):
        return cls()

Inherited class-owned descriptors follow Python's instance lookup order: data descriptor, instance attribute, non-data descriptor, then ordinary class value. A managed __get__ receives the descriptor, the accessed instance or None, and the most-derived accessed class. A managed __set__ owns the write and managed __delete__ or a property deleter owns deletion before the instance map changes. Ordinary managed functions remain non-data descriptors; bound methods expose read-only __self__ and __func__.

Class construction calls inherited __set_name__ once for each authored class value in namespace order. Every notification must finish before the class is published, so a fault preserves an earlier binding. Intrinsic property supplies getter/setter/deleter replacement decorators and explicit missing-accessor AttributeError; staticmethod returns its wrapped value unchanged; classmethod binds the most-derived accessed class.

Explicit instance reads, writes, and deletions support inherited __getattribute__, AttributeError-only __getattr__, __setattr__, and __delattr__, plus bounded object delegation and getattr/setattr/delattr. del handles names, attributes, built-in list/dictionary items, list slices, and nested target lists from left to right.

Zero/one/two-argument super uses one hidden __class__ cell, continues through the receiver C3 MRO, exposes read-only proxy reflection, and permits cooperative object.__init__. Descriptor/hook/super receivers, owner classes, pending stores/deletions/defaults, set-name snapshots, wrappers, and bound methods remain in reachable managed heap accounting under the 64-entry MRO and 64-call-depth ceilings, 4,096-item namespace ceiling, and outer CS486 slices. Metaclasses, __slots__, module/metaclass hooks, user-defined __delitem__, arbitrary native/asynchronous descriptor or attribute hooks, and object-lifetime __del__ remain later work.

5.3 Native modules

ModulePurposeRepresentative calls
osIdentity, time, events, timers, lifecycleget_computer_id, clock, sleep, pull_event, queue_event, shutdown, reboot
termFixed-cell terminalwrite, clear, set_cursor_pos, set_text_color
fsSandbox filesystemread_file, write_file, exists, make_dir, get_size, get_free_space
redstoneSix-sided digital / analog I/Oget_input, get_analog_input, set_output
serialSix full-duplex RS-232C portsread, write, status
spiBounded controller transferstransfer
i2cBounded addressed controller transfersscan, transfer

shell is deliberately absent from the public module table. It carries the authenticated terminal adapter and is granted only to the built-in shell program selected by an empty /startup.py; user Python cannot import it.

5.4 Python modules and regular packages

# /home/cs/pkg/__init__.py
answer = 40

# /home/cs/pkg/tools.py
from . import answer
result = answer + 2

# /home/cs/main.py
import pkg.tools
from pkg.tools import result
print(pkg.tools.result, result)

Module lookup checks the importing file's directory, then /lib/python and /usr/lib/computer-system/python. A directory containing __init__.py is a regular package and wins over a same-name .py module. Dotted imports initialize every parent before its child and publish the child on the parent namespace. Without as, import pkg.tools binds pkg; an alias binds the resolved leaf. Absolute and explicit-relative from imports support aliases, parenthesized lists, selected submodules, and module-level wildcard exports through __all__ or public names.

Every source module initializes once and receives stable __name__, __package__, and __file__; packages also receive __path__. Circular imports expose the exact partially initialized namespace. An escaping initialization fault removes the incomplete module and child publication before a later retry. The graph admits 64 modules including the main script, depth 16, and 512,000 aggregate UTF-8 source bytes. Namespace packages, zip imports, and dynamic import hooks are unavailable.

5.5 Import a C or C++ object

cc -c /fastmath.c -o /fastmath.o
vi /startup.py

# /startup.py
import fastmath
print(fastmath.answer())

reboot

A sibling CS486OBJ file or one in a Python library directory becomes a module. Its global functions use the current zero-argument integer ABI and return through EAX. The function executes inside the calling Python CS486 process, so its instructions, cycles, faults, and RAM accesses use the same limits. This is sandboxed static extension loading, not a host DLL or shared object.

5.6 Event-driven output

import os
import redstone

while True:
    event = os.pull_event("redstone")
    redstone.set_output(
        "right",
        redstone.get_input("left")
    )

Chapter 06 · World interface

Connecting programs to Minecraft

World I/O crosses a narrow adapter boundary. A program observes snapshots and bounded events; it never calls Bedrock APIs directly.

Sides6Digitalfalse / trueAnalog input0…15

6.1 Built-in displays

MachineWeb Terminal rule
Desktop / Advanced DesktopThe CRT is built into the placed Computer. Touch the Computer directly to activate its Web Terminal.
Portable Computer SystemIts LCD is built in. Use it while held, or place and touch the open-laptop block.

Each Computer has a permanent four-digit connection number. Touching an eligible machine activates it once for two minutes; duplicate rapid interactions for the same player and Computer are admitted once. Because the number is permanent rather than single-use, entering it claims a waiting activation when one exists and otherwise falls back to the bounded reconnect exchange for the session that number already owns, so a browser holding no token does not have to re-activate the machine. Bedrock must accept the exact session before a browser opens. After the handoff POST succeeds, the browser stores the number locally and changes the bookmarkable URL to /?computer=NNNN; bearer tokens are never placed in that query or browser history. Invalid guesses are rate-limited and simultaneous number collisions fail explicitly. Placed-machine control pauses beyond three blocks and resumes at 2.75 blocks or nearer. Between those thresholds the prior state remains unchanged, so boundary movement does not spam alternating messages; range status stays in the Web UI rather than Minecraft chat. A reloaded bookmark rotates the bearer token through a bounded reconnect policy and stops when a new activation is required. Portable placement transfers the same persistent Computer identity from item to block. Breaking it returns an identity-carrying Portable Computer System item.

6.2 Side names

NameMeaningUse
top / bottomVertical facesStacks and floor wiring
front / backRelative to block orientationOperator-facing machines
left / rightRelative lateral facesRelay and control pairs

6.3 Six-face serial, SPI, and I2C

Linux bus / DOS busFaceLinux devicesDOS devices
0 / 1bottomttyS0, spidev0.0, i2c-0COM1, SPI1, I2C1
1 / 2rightttyS1, spidev1.0, i2c-1COM2, SPI2, I2C2
2 / 3frontttyS2, spidev2.0, i2c-2COM3, SPI3, I2C3
3 / 4backttyS3, spidev3.0, i2c-3COM4, SPI4, I2C4
4 / 5topttyS4, spidev4.0, i2c-4COM5, SPI5, I2C5
5 / 6leftttyS5, spidev5.0, i2c-5COM6, SPI6, I2C6

RS-232C is 9600 baud, 8N1, full duplex, and direct Computer-to-Computer. At 20 ticks per second each direction advances at most 48 bytes per tick. A full receive queue applies backpressure; disconnect and power changes clear stale bytes. SPI is mode 0 at 1 MHz with 8-bit MSB-first words and a 256-byte atomic limit. I2C is 100 kHz, 7-bit, and limits each combined write/read transaction to 256 bytes. SPI/I2C controller contracts are ready for future IoT blocks; an unattached target fails explicitly.

printf hello > /dev/ttyS0
cat /dev/ttyS0
spi 0 0 9f0000
i2c 0 scan
i2c 0 0x48 00 2

6.4 Polling and events

import os
import redstone

while True:
    os.pull_event("redstone")
    level = redstone.get_analog_input("left")
    redstone.set_output("right", level >= 8)

Use pull_event instead of a tight polling loop. It yields the VM until relevant work exists and avoids consuming the machine's cycle budget while idle.

6.5 Output checklist

  1. Confirm orientation before assigning side names.
  2. Read the existing input and decide a safe default output.
  3. Handle startup before waiting for the first change event.
  4. On failure, leave an explicit terminal state; do not spin-retry.

Chapter 07 · Laboratory exercise

Build a signal threshold controller

This exercise joins filesystem work, source editing, redstone events, diagnostic output, and bounded execution into one repeatable operator workflow.

7.1 Define the contract

InputRuleOutput
Analog left, 0…15level ≥ 8Digital right, on
Analog left, 0…7level < 8Digital right, off

7.2 Implement /startup.py

import os
import redstone

def update():
    level = redstone.get_analog_input("left")
    redstone.set_output("right", level >= 8)
    print("level", level)

update()
while True:
    os.pull_event("redstone")
    update()

7.3 Commissioning procedure

  1. Save with :wq, then run reboot.
  2. Apply levels 0, 7, 8, and 15 to the left face.
  3. Verify the right output changes only at the threshold.
  4. Disconnect and reconnect the terminal; verify the program and machine identity persist.
  5. Inspect free -h and quota after the test.

7.4 Verify boundary and failure cases

CaseVerifyExpect
Below thresholdVerify: Apply analog levels 0 and 7 to the left face.Expect: The right output stays off and the terminal reports each level.
At and above thresholdVerify: Apply analog levels 8 and 15.Expect: The right output turns on exactly at level 8.
StartupVerify: Reboot once with a stable input.Expect: The output reflects the input before the first event wait.
Connection lossVerify: Disconnect, reconnect, and inspect the same Computer identity.Expect: Source and output state persist; reconnect work remains bounded.

7.5 Measure and inspect

cpuinfo
free -h
quota

Verify: Record processor identity and clock, command status, live memory, and disk use before and after one controlled input sequence.

Expect: Output remains correct, idle event waiting does not create a polling storm, and resource use remains within the independent ceilings.

7.6 Deploy and roll back

  1. Copy the last known-good source before replacing /startup.py.
  2. Reboot once and repeat the four boundary inputs.
  3. If startup faults, stop retrying. Preserve the broken file and world. Read the halt screen first: it names the failing boot phase and the exact reason. Open the crashed Computer normally for the recovery instruction, then sneak while opening it; or use the safe-boot power control in an already attached Web Terminal. Restore the known-good source from that one boot.

Safe boot exists only for the crashed lifecycle and preserves the exact /startup.py. It is not a guest-shell or MCP command. This /startup.py workflow is a Desktop CS-Linux workflow; a Portable CS386SX runs no user MicroPython, so safe boot there only retries without bootable floppy media.

Verify: Confirm the file is unchanged before repair, inspect the boot journal, then power-cycle, reconnect, and repeat levels 7 and 8.

Expect: Recovery bypasses the broken file once without resetting it. After an explicit repair, the persisted program starts once, waits for events, and switches only at the documented boundary.

Chapter 08 · Native API

Runtime function reference

Snake-case names are canonical below. Selected camelCase aliases exist for ComputerCraft familiarity; portable programs should prefer one naming convention consistently.

8.1 os

FunctionResult / effect
get_computer_id()Stable numeric Computer identity
clock()Elapsed tick time in seconds
sleep(seconds)Yield for a bounded tick duration
pull_event([filter])Yield until the next matching event
queue_event(name, ...args)Append a bounded local event
start_timer(seconds)Return timer id
cancel_timer(id)Return whether cancellation succeeded
shutdown() / reboot()Request explicit lifecycle transition

8.2 term

Writing write(text), clear(), clear_line(), scroll(lines)

Cursor set_cursor_pos(x, y), get_cursor_pos(), set_cursor_blink(bool)

Geometry get_size()

Color set_text_color(mask), get_text_color(), set_background_color(mask), get_background_color(), is_color()

8.3 fs and redstone

ModuleFunctions
fsexists, is_dir, list, make_dir, read_file, write_file, append_file, delete, copy, move, get_size, get_free_space
redstoneget_input(side), get_analog_input(side), get_output(side), set_output(side, bool)

8.4 serial, spi, and i2c

ModuleFunctionsBus numbering
serialread(port [, maximum]), write(port, text), status(port)0..5
spitransfer(bus, chip_select, byte_list)0..5
i2cscan(bus), transfer(bus, address, write_bytes, read_length)0..5

These modules are available to desktop Computer System Python. The portable CS386SX DOS profile uses the batch-capable SPI/I2C commands and COM devices because user Python is unavailable.

Chapter 09 · Hardware model

Three machine profiles, one safe instruction format

The Computer System Deskpro 486DX selects a CS486DX at 33 MHz with 2 MiB RAM; the Computer System Deskpro 486DX2 selects a CS486DX2 at 66 MHz with 8 MiB RAM; the Computer System LTE 386SX selects a CS386SX at 16 MHz with 2 MiB RAM. These are the manual model names for the Computer, Advanced, and Portable machine types. The persisted CPU model selects timing in O(1), while the bounded scheduler arbitrates actual BDS work fairly.

Computer System Deskpro 486 family all-in-one computer with built-in CRT, keyboard, mouse, and two 3.5-inch floppy drives
Computer System Deskpro 486 family. Computer uses the 486DX/33 and Advanced uses the 486DX2/66 configuration of the same square all-in-one CRT chassis. Computer has one 3.5-inch floppy drive; Advanced has two. The Minecraft implementation models the machine rather than emulating the pictured host hardware literally.

9.1 Machine family

Computer System Deskpro 486DX square all-in-one CRT chassis with one right-mounted 3.5-inch floppy drive
Computer System Deskpro 486DXComputer · CS486DX · 33 MHz · 2 MiB · CS-Linux 1.0
Computer System Deskpro 486DX2 square all-in-one CRT chassis with two right-mounted 3.5-inch floppy drives
Computer System Deskpro 486DX2Advanced · CS486DX2 · 66 MHz · 8 MiB · CS-Linux 1.0
Computer System LTE 386SX cream laptop with trackball and 3.5-inch floppy drive
Computer System LTE 386SXPortable · CS386SX · 16 MHz · 2 MiB · CS-DOS 1.0 · held or placed

Production execution rate

The Bedrock host admits approximately one half of each model's persisted nominal clock: 400,000 cycles per 20 Hz tick for CS386SX 16 MHz, 825,000 for CS486DX 33 MHz, and 1,650,000 for CS486DX2 66 MHz. The build-validated Behavior Pack setting guestRealtimeDivisor controls this ratio; its shipped value is 2, while 1 requests realtime admission. Rebuild the packs and restart BDS after changing it. Managed BDS assigns CS386SX and CS486 Computers to the same fixed worker pool. Each worker and the local Bedrock lane admit at most 1,650,000 modeled cycles and 1,650,000 machine instructions per tick, so one resource can sustain at most 33 MHz of aggregate modeled CPU work before fair sharing. Each resource owns an independent round-robin cursor, so uneven worker placement does not bias long-term sharing among the Computers assigned to that worker. Worker count changes aggregate host concurrency but never changes a model, clock, cycle debt, or per-Computer guest admission rate. Host contention may reduce the observed rate but never increases guest timing above this admission ratio.

9.2 Processor identity

CS486DX processor identification plate
CS486DXStandard desktop processor
CS486DX2 processor identification plate
CS486DX2Advanced desktop processor
CS386SX processor identification plate
CS386SXPortable processor with a 16-bit external data bus

9.3 Register file

RegisterConventional useWidth
EAXAccumulator and expression result32 bit
EBXSecondary operand32 bit
ECXLoop counter32 bit
EDXGeneral data32 bit
ESI / EDISource / destination index32 bit
ESP / EBPStack top / initial stack base32 bit

9.4 Memory model

RAM is a checked, little-endian linear byte array. LOAD and STORE transfer signed 32-bit words. CS386SX exposes a 24-bit address bus and a 16-bit data bus, with 2 MiB provided by two 1 MiB 30-pin SIMM DRAM modules. An even-addressed dword needs two 16-bit transfers; an odd-addressed dword needs three and records an unaligned access. CS386SX has no cache, so every one of those transfers pays the full main-memory cycle cost; CS486DX/DX2 pay that same per-transfer cost only when their L1/L2 misses, so a cache hit stays inexpensive. CS486DX uses four 512 KiB 30-pin SIMMs, while CS486DX2 uses two 4 MiB 72-pin SIMMs. The stack begins at the top of RAM and grows downward.

Memory reports include bounded OS overhead as well as live guest data. CS-Linux separates resident kernel, system services, buffers, and guest runtime. CS-DOS separates DOS system/drivers and guest runtime while preserving conventional, upper, reserved, and XMS region totals. Version 3 executables declare their cs-flat32-v1 stack, heap, and auxiliary residency before process construction. The built-in empty-startup shell uses one 64 KiB composite grant; user-authored startup uses one quarter of physical RAM capped at 1 MiB, and foreground Python keeps its 1 MiB managed-runtime quota. Older version 1/2 executables remain readable but take the complete currently free physical remainder exclusively.

LOW ADDRESSOS resident memorycompiler variables / heapfree space↓ stack growthHIGH ADDRESS

9.5 Model-specific cycle classes

ClassCS486DX / CS486DX2CS386SX
Simple ALU12
LOAD / STORE base2 / 2 plus cache and write-through6 / 4 plus main-memory cycles every access, no cache
PUSH / POP base2 / 2 plus cache and write-through4 / 6 plus main-memory cycles every access, no cache
Conditional branch3 taken / 1 not taken7 taken / 3 not taken
CALL / RET3 / 39 / 12
MUL99–38, operand early-out
DIV / MOD4043
PRINT8 + payload12 + 16-bit bus payload

At 20 ticks per second the nominal clocks correspond to 1,650,000 cycles/tick for the standard desktop, 3,300,000 for Advanced Desktop, and 800,000 for portable. Production divides those admission budgets by the configured guestRealtimeDivisor. CS486DX and CS486DX2 have a cold 8 KiB four-way unified L1 with 16-byte lines and write-through stores; Advanced adds a 256 KiB external L2. CS386SX has neither cache, so it pays the same per-transfer main-memory cost as CS486DX/CS486DX2 on every access instead of only on a cache miss. Cache tags, recency, prefetch state, and counters are transient per process. Every access remains O(1).

9.6 CSBIOS and VGA display profiles

Power-on runs an original deterministic CSBIOS Revision 1.1 sequence in 80x25 text mode. At 20 server ticks per second its 70 ticks take about 3.5 seconds: black, CS-VGA identification, a short black transition, CSBIOS with a bounded same-row memory count, factual device detection, explicit fixed-disk or floppy source plus CS-Linux/CS-DOS target, a handoff blackout, and the selected Starting ... line. The Computer remains booting; guest CPU work and terminal/debug input stay unavailable until the final handoff. POST values come only from the active CPU, clock, RAM, display, VRAM, floppy state, and disk quota. CSBIOS does not copy AMI vendor strings or advertise an unsupported setup utility or FPU.

At handoff CSBIOS clears its frame once and explicitly releases control to CS-DOS or CS-Linux. CS-DOS then shows only its identity, a blank line, and C:\>; CS-Linux shows only its identity, a blank line, and the password or shell prompt. Neither advertises a simulated tty or startup shell-version banner.

MachineVRAMPhysical presentation640x480 maximum mode
Portable256 KiB800x480 LCD, centered 640x480 with 80 px side bars16 colors, four VGA planes
Desktop512 KiBBuilt-in 640x480 CRT256 indexed colors
Advanced Desktop512 KiBBuilt-in 640x480 CRT256 indexed colors with lower modeled transfer cost

Every model also supports 320x200 with 256 colors. The 800x480 Portable panel is not a guest mode, and no model advertises a resolution above 640x480. VRAM is volatile and allocated only while powered; World Dynamic Properties store the small display-profile ID, never framebuffer bytes. Dirty graphics work uses a fixed-capacity queue with O(1) marking and bounded O(D) extraction. One Computer-scoped broker drains it once and shares each immutable update across attached sessions, with queued keyframes for late connections, epoch changes on mode replacement, and fixed Computer, tile, and byte budgets. This keeps publication work O(D+S). The Web text presentation keeps a fixed 80x25 guest grid and scales it to the viewport. Web Canvas delivery and guest graphics APIs remain the next implementation stage.

9.7 Web raster aspect

The Web Terminal uses one shared active-raster layer for command output and full-screen text TUI programs. Its 80x25 IBM VGA text grid is a logical 720x400 glyph raster: 80 columns at 9 pixels and 25 rows at 16 pixels. One blank 16-pixel row above and below supplies CRT vertical raster margin, and a 0.8 horizontal correction presents the complete surface as exact 4:3 glass without changing the guest grid or TUI pointer coordinates. Graphics use mode-specific correction instead: 640x480 VGA is already 4:3 and remains square-pixel at 1.0, while 320x200 receives its own correction. CS Windows is not implemented; this shared layer only preserves the presentation contract needed by a future 640x480 graphics surface.

Chapter 10 · CS ASM 1.0

CS ASM 1.0 for the active CS486/CS386 target

An independent, bounded assembler with Linux and DOS command spellings. One instruction occupies each line; labels end in a colon, semicolons begin comments, registers are case-insensitive, and memory operands use square brackets.

10.1 Build and inspect

# CS-Linux: direct executable
as total.asm -o total
objdump total
run --stats total

# CS-Linux: object plus static link
as -c fast.asm -o fast.o
nm fast.o
objdump fast.o
ld fast.o -o fast -e start

REM CS-DOS: identity, command-line build, and WorkBench
ASM /VERSION
ASM /C FAST.ASM /OUT:FAST.O
LINK FAST.O /OUT:FAST /ENTRY:START
RUN FAST /STATS
CSASM FAST.ASM
PWB FAST.ASM

CS-Linux uses as/ld with -c, -o, and -e. CS-DOS additionally exposes ASM/LINK and accepts /C, /OUT:, and /ENTRY:. CSASM opens CS ASM 1.0 in the full-screen WorkBench, while PWB selects assembly mode from the .ASM extension; F2 saves, Shift+F5 builds and runs, and F4 toggles output; output paths still obey strict DOS 8.3 rules and diagnostics use CRLF. Relocatable assembly declares exported labels with global name and imported labels with extern name. Unmarked labels remain local to that object.

The resulting current CS486OBJ v4 object stores its word32 or byte8 identity, sections, typed symbols, initialized data, alignment, bounded function signatures, and structured relocations. nm and objdump inspect those records; the linker resolves symbols through bounded maps without rewriting assembly text and rejects mixed models. Existing v1-v3 word objects remain readable.

10.2 Instruction set

FormOperation
MOV reg, srcCopy immediate or register
LOAD reg, [addr]Read signed 32-bit word
STORE [addr], regWrite signed 32-bit word
ADD / SUB / MUL / DIV / MODInteger arithmetic into destination
AND / OR / XORBitwise operation
SHL / SHRSigned 32-bit shift; count masked to 0…31
CMP reg, srcSet internal comparison result
JMP / JE / JNEUnconditional / equal / unequal branch
JL / JLE / JG / JGESigned relational branch
PUSH / POP32-bit stack transfer
CALL / RETPush return address / resume caller
PRINT srcWrite register, immediate, or quoted string
HALTSuccessful terminal state

The source path flows through a dedicated tokenizer, bounded preprocessor, parser, constant-expression evaluator, and two assembly passes. Source-span diagnostics identify the guest file, line, and column. Directives include section .text, .rodata, .data, .bss, global, extern, type, align, equ, initialized db/dw/dd data, and reserved resb/resw/resd storage. DOS source may use .CODE, .CONST, PUBLIC, and EXTRN aliases.

%define COUNT 5
%include "common.inc"
%macro add_to 2
  add %1, %2
%%done:
%endmacro

Includes are resolved relative to the source inside the credentialed guest filesystem. The preprocessor reads at most 1,000,000 source characters in total and allows at most 100,000 lexical tokens, 64 include files at depth 8, 256 macro definitions, 32 arguments per call, macro expansion depth 16, and 100,000 expanded tokens. Source characters and lexical tokens are checked before token arrays are materialized; expanded tokens are reserved before definition or macro output is appended. Exceeding a bound, a circular include, or recursive expansion is an explicit source error. DOS also accepts INCLUDE and name MACRO ... ENDM. Labels beginning with %% are local to one macro expansion.

.rodata is a layout and symbol-type category, not runtime page protection. Relocations distinguish control-flow targets from data addresses; a call to a data symbol, a data reference to a function, duplicate symbols, unresolved symbols, bad relocation fields, or total RAM overflow stops the link.

10.3 Counted sum

; EAX = 5 + 4 + 3 + 2 + 1
mov eax, 0
mov ecx, 5
loop:
  add eax, ecx
  sub ecx, 1
  cmp ecx, 0
  jg loop
print eax
print "\n"
halt

Chapter 11 · CS QBASIC 1.0

CS QBASIC 1.0 DOS editor and bounded source

CS-DOS alone ships the independent, sandboxed QBASIC.EXE. It targets Microsoft QBasic 1.1 command and source behavior where listed here, but it is not Microsoft's binary, help database, artwork, 16-bit x86 runtime, or a native DOS interrupt environment. Current CS-Linux exposes neither basic nor basicc.

11.1 Starting CS QBASIC 1.0

QBASIC                         REM open the Welcome dialog
QBASIC C:\WORK\DEMO.BAS       REM open an existing or new buffer
QBASIC /RUN C:\WORK\DEMO.BAS  REM compile, run, and return to the IDE
QBASIC /EDITOR C:\README.TXT  REM the same editor engine used by EDIT

The accepted switches are /B, /EDITOR, /G, /H, /MBF, /NOHI, and /RUN. Unknown and duplicate switches, more than one filename, /RUN without a file, and /EDITOR combined with /RUN fail visibly. /HELP is not invented.

11.2 WorkBench, EDIT, keyboard, and mouse

EDIT file and QBASIC /EDITOR file use the bounded five-menu EDIT session for buffer ownership, Open/Save As browsing, save/error handling, search, undo, dirty transitions, pointer hit testing, drag selection, and Ctrl+C/Ctrl+X/Ctrl+V. Ctrl+O and Ctrl+Shift+S browse strict DOS 8.3 entries on C: or A: without reading host files. Directories, wildcard filters, scrolling, empty/not-ready states, and removable-media changes are explicit. Web Terminal mouse events are accepted only from the current writer; cell coordinates and sequences are checked, moves are coalesced, and pressed buttons are released on takeover, range loss, and disconnect.

EDIT, CS QBASIC, CS ASM, and CS C/C++ share the VGA font, exact DOS palette, two leading menu-bar cells, a continuous left document border, centered document title, scrollbars, a one-leading-cell cyan footer, reversed active menu item, and gray dialog with a black shadow. The Web bridge preserves F1 through F12, Ctrl/Shift/Alt function-key combinations, Ctrl+Shift shortcuts, selection navigation, and Alt+Left. Bare Alt first invokes F10/File, so a Chrome-reserved Alt+F does not leave the DOS menu unreachable; clicking a heading remains an equivalent path. While a DOS editor is active, the transparent keyboard textarea does not receive pointer events, so it cannot cover the menu or the document cursor row. A click on a QBASIC/WorkBench heading dismisses Welcome and opens that menu in the same action.

EnvironmentRun/build result
CS QBASIC F5 / Ctrl+F5 / Shift+F5 / /RUNRun saved BASIC source transiently and return output to the IDE; no OBJ, CSX, or EXE is created
CS ASM / CS C/C++ F7 / Ctrl+F7Build or rebuild the selected source/Program List to a persistent CSX
F3 / Shift+F3 in F4 OutputOpen the next or previous bounded compiler file/line/column
F5 / F8 / F9 in ASM or C/C++Start/continue, trace one instruction, or toggle the current-EIP breakpoint
EscapeReturn from the debugger pane to source while retaining the paused debuggee

CS QBASIC therefore exposes File/Edit/View/Search/Run/Options/Help and does not show Make or Debug. CS ASM and CS C/C++ expose File/Edit/View/Search/Make/Run/Debug/Options/Help. Help is right-aligned in every bar and the active heading is reversed instead of receiving a parenthesized mnemonic suffix.

11.3 Current source subset

AreaAccepted forms
Numeric scalarsCase-insensitive assignment, scalar DIM, LONG-range decimal, &H hexadecimal, and &O octal values
OutputPRINT / ?, numeric expressions, quoted literals with doubled quotes, comma/semicolon separation
ExpressionsArithmetic, integer division, MOD, comparisons, NOT, AND, OR, and XOR
Control flowNumbered or named GOTO/GOSUB/RETURN, inline IF THEN ELSE, FOR/NEXT, WHILE/WEND, DO/LOOP, and EXIT FOR/DO
TerminationEND, STOP, or SYSTEM

Source is capped at 4,096 lines and 8,192 statements, with 1,024 variables, 128 expression tokens, 40-character variable names, and bounded runtime instructions, memory, stack, and output.

11.4 Complete example

10 LET TOTAL = 0
20 FOR I = 1 TO 100
30 LET TOTAL = TOTAL + I
40 NEXT I
50 PRINT TOTAL
60 END

Chapter 12 · CS C/C++ 1.0

CS C/C++ 1.0 for the active CS486/CS386 target

Dedicated bounded tokenizers and parsers accept deliberately small, auditable C and C++ subsets. They do not invoke GCC or Clang and do not claim ISO language or x86 binary compatibility.

12.1 C

cc --version
cc program.c -o program
cc -mbyte8 binary.c -o binary
CSCC PROGRAM.C

The default cs-word32-v1 profile uses CHAR_BIT=32: signed/unsigned char, short, int, long, and pointers occupy one word; long long, int64_t, and their unsigned forms occupy two low-word-first words. -mbyte8 or -mdata-model=cs-byte8-v1 selects 8-bit char, 16-bit short, 32-bit int/long/pointers, 64-bit long long, byte-stride pointers, natural little-endian aggregate padding, packed strings, and exact uint8_t/uint16_t. -mword32 selects the default explicitly. The bounded subset includes promotions and truncation, unsigned arithmetic, if/switch/loops, checked goto labels, file/local static, extern, qualifiers, pointers and validated function pointers, fixed multidimensional arrays, pointer-passed structs, unions, designated initializers, compound literals, final flexible arrays, deterministic 32-bit bit-fields, enums, typedefs, _Bool, _Static_assert, alignof, sizeof, and casts. Up to 32 physical argument words use cs486-cc2; two-word integer or binary64 results return in EDX:EAX, indirect calls validate exact executable entries, and <stdarg.h> bounds every variadic read. Rootfs v19 installs matching libc, libcurses, and libm archives under /usr/lib/cs-word32-v1 and /usr/lib/cs-byte8-v1. <cs/byte.h> explicitly packs octets for word programs but does not change word unsigned char * semantics. This is not native x86 layout or ABI compatibility.

12.2 C++

c++ --version
c++ program.cpp -o program
CSCPP PROGRAM.CPP
PWB PROGRAM.CPP

The C subset plus std::cout << value << std::endl. Classes, inheritance, references, overloads, namespaces, templates, constexpr, exceptions, RTTI, virtual dispatch, concepts, and the ISO standard library are not implemented.

Under CS-DOS, C-only CSCC, C++-only CSCPP, and extension-selecting PWB open the full-screen CS C/C++ 1.0 WorkBench. F2 saves, F7 builds the current file or selected Program List, Ctrl+F7 rebuilds all Program List sources, Ctrl+F5 runs the exact last successful non-stale .CSX, Shift+F5 builds and runs, and F4 toggles bounded output. F3 and Shift+F3 navigate output diagnostics. F5 starts or continues the instruction debugger directly in WorkBench; the DEBUG command is optional. F8 traces and F9 toggles a current-EIP breakpoint. Source-line stepping and local-variable reconstruction remain unavailable.

12.3 Deterministic floating point and libm

#include <math.h>
#include <stdio.h>
int main(void) {
  printf("%.3f
", sqrt(2.0));
  return 0;
}

float is IEEE-754 binary32 and double is binary64; long double is an alias of double. The word model reports sizes 1/2 word units and the byte model reports 4/8 bytes. Parsing, constant folding, arithmetic, casts, comparisons, signed zero, subnormals, infinities, canonical quiet NaNs, and round-to-nearest ties-to-even use the same bounded integer/rational software core. Binary64 arguments occupy two low-word-first physical words and return in EDX:EAX; variadic float promotes to double. Link guest math with -lm. The initial profile includes fabs, copysign, floor, ceil, trunc, round, fmod, sqrt, ldexp, frexp, modf, and classification. %f has at most 18 fractional places. Trigonometric, exponential, logarithmic, pow, complex, mutable rounding modes, x87/SIMD, host libm, and fast-math are not implemented. CS386SX has no on-die FPU, matching the real 80386SX's dependency on a discrete 80387SX coprocessor: every floating-point operation faults at runtime instead of executing. CS486DX and CS486DX2 both model an on-die FPU and execute floating point normally.

12.4 Summation in C

int main() {
  int total = 0;
  for (int i = 1; i <= 100; i++) {
    total = total + i;
  }
  printf("%d\n", total);
  return 0;
}

12.5 Preprocessor, frontend, CSIR, and register allocation

The practical token preprocessor supports quoted/angle #include, object/function #define, #undef, conditional compilation, defined, physical-line continuations, rescanning, # stringification, ## token pasting, and #error. Linux accepts -I/-D/-U; DOS also accepts /I,/D,/U and the INCLUDE environment variable. Include reads use current guest credentials only. Include depth/cycles, macro work, conditional depth, source/tokens, and diagnostics are bounded; #pragma and variadic macros fail explicitly.

The source-character and token ceilings are checked before arrays grow. Tokens retain include and macro-expansion provenance; the parser builds a typed AST with lexical scopes and rejects undeclared, duplicate, malformed, or unsupported constructs before producing an object. A function declaration or prototype must precede each call, and an in-scope local with the same name shadows the function and is not callable.

The typed AST lowers to CSIR. Every computed value has one SSA definition, while mutable C locals remain explicit load-local/store-local operations: this is value SSA, not memory SSA. A bounded verifier checks types, definitions, dominance, control-flow targets, and explicit block terminators. Pass-capped deterministic optimization performs bounded leaf-function inlining, algebraic simplification with power-of-two strength reduction, constant folding, copy propagation, block-local common-subexpression elimination, unreachable-block cleanup, and dead-pure-value elimination.

The backend uses bounded deterministic linear-scan allocation and checked stack spills. ESP and EBP are reserved, values live across a call are conservatively spilled, and locals occupy EBP-relative stack-frame slots. Graph coloring is not required and is not implemented. Inspect the typed symbols, relocations, and final instruction stream with nm and objdump.

12.6 Objects, static linking, and Python imports

cc -c main.c -o main.o
as -c fast.asm -o fast.o
nm main.o
ld main.o fast.o -o program
 run --stats program

New writers emit model-declared version 4 of CS486OBJ, version 5 of CS486, and version 2 of CS486AR. Objects carry ordered .text, .rodata, .data, and .bss sections, typed local/global/undefined symbols, bounded signatures such as (i32,i32)->i32 and ()->void, alignment, initialized bytes, and structured instruction/data relocations; readers retain legacy word objects and executables. nm, objdump, and csdb report the identity. Linking or archive selection rejects mixed models before layout or output mutation. extern int fast(int, int); and the limited C++ spelling extern "C" int fast(int, int); create the same unmangled undefined text-function symbol. Linkage blocks and other language linkages are rejected. Known parameter/return-signature conflicts stop the link deterministically. ASM may opt in with signature fast, i32, i32, i32 or remain untyped for legacy compatibility. Callers push arguments right-to-left and clean the stack; callees preserve ESI/EDI/EBP and return integers through EAX.

Word strings remain decoded 32-bit words plus a zero word; byte strings are packed values plus a NUL byte. Constant globals use .data, zero-initialized globals use .bss, and extern objects retain structured relocations across translation units. Format units, conversions, aggregate storage, initialized bytes, %s reads, and worst-case output are capped before installation.

Linked static bytes are installed in low RAM before execution, and the aligned end of all static data becomes the stack floor. Python static extensions remain explicitly cs-word32-v1; a byte-profile object is rejected rather than converted. A valid word object exposes only the zero-argument EAX-return text-function ABI. Every imported machine instruction is charged to the same CS486 process.

12.7 Cross-profile executable compatibility

as, cc, and c++ write the same validated Computer System CS486 format family under CS-Linux and CS-DOS, but current artifacts also declare cs-word32-v1 or cs-byte8-v1. The two models cannot be linked or imported together. CS QBASIC 1.0 lowers its supported DOS-only source subset to a transient instance of the same process. CS486OBJ is not Linux ELF or OMF, and CS486 is not a native DOS .COM/.EXE or host x86 machine code. Neither profile invokes a host assembler, linker, or loader. A complete compatible CS486 executable can run after transfer to a valid destination path; the destination Computer supplies CPU timing, cache or bus behavior, RAM ceiling, and filesystem rules.

There is currently no guest command for copying a file between two different Computer identities and no shared guest disk. Dynamic linking, native object ingestion, native GDB or DOS DEBUG emulation, source-level debug metadata, PIC/IRQ/IDT execution, BIOS/DOS interrupts, and native COM/EXE loading are not implemented. A legacy version-4 word executable or current version-5 model-declared executable launched by guest PATH or run receives bounded immutable arguments, environment, credentials, declared heap, standard streams, and CS ABI 1.0. <cs/fs.h> transfers word characters for cs-word32-v1 and exact bytes for cs-byte8-v1, with no implicit UTF-8 or newline conversion. Standard output is line-buffered, fflush(stdout) is explicit, stderr is unbuffered, and all pending owned state is finalized once on return, exit, signal, terminal close, or shutdown. The same syscalls reject in non-hosted, background, DOS, debugger, and Python-extension contexts. Mouse events, sound, windows, arbitrary graphics modes, host devices, and native operating-system calls remain unavailable.

12.8 Restricted inline assembly

int answer = 0;
asm("mov eax, 6");
asm("mul eax, 7");
asm("store [answer], eax");

Inline assembly executes at a statement boundary. It may use ordinary arithmetic and checked memory operations. Labels, branches, CALL/RET, PUSH/POP, HALT, and ESP/EBP access are rejected. Dynamic libraries are not yet supported.

12.9 CS-DOS Program Lists

CS PROGRAM LIST 1.0
SOURCE=MAIN.C
SOURCE=FAST.CPP
SOURCE=VIDEO.ASM
OBJECT=VENDOR.OBJ
INCLUDE=INCLUDE
DEFINE=FEATURE=1
ENTRY=main
OUTPUT=DEMO.CSX
LISTING=DEMO.LST
MAP=DEMO.MAP

Select this .CSP file with Make > Set Program List. F7 fingerprints every source, transitive included header, compile option, compiler identity, and authored object, then reuses unchanged project-owned objects. Ctrl+F7 rebuilds all source units. A successful build installs objects, executable, optional listing/map, and its .CBR ownership record transactionally. Failure preserves the prior executable but makes Run Last stale. Clean removes only recorded generated paths. Duplicate/canonicalized paths, generated OBJ collisions, authored inputs, existing unowned outputs, malformed records, and capacity-plus-one lists fail before partial mutation.

12.10 Hosted libc and libcs-curses

cc -c app.c -o app.o
cc -c /usr/src/libcs-curses/curses.c -o curses.o
cc -c /usr/src/cs-libc/libc.c -o libc.o
ld app.o curses.o libc.o -o app
run app

Rootfs v17 provides bounded hosted headers for strings, conversion, sorting/searching, exit handlers, getopt, current directories, directory iteration, metadata, temporary files, wall-clock time, synchronous signal/raise, and a fixed-format printf family. Guest wall time is separate from deterministic CPU ticks. Filesystem calls use the credentialed block-I/O lane; a directory handle snapshots at most 256 entries once and returns them in O(1) steps, with at most eight open directory handles per process.

This is a documented CS C profile rather than a native ISO/POSIX runtime. Aggregate values are not passed or returned by value, so div writes to a supplied div_t * and vsnprintf accepts va_list *. Signal handlers run only for synchronous guest raise; unhandled or host-delivered termination remains owned by the runtime. Normal main return runs bounded atexit handlers. Sorting uses deterministic O(N log N) heapsort and search is O(log N).

libcs-curses exposes one bounded 80×25 character screen, stdscr plus seven allocated windows, 16 color pairs, blocking key input, and one terminal frame per refresh/wrefresh. The library admits at most 1,024 formatted words and returns ERR or ENOMEM at capacity. Rootfs v16 stays frozen and does not gain these v17 headers or sources.

Chapter 13 · Performance engineering

Optimization is part of the machine

Use deterministic guest metrics. Host timing is affected by Minecraft ticks, other Computers, and the global scheduler cap.

13.1 The loop

  1. Establish correctness. Save expected output.
  2. Measure. Record instructions and cycles with run --stats.
  3. Find the dominant term. Count loop iterations and expensive opcodes.
  4. Change one idea. Algorithm, invariant motion, strength reduction, or memory layout.
  5. Compare. Require equal output and lower cost.

13.2 Archived pre-CSIR strength-reduction benchmark

These are historical live BDS measurements captured through the Computer System MCP on 2026-07-15, before the dedicated C/C++ tokenizer, typed AST, CSIR optimizer, and register allocator shipped. The C and C++ rows are retained as pre-CSIR provenance and must not be used as current compiler measurements; rerun every hardware profile before publishing a current comparison. The BASIC rows likewise record the former cross-profile basic command and do not imply BASIC availability on current CS-Linux or parity with the current CS QBASIC 1.0 frontend. All sources compute sum(i*i + 3*i + 7) for i = 1..1500. The baseline performs two multiplications per iteration; the optimized source advances the term with first differences. Every supported run started cold and printed the same checksum, 1129513000. Compile time, Web transport, browser rendering, Minecraft wall time, and MCP overhead are excluded. Each cell is instructions · modeled CPU cycles · virtual microseconds; the final column is cycle reduction.

Advanced Desktop · 9367 · CS486DX2 66 MHz · c-hvq8k7

FrontendBaselineStrength-reducedReduction
ASM15,004 · 42,106 · 637.970 µs9,006 · 12,084 · 183.091 µs71.3%
BASIC66,019 · 279,527 · 4,235.258 µs54,027 · 218,089 · 3,304.379 µs22.0%
CNot re-measured after the CSIR backend; authoritative guest MCP rerun pending.—
C++Not re-measured after the CSIR backend; authoritative guest MCP rerun pending.—
Computer System Python52,532 · 638,275 · 9,670.833 µs46,540 · 551,399 · 8,354.530 µs13.6%

Desktop · 1272 · CS486DX 33 MHz · c-s33g1r

FrontendBaselineStrength-reducedReduction
ASM15,004 · 42,058 · 1,274.485 µs9,006 · 12,048 · 365.091 µs71.4%
BASIC66,019 · 211,787 · 6,417.788 µs54,027 · 159,325 · 4,828.030 µs24.8%
CNot re-measured after the CSIR backend; authoritative guest MCP rerun pending.—
C++Not re-measured after the CSIR backend; authoritative guest MCP rerun pending.—
Computer System Python52,532 · 638,083 · 19,335.848 µs46,540 · 551,195 · 16,702.879 µs13.6%

Portable · 2985 · CS386SX 16 MHz · c-cqvhcs

FrontendBaselineStrength-reducedReduction
ASM15,004 · 68,478 · 4,279.875 µs9,006 · 25,522 · 1,595.125 µs62.7%
BASIC66,019 · 339,520 · 21,220.000 µs54,027 · 250,632 · 15,664.500 µs26.2%
CNot re-measured after the CSIR backend; authoritative guest MCP rerun pending.—
C++Not re-measured after the CSIR backend; authoritative guest MCP rerun pending.—
Computer System PythonUnavailable: both MCP commands returned status 127 and Bad command or file name.—

The archived ordering is a property of this workload and the frontends captured on that date, not a general language ranking or a claim about the current CSIR backend. The captured C and C++ frontends emitted the same instruction stream. CS486DX2 does not simply halve every cycle count: its external L2 participates in cold misses, while its 66 MHz clock still lowers virtual time. CS386SX has no cache and charges its 16-bit external bus, so the same executable has a different cycle total.

13.3 Cost priorities

PriorityQuestionTypical action
O(N)Does work scale with input or nested iteration?Change the algorithm first
Serial fractionWhat remains under global scheduling?Remove repeated setup and output
Opcode costAre DIV/MOD, taken branches, dword bus transfers, or PRINT dominant?Strength-reduce, improve locality, or batch
Memory pressureAre live objects forcing O(N) scans?Release references and reuse buffers

Compare optimizations on the same processor profile: CS386SX and CS486DX intentionally assign different costs to the same instruction stream.

13.4 Alignment and cache locality

Align C/C++ data and ASM buffers to four-byte boundaries. On CS386SX, any even dword address uses two 16-bit bus transfers, while an odd address uses three. Four-byte ABI alignment remains the portable convention. On CS486, keep hot code and data in nearby 16-byte cache lines. Reusing a line produces L1 hits; scattered or conflicting addresses cause bounded line fills. The Advanced external L2 can satisfy a line evicted from L1. Stores are write-through, so reducing unnecessary writes still matters.

RUN --STATS LOCAL
RUN --STATS SCATTER

The second statistics line reports L1 and L2 hits/misses, bus transfers, unaligned dwords, and pipeline flushes. Every run starts cold, so comparisons are reproducible and do not inherit another program's cache.

13.5 Branches and pipelines

Neither CS386SX nor CS486 implements dynamic branch prediction. CS386SX models prefetch overlap and charges taken branches more than fall-through. CS486 models a five-stage refill: a not-taken conditional branch costs one base cycle, while a taken conditional branch costs three and records a pipeline flush. JMP, CALL, RET, and runtime control transfers also flush. Prefer branch removal only after the algorithm and memory-access pattern are correct.

13.6 Batch programs with run --batch

run [--batch] [--stats] program [arguments ...] is CS-Linux only. --batch is a declaration you make about the program: this process uses no operating-system service. A batch process may still receive argv, the environment, and the working directory through the ordinary CS ABI startup image, ask for its heap placement, write to standard output and standard error, and exit with a status. Every other CS ABI operation - opening or reading a file, terminal size and presence, key waits and polls, the clock, and sleeping - fails immediately with UnsupportedOperationError naming the operation, and the message tells you to re-run the program without --batch. Nothing is approximated and no service is silently substituted.

Declaring a program batch lets the host run it on the managed compute plane instead of inside the interactive scheduler lane, so a computation-heavy program finishes in less wall-clock time. It does not change one guest-visible number: instructions, modeled cycles, cache and bus counters, registers, output bytes, and exit status are identical with and without the flag. Compare run --stats bench and run --batch --stats bench and expect the same statistics line. Where a batch program actually runs remains a server operator's configuration, not a guest property.

Batch output is one ordered stream: fd 1 and fd 2 interleave in exact write order, fd 1 is not line buffered, and the whole stream is delivered when the program finishes. Because of that, --batch is refused before anything runs when it is combined with a pipeline or a redirect, when the command is put in the background with &, when the target is a shell utility rather than a compiled program, and when the executable is not a hosted CS-Linux program with a main symbol. CS-DOS run has no batch concept and rejects the option as a usage error.

cc bench.c -o bench
run --stats bench
run --batch --stats bench   # same output, same cycles, less waiting
run --batch reader          # fails: batch process cannot use CS ABI operation 8

Before

mov eax, 0
mov ecx, 100
loop:
 add eax, ecx
 sub ecx, 1
 cmp ecx, 0
 jg loop

After

; equivalent for fixed N
mov eax, 5050

Chapter 14 · Computer System DOS 1.0

Operating CS-DOS 1.0 on the LTE 386SX

Computer System DOS 1.0 (CS-DOS 1.0) is the portable profile for the Computer System LTE 386SX, a CS386SX 16 MHz machine with 2 MiB RAM. It supports CS ASM 1.0, CS C/C++ 1.0, CS QBASIC 1.0, and bounded batch files. User MicroPython is unavailable. Storage, identity, execution limits, and the host security boundary remain shared with the CS-Linux desktop.

Computer System LTE 386SX with 2 MiB RAM showing a DOS prompt, VGA LCD, keyboard, trackball, 3.5-inch floppy drive, rear ports, and battery pack
Computer System LTE 386SX. The CS386SX profile runs at 16 MHz with 2 MiB RAM, a 24-bit address bus, a 16-bit data bus, 256 KiB VRAM, and a nominal pre-divisor budget of 800,000 cycles per 20 Hz tick. Production applies the configured admission divisor. Its 800x480 physical VGA LCD centers guest modes up to 640x480; its narrower bus and 80386-derived timing are active execution constraints rather than display-only labels.

14.1 Boot sequence

  1. Mount C:. Restore the persisted, quota-limited guest filesystem and reset C:\TEMP.
  2. Plan CONFIG.SYS atomically. Parse at most 64 lines, resolve every expected versioned CS-DOS driver capsule, validate dependency order, and trial the complete memory map before committing any directive. Any error discards the whole plan, reports bounded diagnostics, and selects the explicit 64 KiB degraded-low profile; earlier valid lines never survive as partial state.
  3. Run AUTOEXEC.BAT. Execute it through the same bounded batch engine even after a degraded CONFIG boot.
  4. Present the prompt. Start at C:\>; PROMPT, current drive, environment, and PATH are now active.
DEVICE=C:\DOS\HIMEM.SYS
DEVICE=C:\DOS\EMM386.EXE NOEMS
DOS=HIGH,UMB
FILES=32
BUFFERS=16

The supported CONFIG.SYS surface is deliberately narrow: FILES=1…255, BUFFERS=1…99, DEVICE/DEVICEHIGH for the built-in HIMEM and EMM386 models, and DOS=HIGH|LOW,UMB|NOUMB. These settings configure the guest manager; they never execute host drivers or persist derived CONFIG_* environment variables. DEVICEHIGH tries one contiguous UMB block, then loads low with an explicit diagnostic when no such block fits.

14.2 The 2 MiB memory map

RegionAddress rangeNominal sizeUse
Conventional0–639 KiB640 KiBDOS-compatible resident state and guest program working set
Reserved video aperture640–767 KiB128 KiBNot allocatable
Upper memory blocks768–895 KiB128 KiBAvailable with HIMEM, EMM386 NOEMS, and DOS=UMB
Reserved ROM aperture896–1023 KiB128 KiBNot allocatable
Extended / XMS1–2 MiB1024 KiBExposed by HIMEM; HMA is its first 64 KiB, never extra capacity
MEM
MEM /C
MEM /D
MEM /F
REM MEM /P is explicitly unsupported

Every MEM variant reads one immutable boot-manager snapshot; there is no fallback calculation. /C lists category/module residency and actual placement, /D lists manager flags and boot diagnostics, and /F lists actual free extents and largest contiguous blocks. Snapshot work is bounded O(active allocations + free extents) and never grows with filesystem contents or RAM bytes.

14.3 Processor and protected mode

CPU reports the 24-bit address bus, 16-bit data bus, 16 MHz clock, and modeled real/protected/virtual-8086 capability. Guest execution currently runs inside the protected sandbox. EMM386 NOEMS supplies the DOS-visible UMB/v86 compatibility model; EMS page-frame mapping is deferred. Paging, native descriptor tables, ring transitions, BIOS interrupts, DOS interrupts, TSR residency, and arbitrary x86 opcodes are not emulated. The declared cs-flat32-v1 memory contract is a Computer System ABI, not DPMI.

14.4 AUTOEXEC and environment

@ECHO OFF
PATH C:\DOS
SET TEMP=C:\TEMP
SET INCLUDE=C:\INCLUDE
CommandContract
SET [NAME[=VALUE]]List, query, assign, or remove a case-insensitive environment variable
PATH [directories]Show or replace up to the first 16 semicolon-separated search entries
PROMPT [template]Set at most 64 characters; $P $N $G $L $B $Q $V $_ $$ are recognized
ECHO ON / OFFControl batch command echo; a leading @ suppresses one line
REM textComment with no output or side effect

DOS pipelines are sequential: each edge is a uniquely owned strict-8.3 spool under C:\TEMP. A producer completes into the guest filesystem before the next stage starts; consumed spools are deleted as the pipeline advances, and setup, quota, interruption, disconnect, or reboot cleanup never uses a host temporary file. C:\DOS\MORE.COM accepts one file, redirected stdin, or pipe input as the final interactive stage. DIR | MORE, TYPE file | MORE, MORE file, and MORE < file are supported; LESS and Linux-only fd syntax are not.

14.5 Batch programs

@ECHO OFF
REM C:\TOOLS\BUILD.BAT
ECHO SCRIPT=%0
ECHO SOURCE=%1
CC %1 -O %2
ECHO STATUS=%ERRORLEVEL%

A command without a path is resolved in the current directory and then PATH; the .BAT suffix may be omitted. CRLF and LF are accepted. Batch substitution supports %VAR%, %0 through %9, and %ERRORLEVEL%. Labels, GOTO/GOTO :EOF, internal and external CALL, SHIFT, IF [NOT] ERRORLEVEL, IF [NOT] EXIST, and COMMAND /C or /K use the dedicated bounded BAT engine. Unquoted Unix-style && and || chains are rejected inside BAT control flow. Ordinary <, >, >>, and | remain documented safe-shell extensions, not claims of native COMMAND.COM semantics. MORE is terminal-control work and is rejected in this synchronous BAT path.

BoundLimitFailure
Batch lines / labels256 / 256Explicit line or label status
Call depth / positional arguments8 / 9Explicit depth or argument status
Jumps / executed steps1,024 / 4,096Explicit control-flow status
Loaded programs64Explicit program-load status
Expanded command / output4,096 / 256,000 charactersExplicit bounded-output status

CHOICE and PAUSE are terminal-owned BAT commands: each suspends the bounded script once, resumes after one accepted key, and writes CHOICE selection as one-based ERRORLEVEL. Ctrl+C ends the command or batch with status 130. CHOICE /T and native COMMAND.COM binary behavior are not implemented. Missing or duplicate labels, recursion, and exhausted bounds terminate explicitly without invoking a host or native DOS process.

14.6 Command correspondence

TaskLinuxDOS
List / readls / catDIR / TYPE
Page one file or stdinless / moreC:\DOS\MORE.COM
Directory tree / volumefind / dfTREE / VOL / LABEL / CHKDSK
Attributes / metadatachmod / statATTRIB / DIR /A
Edit full screenviEDIT / VI
Create / remove directorymkdir / rmMD / RD (CHDIR and RMDIR aliases)
Copy / move / renamecp / mvCOPY / MOVE / REN or RENAME
Remove filermDEL or ERASE
Clock / measurementdate / timeTIME / TIMER
HistoryhistoryDOSKEY /HISTORY
Clear / versionclear / unameCLS / VER
Hardwarecpuinfo / freeCPU / MEM, MEM /F
System summaryuname -aSYSTEMINFO

DOS-facing commands and errors use CRLF and DOS-specific wording. Commands and paths are case-insensitive, but every directory and file name follows strict 8.3 form: a 1–8 character base plus an optional 1–3 character extension. Invalid long names fail explicitly and are never silently truncated. Backslash is preserved as the displayed separator. Normal DIR prints separate eight-character base and three-character extension columns, aligns <DIR> or a locale-independent comma-grouped size, and follows it with MM-DD-YY and a space-padded 12-hour a/p time. Totals and free bytes use the same comma grouping. DIR /B produces a bare listing and DIR /W retains its wide layout; DIR /A[:attributes] filters persisted FAT metadata; TREE [/F] [/A] is an O(N) traversal capped at 512 entries and 32 levels. CHKDSK never changes guest file contents, labels, or attributes and never repairs a volume, but it may materialize missing versioned FAT metadata while reconciling a legacy entry. C:\TEMP is volatile across boot. NUL and CON are bounded compatibility sink devices; CON is not a raw host console.

14.7 Drives, wildcards, FAT metadata, and floppy limits

The DOS runtime owns exactly A: and C:. C: contains the persistent system volume. A: reflects the removable Floppy Disk item in the physical bay; an empty bay reports Not ready. Each drive keeps its own current directory. FORMAT A: creates FAT12, FORMAT A: /S creates a bootable system disk, SYS A: transfers the system to an existing formatted disk, and EJECT [A:] returns the item. A bootable disk takes CSBIOS priority unless one-shot safe boot was requested. A Linux-installed Computer then runs temporary A:-only DOS with no C: and without changing its Linux filesystem or OS snapshot.

FORMAT A: /S /V:BOOTDISK
DIR A:\
COPY C:\WORK\README.TXT A:\README.TXT
EJECT A:

CD C:\WORK
DIR *.TXT
COPY *.TXT C:\BACKUP
REN *.BAK *.OLD
ATTRIB +R +H SECRET.TXT
DIR /A:H
LABEL C: PROJECT
CHKDSK C:

The removable volume has 2,880 512-byte sectors, two FAT copies, a 224-entry root directory, strict 8.3 names, cluster allocation, fragmentation-aware LBA extents, and FAT UTC timestamps clamped to 1980-2107 at two-second precision. The shipped DOS * and ? traversal examines at most 512 entries, returns at most 512 matches, and stops recursion at 32 levels. Every file retains R/H/S/A metadata and read-only enforcement. ATTRIB /S is bounded; LABEL is generation-bound; CHKDSK reports state without repair.

The current CS-DOS v10 image adds C:\DOS\CHOICE.COM, COMP.COM, FC.EXE, FIND.EXE, PAUSE.COM, and SORT.EXE, while CS-Linux is rootfs v20. Older immutable definitions, including DOS v8, remain registered so overlays migrate without duplicating base data or replacing customized and tombstoned files. Linux v6 retains the prior WorkBench image, DOS v5 retains CS QBASIC 1.0 without the WorkBench launchers, and earlier immutable bases remain readable. Cold DOS persistence preserves C:, labels, attributes, and timestamps but never serializes an inserted A: location into the machine snapshot; media content has its own transactional world record.

Linux vfat mounts are root/sudo-only and use fixed uid=1000,gid=1000,fmask=0133,dmask=0022. Files appear as 0644 and directories as 0755. FAT has no DAC ownership, hard links, or symbolic links, so chmod, chown, and link creation fail explicitly.

14.8 Local bus commands

ECHO HELLO>COM1
TYPE COM1
SPI 1 0 9F0000
I2C 1 SCAN
I2C 1 72 00 2

COM1 through COM6 are the six machine-relative RS-232C ports and work with redirection and TYPE. SPI accepts a one-based bus, chip select, and hexadecimal byte pairs. I2C accepts a one-based bus plus SCAN, or an address, write bytes (use - for none), and read length. These commands are valid in bounded batch files. A missing neighbor, unattached peripheral, NACK, address conflict, full queue, or powered-off endpoint returns a nonzero explicit status.

14.9 Portable toolchains

REM Product identity
ASM /VERSION
CC /VERSION
C++ /VERSION

REM Command-line build
ASM ANSWER.ASM /OUT:ANSWER
RUN ANSWER /STATS
ASM /C ANSWER.ASM /OUT:ANSWER.O
LINK ANSWER.O /OUT:ANSWER /ENTRY:START
CC TOTAL.C -O TOTAL
C++ ANSWER.CPP -O ANSCPP

REM Full-screen WorkBench
CSASM ANSWER.ASM
CSCC TOTAL.C
CSCPP ANSWER.CPP
PWB ANSWER.CPP

QBASIC DEMO.BAS
QBASIC /RUN DEMO.BAS

CS ASM 1.0 keeps AS/LD available, while ASM/LINK provide DOS-friendly aliases. The assembler accepts CRLF source, relative INCLUDE, PUBLIC/EXTRN, .CODE/.CONST, and bounded name MACRO ... ENDM forms. It deliberately rejects ORG, INT, segment models, and other constructs that would imply native OMF, COM, EXE, BIOS, or DOS-interrupt execution.

CS ASM 1.0 and the supported CS C/C++ 1.0 subsets share a full-screen File/Edit/View/Search/Make/Run/Debug/Options/Help WorkBench. F7 builds one source or the selected Program List, Ctrl+F7 rebuilds it, F3/Shift+F3 navigate F4 diagnostics, Ctrl+F5 runs the exact last non-stale artifact, and F5/F8/F9 debug inside WorkBench. CS QBASIC instead shows File/Edit/View/Search/Run/Options/Help: F5, Ctrl+F5, Shift+F5, and /RUN run source transiently and create no OBJ, CSX, or EXE. The guest C/C++ include roots stay inside the DOS filesystem. DOS C/C++ options include /I,/D,/U; the same guest preprocessor handles headers and macros on Linux and DOS. DOS compile-only and executable defaults are same-basename .OBJ and .CSX, not a.o/a.out.

This recognizable period-DOS workflow is original Computer System code; it is not Microsoft C/C++ 7.0 or Programmer's WorkBench binaries, artwork, help, OMF output, or native runtime. The linker applies the same typed-symbol, structured-relocation, section-size, object-count, and RAM bounds as CS-Linux. Each run uses CS386SX timings, its 16-bit external bus, and the 2 MiB limit. MicroPython commands and /startup.py are unavailable on Portable; MCP returns status 127 instead of silently using a different VM.

14.10 Instruction debugger

DEBUG ANSWER
BP MAIN
G
R
U MAIN 8
D 0 16
T
G 1000
Q

The WorkBench Debug menu and the optional DEBUG command expose the same bounded CS486 instruction debugger; csdb is the CS-Linux command spelling. It loads only validated CS486 executables, treats unprefixed DOS addresses as hexadecimal, and uses CRLF output. BP/BC manage breakpoints, T steps one instruction, G continues with an optional bounded instruction count, R reads registers, U disassembles, and D reads memory without modifying it.

This command is not native DOS DEBUG emulation. It cannot write memory, run COM/EXE files, reconstruct C/C++ source variables, or invoke BIOS/DOS interrupts, PIC, IRQ, or IDT behavior.

14.11 C++ exercise

REM ANSWER.CPP
int main() {
  int answer = 6 * 7;
  std::cout << answer << std::endl;
  return 0;
}

C++ ANSWER.CPP -O ANSWER
RUN --STATS ANSWER

Record output, instructions, and cycles. On the 16-bit external bus, memory traffic and output can dominate. Reduce the algorithmic term first, then repeated loads, taken branches, division, and PRINT traffic.

14.12 Linux memory comparison

Portable DOSDesktop Linux
640 KiB conventional + two reserved apertures + UMB + XMS32-bit protected flat sandbox
Inspect with CPU, MEM, MEM /C, MEM /D, MEM /FInspect with cpuinfo, free, /proc/cpuinfo, /proc/meminfo
One boot manager owns system, drivers, and exact process grantsLedger owns kernel, services, buffers, and guest runtime grants
HMA is inside XMS; HIMEM, EMM386 NOEMS, and DOS HIGH/UMB are modeledResident OS overhead plus dynamic used/free/available are reported
No EMS paging, DPMI, or native interrupt executionBounded process table; no paging, swap, or MMU page emulation

Chapter 15 · Service information

Faults are explicit terminal outcomes

Every stateful path assigns a final owner. Crashes, cancellation, disconnect, retry exhaustion, shutdown, reboot, and bounded yields remain observable.

15.1 Start from the observed symptom

SymptomCheckRecovery owner
Web Terminal cannot accept inputCheck writer/viewer, out_of_range, and connection number activation.Take control, return to range, or touch the Computer and reconnect once.
CS-Linux stops before the promptCheck first-boot cs password setup, later username/password login, locked-account state, and startup failure.Complete authentication. For a broken /startup.py, stop retries. When lifecycle is crashed, sneak while opening the Computer or use the attached Web Terminal's safe-boot power control. Repair from that one boot; the broken file is preserved until you edit it.
Machine is crashed with an unreadable screenOpen the Computer or attach the Web Terminal and read the halt screen: the Boot Error row names the failing phase and the Reason rows carry the exact message. The block face stays dark by design because a fault releases VRAM, and a halted machine shows no cursor.Follow the machine-specific recovery on the last screen row: safe boot from the sneaking in-game action or the Web Terminal power control. A full journal is no longer a failure source; it rotates.
Program is not found or does not startCheck OS profile, path, filename rules, executable/object format, execute permission, and status 127.Use an explicit permitted guest path or the toolchain for the active profile.
Permission deniedCheck id, groups, owner/group/other mode bits, ancestor traversal, and the active umask.Correct ownership or mode through a permitted account; do not bypass the credentialed filesystem.
Program is slowCheck hidden polling, repeated output, run --stats, cache/bus counters, and the dominant O(N) term.Bound or deduplicate repeated work before changing machine limits.

15.2 CS486 faults

FaultCauseCorrection
ExecutableFormatErrorBad header, opcode, operand, register, section, symbol, relocation, or targetReassemble; inspect the source artifact
MemoryAccessError32-bit access outside configured RAMCorrect address and allocation math
DivisionByZeroErrorDIV or MOD divisor is zeroGuard the divisor
StackOverflowErrorPUSH/CALL crosses the aligned static-data floorReduce nesting, stack use, or linked static data
StackUnderflowErrorPOP/RET starts above the last addressable stack wordKeep ESP at or below the top-of-RAM boundary
OutputLimitErrorProgram exceeds bounded outputSummarize or batch output

ESP remains a general register: moving it to an in-range address can make POP read that RAM word, even when no PUSH produced it. The runtime guarantees RAM and static-data boundaries, not stack-word provenance. RET additionally validates the popped instruction target. An instruction pointer below zero or beyond the executable range faults; only the exact instruction immediately after the program is a normal fall-through completion.

15.3 Shell statuses

StatusMeaning
0Successful completion
1Ordinary command failure / false result
2Usage or explicitly unsupported option
124CS486 instruction bound reached; yielded
127Command not found for the active OS profile

15.4 Instruction debugger and diagnostic sequence

CS-Linux debugger

csdb program
break main
continue
regs
disasm main 8
memory 0 16
step
continue 1000
quit

General inspection

cpuinfo
free -h
quota
nm program
objdump program
run --stats program
echo $?

csdb pauses only at CS486 instruction boundaries. It can set and clear address or symbol breakpoints, step, continue, read registers, show validated disassembly, and read memory without modifying it. A request is capped at 256 breakpoints, 100,000 continued instructions, 256 disassembled instructions, or 4,096 memory bytes. Hitting a breakpoint, halting, faulting, exhausting the requested limit, interruption, and quit are distinct terminal outcomes; logout, user switch, and terminal disconnect discard the debugger state.

15.5 OS presence diagnostic sequence

  1. Run ps -f, jobs, who, and service --status-all.
  2. Read /proc/loadavg, the relevant PID's status, and /proc/mounts.
  3. Compare dmesg, /var/log/messages, and /var/log/auth.log under permitted credentials.
  4. Run sync before a requested stop when preserving an explicit checkpoint matters.
  5. After reboot, use last and the retained journal to confirm the prior terminal transition.

Expect: Process, job, session, service, proc, and log views agree because they render one bounded per-Computer state. A failed sync or shutdown phase faults explicitly. Host BDS logs remain outside these guest files.

15.6 CS-DOS recovery checklist

  1. Run VER, CPU, MEM /D, and read-only CHKDSK C:.
  2. Inspect TYPE C:\CONFIG.SYS and TYPE C:\AUTOEXEC.BAT.
  3. Use SET, PATH, PROMPT, VOL, and ATTRIB to confirm boot and FAT state.
  4. Use an explicit path if a BAT or compiled program is not found.
  5. Correct every boot warning; unsupported directives are never silently accepted.

Verify: Reboot once after the correction and inspect every boot line, label, attribute, and timestamp.

Expect: Startup reaches C:\> or stops at one explicit, actionable failure. CHKDSK reports but never repairs, and A: remains not ready without inserted media.

15.7 Storage migration after an update

An older world may pause Computer interactions while BDS converts indexed Dynamic Property pages and inline filesystem files. Progress is reported as CS_STORAGE_MIGRATION. Each Computer is written and verified before a legacy identity registry is switched, so an interruption keeps the older complete generation readable and the next start safely resumes by rescanning and skipping completed Computers. The same scan runs when the identity pages are already current: changed Computer payloads are saved and reload-verified, while a healthy current identity head remains unchanged. If a current-format Computer or identity head is invalid but its previous generation validates, that recovered value repairs the head and must reload without fallback before migration completes. A valid head is also retained when its previous manifest is corrupt. Recovery repairs or removes that invalid fallback metadata and incrementally removes target-only content blobs, legacy indexed pages, and stray manifests that corrupt metadata can no longer name. This whole-prefix search runs only during repair; ordinary saves never enumerate every stored page. Page-count or manifest-length overflow is rejected before a generation changes storage.

When the recognized legacy CS-Linux default account is present, boot also completes the computer-to-cs account and home migration described in Chapter 5. This is a rename, not an alias: the old passwd/group/shadow name and /home/computer disappear after success, while the exact password payload and filesystem data/metadata/link identities remain intact.

Optional OS-runtime fields migrate independently and idempotently. Linux restores only cold journal, last-login, service/mount definition, and offline-device state; it never revives a process, job, active mount, or authenticated session. DOS preserves C: drive/label/FAT metadata, activates C:, and always detaches transient A: media and stale generation metadata. Current CS-DOS v7 and CS-Linux v7 images remain compatible with every registered immutable base, including the pre-QBASIC DOS v4 and pre-removal Linux v5 images.

  1. Stop BDS before copying or restoring a world; never copy a live LevelDB directory.
  2. Back up the complete world directory before the first start with a storage-format update.
  3. Start BDS and wait for the migration-complete message before using Computers or running headless probes.
  4. If migration fails, stop BDS, preserve the logs and failed world, then restore the stopped backup or correct the reported corrupt property.

Verify: Find a terminal CS_STORAGE_MIGRATION record with state equal to complete, then inspect the same Linux and DOS Computers after two starts.

Expect: The Computer ID, OS profile, hardware, terminal state, password payload, guest files, modes, ownership, mtimes, symbolic links, hard-link identities, tombstones, Linux cold history, and DOS C: metadata are unchanged except for the complete user/group/shadow and home-path rename. No live Linux process/session or A: media is resurrected, and a second boot performs no further migration.

15.8 Future network-state migration

The optional network-state boundary remains absent from an empty OS snapshot, so a preserved legacy Computer and a new Computer with no guest NIC have the same canonical shape. If a future adapter registers interfaces and addresses, cold restore retains those definitions but forces every link down, resets counters to zero, and removes all process-owned sockets and listeners. A second cold projection is identical.

This boundary owns at most eight interfaces, 32 addresses, and 64 sockets. It is not packet transport: no default lo or eth0, route table, DNS resolver, ip, ping, or ss ships in this release. Web Terminal connectivity remains host transport.

Chapter 16 · Technical appendix

Limits, units, and terminology

A limit is part of the programming model, not an exceptional host failure. Design programs so every ceiling has a useful observable outcome.

16.1 Future network-state limits

StateDefault ceilingCold restore
Interfaces8; name at most 15 UTF-8 bytesDefinition retained, link down, counters zero
IPv4/IPv6 addresses32Definition retained
TCP/UDP sockets and listeners64; backlog at most 128All removed

This empty-by-default state is reserved for a future network adapter. It creates no guest NIC and routes no packets. No network command can inspect it in this release.

16.2 Canonical compatibility matrix

CapabilityCS486DX desktopCS486DX2 advancedCS386SX portable
Default OSCS-Linux 1.0CS-Linux 1.0CS-DOS 1.0
Computer System PythonSupportedSupportedNot available
CS ASM 1.0 / CS C/C++ 1.0SupportedSupportedSupported
CS QBASIC 1.0Not availableNot availableSupported subset; see Chapter 16
Web Terminal displayBuilt-in CRT; placedBuilt-in CRT; placedBuilt-in LCD; held or placed
Maximum guest display640x480x8640x480x8640x480x4

This matrix is the canonical quick compatibility lookup. Profile chapters explain behavior; they do not broaden a capability marked unavailable here.

16.3 Independent resource ceilings

ResourceMeasured asInspect with
CPUInstructions and modeled cyclesrun --stats, time, cpuinfo
RAMLive VM values and CS486 memoryfree -h, /proc/meminfo
DiskPersisted file bytes and entriesdf, du, quota
Processes / jobs64 / 32 per Computer by defaultps, jobs, /proc/loadavg
Sessions / last logins8 active / 64 retained, oldest-first rotationwho, w, last
Services / mounts / devices32 / 16 / 64 recordsservice, mount, /proc/devices
Inittab / crontab entries64 lines eachrunlevel, telinit, /etc/init.d, /etc/crontab
Journal256 records, 32 KiB total, 1 KiB each; oldest-first rotationdmesg, /var/log/messages, auth.log
DOS FAT metadata4,096 records; 255-character normalized pathATTRIB, DIR /A, LABEL, CHKDSK
TerminalRows × columns and bounded outputterm.get_size()
EventsQueued records and wait ownershipProgram diagnostics
SchedulerPer-machine and global tick workcpuinfo, run --stats
Stopping200 ticks per phase; 16 Computers advanced per host tickmessages journal and PWR/HDD state

16.4 Terms

TermDefinition
Computer identityStable id binding block, item, storage, terminal, and runtime state
GuestCode executing inside the sandboxed machine
HostBDS, Minecraft, and the companion processes outside the guest boundary
Cycle debtModeled work awaiting fair scheduler service
Writer leaseExclusive authority for one Web Terminal session to submit input
Terminal stateExplicit completion such as success, fault, cancel, close, shutdown, or yield

16.5 Quick diagnostic card

whoami             # identity and user
uname -a           # OS profile
cpuinfo            # modeled processor
free -h            # memory use
df                  # filesystem capacity
quota               # guest disk limits
history             # recent commands
echo $?             # previous status

16.6 Canonical numeric ceilings

ResourceCeilingObservable outcome
Direct CS486 run10,000 instructions per bounded direct runStatus 124 / yielded
CS-DOS batch256 lines; nesting depth 8Explicit line-limit or depth status
CONFIG.SYS64 linesExplicit unsupported or invalid directive
CS-Linux pipe / redirects4 KiB per edge / 16 redirects per stageBackpressure or explicit syntax/setup failure
Linux live pager history64 KiBExplicit pager input limit
DOS pipeline spool/outputGuest disk quota / 256,000 charactersCleanup plus nonzero ERRORLEVEL
DOS TREE512 entries; 32 levelsExplicit traversal limit
Manual search24 section resultsHighest-ranked bounded results

16.7 Command, API, instruction, and error indexes

LookupPrimary chapterExamples
Commands04 CS-Linux shell; 14 CS-DOSls, grep, DIR, MEM /F
Python API08 API referenceos.pull_event, term.write, redstone.set_output
Instructions10 Assembly languageLOAD, STORE, CALL, RET
Errors and statuses15 DiagnosticsMemoryAccessError, 124, 127, out_of_range

Manual search returns the matching section with a type, applicability, and bounded snippet; use these chapters when the exact contract matters.

16.8 Reading paths

GoalChapters
First program01 → 02 → 03 → 05
Python + Redstone01 → 02 → 03 → 05 → 06 → 07
CS-Linux operator01 → 02 → 03 → 04 → 15
Native development01 → 03 → 09 → 10 / 11 / 12 → 13
Portable / CS-DOS01 → 02 → 14 → 09 → 10 / 11 / 12
Diagnose a problem15 → 16