Brain.md - Context Control Protocol for LLMs

Brain.md is a CLI tool that compiles human-readable brain.md files into token-optimized TOON (Token-Oriented Object Notation) payloads for injection into Large Language Model (LLM) context windows.

Features

  • TOON Parser: Full-featured parser supporting sections, key-value pairs, tabular arrays, and heredocs

  • Pointer Resolution: Automatically resolves and injects external file references

  • Live Context Management: brain boot creates editable context.md for session state

  • Watch Mode: Auto-recompiles on file changes with debouncing and OS notifications

  • Token Budget Enforcement: Ensures payloads stay within specified token limits

  • Mode-Specific Prompts: Supports Strict, Creative, and Analysis driver prompt modes

  • Comment Stripping: Removes comments from final payload while preserving in source files

Installation

pip install -e ".[dev]"

Quick Start

# Create a brain.md file
cat > brain.md <<'EOF'
KERNEL:
  role: "Senior Developer"
  mode: "Strict/Code-Only"
  token_budget: 4000

MEMORY_POINTERS[1]{type, path, description}:
  file, "@schema.sql", "Database schema"
EOF'

# Boot a session (creates context.md with SESSION_SCRATCHPAD)
brain boot brain.md

# Watch for changes
brain watch context.md

Indices and tables

API Reference

Brain.md - Context Control Protocol for LLMs.

TOON Compiler - Resolves @pointers and assembles payload.

brain_md.compiler.compile_brain(source: Path) CompileResult[source]

Compile a brain.md file into a TOON payload.

  1. Parse the source file using TOON parser

  2. Extract configuration from KERNEL section

  3. Detect @pointer references

  4. Resolve and inject file contents as appendix

  5. Return CompileResult with metadata

Parameters:

source – Path to brain.md file

Returns:

CompileResult with payload, token count, and metadata

Raises:

CompileError – If compilation fails or pointers not found

brain_md.compiler.parse_pointer(pointer: str) tuple[str, tuple[int, int] | None][source]

Parse a pointer string into path and optional line range.

Examples

“schema.sql” -> (“schema.sql”, None) “schema.sql:20-50” -> (“schema.sql”, (20, 50))

brain_md.compiler.generate_driver_prompt(kernel: dict) str[source]

Generate mode-specific driver prompt.

Parameters:

kernel – KERNEL section dictionary

Returns:

Driver prompt string based on mode

brain_md.compiler.validate_brain_config(config: BrainConfig) None[source]

Validate BrainConfig structure and raise errors if malformed.

Checks: - KERNEL and REGISTERS are dictionaries (key-value pairs) - MEMORY_POINTERS and PROCESS_STACK are lists (tabular arrays)

Raises:

ParseError – If structure is invalid

TOON Parser - Token-Oriented Object Notation parser.

brain_md.parser.parse_toon(content: str) dict[source]

Parse TOON formatted content into a dictionary.

Handles: - SECTION: headers - key: value pairs with two-space indentation - # comments (stripped) - SECTION[n]{keys}: tabular arrays - >>>…<<< heredoc blocks

Returns:

Dictionary with section names as keys

Raises:

ParseError – If content is malformed

brain_md.parser.strip_comments(lines: list[str]) list[str][source]

Remove comment lines from TOON content.

Lines starting with # (after optional whitespace) are comments. Heredoc delimiters (>>>, <<<) are not treated as comments.

brain_md.parser.parse_value(value_str: str) str | int[source]

Parse a TOON value string.

  • Quoted strings: remove quotes

  • Integers: convert to int

  • Unquoted: return as-is

brain_md.parser.parse_tabular_row(row: str) list[str | int][source]

Parse a comma-separated row from a tabular array.

Handles quoted values with commas inside.

brain_md.parser.parse_tabular_array(header: str, rows: list[str]) list[dict][source]

Parse a tabular array into a list of dictionaries.

Parameters:
  • header – The header line like “SECTION[n]{key1, key2}:”

  • rows – List of comma-separated value rows

Returns:

List of dictionaries with keys from header

Raises:

ParseError – If header format is invalid

Pointer resolution module for brain.md compiler.

brain_md.pointer.parse_pointer(pointer: str) tuple[str, tuple[int, int] | None][source]

