Patchbay
Patchbay guide
patchbay is a small S-expression DSL describing how every incoming publish gets filtered, conditioned, and re-routed. It is shared by the monoblok server and tinyblok on microcontrollers.
This page explains how the language fits together. For what each operator does, see the forms reference; for complete files, see the examples.
Not sure where to get started? Want results fast? Fear not: the
patchbay-authoringskill turns Codex and Claude into fully qualified Patchbay experts. 🤖
A first rule#
Rules are top-level (on SUBJECT-FILTER BODY) forms. The body is evaluated whenever an incoming subject matches the filter. Wildcards are NATS-style: * matches one token, > matches the tail.
(on "sensors.*"
(when (> payload-float 30.0)
(publish! (subject-append "high") payload)))
; Round to 1dp, drop duplicates, emit on the .stable sub-subject.
(on "sensors.*"
(-> payload-float
(round 1)
(squelch)
(publish! (subject-append "stable"))))The first rule copies any reading above 30 to sensors.<name>.high. The second rounds to one decimal place, drops the value if it has not changed, and republishes to sensors.<name>.stable. Both rules see every sensors.* message; rules do not consume messages or stop each other.
The vocabulary is borrowed from electronics (squelch suppresses until the value changes, deadband ignores movement smaller than a threshold) because the names already mean the right thing. A "patchbay" in a studio is a grid of jacks you wire between sources and destinations, which is exactly what the DSL looks like on the page.
S-expression syntax in 30 seconds#
Every list (head arg1 arg2 ...) is a call where head is the operator and the rest are its arguments. Operators precede their arguments, without commas or infix notation; (+ 1 2 3) is 1 + 2 + 3 and (> x 10) is x > 10. Calls can be nested: (publish! (subject-append "high") payload) calls publish! with two args, the first of which is itself the result of calling subject-append. Strings are double-quoted (#"..." is a raw string for regex patterns), numbers bare, and everything else (subject, payload, when, +) is a symbol resolved by the evaluator.
The shape of a patchbay file#
A file is a list of top-level forms. Rules sit beside a handful of config forms:
| form | role |
|---|---|
(on FILTER BODY) | a rule: run BODY for each message whose subject matches FILTER |
(every :ms N BODY...) | a timer rule: run BODY every N milliseconds |
(lvc [FILTER ...]) | opt subjects into the last-value cache |
(export ...) | forward matching publishes to a real NATS cluster (export) |
(import ...) | feed remote NATS or JetStream messages into the rules (import) |
Inside a rule body a handful of bound symbols stand for the current message: subject, payload, payload-float, payload-int, payload-bool, reply-to and replaying?. The reference lists each one.
Forms fall into a few families, and most rules are a short chain drawn from them:
| family | examples | what they do |
|---|---|---|
| pure transforms | round, quantize, clamp, abs, arithmetic | reshape a number |
| gates | squelch, deadband, hold-off, throttle | pass a value or suppress it (return nil) |
| edges | rising-edge, falling-edge, transition, hysteresis | fire once when a condition flips |
| windows | moving-avg, percentile, stddev, rate, ewma | summarise the last N samples or the last N ms |
| clock forms | on-silence, dropout, debounce!, sample!, aggregate!, every | act when time passes, not only when a message arrives |
| JSON | json-get, json-demux! | read fields out of JSON payloads |
| effects | publish!, reply!, count!, bar!, print! | put bytes on the wire (the ! forms) |
The ! suffix identifies effectful forms, including publishing and debug output.
Pipelines#
Most rules read top to bottom as a pipeline, written with ->. Each step receives the previous value as its last argument:
(-> payload-float
(round 1)
(squelch)
(publish! (subject-append "stable")))Gates return their input on pass and nil on suppress, and publish! is a no-op on nil, so a chain of gates stops by itself. You do not need when anywhere in a threaded pipeline. Threading with -> has the full expansion rules.
State#
Stateful forms (gates, windows, counters, bars) remember things between messages. The rules for that memory are short:
- State is per call site and subject. Each place a stateful form appears in a rule body gets its own state, so two
(squelch ...)calls in one rule never share a slot. A rule onsensors.*keeps one slot for every concrete subject it has seen. - The first message on a new subject passes gates. There is no prior value to compare against, so
squelchanddeadbandemit; edge forms such asrising-edgestay quiet because no edge has happened yet. - There is no shared state across subjects. To combine subjects, publish them onto one subject and keep the state there. That is the funnel pattern.
- State survives restarts when snapshots are enabled.
Because every distinct subject gets a slot, avoid unbounded subject tokens such as timestamps, user IDs, or raw device-generated strings unless you intend to create state for each one.
Rules feeding rules#
By default, a publish from inside a rule is delivered to subscribers and the LVC, but is not matched against other rules. One inbound message produces one round of rule evaluation.
Mark a rule :reentrant true and its emissions are matched against the other rules too. That is how staged pipelines are built: one rule demuxes a JSON frame into scalar subjects, and later rules condition each scalar.
(on "devices.*" :reentrant true
(json-demux! "temp" "hum" payload))
(on "devices.*.temp"
(-> payload-float
(round 0)
(publish! (subject-append "stable"))))A rule can trigger itself if its output subject matches its own filter. Re-entry is capped at depth 8; reaching the limit stops further evaluation and logs a warning. See Re-entry.
File formats#
EDN is canonical for hand-written patchbays. .json files are accepted for tooling compatibility, and .yml / .yaml files use a small YAML sugar layer. All three load into the same AST, so the choice is about who edits the file.
The same rule three ways:
(on "car.*.rpm"
(-> payload-float
(quantize 50)
(squelch)
(publish! (subject-append "stable") :dp 1)))on:
- sub: "car.*.rpm"
pipeline:
- $payload-float
- [quantize, 50]
- [squelch]
- [publish!, [subject-append, "stable"], {dp: 1}][
["on", "car.*.rpm",
["->", "$payload-float", ["quantize", 50], ["squelch"],
["publish!", ["subject-append", "stable"], {"dp": 1}]]]
]Side by side#
| EDN | JSON | YAML |
|---|---|---|
(lvc ["demo.>"]) | ["lvc", "demo.>"] | lvc: ["demo.>"] |
(on "sensors.*" (publish! "out" payload)) | ["on", "sensors.*", ["publish!", "out", "$payload"]] | - sub: "sensors.*" with do: [publish!, "out", $payload] |
(moving-avg :ms 5000 payload-float) | ["moving-avg", {"ms":5000}, "$payload-float"] | [moving-avg, {ms: 5000}, $payload-float] |
(on "MARKET.*" :reentrant true (bar! 60 payload-float)) | ["on", "MARKET.*", {"reentrant":true}, ["bar!", 60, "$payload-float"]] | sub: "MARKET.*", reentrant: true, do: [bar!, 60, $payload-float] |
(when (> payload-float 80) ...) | ["when", [">", "$payload-float", 80], ...] | when: [">", $payload-float, 80] beside the body key |
[1 2 3] | {"vector": [1, 2, 3]} | [vector, 1, 2, 3] |
(every :ms 1000 (publish! "tick" "alive")) | ["every", {"ms":1000}, ["publish!", "tick", "alive"]] | every: list, item ms: 1000 and do: [publish!, "tick", "alive"] |
(export :servers ["nats://127.0.0.1:4223"] :export ["demo.>"]) | ["export", {"servers":["nats://127.0.0.1:4223"], "export":["demo.>"]}] | export: map with servers: and export: |
(import :servers ["nats://127.0.0.1:4223"] :subject ["raw.>"]) | ["import", {"servers":["nats://127.0.0.1:4223"], "subject":["raw.>"]}] | import: map with servers: and subject: |
YAML sugar files#
Files ending in .yml or .yaml use a deliberately small patchbay YAML subset. The loader builds patchbay forms directly: YAML never evaluates and no EDN/JSON text is generated internally. Supported shapes are block maps/lists, flow arrays for call forms, flow option maps as direct call arguments, quoted or unquoted scalars, numbers, booleans, nulls, top-level on, every, lvc, export, bridge, and import. In top-level config string positions, env: "NAME" lowers to (env "NAME"). Every file is also valid standard YAML.
Use pipeline: to pass a starting value through successive steps. Use do: for one expression (do: [publish!, "out", $payload]) or a block list of expressions evaluated independently, in order. Each rule or nested body map has exactly one body key. thread: remains an alias for pipeline:, and form: remains accepted for a single direct expression.
on:
- sub: "car.*.rpm"
pipeline:
- $payload-float
- [quantize, 50]
- [squelch]
- [publish!, [subject-append, "stable"], {dp: 1}]The EDN equivalent:
(on "car.*.rpm"
(-> payload-float
(quantize 50)
(squelch)
(publish! (subject-append "stable") :dp 1)))Within expression arrays, the first item is a form symbol. A $name ($payload, $payload-float, $payload-int, $payload-bool, $subject, $replaying, $reply-to) lowers to the bound symbol, and an option map such as {ms: 5000} lowers to keyword/value pairs. Bare option words (ms, dp, subject, ...) remain supported, including standalone flags. Option maps must be nonempty and use unique known keys; values may be expressions, but cannot be maps. Other flow maps are unsupported. Single-quoted scalars are raw ('' is one quote); double-quoted scalars follow standard YAML escapes. Every other string in a rule body must be quoted; an unquoted word that is not a number, boolean, null, binding or option is a load error, so a typo cannot silently become text. Operators made of punctuation (>, *, ->) must be quoted too, as in [">", $payload-float, 80]. when: EXPR is a rule-level guard beside one body key, and [vector, 1, 2, 3] is a literal vector. See examples/rental-car.yml for the fuller shape and patchbay-yaml-schema.md for the YAML shape reference.
JSON patchbay files#
EDN is the canonical notation for hand-written patchbays. Files ending in .json are also accepted, but treat that as a compatibility layer: useful for generated patchbays, web UIs, config systems, and users who need JSON as an affordance. If you're editing rules directly, consider embracing the S-expression form. It is terser, supports comments, and keeps symbols distinct from strings without escape hatches. VS Code's Calva gives good Clojure/EDN highlighting, bracket matching, paren coloring, and Parinfer-style editing. In Emacs, clojure-mode/CIDER works well; clojure-ts-mode is the newer tree-sitter option. Parinfer, paredit, and smartparens are all good ways to make S-expressions feel less manual.
The JSON spelling is not a separate DSL: arrays are forms and the first array item is always the operator symbol. In argument positions, plain objects become keyword options, and strings with a leading $ ("$subject", "$payload", "$payload-float", "$payload-int", "$payload-bool", "$replaying?", "$reply-to") become bound symbols in rule expressions. An unknown "$name" is a load error.
[
["on", "sensors.*",
["->", "$payload-float", ["round", 1], ["squelch"], ["publish!", ["subject-append", "stable"]]]],
["on", "market.*", {"reentrant": true},
["bar!", 60, "$payload-float"]],
["every", {"ms": 1000}, ["publish!", "tick", "alive"]],
["export", {
"servers": ["nats://127.0.0.1:4223"],
"export": ["sensors.*.stable"]
}]
]Other strings in argument positions are string literals, so a plain "payload" is just the text payload, with no error. That is the one migration hazard from the older JSON spelling, where bare "payload" was the bound value: an old file still loads, and silently publishes the word instead of the payload. Search old JSON patchbays for bare "subject", "payload", "payload-float", "payload-int", and "replaying?" and add the $. Use {"str":"$payload"} if you really need the literal text $payload in a rule body, {"kw":"ms"} for a standalone keyword, and {"vector":[...]} when a rule body needs a literal vector (the old {"vec":[...]} key is a load error). See examples/demo.json for a fuller conversion of examples/demo.edn.
EDN is the notation; the patchbay is the evaluator#
Patchbay files are valid EDN, which is why .edn editor tooling (syntax highlighting, paren-matching, structural editing) works out of the box. EDN itself is a data notation: it parses lists (...), vectors [...], strings, numbers, keywords, and so on, and stops there. It does not say what any of those mean. The patchbay is the piece that gives some of those forms call semantics, and only in some places.
If you've used Clojure, this is the part where the muscle memory diverges. Clojure's rule is "every (...) is a call unless I '-quote it." Patchbay has no quote form and doesn't need one, because whether a list dispatches as a call is decided by where it appears, not by a sigil:
- Inside an
(on FILTER BODY)or(every :ms N BODY)body, every list dispatches on its head symbol (hold-off,publish!,+, etc.). Unknown heads and unknown symbols are rejected at load and by--validate, in every branch, not just the one a test message happens to take. - Inside top-level config forms, sequences are data. In
(lvc ...), a single vector is read as the filter set. Inside(export ...), deprecated(bridge ...), and(import ...), after a keyword like:servers,:export, or:subject, a list is read as a literal sequence of values.(:servers ("nats://a:4222" "nats://b:4222") ...)is a two-element list of strings, not a call tonats://a:4222. Same parser, different consumer. The one special list in config string positions is(env "NAME"), which reads an environment variable at patchbay load time.
For unambiguous data-as-data inside a rule body, write a vector with square brackets: [1 2 3], ["red" "green" "blue"]. Vectors self-evaluate (each element is evaluated, the result is returned as a vector), they never dispatch on a head, and they're what contains? checks for membership against. Config readers (export, deprecated bridge, import) accept either (...) or [...] for keyword-tagged collections; vectors read more naturally and are the recommended form.
Validate and debug rules#
Run a patchbay directly with monoblok examples/<file>.edn, .json, or .yml; form-lint without starting the server with monoblok --validate examples/<file>.edn.
For quick patchbay debugging, --soundcheck runs the same evaluator without opening a NATS socket. It reads newline-delimited SUBJECT|payload rows on stdin, passes inputs through stdout, and prints any publish! emissions. Clock/window state lingers briefly after EOF so delayed forms can close; use --soundcheck-linger-ms 0 to disable that wait.
printf 'sensors.temp|31\n' | monoblok --soundcheck examples/sensors.edn
printf 'sensors.temp|31\n' | monoblok --soundcheck --soundcheck-label examples/sensors.edn--validate loads the file with the same loader as startup, so it is strict: unknown forms and symbols are rejected in every branch, duplicate export / import forms and non-integer numbers where an integer is required are errors, and parse errors report line:col. --soundcheck follows :reentrant true publishes like the server does. reply-to is always nil under --soundcheck, so check reply! rules against a running server with nats req. At runtime a failed rule evaluation is logged with the rule's filter and rate-limited (the first failure, then every power of two).
--trace: protocol trace#
Logs parsed client operations to stderr. For rule-level debugging, use --soundcheck or a temporary (print! ...) inside the patchbay.
$ monoblok --port 4222 --patchbay patchbay.edn --trace
trace: conn 1 CONNECT
trace: conn 1 SUB sensors.> 1
trace: conn 2 PUB sensors.temp 4Stage by stage with print!#
(print! LABEL X) writes one line to stderr and returns X unchanged, so it can sit between any two steps of a pipeline. See Debug printing.
Watching rule counters#
The server publishes emitted and suppressed totals for every rule on $STATS.rules.<i>.*, so you can confirm a gate is actually firing (or not).
nats sub '$STATS.>'Coding assistants#
The portable patchbay-authoring skill teaches Codex and Claude Code the DSL and how to validate rules. Download the standalone ZIP, then extract it into .agents/skills/ for Codex or .claude/skills/ for Claude Code. No repository checkout is needed. The usage guide covers project and personal installation, updates, and examples.
Invoke $patchbay-authoring in Codex or /patchbay-authoring in Claude Code. Describe your input subjects and payloads, desired outputs, and thresholds or windows; ask the agent to run monoblok --validate and monoblok --soundcheck and show the transcript. Install Monoblok locally to run those checks. In this repository the skill is already available to both agents.
Scrutinise every line of a generated patchbay before you run it anywhere that matters. A file that validates is well-formed, not correct, and a soundcheck transcript only covers the rows that were fed in.
For some elaborate generated demos, see advanced-examples/. They are intentionally a bit over the top, but they give a feel for what is possible.
Use Claude or Codex has a worked example and a review checklist. Two generated patchbays of this kind are walked through in Large patchbays.
MIT licensed · © 2026 Alex Reid
Lexvica offers solutions built with monoblok.