CLI Developer Tools

Developer Tooling & Testing

Built-in automated test runner with assertions, canonical source code formatter, standalone native binary compiler, and package management.

Interactive REPL

Modern Terminal REPL Experience

BramandScript features a sleek, minimal, high-productivity terminal REPL built directly into the unified CLI (bramand repl or bmd repl). Designed with a clean international aesthetic adhering to our strict No-Emojis Policy, it presents crisp Unicode indicators (✦, ❯, ·), automatic block-depth continuation prompts, and built-in execution timing:

terminal — modern bmd repl session
✦ BramandScript 0.1.2 (arm64-linux) · High-Performance Bytecode VM
  Type :help for documentation, :editor for multi-line, :exit to quit.

✦ bmd ❯ let greeting = "Hello, Universe!"
✦ bmd ❯ println(greeting)
Hello, Universe!

✦ bmd ❯ fn factorial(n) {
· ···     if n <= 1 { return 1 }
· ···     return n * factorial(n - 1)
· ···   }
✦ bmd ❯ factorial(7)
5040

Multi-Line Buffer Editor Mode (:editor)

Type :editor or :edit [filename.bmd] to switch into multi-line buffered mode. Line numbers are automatically rendered, allowing you to edit multi-statement modules and functions before compiling. Type :done to execute or save directly to disk with :done <filename.bmd>:

terminal — :editor mode
✦ bmd ❯ :editor math_util.bmd
__________________________________________________________________
Multi-Line Editor Mode
Type code line-by-line. Type :done to execute, :cancel to abort.
To save to file on disk: :done <filename.bmd>
__________________________________________________________________
01 | fn is_prime(n) {
02 |   if n <= 1 { return false }
03 |   let i = 2
04 |   while i * i <= n {
05 |     if n % i == 0 { return false }
06 |     i += 1
07 |   }
08 |   return true
09 | }
10 | println("Is 97 prime?", is_prime(97))
11 | :done
[OK] Saved 210 bytes to math_util.bmd
Executing buffer...
Is 97 prime? true

REPL Subcommands Reference

Command Description
:help Displays BramandScript language cheat sheet and syntax quick reference.
:editor / :edit [file] Enters multi-line buffered editor mode with line numbers and optional file destination.
:done [file] Compiles and executes editor buffer; optionally writes source code to disk.
:cancel Discards multi-line buffer and returns to standard REPL prompt.
:clear Clears terminal display and scrolls to top of viewport.
:reset Wipes VM symbol table, constant pool, and global variables store for a clean state.
:exit / :quit Gracefully closes REPL and exits to host terminal shell.
Diagnostics Engine

Zero-Box Clang/Rust-Style Diagnostic Engine

BramandScript employs a zero-box diagnostic formatter engineered for international terminal compatibility. Box-drawing characters (╭───╮, │, ╰───╯) commonly cause severe wrapping artifacts, broken vertical margins, and copy-paste corruptions on narrow mobile screens (Termux ARM64) and varied console emulators.

Our diagnostic engine replaces all box characters with clean, standard Clang/Rust-style vertical gutters (|), clickable file location links (--> file:line:col), 5-line contextual source windows, exact caret pointers (^), token span underlines (~~~), and actionable inline hints ([Hint: ...]):

terminal — zero-box compiler diagnostic
✦ error[SyntaxError]: expected next token to be RPAREN, got INT instead
  --> server.bmd:14:28
   |
 9 |   let port = 8080
10 |   let host = "0.0.0.0"
11 |   
12 |   fn start_listener() {
13 |       println("Listening on", host, port)
14 |       if (connection_count > 100 200) {
   |                              ^~~ [Hint: check syntax for missing operator, parenthesis, or delimiter]
15 |           println("Server under load")
16 |       }
17 |   }
18 |   
19 |   start_listener()
   |