Parse a pointer string into path and optional line range.

Examples

“schema.sql” -> (“schema.sql”, None) “schema.sql:20-50” -> (“schema.sql”, (20, 50))

brain_md.pointer.resolve_pointer(pointer: str, base_dir: Path) ResolvedPointer[source]

Resolve a pointer reference to file content.

Parameters:
  • pointer – The pointer string (e.g., “@file.txt” or “@file.txt:20-50”)

  • base_dir – Base directory for resolving relative paths

Returns:

ResolvedPointer with original, path, and content

Raises:

CompileError – If pointer target file not found

brain_md.pointer.extract_pointers(content: str) list[str][source]

Extract all @pointer references from content.

Parameters:

content – The text content to search

Returns:

List of pointer strings (without @ prefix)

File watcher for automatic recompilation.

class brain_md.watcher.BrainFileHandler(callback: Callable[[], None], debounce_seconds: float = 0.5)[source]

Handler for file modification events.

__init__(callback: Callable[[], None], debounce_seconds: float = 0.5)[source]

Initialize file handler.

Parameters:
  • callback – Function to call when file changes

  • debounce_seconds – Minimum time between callbacks

on_modified(event)[source]

Handle file modification events.

trigger_callback_if_pending()[source]

Trigger callback if there are pending changes and debounce time has passed.

class brain_md.watcher.BrainWatcher(source: Path, on_change: Callable[[Path], None], notification_callback: Callable[[str, str], None] | None = None)[source]

Watches brain.md and referenced files for changes.

__init__(source: Path, on_change: Callable[[Path], None], notification_callback: Callable[[str, str], None] | None = None)[source]

Initialize brain watcher.

Parameters:
  • source – Path to brain.md file

  • on_change – Callback when any file changes, receives source path

  • notification_callback – Callback for OS notifications (title, message)

start()[source]

Start watching files.

stop()[source]

Stop watching files.

compile_and_notify(output_to_clipboard: bool = True) bool[source]

Compile brain.md and send notification.

Parameters:

output_to_clipboard – If True, copy to clipboard

Returns:

True if compilation succeeded, False otherwise

Boot command - Creates context.md from brain.md.

brain_md.boot.boot_cmd(source: Path = PosixPath('brain.md')) None[source]

Initialize a session by creating context.md (Dashboard).

This creates a live, editable context file from the source brain.md. The context.md serves as the working RAM during a session.

Parameters:

source – Path to brain.md source file (default: brain.md)

Data models and exceptions for Brain.md CLI.

exception brain_md.models.BrainError[source]

Base exception for brain-md.

exception brain_md.models.CompileError[source]

Compilation failed.

exception brain_md.models.PointerError[source]

Pointer resolution failed.

exception brain_md.models.ParseError[source]

TOON parsing failed.

exception brain_md.models.BudgetExceededError(actual: int, budget: int)[source]

Payload exceeds token budget.

__init__(actual: int, budget: int)[source]
class brain_md.models.PointerSpec(path: str, line_range: tuple[int, int] | None = None)[source]

Parsed pointer reference.

__init__(path: str, line_range: tuple[int, int] | None = None) None
class brain_md.models.ResolvedPointer(original: str, path: Path, content: str)[source]

Resolved pointer with content.

__init__(original: str, path: Path, content: str) None
class brain_md.models.BrainConfig(kernel: dict[str, str | int] = <factory>, registers: dict[str, str] = <factory>, memory_pointers: list[dict] = <factory>, process_stack: list[dict] = <factory>, raw_content: str = '')[source]

Parsed brain.md configuration.

__init__(kernel: dict[str, str | int] = <factory>, registers: dict[str, str] = <factory>, memory_pointers: list[dict] = <factory>, process_stack: list[dict] = <factory>, raw_content: str = '') None
class brain_md.models.CompileResult(payload: str, token_count: int, resolved_pointers: list[~brain_md.models.ResolvedPointer] = <factory>, token_budget: int | None = None)[source]

Compilation output.

__init__(payload: str, token_count: int, resolved_pointers: list[~brain_md.models.ResolvedPointer] = <factory>, token_budget: int | None = None) None