Skip to content

Bashcrawl architecture

The component map behind AGENTS.md: where every part of the dungeon, the TermForge framework, the game engine, the React web app and the tooling lives, what each owns, and the web app's design rules.

AGENTS.md holds the rules an agent must follow; this file is the detail behind them. The five-layer model, the learning loop and the alignment with bashOS and chui are in PLATFORM.md. TermForge's own module map, dependency rules and host contracts are in termforge/architecture.md.

Dungeon layout

The filesystem is the game. Main path: entrance/ β†’ cellar/ β†’ armoury/ β†’ chamber/.

Hidden areas (all rooted under entrance/) are unlocked by collecting treasures, which mv a dotted directory to its visible name:

  • .chapel/ β†’ graveyard/, courtyard/{aviary,hall,library}/ β€” grep, find, pipes
  • .vault/ β†’ stronghold/{nursery,lab}/ β€” variables, env, process substitution
  • .scrap/ β€” a directory (not a file) whose scroll teaches ln -s
  • .rift/ β†’ arena/pit/, spire/mezzanine/ β€” advanced scripting, checksums
  • entrance/workshop/ β€” does not exist until the player runs mkdir (player-created room)

Game encounter files

All game executables share a structure: #!/usr/bin/env bash shebang, the 14-line "wandered out of bounds" boilerplate comment, game-state checks (grep inventory / test $HP), story output via cat << EOF heredocs (plain text, no ANSI), then instructions telling the player to run export/mv commands. Game executables must never mutate git-tracked files and do not use strict mode.

State is held entirely in environment variables and untracked flag files:

export I=amulet,$I              # Inventory: comma-separated env var
grep --quiet amulet <<< "$I"    # Check for an item
export HP=15                    # Health (set by potions)
let "HP=HP-5"                   # Combat damage
touch .statue_defeated          # Non-destructive "defeated" flag, checked on re-entry
mv ../../.chapel ../../chapel   # Unlock a hidden room (target may be 2+ levels up)

Terminal-core and content

Component Purpose
entrance/.functions Defines gameover() and help(); each encounter script sources it itself.
help.sh Root shim that execs src/help.sh (sources src/help/bashcrawl_help.sh).
src/help/ Bash help engine; YAML content registries in src/help/data/.
lib/ Minimal shared shell libs: colors.sh, log.sh (JSONL), yaml_reader.sh, reset.sh.
setup.sh chmods encounter scripts (--quick for tooling/tests).
bin/bashcrawl The optional launcher / dispatch table (bash 3.2-compatible, shellcheck-clean); doctor follows bashOS's bin/os-health verdict format.
courses/ Courses: course.md + NN-lesson.md (frontmatter objectives with a solution each) + lab/ files seeded at /lab/<id>/. Compiled by scripts/course_loader.py.
motion/ All art is ASCII Motion files (.asciimtn, editable at ascii-motion.app): clips/ (command-stage animations), art/ (banner, encounter portraits, room vignettes β€” multi-frame ambient loops β€” arena/levelup/profile/pathfind, the landing logo reveal, the Arcade and Reference door headers). Registered in src/help/data/motion.yaml; scripts/build_motion.py (in make web-build) bundles them into web/assets/js/{fx-clips,art-clips}.js + termforge/core/art.js. Code draws art only via Shell#art(name) / <ArtClip name> β€” never string literals (termforge/test/art.test.js scans web/src too). Workflow: docs/termforge/ascii-motion.md.

TermForge