Diagnostic Architectural Principles

  • Clickable Hyperlinks (--> file:line:col): Formatted according to GNU/Rust convention, enabling direct click-to-open in VSCode, JetBrains, and modern terminal multiplexers.
  • 5-Line Source Window Context: Automatically loads up to 5 preceding and 5 succeeding lines surrounding the defect for instant situational context.
  • Exact Caret & Span Highlighting (^~~~): The caret points to the starting column, while tildes underline the token width.
  • Actionable Intelligence ([Hint: ...]): Every diagnostic is paired with heuristic rules that explain likely remedies directly in the terminal.
Tooling & Verification

CLI Test Runner & Native Testing Suite

BramandScript ships with a built-in zero-dependency testing framework and test runner. Run automated tests with microsecond reporting, sub-suite nesting, rich colored diagnostics, and micro-benchmarking:

bash — Test Runner CLI
# Recursively discover and execute all *_test.bmd and test_*.bmd files
bramand test

# Run specific test file or directory
bramand test tests/
bramand test tests/01_language_foundation_test.bmd

Writing Test Suites (describe, test, assert_*)

bramand — math_test.bmd
describe("Arithmetic & Vector Mathematics", fn() {
    test("Addition and scalar operations", fn() {
        let x = 15 + 25
        assert_eq(x, 40)
        assert_ne(x, 0)
        assert_true(x > 30)
        assert_false(x < 10)
    })

    test("Deep collection equality", fn() {
        assert_eq([1, 2, 3], [1, 2, 3])
        assert_eq({"status": "ok"}, {"status": "ok"})
        assert_not_null({"status": "ok"})
        assert_null(null)
    })
})
Code Formatter

Canonical Code Formatter (bramand fmt)

BramandScript includes a deterministic opinionated formatter built directly into the CLI toolchain (analogous to gofmt / cargo fmt). It normalizes indentation to 4 spaces, aligns operator spacing, cleans trailing whitespace, and verifies AST integrity:

bash — Formatter CLI
# Format all .bmd files in current project in-place
bramand fmt

# Check if files adhere to canonical style (CI validation, exits 1 if unformatted)
bramand fmt -c
bramand fmt --check src/

# Format a specific file
bramand fmt examples/01_quickstart.bmd
Standalone Compilation

Standalone Executable Compilation (bmd build)

Compile any BramandScript program into a completely self-contained, native executable. The generated binary contains the zero-dependency Bramand bytecode engine and an embedded virtual filesystem bundle (BMD_BUNDLE_V2), capable of running instantly on target systems without requiring Go or Bramand to be installed.

Single-Binary Embedding of Global Dependencies

When compiling a program with bmd build, the compiler recursively traverses all static and dynamic import statements across your project. It bundles not only local sibling source files, but also all resolved third-party packages from the centralized registry ($HOME/.bmd_libs/registry/) directly into the binary's compressed virtual filesystem.

bash — Standalone Single-Binary Builder
# Build a standalone native binary bundling all dependencies
bmd build app.bmd -o my_app

# Build with Ahead-of-Time constant folding and opcode optimization
bmd build -O app.bmd -o my_app_optimized

# Execute standalone binary anywhere (no Go, no interpreter, zero dependencies!)
./my_app
Self-Contained Virtual Filesystem (embed:bundle/)

During standalone execution, the VM automatically intercepts imports matching bundled dependencies and resolves them transparently from the in-memory payload without requiring access to the host's $HOME/.bmd_libs/ directory or any active network connection.

Bytecode & Performance

Bytecode Disassembler & Execution Profiler

Inspect generated VM instructions and identify runtime bottlenecks using the built-in disassembler and profiler:

bash — CLI Disassembler & Profiler
# Disassemble source file to bytecode instructions and constant pool
bramand disasm app.bmd

# Profile program execution with opcode timing and hotspot analysis
bramand profile app.bmd
Dependency & Package Architecture

Centralized Package Manager & Dependency Engine (bmd pkg)

BramandScript features a production-grade, centralized package management engine inspired by modern ecosystems like Go and Deno. Rather than littering disk storage with bloated, redundant per-project folders (node_modules/), all external modules, tarball archives, and versioned registries are stored in a single, system-wide centralized store at $HOME/.bmd_libs/.

