Tooling

Tooling is part of the language, not an afterthought. Beamtalk is designed to be used interactively — by humans and AI agents alike — through a live workspace that all tools connect to over the same WebSocket protocol.

CLI Tools

# Project management
beamtalk new mylib          # Create new library project
beamtalk new myapp --app    # Create new application project (supervisor + Main)
beamtalk build              # Compile to BEAM
beamtalk run                # Compile and start (status to stderr, program output to stdout)
beamtalk check              # Check for errors without compiling
beamtalk agents refresh     # Rewrite the generated region of AGENTS.md and .github/copilot-instructions.md from this toolchain's template
beamtalk agents check       # Exit non-zero if either generated region is out of date (BT-5228)

# Dependencies (see Package Management guide)
beamtalk deps add json --git https://github.com/jamesc/beamtalk-json --tag v1.0.0
beamtalk deps list          # Show resolved dependencies
beamtalk deps update        # Update lockfile

# Development
beamtalk repl               # Interactive REPL (connects to workspace)
beamtalk test               # Run test suite

# Type coverage (ADR 0077)
beamtalk type-coverage              # Per-class coverage report
beamtalk type-coverage --detail     # Show each Dynamic expression with location and reason
beamtalk type-coverage --format json          # Machine-readable JSON output
beamtalk type-coverage --at-least 75          # Exit non-zero if coverage < 75% (CI ratchet)
beamtalk type-coverage --class MyApp          # Filter to a specific class
beamtalk type-coverage --detail --class MyApp # Detail for one class

# Releases (ADR 0125)
beamtalk release                          # Build an OTP release (requires [application] in beamtalk.toml)
beamtalk release --output dist/           # Override output directory
beamtalk release --no-include-erts        # Slim image; requires a host OTP
beamtalk release --upgrade-from prev/     # Shape-compatibility preflight against a previous release

# Native Erlang
beamtalk generate native MyActor # Generate skeleton gen_server from a native: Actor class

For full details on beamtalk.toml, dependencies, lockfiles, qualified names, and collision detection, see the Package Management guide.

Project Types

beamtalk new creates a library by default — a package with source and tests, no application supervisor. Pass --app to create an application project with a supervisor and Main entry point.

VariantCommandWhat you get
Library (default)beamtalk new foobeamtalk.toml, src/foo.bt, test/foo_test.bt
Applicationbeamtalk new foo --appAbove plus [application] in toml, src/foo_app_sup.bt, src/main.bt

Both variants generate a Justfile, .github/workflows/ci.yml, AGENTS.md, and .mcp.json. The generated part of AGENTS.md and .github/copilot-instructions.md sits between <!-- beamtalk:template begin --> and <!-- beamtalk:template end --> markers; beamtalk agents refresh rewrites only that region (text outside the markers is kept) and beamtalk agents check fails when it differs from the installed toolchain's template. A file with no marker pair is reported as an error, and a missing file is skipped (BT-5228).

Standard Justfile Targets

Every generated project includes a Justfile with these targets:

TargetCommandDescription
buildbeamtalk buildCompile the project
testbeamtalk testRun the test suite
fmtbeamtalk fmt-checkCheck formatting
fmt-fixbeamtalk fmtFormat in place
lintbeamtalk lintLint source files
cleanrm -rf _buildRemove build artifacts
cifmt lint build testFull CI check
release(script)Tag a release from beamtalk.toml version
publishgit push origin --tagsPush release tags
runbeamtalk runRun the application (--app only)

beamtalk fmt never loses source (BT-5183). Before writing a file, the formatter re-parses its own output and checks that every comment is still there, every number keeps its spelling (16rFF, 1e10) and the program is unchanged. If any check fails — a formatter bug — the file is left untouched, fmt prints what would have been lost and exits non-zero (fmt-check too). A file with parse errors is skipped with a warning, as before. A CRLF file keeps CRLF line endings. The LSP's document formatting applies the same check and returns no edits when it fails.

beamtalk run --raw-mfa (script and --connect modes) follows an uncaught error's message with the complete stack, one at Class>>selector (file:line) [module:function/arity] line per frame, hidden frames included. Without it the message is followed by the visible frames, at Class>>selector (file:line), and (N frames hidden; --raw-mfa shows all) when some were left out, as beamtalk test prints. Put the flag before the program arguments (beamtalk run Greeter main: --raw-mfa Alice); after the first argument it is passed to the program. It is rejected for service mode (beamtalk run .).

