The stagecoach. The town crier. The one place every Quilt component shouts its news and every other component decides whether to listen.
Skip everything below the TL;DR and just do this:
git clone https://github.com/SuperInstance/quilt-bus
cd quilt-bus
PYTHONPATH=src python3 -m unittest tests.test_busYou will see 20 tests run in well under a second. They cover the only four things the stagecoach knows how to do: register a listener, fire an event, deliver to all listeners (exact or pattern), and replay the day's run. That is the whole library. It is small on purpose.
If you only have 30 seconds, read the next two sections.
The Quilt has many moving pieces — substrate, plugin, witness, ledger, cowboy, reactor, picker, casting. Each one has news. Each one needs to act on someone else's news. quilt-bus is the post office they all share.
It provides three primitives and one subscriber:
| Function | What it does | Stagecoach equivalent | Broker equivalent |
|---|---|---|---|
bus.subscribe(topic, fn) |
Register a callback | A porch with a mailbox | a consumer group |
bus.subscribe_pattern(pat, fn) |
Register with a glob | A porch with a flag | a topic pattern |
bus.publish(topic, source, data) |
Fire an event | The driver blows the horn | a producer |
bus.history(topic=None, limit=100) |
Replay past events | "What was the last call?" | a Kafka topic replay |
Event |
The data class for events | A sealed envelope | a Kafka record |
BusLogger |
A subscriber that logs | The town clerk's logbook | a sink connector |
The bus never invents topics. The bus never blocks on a slow subscriber. The bus is the substrate's nervous system.
The whole story is here:
A Quilt component is only as good as the news it hears. The cowboy wants to retire a failing model the moment the witness sees three failures. The picker wants to retire an opener the moment the cowboy retires a model. The reactor wants to log every cast.
The fix is small, simple, and ancient: a list of subscribers
and a publish method. That's the secret of EventBus. The
list is in-process, the publish is synchronous, the subscribers
are called in registration order. No broker, no daemon, no
network. Just a Python list.
For pattern matching (the porch with a flag), the bus
matches topics against glob patterns. cast.* matches
cast.proposed, cast.observed, and cast.model.observed.
*.observed matches cast.observed and witness.observed.
cast.*.observed matches cast.model.observed but not
cast.observed (the middle segment must be non-empty). The
matching is conservative — a flag on one porch doesn't catch
the mail meant for another.
For resilience (a slow subscriber can't break the bus),
each subscriber is called in a try/except. If one subscriber
raises, the others still receive. The cowboy never misses a
retire because the writer is slow.
For history (the bus remembers), every event is appended
to an in-memory list. The list is trimmed at max_history
(default 10000). The bus can save_jsonl(path) to disk and
load_jsonl(path) to replay. The bus is the substrate's
short-term memory.
import sys
sys.path.insert(0, "/workspace/quilt-bus/src")
from quilt_bus import EventBus, BusLogger
# The bus knows the standard Quilt topic conventions.
bus = EventBus()
# 1. Register an exact subscriber (the cowboy, listening for retirements).
cowboy_actions = []
bus.subscribe("model.retired", lambda e: cowboy_actions.append(e.data["model"]))
# 2. Register a pattern subscriber (the reactor, listening for all casts).
cast_log = []
bus.subscribe_pattern("cast.*", lambda e: cast_log.append(e.topic))
# 3. Register a logger (the writer, watching everything).
bus.subscribe("*", BusLogger(stdout=False, path="/tmp/bus.log"))
# 4. Fire some events.
bus.publish("cast.proposed", source="plugin",
data={"model": "PHI-4", "opener": "tide"})
bus.publish("cast.observed", source="substrate",
data={"model": "PHI-4", "success": True, "wilson_lb": 0.92})
bus.publish("model.retired", source="cowboy",
data={"model": "BROKEN", "reason": "consecutive-failures"})
# 5. Read the history.
print(f"Events fired: {len(bus.history())}")
print(f"Per topic: {bus.counts_summary()}")
print(f"Cowboy saw: {cowboy_actions}")The cowboy can now react in real time. The reactor can log every cast. The writer can audit everything. The stagecoach delivered the mail.
Look at the diagram. Three ideas:
-
Topics are dot-namespaced. A Quilt topic is
<domain>.<verb>:cast.proposed,cast.observed,witness.appended,ledger.appended,cowboy.morning,model.retired,model.promoted. The dot is a contract. The cowboy subscribes tocast.observed; the reactor subscribes tomodel.retired. The contract is small enough to fit in one line of code, big enough to wire a system. -
In-process is the right scale. The cowboy runs locally on the F/V EILEEN. The substrate runs on a 12-inch tablet. We do not need Kafka. We do not need Redis. We do not need RabbitMQ. We need a Python list. The bus is a Python list. If you need cross-process, you swap the bus for an external broker — the API stays the same.
-
History is replayable. Every event is appended to an in-memory list. The list can be saved to JSONL and reloaded. The cowboy's
watch --bus-log FILEmode replays a recorded bus session for testing. The reactor'sreplaymode reconstructs a session from JSONL. The bus is the substrate's short-term memory.
The bus is the substrate's nervous system. The substrate is a runtime. The bus is what the runtime uses to whisper between components.
┌─────────────────────────────────────┐
│ THE STAGECOACH │
│ quilt-bus, the in-process pub/sub │
│ │
│ subscribe("cast.observed", fn) │
│ subscribe_pattern("cast.*", fn) │
│ publish("topic", source, data) │
│ history(topic=None, limit=100) │
│ save_jsonl(path) / load_jsonl() │
└─────────────────────────────────────┘
│
EXACT ─── single topic │
PATTERN ─── glob topic │ one purpose:
HISTORY ─── replay past │ deliver news
PERSIST ─── JSONL on disk │ between cells
LOGGER ─── subscriber sink │
from quilt_bus import EventBus
bus = EventBus()
bus.subscribe("cast.observed", lambda e: print(e.data))subscribe registers a callback for an exact topic. It
returns an unsubscribe function — call it and the callback
stops receiving. Multiple callbacks for the same topic all
fire (in registration order). One bad callback doesn't break
the others (each call is wrapped in a try/except).
Stagecoach equivalent: a porch with a single mailbox
labeled cast.observed. The driver drops the mail in any
mailbox whose label matches.
Broker equivalent: a consumer group subscribed to one topic.
bus.subscribe_pattern("cast.*", lambda e: print(e.topic))
bus.subscribe_pattern("*.observed", lambda e: print(e.topic))
bus.subscribe_pattern("cast.*.observed", lambda e: print(e.topic))subscribe_pattern registers a callback for a glob pattern.
The pattern uses * as a wildcard. cast.* matches
cast.proposed and cast.observed. *.observed matches
cast.observed and witness.observed. cast.*.observed
matches cast.model.observed but not cast.observed
(the middle segment is required to be non-empty). Multiple
wildcards work too.
Stagecoach equivalent: a porch with a flag. The flag tells the driver which mail to drop.
Broker equivalent: Kafka topic patterns or RabbitMQ topic exchanges.
bus.publish("cast.observed", source="plugin",
data={"model": "PHI-4", "success": True})publish fires an event. It creates an Event(ts, topic, source, data), appends it to the history, increments the
per-topic counter, then calls every exact and pattern
subscriber. The ts is time.time(). The source is
who's shouting (e.g. "substrate", "plugin", "cowboy").
The data is a free-form dict.
Stagecoach equivalent: the driver arrives at the post office, blows the horn, and the townsfolk decide whether to listen.
Broker equivalent: producer.send(topic, record).
recent = bus.history(limit=10) # last 10 events
casts = bus.history(topic="cast.observed") # only casts
counts = bus.counts_summary() # per-topic countshistory returns the most recent N events, optionally
filtered by topic. The history is bounded by max_history
(default 10000) — when the bus overflows, the oldest event
is dropped. counts_summary returns a dict of
{topic: n_published}.
Stagecoach equivalent: "What was the last call? What arrived this morning?" The clerk looks it up.
Broker equivalent: consumer.poll() or a Kafka topic
replay.
bus.save_jsonl("/var/quilt/state/bus.jsonl") # checkpoint
# ... a week later, in a new process ...
bus2 = EventBus()
bus2.load_jsonl("/var/quilt/state/bus.jsonl") # replaysave_jsonl writes the in-memory history to a JSONL file
(via temp + rename, atomic). load_jsonl reads it back
and replays the events into a new bus. The cowboy's
watch --bus-log FILE mode uses this for testing.
Stagecoach equivalent: the mail logbook. The clerk's record of who mailed what and when.
Broker equivalent: a Kafka topic retention window or a compacted topic.
The cowboy's reactor looks like this:
import sys
sys.path.insert(0, "/workspace/quilt-bus/src")
sys.path.insert(0, "/workspace/quilt-cowboy/src")
from quilt_bus import EventBus, BusLogger
from quilt_cowboy import CowboyReactor, Cowboy
# Initialize the bus and the cowboy.
bus = EventBus()
cowboy = Cowboy(state_dir="/var/quilt/cowboy-state")
reactor = CowboyReactor(cowboy, bus, retire_after_failures=3)
# Subscribe the writer to everything (audit).
bus.subscribe("*", BusLogger(path="/var/quilt/state/bus.log"))
# Subscribe the witness (will write to witness.jsonl on each event).
witness_log = []
bus.subscribe("cast.observed", lambda e: witness_log.append(e))
# The substrate publishes some casts.
for i in range(5):
bus.publish("cast.proposed", source="substrate",
data={"model": "BROKEN", "q": 0.5})
bus.publish("cast.observed", source="substrate",
data={"model": "BROKEN", "success": False})
# The cowboy retires after 3 consecutive failures.
reactor.stop()
print(f"Auto-retired: {sorted(reactor.stats()['auto_retired'])}")
print(f"Bus counts: {bus.counts_summary()}")
print(f"Bus history: {len(bus.history())} events")
# Save the bus state to disk.
bus.save_jsonl("/var/quilt/state/bus.jsonl")This is the entire cowboy's day. The substrate publishes casts, the bus delivers them, the cowboy reacts, the writer audits, the bus saves the day's run. The stagecoach kept the news flowing.
The 5 opcodes are a polyformalism — the same thing in many forms. Here is the 5xN grid:
Python Rust C TypeScript Haskell WASM ...
BIND ✓
LINK ✓
EFFECT ✓
VIEW ✓
TICK ✓
quilt-bus is the EVENT LAYER — what the opcodes use to
broadcast effects and respond to views.
The bus is Layer 0.5 of the polyformalism stack — it sits above the notepad and below the cowboy. The other layers:
- Layer 1 (substrate) — quilt-vm-wasm — the 5 opcodes running in any browser
- Layer 2 (types) — quilt-types — the 5 opcodes as typed dataclasses
- Layer 3 (linker) — quilt-linker — the 5 opcodes as a link-time checker
- Layer 4 (optimizer) — quilt-opt — the 5 opcodes as algebraic optimization passes
- Layer 5 (GC) — quilt-gc — the 5 opcodes as a garbage-collector
- Layer 6 (language syntax) — quilt-polyformalism-dsl — the 5 opcodes as decorators / typeclasses
- Layer 7 (persistence) — quilt-state — the notepad, the witness log
- Layer 8 (model brain) — quilt-casting — the Wilson + LinUCB model router
- Layer 9 (view brain) — quilt-picker — the Wilson + heuristic opener picker
- Layer 10 (cell-plugin bridge) — quilt-cordis — the bridge between Quilt cells and Cordis plugins
- Layer 11 (rider) — quilt-cowboy — the cowboy, the morning ritual, the reactor
The bus is Layer 0.5 because it's the event substrate
the cowboy and reactor use to communicate — the layer that
turns the cells' EFFECT opcode into a broadcast.
The stagecoach is the rider's horn. The cowboy blows the horn when a model retires. The reactor listens for the horn. The picker hears the horn and retires the opener. The writer hears the horn and writes the audit. The horn is the only way news travels. The horn is the only way cells cooperate without coupling.
The bus has a max_history field — by default 10000 events.
When the bus overflows, the oldest event is dropped. The bus
isn't meant to be a permanent log — that's the notepad's job.
The bus is the today's news, the notepad is yesterday's
record. The cowboy reads the notepad every morning, but the
bus is the live wire.
A bus with a slow subscriber is a stagecoach with a broken wheel: it doesn't move. The cowboy's reactor must be fast. The reactor never sleeps. The bus is fast. The bus is simple. The bus is forever.
The cowboy rides.
20 tests covering publish/subscribe, pattern matching, history, persistence, exception isolation, and the logger. Run them with:
PYTHONPATH=src python3 -m unittest tests.test_bus| Test group | Count | What it covers |
|---|---|---|
| Subscribe & publish | 5 | subscribe, multiple subs, no subs, returns Event, unsubscribe |
| Pattern matching | 5 | cast.*, *.observed, cast.*.observed, prefix/suffix, no-wildcard |
| History & counts | 4 | history limit, topic filter, max_history trim, counts |
| Persistence | 2 | save/load JSONL, round-trip |
| Resilience | 2 | exception isolation, complex topology |
| Logger & stats | 2 | BusLogger file, stats summary |
# Event dataclass
Event(ts: float, topic: str, source: str, data: dict)
.to_dict() -> dict
.to_jsonl() -> str
# EventBus
EventBus(max_history: int = 10000)
.subscribe(topic: str, fn: Subscriber) -> Callable[[], None] # returns unsubscribe
.subscribe_pattern(pattern: str, fn: Subscriber) -> Callable[[], None]
.publish(topic: str, source: str = "", data: dict = None) -> Event
.history(topic: str = None, limit: int = 100) -> List[Event]
.counts_summary() -> Dict[str, int]
.save_jsonl(path: str) -> None
.load_jsonl(path: str) -> None
.stats() -> Dict[str, Any]
# Subscriber = Callable[[Event], None]
# BusLogger
BusLogger(path: str = None, stdout: bool = False)
# A subscriber that writes to file and/or stdout
__call__(event: Event) -> None- The cowboy — quilt-cowboy — the rider who subscribes to the bus and reacts in real time
- The notepad — quilt-state — the witness log that the bus writes to
- The picker — quilt-picker — the view brain that hears
model.retired - The casting — quilt-casting — the model brain that publishes
cast.proposed - The bridge — quilt-cordis — the cell-plugin bridge, also a pattern of effects
- The substrate — quilt-substrate — the 405-test Python substrate that uses the bus
- The agent knowledge base — agent-knowledge — 50+ documents on the agent/agent architecture
- The model atlas — casting-call — which model to use for which task
- The forest of agents — ai-forest — the wider ecosystem of 100+ repos
MIT. The stagecoach is the rider's. The rider is the cowboy's. The cowboy's is the wind's.
You came through the stagecoach. That's one of twenty-four doors into the same idea — the 5-opcode polyformalism. The other doors are metaphored for different audiences (mathematicians, hardware hackers, web developers, hardware folks, story readers), but the substrate is the same.
The full map of the collection: COLLECTION.md
From here, three wander-paths you might enjoy:
- quilt-cowboy — the orchestrator that uses the bus
- quilt-state — the witness log that records bus events
- quilt-casting — the LLM cast that publishes to the bus
The cowboy's maxim: The unit of foundation is the cell, not the opcode. The 5 opcodes are the 5 messages a cell can receive. The 24 repos are the 24 doors into the same message. The cowboy is the one who wanders.