Centralized Storage Hierarchy ($HOME/.bmd_libs/)

The centralized tree layout isolates immutable compressed tarballs, live unpacked registry packages, and cryptographic integrity locks:

filesystem — ~/.bmd_libs Tree Layout
$HOME/.bmd_libs/
├── cache/
│   └── tarballs/               # Immutable downloaded archives (.tar.gz, .zip)
│       ├── github_com_user_pkg_v1.0.0.tar.gz
│       └── cdn_a8f3b9..._v2.1.0.tar.gz
├── registry/                   # Unpacked module trees ready for runtime import
│   ├── github.com/
│   │   └── <author>/
│   │       └── <pkg>/
│   │           ├── 1.0.0/      # Versioned release directory
│   │           │   ├── bmdpkg.json
│   │           │   └── main.bmd
│   │           └── 1.2.0/      # Co-existing release directory
│   ├── cdn/
│   │   └── <domain_hash>/
│   │       └── <version>/
│   └── local/                  # Local development package links
│       └── <name>@dev/
└── locks/
    ├── integrity.db            # JSON registry of SHA-256 hashes, sizes & timestamps
    └── *.lock                  # Inter-process atomic flock & channel lock files
Environment VariableDefaultDescription
BMD_LIBS_DIR$HOME/.bmd_libsCustom directory location for the centralized cache, registry, and lock files.
BMD_OFFLINE0When set to 1 or true, enforces offline-first determinism; forbids all outbound network traffic.
BRAMAND_LIBS_DIR$HOME/.bmd_libsLegacy fallback variable for backwards compatibility.

Unified CLI Commands Reference

The package manager provides high-speed, deterministic commands built directly into the unified bmd CLI with zero external dependencies:

✦ 1. bmd install <target> [version] [--offline]

Downloads, verifies, and installs a package into the centralized registry. Supports GitHub repositories, direct CDN tarball URLs, local project directories, and local development links:

# Install from GitHub repository with optional SemVer tag
bmd install github.com/alice/json-tools
bmd install github.com/alice/json-tools 1.2.0

# Install from remote CDN archive URL
bmd install https://cdn.bmd.io/packages/matrix-math.tar.gz

# Link local directory for active development
bmd install ./libs/my_utils
bmd install local/my_utils@dev

# Strictly offline installation from local cache
bmd install --offline github.com/alice/json-tools 1.2.0

Zero-Redundancy Optimization: If the tarball archive already exists in cache/tarballs/ and matches its SHA-256 hash in integrity.db, 0 bytes are downloaded.

✦ 2. bmd get [dir] [--offline]

Synchronizes project dependencies declared in bmdpkg.json. Recursively inspects the dependency graph, resolves diamond dependencies to the highest compatible SemVer, and downloads only missing packages:

# Synchronize all dependencies for current project
bmd get

# Synchronize dependencies for another directory
bmd get ./services/api_gateway

# Offline synchronization using existing centralized registry
bmd get --offline
✦ 3. Centralized Cache Maintenance (bmd cache)

Monitor, clean, and verify cryptographic integrity across all cached tarballs and registry packages:

# Display storage metrics, tarball counts, and integrity database statistics
bmd cache info

# Prune orphaned tarball archives while safely keeping live registry trees
bmd cache prune

# Verify SHA-256 cryptographic checksums of all packages against integrity.db
bmd cache verify
✦ 4. Package Scaffolding & Listing (bmd pkg init & bmd pkg list)

Scaffold standardized package templates and view installed registry modules:

# Initialize a new package with bmdpkg.json manifest and main.bmd
bmd pkg init my-library

# List project dependencies and globally available registry packages
bmd pkg list

Package Manifest Specification (bmdpkg.json)

Every BramandScript package is described by a standardized JSON manifest named bmdpkg.json located in the root of the package directory:

json — bmdpkg.json Specification
{
  "name": "data-transformer",
  "version": "1.4.2",
  "description": "High-speed stream parsing and statistical transformation utilities",
  "entry": "src/index.bmd",
  "license": "MIT",
  "authors": ["Codeleafly <ziprecovery2024@gmail.com>"],
  "permissions": {
    "network": false,
    "filesystem_read": true,
    "filesystem_write": false,
    "subprocess": false
  },
  "dependencies": {
    "github.com/alice/json-tools": "^1.2.0",
    "github.com/bob/matrix-core": ">=2.0.0"
  },
  "compatibility": {
    "bmd_min": "0.1.0",
    "architecture": ["arm64", "amd64"]
  }
}
FieldTypeRequirementDescription & Validation Rules
nameStringRequiredPackage identifier. Matches ^[a-zA-Z0-9_.\-]+(/[a-zA-Z0-9_.\-]+)*$.
versionStringRequiredValid SemVer 2.0 version string (e.g., 1.4.2) or dev.
descriptionStringOptionalHuman-readable synopsis of package functionality.
entryStringOptionalPrimary entrypoint file relative to package root. Cannot traverse outside package root.
licenseStringOptionalStandard SPDX license identifier (e.g., MIT, Apache-2.0).
authorsArray[String]OptionalList of author names, usernames, or contact emails.
permissionsObjectRecommendedExplicit sandbox capability declarations (network, filesystem_read, filesystem_write, subprocess).
dependenciesMap[String]StringOptionalDirect dependencies mapped to SemVer constraints or versions.
compatibilityObjectOptionalEngine compatibility contract (bmd_min minimum Bramand version and target architectures).

Three-Tier Entrypoint Fallback Engine

When a package directory is imported without referencing an explicit subfile (e.g., import "github.com/alice/json-tools" as json), BramandScript's compiler executes the deterministic Three-Tier Fallback Engine:

Tier 1

Manifest Entry

Inspects bmdpkg.json. If "entry" is defined, resolves to specified file (e.g. src/index.bmd). If defined file is missing, aborts immediately with BrokenManifestError.

Tier 2

main.bmd Fallback

If no "entry" is set or manifest is absent, looks for main.bmd in the package root. If present, resolves as module entrypoint.

Tier 3

index.bmd Fallback

If main.bmd does not exist, looks for index.bmd. If none of the 3 candidates exist, compiler halts with a clean diagnostic error.

terminal — Diagnostic Output on Missing Entrypoint
[ERROR] No entrypoint found: package must define bmdpkg.json, main.bmd, or index.bmd: /home/user/.bmd_libs/registry/github.com/alice/broken-pkg/1.0.0

Supply-Chain Permission Contracts & Sandboxing

To protect host systems from malicious supply-chain attacks, third-party packages must declare what capabilities they require in their bmdpkg.json manifest under the "permissions" object:

network

TCP / UDP / HTTP sockets

filesystem_read

read_file, exists, stat

filesystem_write

write_file, delete_file

subprocess

exec, external processes

✦ Install-Time Supply Chain Warning Notice

Whenever an installed package requests sensitive capabilities (network, filesystem_write, or subprocess), the package installer alerts the developer with a prominent security notice:

✦ [SECURITY NOTICE] Package requests host permissions: network, subprocess

VM Runtime Sandboxing (OpEnterPackage & OpLeavePackage): During bytecode execution, the VM tracks the active package contract stack. Even if the user executes the host program with --allow-all, an imported package cannot invoke restricted operations unless those permissions were declared in its own bmdpkg.json. Any violation halts execution with a PermissionDenied runtime error.

Self-Hosted Package Registry Server (tools/registry_server.bmd)

For private enterprise deployments, offline air-gapped networks, or internal development teams, BramandScript includes a lightweight, self-contained package registry server authored in 100% pure BramandScript (tools/registry_server.bmd). It provides publish APIs, tarball archive storage, semver resolution, and package search:

bash — Run Private Registry Server
# Start package registry server on default port 8080
bmd run tools/registry_server.bmd

# Run test suite for package publishing, searching, and versioning
bmd test tests/15_day14_registry_test.bmd
Compiler Optimization & Verification

AOT Compiler Optimizer & Scientific Benchmarks (-O)