Component Purpose
termforge/core/ The TermForge kernel (source of truth): parser, vfs (+ read-only providers), shell (hook spine, injectable clock/rng, owns an EventBus, use(plugin)), packs/{posix,flavour}, protocol, view, sinks/{dom,ansi}, input, ascii-motion (plays every ASCII Motion format incl. session v2, editor effects, Library), art (generated from termforge/motion/*.asciimtn by scripts/build_motion.py). Platform services: events (typed bus), rules (declarative predicates), plugin (shell.use), and the learning plugins curriculum, mastery, explain. Dual-mode files, vendored to web/assets/js/vendor/termforge/. Schemas: docs/schemas/{events,rules,plugin}.v1.md.
termforge/node/ Node hosts: host-tty.js (full-screen HUD via the session.hud() contract, or classic stream with --no-hud/piped stdio; damage events jolt the frame), tui.js (TuiScreen: app-agnostic ANSI compositor β€” sidebar panels, toast row, input row, host-driven jolt offset), pixels.js (PixelBuffer + PixelScreen: a colsΓ—(2Β·rows) truecolor framebuffer painted with half-block cells, pixel font, row-diffed output), gem.js (the hidden gem: DAEMON STORM, a pixel shooter β€” xyzzy/plugh/Konami in HUD mode; fixed 50 ms tick, seeded RNG, BASHCRAWL_GEM_SEED pins a run; zero deps), host-telnet.js + telnet-codec.js (RFC 854 subset), index.js (framework namespace for require()).
termforge/node/hub.js The telnet hub (host-telnet.js --hub): presence, room/global chat, leaderboard, event announcements; sanitizes control/escape characters and rate-limits. Opt-in β€” the default server stays isolated.
termforge/apps/ registry.js (the app registry: --app ID resolves here, --app list prints it), bashcrawl.js (the game as an App descriptor for the hosts), procwatch/ (custom-tool reference: live metrics as provider files), agentwatch/ (AI-agent task dashboard: TaskSource β†’ board/feed + live files; JSONL adapter for logs/sessions/).
termforge/test/ node --test suites incl. golden transcripts (pixel-identity contract; regenerate only via record-goldens.js --update) and the telnet loopback integration.

The game engine (web/assets/js/)

Classic/CJS scripts shared by the browser, the node hosts and the node test harness β€” never ES modules, never compiled by Vite. Their fixed <script> load order is the first of the web app rules.

Component Purpose
web/assets/js/runtime.js The bashcrawl game assembly over TermForge: class Runtime extends TermForge.Shell, the full this.handlers literal (the validate_runtime_commands.py regex contract β€” one key: ref, per line, bare references only), and installGameHooks() (quests/achievements/daily/trainer/pathfind/encounters).
web/assets/js/plugins/ The game's features as TermForge plugins (achievements, daily, progress, arena, pathfind, bestiary, nudge), installed by runtime.js in GAME_PLUGINS order (postExecute order matters: achievements β†’ daily β†’ rank-up β†’ the nudge plugin's "Stuck?" line after three failed command lines in a row, counted in state.stats.errorStreak). Catalogs come from src/help/data/progression.yaml.
web/assets/js/hud.js The shared HUD presenter (one engine, two renderers): status strip, next-step suggestions, side quests, fog-of-war map model, HP/XP, room/quest/hero/lesson/skills models (the quest model evaluates each quest's steps checklist rules), diffEvents() (including one quest-step per newly ticked step) and the layout store β€” consumed by the React HUD (web/src/hud/) and the TTY host (tui.js panels). Loaded like runtime.js: classic script in the browser, require()'d by termforge/apps/bashcrawl.js.
web/assets/js/fx.js The command FX catalog (BashcrawlCommandFx): parses a line into {cmd, flags, motion, accent, piped, redirect}, stamps data-fx-* on the stage and plays the ASCII Motion stage clips for those motions (manifest from motion.yaml via fx-clips.js). Required by the TTY/telnet hosts (termforge/apps/bashcrawl-motion.js); the React effects layer calls apply() per command.
web/assets/js/learn.js The lesson Markdown renderer (BashcrawlLearn.renderMarkdown/inlineHtml): the subset courses use, escaped, with click-to-fill code. The reader over it is React (web/src/learn/LessonReader.tsx).
web/assets/js/ambient.js Ambient ASCII Motion (BashcrawlAmbient): plays .asciimtn clips in a node β€” room vignettes loop, the landing logo reveals once. Visibility-aware, stops when the node is detached, paints the resting frame under prefers-reduced-motion; cells in the clip's default colour (#ffffff) inherit the CSS colour. Wrapped by web/src/fx/useAmbientClip.ts and ArtClip.tsx.
web/assets/js/arcade.js The arcade's games (BashcrawlArcade.GAMES: Path Navigator, grep/find Hunt, Pipe Puzzle, Command Flash β€” seed world + goal predicate + scoring over a scoped bare Runtime β€” and the Vim Catacombs, whose world is a vim buffer) plus CHEAT_LINES, BLOCKED_IN_GAME, scopedRuntime. The flow (start/hint/quit/finish/records) is web/src/arcade/arcade-store.ts.
web/assets/js/vim.js BashcrawlVim, the modal editor behind the Vim Catacombs: a deterministic vim engine (normal-mode motions, counts, operators d/y/c, a register, u, f/t/;/,, literal / search with wrap, insert mode) fed one key at a time, with an allowed set β€” the level's spellbook β€” it refuses early. Knows nothing of gems or levels: arcade.js reads the buffer after each command (* gem taken on landing, ! spike costs a heart, target an exact buffer, won only from normal mode). Levels are arcade.yaml vim_levels (keys cumulative in file order; each carries a solution in vim notation β€” <esc>, <cr>, a /text run β€” that termforge/test/arcade-vim.test.js plays and must win at exactly par). Keys reach it through InputTarget.keystroke (the PromptBar offers every plain key to the owner first; : and / are left to the prompt in normal mode); the buffer is drawn by web/src/arcade/VimStage.tsx above the trial log. Dual-mode like hud.js.

The React app (web/src/)

Component Purpose
web/src/app/ The React shell: App.tsx (providers, route β†’ screen, app-wide keys, boot), AppShell.tsx (skip link, header with mode tabs and settings, one <main id="main-content">, the #stage shake wrapper, footer), useHashRoute.ts (#/story … #/reference, NotFound), modes.ts.
web/src/engine/ The engine bridge: types.ts (typed surface of the globals), index.ts (requireEngine()), game-store.ts (owns the Runtime, TerminalView + DomSink, SessionController, save/restore/reset, presenter models memoised per version, useSyncExternalStore; one instance per page, registered on globalThis so HMR never splits it), fx-bus.ts (what a command changed, published once), data.ts.
web/src/terminal/ The one shared prompt (PromptBar: Enter/↑↓/Tab/Ctrl+L/Ctrl+C/?/Ctrl+/; its label, from prompt-label.ts, trims the path from the left so the room stays visible β€” ~/chapel/…/.study $, just .study $ on narrow screens), TerminalLog (a <pre> the engine's DomSink paints; React never touches its children β€” a click on a data-fill command types it), the reader layer (prose.ts: a per-line classifier for what a file viewer printed; log-decor.ts: the DOM pass after each paint β€” command echoes, prose, code chips in runtime hints, the .rv/--i cascade, and placement, which opens a block taller than the log at its title), ScrollCue ("β–Ό more"), SuggestionChips (fill, never run), InlineHint, the Pager for less (formatted by the same classifier), actions.ts (run/fill/goto/try β€” every chip goes through here), prompt-store.ts.
web/src/hero/ The hero: hero-store.ts (name, path, appearance, tour taken β€” bashcrawl-web-hero-v1, kept apart from the engine's save; whoami knows nothing of it), roles.ts (the four paths), appearance.ts (the wardrobe catalogue β€” skin, eyes, hair style/colour, headgear, outfit, dye, trim, weapon, cape, companion β€” role presets, a random roll, the sanitiser, and paletteStyle() which hands the picks to CSS as --hero-* token references), sprite.ts (the 16Γ—28 pixel character: part bitmaps of colour slots composed in layer order into runs; the bitmaps are template literals and art.test.js exempts them like gem.js), HeroSprite.tsx (one <g> per layer, one <rect> per run; crop="bust" for the header), HeroFigure.tsx, AppearanceEditor.tsx (the wardrobe UI), CreateHero.tsx (the five-step wizard β€” a path dresses the hero in its preset until the wardrobe is touched), ProfileDialog.tsx (rename, wardrobe, path, the sheet, a confirmed new game through GameStore.newRun()), HeroButton.tsx. The hero's colours are art tokens (--bc-hero-* in tokens.css, the same in both themes); shades are derived in hud.css with color-mix.
web/src/chrome/ The shell's chrome and the game's own screens: TitleScreen (Continue Β· New game/New hero Β· How to play Β· Options; ↑↓/Enter/Esc, a menu cursor), Intro (three overview pages, seen once β€” prefs.introSeen), Tour (coach marks over the live page; a stop whose target has no size is skipped; the last one types pwd), OptionsDialog + SettingsForm (theme, sound, effects, shake, text speed/size, CRT), settings-store.ts (bashcrawl-web-settings-v1, applied as data-* on <html>), GameMenu (the pause menu: Escape with nothing open, Alt+M, menu), Tooltips (one tooltip layer for every title= β€” the title moves to data-tip + aria-description on first hover, so write tooltips as title and nothing else), ui-store.ts (which overlay is up, the tour step, isIdle()), the docs drawer, toasts, shortcuts help, the error boundary.
web/src/story/ The chronicle: chronicle.ts (the story β€” a prologue, a chapter per main quest, one per hidden hall, an epilogue β€” authored with {name}/{path} and rendered for the hero when shown), journal-store.ts (chapters unlocked, scrolls read with the command that re-opens them, halls found, ranks β€” bashcrawl-web-journal-v1, unread count), story.ts (installStory() on the FX bus: a quest completed β†’ its chapter, a hall discovered β†’ its chapter and a note, a cat β†’ a lore entry, the main road walked β†’ the epilogue; unlockChapter() is also what creation calls for the prologue), dialogue-store.ts + StoryDialogue.tsx (the RPG dialogue box under the log: typewriter at the text-speed option, Enter/click turns the page, waits while an overlay or the tour is up), QuestTracker.tsx (the objective and its checklist steps in the stage's corner), Journal.tsx (Chronicle Β· Quests Β· Lore Β· Bestiary Β· Badges; Alt+J, journal, the header). The engine knows none of this: its quests and rooms are the triggers, the narration is the web's.
web/src/hud/ The 16-bit HUD over BashcrawlHud: StatusStrip (rank β†’ next rank, HP, quests, badges, streak), PanelFrame, Gauge, RollingNumber, the eight panes, HudMenu (show/hide/reorder/dock, saved under bashcrawl-hud-layout-v1), Sidebar (an overlay under 900px).
web/src/fx/ The effects layer: effects.ts is the one event β†’ effect table (canvas bursts, shake, flash, pane pulses, hero mood, SFX per Hud.diffEvents type); fx-engine.ts + particles.ts (typed-array pool on one fixed canvas, room wipes, idle loop stops, hidden-tab pause), shake.ts (trauma model on #stage), flash-store.ts/ScreenFlash.tsx, anchors.ts (data-fx-anchor targets), bump.ts, hero-mood.ts, useAmbientClip.ts, ArtClip.tsx, and the title cards (banner-store.ts, Banners.tsx: first entry to a room, a quest cleared, a rank, a passage, a lesson β€” queued one at a time). All gated on prefers-reduced-motion and the Effects option.
web/src/audio/ Web Audio chiptune SFX, no files: synth.ts (tone/arp, gesture unlock), sfx.ts (a phrase per event), sound-store.ts (off by default, bashcrawl-web-sound-v1).
web/src/styles/ tokens.css β€” the only file with colour literals (--fleet-* roles, dark/light/auto via data-theme + data-resolved, layer and motion scales, reduced-motion collapse; theme.test.ts enforces it), app.css (Tailwind 4 @theme inline map, base, shell chrome), terminal.css, hud.css, fx.css, learn.css, arcade.css, chrome.css.
web/src/test/ setup.ts (jest-dom, cleanup, jsdom polyfills) and engine.ts, which evaluates the real engine files β€” the same list as termforge/test/helpers/game-harness.js β€” into jsdom's window so component tests play the actual game.

Web app rules

  • The engine stays classic. web/assets/js/** (the vendored core, runtime.js, plugins/, hud.js, storage.js, fx.js, fx-clips.js, art-clips.js, ambient.js, learn.js, vim.js, arcade.js) are classic/CJS scripts shared with the node hosts and the node test harness; they are not compiled by Vite and must not become ES modules. web/index.html loads them in a fixed order: the 22 vendored TermForge core files (protocol β†’ parser β†’ state β†’ vfs β†’ hooks β†’ registry β†’ events β†’ rules β†’ plugin β†’ curriculum β†’ mastery β†’ explain β†’ shell β†’ packs/posix β†’ packs/flavour β†’ view β†’ sinks/dom β†’ sinks/ansi β†’ input β†’ session β†’ ascii-motion β†’ art), then storage β†’ art-clips β†’ plugins/{achievements,daily,progress,arena,pathfind,bestiary,nudge} β†’ runtime β†’ hud β†’ learn β†’ fx-clips β†’ fx β†’ ambient β†’ vim β†’ arcade, with vite-ignore on each tag, then the feedback widget fleet-feedback.js, then <script type="module" src="./src/main.tsx">; the widget's console/error buffer fleet-feedback-capture.js loads before all of them, in <head>. validate_static_web.py enforces the order (and the same in web/dist/index.html when built); vite.config.mts's copyEngine ships web/assets/js and web/data into web/dist verbatim, and its publicDir is the repo-root public/ (the favicon, .nojekyll and the vendored widget), copied into web/dist as is. The root package.json must never declare "type": "module".
  • The app is React (web/src/, TypeScript strict, npm run lint is ESLint flat with the react-hooks compiler rules). State outside React lives in small external stores (web/src/lib/store.ts, useSyncExternalStore); the game store publishes a version per command and components read presenter models from BashcrawlHud through useModel(name). New game features are still plugins (web/assets/js/plugins/, registered in GAME_PLUGINS, loaded by index.html); new UI is a component under web/src/ β€” a HUD pane goes in web/src/hud/ + Sidebar.tsx, a new reaction in web/src/fx/effects.ts, a new sound in web/src/audio/sfx.ts.
  • Design values live in web/src/styles/tokens.css only (--fleet-* roles; theme.test.ts fails on a colour literal or a numeric z-index anywhere else under web/src, canvas code included β€” read a colour with colorOf(role)). Tailwind utilities name the role (bg-panel, text-gold); the pixel chrome is the .bc-frame/.bc-btn/.bc-chip primitives. Everything that moves is inside prefers-reduced-motion: no-preference or gated in JS.
  • The reader layer (web/src/terminal/prose.ts + log-decor.ts) runs after every paint. It classifies what a file viewer printed by the scrolls' own plain-text conventions (===/#### rules and the title between them, # TITLE # frames, CAPS labels, $ cmd # comment, command/purpose tables, box panels, *atmosphere*, **emphasis**, `code`, Markdown in the READMEs, a script mode for cat treasure) and never rewrites the text: markers stay in the DOM inside .sc-mark (hidden by CSS except in box tables), so prose.test.ts round-trips every scroll byte for byte. Fresh lines cascade in (.rv/--i; the step is the text-speed option) and a block taller than the log opens at its title. Keep the scrolls terminal-readable β€” teach the classifier a convention rather than converting content to Markdown for the web's sake.
  • First run: no hero (bashcrawl-web-hero-v1) means the title screen β†’ CreateHero β†’ Intro (once) β†’ the hero's door β†’ Tour (until hero.tourDone) β†’ the prologue in the dialogue box. The brand button reopens the title; the portrait in the party bar, ?, πŸ“– and βš™ open the profile, the shortcuts, the journal and Options; Escape with nothing open is the pause menu. The hero, the options and the journal are app state only; the engine's save is untouched by them, and GameStore.newRun() (+ resetJournal()) is the one way to start over.
  • The prompt answers some words with screens: journal, menu/pause, hero/wardrobe, options/settings, title never reach the engine β€” GameStore.intercept() echoes a dim line and opens the overlay (InputTarget.intercept). Add a word there, not a handler in runtime.js. Hotkeys: Alt+J/H/O/M; they live in App.tsx and chrome/shortcuts.ts together.
  • Screens slide, nothing snaps: App.tsx keys the screen on the route and the mode event runs the pixel wipe over the stage; panels fold through a grid track (.bc-panel-fold, the body goes inert + aria-hidden, never hidden); the status strip and dock enter with a slide. A new surface should get the same treatment β€” and never AnimatePresence mode="wait".
  • A mini-game = (seed world + goal predicate + scoring) over a scoped bare Runtime (BashcrawlArcade.GAMES in arcade.js) β€” never reimplement command behavior outside termforge/core/ + runtime.js. The Vim Catacombs is the one trial whose world is not the shell: a vim.js buffer, needsWorld: false, keys through the store's keystroke hook, :// lines through execute(); a new vim level is a vim_levels entry with a winning solution, never a change to the engine's semantics.
  • Framework changes go in termforge/core/ (then make web-build re-vendors); game-only changes go in runtime.js. The this.handlers = {…} literal in runtime.js must stay a single static literal (validator regex contract).
  • localStorage keys: story save bashcrawl-web-state-v1, arcade bashcrawl-web-arcade-v1, shell prefs bashcrawl-web-shell-v1 (last door, onboarded, introSeen), HUD layout bashcrawl-hud-layout-v1, theme bashcrawl-web-theme (dark|light|auto), CRT bashcrawl-web-crt, sound bashcrawl-web-sound-v1, hero bashcrawl-web-hero-v1, options bashcrawl-web-settings-v1, journal bashcrawl-web-journal-v1 (additive keys; never break the story save β€” termforge/test/game-save.test.js locks the shape). The learn and mastery slices are owned (and sanitized on load) by the curriculum and mastery plugins.
  • The feedback widget is the fleet kit's (bamr87/bamr87 templates/feedback, UPS-FB): public/fleet-feedback.js, its capture buffer public/fleet-feedback-capture.js and the React adapter components/FeedbackButton.tsx are vendored and never edited here (tools/fanout.sh --kit feedback --upgrade refreshes them in place). Bashcrawl's half is web/src/chrome/Feedback.tsx: where reports go, the one mount (in App.tsx, beside the error boundary so the crash screen can still report) and the ReportLink the not-found and crash screens use, a real link to the page_feedback.yml issue form that opens the widget pre-typed once it has loaded. The floating button stacks above the prompt dock and the footer: AppShell publishes their height as --bc-bottom-chrome on <html>, and app.css turns it into the widget's --fleet-space-fab-gap.
  • Tests: npm run test:web (vitest + Testing Library; web/src/test/engine.ts loads the real engine into jsdom) for the app, make test-js for the engine. Dialogs animate out with AnimatePresence, which never completes under jsdom β€” assert the store state, not the DOM's absence, and never use mode="wait" for a sequence of cards (the next one never mounts there); key an enter-only motion.div instead.

Playtest harness and scripts

Component Purpose
src/playtest/ bash_session.py (PTY bash REPL + sentinel prompt), sandbox.py, recorder.py, harness.py, mcp_server.py, scorer.py.
scripts/ export_static_web.py, vendor_termforge.py, write_build_info.py, validate_*, generate_*, playtest.sh, lint.sh, run_tests.sh.

Integration points

  • CI (.github/workflows/): ci.yml is the PR/push gate β€” lint (shellcheck/yamllint/markdownlint/ruff via scripts/lint.sh, make lint-js, npm run lint), test (make validate-contracts + make test + make test-js + make web-test; Node 24, npm install with no lockfile), macos-smoke (real gameplay on stock macOS bash 3.2) and the hub's shared standard-ci.yml. pages.yml runs make web-test and deploys web/dist on main. blank-slate-audit.yml is the weekly agent playtest; claude.yml answers @claude mentions; markdown-oneline.yml unwraps soft-wrapped prose. Every CI check mirrors a local make target, and content rules (shebangs, scrolls, unlocks) live in scripts/validate_content_contracts.py, not inline in workflows.
  • Build identity and health (hub UPS-BE-10, UPS-BE-11): the site is static, so scripts/write_build_info.py runs after every vite build in make web-bundle and make web-test and writes web/dist/version + version.json (name; version, release-please's, from package.json; commit, from GITHUB_SHA in CI; built_at; game_version, from VERSION) and web/dist/healthz + healthz.json ({"status": "ok"}). Pages serves them at <site>/version and <site>/healthz, so the live site says which build it is. A missing version stops the build instead of publishing an empty value.
  • Why standard-ci gets node-version: 24: its default Node 20 ships npm 10, whose engines-aware resolution of the always-latest ranges crashes before any script runs (Cannot read properties of null (reading 'edgesOut'), reproducible in node:20). Vitest stays npm run test:web so that job's npm test is still the engine suite.
  • MCP server: playtest.mcp_server, configured in .mcp.json / .cursor/mcp.json with PYTHONPATH=src; smoke-tested by make test-mcp.
  • Logging: JSONL session logs in logs/sessions/ (playtest recorder + test log capture).
  • Dependencies: Dependabot owns all dependency updates (.github/dependabot.yml).