beamtalk run output routing: Status and progress lines (Building..., Running ClassName>>selector..., Connecting to workspace..., and service mode's Started <app> v<version> / Supervisor / REPL port banner) are written to stderr in all three run modes — script, connected, and service (beamtalk run .). Stdout carries only the dispatched program's own output, keeping it clean for piped/programmatic consumers (beamtalk run MyApp run | head). beamtalk build --escript follows the same convention for its Building... line.

beamtalk run exit codes (Unix): 0 on clean exit or SIGINT (Ctrl+C). 128 + signal when the BEAM process is killed by a signal (e.g. 137 for SIGKILL, 139 for SIGSEGV). Windows always exits 1 on abnormal termination.

Build System

beamtalk build compiles a project (or a single .bt file) to BEAM bytecode. The build pipeline is incremental — unchanged files are skipped, and the compiler caches class metadata across builds.

Build Phases

Every build runs through three sequential phases:

  1. Pass 1 (Discovery) — Read each .bt source file and parse it into an AST. Extract class names, superclass relationships, and method signatures. This produces the class_module_index (class name to BEAM module name) and class_superclass_index (class to superclass) needed for cross-file resolution in Pass 2. Dependency validation (stdlib reservation checks, native module collision detection) also runs here.

  2. Pass 2 (Compile) — For each changed source file: run semantic analysis (type checking, protocol conformance, dependency warnings), then generate Core Erlang. The full class-module index from Pass 1 is injected so cross-file class references resolve correctly. Each .bt file produces a .core file in the build directory.

  3. BEAM compilation (erlc) — Invoke OTP's compile module to turn each .core file into a .beam file. This is the standard Erlang compiler — Beamtalk delegates BEAM bytecode generation entirely to OTP.

Incremental Compilation

Beamtalk uses content-hash-based change detection to avoid redundant work (BT-3120):

Diagnostic Summary (BT-2014)

At the end of a successful build, beamtalk build prints a summary of non-error diagnostics grouped by category and severity. This lets you track typing progress at a glance:

Diagnostic summary (42 files):
  Type              12 warning
  Dnu                3 warning
  Total             15  (15 warning)

The summary is suppressed when --no-warnings is passed.

beamtalk lint prints the same summary at end of run. In --format json mode, a summary JSON object is emitted as the last line with totals_by_severity, totals_by_category, files_checked, and total fields for CI diffing.

When walking a directory, beamtalk lint — like fmt and MCP lint — skips paths ignored by .gitignore (BT-4135): the .gitignore files in and below the walked directory, plus, inside a git repository, those between the repository root and the walked directory. A gitignored .worktrees/ directory holding nested checkouts is therefore not linted twice. As in git, a nested repository (a subdirectory containing .git, such as a submodule) is governed only by its own .gitignore files: the outer repository's rules decide whether it is walked, but not which files inside it are skipped. Neither the per-clone .git/info/exclude nor the global core.excludesFile is consulted, so every clone sees the same files, and a directory passed explicitly is always walked even if an ancestor rule ignores it. build, test, doc and the LSP workspace preload do not consult .gitignore: what gets compiled never depends on it, so a generated, uncommitted .bt source under src/ still builds, and the LSP indexes exactly what builds.

A .beamtalk-lint-exempt file in the linted directory lists subdirectory names (one per line, # comments) whose diagnostics are suppressed: they are not printed, not counted, and do not affect the exit code. The exempted directories still feed cross-file context — resolution and type information — so they do not create false positives in the files that are reported. This is CLI-only; MCP lint does not read the file.

beamtalk lint also loads FFI type signatures from the build cache (_build/type_cache/) so that lint and build agree on Erlang FFI return types. Cache entries are validated against live .beam file mtimes and against the producing compiler's Erlang→Beamtalk type-mapping stamp (BT-2852) — if the underlying module has been recompiled since the cache was written, or the entry was written by a beamtalk build with different type-mapping logic, the stale entry is skipped and lint falls back to untyped-FFI inference. If the project has never been built, lint proceeds without a cache (matching its pre-cache behaviour).

CLI/REPL Diagnostic Parity (BT-4334)

The same source must get the same verdict from batch compilation and from a REPL load-project. All surfaces share one checker (analyse_full via the diagnostic_provider pipelines) and one severity mapping (the package's [diagnostics] table applied after @expect suppression), with the same config: project-complete knowledge scope inside a package, the manifest's has_package_dependencies guard, current_package, the FFI type registry, and project-known Erlang modules. beamtalk test previously compiled test/fixture files with the conservative ModuleOnly default, suppressing DNU/Type diagnostics the REPL live recheck reported — it now declares the same scope as build.

Intentionally surface-specific behaviour (not parity bugs):

Build Artifact Layout (BuildLayout)

All build output goes under _build/ in the project root. The BuildLayout struct centralises path construction so all commands (build, test, run, repl, deps) use consistent locations.

<project_root>/
  _build/
    dev/
      ebin/                        — compiled .beam files from .bt sources
        .beamtalk-pass1-cache.json — Pass 1 incremental cache
        .beamtalk-beam-hashes.json — Pass 2 .beam staleness sidecar (BT-3120)
      native/
        ebin/                      — compiled .beam files from native .erl sources
        include/                   — generated headers (e.g. beamtalk_classes.hrl)
        default/lib/               — rebar3 hex dependency libs (ERL_LIBS)
        rebar.config               — generated rebar3 config (when hex deps exist)
    deps/
      <name>/                      — git dependency checkout
        ebin/                      — compiled .beam files for the dependency

For single-file builds (no beamtalk.toml), output goes to build/ alongside the source file instead of _build/dev/ebin/.

Module Naming

Beamtalk uses a namespaced BEAM module naming scheme to avoid collisions in the flat BEAM module namespace:

ModeModule nameExample
Package (beamtalk.toml present)bt@<package>@<relative_path>bt@myapp@Counter
Single file (no manifest)bt@<module>bt@Counter

Subdirectories within src/ are reflected in the module name: src/models/user.bt in package myapp becomes bt@myapp@models@user.

Dependency Compilation Order

When a project has dependencies (declared in beamtalk.toml), the build resolves and compiles the full transitive dependency graph in topological order before compiling the project's own sources. Each dependency's class-module index is merged into the project's index so cross-package class references resolve during codegen.

Native Erlang dependencies (.erl files under native/ or hex packages) are compiled after Pass 1 but before Pass 2. This ordering ensures the generated beamtalk_classes.hrl header (which maps Beamtalk class names to BEAM module names) is available for native .erl files to include.

__beamtalk_meta/0 Protocol

Every compiled Beamtalk class module exports a __beamtalk_meta/0 function — a zero-process reflection entry point that returns a map of class metadata without requiring any gen_server process to be running:

Module:'__beamtalk_meta'() ->
    #{
        class             => 'Counter',
        superclass        => 'Actor',
        meta_version      => 2,
        is_sealed         => false,
        is_abstract       => false,
        is_value          => false,
        fields            => [count],
        field_types       => #{count => 'Integer'},
        field_has_default => #{count => true},
        %% ADR 0124 §1/B5a: per-field slot kind (`#eager` | `#late`),
        %% instance-side (a class has no fields, ADR 0153).
        field_kinds       => #{count => eager},
        methods           => [{increment, 1}, {value, 0}],
        class_methods     => [{new, 0}],
        method_info       => #{...},
        class_method_info => #{...}
    }

This metadata serves multiple purposes:

Hot-Patching

When a .bt file is reloaded (via Workspace load:, Counter reload, :sync, or a VS Code file save), the compiler produces new BEAM bytecode and the runtime hot-loads it using standard OTP code loading (code:load_binary/3). The class gen_server process updates its live state to reflect the new methods — hot-patched methods take effect on the next message send without restarting the actor.

The compiler server is also notified of the change so its class cache stays current. Since __beamtalk_meta/0 is a compiled function baked into the module, it reflects the original compilation — not hot-patches. The gen_server's class_state record is the authoritative live view; the compiler server receives updates synthesised from class_state, not from the stale __beamtalk_meta/0.

Embedded Compiler Architecture

The Beamtalk compiler (beamtalk-core, written in Rust) runs as an OTP Port managed by beamtalk_compiler_server — a supervised gen_server inside the BEAM node (ADR 0022). This replaces the older separate-daemon architecture and provides:

Check

beamtalk check runs the full analysis pipeline — lexing, parsing, type inference, annotation and @expect handling, cross-file alias/protocol resolution, and visibility checks — and fails on the same error diagnostics beamtalk build emits for those phases, without emitting any output files.

beamtalk check              # Check the current project
beamtalk check path/to/dir  # Check a specific directory
beamtalk check path/to/file.bt  # Check a single file

What it runs: Pass 1 indexing plus the full semantic-analysis pipeline over every source file. It checks all files instead of stopping at the first failure.

What it skips: No .core or .beam files are written for Beamtalk sources (the package's own native/*.erl is compiled, see below), the post-codegen verifier does not run, and no OTP packaging (.app file, corpus) is produced.

FFI note: check compiles the package's own native/*.erl first (as build does), so its -specs type FFI calls the same on a clean tree as after a build. A passing beamtalk check still does not guarantee beamtalk build succeeds.

Warning flags: --warnings-as-errors also fails on Warning/Hint diagnostics (same exclusions as build); --no-warnings suppresses warning output. The two are mutually exclusive (BT-5045).

Exit codes: 0 for success, 1 if any file produces an error-severity diagnostic (or a warning under --warnings-as-errors).

Releases (ADR 0125)

beamtalk release assembles a standard OTP release — a self-contained directory (or tarball) bootable with erl -boot, independent of the development workspace. Requires an [application] section in beamtalk.toml (a release is a long-running service with a root supervisor).

beamtalk release                                    # build the release
beamtalk release --output dist/                     # override output directory
beamtalk release --no-include-erts                  # slim image; requires host OTP
beamtalk release --upgrade-from prev-release/       # shape-compatibility preflight
beamtalk release --force                            # force rebuild
beamtalk release --force-output                     # replace an unmarked, release-shaped --output dir

Release Configuration

Configured via the [release] section in beamtalk.toml:

[release]
name = "myapp"                    # release name (defaults to package name)
apps = ["extra_otp_app"]          # additional OTP apps to include beyond the computed closure
include-erts = true               # bundle ERTS (default: true)
strip-beams = false               # drop debug_info chunks from .beam files
include-compiler = false          # stage the compiler port binary (for runtime compilation)
console = false                   # start with an interactive console (requires a cookie; see deploying.md)
bind = "127.0.0.1"               # REPL bind address (only meaningful when console = true)
sys-config = "config/sys.config"  # custom sys.config path
vm-args = "config/vm.args"        # custom vm.args path

The release name must not contain @ (it forms part of the -sname flag).

What a Release Contains

DirectoryContents
lib/<app>-<vsn>/ebin/Compiled .beam files for each app in the closure
lib/<app>-<vsn>/priv/An app's priv/ directory, when it has one, copied from beside its source ebin/ (dependency priv/ is staged to _build/deps/<name>/priv at build time), so code:priv_dir/1 resolves
erts-<vsn>/Bundled Erlang runtime (when include-erts = true)
releases/<vsn>/.rel, start.boot, sys.config, vm.args
releases/<vsn>/beamtalk-provenance.jsonOTP/beamtalk versions, required_otp range
releases/<vsn>/shapes.jsonFlattened field maps and migration tables for upgrade safety
releases/RELEASESOTP release metadata
bin/<name>POSIX launcher script
bin/<name>.cmdWindows launcher script
<name>-<vsn>.tar.gzDistributable tarball

Launcher Commands

The generated bin/<name> script (and bin/<name>.cmd on Windows) supports these commands:

CommandDescription
foreground (default)Start the release in the foreground
stopStop a running release
pingCheck if the release is running
remote_consoleAttach a remote Erlang shell
eval "Class selector [args]"Dispatch one entry in a throwaway VM (no distribution)
rpc "Class selector [args]"Dispatch one entry into the running node over Erlang distribution
versionPrint the release version

The launcher enforces an OTP-major boot check — it refuses to start when the host OTP version is outside the build-major window declared in otp-support.toml.

Upgrade Preflight

beamtalk release --upgrade-from <prev-release-dir-or-tarball> compares the new release's shapes.json and beamtalk-provenance.json against a previous release and prints a compatibility report:

Use this as a CI deploy gate to catch missing migration methods before production.

REPL

The Beamtalk REPL is an interactive development environment connected to a persistent workspace — a detached BEAM node that survives disconnections (ADR 0004). Actors keep running between sessions; REPL variable bindings are session-local.

BEAMTALK_HOME. The CLI, VS Code extension and runtime resolve workspace state under ~/.beamtalk by default. Set BEAMTALK_HOME to override this root (e.g. export BEAMTALK_HOME=/data/beamtalk). The detached BEAM node, beamtalk workspace, and the VS Code extension all honour the same variable, so they agree on where workspaces live. Every other environment variable the code reads is listed in environment-variables; the beamtalk workspace subcommands and flags are in cli-workspace.

Starting the REPL

beamtalk repl                # Start or reconnect to workspace
beamtalk repl --foreground   # Start node in foreground (debug mode; needs epmd; conflicts with --workspace,
                             # --persistent, --ephemeral and --idle-timeout)
beamtalk repl --idle-timeout 600  # Stop the workspace after 10 idle minutes
beamtalk repl --port 9090    # Use a specific port
beamtalk repl --node mynode  # Use a specific node name

Session idle period. A REPL session whose client disconnected stays resumable for 4 hours, then the workspace stops it. A session no client ever attached to (a dist-attached LiveView) is stopped after the same period without an eval. Change the period with the BEAMTALK_SESSION_IDLE_SECONDS environment variable of the workspace node, or with {beamtalk_workspace, [{session_idle_seconds, N}]} in sys.config (which wins). This is separate from --idle-timeout, which stops the whole workspace node.

On startup, the REPL prints the version and a help hint:

Beamtalk v0.6.0
Type :help for available commands, :exit to quit.

>

If a workspace is already running (from a previous session or another terminal), the REPL reconnects to it. All previously loaded classes and running actors are still available.

Expression Evaluation

The REPL evaluates any Beamtalk expression and prints the result. Variables assigned in one expression persist across subsequent expressions within the same session.

> x := 42
42

> x + 10
52

> counter := Counter spawn
Actor(Counter, 0.234.0)

> counter increment
1

> counter getValue
1

Actor message sends are auto-awaited in the REPL — when you send a message to an actor, the REPL waits for the reply and prints it. In compiled code, you would need to handle the asynchronous response explicitly.

Variable reassignment works as expected:

> x := 100
100

> x + 10
110

Loop mutations also persist across REPL inputs:

> count := 0
0

> 5 timesRepeat: [count := count + 1]
5

> count
5

Commands Reference

REPL commands start with : and provide shortcuts for common operations. Most are thin wrappers around Beamtalk-native message sends (ADR 0040), so the same operations work from compiled code, scripts, and actor methods.

Code Loading

CommandNative equivalentDescription
(none)Workspace load: "path/to/file.bt"Compile and hot-load one .bt file; answers the list of loaded classes. A directory is an error
(none)Counter reloadRecompile a class from its source file
:sync / :sWorkspace syncSync workspace with project (requires beamtalk.toml)
:recheck imageWorkspace recheckImageRe-check all live classes for stale callers / broken signatures
:unload Counter(removes class)Unload a user class from the workspace

There are no :load or :reload commands: :load path is a parse error in the REPL. Use Workspace load: for one file, Counter reload for one class, and :sync for the whole project.

Workspace load: compiles the file and hot-loads the resulting BEAM module. If a class with the same name already exists, the new code replaces it — live actors pick up the new methods on their next message send.

> Workspace load: "examples/counter.bt"
#(Counter)

> c := Counter spawn
Actor(Counter, 0.234.0)

> c increment
1

Workspace load: takes a single file; passing a directory raises Failed to read file: eisdir. To load several files, use :sync (the whole project) or one Workspace load: per file. Loading a directory is deliberately not provided (BT-5113): :sync is the multi-file path and understands beamtalk.toml, source roots and incremental reuse, which a bare directory walk would not.

:sync loads (or reloads) the entire project defined by beamtalk.toml in the current directory. It is incremental — unchanged files are skipped:

> :sync
Reloaded 2 of 5 files
Classes: Counter, Greeter

> :s
Reloaded 0 of 5 files (5 unchanged)

:unload removes a user class from the workspace. Stdlib classes cannot be unloaded:

> :unload MyClass
"Class 'MyClass' removed from system"

> :unload Integer
Error: Cannot remove stdlib class 'Integer'
Hint: Stdlib classes are protected and cannot be removed.

Inspection and Documentation

CommandNative equivalentDescription
:help / :h / :?(none)Show REPL help message
:help CounterBeamtalk help: CounterShow class documentation and methods
:help Counter incrementBeamtalk help: Counter selector: #incrementShow method documentation
:help Counter class(class-side docs)Show class-side methods (spawn, new, reload, ...)
:help Counter class create:(class-side method docs)Show class-side method documentation
:help Erlang listsBeamtalk erlangHelp: "lists"Show Erlang module docs and function signatures
:help Erlang lists reverseBeamtalk erlangHelp: "lists" selector: #reverseShow Erlang function docs and type signature
:bindings / :b(session-local)Show current variable bindings
:show-codegen <expr> / :sc <expr>(REPL-only)Show generated Core Erlang for an expression

:help provides interactive documentation lookup:

> :help Integer
== Integer < Number ==
Instance methods:
  + - * / ...
Class methods:
  parse: text :: Binary radix: base :: Integer -> Result(Integer, Error) [sealed]
...

> :help Integer +
== Integer >> + ==
  ...

> :help Integer isPositive
== Integer >> isPositive ==
  (inherited from Number)
  ...

Package-qualified class names are also supported:

> :help stdlib@Integer
== Integer < Number ==
  ...

Erlang FFI modules are also supported — shows type signatures and EEP-48 docs:

> :help Erlang lists
Erlang module: lists

Functions:
  append: list1 :: List list2: list2 :: List -> List
  reverse: list :: List -> List
  ...

> :help Erlang lists reverse
lists:reverse
  Erlang: -spec reverse(List) -> List when List :: [T], T :: term().
  reverse: list :: List -> List

Tab completion works for module names (:h Erlang li<TAB>) and function names (:h Erlang lists re<TAB>).

:bindings lists the variable names bound in the current session (BT-2369 / ADR 0081 Phase 6: it evaluates Session current bindings keys, so it shows binding names; evaluate a name to see its value):

> x := 42
42

> name := "hello"
hello

> :bindings
name
x

:show-codegen displays the Core Erlang output for any expression, useful for understanding what the compiler generates:

> :sc 2 + 3
'erlang':'+'(2, 3)

Testing

CommandNative equivalentDescription
:test / :tWorkspace testRun all loaded test classes
:test CounterTestWorkspace test: CounterTestRun a specific test class
> Workspace load: "test/counter_test.bt"
#(CounterTest)

> :test CounterTest
TestResult(2 tests, 2 passed (0.0s))

ChangeLog and flush (ADR 0082)

The live-edit save model: live patches install in memory and append to the workspace ChangeLog; the on-disk .bt files are only updated when you flush. See Language Features — Saving live edits back to disk for the full model.

CommandNative equivalentDescription
:changesWorkspace changesShow the ChangeLog (returns a ChangeLog object)
:dirtyWorkspace changes dirtyMethodsPer-class set of dirty selectors
:flushflush operation (as Workspace flush)Write every durable + flushable Tier 1 entry back to its source file
:flush Counterflush operation, class scopeFlush entries targeting one class
:flush #'new-class'flush operation, kind scope (new-class, remove-method, remove-class, rename-class, rename-method)Flush only entries of one kind
:flush #incrementflush operation, selector scopeFlush entries for one method selector in every class
:flush Counter>>#incrementflush operation, class + selector scopeFlush entries for one method of one class
:flush #{ #file => "path" }flush operation, file scopeFlush entries against one file
:flush-destructiveflush operation with confirm_destructiveFlush all pending entries including Tier 2 (remove-class — file deletion); prompts y/N
:flush-destructive Counterflush operation, class scope, confirm_destructiveDestructive flush scoped to one class; prompts y/N
:remove-method Counter incrementCounter removeSelector: #incrementRemove a method from a class (strips optional # from selector)
:remove-class CounterCounter removeFromSystemRemove a class entirely (memory-only; prompts y/N). Flush separately to delete the file
:rename-class Counter AccumulatorCounter renameTo: #AccumulatorRename a class (memory-only; prompts y/N). Flush separately (:flush-destructive) to move the file and rewrite cross-file references
:rename-method Counter increment incrementByCounter renameSelector: #increment to: #incrementByRename a method, instance-side only (memory-only; prompts y/N). Flush separately to write confirmed sites to disk
> Counter >> increment => self.value := self.value + 1   // memory patched, logged
> :dirty
#{#Counter => #{#increment}}
> :flush
_   // FlushResult; quiet on success
> :dirty
#{}

If flush detects an external edit on a target file the offending entries stay pending and surface under the result's #conflicts field. Recover with Workspace changes revert: anEntry (undo one patch by re-installing its prior body), Workspace changes clear (drop the pending ChangeLog entries — note already-installed patches remain live until workspace restart; use revert: if you also want to roll back the in-memory method body), or reconcile the file by hand and retry :flush.

For write-through editor semantics: Workspace autoflush: true flips a per-workspace setting so every successful durable patch flushes immediately. The setting persists across restarts.

Session Control

CommandDescription
:interrupt / :intCancel a running evaluation (out-of-band interrupt over a separate connection)
:clearClear all variable bindings
:raw-mfa [on|off]Per-session: list every stack frame of an error (hidden ones too) with its raw module:function/arity; bare :raw-mfa toggles. Affects only this session
:exit / :quit / :qExit the REPL (Ctrl+D also works)

:clear removes all session-local variable bindings:

> x := 42
42

> :clear
ok

> x
ERROR: Undefined variable

:interrupt cancels a running evaluation. Because the main connection is blocked while an eval is in progress, the interrupt is sent out-of-band on a separate connection. Ctrl-C during an eval sends an interrupt automatically.

> :interrupt
ok

Multi-line Input

The REPL automatically detects incomplete input (unclosed brackets, trailing operators, etc.) and shows a ..> continuation prompt. For constructs where the REPL cannot determine completeness from syntax alone — protocol definitions and class definitions without methods — press Enter on a blank line to submit the accumulated input.

> Protocol define: Greetable
..>   greet -> String
..>                          ← blank line submits the definition
Protocol Greetable defined

Class definitions with at least one method (=>) auto-submit. A blank line is only needed for class headers with state declarations only (before you have added methods):

> Actor subclass: Config
..>   state: verbose = false
..>                          ← blank line submits the class

Multi-line expressions work naturally with blocks, collections, and keyword messages:

> [
..>   :x |
..>   x * 2
..> ] value: 21
42

> #{
..>   #name => "Alice",
..>   #age => 30
..> } at: #name
Alice

Use Ctrl+C to cancel multi-line input without submitting.

Interactive Class Definitions

Classes can be defined directly at the REPL prompt without writing a .bt file:

> Actor subclass: InlineCounter
..>   state: value = 0
..>   increment => self.value := self.value + 1

Methods can be added or replaced on a class whose source the workspace holds, using Tonel-style standalone method definitions (>>). The REPL recompiles the class from its stored source and hot-loads it:

> InlineCounter >> getValue => self.value

> c := InlineCounter spawn
Actor(InlineCounter, 0.234.0)

> c increment
1

> c getValue
1

Redefining a method replaces it for all future message sends, including on existing actor instances:

> InlineCounter >> increment => self.value := self.value + 10

> c2 := InlineCounter spawn
Actor(InlineCounter, 0.234.0)

> c2 increment
10

This is a live edit, not a way to extend a class from another file. A stdlib class is read-only in the workspace, and a class with no stored source (a dependency class, or one made with ClassBuilder) fails with "Class source not available". In a .bt file, Foo >> sel => ... is valid only in the file that defines Foo, where it is folded into the class. In any other file it is a compile error, reported by build, check, lint, MCP lint, the LSP and Workspace load: (ADR 0152).

Hot Reload

When a class is reloaded (via Workspace load:, Counter reload, :sync, or an inline redefinition), existing actor instances pick up the new code on their next message send. State is preserved across the reload.

> Workspace load: "examples/counter.bt"
#(Counter)

> c := Counter spawn
Actor(Counter, 0.234.0)

> c increment
1

> c increment
2

// Edit counter.bt to change increment behavior, then:
> Counter reload
Counter

// Existing actor uses new code, state preserved
> c increment
12

Class-based reload uses the source file path recorded at load time:

> Counter sourceFile
examples/counter.bt

> Counter reload     // Recompiles from that path
Counter

> Integer sourceFile // Stdlib classes have no source file
nil

> Integer reload     // Cannot reload stdlib
ERROR: Integer has no source file

Workspace and Reflection Facades

Beamtalk and Workspace are ordinary sealed, stateless classes whose API is entirely class-side (ADR 0129) — no current accessor, no injected name. Beamtalk works in the REPL, in compiled code and via the MCP server; Workspace works wherever a workspace runs and raises no_workspace elsewhere (Workspace isAvailable asks without raising). See the language reference for the full tables.

Beamtalk — system reflection:

MethodDescription
versionBeamtalk version string
allClassesAll registered classes as class objects
classNamed: #CounterLook up a class by name
help: CounterFormatted class documentation
help: Counter selector: #incrementFormatted method documentation
erlangHelp: "lists"Documentation for an Erlang module (erlangHelp:selector: for one function)
releaseInfoThis node's release provenance (#{#release => nil} outside a release)
shapeManifestShape manifest of every registered project class

Logging and debug control (logLevel, enableDebug:, ...) live on Logger, not Beamtalk.

> Beamtalk version
0.6.0

> Beamtalk allClasses
#(Integer, String, Array, ...)

> Beamtalk classNamed: #Integer
Integer

Workspace (class: Workspace) — project operations:

MethodDescription
load: "path"Compile and hot-load one file (a directory raises eisdir; use sync)
syncSync workspace with project (beamtalk.toml)
classesAll loaded user classes
testClassesAll loaded test classes
isAvailableTrue iff a workspace is running (never raises)
bindingsLive view of the bind:as: entries
testRun all test classes
test: CounterTestRun a specific test class
bind: value as: #NameRegister a value in the workspace namespace
unbind: #NameRemove a workspace binding

Node facts (actors, actorsOf:, actorAt:, processes, supervisors) are on Node, e.g. Node current actors.

> Workspace load: "examples/counter.bt"
["Counter"]

> Workspace classes
#(Counter, ...)

> Node current actors unwrap
#(Actor(Counter, 0.234.0), ...)

> (Node current actorsOf: Counter) unwrap
#(Actor(Counter, 0.234.0))

> Workspace test
TestResult(3 tests, 3 passed (0.0s))

> Workspace bind: myActor as: #MyTool
nil

> MyTool
Actor(Counter, 0.234.0)

> Workspace unbind: #MyTool
nil

Variable Persistence and Name Resolution

REPL variable bindings are session-local — each connected REPL session has its own variable scope. Bindings persist across expressions within the same session but are lost when the session disconnects.

Workspace bindings (via Workspace bind:as:) are workspace-level — they persist across sessions and are visible to all connected clients.

Name resolution in a REPL expression follows a three-tier chain (ADR 0129 §7):

Session locals  →  Workspace bindings  →  Class registry
  x = 42            MyTool = <actor>       Integer = <class>
  counter = ...                            Counter = <class>
                                           Transcript = <class>
  1. Session locals — per-connection variables (x := 42), created by := assignment
  2. Workspace bindings — workspace-level names registered via Workspace bind:as: (listed by Workspace bindings)
  3. Class registry — every registered class, including the stdlib and the Beamtalk, Workspace, Transcript and SystemNavigation facades, which are ordinary classes rather than bindings

Method bodies and batch-compiled code use only the class registry. bind:as: refuses to shadow a registered class name; a plain assignment such as Integer := 3 creates a session local that shadows the class for that session only.

Common Workflows

Load, Edit, Reload, Test

The typical interactive development cycle:

> Workspace load: "src/counter.bt"          // Load the class
#(Counter)

> c := Counter spawn            // Try it out
Actor(Counter, 0.234.0)

> c increment
1

// ... edit counter.bt in your editor ...

> Counter reload               // Hot-reload the change
Counter

> c increment                   // Existing actor uses new code
11

> Workspace load: "test/counter_test.bt"     // Load tests
#(CounterTest)

> :test CounterTest             // Run tests
TestResult(2 tests, 2 passed (0.0s))

Project Sync Workflow

For projects with beamtalk.toml, use :sync to load the whole project:

> :sync                         // Initial load
Reloaded 5 of 5 files
Classes: Counter, Greeter, Logger, Shape, Square

// ... edit files ...

> :s                            // Incremental reload (short alias)
Reloaded 1 of 5 files (4 unchanged)
Classes: Counter

> :test                         // Run all tests
TestResult(10 tests, 10 passed (0.1s))

Prototyping with Inline Classes

Define and iterate on classes without creating files:

> Actor subclass: Greeter
..>   state: name = "World"
..>   greet => "Hello, " ++ self.name

> g := Greeter spawn
Actor(Greeter, 0.234.0)

> g greet
Hello, World

// Add a method
> Greeter >> greetWith: prefix => prefix ++ " " ++ self.name

> g greetWith: "Hi"
Hi World

// Replace a method
> Greeter >> greet => "Hey there, " ++ self.name

> g greet
Hey there, World

Actor Lifecycle Management

Inspect, stop, and kill actors through the workspace:

> c := Counter spawn
Actor(Counter, 0.234.0)

> c isAlive
true

> Node current actors              // See all live actors
#(Actor(Counter, 0.234.0))

> c stop                        // Graceful shutdown
ok

> c isAlive
false

> c stop                        // Idempotent
ok

Node current actors and the workspace actors op (what MCP list_actors, the VS Code sidebar and the connect snapshot show) list the same set: every live actor on the node, including native: actors and the runtime's own actors such as TranscriptStream. The runtime's own actors are marked "system": true in the JSON, and the text lists (the startup banner's "Available actors:" and MCP list_actors) print them with a trailing [system], for example TranscriptStream (<0.9.0>) [system]. inspect works on them; kill refuses them with a system_actor error. A native: pid whose backing module is shared by several classes is listed once, under the alphabetically first class.

MCP Server (AI Agent Interface)

Beamtalk includes an MCP (Model Context Protocol) server that gives AI coding agents structured access to the live workspace. The MCP tools connect via the same WebSocket protocol as the REPL and VS Code extension — the agent interacts with the same running system.

The server binary is beamtalk-mcp (generated projects get an .mcp.json that runs beamtalk-mcp --start, which starts a workspace if none is running). Tool names use underscores, exactly as listed below; beamtalk-surface-drift fails CI if this table and the server's tool list disagree.

Which workspace it attaches to (BT-5080). beamtalk-mcp attaches only to the running workspace of the current project; it never silently attaches to another project's. With no flag and no running workspace for this project, startup fails; if other projects' workspaces are running, the error names them and says to pick one with --workspace-id <id>, give a port with --port, or start this project's with --start. An explicit --workspace-id that is not running is an error and never falls back to a different workspace. Tool output shows which workspace a call touched: describe starts with a Workspace: <id> line, and flush, remove_class and rename_class end with one (Workspace: (explicit --port) when the server was given --port).

Path arguments of lint, diagnostic_summary, load_file, load_project, test (file) and export_traces are confined to the project root (symlinks and .. are resolved); pass --allow-outside-project to beamtalk-mcp to lift that. Every tool carries MCP readOnlyHint, and every non-read-only tool a destructiveHint.

MCP ToolDescription
evaluateRun any Beamtalk expression in the workspace (optional timeout_secs overrides the default 30 s; BEAMTALK_MCP_EVAL_TIMEOUT env var sets the server-wide default; trace=true returns per-statement step values)
completeAutocompletion suggestions for partial input
interruptCancel a running evaluation
inspectInspect a running actor's state by PID
show_codegenShow generated Core Erlang for an expression (code) or a loaded class (class, optional selector)
load_fileCompile and hot-load a .bt file
load_projectLoad all project files in dependency order
reload_classHot-reload a class, migrating running actors to the new code
unloadUnload a class from the workspace (running actors are unaffected)
list_classesList loaded Beamtalk classes (optional superclass filter, optional scope: stdlib or user)
list_packagesList loaded packages with versions, class counts and dependencies
package_classesList the classes belonging to a named package
docsQuery class/method documentation (class, or erlang_module for Erlang FFI, plus optional selector)
testRun tests (all, by class, or by file; class and file are mutually exclusive)
lintStyle and redundancy lint of a file or directory (path, warnings_as_errors)
search_examplesSearch the bundled example corpus (offline)
search_classesSearch class names and documentation (offline)
describeDiscover the supported REPL operations and protocol version
list_actorsList live actors (PID and class)
supervision_treeSnapshot the live supervision tree (scope: default or system)
nodesList connected BEAM nodes with their shape-skew counts
save_methodDurable live patch (ADR 0082): wraps aClass compile: #sel source: body; logs a durable ChangeEntry
try_methodEphemeral spike (ADR 0082): wraps aClass tryCompile: #sel source: body; logs an ephemeral ChangeEntry (not flushable — pruned on workspace restart or via Workspace changes clear)
save_classCreate a new class file (ADR 0082): sends the save-class op (Workspace newClass: source at: path semantics); logs a kind: #'new-class' ChangeEntry (flush writes the file to disk)
remove_methodRemove a method from a class (ADR 0112): wraps Behaviour>>removeSelector: with optional if_absent fallback
remove_classRemove a class entirely (ADR 0113): wraps removeFromSystem, returns the resulting remove-class ChangeEntry
rename_classRename a class in the running system (ADR 0114): wraps renameTo:, auto-rewriting in-project cross-file references
rename_methodRename a method on a class (ADR 0114): wraps renameSelector:to: (instance-side only), auto-rewriting only structurally-safe self/super sends
flushWrite pending durable changes to disk (ADR 0082): wraps Workspace flush (optional class / file / kind argument selects a subset). Pass confirm_destructive: true to include Tier 2 entries (remove-class/rename-class/rename-method — file deletion or multi-file rewrite)
list_changesWraps Workspace changes — serialised view of the pending ChangeLog
dirty_methodsWraps Workspace changes dirtyMethods — per-class set of dirty selectors
enable_tracingEnable detailed trace event capture for actor dispatch (also switches on the opt-in [beamtalk, actor, dispatch, *] telemetry events, BT-4113)
disable_tracingDisable trace event capture (aggregate stats remain)
get_tracesRetrieve trace events with optional filters (actor, selector, class, outcome, duration)
export_tracesExport trace events to a JSON file
actor_statsGet aggregate per-actor, per-method statistics (call counts, durations, error rates)
precheck_methodPre-save advisory (ADR 0105 Phase 3): compile a pending method edit and report would-be-stale dependents without installing it
recheck_imageWhole-image re-check (ADR 0105 Phase 3): re-check all live classes for stale callers and broken signatures
diagnostic_summaryAggregated diagnostic counts by category/severity plus type-coverage stats (offline)

All MCP tools map to the same Workspace and Beamtalk APIs available in the REPL. The tracing tools correspond to the Tracing stdlib class (see Language Features — Actor Observability). The live-edit save tools (save_method, try_method, save_class, remove_method, remove_class, rename_class, rename_method, flush, list_changes, dirty_methods) correspond to the ChangeLog model (see Language Features — Saving live edits back to disk); the same operations are exposed to editors via the LSP executeCommand handlers beamtalk.flush, beamtalk.flush.class, beamtalk.flush.file, beamtalk.flush.kind, beamtalk.saveClass, and beamtalk.removeMethod, which emit workspace/applyEdit on each flushed file so open buffers refresh automatically. When a destructive flush deletes a .bt file, the LSP emits a typed DeleteFile resource operation so the editor closes any open buffer for the removed file. When a destructive flush renames/moves a class file, the LSP sends a custom beamtalk-lsp/documentMoved notification ({oldUri, newUri}) so the VS Code extension can retarget open tabs; cross-file reference rewrites emit TextDocumentEdit per confirmed site (see surface-parity.md for the full breakdown).

VS Code Extension

The Beamtalk VS Code extension connects to the live workspace and provides:

The extension connects to the same workspace as the REPL and MCP server. Changes made in VS Code (file saves trigger hot-reload) are immediately visible in the REPL and to AI agents.

LiveView IDE

The LiveView IDE is a Phoenix LiveView client that connects to the workspace over Erlang distribution (the Attach topology), bypassing the WebSocket JSON protocol entirely. It consumes native op_result() terms end-to-end via beamtalk_repl_ops:dispatch/4.

just web-setup    # mix deps.get + asset build
just web <name>   # Start the LiveView IDE, connecting to workspace <name>

Current capabilities (Cockpit UI):

Packaging: The IDE ships on its own release lane (separate from the beamtalk toolchain bundle). Three installation paths:

Version is derived from the repo VERSION file. See editors/liveview/README.md and docs/deployment/remote-liveview-ide.md for full setup and remote deployment.

Testing Framework

Beamtalk includes a native test framework inspired by Smalltalk's SUnit.

// stdlib/test/counter_test.bt

TestCase subclass: CounterTest

  testInitialValue =>
    self assert: (Counter spawn getValue) equals: 0

  testIncrement =>
    self assert: (Counter spawn increment) equals: 1

  testMultipleIncrements =>
    counter := Counter spawn
    3 timesRepeat: [counter increment]
    self assert: (counter getValue) equals: 3

Each test method gets a fresh instance with setUp → test → tearDown lifecycle.

Assertion Methods

MethodDescriptionExample
assert:Assert condition is trueself assert: (x > 0)
assert:equals:Assert two values are equalself assert: result equals: 42
deny:Assert condition is falseself deny: list isEmpty
should:raise:Assert block raises errorself should: [1 / 0] raise: #badarith
fail:Unconditional failureself fail: "not implemented"

Running Tests

// From the REPL:
> Workspace load: "stdlib/test/counter_test.bt"
#(CounterTest)

> :test CounterTest
TestResult(2 tests, 2 passed (0.0s))

// Equivalent native API — works from compiled code too:
> (Workspace test: CounterTest) failed
// => 0

Parallel Test Runner

By default, beamtalk test runs test classes concurrently using the BEAM scheduler count:

beamtalk test              # Auto parallelism (default)
beamtalk test --jobs 4     # Up to 4 classes concurrently
beamtalk test -j 1         # Sequential (backward-compatible)
beamtalk test --raw-mfa    # Every stack frame per failure (hidden ones too), raw module:function/arity beside each name

From code: TestRunner runAll: 0 (auto), TestRunner runAll: 4 (bounded), TestRunner runAll (sequential).

Serial opt-out: Test classes that touch global state (registered names, ETS tables, TranscriptStream) should override serial to prevent interference:

TestCase subclass: TracingTest
  class serial -> Boolean => true

  testEnable =>
    self assert: Tracing isEnabled equals: false

Serial classes run alone, sequentially, after all concurrent classes complete.

Type Coverage (ADR 0077)

beamtalk type-coverage reports what percentage of expressions in your project have non-Dynamic inferred types. This helps track type adoption progress and gate CI on coverage regressions.

Basic Usage

$ beamtalk type-coverage
Type Coverage Report
====================

File                          Class              Coverage
src/account_service.bt        AccountService     92.3%  (48/52 expressions, 0 narrowing)
src/router.bt                 Router             87.1%  (54/62 expressions, 0 narrowing)
src/config_loader.bt          ConfigLoader       71.4%  (30/42 expressions, 0 narrowing)
src/my_app.bt                 MyApp              45.0%  (9/20 expressions, 0 narrowing)
──────────────────────────────────────────────────────────────────────
Total                                            80.1%  (141/176 expressions, 0 narrowing)

Coverage is defined as (expressions with non-Dynamic inferred type) / (total expressions in the TypeMap). Every AST node that produces a TypeMap entry is counted — identifiers, message sends, assignments, literals, block bodies, and binary operations. Sub-expressions are counted individually.

Flags

FlagDescription
--detailShow each Dynamic expression and each narrowing cast with file:line:col location
--format jsonMachine-readable JSON output for dashboards and CI
--at-least NExit non-zero if total coverage < N% (CI ratchet)
--class ClassNameFilter to a specific class

Narrowing Casts (BT-4719)

A local annotation narrower than its right-hand side, such as n :: Integer := opts at: #max, is an unchecked cast: nothing verifies it at runtime. type-coverage counts these separately, per class (the narrowing column) and in total, and --detail lists each as file:line:col (:: Integer from Dynamic). JSON output carries narrowing_casts on the report and on each class, plus narrowing_entries under --detail. The coverage percentage is unchanged. To flag them as diagnostics, enable the opt-in narrowing-cast lint under [diagnostics] (off by default). See Local Variable Type Annotations.

Detail Mode

$ beamtalk type-coverage --detail --class MyApp
Type Coverage Report
====================

File                          Class              Coverage
src/my_app.bt                 MyApp              45.0%  (9/20 expressions, 0 narrowing)
──────────────────────────────────────────────────────────────────────
Total                                            45.0%  (9/20 expressions, 0 narrowing)

Dynamic expressions:
  src/my_app.bt:12:5                             (unannotated return)
  src/my_app.bt:15:9                             (dynamic receiver)
  src/my_app.bt:18:5                             (dynamic receiver)
  ...

Each Dynamic expression shows its file:line:col location and the reason the type could not be determined. The reason strings match those shown in LSP hover (see Dynamic Type Visibility).

CI Integration

Use --at-least to prevent coverage regressions in CI pipelines:

# In CI pipeline
- run: beamtalk type-coverage --at-least 75 --format json

The command exits non-zero if total coverage falls below the threshold. JSON output includes a passed field for easy scripting:

{
  "total_expressions": 176,
  "typed_expressions": 141,
  "coverage_percent": 80.1,
  "threshold": 75,
  "passed": true,
  "classes": [
    {
      "name": "AccountService",
      "file": "src/account_service.bt",
      "total": 52,
      "typed": 48,
      "coverage_percent": 92.3
    }
  ]
}

Scope and Limitations

Shared Protocol Architecture

All browser-facing interfaces — REPL, VS Code, MCP — connect to the same live BEAM workspace node via the same WebSocket JSON protocol (beamtalk_ws_handler). This means:

Adding a new WebSocket-based interface requires only a protocol adapter over the existing transport. The LiveView IDE uses an alternative Attach topology — it runs as a separate BEAM node and calls into the workspace over Erlang distribution, consuming native op_result() terms from beamtalk_repl_ops:dispatch/4 without the JSON encoding step.

Native Erlang Integration

For packages that need hand-written Erlang code — gen_server implementations, hex.pm dependencies, or direct OTP control — see the Native Erlang Integration guide. It covers the native/ directory layout, the native: keyword for actor classes, the generate native stub generator, and hex dependency management via [native.dependencies] in beamtalk.toml.