BramandScript includes an Ahead-of-Time (AOT) optimization pass that pre-evaluates constant expressions in the AST (compiler/optimizer.go) and performs peephole opcode compaction. Pass the -O or --optimize flag to run, build, or disasm to activate compile-time optimization:

bash — Optimizing Compiler CLI Flags
# Run source file with Ahead-of-Time optimizations enabled
bramand run -O app.bmd

# Compile standalone native binary with optimized bytecode
bramand build -O app.bmd -o app_release

# Disassemble optimized bytecode to inspect constant folded opcodes
bramand disasm -O app.bmd

# Execute the comprehensive scientific benchmark suite
bramand run benchmarks/math_benchmarks.bmd
Constant Folding & Instruction Reduction

Expressions like let x = 2 * 3 + 4 * 5 are folded into a single constant 26 at compile time, reducing instruction count and eliminating runtime stack pushes. Consecutive duplicate/pop operations are eliminated during the peephole stage.

Runtime Permission Guards & Configurable Stack

Control execution safety and system resources using explicit runtime flags:

bash — Permission & Stack Options
# Grant all execution, file system, and network capabilities
bramand run --allow-all app.bmd

# Granular capability grants
bramand run --allow-run script.bmd       # Allow exec()
bramand run --allow-write script.bmd     # Allow write_file(), delete_file()
bramand run --allow-net server.bmd       # Allow tcp_listen()

# Custom call stack depth limit
bramand run --max-frames 2048 deep_recursion.bmd

CLI Runtime Options & Security Flags Reference

Option / FlagDefaultDescription & Protected Operations
--allow-allfalseGrants all permissions (process execution, file system mutation, and network listening).
--allow-runfalseAuthorizes execution of external subprocesses via exec().
--allow-writefalseAuthorizes file system write and delete mutations (write_file(), append_file(), delete_file()).
--allow-netfalseAuthorizes host network socket listening (tcp_listen(), web servers).
--max-frames <N>1024Sets maximum call stack frame limit for deep recursive algorithms.
-OfalseEnables ahead-of-time (AOT) constant folding and peephole bytecode optimization.
Day 35 Standard Testing & Performance

Built-in Benchmarking & Automated Fuzz Testing (bmd bench & bmd fuzz)

BramandScript provides production-grade performance benchmarking and mutation-based fuzz testing directly integrated into the VM engine and unified CLI toolchain:

1. Built-in Micro-Benchmarking Framework (bmd bench)

The bench(name, fn) primitive dynamically scales iterations (b.n) until statistical timing converges, reporting nanoseconds per op (ns/op), bytes allocated (B/op), and heap allocations (allocs/op):

bmd — benchmark implementation
import "std/testing" as testing;

testing.bench("Array push 1000 items", fn(b) {
    let i = 0;
    while i < b.n {
        let arr = [];
        let j = 0;
        while j < 1000 {
            push(arr, j);
            j = j + 1;
        }
        i = i + 1;
    }
});
bash — CLI Benchmark Execution
# Run all benchmarks in file
bmd bench benchmarks/stream_benchmarks.bmd

# Output:
# ✦ BramandScript Benchmark Runner
# BenchmarkArrayPush1000Items    50000    24100 ns/op    8192 B/op    10 allocs/op
# PASS: 1 benchmarks completed

2. Automated Fuzz Testing Engine (bmd fuzz)

The fuzz(target_fn, options) primitive mutates input corpora using byte-flipping, random insertions, character deletions, and boundary value injections to uncover unexpected crashes, boundary violations, or infinite loops:

bmd — fuzz testing target
import "std/testing" as testing;
import "std/json" as json;

testing.fuzz(fn(data) {
    // Parser must never crash with uncaught host panic
    try {
        json.parse(data);
    } catch err {
        // Handled parsing errors are valid outcomes
    }
}, {"iterations": 500, "corpus": ["{}", "{\"a\": 1}", "[]"]});
bash — CLI Fuzz Execution
# Run fuzz tests targeting edge cases
bmd fuzz tests/fuzz_json.bmd

