bubbaloop
CLAUDE.md28 starsChanged 8 months agoApache-2.0View on GitHub
Physical AI orchestration built on Zenoh. Single binary: CLI + daemon + MCP server. Key source files in crates/bubbaloop/src/: - cli/login.rs — login/logout/status + has_claude_credentials() (env var → OAuth → key file) - cli/agent_setup.rs — bubbaloop agent setup: interactive provider/model/identity wizard (no daemon needed) - cli/agent_client.rs — Thin Zenoh CLI client for agent chat/list (pub/sub, no LLM) - agent/mod.rs — Agent core: EventSink trait, run_agent_turn(), AgentTurnInput (soul_path triggers onboarding) - agent/gateway.rs — Zenoh gateway wire format (AgentMessage, AgentEvent, topic builders)…
- Reads credentials
- Deletes or force-pushes
- Installs packages
- Commits and pushes
In this repository4 other files it gives its agents.
- docs/llms-full.txtllms.txt
- docs/llms.txtllms.txt
- ui-ux-pro-maxSkill
- bubbaloop-physical-aiSkill
The file
We split this CLAUDE.md into the rules it gives an agent
8 rules. About 0 are common, 0 are distinctive, and 8 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 131
Never use println!()/print!()/eprintln!() — all output via log macros (log::info!() for user-facing CLI output, log::warn!()/log::error!() …
- Very specific: line 149
All tool handlers include audit logging: log::info!("[MCP] tool=...")
- Very specific: line 156
Every ctx.topic(suffix) / ctx.local_topic(suffix) call auto-prefixes with instance_name:
- Very specific: line 179
NEVER: use .complete(true) on queryables — blocks wildcard queries like bubbaloop//schema
- Very specific: line 182
Rust: Do NOT use .complete(true) — use .await?
- Very specific: line 183
Validation: Run ./scripts/validate.sh to catch these errors automatically
- Very specific: line 188
Never commit: target/, node_modules/, dist/, .pixi/ Always commit: Cargo.lock, pixi.lock, package-lock.json
- Very specific: line 189
Always commit: Cargo.lock, pixi.lock, package-lock.json
≈ “Common” is an estimate: at least 1 in 5 of the 28,633 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
🦐 Bubbaloop
Physical AI orchestration built on Zenoh. Single binary: CLI + daemon + MCP server.
Living Documents (update these as architecture evolves)
- ARCHITECTURE.md — Layer model, node contract, security, open-core boundary
- ROADMAP.md — Implementation phases (YAML skills, agent, SQLite memory, scheduling)
- CONTRIBUTING.md — Agentic workflows, agent tiers, validation, two-critic loop
- docs/concepts/dataflow.md — Provenance envelope, manifest queryable,
bubbaloop dataflowCLI + MCP tool (how the SDK answers "what's wired, what's flowing")
Structure
crates/bubbaloop/ # Main binary (CLI + daemon + MCP server)
crates/bubbaloop-node/ # Node SDK (standalone, NOT in workspace — batteries-included framework)
crates/bubbaloop-node-build/ # Build helper for nodes (wraps prost-build, standalone)
crates/bubbaloop-schemas/ # Protobuf schemas (standalone, NOT in workspace — never add to workspace)
dashboard/ # React + Vite + TypeScriptKey source files in crates/bubbaloop/src/:
cli/login.rs— login/logout/status +has_claude_credentials()(env var → OAuth → key file)cli/agent_setup.rs—bubbaloop agent setup: interactive provider/model/identity wizard (no daemon needed)cli/agent_client.rs— Thin Zenoh CLI client for agent chat/list (pub/sub, no LLM)agent/mod.rs— Agent core: EventSink trait, run_agent_turn(), AgentTurnInput (soul_path triggers onboarding)agent/gateway.rs— Zenoh gateway wire format (AgentMessage, AgentEvent, topic builders)agent/runtime.rs— Multi-agent runtime: AgentsConfig, AgentRuntime, ZenohSink, agent_loop;agent_directory()(pub)agent/prompt.rs— System prompt builder;build_system_prompt_with_soul_path()injects onboarding prompt for new agentsagent/soul.rs— Soul struct, first-run onboarding, notify hot-reload (~/.bubbaloop/soul/)agent/provider/mod.rs— ModelProvider trait, Message, ContentBlock (incl.Image), ToolDefinition, StreamEventagent/provider/gemini.rs— Gemini API client (recommended default — free tier, vision-capable)agent/provider/claude.rs— Claude API client with dual auth (API key + OAuth bearer token)agent/provider/ollama.rs— Ollama local LLM client with tool calling (/api/chat)agent/camera.rs—grab_frameimplementation: Zenoh query for one JPEG frame + JSON metadata attachment, emitsContentBlock::Imageagent/gateway.rs— Zenoh + HTTP+SSE agent gateway; per-agent cancel topicbubbaloop/global/{machine_id}/agent/{agent_id}/cancelagent/memory/— 4-tier: world state (live SQLite) + short-term (RAM) + episodic (NDJSON) + semantic (SQLite)agent/heartbeat.rs— Adaptive heartbeat: arousal + decay + state collectionagent/dispatch.rs— Internal tool dispatch (47 public MCP tools + ~43 agent-internal tools incl.grab_frame, telemetry, beliefs, constraints, missions)cli/node/mod.rs— node CRUD, validation, list/add/removecli/node/install.rs— install, precompiled binary download, GitHub clonecli/node/lifecycle.rs— start, stop, restart, logscli/node/build.rs— build nodedaemon/mod.rs— skill runtime: registry + lifecycle + health + MCP + telemetry watchdogdaemon/telemetry/— Resource watchdog: sampler (sysinfo), circuit breaker, SQLite storage, hot-reload configdaemon/node_manager.rs(57KB) — node lifecycle, build queue, healthdaemon/systemd.rs(38KB) — D-Bus/zbus integrationdaemon/registry.rs—~/.bubbaloop/nodes.jsonmanagementregistry.rs— marketplace fetch/parse/cache,find_curl()marketplace.rs— shared precompiled binary download logic (used by CLI and MCP)mcp/mod.rs— MCP tools, BubbaLoopMcpServer<P>, ServerHandler implmcp/platform.rs— PlatformOperations trait, DaemonPlatform, MockPlatform
Node SDK (crates/bubbaloop-node/)
Batteries-included framework for writing nodes. Reduces boilerplate from ~300 to ~50 lines.
lib.rs—Nodetrait,run_node(), re-exports (zenoh, prost, tokio, anyhow, log, serde_json)context.rs—NodeContext(session, machine_id, instance_name, shutdown_rx,topic(),local_topic(),publisher_proto(),publisher_json(),publisher_raw(),publisher_raw_proto(),subscriber(),subscriber_raw())publisher.rs—ProtoPublisher<T>(APPLICATION_PROTOBUF + schema suffix),JsonPublisher(APPLICATION_JSON),RawPublisher(ZBytes, optional encoding, SHM congestion control)subscriber.rs—TypedSubscriber<T>(auto-decode, 256-slot FIFO),RawSubscriber(raw ZBytes, 4-slot FIFO)proto_decoder.rs—ProtoDecoder(dynamic protobuf decode via SchemaRegistry, caches DescriptorPool)discover.rs—discover_nodes(),NodeInfo(discovers nodes via health heartbeats)get_sample.rs—get_sample()(single-shot pull without maintaining subscription)config.rs— YAML config loading;extract_name()readsnamefield for per-instance topicszenoh_session.rs— Client-mode Zenoh session (scouting disabled)health.rs— Background health heartbeat (5s interval) to{instance_name}/healthschema.rs— Schema queryable at{instance_name}/schema(FileDescriptorSet serving)shutdown.rs— SIGINT/SIGTERM signal handling via watch channel
Standalone crates (NOT in workspace). Nodes depend via git:
[dependencies]
bubbaloop-node = { git = "https://github.com/kornia/bubbaloop.git", branch = "main" }
[build-dependencies]
bubbaloop-node-build = { git = "https://github.com/kornia/bubbaloop.git", branch = "main" }Rust ↔ Python SDK parity (MUST hold): crates/bubbaloop-node/ (Rust) and python-sdk/ (Python) are peer APIs, not layered — every publisher/subscriber/context method added to one MUST have an equivalent in the other in the same PR (or a linked tracking issue). Names should match where possible; where the underlying binding can't surface a knob, the Python side collapses it to the simplest equivalent that preserves wire behavior. Example: Rust publisher_cbor_shm(suffix, slot_count, slot_size) ↔ Python publisher_cbor(suffix, local=True) — zenoh-python doesn't expose ShmProvider so slot sizing is implicit, but encoding (application/cbor) and congestion control (Block) are identical on the wire.
Multi-instance support: SDK reads name from config YAML at startup. Health and schema topics use this name, so tapo_entrance and tapo_terrace instances of the same binary get separate topics: bubbaloop/global/host/tapo_entrance/health vs bubbaloop/global/host/tapo_terrace/health.
Topic key spaces: Two fixed key spaces replace the old {scope}:
ctx.topic(suffix)→bubbaloop/global/{machine_id}/{suffix}(network-visible, dashboard, CLI)ctx.local_topic(suffix)→bubbaloop/local/{machine_id}/{suffix}(SHM-only, same-machine, never crosses WebSocket bridge)
Node Build Helper (crates/bubbaloop-node-build/)
Companion build crate (tonic-build pattern). Node build.rs is one line:
fn main() -> Result<(), Box<dyn std::error::Error>> {
bubbaloop_node_build::compile_protos(&["protos/my_node.proto"])
}Automatically: embeds header.proto (no local copy needed), maps .bubbaloop.header.v1 → ::bubbaloop_node::schemas::header::v1, writes descriptor.bin for schema queryable registration.
Python SDK: python-sdk/ — synchronous Python wrapper over zenoh-python (no asyncio). Exports: NodeContext, run_node, JsonPublisher, ProtoPublisher, RawPublisher, ProtoSubscriber (auto-decode via SchemaRegistry), RawSubscriber, ProtoDecoder, discover_nodes, get_sample. Install:
pip install git+https://github.com/kornia/bubbaloop.git#subdirectory=python-sdk
Nodes repo: bubbaloop-nodes-official
MCP Server (Core)
MCP is core (not feature-gated). 3-tier RBAC, bearer token auth. Run: bubbaloop mcp --stdio or daemon HTTP on :8088.
The daemon runs the agent runtime (multi-agent Zenoh gateway) alongside the MCP server. Agents are configured via ~/.bubbaloop/agents.toml, each with per-agent Soul and Memory in ~/.bubbaloop/agents/{id}/. The CLI (bubbaloop agent chat) is a thin Zenoh client — all LLM processing is daemon-side.
Key files in crates/bubbaloop/src/mcp/: mod.rs (tools, BubbaLoopMcpServer), platform.rs (PlatformOperations trait), rbac.rs, auth.rs.
MCP tools: install_node accepts marketplace names (e.g., "rtsp-camera"), local paths, or GitHub user/repo. Full lifecycle: install_node, uninstall_node, clean_node, enable_autostart, disable_autostart.
Testing: cargo test --features test-harness --test integration_mcp (47 tests)
Build & Verify
pixi run check # cargo check (fast — run after every change)
pixi run clippy # zero warnings enforced (-D warnings)
pixi run test # cargo test (2400+ unit tests)
pixi run fmt # cargo fmt --all
pixi run build # cargo build --release (slow on ARM64; install mold+clang to speed up)
cargo test --features test-harness --test integration_mcp # 47 integration testsConventions — MUST follow
Use these (not alternatives):
arghfor CLI — NOT clap (#[derive(FromArgs)],#[argh(subcommand)])log+env_logger— NOT tracing (log::info!(), logs to stderr)thiserrorfor library errors,anyhowfor CLI — module-specifictype Result<T>zbusfor systemd — NEVER spawnsystemctlas subprocess- Never use
println!()/print!()/eprintln!()— all output vialogmacros (log::info!()for user-facing CLI output,log::warn!()/log::error!()for problems). Main binary defaults to"bubbaloop=info,warn"so CLI info is visible without settingRUST_LOG. tempfile::tempdir()for filesystem tests, co-located#[cfg(test)] mod tests- 100% safe Rust — no
unsafe
Async patterns:
- tokio with
watch::channel(())shutdown pattern - Zenoh queries: 3 retries, 1s timeout,
QueryTarget::BestMatching
Security:
find_curl()inmarketplace.rsandregistry.rssearches/usr/bin,/usr/local/bin,/binonly (no PATH)- Build commands: allowlist prefixes only (cargo, pixi, npm, make, python, pip)
- Node names: 1-64 chars,
[a-zA-Z0-9_-], no null bytes - Git clone: always use
--separator - Bind localhost only, never
0.0.0.0 kill <numeric_pids>allowed (agent lifecycle cleanup);kill 0/1/-1,killall,pkillblocked
MCP:
- RBAC: Viewer/Operator/Admin tiers, unknown tools default to Admin
- All tool handlers include audit logging:
log::info!("[MCP] tool=...") - PlatformOperations trait for clean daemon/MCP separation
test-harnessfeature enables integration tests with MockPlatform- Daemon hosts agent runtime (multi-agent Zenoh gateway) + MCP server
Topic naming (auto-scoped)
Every ctx.topic(suffix) / ctx.local_topic(suffix) call auto-prefixes with instance_name:
bubbaloop/{global|local}/{machine_id}/{instance_name}/{suffix}- Publishers (
publisher_*(suffix)) auto-scope:ctx.publisher_json("data")→bubbaloop/global/{machine_id}/{instance_name}/data. Usepublisher_*_absolute(suffix)only for explicit cross-node control topics (e.g. daemon broadcast channels). - Subscribers (
subscribe(absolute_suffix)) are absolute by default — pass the upstream node's full topic suffix including its instance name, e.g.ctx.subscribe("tapo_terrace_embedder/embeddings"). - Asymmetry rationale: publishers own their outputs (auto-scope makes sense), subscribers consume upstream (absolute avoids silent self-scoping bugs).
- Three roles (
spec.role:innode.yaml v2):source(raw sensor),processor(derived signal),sink(actuator/store). Processors inherit their source's instance prefix:tapo_terrace_embedderderives fromtapo_terrace. - Instance-naming convention:
<source>[_<purpose>]— e.g.tapo_terrace,tapo_terrace_embedder,tapo_terrace_detector. bubbaloop-nodes-officiallayout (future restructure, not yet done): group directories by role —sources/,processors/,sinks/.- Every node served by the SDK exposes
{instance}/manifest(CBOR queryable) listing its liveinputs/outputs(each with per-topic{ever_fired, still_live, declared_at_ns}liveness) +role;bubbaloop dataflow(and thedataflowMCP tool) reconstruct the full DAG from these — no config grepping required. Default edge inference requiresstill_live && ever_fired; passinclude_declared_but_unused=trueto see wired-but-idle pipes.
DO / DON'T
DO: pixi run check after changes | pixi run fmt && pixi run clippy before commits | tests with every PR | validate user input | -- in git clone | verify both bubbaloop-schemas and bubbaloop compile after proto changes
DON'T: edit target//OUT_DIR | commit .env/credentials/target/ | add bubbaloop-schemas to workspace | combine git+path in Cargo deps | git push --force to main | commit directly to main (always use a branch + PR)
Zenoh API Rules (templates & nodes)
- ALL nodes MUST use
mode: "client"— peer mode doesn't route through zenohd router - NEVER use
.complete(true)on queryables — blocks wildcard queries likebubbaloop/**/schema - Python:
query.key_expris a property NOT a method — NEVER usequery.key_expr() - Python:
query.reply(query.key_expr, payload_bytes)— correct reply pattern - Rust: Do NOT use
.complete(true)— use.await?directly - Validation: Run
./scripts/validate.shto catch these errors automatically
Commits
Conventional: feat:, fix:, chore:, docs:, refactor:, test:
Never commit: target/, node_modules/, dist/, .pixi/
Always commit: Cargo.lock, pixi.lock, package-lock.json
Dashboard View Components
Encoding-First Decode (preferred)
New view components should read sample.encoding() as the primary decode signal:
import { getEncodingInfo } from '../lib/zenoh';
const handleSample = (sample: Sample) => {
const encoding = getEncodingInfo(sample);
// APPLICATION_JSON (5) → snakeToCamel(JSON.parse()) — nodes publish snake_case, dashboard normalizes
// APPLICATION_PROTOBUF (13) → SchemaRegistry decode (with on-demand schema fetch)
// ZENOH_BYTES (0) or unknown → sniff fallback
};Legacy Gating (backward compat for old nodes)
For views that must support old nodes publishing without encoding:
const schemaReady = useSchemaReady(); // from hooks/useSchemaReady
useZenohSubscription(topic, schemaReady ? handleSample : undefined);This prevents the race where Zenoh delivers messages before schemas load. Exception: views using encoding-first decode don't need gating.
Pitfalls
- OAuth token lacks
workflowscope — use SSH for workflow files - ARM64 release builds are slow — use
pixi run checkfirst - Proto changes require rebuilding both
bubbaloop-schemas/andbubbaloop(descriptor.bin is compiled in) - MCP is core — rmcp, schemars, tower_governor are unconditional deps
- TUI was removed in v0.0.6, re-added in v0.0.11 as ratatui chat REPL (
agent chat). Single-message mode stays plain stdout. dashboardfeature is opt-in (not default) — use--features dashboardto build the web UI- Binary size profile:
panic=abort+lto=true+opt-level=z+strip=symbols+rusqlite bundled(not bundled-full) - mold linker config ready in
.cargo/config.toml— activate withsudo apt install mold clang - Logs must go to stderr (convention: never pollute stdout)
- Zenoh session: MUST use
"client"mode for router routing; checkBUBBALOOP_ZENOH_ENDPOINTenv var - Dashboard schema race: for old nodes without encoding, use
useSchemaReady()gating. New nodes with encoding decode on first sample. - Daemon wire format: ALL daemon messages are JSON (not protobuf). Dashboard uses
JSON.parse()for daemon responses. - Zenoh default encoding: samples published without explicit encoding get
ZENOH_BYTES(id=0). Dashboard treats this as "no signal" → sniff fallback. - OAuth tokens require Claude CLI identity headers (user-agent, x-app, anthropic-beta) — see
agent/provider/claude.rs::OAUTH_BETA_HEADERS - Agent robustness constants in
agent/mod.rs:TURN_TIMEOUT_SECS=120,TOOL_CALL_TIMEOUT_SECS=30,MAX_TOOL_RESULT_CHARS=4096— change these to tune agent behavior run_turn_loop()is the inner async fn wrapped bytokio::time::timeout— keep turn-level logic there, finalization (Done event, trim) inrun_agent_turn()- Agent ID vs display name: agent ID (
agents.tomlkey) is the routing/filesystem key — immutable. The display name lives inidentity.md(hot-reloaded). Editidentity.mdto rename an agent without touching the ID. agent setuponboarding flow: writes.needs-onboardingmarker in~/.bubbaloop/agents/{id}/. On first chat turn, daemon injectsNEW_AGENT_IDENTITYprompt; LLM writesidentity.md; daemon clears marker.needs_onboardingbool is cached inagent_loopto avoid hot-pathPath::exists()calls.agents.tomlmodelfield overridesSoul.capabilities.model_nameper-agent. Omit to use soul default.- Topic key spaces:
global= network-visible (dashboard, CLI, remote machines),local= SHM-only (same-machine, never crosses WebSocket bridge). The old{scope}(local/staging/prod) was removed — all topics now usebubbaloop/global/...orbubbaloop/local/.... RawPublisherwithlocal=trueusesCongestionControl::Block— required for SHM so frames aren't silently dropped. Without it, slow consumers lose frames.RawSubscriberuses a 4-slot FIFO (not 256 likeTypedSubscriber) — older frames are intentionally dropped when the consumer is slow. This is correct for video frames.- Python
ProtoSubscriberauto-decodes viaSchemaRegistry(queriesbubbaloop/**/schema, 2s timeout). No_pb2imports needed — schema is fetched from the publishing node at runtime. - Python SDK subscribers use
_BaseSubscriberfor shared iterator protocol. Only overriderecv()in subclasses.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