# Output:
# ✦ BramandScript Fuzz Testing Engine
# FuzzJSONParser    500 runs    0 crashes    0 defects
# PASS: Fuzzing completed successfully
Day 35 Standard Time-Travel Debugging

Time-Travel Execution Recorder & Replay Debugger (bmd record & bmd replay)

BramandScript introduces deterministic step execution recording. Developers can record a full VM execution session to a JSON trace file and step backward and forward through time to pinpoint defects with zero guesswork:

bash — Record and Replay Execution Trace
# Record program execution into trace file
bmd record script.bmd -o trace.json

# Launch interactive time-travel replay debugger
bmd replay trace.json

Interactive Replay Commands

CommandAliasDescription
steps, n, nextSteps forward one VM instruction in time.
step_backb, back, prevSteps backward one instruction in time, restoring previous stack and frame state.
historyh, logDisplays execution history window with the current position indicator (❯).
goto <step>g, jumpJumps directly to any step checkpoint in execution history.
inspecti, stateInspects top of operand stack, stack depth, and frame pointers at current step.
help?Displays all available interactive time-travel debugger commands.
quitq, exitExits the time-travel replay session.
Self-Hosted Toolchain

100% Native BramandScript Tooling Ecosystem (tools/ & std/tooling/)

Following the industry-standard runtime architecture popularized by Node.js—where the core execution engine (V8 in C++) is kept minimal and performant while high-level tooling, REPLs, and CLI workflows are written directly in the language itself—BramandScript provides a complete suite of developer tools authored natively in 100% pure BramandScript (.bmd).

This architecture ensures that language enhancements immediately benefit the tooling ecosystem while validating the VM's real-world robustness through complete self-hosting and application dogfooding (Rule 11 & Rule 12).

✦ Native REPL (tools/repl.bmd)

Stateful persistent session evaluation with multi-line delimiter depth tracking, ANSI TrueColor syntax rendering, and commands (:help, :reset, :env, :disasm).

bramand bmd-repl
✦ Master CLI Router (tools/cli.bmd)

Unified command dispatcher routing run, repl, test, fmt, pkg, disasm, and bench with automated help screens.

bramand cli <command> [args]
✦ Test Discovery Runner (tools/test_runner.bmd)

Automated recursive test suite discovery (*_test.bmd), execution time measurement in ms, and clean status reporting.

bramand bmd-test [path]
✦ Package Manager (tools/pkg_manager.bmd)

Local and remote package installation, manifest generation (package.bmd), and module uninstallation in ~/.bramand_libs/.

bramand bmd-pkg install <pkg>
✦ Bytecode Disassembler (tools/disasm.bmd)

Parses and compiles source code, outputting annotated VM instructions, operand values, jump targets, and constant tables.

bramand bmd-disasm app.bmd
✦ Canonical Formatter (tools/formatter.bmd)

Pure BramandScript source code formatter with indentation normalization, operator spacing, and verification checking (-c).

bramand bmd-fmt [paths]
✦ Package Registry Server (tools/registry_server.bmd)

Self-contained HTTP package registry server providing publish APIs, tarball artifact storage, semver resolution, and search endpoints.

bramand run tools/registry_server.bmd
✦ Project Task Tracker (tools/task.bmd / bmd-task)

Strict roadmap and milestone tracking tool written in 100% native BramandScript managing weekly task manifests under date/MMYY/ with automatic status checkboxes.

bmd-task list

Underlying VM Primitives

The native tooling ecosystem is enabled by four high-performance reflection and evaluation primitives exposed by the Go VM engine:

Primitive BuiltinSignatureReturnEngine Description
create_sessioncreate_session()SESSIONAllocates a persistent stateful evaluation session with dedicated symbol table and globals store.
session_varssession_vars(sess)HASHExtracts a dictionary of all actively bound user identifiers and their current runtime values.
evaleval(code, [session])ANYCompiles and executes source strings, retaining symbols and mutations when passed a session.
disasmdisasm(target)STRINGInspects compiled bytecode and returns formatted human-readable opcode disassembly.