WYRM
WYRM is an industrial IoT broker. Devices, services and logic live in one tree of
nodes. Every client reads it the same way: list a node’s children, subscribe
to values, set a value, invoke an action. Under the tree runs
Eclipse Zenoh 1.x as the transport. WYRM adds the semantics
on top: key-space conventions, canonical CBOR, tokens and static plugins.
Zenoh itself is not patched or forked.
Status: before 1.0 (version 0.1.0). The protocol (
spec/0.2.36) and the broker are tested on every commit (unit, fixture and end-to-end tests). Every protocol link is tested against its own simulator. No link has been checked against a real device yet (ADR 0029, decision 5). Expect changes.
- Source code: github.com/gencto/wyrm
- Releases: github.com/gencto/wyrm/releases
- Read next: Overview · Documentation map · Specification
Official links
Links connect devices and services to the broker. This table comes from links/official.json.
| Link | Category | Summary | Forms |
|---|---|---|---|
| Modbus | Equipment | Modbus TCP, RTU over TCP and serial RTU devices, as a master or as a slave | builtin, process |
| OPC UA client | Equipment | Nodes of OPC UA servers as points: batched reads, typed writes, browse | builtin, process |
| BACnet/IP | Equipment | BACnet/IP devices: Who-Is discovery, batched reads, writes with priorities, BBMD | builtin, process |
| Siemens S7 | Equipment | S7-300/400/1200/1500 PLCs over S7comm (ISO-on-TCP) | builtin, process |
| SNMP | Equipment | SNMP v2c and v3 agents: batched GET, table columns, SET, walk | builtin, process |
| MQTT | Equipment | MQTT topics as points (JSON, raw, Sparkplug B) | builtin, process |
| HTTP / REST | Equipment | JSON APIs polled on a schedule, JSONPath selectors as points, JSON writes | builtin, process |
| Prometheus | Equipment | Prometheus and OpenMetrics endpoints scraped into points | builtin, process |
| S3 and compatibles | File stores | A bucket of AWS S3, MinIO, R2, Wasabi, B2 or GCS as a tree of folders and files | builtin, process |
| Google Drive | File stores | A Google Drive folder or shared drive as a tree of folders and files | builtin, process |
| WebDAV | File stores | A folder of Nextcloud, ownCloud or another WebDAV server as a tree | builtin, process |
| Local folder | File stores | A directory of the host (disk, USB/SD card, network mount) as a tree | builtin, process |
| PostgreSQL / TimescaleDB | History sync | Sends the historian’s journal to PostgreSQL or TimescaleDB | process, wasm |
| MySQL / MariaDB | History sync | Sends the historian’s journal to MySQL or MariaDB | process, wasm |
| MongoDB | History sync | Sends the historian’s journal to MongoDB | process, wasm |
| InfluxDB 2.x / 3.x | History sync | Sends the historian’s journal to InfluxDB | process, wasm |
| DynamoDB | History sync | Sends the historian’s journal to Amazon DynamoDB | process, wasm |
| Scheduler | Apps | Weekly schedules and special days that write values to points | process, wasm |
| Alarms | Apps | Alarm classes on points, records, acknowledgement and export | process, wasm |
| DQL queries | Apps | Standing and ad-hoc queries over the tree, as tables | process, wasm |
| Platform upstreams | Apps | Live values to MQTT/UNS, Sparkplug B, ThingsBoard, Azure IoT Hub, AWS IoT Core | process, wasm |
| Telegram | Messaging | Telegram bots: templates, recipients, paired chat users | process, wasm |
| Slack | Messaging | Slack bots: templates and recipients, send only | process, wasm |
| Assistant agent | Apps | An AI agent that plans changes for a person to approve | builtin |
| Mock device | Test | Simulated devices on the driver framework, for trials and tests | builtin, process |
Latest architecture decisions
| ADR | Title | Status |
|---|---|---|
| 0051 | Broker images for boards, and a web image builder | proposed · 2026-11-25 |
| 0050 | Biometric unlock with device keys, and finding a gateway on the local network | accepted · 2026-11-14 |
| 0049 | What the agent link and the gateway need for the Studio Assistant | proposed · 2026-11-14 |
| 0048 | Updates, restore points and backups from Studio | proposed · 2026-11-13 |
| 0047 | Checking an action without running it (~act/<a>?check) | accepted · 2026-11-13 |
| 0046 | Link grants on the site’s storage | accepted · 2026-11-13 |
| 0045 | Flow metrics in ~val | accepted · 2026-11-12 |
| 0044 | Flow blocks, third set: computation on the server | accepted · 2026-11-11 |
| 0043 | The official links manifest: one checked-in list, one published index | accepted · 2026-11-11 |
| 0042 | Names people read: one rule for actions, parameters and nodes | accepted · 2026-11-11 |
All decisions: architecture decisions.
Latest specification changes
- 0.2.36 (2026-11-20): 04 — a
ptokis at most 65 536 bytes; a responder refuses a longer one (permission_denied) before it checks the signature, and a minter makes none (security audit of PR #150: the cost of a refused token grows with its length times the number of trusted keys). The wire format does not change. No fixture change. - 0.2.35 (2026-11-15): 01 — a
~valselector withhistoryorsincenames each ofhistory|since(not both),agg,window,limitat most once and no other parameter; names that start with_are Zenoh’s and are not read; a duplicate or another parameter isinvalid_parameter(typing audit 2026-11-15: afromtext could add its ownlimitto the gateway’s selector, and the historian took the first). A requester makes the selector from parsed values only. No fixture change. - 0.2.34 (2026-11-14): 06 — the 100 ms of a table’s per-row scripts are CPU time of the thread that runs them; time the host keeps that thread off a core does not count, and the wall clock counts only where the platform has no thread CPU clock. No fixture change.
- 0.2.33 (2026-11-13): 01, 05 —
~act/<a>?check: the responder checks a call as the action would take it (token, level, arguments against the meta, its driver’s own parsing) and does nothing; the answer isokor the refusal the action would give; the audit recordscheck. A responder that answers it hasattr.check = trueon its root~meta; a requester sends?checkonly there (an older responder would run the action). A WASM component of world 0.3.0 checks against the meta only (ADR 0047). No fixture change. - 0.2.32 (2026-11-13): 04 — the “no details in
err” rule covers the token check and the level check of the request; a refusal the responder gives after them by its own rule (a key outside a link’s grants or its author’s rights, an action that writes outside the node granted) says why inerr. The responder logs the reason of every refusal. No fixture change. 06 —permissions.maxpermis a code or a name ("write"), as the engine already read it; its refusal names both (2 (read) < 3 (write)). No fixture change. - 0.2.31 (2026-11-12): 06 — flow metrics:
~valgets the text keystats{nodes, edges, samples_in, samples_out, dropped, restarts, commands: {sent, ok, error}, last_sample_t?}(additive; old readers ignore it).samples_in= samples a node takes from an edge or from its own source (answers, read requests and triggers are not samples);samples_out= samples sent on a wired output;dropped= inbox drops ofpolicy.overflow;commands= thesent/ok/errorevents ofinvoke/set. Counters reset at each deploy (so at every engine start and ACL rebuild),startandreload, and are kept across a restart after a panic (restarts+ 1) and while stopped. A refused draft’sstate: 2anderrorstay in the later~vals until the next state change. A state change publishes~valat once as before; otherwise~valgoes out again only when the counters moved, at most once per period (wyrmd:metrics_interval_ms, at least 5 s) (ADR 0045). No fixture change.
All changes: specification changelog.
This site is built from the repository after every merge to main. Do not edit it by hand: change docs/, spec/ or links/official.json.
WYRM
WYRM is an industrial IoT broker. Devices, services and logic live in one tree of
nodes. Every client reads it the same way: list a node’s children, subscribe
to values, set a value, invoke an action. Under the tree runs
Eclipse Zenoh 1.x as the transport. WYRM adds the semantics
on top: key-space conventions, canonical CBOR, tokens and static plugins.
Zenoh itself is not patched or forked.
One binary, wyrmd, is the broker. It holds the router, the admin, the flow
engine, the historian, the user gateway and the links. WYRM Studio, a
Flutter app, is the desktop window onto one broker or a chain of them.
Wyrm: a wingless serpent-dragon. Its long body of segments is like a tree of nodes, and it is kin to the dragon on Zenoh’s logo.
Status: before 1.0 (version 0.1.0). The protocol (
spec/0.2.36) and the broker are tested on every commit (unit, fixture and end-to-end tests). Every protocol link is tested against its own simulator. No link has been checked against a real device yet (ADR 0029, decision 5). Expect changes.
What you get
Broker core
- A node tree under
wy/<site>/…with livelist,subscribe,setandinvoke. Metadata, profiles and units come with every node (spec). - A control plane in the same tree (
sys/**): links, packages, tokens, an internal CA, a generated ACL, quarantine, audit, logs and status values (broker reference). - Security on by default: TLS/mTLS off loopback, signed per-request tokens (
ptok), secrets sealed outside the tree, rate limits, and an audit of everysetandinvoke(threats). - Broker storage
storage/**for folders and typed values people create.
Links (connectors)
- Protocols: Modbus TCP/RTU (master and slave), BACnet/IP, OPC UA, Siemens S7, SNMP v2c/v3, MQTT and Sparkplug B, HTTP/REST JSON, Prometheus/OpenMetrics.
- File stores: S3 and compatible stores, Google Drive, WebDAV, a local directory.
- History sync to PostgreSQL/TimescaleDB, MySQL/MariaDB, MongoDB, InfluxDB and DynamoDB.
- Messengers: Telegram (paired users can read and set points from a chat) and Slack.
- Three ways to run a link: embedded, as a process, or as a sandboxed WebAssembly component. Links install while the broker runs: from the official list, a zip, a URL, Git or a
.wasmfile (links).
Logic and data
- Dataflows: a graph of 125 block types. They cover math, logic, text, date and time, tables, readers, alarms, rhai scripts, WASM nodes and the action block that writes and invokes (blocks). Every block has a value test.
- 14 ready-made flows in
examples/flows: a threshold alarm, running hours, daily energy, a schedule setpoint and more. A test compiles and runs each one. - Every deployed flow shows its counters in
dataflows/<id>/~val.stats: samples, drops, restarts and command results (ADR 0045). - An embedded historian with watch groups, rollups and one file per day (history).
- Built-in links: a scheduler (weekly schedules, special days, overrides; scheduler), alarms (classes, acknowledgement, escalation, export; alarm), DQL (live tables over many points; dql) and uplink (MQTT UNS, Sparkplug B, ThingsBoard, Azure IoT Hub, AWS IoT Core; uplink).
Many sites
- Brokers form chains and stars over QUIC with mTLS. A downstream broker enrolls with its upstream, and the upstream reads it and commands it as the downstream allows (broker reference).
- A standby broker follows the active one (stores, files, storage, history) and takes over through a witness (operations).
People and tools
- WYRM Studio (
studio/), a desktop app in English and Ukrainian. Its screens:- Explorer: the tree, actions, staged writes;
- Links: the install wizard and quarantine;
- Flows: the editor with live values, custom blocks, undo;
- History, Access and Sites (a map of the broker network);
- System: status, availability, log, maintenance;
- Assistant (studio).
- A user gateway: logins, roles, and a WebSocket CBOR proxy that filters each point by the user’s grants.
wyr, the CLI for operators and developers (tools/wyr).- AI: an MCP server, a Claude Desktop extension and OAuth
/mcpon the gateway (claude, mcp). Thewyrm-agentCLI runs checked plans, and the agent link runs only plans a person approves (agent). - SDKs: Rust (
wyrm-client,wyrm-link-sdk, portable links onwyrm-link-api), Dart (dart/) and a C ABI (crates/wyrm-ffi).
How it fits together
flowchart TB
studio["WYRM Studio · wyr · MCP / Claude"] -->|"HTTPS + WebSocket"| gw
subgraph wyrmd["wyrmd (one site)"]
gw["user gateway"]
admin["admin · sys/**"]
flow["flow engine · dataflows/**"]
hist["historian"]
stor["storage/**"]
emb["embedded links<br/>scheduler · alarm · dql · uplink"]
router(("Zenoh router"))
gw --- router
admin --- router
flow --- router
hist --- router
stor --- router
emb --- router
end
router -->|"mTLS"| proc["process and WASM links<br/>modbus · opcua · bacnet · s7 · …"]
proc --> dev["devices and services"]
router <-->|"QUIC + mTLS"| peers["upstream and downstream brokers"]
Rules that hold everywhere (ADR 0001–0011):
- Zenoh is the transport; WYRM puts its meaning into the key space, a CBOR attachment, the SDKs and static plugins. It never loads dynamic Zenoh plugins.
- The broker persists only its own state: registry, ACL, PKI, profiles and flow definitions. A link owns its subtree and declares it again on every connect.
- Nobody reads another component’s state directly. Every component uses
put,getandsubscribeon keys, in-process too. - The wire has one codec: canonical CBOR with integer keys.
Quick start
The demo: three sites and Studio
examples/demo/run.sh # build, then start plant → edge → central; Ctrl+C stops all
- Wait until all three sites are up. Each site runs its links against their simulators: Modbus, HTTP, SNMP, Prometheus, S7, BACnet, OPC UA and mocks.
- Log in to a site’s gateway with user
adminand passwordwyrm-demo-1(or$WYRM_GATEWAY_ADMIN_PASSWORD). The gateways are centralhttp://127.0.0.1:8445, edge:8444and plant:8446. - Note that central reads plant through edge.
examples/demo/run.sh --clean starts from empty sites.
WYRM Studio
Studio needs Flutter 3.50.0 (pinned in studio/pubspec.yaml) and frx.
cd studio && flutter pub get
cd app && flutter run -d macos # or linux, windows
Log in to one of the demo gateways. Each screen and its broker calls are in docs/studio.md.
One broker
cargo build --release -p wyrmd -p wyr
target/release/wyr keygen --out admin.key # prints the public key
- Put the printed key into
admin_keysinexamples/wyrmd.json5. - Start the Modbus simulator, which the example’s
plc1link talks to:cargo run -p wyrm-link-modbus --features bin --bin wyrm-modbus-sim & - Start the broker:
target/release/wyrmd -c examples/wyrmd.json5 - Read and write the tree:
target/release/wyr list wy/local/downstream target/release/wyr sub 'wy/local/downstream/mock/**' target/release/wyr --key admin.key set wy/local/downstream/mock/g0/g0/p0 42 target/release/wyr --key admin.key invoke wy/local/downstream/mock count n=3
To use Studio with this broker:
- Uncomment the
gatewayline in the config. - Start
wyrmdonce withWYRM_GATEWAY_ADMIN_PASSWORDset. This creates the first admin (broker reference).
Containers
deploy/docker builds minimal scratch images: static musl binaries, no shell, a non-root user.
docker compose -f deploy/docker/compose.yaml up -d --build
Official links
Each links-v* release on GitHub holds every official link as a package: WASM, and process binaries for linux-x86_64, linux-aarch64 and macos-aarch64. The release links-index holds the index. To get the official list in Studio’s install wizard and in install_repo, set packages.repository: "official" in wyrmd.json5. The broker then checks the SHA-256 of every package. The manifest is links/official.json; links.md §12a describes the release.
Repository
| Path | What |
|---|---|
crates/wyrmd | the broker binary |
crates/wyrm-core | wire types, canonical CBOR codec, key-space helpers |
crates/wyrm-link-sdk | the link SDK and the driver framework (connection → device → point; ADR 0004) |
crates/wyrm-client, crates/wyrm-gateway-client | clients of the tree and of the user gateway |
crates/wyrm-admin, wyrm-state, wyrm-gateway | control plane, WAL state, user gateway |
crates/wyrm-flow, wyrm-wasm-host | dataflow engine and WebAssembly host |
crates/wyrm-history, wyrm-history-sync, wyrm-storage, wyrm-schedule, wyrm-dql, wyrm-messenger, wyrm-filestore | the cores of the historian, the sync links, storage, schedules, DQL, messengers and file stores |
crates/wyrm-link-api, wyrm-link-portable, wyrm-link-guest | portable links that run natively or as WASM components |
crates/wyrm-ffi | C ABI (include/wyrm.h) |
links/* | the links; links/official.json lists those that are released |
studio/ | WYRM Studio (Flutter, AsyncRedux, made with frx) |
dart/ | Dart packages: codec, gateway client, FFI |
tools/wyr, tools/wyrm-mcp | the CLI and the MCP server |
spec/ | the normative protocol and its CBOR fixtures |
docs/ | guides, ADRs, security review |
examples/ | the demo, broker configs, flows, agent plans, example links |
deploy/, packaging/ | container images, the Claude Desktop extension, the links release workflow |
Documentation
Start at docs/README.md. It lists a guide for each task and each protocol, plus the rules and decisions. Key entry points:
- broker.md: the
sys/**tree, storage, many brokers, the gateway, flows from the CLI. - operations.md: systemd, backup and restore, standby.
spec/: keys, metadata, values, tokens, methods, flow definitions.docs/adr/: one file per decision.- SECURITY.md: how to report a vulnerability, what is supported.
Development
cargo fmt --all --check
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo test --workspace --all-features
spec/is normative. A change there needs four more steps: updatespec/fixtures/gen.py, regenerate the 28 fixtures, make every SDK’s fixture test pass, and add a line tospec/CHANGELOG.md.- A decision goes into
docs/adr/. - CONTRIBUTING.md has the code rules (wire enums, QoS, logging, drivers).
- Zenoh is pinned to an exact version, now 1.10.1. The MSRV is Rust 1.97 (wasmtime 50).
License
WYRM documentation
Start with the root README: what WYRM is, a quick start with one broker, and the demo of three sites (examples/demo/run.sh).
Guides
| Guide | Read it when you want to |
|---|---|
| broker.md | look up the broker’s own trees: sys/** (links, packages, tokens, quarantine, logs, history, audit), profiles, storage, two or more brokers, the gateway, flows from the CLI |
| links.md | install a link while the broker runs, package one, give it network or grants; §12a: the official links (links/official.json, packages.repository: "official", the release workflow) |
| history.md | record points, read their history, keep broker storage (storage) |
| scheduler.md | switch equipment on a weekly schedule, with special days and overrides |
| dql.md | collect values from many points into one table, or write them on to a target |
| alarm.md | raise alarms from points (range, boolean, staleness, quality), acknowledge them, send the records to a central database |
| uplink.md | send live values to an MQTT broker (UNS), a Sparkplug B host, ThingsBoard, Azure IoT Hub or AWS IoT Core |
| messenger.md | send alarms and reports to chat platforms from templates and recipients; telegram.md: paired users read and set points; slack.md: mrkdwn and Block Kit |
| ../deploy/docker | run the broker and links in minimal scratch containers; image sizes and memory |
| filestores.md | connect S3, Google Drive, WebDAV or a local directory and move files |
| claude.md | connect Claude Desktop to the broker network as a gateway user (one-file extension, no API key) |
| mcp.md | let an AI assistant read the tree and propose changes for a person to approve |
| agent.md | work on the broker network from the command line (wyrm-agent), or run the AI agent link |
| flow-blocks.md | calculate in a dataflow with its 125 blocks; start from a ready-made flow in examples/flows |
| operations.md | run wyrmd under systemd or a container, know what a restart recovers and how fast, back up and restore data_dir |
| studio.md | build WYRM Studio, the Flutter app: layout, rules, the frx commands of each phase, every screen’s broker calls |
Protocol links
| Guide | Devices or services |
|---|---|
| modbus.md | Modbus TCP and RTU, as a master or as a slave |
| bacnet.md | BACnet/IP devices |
| opcua.md | OPC UA servers |
| s7.md | Siemens S7 PLCs |
| snmp.md | SNMP v2c and v3 agents |
| http.md | HTTP/REST services that answer JSON |
| prometheus.md | Prometheus and OpenMetrics endpoints |
The history sync links (links/postgres, mysql, mongodb, influxdb, dynamodb) send the historian’s data to an external database. ADR 0026 describes them.
Every protocol link has a simulator. The guides show how to run it. No link has been checked against a real device yet (ADR 0029, decision 5).
Rules and decisions
spec/is the normative protocol: keys, metadata, values, tokens, methods, flows.adr/holds one file per decision. ADR 0029 collects the decisions the owner delegated on 2026-10-31. ADR 0031 says what happens to each finding of the security review of 2026-10-31 (security/review-2026-10-31.md).security/review-2026-11-15-typing.mdis the typing audit of 2026-11-15, with the status and order of work of each finding.security/threats.mdlists the threats and what answers each one.backlog.mdlists the work that is known and not done.
Broker reference
The broker’s own trees and endpoints in one place: the control plane sys/**,
profiles, broker storage, two or more brokers, and the user gateway. The root
README says what WYRM is; operations.md says how
to run it. The normative protocol is spec/.
Control plane
wyrm-admin serves wy/<site>/sys/** with the same list/subscribe/invoke as devices. Actions need a ptok with config, except hello, which checks the link token.
| Node | Actions / value |
|---|---|
sys | values as on a DSA broker (versions, start time, traffic per second, allow_all_links, enable_quarantine); ~act/clear_conns, get_permissions, update_permissions {role, path, level} |
sys/links | Install Link ▸ ~act/install {id, driver, mode, params} (from Driver), install_zip {name, zip}, install_url {name, url}, install_git {name, url, ref}, install_repo {name, package}, install_wasm {name, wasm} — packages run as process or WASM links; see docs/links.md. packages.seed_dir: the packages of a board image’s seed, installed once on the first start as broker:seed (operations.md “Seed packages”, ADR 0051 §1) |
sys/packages/<name> | installed link package (version, kind, source, SHA-256); ~act/remove |
sys/upstream | brokers this one connects to (as DSA’s): ~act/add {name, url, ca, token, enabled} with url the upstream’s peers.enroll; this broker makes its own key and asks for its certificate; <site> shows url, ca, certificate, key (SHA-256 of our public key), status (pending authorization, issued, a refusal), writable enabled; ~act/remove (ADR 0015) |
sys/overlays/<link> | attributes the broker lays over that link’s nodes (ADR 0016): today attr.history of each recorded point (its watch keys); the link’s SDK merges them into ~meta and the view=list summary (has_history) |
sys/tokens | ~act/add {count, hours} → a token (shown once) that admits a downstream broker at once; <id> shows uses and expires, ~act/remove |
sys/~act/enroll | open action on the peers.enroll listener: a downstream broker’s {site, csr, token, via} → {status: issued, certificate, port}, pending or refused |
sys/links/<id> | ~act/start, stop, remove, hello {token}, set_secret {name, value}, delete_secret {name}, update {params}, history, rollback {rev} (runtime-installed links; the last 10 params revisions are kept), grant {path, level} (requester grants, ADR 0013); child state (installed, starting, connected, stopping, stopped, failed) |
sys/quarantine | ~act/authorize {dsid, group, name, via}, deauthorize {link} (a runtime external link or downstream broker goes back to quarantine) |
sys/quarantine/<cn> | unknown CA-signed certificate (a link over tls, or a downstream broker broker:<site> over quic, attr.kind); ~act/approve {driver, params, group, name} ({via} for a broker), reject |
sys/log_level, sys/~act/get_log {lines, level, filter, link} | broker log level (saved) and its last log lines; sys/links/<id>/log_level and ~act/get_log for each embedded or process link |
sys/acl_denied | router access-control drops (with the other broker status values: uptime, links, sessions, CPU, memory, disk) |
sys/history | embedded historian (ADR 0014): database values, auto_purge, disk_space_remaining, retention_days; ~act/add_watch_group {name, logging_type, interval, buffer_flush_time}, purge {timerange}; sys/history/<group>: edit, add_watch_path {path}, remove {purge}; sys/history/<group>/w<N>: enabled, start_date, end_date, get_history {timerange, interval, rollup, limit}, purge, unsubscribe, unsubscribe_purge — see docs/history.md |
sys/audit | ~act/tail {n} — HMAC-chained audit records |
wy/<site>/sys/broker | liveliness token of the broker (no node); sys ~meta carries attr.proto, version, site |
wyr gets admin commands as well (links, install, set-secret, …) — see wyr --help. ACL changes rebuild the router runtime (ADR 0006).
Link secrets (device passwords, keys) live in data_dir/secrets.bin (ChaCha20-Poly1305, key file 0600), never in the tree, ~def or logs. install refuses params that look like secrets. Embedded links get them at start, process links in the hello reply; a link sees a new secret on its next start. wyr admin set-secret <site> <id> <name> reads the value from stdin.
Profiles
A node’s ~meta.is names a profile; absent fields come from it, through extends (spec 02). The admin serves wy/<site>/pub/<profile>/~meta (10 built-ins such as wy:number, wy:folder, wy:link; others stored in its WAL) and changes them with sys/profiles/~act/put {name, profile} and remove {name} (config). ?expand=true returns a profile with its chain folded in; WyrmClient::meta_expanded(node) returns a node’s ~meta with its profile applied. Links and upstream sites may read pub/**; nobody but the admin writes it.
Storage
wy/<site>/storage keeps nodes and values people create, as a DSA broker’s /data (ADR 0017). The root offers add_node {name}, add_value {name, type, editor}, publish {path, value} (creates the missing folders and a dynamic value), export and import {data | file} (JSON: $type, @editor, ?value, children as objects, binary as {"$hex": …}; a file larger than a WebSocket frame goes over POST /api/invoke); a folder also offers delete {recursive}, rename {name} and duplicate {name}, a value ~set, delete, rename and duplicate. Types: string, number, bool, array, map, binary, dynamic. Every action and ~set needs write; the admin keys, users through the gateway (viewer read, operator write, engineer config) and flows (at write) are trusted. The tree lives in data_dir/storage/storage.redb: structure at once, values at most once a second. Limits: 10 000 nodes, 16 levels, 32 KiB per value, 64 MiB in all, 4 MiB per import or export. A link stored under the id storage (before spec 0.2.2) stops wyrmd from starting: remove it with the previous version. The historian may watch storage values (add_watch_path {path: "storage/…"}); an upstream site reads them.
Two brokers
// central: brokers connect on 7449; they ask for their certificate on 7450
peers: { listen: "quic/0.0.0.0:7449", enroll: "quic/0.0.0.0:7450" },
As in DSA (ADR 0015), the downstream broker adds the connection itself: on edge, sys/upstream ▸ Add Upstream Connection {Name central, Url quic/central.example:7450, CA (central’s data_dir/pki/ca.pem), Token (optional)}. Edge makes its own key and asks central for a certificate. Central admits it:
- at once with a token from its
sys/tokens▸ Add Token, when edge relays no sites; - at once with
sys/allow_all_linkson, when edge relays no sites; - else edge waits in
sys/quarantine/edge(kind: broker): compare itskeywith edge’ssys/upstream/central/key, then Authorize (Via: the sites edge relays).
A broker that names relayed sites (via, at most 16) always waits for Authorize, token or not: only an administrator gives a downstream broker the right to publish under other sites’ names (security review, ADR 0031).
Edge then connects on 7449 and shows up in wy/central/downstream/edge; Deauthorize sends it back to quarantine. Central’s QUIC listeners trust its own CA alone (certificate CN broker:<site>); edge trusts central’s CA only on that connection.
Without runtime steps (wyrmd.json5 on both sides): central lists downstream: [{ site: "edge" }] and wyrmd -c central.json5 ca issues data_dir/peers/edge/broker.{pem,key}; edge names them: upstream: [{ site: "central", endpoint: "quic/central.example:7449", ca, cert, key }]. The upstream site may subscribe and query ~meta|~val under wy/<edge>/{downstream,dataflows,sys,upstream,storage}/** (and ~def|~state under downstream/dataflows). Requesters at the central broker may read wy/<edge>/**.
Commands from above (ADR 0018): central’s users (through its gateway) and operators (with central’s admin key, SigningTokens::new(key, "edge")) may set and invoke on edge’s downstream, dataflows and storage at write, as far as their grants at central go (wy/central/x grants count as wy/edge/x); config there (link actions such as Export, Edit, Stop) and edge’s sys only when edge allows it: allow_config: true on the peers.upstream entry, or sys/upstream/central/allow_config. Edge learns the keys that sign these requests from wy/central/sys/signing_keys (central’s admin keys and gateway key, and the keys above central; for config only those every hop allows) and trusts them only within its own site, at those levels; learning new keys rebuilds edge once. A sys action that edge does not allow is dropped on the way, so the caller sees a timeout. Edge’s audit names the user as user:<name>@central. Clocks must agree within a few minutes (tokens live 5 minutes).
Certificates last 365 days. The broker issues its own again (listener, client, process links, data_dir/peers/<d>/broker.*) when one has less than 30 days left: at a start, at each rebuild and in an hourly check that rebuilds when one was renewed. A downstream broker that enrolled asks its upstream again with the same key in those 30 days, and the upstream signs a new certificate for that key (audit renew); if the upstream does not renew, sys/upstream/<u>/status says so and the downstream asks again every hour (security review, ADR 0031). УВАГА: files issued for peers.downstream without enrollment (wyrmd ca) are renewed only in the upstream’s data_dir/peers/<d>/: copy them to the downstream again before the old ones end.
A chain plant → edge → central: edge lists plant as its downstream (and listens on QUIC), central adds via: ["plant"] to its edge entry, and then reads wy/plant/** through edge (ADR 0007) and commands it as plant allows (allow_config at each hop for sys).
Demo with a chain of three sites and connectors:
examples/demo/run.sh starts central, edge (mock, mockdev, modbus
as a process link, modbus_slave, http, snmp, prometheus) and plant
(mock, s7, bacnet, opcua; connected to edge), each link against its
simulator, each with a gateway (:8445, :8444, :8446, user
admin, password wyrm-demo-1); central reads plant through edge. wyrmd -c <cfg> ca creates a site’s CA
and the certificates of the sites below it before they start. The app is
WYRM Studio (studio/, studio.md); it logs in to
any of the three gateways.
Gateway
gateway: { listen: "0.0.0.0:8443", tls_cert: "gw.pem", tls_key: "gw.key", admin_user: "admin" },
// or a certificate the broker issues from its own site CA (ADR 0051 §3)
gateway: { listen: "0.0.0.0:8443", tls: "site_ca", admin_user: "admin" },
// the first admin from a one-time setup code; the file holds its hash (ADR 0051 §3)
gateway: { listen: "0.0.0.0:8443", tls: "site_ca", setup_file: "/etc/wyrm/setup" },
With tls: "site_ca" the broker issues the gateway’s certificate itself at each start, into data_dir/gateway/tls.{pem,key}, and keeps it while it names exactly the same names and has more than 30 days left. While the gateway serves, the broker reads the host’s addresses every 30 s and serves a new certificate when they change or the one in force has less than 30 days left, without a restart; clients trust data_dir/pki/ca.pem (operations.md §2, “Gateway TLS from the site CA”). On Linux, temporary (privacy), deprecated and tentative IPv6 addresses are left out of the certificate; elsewhere every global IPv6 address is named. A certificate the site CA did not sign (keys restored from another site) is issued again. With tls_cert/tls_key, a pair that cannot be read or does not match stops the broker at its start (the error names the file); at a later router rebuild such a pair leaves the certificate in force with a warning.
Start wyrmd once with WYRM_GATEWAY_ADMIN_PASSWORD set to create the first admin, or give it the hash of a one-time setup code in gateway.setup_file (wyrmd setup-code; ADR 0051 §3, operations.md “First admin from a setup code”): while no user exists, POST /api/setup {code, user, password} (CBOR, no session) makes that user an admin and uses the code up. It answers 204, or refuses with 409 code no_setup (no setup pending, or a user exists), 403 code setup_code_wrong, 400 for a name or password /api/users would refuse, and 429 from the limiter of /api/login (the same budgets: 5 failures per 60 s per user name and address, 20 per 60 s per address over all names). On a stopped broker, wyrmd -c wyrmd.json5 user list|add <name> --roles a,b|passwd|roles|disable|enable|remove manages users (passwords from stdin, changes audited as local:cli); while it runs, the stores are locked and the gateway’s /api/users endpoints do the same. POST /api/login {user, password} (CBOR) returns a session; POST /api/ws-ticket (bearer session) returns a single-use 30 s ticket, and GET /api/ws?ticket=… opens the WebSocket proxy (both for a session of a password or device login only; any other session gets 403 person_required) (list, subscribe, set, invoke, doc, filtered by the user’s grants). doc {key, suffix} reads a node’s document (suffix: ~state or ~def, at most 1 MiB) with the rights of list on the node; a restricted node (an agent’s tasks) decides by the user’s own token. invoke … approve {steps: [n…], plan} on an agent task is signed by the gateway: one token per named step, for the plan it reads itself, within the user’s grants (ADR 0049, docs/agent.md). The gateway signs one ptok per request with its own key, which links, the flow engine and the admin (sys/**) trust; the user’s grants decide what each request may do, and only the admin role has grants on sys/** (ADR 0009). Whoever can read data_dir/gateway/gateway.key is therefore a full administrator: keep data_dir readable by the broker user only. One user holds at most 8 WebSockets and sends at most 100 requests per second over all of them (burst 200; rate_limited past it); a history request asks for at most 10 000 rows (security review).
Device keys, step-up and finding the gateway (ADR 0050)
gateway: {
listen: "0.0.0.0:8443", tls_cert: "gw.pem", tls_key: "gw.key",
tls_ca: "ca.pem", // optional: the CA whose code people compare (default below)
devices: { enabled: true, max_per_user: 5, password_every_days: 30, idle_lock_max_min: 30,
step_up: "none", // "config": config changes need a confirm in the last 5 min
allow_device_credential: false,
origins: [] }, // default: the names of gw.pem on this port
announce: { enabled: true, interfaces: [], pair: "gw-b.plant.example:8443" },
}
A person turns on Unlock with Touch ID (or Windows Hello, Face ID, fingerprint) in Studio after a password login. The device makes a key in its secure hardware; the gateway keeps only the public key, in the users store (SCHEMA 5, replicated to a standby like the users). A later login is a signature over a single-use 60 s challenge: POST /api/device/challenge {device} → {nonce}, then POST /api/device/login {device, origin, nonce, signature} → the session a password login gives, with the same roles. The gateway refuses with a code: device_removed (an admin removed it), password_changed (a new password, Sign out everywhere or a disable signs every device out), password_due (no password on that device for password_every_days; a password login that names the device, POST /api/login {…, device}, clears it) and devices_off. An unknown device, a bad signature, a used or old nonce and an origin not in devices.origins all get the same bare 401, limited like password logins. GET /api/devices lists a user’s own devices, DELETE /api/devices/<id> turns one off (an admin’s removal of another user’s device leaves a tombstone that names the admin), GET /api/users/<name>/devices lists anyone’s for an admin, and POST /api/me/sign-out ends every session and signs every device out. With step_up: "config", a config change (a config action or point, user management, removing someone’s device) of a session that did not log in or confirm in the last 5 minutes answers confirm_required with a nonce and the request’s hash: sign them with POST /api/device/confirm or send POST /api/confirm {password}, then send the request again. Until a session is confirmed, every token the gateway mints for it reaches write at most. MCP tokens cannot confirm, so a site with the step-up on gives the MCP endpoint no config. Audit: device_added, device_login, device_refused, step_up, device_removed; never a key, nonce or signature. The signed bytes and the full rules: ADR 0050, last section.
GET /api/info (no session, 60 a minute per address) tells a log-in page {site, version, tls, role, pair?, up, devices: {policy}, min_studio, ca_fp?, ca?, names?, setup?, setup_proof?}; setup: true while a setup code waits for the first admin (ADR 0051 §3), absent otherwise. With a setup pending and a ca to show, setup_proof (32 bytes) is HMAC-SHA-256 keyed with the setup hash over "wyrm-setup-proof-v1\n" and the bytes of ca: a client verifies it from the typed code (wyrm_gateway::setup::verify_setup_proof) and checks that the connection’s certificate chains to that ca before it sends the code to /api/setup, then pins that ca (operations.md “First admin from a setup code”). Without the hash nobody can make a proof for another CA. When the gateway listens off loopback, wyrmd also announces it by DNS-SD (_wyrm._tcp, instance = site, TXT v, site, tls, fp, role, pair, up; no users, no secrets) while it serves; announce: {enabled: false} turns that off. Finding a gateway never means trusting it: Studio computes the CA’s code itself from the ca it received (8 groups of 4, never the ca_fp the server sends). The person compares it with wyrmd ca fingerprint on the broker. Studio pins that CA only after a second read under it alone. The code is of gateway.tls_ca, else the last certificate of a chain in tls_cert, else the site CA when it issued tls_cert or the gateway’s certificate (tls: "site_ca").
Flows
wy/<site>/dataflows/~act/deploy {def, proofs} deploys a flow (spec 06); ~def is read-only. Links trust the flow engine’s key, so the deployer sends one token per command target (proofs: target key → token with at least the flow’s maxperm, same subject). Targets must be exact keys under wy/<site>/downstream/ or wy/<site>/storage/. wyrm_flow::command_targets and WyrmClient::proof build the proofs; through the gateway, the gateway adds them (ADR 0008, 0033).
wyr --key admin.key flow validate local peak.json5 # compile only
wyr --key admin.key flow deploy local peak.json5 # signs one proof per invoke/set target
wyr flow list local # id, state (running|stopped|error), version
wyr --key admin.key flow show local peak # state + ~def
wyr --key admin.key flow stop|start|reload|remove local peak
dataflows/<id>/~val holds the flow’s state, version, deployer and, since spec 06 0.2.31, its counters stats (samples in and out, dropped, restarts, commands sent/ok/error; ADR 0045). The blocks are in flow-blocks.md; ready-made flows in examples/flows.
Data storage and history
This page tells you where WYRM keeps point values, how to record history in the broker, how to read it back, and what the limits are. Decision: ADR 0014.
1. What the broker keeps
| What | Where | How long | Who reads it |
|---|---|---|---|
The last value of every point (wy/**/~val) | Zenoh storage, memory volume, in RAM | until the broker stops | every subscribe (the stored value first, then live), get ~val |
| History of the points you watch | data_dir/history, one file per UTC day | until retention_days or auto_purge deletes the day | sys/history/<group>/<watch> ▸ Get History |
| Control-plane state (links, ACL, flows, settings) | data_dir/state (WAL + snapshot) | always | the admin |
The last values are not saved: after a restart a point has a value again when its link publishes one. History is recorded only for points in a watch group.
Broker storage (wy/<site>/storage, values that people create) is kept in
data_dir/storage/storage.redb. To change a storage value in the explorer,
click it in Metrics and type the new value:
| Type | Type it as | Example |
|---|---|---|
number | a number; a unit after it is ignored | 21.5 |
bool | choose true or false | |
string | text | north wing |
map | a JSON object | {"mode": "eco", "limit": 40} |
array | a JSON array | [1, 2, 3] |
binary | hex bytes, 0x before them is optional | 0x0a1b |
dynamic | JSON, or else text | {"on": true} or hello |
The explorer does not send text that is not of the value’s type. It shows why under the value, for example “a JSON object”.
2. Record history
Open wy/<site>/sys/history.
- ▸ Add Watch Group: Name, Logging Type, Interval, Buffer Flush Time.
- Open the group ▸ Add Watch Path: Path. Write
downstream/<link>/<point>(this site), or the full keywy/<site>/downstream/…(this site or a downstream site). Flow outputs (dataflows/<flow>/…) work too. - The watch appears as
w1,w2, … with the point key as its name. - The point itself shows that it is recorded: its
~metagetsattr.history(the watch keys), its row in the tree and in Metrics a history mark; a click on the mark opens its history (ADR 0016). A downstream site’s point recorded here gets the mark as seen through this site’s gateway (sys/overlays/.sites, ADR 0020), not on the downstream site itself.
| Logging Type | Records |
|---|---|
| None | nothing (the group is paused) |
| Interval | the last value of each point every Interval seconds, changed or not |
| All Data | every update |
| Point Change | an update whose value or quality differs from the last one recorded |
Only if more than 4096 updates of a point wait for the historian
(overflow) does it keep the newest one until it has caught up; the lost
updates are counted (EventStream::dropped, see docs/links.md “Streams
and a slow consumer”).
- Buffer Flush Time (seconds, 0.1 to 600): rows wait in memory, then go to disk in one write. A longer time writes less often; a crash loses the rows in memory.
- Interval (seconds, 0.1 to 86 400): Interval logging only.
- Change them with the group’s ▸ Edit. A watch’s
enabledpauses one point. - After a restart or a router rebuild the group goes on; the first value it sees is not stored again if it is the one already stored.
3. Read history
The watch ▸ Get History (needs config on sys/**, as every action
here: the rows are point values):
| Field | Meaning |
|---|---|
| Timerange | <from>/<to> in RFC 3339: 2026-10-22T08:00:00Z/2026-10-22T12:00:00Z. A date alone is its midnight UTC; an offset (+03:00) is allowed; an empty end is now: 2026-10-22/. |
| Interval | none, or a number and s, m, h, d, w: 5m, 1h, 1d. One row per interval, starting at from. |
| Rollup | how the samples of one interval become one value: none (the first), first, last, avg, min, max, sum, count, delta (last − first), and, or (booleans). A Rollup without an Interval gives one row for the whole range. |
| Rows | at most this many rows: 1 000 by default, at most 10 000. |
The answer is a table (in the explorer: output ▸ Table..):
- raw rows:
time,value,quality(good,uncertain,bad); - with an Interval or a Rollup:
time(the interval start) andvalue. Rollups skipbadsamples; intervals without samples give no row.
Each watch also shows start_date and end_date. It does not show
its last value (DSA’s Last Written Value): the point itself has it.
Without sys: the point’s own history
Everyone who may read a point’s value may read its history; no sys rights
are needed (spec 05 0.1.10):
| Where | How |
|---|---|
| Explorer | the history mark after a recorded point’s name, or right-click a recorded point (in Data or Metrics; attr.history, as DSA’s @@getHistory) ▸ View History: presets 1 h, 24 h, 7 d, 30 d, or From/To, Interval, Rollup ▸ Load; a chart of the numeric values (bad samples as red dots) and the rows; the store that records it at the top (a choice when there are several) |
| Zenoh | get wy/<site>/downstream/<link>/<point>/~val?history=2026-10-22T08:00:00Z..&agg=avg&window=5m (spec 01/03): one or more replies, each a CBOR array of [t, v, q] (or [t_start, v]) |
| Rust | WyrmClient::history(node, &HistoryQuery::from_text(from, to, agg, window, limit)?); HistoryQuery holds parsed values (TimeUs, Rollup, Window, NonZeroUsize) |
| Dart | api.history(key, from: …, to: …, agg: …, window: …) (gateway and FFI) |
| CLI | wyr values wy/<site>/downstream/mock/g0/p0 --from 2026-10-22 --agg avg --window 1h |
| Gateway WS | op history, args {from, to, agg, window, limit}; needs read on the point |
- Parameters:
history=<from>..<to>(an empty end is now) orsince=<from>;aggandwindowas Rollup and Interval above;limitrows (10 000 by default, at most 100 000; the gateway gives at most 10 000). Each parameter at most once and no other (spec 01 0.2.35): a repeated or unknown one isinvalid_parameter. - This site’s broker answers for its points; a downstream site’s broker answers for the points it records.
- Every watch also answers at its own key
(
wy/<site>/sys/history/<group>/<watch>/~val?history=): that is where a downstream site’s point recorded here is read (ADR 0020). Through the gateway it needs read on the point itself. - A point nobody records has no history: the answer is empty. A wrong parameter or a wildcard in the key is an error.
4. Space and purging
sys/history shows rows_written, writes_per_second, rows_pending,
rows_dropped, last_flush, database_size, space_available, series,
day_files and oldest_day. A group shows its logging_type, interval
and buffer_flush_time.
| Setting | Default | Effect |
|---|---|---|
auto_purge | on | Every minute: while the disk has less free space than disk_space_remaining, delete the oldest day. |
disk_space_remaining | 1024 MiB | The free space auto_purge keeps. |
retention_days | 0 (keep) | Every minute: delete days older than this. |
keep_after_sync_days | 90 | With at least one sink (section 6): delete a day once every sink confirmed it and it is older than this; 0 keeps only what is not sent; empty: off. |
- The current day is never deleted by these rules.
retention_daysandauto_purgenever wait for a sink: the equipment keeps recording while the cloud may be down. Rows a sink had not confirmed are counted in itsrows_dropped_unsent.- ▸ Purge {Timerange} on
sys/historydeletes every point’s rows in the range; on a watch, that point’s rows only. - ▸ Unsubscribe stops recording a point and keeps its rows; ▸ Unsubscribe and Purge deletes them too. A group’s ▸ Delete with Purge deletes the rows of all its watches.
- Every change, purge and automatic deletion is in the audit journal
(
history_group,history_watch,history_options,history_purge).
5. Limits
| What | Limit |
|---|---|
| Watch groups | 64 |
| Watches | 10 000 in all, one point each (no wildcards), never sys |
| Rows in memory | 200 000 for all groups; more are dropped (Rows Dropped) |
| Sample time | the source’s time; more than 5 min ahead of the broker’s clock or more than 31 days back: dropped (Rows Dropped) |
| Get History | 10 000 rows per call (~val?history=: 100 000) |
| One read | at most 5 000 000 rows scanned (a longer range is refused: ask for a shorter one); 4 reads at a time, others wait up to 5 s |
| Gap at a router rebuild | about a second: samples then are not recorded |
| Sinks | 16; a batch at most 5 000 rows and 1 MiB |
6. Sending the history on: sinks (ADR 0026)
A sink lets one link read what the historian writes, in batches, and send it on to another database (InfluxDB, PostgreSQL, MySQL, MongoDB, DynamoDB). The historian stays the store on the site; only it deletes.
- Install the link that sends the rows.
- On
sys/history/sinks▸ Add Sink {Name, Link, Groups, From}: the watch groups it takes, comma separated (empty: all); Fromstartsends everything on disk,nowonly what is written from now on. The link gets a requester key and, if it runs as a process, starts again; the broker rebuilds once. - The link asks ▸ Next Batch {After, Max} on its sink and gets
{rows: [{seq, key, t, v, q}], next}; it stores the rows, then asks again withafter=next. Thatafterconfirms every row up to it (at least once: a lost reply sends the batch again, so the database must replace on(key, t)). At most 5 000 rows and 1 MiB per batch.
Only the sink’s link may ask (it signs as link:<id>); a person who ran
Next Batch would confirm rows the database never got, so it is refused.
A sink shows link, groups, confirmed_seq, lag_entries (journal
entries after the cursor; rows of other groups count too), rows_sent,
rows_dropped_unsent and last_request; actions Edit, Reset Cursor {start |
now} and Remove. Every row written gets a journal number, so a late row or a
row written again is sent again. Rows recorded before this version have no
number and are not sent.
Sink links
Each database is a link package of its own (ADR 0026), built on
wyrm-history-sync: a WASM package by default, a process package from the
same code. Install it, then:
- Give it the params:
sink(the sink’s key,wy/<site>/sys/history/sinks/<name>: Copy Path on the sink),batch(rows per batch, default 500, at most 5 000),idle_s(wait when nothing is new, default 5),retry_s(longest wait after an error, default 60), and the database’s own params (below). Put the database’s host in the link’snetlist (a host name is allowed:db.example.com:443; a name reaches public addresses only, so a database on the LAN needs its address too:db.lan:5432, 10.0.5.20:5432). A WASM package reaches TLS only when it is built for the worldwyrm:app@0.3.0(everywyr link packsince 2026-11-01, ADR 0030); one built for 0.2.0 answersnot_supportedto TLS: rebuild it or use the process package. - ▸ Set Password: the password or token, kept in the link’s sealed store (never a param: the registry keeps params in the clear).
- Add the sink for this link (section above), then ▸ Test Connection.
The link shows status (connecting, reading, idle, waiting after an error,
failed, paused), error, rows_sent, rows_refused, last_batch and
cursor; ▸ Pause and ▸ Resume (kept across restarts). A failed link (wrong
token, a missing table, no rights) waits for a change: Set Password, Resume
or new params.
A row the database refuses for its data (a value too long or too large, a type it cannot take) does not stop the link (security review, ADR 0031):
- The link writes that batch again one row at a time.
- It skips each row the database refuses alone, logs its key and time
(never the value) at
warn, and counts it inrows_refused;errornames the reason. - It confirms the batch, so the cursor moves past the skipped rows.
- When the very first rows since the link started are all refused, the link
stops as
failedinstead: the database refuses everything, not one row.
ОБЕРЕЖНО: a skipped row is not sent again. Read rows_refused and error
after a change of schema or of a point’s type.
| Link | Params | Writes |
|---|---|---|
influxdb | url (https://host[:port][/base]; http:// only to loopback unless insecure_plaintext), org, bucket, measurement (default wyrm), ca_pem, timeout_ms | v2 write API (InfluxDB 2.x and 3.x), line protocol at µs: tags site, key; fields value (float: every number, and a bool as 1.0/0.0), value_text (text) and quality, so a series never changes a field’s type. Integers beyond 2^53 lose precision. A row that is not a number, a bool or text is skipped. measurement may not start with # or _. УВАГА: links before 2026-11-01 wrote integers as integer fields, bools as bool fields and text in value; InfluxDB refuses a float value for such a series until the next shard group (2.x) or for good (3.x). Give the link a new measurement after the upgrade, or such rows count in rows_refused. |
| postgres | host, port (5432), database, user, table (wyrm_history or schema.table), sslmode (require, default, or disable: loopback only unless insecure_plaintext), ca_pem, timeout_ms, create_table (true) | One table site, key, t timestamptz, value double precision, value_text text, quality smallint, primary key (key, t), upsert. TLS by SSLRequest; SCRAM-SHA-256, or a cleartext password over TLS or to loopback; MD5 is refused. TimescaleDB too (make the table a hypertable yourself). |
| dynamodb | region, table, access_key_id, endpoint (default the region’s; http:// only to loopback, for DynamoDB Local, unless insecure_plaintext), ttl_days (0: none), create_table (false), ca_pem, timeout_ms | BatchWriteItem, 25 puts per request, SigV4; partition key key, sort key t (µs), site, value (N, BOOL, S or NULL), quality, expiration (epoch s) with ttl_days: switch the table’s TTL on in AWS. The secret access key with Set Password. |
| mysql | host, port (3306), database, user, table (wyrm_history), ssl (require, default, or disable: loopback only unless insecure_plaintext), ca_pem, timeout_ms, create_table (true) | MySQL and MariaDB. One table site, `key` VARCHAR(700), t DATETIME(6), value DOUBLE, value_text TEXT, quality (utf8mb4), primary key (`key`, t), INSERT … ON DUPLICATE KEY UPDATE; text as hex literals. TLS by SSLRequest; caching_sha2_password (the full login only over TLS: no RSA) or mysql_native_password. A key over 700 characters is skipped. |
| mongodb | host (the primary or a mongos; mongodb+srv is not resolved), port (27017), database, collection (wyrm_history), user, auth_source (admin), tls (true; false only to loopback unless insecure_plaintext), ca_pem, timeout_ms, ttl_days (0: no TTL index) | OP_MSG; one document per row, _id: {k, t}, with site, key, t (µs), ts (a date), value, quality; a batch is one update of replace-upserts, ordered: false. SCRAM-SHA-256 (an ASCII password: it is not SASLprep-normalised). With ttl_days, a TTL index on ts. |
7. Other historians
A link can record history itself (another database, a cloud service): give
it a read grant on the points (requester in its package, or sys/links/<id>
▸ Grant Access, ADR 0013). examples/links/requester records
wy/<site>/downstream/mock to a CSV file this way.
8. Not yet
- A watch for a whole subtree (
downstream/<link>/**): today one watch is one point. - MCP tool
history(tools/wyrm-mcp).
Scheduler
The scheduler link keeps schedules in the broker and writes their values
to equipment at the times they give. It works offline, for months, with no
upstream connection: a restart, a power cut or a clock step does not miss or
repeat a transition. People (explorer) and AI (the agent link, through
actions) make the schedules. Decisions: ADR 0022 (the scheduler), ADR 0023
(portable links).
Code: crates/wyrm-schedule (the model and the evaluator; no I/O, no clock)
and links/scheduler (wyrm-link-scheduler, the link as a portable App).
1. Words
| Word | Meaning |
|---|---|
| Schedule | A value that changes with time: a default, a time zone, events and targets. Its value now is <s>/current. |
| Default | The value when no event is active. |
| Event | A value for a time: a window (start < end) or a moment (start = end), once or with a recurrence. |
| Window | The event’s value counts from start up to end; at end the next value takes over. |
| Moment | The event’s value is written once, at that instant. It has no end and no return to default: the schedule keeps the moment’s value until its next transition. |
| Priority | 1 (highest) to 9; 0 = none, the lowest. Decides between events active at the same time (section 6). |
| Special day | A local day (midnight to midnight in the schedule’s zone) that an occurrence of a special event touches. On that day only special events count. |
| Transition | A change of the schedule’s state: its value or the occurrence it comes from. Each transition writes the targets. |
| Target | A point the schedule writes on each transition, with a way to confirm the write (section 9). |
2. Where it runs
One source runs in three modes (ADR 0023). They behave the same.
| Mode | Where | How you get it |
|---|---|---|
| Embedded (the default) | wy/<site>/downstream/scheduler | Every wyrmd runs it. wyrmd.json5 scheduler: { enabled: true, store_mb: 64 } (both optional) turns it off or sizes its store (1–64 MiB). |
| WASM package | wy/<site>/downstream/<id> | Package scheduler (a component), Install Link ▸ from Repository / Zip / Url. Store 16 MiB (capabilities). |
| Process package | wy/<site>/downstream/<id> | Package scheduler-process, the same app as a supervised process. Store 16 MiB. |
examples/packages/build.sh builds both packages
(wyr link pack --manifest-path links/scheduler/Cargo.toml, the second
with --kind process --name scheduler-process).
- The id
schedulerbelongs to the embedded instance. A new link cannot take it, andwyrmdrefuses to start with a stored link of that id (as withstorage). The embedded scheduler is not insys/links. - Default zone. The param
default_tz(an IANA name, defaultUTC) is the zone of a schedule added withouttzand of a DSA import. The embedded scheduler takes the system zone (UTCwhen the system zone has no IANA name). A package uses its param: adddefault_tzto the link’s params, beside its capabilities, with the link’supdate(sys/links/<id>orwyr update). An update replaces the params: give the others again, assys/links/<id>▸ History shows them. For the WASM package:update {params: {net: "", store_mb: 16, memory_mb: 64, call_ms: 2000, component: "scheduler", default_tz: "Europe/Kyiv"}}(the process package has nocomponent). Withoutstore_mbthe store falls to 1 MiB. - Without its keys. The embedded scheduler signs its writes with keys
the admin keeps as link secrets. When the admin cannot save them (a full
or read-only disk),
wyrmdlogs it aterrorand runs without the scheduler; the next router rebuild or restart tries again. - Grants of a package. A package has no grants of its own. Before a
package scheduler can write a point, give it
writeon that point’s link:sys/links/<id>▸ Grant Access{path: wy/<site>/downstream/<link>, level: write}(ADR 0013). A running process link restarts to get the new grant; a WASM link gets it with the router rebuild. Without the grant,add_targetfails withpermission_denied(no message).
3. Make a schedule
In the explorer, open wy/<site>/downstream/scheduler.
- ▸ Add Schedule: Id
lobby, Defaultfalse, Time ZoneEurope/Kyiv(empty:default_tz). - Open
lobby▸ Add Event: Valuetrue, Start2026-11-02T08:00, End2026-11-02T17:00, RecurrenceFREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR. The result is the event’s id,e1. lobby▸ Add Target: Pointwy/<site>/downstream/modbus/line1/ahu1/fan, Confirmread_back. This needsconfig(section 10). The target writes the state now at once.lobby/currentshowstruefrom 08:00 to 17:00 on weekdays, elsefalse.lobby▸ Get Events with a Timerange shows the occurrences ahead.
The same through wyrm-client or wyr probe: invoke wy/<site>/downstream/scheduler add_schedule {id, default, tz}, and so on
(section 8).
4. Time
- Local times.
start,endandUNTILare local wall-clock times in the schedule’s zone:YYYY-MM-DDTHH:MMorYYYY-MM-DDTHH:MM:SS, no offset. Text with an offset orZis refused (invalid_parameter, field named). Only a DSA import converts instants with an offset. - Zones are IANA names (
Europe/Kyiv,America/New_York,UTC) from the time zone database bundled in the link: a WASM scheduler never reads the host’s zone. A native build may use the host’s newer database. - Occurrences are local. Each occurrence’s start and end are computed as local date-times, then mapped to instants with the zone’s rules:
| Case | What happens |
|---|---|
| A local time in the spring-forward gap (02:30 on the night 02:00 → 03:00) | It moves to the first instant after the gap (03:00). |
| A local time in the fall-back overlap (the hour that comes twice) | It takes the first (earlier) instant. |
| A window on a DST day | It keeps its wall-clock length: 08:00–17:00 stays 08:00–17:00 (8 or 10 hours of real time for a window across the change). |
| Day 29–31 in a month without it, Feb 29 in another year | That occurrence is skipped, never rolled into the next month. |
| A window across midnight, the hour or the week | Allowed; every occurrence is the same window. |
- Instants in the tree and in
get_eventsare RFC 3339 UTC (2026-11-02T06:00:00Z).
5. Recurrence (RRULE subset)
recurrence is RRULE text: parts NAME=VALUE joined by ;. Empty means
once. The rule walks periods of FREQ × INTERVAL from the event’s first
window (start, end).
| Part | Values |
|---|---|
FREQ | HOURLY, DAILY, WEEKLY, MONTHLY, YEARLY (required) |
INTERVAL | 1 to 1 000 (default 1) |
COUNT | 1 to 10 000 occurrences, or |
UNTIL | a local time: the last occurrence starts at or before it (not with COUNT) |
BYDAY | MO,TU,…,SU; with MONTHLY and YEARLY an ordinal in the month, 1 to 5 or -1 to -5: 1MO (first Monday), -1FR (last Friday) |
BYMONTHDAY | 1 to 31, or -1 (the last day of the month) |
BYMONTH | 1 to 12 |
How the BY… parts act:
| FREQ | BYDAY | BYMONTHDAY | BYMONTH |
|---|---|---|---|
HOURLY, DAILY | filter (no ordinals) | filter | filter |
WEEKLY | the days in each week (Monday first) | filter | filter |
MONTHLY | the days in each month | the days in each month; with BYDAY both must match | filter |
YEARLY | the days in each month of the year | the days in each month | the months (default: the start’s month) |
Examples:
| Recurrence | Occurs |
|---|---|
FREQ=DAILY | every day |
FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR | weekdays |
FREQ=WEEKLY;INTERVAL=2;BYDAY=SA | every second Saturday |
FREQ=HOURLY;INTERVAL=3 | every 3 hours from the start |
FREQ=MONTHLY;BYMONTHDAY=1,15,-1 | the 1st, the 15th and the last day of each month |
FREQ=MONTHLY;BYDAY=-1FR | the last Friday of each month |
FREQ=YEARLY;BYMONTH=12;BYMONTHDAY=25 | December 25 |
FREQ=DAILY;COUNT=10 | the next 10 days |
FREQ=DAILY;UNTIL=2026-12-31T23:59 | every day up to the end of 2026 |
FREQ=DAILY;BYMONTH=6,7,8 | every day in summer |
Checks: a window must not be longer than its period (the shortest gap
between two occurrences; WEEKLY;BYDAY=MO,TU gives one day), end must not
be before start, UNTIL not before start, a part only once.
6. Which value wins
At any instant:
- On a special day only special events count, for the whole local day.
- Among the active windows, the highest priority wins (1 > 2 > … > 9 > 0).
- On equal priority, the occurrence that started later wins.
- On an equal start, the lower event id wins (
e2beforee10). - No active window:
default.
The rules hold for any number of overlaps, also between occurrences of one event.
Moments follow the same rules: a moment writes its value only if no
window that would beat it is active at its instant. After it the schedule
keeps the moment’s value (source = its id) until its next transition, also
across a restart. A moment missed while the link was down is not written
later (section 11).
7. The tree
Paths under the link root (wy/<site>/downstream/scheduler):
| Path | Value | Attributes |
|---|---|---|
<s> | folder | display, tz, source (default or the event id), next_time (RFC 3339 or null), next_value |
<s>/current | the schedule’s value now (read-only) | |
<s>/default | writable value; saved | |
<s>/enabled | writable bool; saved | |
<s>/events/<e> | folder | display, value, start, end, recurrence, priority, special |
<s>/targets/<t> | the target’s state (text) | point, confirm, feedback, last_error, last_write, attempts, created_by |
next_timeandnext_valueare the next transition (an event start, an event end, a day under a special day, a moment), up to 366 days ahead; null when nothing changes in that time or the schedule is off. An enabled schedule with nothing in that time is evaluated again 365 days on, so an event further ahead still fires, with no edit or restart.enabledoff: the schedule shows its value but wakes and writes nothing. Turned on, it is a transition: every target is written.- Writing
defaultchanges the definition (saved at once); a different state now is a transition. - The tree publishes only on a change: at idle, between transitions, the link sends nothing.
8. Actions
Levels: read < write < config (section 10). Every action checks all
its fields before it saves anything; the change is on disk before the
action answers.
| Node | Action | Level | Params | Result |
|---|---|---|---|---|
| root | add_schedule | write | id (required), display, tz, default (required), enabled (default true) | — |
| root | import | config | json (required), id, overwrite | {id} |
<s> | add_event | write | value, start, end (required), display, recurrence, priority (default 0), special (default false) | {id} (e<n>) |
<s> | get_events | read | timerange (required), limit (1 000, at most 5 000) | rows {start, end, event, value, priority, special} |
<s> | export | read | — | {json} |
<s> | edit | write | display, tz, default | — |
<s> | remove | write | — (refused while it has targets: remove them first, at config) | — |
<s> | add_target | config | point, confirm (required), feedback, map, feedback_map, tolerance | {id} (t<n>) |
<s>/events/<e> | edit | write | the fields of add_event; absent or null keeps a field; an empty recurrence makes it once | — |
<s>/events/<e> | remove | write | — | — |
<s>/targets/<t> | edit | config | the fields of add_target; absent keeps a field | — |
<s>/targets/<t> | enable, disable, remove | config | — | — |
- Ids. A schedule id is 1 to 64 of
A-Z a-z 0-9 _ -. Event idse<n>and target idst<n>come from the link and are never used again in that schedule. get_eventstimerangeis<from>/<to>(or<from>..<to>) in RFC 3339; a date alone is its midnight UTC. The rows are every event’s occurrences that touch the range, by start, precedence not applied (a timeline). A moment exactly atfromis in.confirmis an enum: an action takes the index of the choice (0read_back, 1feedback, 2ack; the explorer sends it); an import JSON takes the text.mapandfeedback_mapare JSON object text (or a map).- Edits that change the state now (an event added, edited or removed, a
new
defaultortz) are a transition. An edit that leaves the state as it was writes nothing.
Errors (the status, then <field>: <rule>):
| Status | When |
|---|---|
invalid_parameter | A field is missing or wrong: end: end is before start, recurrence: COUNT: must be 1 to 10000, tz: unknown IANA time zone "Kyiv", id: lobby exists, point: … is written by lobby/t1, default: a number must be finite (no NaN or infinity) (also an event value, map, feedback_map). A schedule remove while it has targets: lobby has 1 targets: remove its targets first. |
resource_exhausted | A cap (section 13), named: lobby: at most 100 events per schedule, at most 9500 nodes in the scheduler (9496 used). Also a full store. Nothing is saved or declared. |
not_found | No such schedule, event or target. |
busy | import, add_target, a target’s edit, and enable of a disabled target, while the link still loads its schedules after a start (N schedules are still loading): they check one writer per point against every schedule. Try again. |
not_supported | No such action on that node. |
permission_denied | The caller’s level is too low, or a package scheduler has no grant on the target’s link. No message (spec 04). |
9. Targets
A target is {point, confirm, feedback?, map?, feedback_map?, tolerance?}:
the point is wy/<site>/downstream/<link>/<path> on this site (no *, ~
or empty segment; never sys/** or another site).
On each transition (and when a target is added, edited or enabled) the link
writes the schedule value to the point with ~set, mapped by map when it
has an entry. Then it confirms the write:
| Confirm | Confirmed when |
|---|---|
read_back | the point’s value equals what was written |
feedback | the feedback point’s value equals the expected value (feedback_map[value], else the written value). For devices whose write register is not the one read back: a Modbus coil written, a status register read. |
ack | the target link answers ok |
- Equal means: numbers within
tolerance(default 1e-6, relative; absolute when the expected value is 0);true/falseand 1/0 are equal; other values exactly. - A value with quality
uncertainorbad(a device offline) confirms nothing, and the link forgets the key’s last value: a laterokdoes not confirm on a value from before it. mapkeys are the schedule value as text:true,false, a number in its shortest form (1,0.5), text as it is. Example:{"true": 1, "false": 0}writes 1 fortrue. A value without an entry is written as it is.- A matching value counts while the write waits for its reply or after the
ok. Links publish a value only when it changes, so a point that already shows the value confirms on theok. No matching value 10 s after theok: the write failed. - Retries. A failed or refused write is tried again after 1 s, then 2 s, 4 s … up to 60 s, each ±20 %. It never gives up within a transition; the next transition replaces it.
- Override. After a target is confirmed, a different value on its
confirm point marks it
override: a person changed the device by hand and wins. The link does not write it again until the next transition. Inackmode nothing reads the point back, so no override is seen. - One writer per point. A point is the target of one schedule of this
link only (
point: … is written by <s>/<t>). A flow that writes the same point is not detected: do not do that. - The write queue. At most 50 writes wait for a reply at a time; the others wait in order. A burst (1 000 schedules at 08:00) is written in full, 50 at a time.
- Subscriptions. A target holds a subscription on its confirm key while
it is enabled, not
overrideand notack. Targets that confirm on the same key share one.
The target node’s value is its state:
| State | Meaning |
|---|---|
pending | waiting to write (in the queue, or waiting for a first sample at start) |
writing | written, waiting for the reply and the confirmation |
confirmed | the point shows the value |
retrying | the write failed; last_error says why, attempts counts |
override | changed by hand after it was confirmed |
disabled | the target is off |
Audit. Every write is a ~set and the target link audits it as any
other: sys/audit/<target link> with the subject link:<scheduler id>
(link:scheduler for the embedded one). Confirmations and overrides go to
the link log at info (ids and states only, never values) and to the
target node.
10. Who may do what
| Level on the scheduler | Allows |
|---|---|
read | see the tree, get_events, export |
write | schedules and events: add_schedule, add_event, edit, remove (a schedule without targets), default, enabled |
config | targets and import: add_target, a target’s edit/enable/disable/remove, import |
Targets are configuration, within the author’s rights. Adding,
editing and importing targets needs config on the scheduler. A target
also writes only what its author may write (ADR 0029, decision 10):
- The scheduler keeps the caller’s own rights (the token’s
auth, spec 04) with each target it adds, edits or imports. - It refuses a target whose point the caller may not write, or whose
feedbackkey the caller may not read (permission_denied, “outside the rights of the target’s author”). - It checks the point again before every write.
- A token without
auth(an old client, a flow) cannot define targets. - The editor of a target becomes its author:
created_byand the rights are the editor’s from then on. - The export leaves the rights out. An import takes the importer’s.
- The rights are read as at the gateway: the first grant of the role list whose key pattern matches decides (spec 04). Put a narrow grant before a wider one (ADR 0031).
УВАГА: a target made before this rule has no stored rights. It writes
nothing and stays retrying with “its author’s rights are unknown” until
someone with config edits it once (an edit with no fields is enough).
With the gateway’s default roles:
| Role | Can |
|---|---|
viewer | read |
operator | make and edit schedules and events, turn them on and off; not add targets |
engineer, admin | all, targets and import too |
- The
agentlink is capped atwrite: it edits schedules and events, it cannot add targets. - Users of an upstream site (ADR 0018) write at
writeon this site: schedules and events, not targets. - A target keeps
created_by(the subject that added or last edited it) and that subject’s rights at that time. A schedule keeps writing after its author loses rights later (as flows do). - The link’s own writes. The embedded scheduler signs its writes with
its own key (a link secret made by the admin). Links trust that key at
write, only underwy/<site>/downstream, only with the subjectlink:scheduler. A package scheduler signs with its requester key, up to its grants (section 2). - Not itself. The embedded scheduler does not trust its own key, so a
schedule cannot write the scheduler’s own nodes (
<s>/default,<s>/enabled) in a loop. The app does not know its own link id, soadd_targetaccepts such a point; its writes fail withpermission_deniedand the target staysretrying. Do not do that. - Removing a schedule.
removeis atwrite, its targets are atconfig: a schedule with targets is refused until someone withconfigremoves them.
11. Clock steps and restarts
The link computes the state from the definition alone; it never replays what it missed.
- One timer for all schedules: the earliest next transition. The timer is monotonic.
- Clock watchdog. The timer fires at least every 30 s. When the wall clock and the monotonic time differ by more than 2 s (an NTP step either way, a host resumed from sleep), the link evaluates every schedule at “now”. A schedule whose state is the same is not written. A step back inside a window writes nothing, and the window’s end still fires.
- Late work. A burst is done in batches of at most 800 commands per event. Work that goes on more than 30 s late counts as a clock step: the link goes to the state now, and moments inside that lag are not written.
- Restart. The link loads every schedule and evaluates it at “now”. For each target:
| Stored record for the target | At start |
|---|---|
confirmed or override for this same state (value and occurrence), and no transition since (valid_until) | left as it was: no write; a manual change survives a restart inside the same window |
none, for another state, or past its valid_until; ack | written |
none, for another state, or past its valid_until; read_back/feedback | waits 2 s for a first value of its confirm key: a value that already shows the expected one confirms without a write, else it is written |
valid_until. A record keeps the instant of the next transition after its state (365 days on when there is none). A record past it is stale: the link was down across a transition and back, and an override from before does not pass for the state now. An edit that moves the next transition puts the records again. Records of an older version have novalid_untiland are stale once, at the first start after the upgrade.- Held moments. A moment that fired and is still the schedule’s state is
kept across a restart (store key
h/<s>, deleted when the next transition replaces it): the schedule shows it, and its targets follow the rules above. A moment missed while the link was down is still not written. - Records are kept only for
confirmedandoverride; a target edit, disable or remove drops its record.
12. Import and export
export gives the schedule with its targets as JSON, format
wyrm-schedule/1:
{
"format": "wyrm-schedule/1", "id": "lobby", "display": "Lobby", "tz": "Europe/Kyiv",
"default": false, "enabled": true, "next_event": 2,
"events": [{ "id": "e1", "display": "", "value": true, "priority": 0, "special": false,
"start": "2026-11-02T08:00", "end": "2026-11-02T17:00",
"recurrence": "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR" }],
"targets": [{ "id": "t1", "point": "wy/edge/downstream/modbus/line1/ahu1/fan",
"confirm": "read_back", "enabled": true, "created_by": "user:admin" }],
"next_target": 2
}
import {json, id?, overwrite?} (level config) takes this format or a
DSA dslink-dart-localschedule (2.0.4) export:
idnames the new schedule; default: the export’sid(DSA: itsname, when that is a valid id, elseidis required).- A schedule with that id exists: refused, unless
overwrite: truereplaces it as a whole (its old targets and records go). - Own format: every target is checked as by
add_target(one writer per point, the caps, the grants);created_bybecomes the importer. - Export and import round-trip: an import of an export gives the same rows
in
get_events. Removetargetsto copy a schedule (each point has one writer).
DSA mapping:
| DSA | WYRM |
|---|---|
name | display (and the id when id is not given) |
value | default |
| — | tz = the link’s default_tz; enabled = true |
events[] | events e1, e2, … in file order |
events[].name, value, priority, special | display, value, priority, special |
timeRange.sDate + sTime | start (the date of sDate, the time of sTime) |
timeRange.eTime − sTime | the window length: end = start + it; equal times = a moment |
timeRange.freq 0 | once |
timeRange.freq 1–5 | FREQ=HOURLY, DAILY, WEEKLY, MONTHLY, YEARLY, INTERVAL=1, UNTIL = the date of eDate with the time of sTime |
times with Z or an offset | converted to the zone; times without one are local |
DSA has no targets: add them after the import.
13. Limits
| What | Limit |
|---|---|
| Events per schedule | 100 |
| Targets per schedule | 20 |
| Nodes of the link | 9 500 (6 per schedule, 1 per event, 1 per target): 1 000 schedules with 2 events and 1 target each fit |
| Subscriptions | 1 000 (one per confirm key) |
| Writes waiting for a reply | 50; the rest wait in the queue |
COUNT | 10 000 |
INTERVAL | 1 to 1 000 |
| Next transition | 366 days ahead; with none, evaluated again 365 days on |
get_events | 5 000 rows (1 000 without limit) |
| Store | embedded 64 MiB (scheduler.store_mb), packages 16 MiB; each schedule, held moment and target record takes at least 4 KiB. Keys at most 1 + 2 × schedules + targets (8 031 within the node budget), below the host’s 10 000 |
| Requests | 50 per second per caller (burst 100), as every link |
14. Measurements
Apple M4 Max, release builds.
cargo bench -p wyrm-schedule --bench eval (the evaluator, per call):
| Schedules × events | state_at p50 | next_transition p50 |
|---|---|---|
| any × 1 | 0.21 µs | 0.62–0.67 µs |
| any × 10 | 5.5 µs | 11.6 µs |
| any × 100 | 53.7 µs | 113 µs |
- The evaluator’s cold start (
Compiled::new+state_at), 1 000 schedules × 10 events: p50 8.96 ms. occurrencesover a year, 10 events (7 198 rows): p50 0.83 ms.- The worst
COUNTcompile (100 events whose rule never matches, 400 years each): 17–84 ms.
cargo bench -p wyrm-link-scheduler --bench cold_start (the link on
SimHost, 1 000 schedules × 2 events × 1 target, 10 rounds, p50 / max, from
the start of Scheduler::start):
| Confirm | start event | tree complete | last write sent | all confirmed |
|---|---|---|---|---|
ack | 1.71 / 1.94 ms | 26.22 / 29.96 ms | 40.34 / 45.50 ms | 40.85 / 46.03 ms |
read_back | 1.67 / 1.76 ms | 25.84 / 26.53 ms | 44.27 / 45.02 ms | 44.92 / 45.74 ms |
With read_back or feedback, a real host adds the 2 000 ms first-sample
wait before the writes.
On the demo (examples/demo/scheduler-load.sh; Apple M4 Max, demo edge
site, embedded scheduler, release build, 2026-10-29):
| Measurement | Result |
|---|---|
| Samples in 60 s at idle, 1 000 schedules | 0 (target 0); 3 000 stored values at subscribe |
| Making and removing the 1 000 schedules | 47.1 s and 42.8 s (50 requests per second per caller) |
Transition latency, 100 moments, current | p50 16.0 ms, p99 23.7 ms, max 26.7 ms (target < 50 ms) |
Transition latency, the written mock point (ack target) | p50 16.9 ms, p99 24.8 ms, max 27.6 ms |
feedback target on modbus/line1/ahu1/fan with fan_status | confirmed after 390 ms; a write of false by hand: override after 973 ms; the next transition wrote true again: confirmed |
WASM package, 200 schedules × 10 events × 1 target: start answered in
0.29 s, all 200 back in the tree in 1.7 s (e2e scheduler_three_modes).
15. Known limits
- An audit record put while the target link reconnects (a router rebuild) can be lost: records are sent once.
rustlsis pinned to 0.23.45:zenoh-link-tls1.10.1 races its reader and writer on newer versions.- A forward clock step under 30 s while a long burst still runs replays the transitions of that span (moments too) instead of skipping them.
- An event
editcannot set the value to null (null keeps the old value). - A definition the link cannot read from its store stays in the index and
cannot be removed with
remove. - A target’s
feedbackkey may be another target’s point; only the written points are checked for one writer. permission_deniedhas no message: a missing grant shows only the status.
16. Try it in the demo
- Run
examples/demo/run.sh. Every site (central, edge, plant) has its embedded scheduler. - Log in to the edge gateway (
http://127.0.0.1:8444, useradmin) and openwy/edge/downstream/scheduler. Make a schedule as in section 3 with the targetmodbus/line1/ahu1/fan, Confirmfeedback, Feedback Pointwy/edge/downstream/modbus/line1/ahu1/fan_status. - Write
falsetofanby hand: the target turnsoverride. wyr probe --gateway http://127.0.0.1:8444 --site edge schedulerruns the built-in scenario (links/probe/scenarios/scheduler.json).examples/demo/scheduler-load.shruns the measurements of section 14 on edge and removes what it made (N=3 MOMENTS=5 IDLE_S=5for a short run).
DQL — queries over the tree
DQL (“distributed query language”, after DSA’s dslink-dart-dql) finds nodes, reads their
values and meta, computes columns and can write the result back to points. A query is a
pipeline:
list wy/plant/downstream/plc1/** | where type == "number" && attr.unit == "°C"
| subscribe value :name | expression f="value * 1.8 + 32.0"
Its result is a table: one row per node (the row id is the node key), one column per
subscribe, expression or meta field. Design: ADR 0025.
Where it runs
| Mode | What | Rights |
|---|---|---|
| Embedded (default) | wy/<site>/downstream/dql in every wyrmd | reads this site’s downstream, dataflows, storage, upstream and the readable sections of downstream sites; sinks write only this site’s downstream |
WASM package dql | the same link, installed from a repository or zip | what an operator grants (sys/links/<id>/~act/grant): read on each root, write on each sink target |
Process package dql-process | the same link as a process | as the WASM package |
wyr query "<text>" | the same engine in the terminal, nothing stored | your own token |
wyrmd.json5: dql: { enabled: true, store_mb: 16 } (both optional). The id dql is reserved.
The link’s tree
dql/
add_query {id, text, display?, enabled?, publish_ms?, publish?} write; set/invoke or publish need config
run {text, id?, ttl_s?, publish?} -> {id, table?} ad-hoc, not stored
explain {text} -> {stages, columns, roots, sinks, errors}
import {json, id?, overwrite?} config
convert_dsa {text, site} -> {text}
stats/queries, rows, lists, subscriptions, sink_calls
<query>/ attrs: text, status, error, rows, columns, errors, sink_calls,
lists, lists_pending, depth, sites, collect_ms, last_publish,
created_by, expires (ad-hoc)
table the rows: an array of maps, in key order (only with publish)
enabled writable
get_table {from?, limit?} -> {rows, total, columns, status}
edit {display?, text?, publish_ms?, publish?}, export -> {json}, remove
- Stored queries (
add_query,import) live in the link’s store and come back after a restart; their table is rebuilt from the live tree (nothing of the old result is kept). - Ad-hoc queries (
run) end afterttl_s(300 s, at most 3 600) unlessget_tableorrunwith the same text renews them. The same text shares one query. Withida dataflow can subscribe a fixed key:…/dql/<id>/table(withpublish). - The table is read with
get_table, which gives each caller the rows it may read itself. Withpublish: true(needsconfig) it is also the live value<id>/table, published at most everypublish_ms(500 ms; 100 … 60 000) and only when it changed: a quiet tree sends nothing. Whoever may read that node sees the whole table.
Collection takes time
Each level a pattern reaches is one list round trip; another site adds a peer hop. A query
shows:
status:collectinguntil every list it opened answered once, thenready(disabled,errorwhen its text no longer parses);lists,lists_pending,depth(deepest level reached),sites,collect_ms(start toready);error: why the table may be incomplete —max_rows,max_lists, a refused list, orincomplete: N lists pending after T s(option timeout_s, default 30 s).
Prefer the narrowest fixed prefix: wy/plant/downstream/plc1/**, not wy/plant/**. A pattern
with ** near the top of a big site lists every folder below it.
Commands
| Command | Meaning |
|---|---|
list <pattern>[, <pattern>…] | Rows for nodes under the patterns. Keys are full (wy/<site>/<section>/…); * is one segment, ** any number. A pattern without a wildcard lists that node’s children. Folders are listed, values are not (they have no children). |
list sites wy/<site> | Broker nodes the site sees: upstream/* and downstream/* with attr.root (DSA brokers). |
path <key> | One row: that node. |
sublist <pattern> | Below each row: ./*, ./**, ./a/*. Its rows replace the parent’s; a parent that goes takes its rows with it. |
where <CEL> | Keeps rows for which the predicate is true. |
filter <DSA tests> | DSA’s syntax, turned into CEL: $type="number" @unit!="%" :name like 'Temp%' value >= 20. Tests side by side all hold. |
subscribe [<key> [as <col>]]… | Columns: value (default), value.timestamp (µs), value.quality, a child (./setpoint, setpoint.timestamp), $type, $unit, $writable, $is, $display, @<attr>, :name, :display, :path, :actions. |
expression <col>="<CEL>"… | Computed columns. |
rename <a> as <b> · drop <cols> | As DSA. |
option k=v … | throttle_ms, max_rows (1 000; at most 5 000), timeout_s (30; at most 600), invoke_allow_null. DSA’s qos, traverseBrokers, listActions are accepted and ignored. |
set <node> = <CEL or %col> | Writes the value to a point (~set) for each row. <node> is a full key or relative to the row (., .., ./x). |
invoke <node>/~act/<action>(<p>=<CEL or %col>, …) | Calls an action for each row; invoke ack(…) calls ack on the row itself. |
A name a where, expression or sink uses that no stage made is subscribed first: value is
the row’s value, any other name a child’s (as DSA’s filter did).
Expressions: CEL
Predicates and expressions are CEL (Common Expression
Language, the standard used by Kubernetes, Envoy and Firebase), evaluated by the cel crate.
Variables of a row:
- its columns, by name (
value,f), and all of them as the maprow(row["value.timestamp"]); - its meta:
path,name,type,unit,writable,is,display,quality,attr(map),actions(list of names), and all of it asmeta.
Examples: type == "number" && value > 20.0, name.matches("^ahu[0-9]+$"),
"unit" in attr && attr.unit == "%", string(value) + " " + unit, [1, 2].exists(x, x > value).
An expression that fails on a row (a type error, a missing key) gives null in that column;
it counts in errors only when what it reads is there (value + 1 before the first sample is
not an error). A where that fails drops the row.
Reading attr, actions or meta makes the query fetch each listed node’s whole ~meta
(one more request per node): use it on narrow patterns.
Rights: a query runs with its author’s
A query reads and writes only what the user who defined it may (ADR 0025 item 4): the action’s
token carries the caller’s grants (auth, spec 04), and the link keeps them with the query.
- A node the author may not
readis no row; a value they may notreadis not taken. - A
setorinvokewhose target the author may notwriteis refused when it would fire: it counts inerrorsanderrornames the key. - An
editof the text, animportor aruntakes the caller’s rights. - A caller whose token has no
auth(a dataflow, an older client) cannot define a query. - The rights are read as everywhere else: the first grant of the role list whose key pattern
matches the key decides (spec 04). A narrow
writegrant listed after a widerreadgrant givesreadonly, at the gateway, at the target link and in a query alike (ADR 0031). get_tablegives each caller the rows it may read itself: the row’s node and every node its columns read (./x,..). Changing the text of a published query needsconfig. A published table (publish: true,config) is one value for whoever may read<id>/table: publish only what those readers may see.
Sinks: set and invoke
- A query with a sink needs
configon the DQL link (the gateway’sengineer,admin);write(operator, the agent, dataflows) may define queries without sinks only. The same holds for changing a sink query: switching it on,edit,runwith its id and another text,remove;writemay switch it off (stop its writes). - Nothing fires on start: the first complete arguments of a row (after a start, a restart,
an edit,
enabledon, or when the row appears) are its baseline. A call goes out only when they change. A row whose arguments holdnullsends nothing (unlessinvoke_allow_null). - One call in flight per row and sink; changes meanwhile wait and the newest goes next.
throttle_msspaces a row’s calls. At most 50 calls in flight for the link. - A failed call counts in
errorsand is logged atinfo(ids only, never values); it is not retried (an action is not idempotent). - The embedded link does not trust its own key: a query cannot write the DQL link’s own nodes.
Bounds
200 queries; 1 000 rows per query by default (5 000 at most); 1 000 lists per query (the host allows 2 000 per link); 1 000 subscriptions per link; 20 000 cached samples per query; 16 stages and 4 KiB per query text, 1 KiB per expression. Every event of the link spends at most 700 commands; the rest goes on in the next events.
An expression’s cost per row is bounded before it runs, on the parsed expression (CEL cannot be stopped halfway):
- no macro (
map,filter,all,exists,exists_one) inside another macro’s body: chain them instead (list.filter(x, …).map(x, …)), at most 4 in one expression; - no
+and no list or map literal inside a macro’s body, so each step of a chain gives at most what it was given; - no
+in a macro’s range ((l + m).map(…)): a range is a value, a literal or a chained macro, so one expression runs at most 4 × 1 000 steps; - a list literal holds at most 64 items;
matches()takes its pattern as literal text (name.matches('^ahu[0-9]+$'), notname.matches(unit)), and the pattern compiles to at most 16 KiB: CEL compiles it again on every call (security review);- a value of more than 1 000 items (all levels; text, bytes and map keys count one item per 16
bytes) is
nullin an expression, and a result that large is an error.
What only the run can see (a row variable read on every item of a long range) is bounded while
it runs: one evaluation reads row variables at most 10 000 times and, in a native link, takes
at most 20 ms; past either it stops with the error too costly, and the row counts an error.
One event (a value that came, a tick) runs at most 2 000 evaluations of a query, and in a native link at most 100 ms of them. A value that many rows read (a column with a full key) evaluates the rows that fit; the others wait and are evaluated in the next ticks, which come at once. The table is right after those ticks; other queries run in between (security review).
From DSA
convert_dsa {text, site} (or wyrm_dql::dsa::convert) rewrites a DSA text for one site:
| DSA | WYRM |
|---|---|
list /downstream/System/* | list wy/<site>/downstream/System/** |
? | * |
list * | list wy/<site>/downstream/** |
list brokers | list sites wy/<site> |
sublist /downstream/? | sublist ./downstream/* |
invoke /downstream/Mongo/x/publish(…) | invoke wy/<site>/downstream/Mongo/x/~act/publish(…) |
filter … | kept (turned into CEL) |
expression d="row.value * 2" | kept; it is CEL now (Math.min and other JavaScript are not) |
Differences: like is SQL’s (% is any text, the whole value must match; DSA matched
anywhere); DSA’s >= was always true (a bug) and is a comparison here; a sublist parent that
goes takes its rows with it (DSA left them).
In the terminal
wyr query "list wy/s/downstream/mock/** | where type == 'number' | subscribe"
wyr query --once --json "list sites wy/central"
--every-ms paces the printout; sinks are printed, not sent, unless --sinks.
Alarms
The alarm link watches points of the tree and raises alarm records: a value out of range, a boolean that says “fault”, a device that stopped sending, a sample of bad quality. A dataflow, the agent or a person can raise one too. People acknowledge records, add notes and look back over a time range. The records live in the broker’s own store and go to a central database through the history sync links (MySQL, MongoDB, PostgreSQL, InfluxDB, DynamoDB) with no new protocol. Design: ADR 0034 (the link), ADR 0023 (portable links), ADR 0026 (the sinks).
Code: links/alarm (wyrm-link-alarm, the link as a portable App).
1. Words
| Word | Meaning |
|---|---|
| Class | A group of watches and their records (line1, comms, safety), with its escalation times. |
| Watch | A source point (or a subtree) and an algorithm that says when it is in alarm. |
| Record | One alarm: the source, the class, the type, a message, when it was raised, when it went back to normal, when and by whom it was acknowledged, its notes. |
| Active | The record’s condition still holds (no normal yet). |
| Open | Active, or not yet acknowledged. Closed: normal and acknowledged. |
| Type | alert, warning or fault (as DSA). |
| Inhibit | to_alarm_s: the condition must hold this long before a record is made; to_normal_s: it must be gone this long before the record is normal. |
| Escalation | A record nobody acknowledged within escalation1_s is at level 1, within escalation2_s at level 2. |
| Sink | A reader of the records for a central database: a history sync link that pulls batches with next. |
2. Where it runs
One source runs in three modes (ADR 0023). They behave the same.
| Mode | Where | How you get it |
|---|---|---|
| Embedded (the default) | wy/<site>/downstream/alarm | Every wyrmd runs it. wyrmd.json5 alarm: { enabled: true, store_mb: 64, retention_days: 365, max_records: 100000 } (all optional). |
| WASM package | wy/<site>/downstream/<id> | Package alarm (a component), Install Link ▸ from Repository / Zip / Url. Store 16 MiB. |
| Process package | wy/<site>/downstream/<id> | Package alarm-process, the same app as a supervised process. Store 16 MiB. |
examples/packages/build.sh builds both packages.
- The id
alarmbelongs to the embedded instance (asscheduleranddql): a new link cannot take it, andwyrmdrefuses to start with a stored link of that id. - The embedded link reads this site’s
downstream,dataflowsandstorage. It writes nothing, so no link needs to trust its key. - Grants of a package. A package has no grants of its own. Before a package can watch a
point, give it
readon that point’s link:sys/links/<id>▸ Grant Access{path: wy/{site}/downstream/<link>, level: read}({site}as it is: the broker puts in its own site). A watch added before the grant showserror: permission_denied; Disable and Enable it once the grant is there. - Params of a package:
retention_days(365, at most 3 650) andmax_records(100 000, at most 1 000 000), beside the capabilities, with the link’supdate.
3. The tree
alarm/
add_class {id, display?, escalation1_s?, escalation2_s?} write
raise {class, source, type?, message?} -> {id} write a record no watch owns
acknowledge {id, note?} normal {id} add_note {id, note} write
ack_all {class?} -> {acknowledged} write
get_alarm {id} -> the record; get_notes {id} -> rows read
get_alarms {timerange?, class?, source?, state?, type?, limit?} read -> {rows, complete, scanned_to}
import {json, overwrite?} purge {before} config
add_sink {name, link, classes?, from?} config
stats/open, active, unacked, records, watches, raised, dropped
sinks/<s> value: the confirmed journal entry; attrs link, classes, lag_entries,
rows_sent, dropped_unsent, last_request; next (read), edit, reset, remove (config)
<class>/ attrs display, escalation1_s, escalation2_s, created_by
add_watch (config); edit, remove, ack_all (write); export (read)
open, active, unacked counts
alarms the open records, newest first, at most 200 rows
watches/<w> value: normal | alarm | to_alarm | to_normal | disabled | error
attrs source, algorithm, params, type, message, to_alarm_s, to_normal_s,
keys, in_alarm, last_change, last_record, error, created_by
edit, enable, disable, remove (config)
A record’s state in answers: active (not normal, not acknowledged), acked
(acknowledged, still active), normal (normal, not acknowledged), closed.
4. Watches
add_watch {source, algorithm, …} on a class:
algorithm | In alarm while … | Parameters |
|---|---|---|
boolean | the value equals alarm_value (default true). A number counts as true when it is not 0; the texts true/false, on/off too. | alarm_value |
out_of_range | the value is below min or above max (either may be absent). Back to normal only deadband inside the limit (hysteresis). A value that is not a number says nothing. | min, max, deadband |
staleness | no sample came for stale_s seconds. The next sample ends it. | stale_s |
quality | the sample’s quality is bad; with include_uncertain also uncertain. | include_uncertain |
Through an action an enum is given by its index, as everywhere in WYRM (algorithm: 0
boolean, 1 out_of_range, 2 staleness, 3 quality; type: 0 alert, 1 warning, 2
fault; get_alarms state: 0 open, 1 active, 2 unacked, 3 closed, 4 all; a sink’s
from: 0 start, 1 now); in an import, by its name.
Arguments: each action declares its parameters once (a struct, src/actions.rs), and
the same declaration reads them. The SDK checks the arguments against ~meta before the
link sees them: a name the action does not declare (unknown param x), a required
argument that is absent (missing id), a value of another type (min: expected number,
algorithm: expected enum index). The link itself refuses a number that is no whole
number from 0 (limit: expected a whole number (a negative number)) and a record id
that is none (id: required for null, id: a record id); these are
invalid_parameter. A record’s id is a number or its decimal text.
An edit keeps what it does not give. A null is no value of a typed argument (the SDK
refuses it), so an edit cannot take a limit of out_of_range away (min or max back
to none): remove the watch and add it again.
Common fields: type (alert, warning, fault), message (a template:
{name} is the key’s last segment, {source}, {value}, {quality}, {class}, {watch},
{stale_s}; default {name}: {value}), to_alarm_s, to_normal_s, enabled.
- Source: a point key
wy/<site>/downstream/<link>/<path>(also underdataflowsorstorage), or a subtreewy/<site>/downstream/<link>/**: one subscription, one state per key, one record per key (at most 2 000 keys; beyond, the watch showserror).keysandin_alarmcount them. - One record per key at a time: while a key’s record is active, the same condition makes no second one; after it is normal, the next alarm is a new record.
- Inhibits are measured on the broker’s clock from the sample’s arrival. A flip of the
condition before the time is up cancels the wait. They do not apply to
staleness. - Who may add a watch:
add_watchisconfig(it subscribes a point), and the watch keeps its author’s rights (ADR 0029): a token withoutauth(a dataflow’s) cannot add one; a source the author may notreadis refused; a subtree watch drops the keys its author may not read. The watch keeps running after its author loses rights. A watch edited with a newsourcetakes the editor’s rights. - Disable, remove, a new source: the watch’s active records go back to normal (nobody watches them any more).
- No sample: a key that has no sample is never taken as
good. Before its first sample aboolean,out_of_rangeorqualitywatch judges nothing and makes no record (there is no value and no quality to judge). Astalenesswatch on a point counts from the start, and its record, before the first sample as after a later silence, has valuenulland qualitybad({value}=null,{quality}=bad): it says that nothing fresh is known of the key, so it never reports the quality of the last sample. A record made when a wait ends takes the key’s last sample; without one it isnull/badtoo. The watch’s own value (watches/<w>) is the state of the watch, not of its source:normalmeans “no record and no wait”, so a watch whose key has sent nothing yet isnormal. A key that may go silent needs astalenesswatch.
5. Records
raise {class, source, type?, message?}makes a record no watch owns: a dataflow’sinvokesink, the agent or a person says there is a problem withsource(a key of this site).normal {id}ends it; a watch’s record ends by its point.raiseneedswriteon the link and noauth.acknowledge {id, note?}names the caller (ack_by) and the time;add_note {id, note}(≤ 20 notes of ≤ 1 KiB per record, also on a closed one);ack_all {class?}acknowledges every open record the caller may see.- Who sees what:
get_alarms,get_alarm,get_notes,acknowledge,normal,add_noteandack_allneed the caller’sauth(the gateway,wyrand the agent give it) and answer only records whosesourcethe caller mayread. A class’salarmstable and the counts are for whoever may read those nodes: a role withreadon the alarm link reads the site’s alarms. get_alarms:stateisopen(default),active,unacked,closedorall;timerange<from>/<to>(RFC 3339, on the creation time);class;source(a key, or a prefix ending with/);type;limit(500, ≤ 5 000). Rows come newest first. The open records are in memory;closedandallread the store, at most 256 pages (16 384 records) per call:complete: falseandscanned_to(the oldest creation time read) say where to go on with a narrowertimerange.- Escalation: a record nobody acknowledged within the class’s
escalation1_sgoes to level 1 (escalation), withinescalation2_sto level 2; each is a change the sinks see. - Bounds: 10 000 open records; over it the oldest record that is normal but
unacknowledged is acknowledged by
system:overflow(a storm cannot grow without end). With none such (all active) the record is still made. 200 classes, 500 watches per class, 1 000 in all.
6. The store, retention and restarts
Records live in pages of 64 in the link’s sealed store (p/<n>), the open ones also in
memory; every creation and change is one entry of a journal (j/<n>, at most 102 400
entries) that sinks read. A record is on disk before the action that made it answers; a
record made from a sample is logged at error and counted in stats/dropped when the store
refuses it.
- Retention: once a day (and at start) the oldest pages whose records are all closed go
while they are older than
retention_daysor the store holds more thanmax_records. A page with an open record stays: an open alarm is never deleted.purge {before}(config) removes the closed records created before an instant, page by page. - Restart: the classes and watches come back, the open records too. A watch’s key whose
record is active starts as “record open”: the first normal sample closes it, the same alarm
makes no second record. A
stalenesswatch counts from the start. Escalations due are still due. - Clock steps: inhibits, staleness and escalations are durations; a wall-clock step (NTP, a resume from sleep) moves them with it. A step seen by a timer is exact; one seen by another event first is measured against the link’s last event, so a wait may end late by that much (at most the 30 s watchdog).
7. Sinks: records in a central database
The records go out through the history sync links (ADR 0026), exactly as the historian’s
rows do. On the alarm link: add_sink {name, link, classes?, from} — the link id that reads it,
the classes it takes (empty: all), and whether it starts from the oldest journal entry kept
(start) or from now. Then on the sync link (installed from its package: postgres, mysql,
mongodb, influxdb, dynamodb, or their -process forms) set the param
sink: wy/<site>/downstream/alarm/sinks/<name> beside its own params, and give it
read on the sink’s key: sys/links/<db link> ▸ Grant Access
{path: wy/{site}/downstream/alarm/sinks/<name>, level: read} ({site} as it is). With read
the router lets the link call next there (and no other action), as a process package
too. Use a table, measurement or
collection of its own for alarms.
Each row the database gets is one record: key = the record’s source point, t = when it was
raised, v = the record as JSON text (wyrm-alarm/1: id, class, watch, source,
type, message, value, created, normal, ack, ack_by, escalation, notes,
by, state), q = good. Every change (normal, acknowledged, a note, an escalation) sends the
record again with the same (key, t), so the database holds its last state (PostgreSQL and
MySQL replace on their primary key, MongoDB on _id, DynamoDB on its keys, InfluxDB on the same
series and time). In PostgreSQL value_text::jsonb queries the fields.
Only the sink’s link may call next (it signs as link:<id>); anyone else is refused, since
next confirms the previous batch. The sink node shows lag_entries (changes not yet
confirmed), rows_sent and dropped_unsent (journal entries that went before the link
confirmed them: the journal keeps the last 102 400 changes). reset {from} moves the cursor.
8. Example: a PLC’s faults, to PostgreSQL
alarm ▸ Add Class {id: line1, escalation1_s: 600, escalation2_s: 3600}
alarm/line1 ▸ Add Watch {source: wy/plant/downstream/plc1/line1/ahu1/fault,
algorithm: boolean, type: fault, message: "AHU1 fault"}
alarm/line1 ▸ Add Watch {source: wy/plant/downstream/plc1/line1/ahu1/temp,
algorithm: out_of_range, max: 28, deadband: 1,
to_alarm_s: 60, type: warning, message: "{name} at {value} °C"}
alarm/line1 ▸ Add Watch {source: wy/plant/downstream/plc1/**, algorithm: quality,
to_alarm_s: 30, message: "{source}: {quality}"}
alarm ▸ Add Sink {name: cloud, link: pg, from: start}
sys/links/pg ▸ Grant Access {path: wy/{site}/downstream/alarm/sinks/cloud, level: read}
(on pg: params sink = wy/plant/downstream/alarm/sinks/cloud, table = alarms)
The explorer shows line1/alarms as a table; get_alarms {state: closed, timerange: …} looks
back. With wyrm-agent (ADR 0033): invoke wy/plant/downstream/alarm get_alarms '{"class":"line1"}'.
9. What differs from the DSA alarm link
Kept: classes, watches with Boolean, Out Of Range and Staleness algorithms (and quality,
new), the three types, the record’s life and notes, escalations, Get Alarms over a range,
acknowledge all, a database behind. Changed: the records are in the broker’s sealed store,
not in a database inside the link; the central database is fed through the sync links the
site already uses, not by swapping the record store; nothing polls (a change is one journal
entry, a quiet site sends nothing); every bound is explicit; whoever acknowledges or reads
must be able to read the source point, and a watch reads with its author’s rights.
Uplink: platform upstreams
The uplink sends a site’s live values to the platforms the rest of the plant uses: an MQTT
broker as a Unified Namespace (HiveMQ, EMQX, Mosquitto, …), a Sparkplug B host (Ignition’s MQTT
Engine and others), ThingsBoard, Azure IoT Hub and AWS IoT Core. An upstream is added with one
action, as an upstream broker is added on sys/upstream, and shows as a node with its status
and counters. Design: ADR 0035.
For complete, ordered data (every row, replayed after an outage) use a history sink instead
(ADR 0026, history.md §6): the uplink is live and at most once.
Where it runs
| Mode | What | Rights and network |
|---|---|---|
| Embedded (default) | wy/<site>/downstream/uplink in every wyrmd | reads this site’s downstream, dataflows, storage and the readable sections of downstream sites; network from uplink.net |
WASM package uplink | the same link, installed from a repository or zip | what an operator grants (sys/links/<id>/~act/grant): read on each root an upstream selects; net from the package’s capabilities or the link’s params |
Process package uplink-process | the same link as a process | as the WASM package |
wyrmd.json5:
uplink: {
enabled: true, // default
store_mb: 2, // definitions and secrets
// the platforms it may reach (ADR 0012 syntax, host names allowed); empty = none
net: "broker.plant.example:8883, *.azure-devices.net:8883, *.iot.eu-central-1.amazonaws.com:8443",
// upstreams fixed here (origin: config): the Add fields plus kind and name
upstreams: [
{ name: "uns", kind: "mqtt", url: "mqtts://broker.plant.example", topic_prefix: "plant" },
],
}
The id uplink is reserved. A host that net does not cover is refused at Add, with the entry
to add; the secret of a config-file upstream still goes in with Set Password.
The link’s tree
uplink/
add_mqtt, add_sparkplug, add_thingsboard, add_azure, add_aws config
stats/upstreams, connected, published, dropped
<name>/ attrs: kind, origin (runtime | config), select
status connecting | connected | waiting | failed | disabled
error the last error
url, connected_since, published, dropped, queued, last_publish
enabled writable at config (not for a config-file upstream)
set_password the one secret, kept in the link's sealed store
test_connection a whole handshake now → {success, message}; a connected MQTT
upstream answers from its live session (a second CONNECT with
its client id would close it and send its will)
edit, remove not for a config-file upstream
failedmeans the platform refused the credentials (or a secret is missing): nothing is tried again until Edit, Set Password or Enable.waitingmeans a network error: the link connects again after a back-off (1 s, ×2, up toretry_s). The queue stays through both.- Every upstream has its own subscriptions: an Add, and every Edit, sends the current value of each selected point first, then the changes, also when another upstream selects the same keys.
- Definitions come back after a restart; secrets with them.
Fields every kind takes
| Field | Meaning |
|---|---|
name | one key segment: the upstream’s node |
url | mqtt://host:1883, mqtts://host:8883 (Azure: made from hub when empty; AWS: https://<endpoint>:8443) |
select | full node keys whose values go up, one per line or comma: everything under each; default wy/<site>/downstream; the link’s own subtree never goes |
max_hz | at most this many values per point per second, the latest kept while over; 0 = every change |
queue_max | values held while the platform is slower than the site (10 000; up to 100 000); the oldest go, counted in dropped |
flush_ms | how often queued values are sent (250) |
ca_pem | trust only this CA (TLS) |
timeout_ms, retry_s | a connect or request; the longest wait between attempts |
insecure_plaintext | send the secret over mqtt:// or http:// to a host that is not loopback |
enabled |
A plaintext URL to a host that is not loopback is refused without insecure_plaintext: the
secret would go in the clear.
The kinds
mqtt — a Unified Namespace
One topic per point: <topic_prefix>/<site>/<path> (the key below wy/), e.g.
plant/edge1/downstream/plc1/d0/temp. Payload json (default): {"v": 21.5, "q": "good", "t": 1700000000000000} (t in UTC µs, as the tree has it); payload: value sends the value
alone (21.5, true, hot). retain is on by default so a consumer reads the last value at
once; qos 0 (default) or 1. Fields: topic_prefix (wyrm), qos, retain, payload,
client_id (wyrm-<site>-<name>), username (the password with Set Password),
keep_alive_s (60).
sparkplug — Sparkplug B 3.0
The site is the edge node (edge_node_id, default the site’s name) in group_id (wyrm); a
link under downstream is a device (<link>; another site’s <site>.<link>); dataflows and
storage are devices of their own; a metric is the path below the device (d0/temp).
Numbers are Double, bools Boolean, text String, so a metric’s type never changes between
an integer and a float. On every connect: NBIRTH (with bdSeq from the store and Node Control/Rebirth), then a DBIRTH per device with every metric seen so far; changes are
DDATA; a device that shows a new metric (or a metric whose type changed) is born again;
NDEATH is the will. Node Control/Rebirth on NCMD (and Device Control/Rebirth on
DCMD) answers with a full rebirth. Same MQTT fields as mqtt.
thingsboard — the gateway API
The link is a ThingsBoard gateway; username is the gateway’s access token (Set Password).
A link is a device named <device_prefix>-<link> (device_prefix defaults to the site’s
name), announced with v1/gateway/connect once per session and fed with
v1/gateway/telemetry {"<device>": [{"ts": <ms>, "values": {"<path>": v}}]} per flush,
QoS 1. Devices are created on first sight.
azure — IoT Hub
Fields hub (myhub or myhub.azure-devices.net), device_id, sas_ttl_s (3600). The
device key (base64, from the hub) goes in with Set Password; the link makes a SAS token from it
and connects again with a new one before it runs out. Username <hub>/<device>/?api-version=…,
topic devices/<device>/messages/events/$.ct=application%2Fjson&$.ce=utf-8, payload a JSON
array of {"key", "v", "q", "t"} per flush (key below wy/), QoS 1. X.509 devices are not
supported (no client certificates in the host yet).
aws — IoT Core over HTTPS
Fields url (https://<endpoint>-ats.iot.<region>.amazonaws.com:8443, the account’s data
endpoint), region, access_key_id, topic (wyrm/<site>); the secret access key goes in
with Set Password. Every flush is one POST /topics/<topic>?qos=1 signed with Signature V4
(service iotdata) with a JSON array of samples. The IAM policy needs iot:Publish on the
topic. MQTT with mTLS is not supported (no client certificates in the host yet).
Rights
Every action and the enabled leaf are config on the uplink (the built-in roles engineer
and admin). The link never writes to other links; its one key is its store key.
- An upstream sends with its author’s rights (ADR 0029), as a DQL query or an alarm watch
reads: the link itself reads the whole site, config on the uplink alone does not. Add and Edit
need the caller’s
auth(the gateway,wyrandwyrm-agentgive it); aselectkey the caller may notreadis refused; under a selected root, points the author may not read never go up. An Edit takes the editor’s rights. Entries ofwyrmd.json5send what they select (the operator wrote them). An upstream kept without rights (made before 2026-11-05) isfaileduntil an Edit. - The secret stays with its endpoint. An Edit that changes the host, the port, TLS,
insecure_plaintextorca_pemdeletes the secret: Set Password again. So a caller with config cannot send the password to a host of its own.
Limits
16 upstreams per link; select ≤ 32 keys per upstream; one tcp_send ≤ 64 KiB and at most 8
per flush; 32 unacknowledged QoS 1 packets; a CONNACK within 10 s; a PUBACK within 30 s;
MQTT 3.1.1, QoS 0 and 1. Counters reset when the link starts.
Logic blocks in dataflows
Logic blocks are node types of a dataflow (dataflows/<id>/~def, spec 06) for
small calculations: variables, arithmetic, comparisons, a hub, a stopwatch and
text. They sit beside expression, scale, window and the other node types,
and the editor shows them in its palette (dataflows/~act/node_types).
ADR 0032 records the rules below.
How a block works
- A block keeps the last sample of each input port.
- A parameter has a value from the node’s config (or its default). Where the
block has the port
in.<parameter>, a sample there replaces that value. - Blocks with variable inputs take the config list
inputs(default["0", "1"], at most 64 names[A-Za-z0-9_]+). Each name is a portin.<name>. A name may not be a parameter’s name. - Any sample on an input calculates the block.
- An operand input (
in,in.<name>) can hold a constant: the config keyvalues: {"in.0": 5}(spec 06 0.2.19). The constant is the input’s value until a sample on that input replaces it. A parameter’s port,resetand the variables take no constant (a parameter’s config is its constant).nowtakes none either: itsinis only a trigger (spec 06 0.2.30). When a block calculates from its constants alone, see “What calculates at start”. - An output is sent only when its value or its quality changed. Events
(
on_change,on_loop) are always sent:{event: <port>, id: <n>}. - Quality is the worst quality among the inputs that have a sample. The time is the latest of their times.
What calculates at start (spec 06 0.2.30)
A block that has only typed values must show a result: add with 2 and 3
shows 5, a CSV typed into table_from_csv shows its table. The rule
(2026-11-11, it narrows ADR 0032 §5):
- The variables (
number,string,bool,table) andconstantsend their value at start, asconstdoes. - A pure block with no wired input calculates once at start from its
constants and its parameters. “No wired input” means no edge into any of
its ports: an operand, a parameter’s port and
resetcount. - A block with at least one wired input waits for its first sample, as before. Its constants are used when that sample comes. A sample from a block of rule 2 is such a sample: the blocks after it calculate from it.
nowgives the time at start when itsinterval_msis above 0 (see “Date and time”).- Every other block waits for its first sample, wired or not.
A pure block is a function of its inputs and parameters only: no state, no events, no clock of its own. These 83 types are pure:
| Section | Types |
|---|---|
| Math | add, subtract, multiply, divide, max, min, abs, round, modulo, stats, factorial, log, power, root, bound, round_up, round_down |
| Trigonometry | sin, cos, tan, cot, asin, acos, atan, to_degrees, to_radians |
| Statistics | average, median, mode, std_deviation, variance |
| Logic | not, if, case, select |
| Text | concat, length, substring, replace, split, join, format_number, parse_number, left, right, trim |
| Codecs | base64_encode, base64_decode, url_encode, url_decode, to_camel_case, from_camel_case, hash, json_parse, json_stringify |
| Data | make_object, make_array, get |
| Date and time | date_time, date_format, date_parse, date_math, date_range |
| Tables | table_from_csv, table_to_csv, table_from_json, table_to_json, table_map_columns, table_sort, table_filter, table_remove_rows, table_edit_rows, table_group_by, table_join, table_rollup, table_aggregate, table_select_rows, table_select_columns, table_columns, table_row_cells, table_add_row, table_transpose, table_from_map |
These never calculate at start by rule 2, because they keep state, fire
events, keep time or route: counter, toggle, changed, rising_edge,
falling_edge, event_gate, sample_and_hold, debounce, throttle,
stopwatch, hub, trace, catch_error, router, table_recorder,
table_page, and now (rule 4). Node types that are not logic blocks
(sources, readers, expression, filter, scale, deadband, latch,
delay, window, alarm, publish, set, invoke, wasm) take no
operand constants and keep their own rules.
date_range with a relative range (today) reads the clock, as it does on
its own tick: when the day changes, its new range is an ordinary sample.
A sample of rules 2 and 4 is made of constants (Msg::constant in the
engine). It is also born at the start (ADR 0040 §2), and so is everything a
node sends while it handles it: the runtime carries both marks on. Such a
sample runs no command. It only gives the field its value: trigger,
auto_run, arg.<name>, and also in of set and invoke.
A block fed at start by a pure block and by a read or a variable calculates
twice, in the order the two samples come. Only the read’s or the variable’s
result can write through in of a command, so the value written at deploy may
lack the constant. The next real sample writes the right value.
УВАГА: a variable’s start value is born at the start, but it is not made of
constants. Wired to in of a set or an invoke, it still writes at
deploy, at a hot swap and at a restart (ADR 0038 §6), and so does the first
value of a subscribe. A pure block with no wired input never does: put the
value in the block, not in a variable, when the flow must not act at deploy.
Numbers and conversions
- A number stays an integer while the result fits:
add,subtract,multiply,abs,roundto 0 places andmodulo’s quotient. On an overflow the result is a float. dividealways gives a float.- A result that is not finite (a division by 0, an overflow of a float) is
null. - Text that parses is a number (
" 5 "→ 5,"2.5"→ 2.5).trueis 1 andfalseis 0. Other values are not numbers and are left out of a sum or a product. - As a bool: a number is true unless it is 0. Text is false when it is
false, empty or0, else true.nullis false. A list or a map is true.
The blocks
Parameter names are snake_case, as every other node type’s.
Variables
| Type | Inputs | Outputs | Parameters |
|---|---|---|---|
number | in | out | value (default 0) |
string | in | out | value (default empty) |
bool | in | out | value (default false) |
A variable sends value at start. A sample on in replaces it, converted to
the variable’s type, and goes out when it differs. A string longer than 4 KiB
is null.
Math
| Type | Inputs | Outputs | What it gives |
|---|---|---|---|
add | in.<inputs> | out | The sum; no number at all gives 0. |
subtract | in.<inputs> | out | The first minus the others; no number gives null. |
multiply | in.<inputs> | out | The product; no number gives null. |
divide | in.<inputs> | out | The first divided by the others, as a float. |
max, min | in.<inputs> | out | The largest or the smallest number. |
abs | in | out | The absolute value. |
round | in, in.precision, in.min_precision | out, text | Rounded to precision places (0 to 20, default 0: an integer). Halves round away from 0. text (spec 06 0.2.21): the same number as text with precision places, its trailing zeros trimmed down to min_precision places (default: precision). |
modulo | in, in.modulo | quotient, remainder | The quotient as a whole number toward 0, and a remainder that is never negative (-7 by 3: -2 and 2). By 0: both null. |
scale | in, in.input_min, in.input_max, in.output_min, in.output_max | out, input_out_of_range | See below. |
scale is k × in + b (defaults 1 and 0). When one of input_min,
input_max, output_min, output_max is set in the config or arrives on its
port, in is first mapped from input_min…input_max to
output_min…output_max (defaults 0, 1, 0, 100), and input_out_of_range
says whether in was outside the input range. A scale without them stays
linear, as before.
Logic
| Type | Inputs | Outputs | Parameters |
|---|---|---|---|
not | in | out | — |
if | in.op, in.then, in.else, in.<inputs> | out | op, then (default true), else (default false), inputs |
hub | in.ignore_null, in.<inputs> | out, index, on_change | ignore_null (default true), inputs |
stopwatch | reset, in.enabled, in.interval, in.step, in.modulo, in.loop, in.reset_value | out, on_loop | the same names |
trace | in.tracing, in.msg, in.<inputs> | — | tracing (default true), msg (default trace), inputs |
case | in, in.op, in.else, in.<inputs> (pairs) | out | op (default =), else (default null), inputs |
if sends then when the inputs pass op, else else:
=(default): all inputs are equal; the same number in another form counts ("5"and5);and,or: of the inputs as bools;>,<,>=,<=: between each input and the next (in.0 > in.1 > in.2); fewer than two inputs do not pass;!=(spec 06 0.2.21): the first input equals none of the others;contains,starts_with,ends_with: the first input as text with any of the others as text (anullother never matches).
case (spec 06 0.2.21) compares in with case values and
sends the value paired with the first case that matches, else else
(default null). Its variable inputs come in pairs: the first of a pair is a
case, the second what it gives. Give them constants in values:
{ type: "case", op: ">=", inputs: ["c1", "v1", "c2", "v2"],
values: { "in.c1": 90, "in.v1": "high", "in.c2": 10, "in.v2": "normal" },
else: "low" }
op is =, !=, >, <, >=, <= (as numbers; = and != as if’s
=), or contains, starts_with, ends_with (as text; an empty case text
matches nothing), or regexp (spec 06 0.2.29: a bounded pattern, see “Text
and codecs”). An input left without a pair is not used.
hub sends the input that changed last: its value on out (also when it is
the same value as before), its place in inputs on index, and an event on
on_change. With ignore_null, a null is not passed.
stopwatch counts while enabled:
- Every
intervalseconds (at least 0.05; its clock ticks every 50 ms) it addsstepto the count and sends it onout. - With
moduloabove 0, a count that reachesmodulostarts again from the remainder and sends an event onon_loop. Withloopfalse it stops atmoduloand switches itself off untilenabledcomes again. - Any sample on
resetsets the count toreset_valueand sends it at once. - A hot swap keeps the count.
trace writes msg and the values of its inputs to the broker log.
ОБЕРЕЖНО: trace writes at the level trace only, as every log line that
holds values. Set the broker’s sys/log_level to trace to see its lines,
and set it back after.
Text
| Type | Inputs | Outputs | What it gives |
|---|---|---|---|
concat | in.strict, in.<inputs> | out | The inputs as one text; a missing input is empty text, or with strict the result is null. A text longer than 4 KiB is null with quality bad. |
length | in | out | The characters of a text, the items of a list, the entries of a map or the bytes of binary; else null. |
The second set (spec 06 0.2.25, ADR 0040 §4)
Every parameter below has the port in.<parameter>.
| Type | Inputs | Outputs | Parameters and what it gives |
|---|---|---|---|
substring | in | out | start (default 0), length (default: to the end), counted in characters. |
replace | in | out | from, to: every from in the text becomes to. Plain text, no pattern. An empty from replaces nothing. |
split | in | out | separator (default ,): a list of texts, at most 1000. An empty separator gives one item. |
join | in (a list) | out | separator (default ,): the items as one text. |
make_object | in.<inputs> | out | A map: each input’s name is a key. Use it for a map argument of an action. |
make_array | in.<inputs> | out | A list of the inputs, in their order. |
get | in | out | path (default empty): the value at a.b.0 inside a map or a list; a number is an index. null when it is not there. |
stats | in (a list) | min, max, avg, sum, count | The numbers of the list. An empty list gives count 0 and null for the others. |
changed | in | on_change | An event when in differs from the sample before. The first sample only starts it. |
rising_edge | in | on_edge | An event when in becomes true. Nothing before counts as false. |
falling_edge | in | on_edge | An event when in becomes false after it was true. |
counter | in, reset | out | step (default 1), initial (default 0): each sample on in adds step; a true reset goes back to initial. |
toggle | in, reset | out | initial (default false): each sample on in flips the bool. |
sample_and_hold | in, trigger | out | The value in has when a sample comes on trigger. |
select | in.<inputs> | out | index (default 0): the input at that position, from 0; null when there is none. |
debounce | in | out | ms (default 500): the last value, once ms passed without another. |
throttle | in | out | ms (default 500): the first value at once, then the latest at the end of each period. |
- A text result longer than 4 KiB, and a
splitof more than 1000 parts, isnullwith qualitybad. changed,rising_edge,falling_edge,counter,toggleandsample_and_holddo not act on a value that exists because the flow started (a variable’s start value, the first sample of asubscribe). Such a value only gives the block where it starts from. So these blocks are safe in front of atrigger.counterandtogglekeep their state across a hot swap.- A number that is not finite (NaN, infinity) is no number for a block. On a parameter’s port it is ignored, and the last good value stays.
debounceandthrottlesend their value at most a quarter ofmslate (5 to 50 ms).
Readers:
| Type | Inputs | Outputs | Parameters |
|---|---|---|---|
load_value | trigger, in.key, in.interval_ms, in.auto_run, in.enabled | out, ok, error, running, last_run | key, key_scope, interval_ms (default 0), auto_run (default true), enabled (default true) |
list_children | trigger, in.path, in.interval_ms, in.auto_run, in.enabled | out, ok, error, running, last_run | path, path_scope, interval_ms, auto_run, enabled |
load_valuereads the stored value of a point once.outcarries it with its quality and time. A point without a stored value giveserrorwithnot_found.list_childrengives a list of rows, one per child:{name, path, type, display, is, unit, writable, has_children}(type,display,isandunitonly where the child has them). At most 1000 rows. The deployer, and whoever watches the flow, must read the children (<path>/*) as well as the node: one child that is denied refuses the block.auto_runreads at the start and when the key changes. A read is no command, so it may run at deploy.triggerreads on an event or a changed value;interval_msreads every period.keyandpathtake another key on their port insidekey_scopeorpath_scope, assubscribedoes (see “A key from a port”). A refused key is anerrorevent withinvalid_parameter.
The third set (spec 06 0.2.29, ADR 0044)
These blocks add math, text, time, events, tables and two readers (70 types,
125 in all). Every parameter has the port in.<parameter>, except inputs, a scope and a rhai
script. The rules of “How a block works” apply: change-only outputs, the worst
quality, and “What calculates at start”: a pure block of this set with no
wired input calculates at start, the others wait for a sample.
Math, rounding and number formatting
| Type | Inputs | Outputs | Parameters and what it gives |
|---|---|---|---|
constant | — | out | name (default pi; e, sqrt2, ln2, ln10, log2e, log10e). Sent at start, as a variable. |
factorial | in | out | n! of the whole part of in. Below 1: 1. An integer up to 20!, a float up to 170!, above that null. |
log | in | out | base (default 10). in at most 0: null. |
power | in | out | exponent (default 2). An integer stays an integer while it fits. |
root | in | out | degree (default 2). A negative in has a root for an odd whole degree (−8, 3: −2); else null. An exact root is a whole number (27, 3: 3). |
bound | in | input_out_of_range, out | min, max (none: that side is open). max applies first, then min, so min wins when it is above max. |
round_up, round_down | in | out, text | precision (0…20, default 0). text has exactly precision places. |
format_number | in | out | format (default #,##0.###), decimal_separator (default .), group_separator (default ,). |
parse_number | in | out | The first number in a text: abc12.5kg → 12.5, 1,234.5 → 1234.5 (commas dropped), #ff and 0xff → 255. A number passes as it is. |
format_number patterns:
0is a digit that is always shown;#a digit shown only when it is not a leading or a trailing zero.0.5with#.##is.5, with0.000.50.- A comma in the whole part sets the group size: the digits after the last
comma (
#,##0groups by 3). %in the text around the number multiplies by 100:0.0%gives25.6%for 0.256.- Text before and after the number part stays as it is:
€ #,##0.00. - A pattern is at most 64 bytes, a separator at most 8. An empty
group_separatorgives no groups. A pattern without#or0givesnull.
Trigonometry (degrees)
| Type | What it gives |
|---|---|
sin, cos, tan, cot | The function of in degrees. cot 0 is null. |
asin, acos | The angle in degrees; outside −1…1 null. |
atan | The angle in degrees of the point (x, in); x defaults to 1, so it is the arc tangent of in. |
to_degrees, to_radians | The conversion. |
The degree factors are written out: 57.29577951308232 × asin(x) and
cos(0.017453292519943295 × x), to the last digit.
Statistics
average, median, mode, std_deviation and variance take the variable
inputs (inputs, default in.0, in.1). An input that holds a list gives its
numbers, so one wire from a split or a history column is enough. At most 1000
numbers count.
medianof an even count is the mean of the two middle numbers.varianceandstd_deviationare of the population (÷ n).modeis the value that occurs most often, compared as text;null, empty text, lists and maps do not count. A tie goes to the value that got there first.- No number at all gives
null.
Text and codecs
| Type | Inputs | Outputs | Parameters and what it gives |
|---|---|---|---|
left, right | in | out | length (default 0): the first or the last characters of in as text. |
trim | in | out | The text without spaces at its start and end. null gives empty text. |
base64_encode | in | out | A text (as UTF-8) or bytes as Base64. Another value gives null. |
base64_decode | in | out, bytes | Base64 (standard or URL alphabet, padding optional): out as text (UTF-8; a bad sequence is U+FFFD), bytes as bytes. No Base64: null. |
url_encode | in | out | A URL component: every byte but A–Z a–z 0–9 - _ . ! ~ * ' ( ) as %XX. |
url_decode | in | out | + is a space, %XX a byte, a bad or cut % stays as it is (100% → 100%). |
to_camel_case | in | out | Hello World-foo → helloWorldFoo; abc 2nd → abc2Nd. |
from_camel_case | in | out | HelloWorld → hello world (each capital becomes a space and the small letter). |
hash | in | out | algorithm (sha256 default, sha1, md5): the digest of a text (as UTF-8) or of bytes in lower-case hex. |
json_parse | in | out, parse_error | A JSON text as a value. A value that is no text passes as it is. No JSON: out null, parse_error true. |
json_stringify | in | out | pretty (default false): a value as JSON text. Bytes become Base64 text. |
- Text results are at most 4 KiB, as every text block: a longer one is
nullwith qualitybad. JSON texts (json_parsein,json_stringifyout) are at most 256 KiB, a parsed value at most 32 levels deep. md5andsha1are check sums a device or a service may ask for. Do not use them for a secret.
Older text blocks, changed by this set (a config without the new field gives what it gave before):
substringtakesend: withoutlength, the part ends before the characterend; below 0 counts from the end (start 1,end -1on[abc]givesabc).lengthwins overend. An overrun still clamps.replacetakesregexp(default false):fromis then a pattern.tois taken as it is:$1is no group.casetakes the operatorregexp:inas text has a match of the case.
ОБЕРЕЖНО: a pattern is at most 256 bytes and 64 KiB compiled. The engine
(the regex crate) has linear time and no backreferences, so a pattern from a
port cannot hang the flow. A pattern that does not compile matches nothing
and replaces nothing.
Date and time
A date value is a number of microseconds since the Unix epoch, as the time
t of every sample, a history row and last_run. A date input also takes
text: RFC 3339 (2026-10-29T13:00:00Z, …+02:00), a date and time without an
offset (2026-10-29T13:00:00, read in time_zone), yyyy-M-d, yyyy/M/d and
M/d/yyyy, each with an optional H:mm[:ss[.fff]] and am/pm.
time_zone (default UTC) is an IANA name (Europe/Kyiv), UTC or an offset
±HH:MM. A wall time in a DST gap moves forward; a time that occurs twice
takes the earlier instant.
УВАГА: the default zone is UTC, not the broker host’s zone. Set time_zone
on every date block that shows or counts wall time.
| Type | Inputs | Outputs | Parameters and what it gives |
|---|---|---|---|
now | in, in.interval_ms | out | The current time: at start, every interval_ms (default 1000; 0: only on samples of in; else 100 … 86 400 000), and on each sample of in. in is only a trigger: it takes no constant, and its value means nothing. A now stored before spec 06 0.2.30 also ticks every second: set interval_ms: 0 for the old behaviour. |
date_time | the parameter ports | out | year (default 1970), month, day (default 1), hour, minute, second, millisecond (default 0), time_zone. Parts overflow as a calendar counts: month 13 is January of the next year, day 0 the last day of the month before. A part that is not whole is cut. |
date_format | in | out | format (default yyyy-MM-dd'T'HH:mm:ss), time_zone (also auto: the offset written in the input text). |
date_parse | in | time, year, month, day, hour, minute, second, millisecond, weekday | time_zone. weekday 1 is Monday, 7 Sunday. A text that is no date gives null on every output. |
date_math | in | out | op (after default, before), year, month, day, hour, minute, second, millisecond, time_zone. |
date_range | in, next, previous | start, end, this_range, next_range, previous_range, formatted, duration | format, range_delimiter (default /), keep_special (none, raw, formatted), week_start (default monday), time_zone. |
Pattern letters of date_format and date_range.format: yyyy (yy two
digits), M/MM, MMM (Oct), MMMM (October), d/dd, D (day of the
year), E (Thu), EEEE (Thursday), H/HH, h/hh with a
(AM/PM), k, K, m/mm, s/ss, S… (fraction digits), Z
(+0200), xxx (+02:00), XXX (as xxx, Z for UTC). Text in single
quotes stays as it is; '' is a quote. A letter is always a pattern letter:
quote words ('at'). A pattern is at most 128 bytes. Names are English.
date_math:
- Years, months and days count on the calendar of
time_zone. Jan 31 + 1 month is the last day of February. A day over a DST change keeps the wall time (it lasts 23 or 25 hours). - Hours, minutes, seconds and milliseconds are elapsed time.
date_range reads a range text:
| Text | Range |
|---|---|
today, yesterday | the day, from 00:00 to 23:59:59.999999 |
thisWeek, lastWeek | seven days from week_start |
thisMonth, lastMonth, thisYear, lastYear | the calendar month or year |
current<N><unit> | the last N units up to now (current3days) |
previous<N><unit> | the N units before current<N><unit> |
2026, 2026-10, 2026-10-29 | the year, the month, the day |
<a>/<b> | from a to b; an end written to the second takes the whole second |
- Units:
seconds,minutes,hours,days,weeks,months,years; N is 1 … 100 000. A name may also be written in snake case (this_week). startandendare microseconds,endinclusive.durationisend − start + 1.this_rangeisstart/endasyyyy-MM-ddTHH:mm:ssintime_zone.next_rangeandprevious_rangeare the texts of the neighbours:today↔yesterday,thisX↔lastX,currentN↔previousN, the next and the previous year, month or day, ana/brange shifted by its length.- A sample on
nextorprevious(not one born at the start) moves the block to that neighbour. A new value onindrops the move. - A named or a relative range is calculated again every second, so
todayrolls over at midnight andcurrent1hoursmoves with the clock. A change goes out only when an output changed.
Logic and events
| Type | Inputs | Outputs | Parameters and what it gives |
|---|---|---|---|
router | in, condition, in.<inputs> (the cases) | out.<inputs>, else | op (as case, default =), single_output (default false), inputs. in goes out on out.<name> of the first case that condition matches, else on else. |
event_gate | reset, in.<inputs> | on_finish, order | log_order (none default, first_occurrence, last_occurrence, all), inputs. An event once every input changed at least once since the last reset. |
catch_error | in.<inputs> | out, code, source, on_error | inputs. Wire the error outputs of readers and commands into it: out is the message, code the status code, source the input’s name, on_error an event for each error. |
router:
{ type: "router", inputs: ["high", "low"], op: ">=",
values: { "in.high": 90, "in.low": 0 } }
// edges: ["level.out", "r.condition"], ["alarm.event", "r.in"],
// ["r.out.high", "notify.trigger"], ["r.out.low", "log.trigger"]
- A case value is the input
in.<name>; give it a constant invalues. single_output: truesets the output routed before back tonullwhen the route changes. Without it each output keeps its last value.routerroutes on any sample onin,conditionor a case.
event_gate:
- A sample born at the start does not count, and the gate fires once. A
sample on
reset(not one born at the start) opens it again. orderlists the input names joined with commas; withallit keeps the last 1000 changes.ordernames the inputs, it does not number them.
catch_error takes only wired errors: there are no error groups that route an
error to a catcher without a wire. A wire keeps the cycle check, watch and
preview true to the graph (ADR 0044 §7).
Readers: history and node
| Type | Inputs | Outputs | Parameters |
|---|---|---|---|
load_history | trigger, in.key, in.interval_ms, in.auto_run, in.enabled, in.time_range, in.rollup, in.window, in.limit, in.time_zone | out, ok, error, running, last_run | key, key_scope, interval_ms, auto_run (default true), enabled, time_range (default today), rollup (default none), window, limit (default 10 000), time_zone (default UTC) |
get_node | trigger, in.key, in.interval_ms, in.auto_run, in.enabled | out, actions, ok, error, running, last_run | key, key_scope, interval_ms, auto_run (default true), enabled |
load_history reads the historian (~val?history=, docs/history.md):
time_rangeis a range text asdate_rangereads it:today,lastWeek,current24hours,2026-10,<a>/<b>. Wiredate_range.this_rangeintoin.time_rangefor a fixed or a named range a user moves withnextandprevious.- For a sliding range (
current24hours), write the text itself intotime_rangeand setinterval_ms.this_rangeof a sliding range changes every second: wired intoin.time_range, it asks the historian once a second. A change while a read runs reads again after it. window(5m,1h,1d,1w; empty: none) androllup(avg,min,max,sum,count,first,last,delta,and,or) give one row per window.outis a table (ADR 0044 §2) with the columnst(microseconds),vandq(the quality code;nullfor a rollup row).limitis 1 … 10 000. An answer that reached the limit may have more rows: theokevent then carriestruncated: trueandrows. A table larger than 512 KiB is anerrorwithresource_exhausted.- A changed query field (
in.time_range, …) reads again whenauto_runis true. A history read has 30 s to answer.
get_node reads a node’s ~meta:
outis its summary:{name, display, type, unit, enum, writable, is, has_children}.actionsis a table{name, display, group, level, params};paramsis a list of{name, type, default, required, display, description, unit, enum}. It gives an action’s default arguments.
Both read inside a scope as load_value does: the deployer, every watcher and
every previewer must read the key and all of key_scope.
Every reader (load_value, list_children, load_history, get_node) also
runs on dataflows/<id>/~act/trigger {node} (the editor’s Run button). The
caller then needs read on the reader’s key and all of its scope (for
list_children also on the children), not a command’s level.
УВАГА: a run that a trigger starts flows on along the edges. When a set or an
invoke is downstream of the triggered node (directly, through other blocks
or inside a custom block), the caller also needs that block’s level on its
target: max(maxperm, write). A reader with no command downstream needs read
alone. The same holds for a command block whose answer runs another command.
Tables
A table is a value (ADR 0044 §2):
{"columns": ["name", "kw"], "rows": [{"name": "pump", "kw": 3}, {"name": "fan", "kw": 7}]}
columnsgives the order; each row is a map. A cell a row lacks isnull.- Every table input also takes a list of maps, as
list_childrenandload_historygive them; its columns are the keys in the order they first appear. Rows given as lists ({"columns": [...], "rows": [[...]]}) are taken by position. - There is no index column: a row’s index is its place, from 0.
- Bounds: 10 000 rows, 128 columns, a column name of 256 bytes, 512 KiB of
cells, a cell 29 levels deep. A larger result is
nullwith qualitybad. - The parsers check their bounds while they read, not after:
table_from_csvrefuses (parse_errortrue) a text past 512 KiB, a row of more than 128 fields (a header too: it is not cut) and a field past 64 KiB; a row map of more than 128 keys is no table;table_from_jsonandjson_parseread at most 256 KiB and 32 levels; a list of names (columns,ignore_columns) counts its first 512 items. An equal header name gets_2,_3, … in one pass (a,a_2); an empty header name, a column past the header’s last name and every column of a CSV read without a header are named by their column number from 1 (v3). - A table block takes a table on
inand gives a new one: the mutators (table_add_row,table_edit_rows,table_remove_rows) are transforms, not writes into a stored table. Keep a table across samples in atable_recorder, or write it to broker storage withset.
Per-row scripts (table_filter, table_remove_rows, table_edit_rows,
table_map_columns) are rhai, with two variables: row (the row as a map:
row.kw, row["kw rate"]) and index (from 0). A column name is not a
variable: names come from the data, and the compiler checks a script when the
flow is deployed. state is a map that lives for one table. A missing cell is
(): write row.kw != () && row.kw > 5. All the scripts of one table have
100 ms; past that the block gives null and the reason on error. The 100 ms
are CPU time of the thread that runs them: time the host keeps that thread off
a core does not count (the wall clock only where the platform has no thread CPU
clock: NetBSD, illumos, Windows, wasm32).
| Type | Inputs | Outputs | Parameters and what it gives |
|---|---|---|---|
table | in | out | value: a table, sent at start as a variable. |
table_recorder | reset, in.<inputs> | out | enabled, buffer_size (default 1024, at most 10 000), time_window_s, ignore_null, inputs. A row {t, <input>…} for each sample on an input (t: the sample’s time, µs); a sample on reset clears it (a table on reset replaces the rows). |
table_from_csv | in | out, parse_error | with_header (default true), delimiter (default ,). Cells are texts. |
table_to_csv | in | out | with_header, delimiter. |
table_from_json | in | out, parse_error | selector (data.items, a[0].b). A list of objects (nested keys as a/b), one object, or {columns, rows}. |
table_to_json | in | out | pretty. The rows as JSON objects. |
table_map_columns | in | out, error | retain_columns, mapping: [{name, from}]; from is a column, = expr (a value), + expr (a number), & expr (a bool). |
table_sort | in | out | column, method (number, string, natural), order. No value sorts last either way; equal keys keep their order. |
table_filter | in | out, error | expr: the rows for which it is true. |
table_remove_rows | in | out, error | expr: the rows for which it is false. |
table_edit_rows | in | out, error | expr, cells ({<column>: <value>}): each matching row gets the cells. |
table_group_by | in | out | column, include_blank, nested (a column rows with each group’s table), aggregates. |
table_join | in, right | out | column, right_column (default: column), join (left, inner, right, full, exclude, union). |
table_page | in, next, previous, first, last | out, current_page, total_pages | page_size (default 10; below 0: all), page (from 0). |
table_rollup | in | out | time_column (default t), interval (default 1h), round_time (default true), method, aggregates, week_start, time_zone. |
table_aggregate | in | out | column, method. One value. |
table_select_rows | in | out | indexes: 0,2,5, a list or a number. |
table_select_columns | in | out | columns: name,zone or a list. |
table_columns | in | out | A table {name, type}; type is number, string, bool, map, list, bytes, mixed or null. |
table_row_cells | in | out, count | row: that row as a map; count: the rows. Wire get for one cell. |
table_add_row | in | out | row: a map appended (a make_object gives one; a new key adds its column). |
table_transpose | in | out | header_column, include_headers, header_prefix (default c), ignore_columns. |
table_from_map | in | out | A map as a one-row table; a table passes. |
aggregates (of table_group_by and table_rollup) is a list
[{column, method, as}]; as names the result (default: the column). The
methods: first, last, count (cells with a value), sum, average,
min, max, median (of the sorted cells), mode, std_deviation, variance, concat, concat_unique (texts
joined with commas, at most 4 KiB).
table_join is one to one: the first row of the other table
with the key counts; keys compare as text (1 matches "1"). left keeps
every row of in and adds the new columns of right; inner only the rows
with a match; right every row of right (its cells win); full the rows of
in with a key, once each, then the rows of right none of them has;
exclude the rows of in that right lacks; union all rows of both. A
table with no key column passes in (for right: right).
table_rollup:
intervalis a number and a unit:s,m(minutes),h,d,w,M(months),y. The namesfiveMinutes,oneHour,day, … are taken too.round_time: truestarts the buckets on round times intime_zone(15m: :00, :15, …;1d: midnight;1w:week_start);falsestarts them at the first row’s time.- A bucket without rows gives no row. The time cell is the bucket’s start in microseconds.
- Without
aggregates, every other column is reduced bymethod.
// the hourly maximum of a day of history
{ h: { type: "load_history", key: "downstream/plc/t1", time_range: "yesterday" },
r: { type: "table_rollup", interval: "1h",
aggregates: [{ column: "v", method: "max", as: "t_max" }] } }
// edges: ["h.out", "r.in"]
Parameter ports of the other node types
The older node types take the parameters an editor binds on a port
in.<parameter> too (spec 06 0.2.17), with the rule of the blocks: the config
value (or the default) at start, then the last good sample.
| Type | Parameter ports |
|---|---|
scale | in.k, in.b (and the range ports in.input_min … in.output_max) |
alarm | in.high, in.low, in.hysteresis, in.delay_s, in.return_delay_s |
delay | in.ms |
window | in.size_s |
deadband | in.abs, in.pct |
timer | in.period_ms |
- Every one of these ports takes a number. A sample that is not a finite
number, or that is outside the parameter’s bounds (
period_msat least 10,size_sabove 0,ms,delay_sandreturn_delay_sat least 0), is ignored: the last good value stays. - The config rules stay:
alarmstill needshighorlowin its config,deadbandabsorpct. The config gives the start value. - A new
period_ms,ms,size_sor alarm delay takes effect at once. The node’s clock starts again one period after the change. A sample that adelayalready holds keeps its time.
Quality and status codes from a value
A node reads a quality or a status code from a value in four places: the
result of an expression with quality: custom, the answer of a reader, the
answer of a command, and a saved state. Spec 06 does not say what a missing
or a wrong code means, so these rules apply (ADR 0029, decided 2026-11-15;
crates/wyrm-flow/src/codes.rs):
- A code is valid when it is an unsigned integer in the code table
(
spec/tables.json), or the wire name of an entry as a text ("good","uncertain","bad";"timeout","busy", …). A fraction, a float with no fraction (2.0), a negative number, NaN, a number out of the table, an unknown name,nulland a missing field are not valid. - A quality that is not valid is
bad. It is nevergood. expressionwithquality: custom: the result must be a map{v, q}. The output isvwith the quality ofq(rule 2). A missingq, and a result that is not a map withv, givebad.- A reader or a command whose answer failed gives the event
errorwith an error code (spec 04 status group error,0x20and above). A code that is not valid, or that is not in the error group (ok, a progress or a closed code), isinternal_error(0x25). A failure never reads as a success. - A command passes a user-defined error code (
0x40…0x4F) and an unknown error-group code in the eventerroras it is (CONTRIBUTING “Wire enums” rule 3). A reader givesinternal_errorfor them, as it always did.
A key from a port
subscribe and liveliness read the key of their config. Their port in.key
takes another key while the flow runs (spec 06 0.2.22, ADR 0040 §1): a text
block builds a path, and the path drives the source.
| Type | Inputs | Outputs | Parameters |
|---|---|---|---|
subscribe | in.key | out, error | key (the start key; may be absent with a scope), key_scope |
liveliness | in.key | out, error | key, key_scope |
- Give the node
key_scope, a key expression of the keys the port may name:downstream/modbus/line1/**. The compiler refuses an edge intoin.keywithout it. - Deploy. The deployer must read all of the scope.
watch,portsandpreviewask the same of their caller. - Send a key to
in.key: a text, one concrete key inside the scope (downstream/modbus/line1/t1). A wildcard, a key of another site, a key undersysand a value that is not a text are refused.
- A new key ends the old read first.
outisnullwith qualityuncertainuntil the new key’s first sample. - A refused value reads nothing.
errorcarries the reason as a text and goes back tonullwith the next good key. nullon the port reads nothing and is no error.- Two changes are at least 100 ms apart. The latest value wins.
- The output
key(the parameter’s echo) is the key in use. livelinesssends nothing for a node that has no token, as before.
subscribe and liveliness look alike in the editor, but they read two
different things. subscribe reads a point’s value (~val) as it changes:
a number, a text, any value. liveliness reads whether a node is there: true
while its liveliness token is present (a link, a device or a broker that is up),
false when the token goes. The editor names the field Node and the output
Alive.
УВАГА: the targets of set and invoke have no port. A flow changes what it
writes and the arguments of an action, never where it writes (ADR 0040 §1a).
The action block and the command behaviours
invoke is the action block: an action of a node, dropped from the tree. set
writes a point. Both are commands, and both have the same behaviour fields
(spec 06 0.2.23, ADR 0040 §2).
| Type | Inputs | Outputs | Parameters |
|---|---|---|---|
invoke | in, trigger, in.interval_ms, in.auto_run, in.enabled, arg.<name> | out, result, sent, ok, error, running, last_run | path, action, args, on, allow_bad, interval_ms (default 0), auto_run (default false), enabled (default true), run_on_start (default false) |
set | in, trigger, in.interval_ms, in.auto_run, in.enabled | sent, ok, error, running, last_run | path, on, deadband, allow_bad, interval_ms (default 0), auto_run (default true), enabled (default true), run_on_start (default false) |
Arguments of invoke:
- Each key of
argsis one argument. Its value is the argument’s constant:args: {setpoint: 21.5, mode: "auto"}. - Each argument has the port
arg.<name>. A sample there replaces the constant. Usenullas the constant of an argument that only a wire gives. "$in"as a constant stands for the last value onin.
What runs a command:
| Cause | invoke | set |
|---|---|---|
a sample on in | every sample that passes on | the value, when auto_run is true and it passes on/deadband |
trigger | an event, or a value that differs from the last one | the same: it writes the value that in holds |
auto_run | a sample on arg.<name> that changes the argument | see in |
interval_ms above 0 | every period | every period: the held value again |
the action dataflows/<id>/~act/trigger {node} | one run | one write of the held value |
run_on_start: true | one run, 250 ms after each start of the flow | one write of the value in got by then |
enabled: falsestops every cause.interval_msis 0 (off) or 100 … 86 400 000. A period is skipped while the run before it has not answered.sentfires when the request leaves,okwhen the target answered,errorwhen it refused:{event: "error", id, code, message}with the status code of spec 04.runningis true between the two.last_runis the time of the lastsentin microseconds.invoke.resultis the last result.invoke.outstays: the result, or the error text with qualitybad.
УВАГА: a deploy, a hot swap, a reload and a restart never run a command through
trigger, auto_run or interval_ms. A value that exists because the flow
started (a variable’s start value, a const, a parameter’s echo, a timer’s
first tick, the first sample of a subscribe) only fills the field. The first
run of interval_ms is one full period after the start. in does not have
this rule: a variable wired to in of a set or an invoke still acts at
deploy. Wire trigger where a deploy must do nothing.
There is one action block. A block that runs on a trigger, a block that runs
at deploy and a periodic block are the same invoke with other fields; there
is no block type per behaviour. The older on of invoke still works for
in: change is what trigger does, and rising or falling is a
rising_edge or falling_edge block wired into trigger.
ОБЕРЕЖНО: run_on_start: true is the one exception to the rule above. The
block then runs once at every start of the flow: each deploy, each hot swap,
each reload and each broker restart. Set it only on a command that is safe to
repeat.
The trigger action is the block’s button in the editor. It needs level
write on the flow, and the caller needs write on the block’s own target
(the flow’s maxperm when that is higher).
It works on a deployed flow that runs. In a preview a command block shows what
it would send (sinks), fires sent, and never ok or error.
Custom blocks
A custom block is a sub-flow that a flow uses as one block (spec 06 0.2.24,
ADR 0040 §3). The definition carries it in blocks; a node of type
block:<name> is an instance.
{
"blocks": {
"mean": {
"inputs": [
{"name": "a", "to": "sum.in.0"},
{"name": "b", "to": "sum.in.1"},
{"name": "k", "to": "div.in.1", "default": 2}
],
"outputs": [{"name": "out", "from": "div.out"}],
"nodes": {"sum": {"type": "add"}, "div": {"type": "divide"}},
"edges": [["sum.out", "div.in.0"]]
}
},
"nodes": {"m1": {"type": "block:mean", "values": {"k": 4}}},
"edges": [["x.out", "m1.a"], ["y.out", "m1.b"], ["m1.out", "r.in"]]
}
- The fields of an instance are the block’s inputs and outputs, in their
order. A parameter is an input with a
default. valuesgives an input its constant for this instance. A wire replaces it.- The compiler replaces the instance by the inner nodes
m1/sumandm1/div.watch,portsandpreviewshow them under these ids;nodes: ["m1"]asks for all of them. - A block may hold other blocks, at most 4 deep and at most 64 instances in one block. A block may not contain itself. The 1000 nodes of a flow count every inner node and every instance; a flow has at most 4000 edges with its blocks expanded.
- A constant goes only to an inner input that keeps one: a parameter’s port,
an operand of a logic block, an argument of
invoke,inof a variable. - A block with a
publishinside can be used once in a flow.
The library keeps blocks for every flow of the site:
- Store a block:
dataflows/~act/put_block {name, def}(levelconfig). - Read it:
get_block {name}gives{name, version, def, requires}. - Copy
defand every block ofrequiresintoblocksof the flow. - Deploy the flow.
list_blocks lists them; remove_block {name} removes one. A flow holds its
own copy: a change in the library reaches a flow when the block is copied and
the flow is deployed again.
Fields as outputs
Every field of a node is also an output (ADR 0038, spec 06 0.2.15). This applies to every node type, not only to the blocks.
- A parameter
pis an outputp. It sends the parameter’s effective value: the config value or the default, replaced by the last sample onin.<p>where that port exists. It sends once when the node starts and then on every change. Astopwatchthat stops atmodulosendsenabledfalse. - An input
xthat is not a parameter’s port is an outputx. It repeats every sample onx, before the node handles it. - The output has the field’s name:
["scale1.input_min", "add1.in.0"]reads the parameterinput_minofscale1;["if1.in.0", "show.in"]repeats the inputin.0ofif1. - A declared output keeps its name. An input’s echo comes before a parameter’s:
latchhas the inputresetand the parameterreset, so its parameter has no output. - Types: an input’s echo has the input’s type. A parameter’s echo is
number,boolormapas the parameter, elseany. - An echo output with no edge is never built and costs nothing.
УВАГА: a parameter’s echo sends at start. An edge from it to an invoke or a
set runs that command when the flow is deployed, restarted or hot-swapped.
This is the one way a block fires a command by itself.
The catalog (dataflows/~act/node_types) tells an editor which field is
which: per parameter port (in.<p> when it has one), default (typed: a
number stays a number) and echo; per type port_types and echo_inputs.
An editor shows the live values of a deployed flow with
dataflows/<id>/~act/watch (spec 06, “Живі значення”). The engine keeps the
last sample of every port from the start (spec 06 0.2.18), so a variable that
sent its value once at deploy shows in every later snapshot and in ports.
An editor shows the live values of a draft that is not deployed with
dataflows/~act/preview {def} (spec 06 0.2.16, ADR 0038 §5). The draft runs
in a sandbox: nothing is stored, and set, invoke and publish write
nothing. The rows are those of a watch, plus sinks: what each of these nodes
would write, and where. The first row already has the variables’ start values.
A preview ends after 10 minutes; the editor opens it again with its latest
draft.
Does a deployed flow work (spec 06 0.2.31, ADR 0045)
dataflows/<id>/~val shows the state of the flow (state, error,
version, since, deployed_by) and its counters in stats. You need only
read rights on the flow to see them:
| Key | What it counts |
|---|---|
nodes, edges | the size of the compiled flow, custom blocks expanded |
samples_in | samples the nodes took in from an edge or from their own source (subscribe, liveliness, const) |
samples_out | samples the nodes sent on a wired output |
dropped | samples the node queues dropped (policy.queue, policy.overflow) |
restarts | restarts after a node panic |
commands.sent, .ok, .error | the events of the invoke and set blocks; error also counts a run refused as busy |
last_sample_t | when a node last took in a sample (µs); absent before the first one |
How to read them:
samples_instands still while the flow runs: no source sends. Check the source keys and the links behind them.droppedgrows: a node is slower than its input. Makepolicy.queuebigger, or reduce the input withthrottle,deadbandorwindow.commands.errorgrows: open a watch on the command block. Itserroroutput has the code and the message.
The counters start from 0 at each deploy, start and reload, and at every
broker start (the engine deploys its stored flows again). A restart after a
panic keeps them and adds 1 to restarts. A stopped flow keeps its last
totals. A state change publishes ~val at once. Between state changes,
~val goes out again only when a counter moved, at most once per
metrics_interval_ms of wyrmd.json5 (default 10 s, never below 5 s). For
totals over a longer time, record dataflows/<id> with a historian watch.
Example
A tank level in percent, on a flow value, and a high alarm at 90 %:
{
id: "tank", version: 1,
nodes: {
raw: { type: "subscribe", key: "downstream/plc/tank/level_raw" },
pct: { type: "scale", input_max: 4095 },
whole: { type: "round" },
high: { type: "if", op: ">", then: "high", else: "ok" },
limit: { type: "number", value: 90 },
show: { type: "publish", node: "level" },
state: { type: "publish", node: "state" },
},
edges: [
["raw.out", "pct.in"], ["pct.out", "whole.in"], ["whole.out", "show.in"],
["whole.out", "high.in.0"], ["limit.out", "high.in.1"], ["high.out", "state.in"],
],
}
How the editor shows each block
WYRM Studio’s flow editor draws a block as fields, one row each
(studio/docs/design/specs/flow-editor.md §3). It builds them from the
catalog (dataflows/~act/node_types) in studio/business/lib/wyrm/mappers/flow_fields.dart
(fieldsOf, fieldLabel, isVariable, tailParams).
Pins (owner decision 2026-11-09). The rows below are a
type’s defaults: a block draws its pinned fields, and the inspector lists
every field with a pin to put it on the block or take it off. A field with a
wire is always a row. The user’s choices travel in the definition’s layout
(flow-editor.md §12).
One field = one entity (owner decision 2026-11-08). A field’s value, its binding and what it feeds are one row, never three:
- a field
pof a block is the parameterp∪ its inputin.<p>∪ its echo outputp(ADR 0038 §1); - the main value of a variable block (
number,string,bool,const: inputin, parametervalue, outputout) is ONE fieldValue; - an operand (
in,in.0,in.1, … that is no parameter’s port) is a field with both ports: its input and its echo; - a result (
out,quotient,remainder, …) is a field with a right port only.
Binding INTO a field is an edge to its engine input (in.<p>; in for a
variable’s Value, an operand’s own port); binding OUT of a field is an edge
from its echo or output (out for a variable’s Value, p for a
parameter). Older definitions that wired a variable’s echoes value or in
still draw on the Value row; a new binding uses out.
Rules:
- A row reads a human label: the catalog’s
display, else an override, else sentence case with a unit suffix in brackets. Numbered inputsin.0,in.1readInput 1,Input 2. Names a user or a device gave (points,expressionvariables,wasmports,invokearguments) stay as given. The engine name is the row’s tooltip and stands under the label in the inspector. - Ports:
⇄a left port (the engine has an input for the field) and a right port (its echo or output);→a right port only;←a left port only. - Order: fixed operands, then the parameters, then the variable inputs,
then the parameters drawn after them (
tailParams:ifthen, else;concatstrict;hubignore null), then the results. A sink names what it writes before the value. - A parameter is a row of the block when it has a port, belongs to the form
in use, is set, has a default, is required, or is one of a pair the engine
needs one of (
deadbandabs/pct,alarmhigh/low). Maps, lists and the list of variable inputs (inputs) are edited in the inspector only. - In the inspector a parameter with
choicesis a dropdown, aboola toggle, anything else a text field typed as the parameter’s type (a number, text, JSON). - A bound field shows the value that comes in along its wire, never the
path (accent colour on the block; read only, framed, with a
boundmark in the inspector). The wire and the source row light when the pointer is over the field; the inspector’s link menu hasGo to sourceandUnbind. A bound field with nothing known yet shows nothing, not the typed value the binding replaces. - An operand of a type with catalog
values: trueholds a typed value: the node’s configvalues: {"<port>": <value>}(spec 06 0.2.19). A binding replaces it; the typed value stays in the config and returns on unbind. Never on a parameter’s port,stopwatch.resetor a variable’sin.casereads its variable inputs as pairs:Case 1,Then 1, … A typed value is read as JSON (5is a number), except the text operandsinoftable_from_csv,split,replaceandjson_parseand a range text: they stay the text typed. A text of several lines (a CSV needs a header and a row) is typed in the value viewer: the eye of the row, then Edit; Enter starts a new line, ⌘/Ctrl+Enter saves. The inspector’s row then grows to show the lines and keeps them. - Values are live. A draft that runs otherwise than the deployed version
(its layout aside) runs as a preview (
dataflows/~act/preview): the blocks show its values and each sink what it would write (would write 70.7, apreviewtag; nothing is written). A draft equal to the deployed version shows the watch’s values (dataflows/<id>/~act/watch). Where neither has a sample the editor follows the wire back to its source field: a variable’s or a parameter’s typed value, a point’s tree value. - Sinks (
publish,set,invoke) show no echo outputs of their parameters (the engine has them; the editor leaves them out so a sink stays a sink). Asetrepeats what it writes on its point’s row. - A key field takes a wire inside a scope (ADR 0040 §1; the catalog’s
params[].scope). WhenPoint(subscribe,liveliness,load_value) orNode(list_children) gets a wire and the block has no scope, the editor asks for it on the field:This block may read keys under, with the key’s parent and all below it proposed (downstream/modbus/line1/**), the site’s sections as chips, and the engine’s rule checked as it is typed (insidedownstream,dataflowsorstorageof this site). Save writeskey_scope; Cancel takes the wire away. The scope then shows as the rowScope; unbinding keeps it. The deployer’s and the watcher’s rights on the scope (forlist_childrenalso on its children,<scope>/*) are checked by the engine, not by the editor. - A block with behaviours (
invoke,set,load_value,list_children: atriggerinput and the event outputs) lists its fields in groups in the inspector: Target, Arguments, Behaviour, Events, State. On the block only what the user set or wired shows beyond the defaults in the table. An unboundTriggerof a command block is aRunbutton: the engine’sdataflows/<id>/~act/trigger {node}on the DEPLOYED flow, off with the reason while the draft differs from the deployed version. An event output reads when it last fired,errorwith its code and message. In a preview the block’s trigger row readswould send …. - An action dragged from the Tree tab becomes an
invokewithpath,actionand one argument per parameter of the action (its default, else nothing yet); required arguments are rows of the block. The action’s own parameter types come from the node’s~metaand choose each argument’s editor. - A custom block (ADR 0040 §3) is made from a selection (
Create custom block…: a name, and a name per port; an input may get a default), kept in the definition’sblocks, and drawn as one block per instance. Its inside opens on the canvas (Open inside,Edit custom block) with anInputsblock and anOutputsblock: a wire fromInputs.<a>to an inner field is thetoof inputa, a wire from an inner output intoOutputs.<x>thefromof outputx. The My blocks tab lists the flow’s blocks and the site’s library (list_blocks); a library block placed is copied into the flow with the blocks it uses (get_block). - On a broker without ADR 0040 (no
scopein the catalog, no type withtrigger: true,list_blocksnot answered) the editor draws the older shape and says why a thing is off: a key field takes no wire (This broker cannot bind …),Runis off, My blocks and the custom-block items of the menu are off.
| Type | Fields on the block, in order | Field ← engine | Inspector only | Editors |
|---|---|---|---|---|
number, string, bool | Value ⇄ | Value = in → value → out | — | number box; text; toggle |
const | Value → | Value = value → out | — | JSON or text |
subscribe | Point ⇄ · Scope (once a wire feeds Point, or a scope is written; a pencil opens its prompt) · <point> → · Error → (once a wire feeds Point) | in.key → key; key_scope; the point’s value on out; error | — | Point: a text, or a wire; Scope: the prompt on the field, or a text field that says why a scope is refused |
liveliness | Node ⇄ · Scope · Alive → · Error → (as subscribe) | in.key → key; key_scope; out (true while the node is there); error | — | as subscribe |
timer | Period (ms) ⇄ · Count → | in.period_ms → period_ms; out | — | — |
expression | Expression → · Trigger → · Quality → · <name> ⇄ … · Output → | in.<name> ⇄ | Inputs (list) | Trigger, Quality dropdowns |
filter | Input ⇄ · Expression → · Output → | in; expr | — | — |
latch | Input ⇄ · Reset ⇄ · Reset mode · Output → | in, reset (operands); reset parameter (no echo: the input took the name) | — | Reset mode dropdown |
delay | Input ⇄ · Delay (ms) ⇄ · Output → | in; in.ms → ms | — | — |
scale, form k × in + b | Input ⇄ · Factor ⇄ · Offset ⇄ · Output → | in; in.k → k, in.b → b; out | Form | Form dropdown |
scale, form Range | Input ⇄ · Input min ⇄ · Input max ⇄ · Output min ⇄ · Output max ⇄ · Output → · Input out of range → | in.input_min → input_min, … | Form | Form dropdown |
deadband | Input ⇄ · Absolute change ⇄ · Percent change ⇄ · Output → | in; in.abs → abs, in.pct → pct | — | — |
window | Input ⇄ · Size (s) ⇄ · Kind → · Function → · Max samples → · Output → | in; in.size_s → size_s; the others config only | — | Kind, Function dropdowns |
alarm | Input ⇄ · High ⇄ · Low ⇄ · Hysteresis ⇄ · Delay (s) ⇄ · Return delay (s) ⇄ · On bad quality → · Active → · Event → | in; in.high → high, in.low, in.hysteresis, in.delay_s, in.return_delay_s; on_bad config only | — | On bad quality dropdown |
publish | Value name · Value ← | in | Meta | — |
set | <point> ⇄ (a behaviour that is set shows too) | in → its echo in | Target: Point (path) · Behaviour: Trigger (unbound: Run) · Auto run · Every · Enabled · Run on start · Write on · Deadband · Allow bad quality · Events: Sent, Ok, Error · State: Running, Last run | Run button (~act/trigger); toggles; Every: a number and its unit; Run on start asks first with the catalog’s warning |
invoke | header <node> · <action> · <required argument> ⇄ … · Trigger ⇄ · Ok → · Error → (a behaviour that is set shows too) | arg.<name> ⇄ (constant in args); trigger; ok, error | Target: Node (path), Action · Arguments: the action’s other parameters · Behaviour: Run when (in), Auto run, Every, Enabled, Run on start, Run on, Allow bad quality · Events: Sent · State: Output (out), Result, Running, Last run | an argument as its action types it (choices, toggle, number, text); Run button; Every: a number and its unit; Run on start asks first |
wasm | Artifact → · <input> ⇄ … · <output> → … | ports named by inputs/outputs | Config, Fuel, Memory (MB) | — |
add, subtract, multiply, divide, max, min | Input 1 ⇄ · Input 2 ⇄ · … · Output → (− / +, at least 2) | in.0, in.1, …; out | — | operands typed (values) |
abs, not, length | Input ⇄ · Output → | in; out | — | in typed (values) |
round | Input ⇄ · Precision ⇄ · Min precision ⇄ · Output → · Text → | in; in.precision → precision, in.min_precision → min_precision; out, text | — | in typed (values) |
modulo | Input ⇄ · Modulo ⇄ · Quotient → · Remainder → | in; in.modulo → modulo | — | — |
if | Operation ⇄ · Input 1 ⇄ · Input 2 ⇄ · … · Then ⇄ · Else ⇄ · Output → | in.op → op; in.<n>; in.then → then, in.else → else | — | Operation dropdown (=, !=, and, or, >, <, >=, <=, contains, starts_with, ends_with); operands typed |
case | Input ⇄ · Operation ⇄ · Case 1 ⇄ · Then 1 ⇄ · … · Else ⇄ · Output → (− / + by a pair, at least one) | in; in.op → op; pairs in.<n> by position; in.else → else; out | — | Operation dropdown; cases and thens typed (values) |
hub | Input 1 ⇄ · Input 2 ⇄ · … · Ignore null ⇄ · Output → · Index → · On change → | in.<n>; in.ignore_null → ignore_null; outputs | — | Ignore null toggle; operands typed |
stopwatch | Reset ⇄ · Enabled ⇄ · Interval (s) ⇄ · Step ⇄ · Modulo ⇄ · Loop ⇄ · Reset value ⇄ · Output → · On loop → | reset; in.<p> → p | — | Enabled, Loop toggles |
trace | Tracing ⇄ · Message ⇄ · Input 1 ⇄ · Input 2 ⇄ · … | in.tracing → tracing, in.msg → msg; in.<n> | — | Tracing toggle; operands typed |
concat | Input 1 ⇄ · Input 2 ⇄ · … · Strict ⇄ · Output → | in.<n>; in.strict → strict; out | — | Strict toggle; inputs typed (values) |
load_value | Point ⇄ · Scope · Trigger ⇄ · Error → · Output → | in.key → key; key_scope; trigger; error, out | Behaviour: Auto run, Every, Enabled · Events: Ok · State: Running, Last run | as subscribe for Point and Scope; Run button (~act/trigger, the caller reads the key and the scope) |
list_children | Node ⇄ · Scope · Trigger ⇄ · Error → · Output → | in.path → path; path_scope; trigger; error, out | as load_value | as load_value |
substring, replace, split, join, get | Input ⇄ · <parameter> ⇄ … · Output → | in; in.<p> → <p>; out | — | a parameter typed as the catalog says |
make_object, make_array, select | <input> ⇄ … (select: Index ⇄ first) · Output → (− / +) | in.<name> (named inputs keep their names); in.index → index; out | Inputs (list) | inputs typed (values) |
stats | Input ⇄ · Min → · Max → · Average → · Sum → · Count → | in; min, max, avg, sum, count | — | — |
changed, rising_edge, falling_edge | Input ⇄ · On change → / On edge → | in; on_change / on_edge (an event: the row reads when it fired) | — | — |
counter, toggle | Input ⇄ · Reset ⇄ · Step ⇄ · Initial ⇄ · Output → | in, reset; in.<p> → <p>; out | — | Initial: a number / a toggle |
sample_and_hold | Input ⇄ · Trigger ⇄ · Output → | in, trigger; out | — | — |
debounce, throttle | Input ⇄ · Quiet time (ms) ⇄ / Period (ms) ⇄ · Output → | in; in.ms → ms; out | — | — |
block:<name> (an instance of a custom block) | header MY · <input> ⇄ … · <output> → … · Open inside | an input: the inner input its to[0] names (its constant in values, else the block’s default); an output: the inner output from; live values from the rows <instance>/<inner> | — | an input typed as any value (2 is a number, AHU- a text) |
constant | Name ⇄ · Value → | in.name → name; out | — | Name dropdown |
factorial, parse_number, sin, cos, tan, cot, asin, acos, to_degrees, to_radians | Input ⇄ · Output → | in; out | — | in typed (values) |
log, power, root, atan | Input ⇄ · Base / Exponent / Degree / X ⇄ · Output → | in; in.<p> → <p>; out | — | — |
bound | Input ⇄ · Min ⇄ · Max ⇄ · Input out of range → · Output → | in; in.min, in.max; outputs | — | — |
round_up, round_down | Input ⇄ · Precision ⇄ · Output → · Text → | in; in.precision; out, text | — | — |
format_number | Input ⇄ · Format ⇄ · Decimal separator ⇄ · Group separator ⇄ · Output → | in; in.<p>; out | — | — |
average, median, mode, std_deviation, variance | Input 1 ⇄ · Input 2 ⇄ · … · Output → (− / +) | in.<n>; out | — | operands typed (values) |
left, right | Input ⇄ · Length ⇄ · Output → | in; in.length; out | — | — |
trim, base64_encode, url_encode, url_decode, to_camel_case, from_camel_case | Input ⇄ · Output → | in; out | — | in typed (values) |
base64_decode | Input ⇄ · Output → · Bytes → | in; out, bytes | — | — |
hash | Input ⇄ · Algorithm ⇄ · Output → | in; in.algorithm; out | — | Algorithm dropdown |
json_parse | Input ⇄ · Output → · Parse error → | in; out, parse_error | — | — |
json_stringify | Input ⇄ · Pretty ⇄ · Output → | in; in.pretty; out | — | Pretty toggle |
now | Input ⇄ (a trigger: a wire, no typed value) · Every ⇄ · Output → (a date and time) | in; in.interval_ms → interval_ms; out | — | Every: a period in a unit; the viewer: the local date, UTC and the µs |
date_time | Year ⇄ · Month ⇄ · Day ⇄ · Hour ⇄ · Minute ⇄ · Second ⇄ · Millisecond ⇄ · Time zone ⇄ · Output → (a date and time) | in.<p> → <p>; out | — | Time zone: a text with a menu of zones (UTC, IANA names, ±HH:MM) |
date_format | Input ⇄ (a µs value as a date and time) · Format ⇄ · Time zone ⇄ · Output → | in; in.format, in.time_zone; out | — | Time zone: the zone menu with auto first |
date_parse | Input ⇄ · Time zone ⇄ · Time → (a date and time) · Year → · … · Weekday → | in; in.time_zone; the parts | — | Time zone: the zone menu |
date_math | Input ⇄ · Operation ⇄ · Year ⇄ · … · Millisecond ⇄ · Time zone ⇄ · Output → (Input and Output as a date and time) | in; in.<p>; out | — | Operation dropdown; Time zone: the zone menu |
date_range | Input ⇄ · ▸ Next ← · ▸ Previous ← (buttons: a sample on the wire presses them) · Format ⇄ · Delimiter ⇄ · Keep special ⇄ · Week start ⇄ · Time zone ⇄ · Start → · End → (dates and times) · This range → · Next range → · Previous range → · Formatted → · Duration → | in, next, previous; in.<p>; outputs | — | Input: a text with a menu of range texts (today, lastWeek, current24hours, …); Keep special, Week start dropdowns; Time zone: the zone menu; Next, Previous: an off button that says a wire presses it |
router | Input ⇄ · Condition ⇄ · Operation ⇄ · Case 1 ⇄ · Case 2 ⇄ · … · Single output ⇄ · Else → (− / + adds a case with its output, removes both with their wires) | in, condition; in.op, in.single_output; a case row is one field: in.<case> on the left, out.<case> on the right (a named case reads its name); else | Inputs (list) | Operation dropdown; cases typed (values) |
event_gate | Reset ⇄ · Log order ⇄ · Input 1 ⇄ · … · On finish → · Order → | reset; in.log_order; in.<n>; outputs | — | Log order dropdown |
catch_error | Input 1 ⇄ · … · Output → · Code → · Source → · On error → | in.<n>; outputs | — | — |
load_history | Point ⇄ · Scope · Time range ⇄ · Rollup ⇄ · Window ⇄ · Trigger ⇄ · Error → · Output → | in.key → key; in.<p>; trigger; error, out | Behaviour: Auto run, Every, Enabled · Limit, Time zone · Events: Ok · State: Running, Last run | as load_value; Time range: a text with the range menu; Rollup dropdown; Time zone: the zone menu; Run button (a refusal shows the broker’s words); the viewer shows out as a table, t as dates |
get_node | Node ⇄ · Scope · Trigger ⇄ · Error → · Output → · Actions → | in.key → key; trigger; error, out, actions | as load_value | as load_value |
table | Value ⇄ | Value = in → value → out | — | typed in the viewer’s grid (cells, rows, columns; Edit as JSON too); the viewer shows every row, the counts, a filter, Copy CSV and Copy JSON |
table_recorder | Reset ⇄ · Input 1 ⇄ · … · Enabled ⇄ · Buffer size ⇄ · Time window (s) ⇄ · Ignore null ⇄ · Output → | reset; in.<n>; in.<p>; out | Inputs (list) | — |
table_from_csv, table_to_csv, table_from_json, table_to_json | Input ⇄ · <parameter> ⇄ … · Output → (· Parse error →) | in; in.<p>; outputs | — | table_from_csv Input: a text of several lines (its first line and ↲ +N on a row); the viewer’s “As table” tab reads it by the block’s delimiter and with_header and writes edits back as CSV |
table_map_columns | Input ⇄ · Retain columns ⇄ · Output → · Error → | in; in.retain_columns; outputs | Mapping (list of name/from) | Mapping: rows of name and from |
table_sort, table_aggregate, table_select_rows, table_select_columns, table_row_cells, table_add_row, table_transpose, table_columns, table_from_map | Input ⇄ · <parameter> ⇄ … · Output → | in; in.<p>; outputs | — | Method / Order dropdowns |
table_filter, table_remove_rows, table_edit_rows | Input ⇄ · (Cells ⇄) · Output → · Error → | in; (in.cells); outputs | Expression | Expression: multi-line |
table_group_by, table_rollup | Input ⇄ · <parameter> ⇄ … · Output → | in; in.<p>; out | Aggregates (list of column/method/as) | Aggregates: rows of column, method, as |
table_join | Input ⇄ · Right ⇄ · Column ⇄ · Right column ⇄ · Join ⇄ · Output → | in, right; in.<p>; out | — | Join dropdown |
table_page | Input ⇄ · ▸ Next ← · ▸ Previous ← · ▸ First ← · ▸ Last ← (buttons, as date_range) · Page size ⇄ · Page ⇄ · Output → · Current page → · Total pages → | in, triggers; in.<p>; outputs | — | the four buttons: off, a wire presses them |
Limits of single types that the table does not show:
consthas no input: it sends its value once, at the start.delayhas no mode: for a window or a wait usethrottleordebounce.concathas no separator.- An instance of a custom block has no row of its own in
watch(ADR 0040, deferred). load_historygivestin microseconds and fixed column names; atable_map_columnsrenames them.table_from_jsonkeeps a nested list as one cell.table_joinrenames no columns; atable_map_columnsdoes.
The editor takes the ports from the catalog (a parameter’s port), so a
port the engine adds shows without an editor change. Parameters the engine
has no input for show no left port, and a wire dragged onto them is refused
with <field> takes no input: type its value. Today these are expression
expr, trigger, quality; filter expr; latch its
parameter reset; window kind, fn, max_samples; alarm on_bad;
a scope (key_scope, path_scope); the command targets (set.path,
invoke.path, invoke.action, ADR 0040 §1a) and run_on_start
(crates/wyrm-flow/src/catalog.rs).
Claude connector — WYRM in Claude Desktop (ADR 0041)
Claude works on your broker network as one gateway user. It reads the tree, values and history. After a dry run that you approve, it writes values, runs actions, deploys dataflows and runs checked plans. The user’s role decides what is allowed. You need no API key: Claude Desktop runs the connector on your computer, and it logs in to the gateway like Studio does.
1. A gateway user for Claude
Create a user of its own, so the audit shows which changes Claude made. On the broker host, run this (the password is read from stdin):
wyrmd -c wyrmd.json5 user add claude --roles operator
| Role | What Claude can do |
|---|---|
viewer | read devices and storage |
operator | read, write points, run write-level actions, read flows |
engineer | also config-level work: add/edit devices, deploy flows (needs Allow config-level changes too) |
2. Install the extension
- Get
wyrm-<version>-darwin.mcpb(macOS) orwyrm-<version>-win32.mcpb(Windows) from the CI run of claude-desktop (Actions → claude-desktop → Artifacts; the workflow ispackaging/claude-desktop/ci-workflow.yml, copied to.github/workflows/claude-desktop.yml), or build it yourself:
The file goes topackaging/claude-desktop/build.sh --universaldist/claude-desktop/. On Windows, runbash packaging/claude-desktop/build.shfrom Git Bash. - Double-click the file, or in Claude Desktop open Settings → Extensions → Install Extension….
- Fill in the form:
| Setting | Value |
|---|---|
| Gateway URL | https://<broker>:<port>. For a gateway on this computer (the demo), http://127.0.0.1:8445. Plain HTTP to another host is refused, because the password would go in clear. |
| Gateway user / Password | the user from step 1. Claude Desktop keeps the password in the system keychain. |
| Gateway CA certificate | the PEM that signs the gateway’s certificate: the broker CA, or the certificate itself when it is self-signed. Leave it empty for a certificate from a public CA. |
| Read-only | refuses every change |
| Allow config-level changes | off by default. When it is off, Claude can show config-level changes (config points and actions, anything under sys, flow deploys) but not send them. |
- Start a chat and ask “who are you on WYRM?”. Claude calls
whoamiand answers with the user, the site and the grants.
3. What to expect
- Before a change, Claude reads the node’s
~meta, runs a dry run and shows what it would send. A link built with spec 0.2.33 or later also checks the call itself without running it (checked_by_link:okor the refusal the action would give, ADR 0047); an older link is checked against its~metaonly. Claude Desktop asks you before each tool call. Allow only what you have read. - Several dependent steps (add a device, wait for it, set a value, expect a reading) go in one
plan_run. Claude checks the plan first and applies it after you agree. - Claude does not approve a plan of the agent link (
tasks/<id>▸approve): the connector refuses it and so does the gateway for the remote connector. Approve it in Studio (ADR 0049). - Keys:
downstream/modbus/plc1/tempmeans a key on the gateway’s own site.wy/<site>/…reaches a site below it. - When the session expires (8 h by default), the connector logs in again by itself.
4. When it does not work
| Message | Cause |
|---|---|
wrong user or password, or the user is disabled | Fix the settings under Settings → Extensions → WYRM. |
TLS: invalid peer certificate: UnknownIssuer | Set Gateway CA certificate to the PEM of the broker CA or of the self-signed certificate. |
plain HTTP only on loopback | Use https:// for a gateway on another host. The gateway serves TLS when tls_cert/tls_key or tls: "site_ca" are set in wyrmd.json5; for site_ca, set Gateway CA certificate to the broker’s data_dir/pki/ca.pem. |
Connection refused | The gateway is not running, or the port is wrong (gateway.listen in wyrmd.json5). |
refused_by_connector: … allow_config | A config-level change. Turn on Allow config-level changes if the user’s role should be used for it, or do it in Studio. After the switch, quit Claude Desktop (⌘Q) and open it again: a chat keeps talking to the connector process it started with, and that process read the old setting. whoami shows connector.allow_config as it is in force. |
permission_denied | The user’s role does not allow it. |
… takes no file: invoke it over the WebSocket, with arguments under 60 KiB | A text or map argument is too large. Send less at a time (one branch of an import). Only a parameter with editor: file takes more (up to 64 MiB). |
Logs: in Claude Desktop, open Settings → Developer, or open the extension’s log file (mcp-server-WYRM.log).
Claude Code and other MCP clients
The same binary runs anywhere MCP runs:
{
"mcpServers": {
"wyrm": {
"command": "/abs/target/release/wyrm-mcp",
"args": ["--gateway", "https://broker.example:8445", "--user", "claude", "--gateway-ca", "/abs/broker-ca.pem"],
"env": { "WYR_GATEWAY_PASSWORD": "…" }
}
}
}
Without --gateway, wyrm-mcp is the Zenoh-side server with approval tokens (mcp.md).
Claude on the web and mobile: the remote connector
The gateway serves an MCP endpoint at https://<broker>/mcp itself, with its own OAuth 2.1 sign-in (ADR 0041 stage B). You add it once on claude.ai, and it works on the web, in Desktop and on mobile. It is off by default. It needs a public HTTPS name that Claude’s servers can reach.
- In
wyrmd.json5:
Restartgateway: { listen: "0.0.0.0:8445", tls_cert: "/etc/wyrm/gateway.pem", // a certificate for broker.example from a public CA tls_key: "/etc/wyrm/gateway.key", mcp: { public_url: "https://broker.example:8445", // optional: redirect_uris (default: Claude's callbacks and "loopback"), // access_ttl_s (60…3600, default 3600), refresh_days (1…365, default 30) }, },wyrmd.https://broker.example:8445/.well-known/oauth-protected-resourcenow answers with JSON. - On claude.ai, open Settings → Connectors → Add custom connector, name it
WYRM, and set the URL tohttps://broker.example:8445/mcp. No client ID or secret is needed: Claude registers itself. - Claude opens the gateway’s sign-in page. Enter the gateway user (step 1 above) and the password, choose Allow changes and/or Allow config-level changes, and sign in.
What is checked:
- Only redirect URIs on the allowlist register: Claude’s callbacks, and loopback for MCP clients on your own computer.
- The code is single use, lasts 60 s, and is bound to PKCE S256.
- An access token lasts at most 1 h and is valid only on
/mcp, never as a Studio session. - Refresh tokens are bound to the client. A new password, a disabled user or a removed user ends every token.
- Each sign-in is in the audit as
mcp_sign_in, with the client’s name and what was allowed.
Exposure: the gateway is reachable from the internet. Put it behind a reverse proxy that passes /mcp, /oauth/* and /.well-known/oauth-* and allows only Anthropic’s published egress IP ranges for /mcp and /oauth/token. The sign-in page itself opens in your browser. If you cannot expose the gateway, use the Desktop extension above: it needs no inbound access.
wyrm-mcp — the WYRM tree as MCP tools (ADR 0005)
For Claude Desktop, use the gateway mode instead: one extension file, a gateway user, no key file (claude.md, ADR 0041).
tools/wyrm-mcp is an MCP server over wyrm-client (stdio; streamable HTTP on loopback with --http). It signs requests as ai:<agent-name> with at most write; without --key it is read-only.
Tools
tree_list, tree_resolve, node_meta (expand applies profiles), value_get, node_set, action_invoke, profiles, flow_get, flow_validate, flow_apply, link_status, spec; resources wy://spec/<file>.
node_set,action_invokeandflow_applydefault todry_run: true: they validate against~meta(type, enum, bounds, action schema, level) and return what would be sent.- Config-level operations (
writable = config, action levelconfig, anything undersys/**, flow deploys) needapproval: a base64ptokminted by a human for exactly that key and exactly those arguments (≤ 15 min, subject notai:). It is sent instead of the service token, so the link checks the human’s rights.flow_applyalso needs one proof per command target from the same human (ADR 0008). - An approval is bound to the arguments (claim
args, spec 04 0.2.14; security review). Without it an MCP client could show a harmless dry run, get the token, then send other arguments with it. The steps:- Run the tool with
dry_run(the default). Readwould_send(forflow_apply: the definition and the proofs) and copyargs_sha256. - Mint the approval for that key and that hash:
wyr --key admin.key token <key> --subject user:<you> --args-sha256 <hash> [--ttl-s 300]. - Run the tool again with the same arguments,
dry_run: falseandapproval.
- Run the tool with
- The MCP server refuses an approval without
argsor with another hash before it sends anything; the link refuses it too. - For
flow_apply, give the proofs in the dry run already: they are part of the request, so the hash covers them.
Claude Code
WARNING: the key file is an admin signing key. Keep it at mode 0600.
- Run
cargo build --release -p wyrm-mcp. - Put this in
.mcp.json(absolute paths):
{
"mcpServers": {
"wyrm": {
"command": "/abs/wyrm/target/release/wyrm-mcp",
"args": ["--connect", "tcp/127.0.0.1:7447", "--site", "local", "--agent-name", "claude"],
"env": { "WYRM_MCP_KEY": "/abs/ai.key" }
}
}
}
For HTTP: run wyrm-mcp --http 127.0.0.1:8765 (set WYRM_MCP_HTTP_TOKEN, at least 32 characters, or copy the random token it prints) and use {"type": "http", "url": "http://127.0.0.1:8765/mcp", "headers": {"Authorization": "Bearer <token>"}}. Requests need a loopback Host with that port and no Origin header (DNS-rebinding guard).
Not yet
Tools history, device_models, link_install; tree and profile resources; prompts; origin marking for approved AI calls; a service identity issued by the admin (the write cap is enforced by the MCP process); TLS for --http (loopback only, bearer token).
AI agent link (links/agent)
links/agent has two parts:
wyrm-agent, the command line (below): an operator or an AI assistant (Claude Code) runs it on a workstation and works on the whole broker network through one gateway.- The
agentdriver: an LLM inside the broker that plans tasks for people to approve (from “How a task runs” on).
wyrm-agent: the command line
Build it once:
cargo build --release -p wyrm-link-agent --features cli --bin wyrm-agent
It logs in to a gateway as one of its users. The password comes from
WYR_GATEWAY_PASSWORD, never from the command line. The user’s role decides every read and
write. The gateway reaches the sites below its own, so central’s gateway works on edge and
plant too (ADR 0007, 0018).
| Command | What it does |
|---|---|
tree <key> [--depth N] | The nodes below a key: type, unit, writable. |
meta <key> | The full ~meta: actions with their parameters, levels, bounds. |
get <key>… | Current values. |
watch <pattern> [--seconds N] | Samples of a key or a pattern for a while. |
set <key> <json> | Writes a value. |
invoke <key> <action> [<json args>] [--args-file <path>] [--file <param>=<path>]… | Runs an action. --args-file reads the JSON arguments from a file; --file sets a binary parameter to the bytes of a file (a zip, a part). Arguments over 60 KiB go by the gateway’s POST /api/invoke, which takes only an action with an editor: file parameter, up to 64 MiB. |
history <key> <json args> | Recorded values ({"from": "…", "limit": 100}). |
run <plan.json> [--apply] | Checks a plan; with --apply, runs it. |
Every answer is JSON, one object per line. The exit code is 1 when a plan check or a step fails.
Plans
A plan is {"steps": [...]}, run in order. A step is one of:
{"invoke": <key>, "action": …, "args": {…}, "unless": <key>, "ok_if_error": <text>}: runs the action; skipped whenunlessexists, and done when the action is refused with a message that holdsok_if_error("is watched": it is so already). With these the same plan runs again;{"set": <key>, "value": …};{"deploy": "wy/<site>/dataflows", "def": {…}}: deploys a flow one version above the one that runs (the gateway signs the proofs of its targets with your rights);{"wait": <key>, "timeout_s": N}: waits until the node exists;{"expect": <key>, "equals": …}or"min"/"max"or"changes": true, withtimeout_s: waits until the value passes;{"sleep_s": N}.
- Run
run <plan>first. It checks each step against the live~meta: the action exists, its arguments fit its schema, a value fits its point. A step on a node an earlier step makes is checked when it runs ("check": "later"). - Read the result, then run
run <plan> --apply. It stops at the first step that fails and says which.
УВАГА: --apply changes the sites at once, with your rights. Read the check first.
Example: a Modbus device, history, upstream and a dataflow
examples/agent/modbus-dataflow.json runs on the demo (examples/demo/run.sh) through
central’s gateway:
export WYR_GATEWAY_PASSWORD=wyrm-demo-1
wyrm-agent --gateway http://127.0.0.1:8445 run examples/agent/modbus-dataflow.json
wyrm-agent --gateway http://127.0.0.1:8445 run examples/agent/modbus-dataflow.json --apply
It adds the device ahu2 with four points on edge’s Modbus link, records two of them on edge
and one on central (central’s historian records a point of the site below), deploys a flow on
edge that turns the counter into a command (count mod 10 × 10) and the temperature into °F
and a flag, and on each change writes the command to another link (mockdev/bench/rig1/knob).
The last steps check the flow’s values and that the knob follows.
The agent driver
The agent driver takes a task in plain words, asks an LLM for a plan, and runs the plan
after a human approves it (ADR 0005). It runs embedded in wyrmd
(sys/links ▸ Install Link ▸ from Driver, driver agent).
How a task runs
- A user with
writeon the link calls ▸ Ask{task}. The link createstasks/<id>.{task, parent, context}may name a task this one follows (a retry, an undo, another plan) and node keys to read first. A parent that waits for a person is replaced (below). - The model reads the tree with read-only tools. It may ask back (
ask_user): the task waits inawaiting_answeruntil ▸ Answer{answers}. - The model proposes a plan.
setandinvokesteps change the site.wait,expectandsleepsteps only read: they prove the plan and need no approval. - The link checks every step against
~meta,allowed_prefixesand the level the step needs. - With approval needed, the task waits in
awaiting_approval. The record is the task’s~statedocument (restricted: the reader needslist):plan[]holds every step in thewyrm-agent runformat with its numbern, level,after,check,warnandreason. ▸ Approve{approvals: {"<n>": <token>}, plan}takes one human token per step, at the level of that step.writeon the task is enough to call it. - The link runs the stored plan. A step with a human token runs with that human’s rights. A
step without a token that needs one is
skipped, and so is every step that needs it (after). The run stops at the first step that fails.
The agent never runs a config step without a human token.
What the model offers next
The model may offer the person something to ask next (its tool suggest). The record holds
it as suggestions[]: {id, label, detail, changes, step?, rows?: [{key, label, detail}]}.
step: the suggestion is a fix for the warning of that plan step (warnis the link’s finding,model_warnthe model’s words; show them apart).rows: nodes the same change fits (the same for more units). The person ticks rows.changes: how many changes the model expects it to take. 0: nothing changes.
A suggestion runs nothing. To pick one, send a follow-up Ask: {parent: <this task>, task: "<label>. <detail>", context: [<keys of the ticked rows>]} (askSuggestion in wyrm_client).
The model plans it as a new task, and you approve that plan step by step.
After a run stops at a step, the model gets one more turn (param review_turns). It only
reads, and it offers ways out as suggestions. While the turn runs, the task shows
reviewing: true. What the model found is review in the record. The task stays failed.
Limits: 8 suggestions in a task, 16 rows each, label 80 bytes, detail 300 bytes (a cut
text keeps its … inside the bound). A row
must be a node that the agent may read and that the asker of the task may read. A task that
fails drops the suggestions of its planning. A row is checked against the asker’s rights
from their token’s auth (spec 04), and only until that token’s exp. The asker’s own
answer or approve renews them. Without them the row is refused: a token without auth,
an expired token, a restart of the link (the rights are kept in memory only). context in
Ask needs a token with auth too.
You can stop the turn after a run: ▸ Cancel while reviewing. The task stays failed.
What the model found
The model may note what it read about a node (its tool found, in planning and in the turn
after a run). The record holds it as findings[]: {key, label, detail}, one per node, in
the order the model noted them. Studio shows them as the rows of What I found in the
Explorer drawer.
labelanddetailare the model’s words. Show them as plain text, never as a check.- A finding has no mark good or bad. A client that marks a row takes the mark from the node’s live value, read with the viewer’s own rights.
keyis a plain node key of the task’s site that the agent may read and that the asker of the task may read. It is checked like a row of a suggestion: against the asker’s rights from their token’sauth, only until itsexp. Without them the finding is refused.- Limits: 12 findings in a task,
label80 bytes,detail300 bytes. Longer text is cut, and the…that marks the cut is inside the bound. - One row per node. A second finding on a node replaces the words of its row, in the same place: the turn after a run corrects what planning noted.
- A finding the link does not note is counted by why in
findings_refused:{rights_unknown | rights_expired | outside_rights | limit | invalid: <count>}. These are fixed words, never the model’s text. Studio says from them why rows are missing.
The asker’s rights last as long as the token of their last call on the task: Ask, or their
own Answer or Approve. Through a gateway such a token lasts 5 min. Nothing else renews the
rights, so findings are refused as rights_expired in two common cases:
- The turn after a stopped run starts when the run ends, not by a person. If another person approved the plan, their approval does not renew the asker’s rights.
- The asker approved, and the run took more than about 5 min after the approval.
The same holds for the rows of a suggestion.
- A finding runs nothing and is no part of the plan (not in its hash). A task that fails keeps its findings: they say what was read.
A replaced plan
A follow-up Ask (parent) of a task in awaiting_approval or awaiting_answer takes its
place. The old task goes to failed with error: "replaced by <id>" and replaced_by: <id>
in the record and in ~val. ▸ Approve on it is refused (invalid_parameter, task was
replaced by <id>), through a gateway too. A follow-up of a task that plans, runs or has ended
replaces nothing.
Who approves decides what runs without a token:
- The asker of the task, or a user with
configon the link: awritestep that needs no approval runs with the agent’s own key (ai:<link>, at mostwrite, only underallowed_prefixes). - Any other user: only the steps they sign run. Every other step that changes something is
skipped.
Through a gateway
A gateway user holds no key. Send approve {steps: [n…], plan: <hash>}: the gateway reads the
stored plan, checks your grants for each step and signs one token per step (ADR 0049). plan
is the hash of the plan you read: SHA-256 (hex) of the canonical CBOR of ~state.plan, each
step without approval, check, warn, model_warn, reason, result (planHash in
wyrm_client).
A step outside your grants refuses the whole call and names the step and the right.
The gateway signs only:
- for a person’s own session. A session of an MCP client (the Claude connector,
/mcp) is refused, and the connector itself never sendsapprovefor a task: approve in Studio. - for a task of an agent link of the gateway’s own site, as the broker’s registry knows it
(driver
agent). A task on a downstream site is refused for now: approve it through that site’s gateway, or with your own tokens.
An approval does not wait
An approval token is made when you approve and is good for a few minutes (5 min from the gateway; never more than 15 min, spec 04). The run sends each step in its turn, after the waits of the proof steps before it. So:
- The link takes no step that needs a person into a plan when the waits before it
(
wait/expecttimeouts,sleep) add up to more than 240 s. The model is told to shorten the waits or to end the plan there. - ▸ Approve is refused, and the task keeps waiting, when a token cannot outlive the waits
before its step plus 30 s. Leave the step out; it is
skipped. - Ask for the rest as a follow-up (
ask {parent}) when the plan is done, and approve it then. A token is never made for later.
The gateway op doc {key, suffix: "~state"} reads the record.
What a task shows
| Key | Who reads | What |
|---|---|---|
tasks/<id>/~val | read on the link | {state, step, of, last: {n, ok, result}, suggestions?, findings?, reviewing?, replaced_by?}: numbers, fixed words and task ids only (suggestions and findings are counts) |
tasks/<id>/~state | list on the task | the ask, owner, plan with results, questions, suggestions, findings, replaced_by, review, log, error |
budget_used_today | read on the link | LLM tokens used this UTC day |
sys/links/<id> ▸ secrets | config | the names of the link’s secrets, never a value |
Params
| Param | Default | Meaning |
|---|---|---|
model | claude-sonnet-5-5 | The model. |
budget_tokens_day | 1 000 000 | LLM tokens per UTC day; Ask is refused at the limit. |
allowed_prefixes | none | Keys under which the agent may propose changes. Empty: nothing. |
require_approval | write | Which steps need a human (below). |
api_key_ref | anthropic_api_key | The link secret with the API key (▸ Set Secret). |
api_base | https://api.anthropic.com | Where the API key is sent. |
max_turns, max_tokens, llm_timeout_s, fallbacks | Bounds of one planning run. | |
review_turns | 4 | LLM calls of the turn after a run stopped at a step (ways out). 0: none. |
Approval modes
write(default): every step needs a human token. Keep this mode.configandnever: onlyconfigsteps need a human;writesteps run at once with the agent’s key.
УВАГА: with config or never, the model’s plan writes without a human. The model reads
text that devices and users put in the tree: node names, descriptions, enum names, values,
profiles, flow definitions. Anyone who can write such text can try to steer the plan
(prompt injection). Use these modes only with narrow allowed_prefixes, and only where
every write there is safe to make without review (security review, ADR 0031).
ОБЕРЕЖНО: the reason and model_warn of a step, a question’s text, a suggestion, a finding, review
and the model’s log lines come from the model too. Before you approve, read each step’s key
and arguments in plan, not only the reason.
УВАГА: with config or never, one click on a suggestion card (a way out, a fix, Make a
plan for n units) sends the model’s text as a new Ask. That text can carry text the model
read from devices (prompt injection), and the new plan’s write steps then run without
a human. The tag changes (nothing at 0) is only the model’s guess, not a check: a
suggestion tagged nothing can still lead to a plan that writes. Read a suggestion before you
pick it, and keep the mode write where you use the suggestion cards.
The API key and api_base
The API key is entered once with ▸ Set Secret (anthropic_api_key) and is never shown.
It goes only to api_base, over TLS with the system roots.
The secret may also hold an OAuth access token of the ant CLI (it starts with sk-ant-oat;
ant auth print-credentials --access-token prints it after ant auth login). The link then
sends it as Authorization: Bearer. Such a token lasts some hours and the link does not
refresh it: when Ask fails with HTTP 401, set the secret again. Use it to try the assistant;
give a broker that runs for long an API key.
A change of api_base (▸ Update with another host or path) deletes the API key secret. Enter
the key again after the change; the audit shows secret_dropped. A user with config on the
link cannot read the secret, and this rule stops them from sending the key to a host of their
own (security review, ADR 0031).
Links: install, run and package them
A link connects devices or services to the WYRM tree. It serves the
subtree wy/<site>/downstream/<link>/**: nodes, values, set and actions. This
page tells you how to install a link while the broker runs, what the broker
does with it, what goes in a package, and what the limits are.
Decisions behind this page: ADR 0004 (driver framework), ADR 0006 (ACL and
quarantine), ADR 0010 (WASM host), ADR 0011 (installing links at runtime),
ADR 0012 (network for WASM links), ADR 0013 (links as requesters), ADR 0021
(packaging with wyr), ADR 0023 (portable links), ADR 0030 (TLS and random
bytes for WASM apps, world wyrm:app@0.3.0), ADR 0043 (the official links
manifest and its index).
1. How a link runs
| Mode | Where the code runs | Where the code comes from | Isolation | Typical use |
|---|---|---|---|---|
embedded | in the broker process | a driver built into wyrmd | none: same process | the built-in drivers |
process | a child process the broker starts and watches | a built-in driver (wyrmd link <driver>) or a process package | own process, mTLS identity, ACL on its own branch, rlimits, cleared environment | your own driver in Rust |
| WASM | in the broker process, in a sandbox | a WASM package or one component (.wasm) | WebAssembly sandbox: no files, no WASI, only the imports of its world (an app also gets the host’s clock, timers and its store), only the TCP addresses you list, fuel, memory and time limits | small protocol drivers, computed points, portable links (section 9) |
external | on another machine | anything that speaks the link protocol with a certificate from the broker’s CA | mTLS identity, ACL on its own branch | gateways and devices in the field |
New code that arrives while the broker runs never loads into the broker as native code: Rust has no stable plugin ABI, and a crash would take the broker down. In the broker’s own process it runs only as WASM.
A refusal is an error
Spec 04 puts every status below 0x20 in the success or closed groups, and
requesters (wyrm-client, the gateway, Studio, wyr) read those as done. So
a link never answers a refused set or invoke with one. not_available
(0x08) is the status of a value that has none yet, never of a refused
request. The SDK enforces it: a LinkError with a closed-group status leaves
as disconnected, one with a success-group status as internal_error with a
warning in the log. The built-in drivers use these codes:
| The refusal | Status |
|---|---|
The device answered with an error for this request (a protocol exception, an SZL error, an SNMP error-status, a BACnet Error/Reject/Abort, an HTTP error reply) | invalid_parameter |
| The device’s reply cannot be read (a value that does not decode, a reply that is not JSON) | invalid_message |
| What the request needs is not there yet (no scrape, no reply kept) | not_found |
| The link cannot do it as configured (the agent without an LLM API key) | not_supported |
| The device does not answer | timeout |
| The connection is broken | disconnected |
A file or a part of one is editor: file
A gateway’s WebSocket frame is at most 64 KiB. Larger arguments go by the
gateway’s POST /api/invoke, and the gateway takes there only an action
that has a parameter with editor: "file" (ADR 0011, ADR 0028 amended
2026-11-15). So every binary parameter that can be larger than a frame
carries editor: file: a whole file (install_zip, upload, import)
and also a part of one (restore_part, a file store’s upload_part), a
component (put_artifact), a profile (profiles ▸ put). In a generic
action form it is a file picker. A string or map argument cannot take
this route: keep it under 60 KiB, or take it as a file. The gateway refuses
it with “takes no file: … arguments under 60 KiB”; when an action needs more,
give it a binary editor: file parameter beside the text one (as storage
import {data | file}). Studio and the Rust client (wyrm-agent, the MCP
connector) take the route on their own (ADR 0028 amendment 2).
An action’s arguments are one struct
An action declares its parameters and reads its arguments from one struct
with #[derive(Args)] (wyrm_link_sdk::Args, wyrm_link_api::Args for a
portable link; docs/rust-rules.md §7): X::action() is what ~meta
publishes, X::decode(args)? is what the handler gets. A wrong type, a
fraction for a whole number, a number out of its bounds, a name that is not
in the set and an unknown argument are refused with invalid_parameter and
the argument’s name.
SDK API change (2026-11-17, typing audit). A link built on the Rust SDK changes three things when it moves to this version; nothing changes on the wire:
wyrm_core::meta::EDITOR_PASSWORD,EDITOR_TEXTAREA,EDITOR_FILE,EDITOR_DATERANGE,EDITOR_DATEandEDITOR_DURATIONare gone. Usewyrm_core::meta::Editor::{Password, Textarea, File, Daterange, Date, Duration}.ParamMeta::editortakes anEditor(it took text), and the fieldParamMeta.editoris anOption<OrUnknown<Editor>>; ask withParamMeta::has_editor(Editor::File).Link::on_checktakes its arguments by value (args: Value, it was&Value), likeon_invoke.App::on_checkof a portable link is as it was.ParamSpec.editoris anOption<Editor>andParamSpec::editortakes anEditor.#[param(editor = "textarea")]of the driver derive is as it was; a name that is no editor does not compile any more.
Names people read
Keys are wire names: a node key is a path segment, an action key or a
parameter key is what plans and args use. They never change for style.
People read display (spec 02 0.2.28, ADR 0042):
- Actions and parameters. Leave
displayout when the key says it: the SDK derives one withwyrm_core::display::humanize(add_device→Add device,unit_id→Unit ID,timeout_ms→Timeout (ms)). Write one only where the derived text is wrong or thin. - Style of a
displayyou write. Sentence case, short, no dot at the end. An action starts with a verb (Add connection,Read registers,Set password,Test connection), a parameter is a noun (Poll rate (s),Unit ID). Units in brackets (Timeout (ms)). Acronyms upper case aswyrm_core::display::WORDSwrites them (URL,ID,TLS,CA,MQTT). A product name that is not inWORDS,NAMESorPHRASESgoes there. - Nodes.
NodeMeta::display(..)setsattr.display, shown instead of the key (key 12 inview=list). On the driver framework the user sets it:add_*andeditof a connection, device or point take an optionaldisplay(“Display name”), so pointt1reads “Supply temperature”. Edit without it keeps the name,""clears it; Edit withdisplayalone renames and keeps every param. A new name restarts nothing.displayis reserved: no driver param may use that name. - Enum values and
groupare wire values, not names: they stay as they are.
The wyrmd test every_action_has_a_name_people_read walks every built-in
link and fails on a text that breaks the style; the test hosts of the
messenger and history sync apps check the same.
2. What WYRM ships
- Built-in drivers (in
wyrmd):mock,mockdev(the mock on the driver framework),modbus,mqtt,agent,wasm,app(a portable link on a WASM component, section 9) andportable-echo(the example portable link, native). Install them with from Driver. snmp(built in, from Driver): SNMP v2c/v3 poller; guide snmp.md.s7(built in): Siemens S7-300/400/1200/1500 PLCs over S7comm (ISO-on-TCP); guide:docs/s7.md.- Link SDK (
crates/wyrm-link-sdk): the raw link layer, the driver framework (Connection → Device → Point withAdd/Edit/Removeactions) andprocess::runfor a link that runs as its own binary. - WASM host and WIT (
crates/wyrm-wasm-host/wit/link/point.wit): the component worldswyrm:link/pointandwyrm:link/driver. - Example links (
examples/links): a responder (themockdevdriver as its own binary), a requester (records another link’s values to CSV) and a link that is both (serves statistics of another link and writes its points), and a portable link (examples/links/portable, section 9) in its three modes.examples/packages/build.shpackages them withwyr link packand makes a repository withwyr repo add(ADR 0021). - Scheduler (
links/scheduler, ADR 0022): schedules of events that write values to points at times. Every broker runs one atwy/<site>/downstream/scheduler; it is also a portable link in the packagesscheduler(WASM) andscheduler-process. Guide:docs/scheduler.md. - Alarms (
links/alarm, ADR 0034): watches on points (boolean, out of range, staleness, quality) that raise alarm records, acknowledged, noted, kept in the broker’s store and sent to a central database through the history sync links. Every broker runs one atwy/<site>/downstream/alarm; also the packagesalarm(WASM) andalarm-process. Guide:docs/alarm.md. - Uplink (
links/uplink, ADR 0035): platform upstreams, the site’s live values to an MQTT broker (a Unified Namespace), a Sparkplug B host, ThingsBoard, Azure IoT Hub or AWS IoT Core, added with one action each as an upstream broker is. Every broker runs one atwy/<site>/downstream/uplink(uplink.netlists the platforms); it is also a portable link in the packagesuplink(WASM) anduplink-process. Guide:docs/uplink.md. - Telegram (
links/telegram) and Slack (links/slack), ADR 0039: one link per chat platform on the shared corecrates/wyrm-messenger. Recipients and message templates are nodes (text, photo, document, location, buttons, Block Kit on Slack, live values escaped for the markup), each template with its own Send action; Telegram users pair their account with a one-time code and get/get,/set,/dowithin their level, their inviter’s rights and the link’s grants. Not embedded: packagestelegram,telegram-process,slack,slack-process. Guides:docs/messenger.md,docs/telegram.md,docs/slack.md. - Modbus (
links/modbus, built-in drivermodbus, packagemodbus): a master of Modbus TCP, RTU over TCP and serial RTU devices, and a slave that serves the tree’s values to masters (ADR 0024);import_dsatakes adslink-java-modbustree. ItsScalingmultiplies where DSA’s divides: read the guide first,docs/modbus.md. - HTTP (
links/http, driverhttp): JSON REST APIs polled on the driver framework. Guide:docs/http.md. - BACnet (
links/bacnet): BACnet/IP devices (driverbacnet, packagebacnet). Guide:docs/bacnet.md. - OPC UA client (
links/opcua, driveropcua, packageopcua): nodes of OPC UA servers as points, with security and certificates. Guide:docs/opcua.md. - Prometheus (
links/prometheus, driver and packageprometheus): scrapes Prometheus / OpenMetrics endpoints and turns series selectors into points. Guide:docs/prometheus.md. - File stores (
links/s3,links/gdrive,links/webdav,links/localfs; drivers and packagess3,gdrive,webdav,localfs): a bucket, a Google Drive folder, a WebDAV collection or a directory of the host (disk, USB/SD, NFS/SMB mount) as a tree of folders and files, with Create Folder, Upload File, Download and Delete. Guide:docs/filestores.md.
3. The Install Link menu
Open sys/links and its menu Install Link ▸. Every item needs config
on wy/<site>/sys/** (the admin role of the gateway). Every item except
from Driver answers with two rows, as in DSA: success (true or false)
and message (what happened, or why it failed).
| Item | Fields | What it does |
|---|---|---|
| from Driver | Link ID, Driver (the drivers this broker hosts, as choices), Mode, Params | A built-in driver as embedded, process or external. |
| from Zip | Name, Zip (a file you choose) | Installs the package in the zip and runs it as link Name. |
| from Url | Name, Url | Downloads a package zip, then as from Zip. |
| from Git | Name, Url, Ref | Clones a repository that holds a built package, then as from Zip. |
| from Repository | Name, Package | Takes a package from the index in packages.repository, checks its SHA-256, then as from Zip. |
| from WASM | Name, Component (a .wasm file) | Wraps one component as a WASM package named Name and runs it. |
A downstream broker is not installed here: as in DSA, it adds this broker
itself and comes in through a token, allow_all_links or quarantine
(README, Two brokers; ADR 0015).
A board image can install packages without this menu: the broker installs
the packages of its seed directory (packages.seed_dir) once, on its first
start, through the same path and checks as from Zip, as the subject
broker:seed (operations.md, Seed packages; ADR 0051 §1).
Name is the new link’s id: wy/<site>/downstream/<Name>. It is a key segment
(letters, digits, ., _, -; not starting with .), and must not be the
name of an existing link, a removed remote link, a downstream site or an
operator certificate.
4. What happens when you install a package
- Fetch. from Url and from Repository download over HTTPS (plain
HTTP only to a loopback address), at most 3 redirects, 64 MiB, 90 s.
from Git runs
git clone --depth 1over HTTPS. from Zip and from WASM take the file you chose. - Unpack and check, in a temporary directory under
<data_dir>/packages/:- at most 64 MiB zipped, 256 MiB unpacked, 1000 files;
- relative paths only, no
.., no symlinks, regular files only; wyrm-link.jsonat the zip root, valid (section 6);wyrm_linkequal to the broker’s link protocol version;- the entry for this host present (
process), or the.wasmentry present (wasm); wasm: the component’s world, read from its exports (app,driverorpoint), matchesworldif the manifest has one;capabilitiesonly for anapp, within their bounds (section 9).
- Rights the package asks for. A new link of the package gets its
network allowlist (
capabilities.net) and itsrequestergrants. Without Accept Requested Rights (accept: true) such an install answerssuccess: falsewith the list (… asks for: network 10.0.5.0/24:502; read on wy/plant/downstream/mock) and installs nothing. Read the list, then install again with it on (security review, ADR 0031). An update of a package keeps the rights its links already have; rights the new version asks for beyond them need Accept Requested Rights again (section 5a). - Move into place with one rename:
<data_dir>/packages/<name>/<version>/. A failed install leaves nothing. - Record. The registry (
<data_dir>/state, a write-ahead log) stores the package: name, version, kind, entry, SHA-256 of the zip, source. The audit journal getspackage_installwith the SHA-256 and the source. - Start the link with driver
pkg:<package>:processpackage: a process link. The broker issues a certificate with CN = the link id and a link token, rebuilds the router ACL (the router restarts for about a second, and open app connections reconnect), and starts the package entry.wasmpackage: the broker copies the component to<data_dir>/packages/.wasm/<package>.wasmand starts an embedded link: adriverorpointcomponent on thewasmdriver with one connectionmain; anappcomponent on the driverappwith its capabilities as params (section 9).
- Answer
success: trueand a message such aspackage example-link 1.0.0 installed; link ex1 installed(an app adds; capabilities net none, store 1 MiB, memory 64 MiB, call 2000 ms).
A link from a package starts with an empty tree if its driver is a
framework driver: add connections, devices and points with its Add actions.
The framework keeps that tree in the link’s data directory. A connection runs
one driver action (a scan, a register read) at a time: while it is queued or
runs, another action on that connection answers busy at once. A set on that
connection answers busy during an action at level write or config (a
scan) and waits for one at level read. Send a busy call again after the
action. Sets on the link’s other connections are not delayed, except while
a set waits behind a read action: that wait holds the link for up to 5 s,
and a set whose read action outlasts 5 s answers timeout and is not
written.
5. Upgrade, reinstall, remove
| You do | Result |
|---|---|
| Install the same package (same version, same bytes) under another Name | A second link of the same package. The files are reused. |
| Install the same version with other bytes | Refused: … is installed with other content. Raise the version. |
| Install a new version (any Name that runs the package, or a new one) | An update (section 5a). Every link of the package restarts on the new version; a running link of an app component gets the new code in place instead (hot start, section 9). The old files are kept for a rollback. Links keep their devices and points. A link that does not start is named in the result (not restarted: <id> (<error>)); the health check then decides. |
sys/links/<id> ▸ Remove | The link stops and goes away. A process or external link’s id is retired: its certificate stays valid until it expires, so the id cannot be used again (ADR 0006). |
sys/packages/<name> ▸ Remove | Refused while a link runs the package. Otherwise the package files and its WASM component are deleted. |
sys/packages/<name> shows the version, kind, source and SHA-256 of each
installed package, and what section 5a adds.
5a. Update a package, roll back, restore points (ADR 0048)
One version of a package is installed, and every link that runs the package is updated together. An update is safe to try: the broker keeps what it needs to go back.
What sys/packages/<name> shows
| Value | Meaning |
|---|---|
version | The installed version. |
latest | The version in the repository index (section 12). Empty for a custom package: one the index does not list. |
update_available | latest is newer than version. Dotted numbers compare as numbers (1.10.0 over 1.9.2); a release is newer than its pre-release (1.0.0 over 1.0.0-rc1); build metadata (+…) does not count. |
changes_state | The update to latest changes the store format (below). |
state | The store format the installed version writes. |
previous | The version kept for a rollback: {version, keep_until, changes_state}; an empty map when none is kept. keep_until is unix seconds. |
last_update | The last update or rollback: {from, to, at, result, kept, new, gone, new_keys, gone_keys, reason, links, changes_state, restore_point}; an empty map before the first one. |
sys/links has the attribute updates_available beside catalog: the
number of links whose package has update_available.
sys/links/<id>/restore_points lists the link’s restore points, newest
first: [{at, version, size}] (at in unix seconds, size in bytes).
Update
| Package | Action |
|---|---|
| In the repository | sys/packages/<name> ▸ Update {version, accept, restore_point, auto_rollback_s}. version defaults to latest; an index names one version of a package, so no other can be asked for. Same download and SHA-256 check as from Repository. |
| Custom | Install Link ▸ from Zip, from Url or from Git with a package of the same name (any Name that runs it). They take accept, restore_point and auto_rollback_s too. |
restore_point (default true) and auto_rollback_s (default 120, 0 to
600) mean nothing for a package that is not installed yet. The action
answers success and message like an install; a wrong argument
(auto_rollback_s: 900) and an unknown package are errors.
What the broker does, in this order:
- Unpack and check the new version beside the old one (section 4, steps 1–2). Nothing runs it yet.
- Rights. Grants and network entries the new version asks for and a
link does not have are listed, and nothing is installed, unless
accept: true. With it, each link gets them: grants as Grant access does, network entries added to the link’snetparam (a link then starts again instead of a hot start). They stay with the link after a rollback: remove them by hand if you do not want them. - Store format. If the new version does not read the installed
state(section 6), the update changes the store format: withrestore_point: falseit is refused. - Restore points, before anything stops. For every link of the
package: its key list (
~meta?view=keysof its root, as a reader without a token sees it) and, withrestore_point, a link backup without history and without the package (backups.md §3): the link’s definition, its secrets and its private data (<data_dir>/links/<id>/data: runtime edits of a driver, a portable app’s store) as<data_dir>/restore/<id>/<UTC>.wyrm-link, with<UTC>.meta(the key list) beside it. The file is sealed for this broker with a key fromsecrets.key: it needs no passphrase and nobackups.export_secrets, and opens only on this broker (or one with its key bundle). Scratch (uploads/,tmp,*.tmp) is left out. The link still runs and owns that directory, so the broker follows no symlink in it: every entry is opened once without following links and sealed from that handle; symlinks, sockets and FIFOs are skipped and counted in the audit record, and an entry swapped for a symlink while it is copied ends the update with nothing changed. A rollback builds a new directory and swaps it in, never through a symlink. A failure here ends the update with nothing changed. - Install. The new version goes to
<data_dir>/packages/<name>/<version>/; the old directory stays, and the registry keeps it aspreviousuntilkeep_until(packages.keep_previous_days, default 7, 1 to 365). One previous version is kept: the one before it is deleted. - Restart every link of the package (hot start for an app component),
and answer. The message ends with
the links are being checked …. - Health check, in the background;
last_update.resultischeckingand its counts move while it runs. Every link must answer and have every key it had.kept,newandgonecount the keys (as<link>/<path>;new_keysandgone_keyshold the first 200 of each). It ends when:- every link is back with every key and that has not changed for 3 s
(12 s after a hot start, whose old nodes are swept after 10 s):
result: ok; auto_rollback_sis over and a key isgoneor a link did not come back: the broker rolls back by itself (result: rolled_back,reasonsays which link and how many nodes; auditupdate_rollback);auto_rollback_s: 0: nothing is rolled back. The report is made when every link answers and its keys have not changed for 3 s:ok, withgoneand areasonwhen keys are missing. A link that does not answer in 120 s makes itfailed; the new version stays.
- every link is back with every key and that has not changed for 3 s
(12 s after a hot start, whose old nodes are swept after 10 s):
While the check runs, the package and its links are the check’s: another
install of the package, sys/packages/<name> ▸ Remove and a link’s Start,
Stop and Remove answer busy. A rebuild of the router (another link was
installed, a grant changed) does not wait for the check and is not held up
by it: the check steps aside and goes on with the new router, with the time
it had left (at least 30 s). The rebuild does wait for steps 1–6 and for a
rollback. If the broker process ends during the check, the next start closes
the report as failed and the new version stays; roll back by hand if needed.
A link that was stopped before the update, or has more keys than one read
returns (10 000), has no key list: the check only waits for it to answer.
Nodes a reader without a token cannot see (restricted subtrees) are not
counted. The rule is strict: a node that goes away by itself during the
check (an ad hoc query whose time is up) counts as gone. For a link with
such nodes, update with auto_rollback_s: 0 and read the report.
Roll back
sys/packages/<name> ▸ Roll back {to} brings previous back, until
keep_until. to defaults to the kept version; no other can be named.
- Every link of the package stops.
- The registry names the kept version again (from its kept directory).
- Each link’s private data is replaced, as a whole, by its newest restore point taken at or before that update, and the link’s secrets are set as they were then (the ones the broker makes for a link stay). A link without one keeps its data and the message says so; when the update changed the store format, a link without one refuses the rollback (the old version could not read the data).
- The links start; the directory of the version that was rolled back is deleted.
last_updatebecomes{from, to}of the update that was undone, withresult: rolled_back,reason(rolled back by <who>) and its counts. Nothing is kept after a rollback:previousis empty.
During the health check, Roll back stops the check, which then rolls back
(reason: stopped by <who>).
Audit records: package_update (start, and the end with the counts),
restore_point (per link), update_rollback (with the reason and the links
whose data was restored), beside package_install.
What is not kept
- Restore points are pruned after
packages.keep_previous_days, with the previous version. A removed link loses its restore points. - A rollback takes the link’s private data and secrets from a restore
point, not its params or grants (
sys/links/<id>▸ History and Rollback keep the params). The file holds the link’s definition too: Install Link ▸ from Backup on this broker takes a restore point as any link backup (backups.md §3). - A warm standby (docs/operations.md) does not copy
<data_dir>/restore: after a takeover a rollback has the kept version and no data to restore. - A link replaced by from Backup gets a restore point first, listed and pruned with the ones of updates.
6. Package format
A package is a zip with wyrm-link.json at its root.
{
"name": "example-link",
"version": "1.0.0",
"description": "Example process link: the mockdev driver as its own binary",
"wyrm_link": 1,
"kind": "process",
"entries": {
"macos-aarch64": "bin/macos-aarch64/wyrm-example-link",
"linux-x86_64": "bin/linux-x86_64/wyrm-example-link",
"linux-aarch64": "bin/linux-aarch64/wyrm-example-link"
},
"args": []
}
{
"name": "register",
"version": "1.0.0",
"wyrm_link": 1,
"kind": "wasm",
"entry": "register.wasm"
}
| Field | Required | Meaning |
|---|---|---|
name | yes | Package name: a key segment (as a link id). |
version | yes | 1–32 of A–Z a–z 0–9 . _ - +, not starting with .. |
description | no | Shown under sys/packages/<name>. |
wyrm_link | yes | The link protocol version the package was built for (LINK_PROTOCOL in wyrm-link-sdk; now 1). Another value is refused. |
kind | yes | process or wasm. |
entries | process | Executable per host, as <os>-<arch>: linux-x86_64, linux-aarch64, macos-aarch64, macos-x86_64. One zip can carry several hosts. |
args | no | Arguments for the executable. |
requester | no | Grants the package asks for: [{"path": "wy/{site}/downstream/mock", "level": "read"}] (section 10). Name a link or flow: a whole wy/{site}/downstream or wy/{site}/dataflows is refused. |
entry | wasm | The component file. |
world | no | wasm: app, driver or point, or an app world with its version: wyrm:app@0.1.0, wyrm:app@0.2.0 or wyrm:app@0.3.0 (wyr link pack writes the version). Informational: the broker reads the world (and an app’s version) from the component and refuses a package whose world says otherwise; plain app takes any version. |
capabilities | no | A portable app (wasm app component or process): {"net": ["10.0.5.0/24:502"], "store_mb": 4, "memory_mb": 64, "call_ms": 2000} (section 9). |
state | no | The format of the link’s private data (its store, its saved tree) that this version writes: an integer from 1, default 1. Raise it when an older version could not read what this one writes. |
reads_state | no | The formats this version reads (and moves to state): 1 to 32 integers, default [state]. It must hold the package’s own state. |
state and reads_state tell the broker whether an update changes the
store format (section 5a): it does when the new version’s reads_state
does not hold the installed version’s state. A version that writes format
3 and migrates from 2 says "state": 3, "reads_state": [2, 3]; updating
from a version of state 1 to it changes the format, from state 2 it does
not. A package that names neither is state 1 and reads 1. The broker never
reads a link’s data: the numbers are the package author’s word.
Unknown fields are refused, so a typo does not pass silently.
7. Build a process package
A process package is a binary built on wyrm-link-sdk (feature
process). Its whole main is one call: process::main sets up the logs
(RUST_LOG), applies the supervisor’s limits before the runtime, and runs
process::run. See examples/links/responder or links/modbus:
fn main() -> std::process::ExitCode {
wyrm_link_sdk::process::main::<Framework<MyDriver>>()
}
The links in links/ ship this way too: modbus, mqtt and mockdev
(links/mock) build their package binaries with the feature process.
The broker starts it with a cleared environment (only RUST_LOG,
RUST_BACKTRACE, TZ, LANG, LC_ALL, PATH are kept) plus:
| Variable | Value |
|---|---|
WYRM_SITE, WYRM_LINK_ID | Site and link id. |
WYRM_ENDPOINT | The broker’s tls/ listener on loopback. A link started by hand (an external link, a package on another host) may list several endpoints, comma-separated, in the order to try: tls/10.0.0.1:7448,tls/10.0.0.2:7448 (a site with a standby broker, ADR 0036). One session per endpoint: the link connects to the first that answers, and serves it only when the site’s broker is there (the liveliness token wy/<site>/sys/broker); a router without it, or whose broker has been gone for WYRM_BROKER_WAIT_S, is left for the next endpoint. |
WYRM_BROKER_WAIT_S | With several endpoints: seconds a router without the site’s broker is kept before the next endpoint (15 by default). |
WYRM_CA, WYRM_CERT, WYRM_KEY | mTLS files: broker CA, the link’s certificate (CN = link id) and key. |
WYRM_TOKEN_FILE | The link token for hello. |
WYRM_DATA_DIR | The link’s private directory (<data_dir>/links/<id>/data, mode 0700). |
WYRM_PARENT_PID | The broker; the link exits when it is gone. |
WYRM_LIMIT_MEMORY_MB, WYRM_LIMIT_OPEN_FILES | Limits the binary applies to itself (link_limits in wyrmd.json5). |
process::run connects, says hello (and gets its params, secrets and
trusted keys), then serves the tree. The supervisor restarts a crashed link
with backoff, at most max_restarts times (10 by default).
Process mode needs a tls/ listener in wyrmd.json5.
Pack it with wyr link pack (ADR 0021)
Describe the package in the crate’s Cargo.toml; wyrm-link.json is
generated from it and from the crate’s version and description:
[package.metadata.wyrm-link]
name = "recorder" # default: the crate name
description = "Records …" # default: the crate's description
features = ["bin"] # Cargo features to build with
bin = "wyrm-example-recorder" # default: the crate's only binary
args = []
requester = [{ path = "wy/{site}/downstream/mock", level = "read" }]
state = 2 # default 1 (section 6)
reads_state = [1, 2] # default [state]
wyr link pack --manifest-path links/acme/Cargo.toml # this host
wyr link pack --manifest-path links/acme/Cargo.toml \
--target x86_64-unknown-linux-musl --target aarch64-unknown-linux-musl
wyr link pack --component register.wasm --name register --version 1.0.0
Each build is one zip, <name>-<version>-<host>.zip, in
<target dir>/wyrm-link (or --out); the same input gives the same bytes.
Unknown fields in the section are refused. --no-build packs the binaries
built before; --name packs the crate under another package name. The
format lives in wyrm-link-sdk (feature package): the broker checks a
package with the same code that wyr writes it with.
8. WASM links
A WASM link is the framework driver wasm running a component of the WIT
world wyrm:link/driver (crates/wyrm-wasm-host/wit/link/point.wit):
interface tcp {
connect: func(addr: string, port: u16, timeout-ms: u32) -> result<u32, string>;
send: func(conn: u32, data: list<u8>) -> result<_, string>;
recv: func(conn: u32, max: u32, timeout-ms: u32) -> result<list<u8>, string>;
close: func(conn: u32);
}
world driver {
import tcp;
export init: func(config: list<u8>) -> result<_, string>;
export read: func(point: list<u8>) -> result<list<u8>, string>;
export write: func(point: list<u8>, value: list<u8>) -> result<_, string>;
}
A component of the world wyrm:link/point (the same exports, no import)
runs too. Any other import is refused when the component loads.
Parameters (edit them with the connection’s, device’s and point’s Edit and Add actions):
| Level | Parameter | Meaning |
|---|---|---|
| Connection | Package (component) | The WASM package that runs (set by the install). |
| Connection | Network (net) | Where the component may connect, see below. Empty: no network. |
| Connection | Config (config) | JSON, given to init as CBOR. |
| Connection | Call ms (call_ms) | Time of one call, network included: 2000 by default, 10–10000. |
| Device | Note | Devices only group points (no ping). |
| Point | Type (value) | number (default), bool, text or any: the value type the app shows and sends on set. |
| Point | Point config (cfg) | JSON, given to read and write as CBOR. |
| Point | Poll s, Writable, Unit | How often the point is read; whether set is allowed; its unit. |
read answers with the ~val payload {0: v, 1: q, 2: t} or a bare CBOR
value. A write is not shown at once: the next read shows the result.
The network list. Entries <ip>/<prefix>:<port> or <ip>:<port>,
separated by commas or spaces: 10.0.5.0/24:502, 192.168.1.20:1502, [fd00::]/64:502.
- A WASM driver (
wyrm:link/tcp): IP literals only, in the list and inconnect. - A portable app (ADR 0026; native and process forms, and WASM components of world
wyrm:app@0.3.0, ADR 0030) may also name hosts:db.example.com:5432,*.example.com:443, intcp_connect,tls_connect, andtls_upgrade(TLS on an open connection, as PostgreSQL’s and MySQL’sSSLRequest). The host resolves the name and connects only to an address that an IP entry allows, or to a public address when the name is listed: a listed name never reaches loopback, link-local, metadata or private addresses (10/8,172.16/12,192.168/16,100.64/10,fc00::/7) by itself. A database on the LAN needs its address or range as an IP entry too (db.lan:5432, 10.0.5.0/24:5432): whoever answers for a name in DNS could otherwise point the link at any host of the LAN (security review). connectpasses when the address is inside an entry and the port is that entry’s port.- Loopback, link-local (also
169.254.169.254), multicast, broadcast,0.0.0.0/8, cloud metadata and IPv6 addresses that carry an IPv4 address (NAT64, 6to4, IPv4-compatible) pass only an entry of their own class:0.0.0.0/0does not reach the broker itself. Private ranges (10/8,172.16/12,192.168/16,fd00::/8) are ordinary for IP entries; a host name entry does not reach them (above). - Only users with
configcan change the list.
Limits per call: the call time (call_ms, also caps every network wait),
100 M fuel, 16 MiB memory, at most 4 open connections, 64 KiB per send and
per recv. Past a limit the call fails, the instance is dropped with its
connections, and the next call starts a new one.
Not available to a driver component (wyrm:link/driver): TLS, DNS,
UDP, serial ports, files, clocks, random numbers, other processes. The
component implements its protocol itself (for example Modbus TCP framing).
A portable app (section 9) gets more from its host.
Building a component. Any toolchain that produces a component for the
world above works (for example Rust with wit-bindgen and wasm-tools component new). The example components in examples/packages are written
by hand in the component text format. For a new link, a portable link
(section 9) is simpler: wyr new link --app scaffolds it and wyr link pack builds its component.
9. Portable links
A portable link (ADR 0023) is one Rust source, an App from
wyrm-link-api, that runs in three modes with the same behaviour:
| Mode | How | Built with |
|---|---|---|
| Embedded | wyrm_link_portable::Portable<App>, compiled into a broker | the crate as a dependency |
| Process | wyrm_link_sdk::process::main::<Portable<App>>(), supervised | --features process |
| WASM | a component of the world wyrm:app on the driver app | --features wasm, wasm32-unknown-unknown |
The app declares its nodes and actions in start, answers on_set and
on_invoke, and keeps its state in the host: the tree and a sealed store
in the link’s data directory. The host restarts a crashed instance with
backoff; the store stays. wyrm-link-guest (export!) makes the WASM
glue for the world wyrm:app@0.3.0 (crates/wyrm-wasm-host/wit/app3/app.wit).
What a WASM app may call (the one import wyrm:app/host; no WASI):
| World | Adds |
|---|---|
wyrm:app@0.1.0 (wit/app, frozen) | the tree (declare-node, declare-action, remove-node, update), the clock, timers, the store, subscribe, set, invoke, plain TCP (tcp-connect, tcp-send, tcp-recv, tcp-close), log |
wyrm:app@0.2.0 (wit/app2, frozen) | list and the export on-list (ADR 0025); subscribe of <prefix>/** |
wyrm:app@0.3.0 (wit/app3) | tls-connect, tls-upgrade (TLS within net, the certificate verified against the system roots or a given CA; the keys stay in the host) and random-bytes (at most 1024 bytes per call, from the OS) (ADR 0030) |
A broker runs all three. The calls go to the same host code as the native
and process forms, under the same net list, call time and bounds; a
capability not granted fails with permission_denied. A package needs
wyrm:app@0.3.0 for TLS (a history sync link to a cloud database, for
example): one built for 0.2.0 still runs, but answers not_supported to
TLS and gets no random bytes. Rebuild it with wyr link pack.
The reference link is examples/links/portable (wyrm-example-portable,
app Echo). wyrmd runs it embedded as the driver portable-echo;
examples/packages/build.sh packs it twice from the same crate:
wyr link pack --manifest-path examples/links/portable/Cargo.toml # portable-echo-1.0.0.zip (wasm)
wyr link pack --manifest-path examples/links/portable/Cargo.toml \
--kind process --name portable-echo-process # portable-echo-process-1.0.0-<os>-<arch>.zip
--name gives the process form its own package name: a broker keeps one
package per name. The e2e test one_app_three_modes runs one scenario on
the three modes and compares the results.
Cost of the modes (cargo bench -p wyrm-link-portable --bench roundtrip,
Apple M4 Max, release): one event round trip through the engine is about
0.1 µs native and 1.4 µs WASM; a WASM instance starts again after a trap in
20–30 µs (median; the backoff of 1 s, ×2, comes on top); one instance of the
example has 1.1 MiB of linear memory, about 70 KiB of it resident.
Start a crate:
wyr new link acme --app # links/acme: lib (the App), src/bin, tests
cargo test -p wyrm-link-acme # the app on the native adapter
The crate has crate-type = ["cdylib", "rlib"], the features process
and wasm, and this section in its Cargo.toml:
[package.metadata.wyrm-link]
name = "acme"
kind = "wasm" # `wyr link pack --kind process` overrides
features = ["process"] # features of a process build
capabilities = { net = ["10.0.5.0/24:502"], store_mb = 4, memory_mb = 64, call_ms = 2000 }
requester = [{ path = "wy/{site}/downstream/mock", level = "read" }]
Pack it:
wyr link pack --manifest-path links/acme/Cargo.toml # acme-<version>.zip
For kind = "wasm", wyr link pack:
- runs
cargo build --release --lib --target wasm32-unknown-unknown --features wasm(strip = trueis fine: it keeps the component type, a custom section of the module); - makes the module a component in-process (
wit-component) and checks that its world isapp; - writes one zip for every host,
<name>-<version>.zip, withworld: "wyrm:app@0.3.0"(the version the component was built for) and thecapabilitiesinwyrm-link.json.
Add the target first: rustup target add wasm32-unknown-unknown.
Capabilities, granted at install (Install Link ▸ from Zip, Url,
Git or Repository). The install result lists them, for example
capabilities net none, store 1 MiB, memory 64 MiB, call 2000 ms. They
become the link’s params:
| Capability | Default | Bounds | Meaning |
|---|---|---|---|
net | none | entries as in section 8 | Where the app may connect (tcp_connect, tls_connect). |
store_mb | 1 | 0–64 | Size of the store; 0 refuses every write. |
memory_mb | 64 | 1–512 | Linear memory of one instance (all its memories together). |
call_ms | 2000 | 1–10000 | Time of one call (also caps network waits). |
The install result and the package_install audit record list the
capabilities and the requester grants. A process package of the same
app may carry the same capabilities (wyr link pack --kind process
keeps them): they become its params too, without component.
requester grants (section 10) apply as for a process package. Later
changes go the usual ways: grants with Grant Access, the others with the
link’s update (params) or rollback. The broker checks the new params
with the driver the link runs on (app for an app component); it does not
check a process package’s params: its binary parses them when it starts.
An upgrade (a new version of the package) keeps the params of the links on
it. A running app link gets the new code in place (hot start): the
link is not stopped and its tree stays, the old instance’s stop runs (at
most 2 s), requests in flight get busy, and the new code starts at once
on the same store (audit op hot_start). Install Link ▸ from WASM with
an app component installs it with the default capabilities.
Bounds of the store: each entry counts its key and value rounded up to
4 KiB, and at least 4 KiB (a 1 MiB store holds at most 256 entries); at
most 10 000 keys; a key is 1 to 256 bytes. Over a bound, store_put fails
with resource_exhausted. A write that does not grow the store passes even
over a smaller store_mb.
Call time: a set or invoke of a portable link may take call_ms;
the broker waits at least call_ms + 1 s (and at least 5 s) before it
answers timeout. A request that was answered timeout while it waited in
the queue is not run, and one that waited in the link’s queue so long that
call_ms more would pass that bound gets timeout at once instead of
running. A
caller’s own timeout must be longer than the app’s call_ms + 1 s: the
wyrm-client waits 10 s by default (DEFAULT_TIMEOUT), so with call_ms above 9000 give the
caller a longer timeout, or it sees timeout for a call that still runs.
The broker tells the world from the component’s exports: an app
component runs on the driver app; a driver or point component on the
framework wasm driver (section 8). An app’s version comes from its import
wyrm:app/host@<version>. A manifest whose world is not the component’s
(with a version: not its version), an app world version the broker does not
run, and capabilities on a driver or point component, are refused.
10. Requester links
A link that only serves its own branch is a responder. A link can also
read and command other links (a requester, as isRequester in DSA), or
do both. Give it grants, as a role has them:
| Level | The link can |
|---|---|
list | list the nodes under the path (~meta) and see them come and go |
read | also read and subscribe to their values (~val) and call next on a sink under the path (a history sync link reading a link’s sink, ADR 0034) |
write | also set them and invoke their actions |
- Path:
wy/{site}/downstream(every link),wy/{site}/downstream/<link>[/…](one link or a part of it),wy/{site}/dataflows[/…](at mostread), orwy/{site}/storage[/…](the site’s storage, ADR 0046:readanywhere in it,writeonly on a folder below it,wy/{site}/storage/<folder>[/…], never on all of it). Plain segments only: no wildcards, no~suffixes, neversys. A grant covers the path and everything under it.configis for people only. - Storage: a link with a grant there reads and writes those values as a
flow does, e.g. a chat bot’s buttons and
/seton the points ofstorage/<bot>/cmd(grantwriteonwy/{site}/storage/<bot>/cmd,readonwy/{site}/storage/<bot>). The storage link trusts the link’s requester key only under the grant’s path. - Who grants: a package asks in
wyrm-link.json(requester, section 6); every link installed from it gets these grants, and the install message lists them (…; grant wy/{site}/downstream/mock read). Change them withsys/links/<id>▸ Grant Access{path, level}(noneremoves).sys▸ Get Permissions lists them (sourcelink), andsys/links/<id>shows them as attrgrants({path, level}) besidenet, the hosts a portable link may reach (administrators readsys; the link’s own~metanever shows them). Each change is in the audit journal (link_grant) and rebuilds the router. - How the link uses them: with its own session,
ctx.client(), andwyrm_client::WyrmClientover it. The router ACL lets the link’s certificate reach the granted paths. Forsetand actions the client signs aptokwith the link’s requester key,LinkCtx::requester_key()(the link secret.requester_key, made by the broker for a link with grants). Every link trusts that key up to the grant’s level, only under its path and only with the subjectlink:<id>:
#![allow(unused)]
fn main() {
let key = ctx.requester_key().ok_or("no grants")?;
let tokens = SigningTokens::new(key, ctx.site()).subject(format!("link:{}", ctx.link()));
let client = WyrmClient::new(ctx.client().clone()).with_tokens(Arc::new(tokens));
client.set(&point, value).await?;
}
- Embedded links run on the broker’s own session and bypass the router
ACL, so they read every branch already. A grant gives them the requester
key for
setand actions. - A requester key never opens
sys/**, never deploys a flow, and never passesconfig.
examples/links/requester (a read grant) and examples/links/both (a
write grant) show both kinds; examples/links/README.md tells how to
install them.
Streams and a slow consumer
WyrmClient::list, subscribe, subscribe_reliable and invoke return an
EventStream. A stream never holds up the Zenoh session, also when its
consumer stops reading: it keeps its own bounded buffer, and a full buffer
follows the policy of its kind. EventStream::dropped() counts what the
stream did not deliver; it stays 0 while the consumer keeps up.
| Stream | When the consumer is behind |
|---|---|
subscribe (~val) | Every sample, in arrival order, while at most VALUE_BUFFER (4096) wait: a consumer that is a little behind loses nothing. Only one more switches the stream to overflow mode until the consumer has taken what waits: one pending value per key, a newer t replaces an older one (values are state), and the replaced values count. After the stall the consumer gets the queued samples, then the latest value, quality and time of every key, in time order per key. At most MAX_PENDING_KEYS (4096) keys wait: a sample of one more key is dropped and counted, and when the consumer has taken what waits, the stream reads the stored values again, so that key still gets its newest stored value. If more than 4096 keys wait again after MAX_RESYNCS (3) such reads in a row, without the consumer catching up in between, the stream ends with resource_exhausted (“consumer too slow”). |
subscribe_reliable (QoS 2/3) | A queue of RELIABLE_BUFFER (4096) samples; the oldest beyond it is dropped and counted. |
list (~meta, liveliness) | Up to LIST_BUFFER (1024) events are held. One more discards them (counted), and the stream reads the children again and sends Refreshed, so the consumer’s view is whole again. If the owner is gone, it sends Disconnected(None) and lists again when the owner is back. |
invoke (a stream action) | Up to INVOKE_BUFFER (1024) replies are held. One more ends the stream: the held replies, then resource_exhausted (“consumer too slow”). Results are never dropped one by one. |
subscribe still subscribes before it reads the stored values (no lost
update), and per key it never hands out a sample as old as or older than
one it already gave. One stream hands out at most MAX_STREAM_KEYS
(16 384) distinct keys, gateway subscriptions included; one more ends it
with resource_exhausted (“the pattern matches more than 16384 keys”):
subscribe narrower patterns. EventStream::error() tells, after the
stream ended, which limit ended it; the gateway sends it to the
WebSocket as the stream’s error frame instead of closed.
subscribe_filtered(pattern, keep) drops the keys
keep refuses before they take room; the gateway passes the user’s read
grants, so a point the user may not read uses no memory. A consumer
that must see every sample (a historian with All Data logging, a flow
counter) gets every sample unless more than 4096 wait; only then are
intermediate samples lost, counted in dropped(); before this rule it
stopped the session instead. The gateway forwards each stream to its WebSocket and
waits there for room, so a slow socket only slows its own streams.
A stream holds its buffer only while it lives: dropping it undeclares its
subscribers, cancels the query of an invoke, and frees the buffer at
once; Zenoh’s later replies to that query are dropped on arrival.
A link that has just appeared
A link’s liveliness token can arrive before queries to the link do. When a
router connects (a downstream broker, also after its rebuild), the router
above routes the new router’s tokens about one routing-tree computation
before it routes queries to it (Zenoh 1.10.1 debounces that computation by
100 ms). In that gap every query toward it ends at once with no reply
(docs/backlog.md §6). wyrm-client follows these rules:
- A read under a link (
meta,children,resolveofwy/<site>/downstream/<link>/…) that has no reply while the link’s token is there is sent again after 25 ms, then 50, 100 and 200 ms, until it has an answer, the token is gone (disconnected), or the timeout is spent (timeout, 10 s by default, spec 05). This full timeout is only for a read that the caller asked for. A key without a link token gets two tries, so a key that no queryable serves still fails at once. - A list of the links root (
wy/<site>/downstream) lists a link only with the meta the link answered, inRefreshedand inAdded. It never lists a link with an empty default meta because of a missing reply. - A list never waits long for one link. It reads the root
~metaof each link on a task of its own, all at once, and gives each read at mostLIST_READ_WINDOW(1.5 s). The route gap is one tree computation, which Zenoh runs 100 ms after the last change, so a read in the gap answers well inside that window. The firstRefreshedcomes after at most one window, however many links are silent. AnAddedof one link never waits for another link. - A link whose token is there but which gives no reply in its window is
not listed yet. The list reads it again after 1 s, doubled up to 30 s,
each read again in a window of 1.5 s, and sends
Addedwhen it answers. If its token goes first, the list sends nothing for it.childrenof the links root leaves such a link out. - A link that answers the read with a refusal (
permission_denied, a meta that does not decode) is listed with an empty meta: the link is there, and its name is all the reader may see.
A requester that reads a peer’s own sections (wy/<d>/sys, storage,
dataflows) right after the peer connects has no link token to wait on.
Wait for downstream/<d>/connected (docs/operations.md, “Several sites”)
before the first read.
11. Logs
sys/links/<id>▸ Get Log{lines, level, filter}shows the link’s last lines: an embedded link’s lines in the broker log (they carry its id), a process link’s stdout and stderr (the last 2000 lines, also written to the broker’s stderr). An external link logs on its own host.sys/links/<id>/log_level:defaultor a level. For an embedded link it sets the level of its lines alone; for a process link it sets itsRUST_LOGand restarts it. Saved in the registry.- The broker’s own:
sys/log_levelandsys▸ Get Log (filter bylinkto see one embedded link). - A process package should log with
tracing-subscriber(as the crates inexamples/links): the level names in its lines become the level column.
12. Repository
Set packages: { repository: "https://…/index.json" } in wyrmd.json5 (as
DSA’s linkRepositoryUrl). The index is a JSON array, one entry per
package (ADR 0021):
[{ "name": "example-link", "version": "1.0.0", "description": "…",
"assets": {
"linux-aarch64": { "url": "example-link/1.0.0/example-link-1.0.0-linux-aarch64.zip", "sha256": "<64 hex>" },
"macos-aarch64": { "url": "example-link/1.0.0/example-link-1.0.0-macos-aarch64.zip", "sha256": "<64 hex>" } } },
{ "name": "register", "version": "1.0.0",
"url": "register/1.0.0/register-1.0.0.zip", "sha256": "<64 hex>" }]
A process package has a file per host in assets; the broker installs the
file of its own host and lists only packages built for it. A package that
runs on any host (WASM) has url and sha256. A url without a scheme is
relative to the index, so the repository directory can be copied or
mirrored as it is.
Make a repository with wyr repo add: it puts each zip in
<repo>/<name>/<version>/ and updates <repo>/index.json (a new version
replaces the entry, the same version adds the zip’s host). Serve the
directory over HTTPS.
wyr repo add target/wyrm-link/*.zip --repo /srv/wyrm-repo
The broker fetches the index in the background on every start and rebuild;
from Repository lists its packages when it arrives. A broker without the
network starts as usual: the field then says why the list is empty. A fetch
that fails is tried again after 5 s, then 10, 20, … up to every 5 min, so a
repository that comes up later is picked up without a restart; a fetched
index is read again every hour (a new release shows by itself). A failure
after a success keeps the index read last. Without
packages.repository the item is still in the menu and says how to set it.
An index may carry more fields than these (the official index does, §12a);
the broker ignores fields it does not know. wyr repo add and the official
index copy state and reads_state from a manifest that names them, so
sys/packages/<name>/changes_state is known before the zip is fetched (the
manifest in the zip decides at the update).
12a. Official links
links/official.json is the one list of the links this project releases
(ADR 0043): per link its id, crate, title, summary, category,
version (the crate’s), wyrm_link (link protocol), min_broker and
forms: builtin (a driver of wyrmd), wasm (one package for every
host), process (one package per host of hosts: linux-aarch64,
linux-x86_64, macos-aarch64). It holds no URLs and no hashes: CI adds
them when it publishes.
Use it on a broker. It is off by default: a broker fetches nothing until you set the repository.
packages: { repository: "official" },
"official" is the index of the manifest this broker was built with,
https://github.com/gencto/wyrm/releases/download/links-index/links-index.json.
Install Link ▸ from Repository then lists the official packages built for
this host, and installs one after it checks its SHA-256. A site without
internet access uses a mirror (docs/operations.md, Official links offline).
What a client reads. The ~meta of wy/<site>/sys/links has
attr.catalog: one map per built-in driver of this broker and per
repository package for this host, with id (driver:<code> or
package:<code>), code, link, title, summary, category,
version, form (builtin, wasm, process) and official. A driver’s
version is the broker’s, a package’s is the index’s. A driver’s title comes
from the broker’s own copy of the manifest, so built-in drivers have one
without the network. A package’s title, summary and category come only from
its index entry. A package is official: true only when the repository is
the official index ("official") and the broker’s manifest lists that
package, form and version; a package of another repository with an official
name is official: false. WYRM Studio’s Add a link reads this list.
Change it. A new official link or a new version is one edit of
links/official.json together with the crate’s Cargo.toml.
cargo test fails when they disagree (wyr test
official_manifest_matches_the_workspace, wyrmd test
official_builtin_forms_are_drivers_of_wyrmd). Check it by hand:
wyr repo check # the manifest against the workspace
wyr repo build --form wasm --out dist # every wasm form
wyr repo build --form process --target x86_64-unknown-linux-musl --out dist
wyr repo index --zips dist --tag links-v2026.11.11 --out dist/links-index.json
wyr repo index refuses a zip that is not a listed form, of another
version, kind, protocol or host, and a form or host with no zip
(--partial allows the last one, for a local run). Without --tag or
--base the URLs are relative: the zips beside the index (a mirror).
Release. Push a tag links-v<anything>. The workflow
packaging/links/release-workflow.yml (copied to
.github/workflows/links-release.yml) builds every form on GitHub runners,
publishes the zips, links-index.json, official.json and SHA256SUMS as
release <tag>, and replaces the one asset of release links-index. The
index of a release names the files of that release, so a broker that read
the index just before the next release still installs matching files.
Trust. The index is fetched over HTTPS from github.com and every zip is checked against its SHA-256. The broker checks no signature: whoever can write release assets of the repository can change what brokers install. The install still shows the network and grants a package asks for before it runs anything (§13).
Provenance. Since the release after links-v2026.11.12, the workflow
attests every zip and links-index.json (GitHub build provenance, SLSA): the
attestation names the workflow, the commit and the tag that built the file.
Check a file before you install it by hand or mirror it:
gh attestation verify example-link-1.0.0-linux-x86_64.zip -R gencto/wyrm
A file that fails this check did not come from the release workflow of this
repository. links-v2026.11.12 has no attestations; check it by SHA256SUMS.
Checking a call without running it
~act/<a>?check (spec 05 0.2.33, ADR 0047) asks a link whether it would take a call, without
running it: the SDK checks the token, the level and the arguments against the action’s meta,
then calls Link::on_check (portable links: App::on_check); both default to accepting. A
link whose actions parse their arguments further (a form, a recipient, the author’s rights)
implements it with the same parsing, so a dry run refuses what the action would refuse. Do
nothing in it: a portable link’s host commands during a check are dropped. The SDK marks every
link root with attr.check, and clients ask only links that have it. A WASM component of world
0.3.0 has no such call: its check ends at the meta.
13. Trust and security
- Who can install: users with
configonwy/<site>/sys/**. Each install and removal is in the audit journal (sys/audit) with the user, the package SHA-256 and the source. - No signing (owner decision, as in DSA). A process package is code that runs on the broker host as the broker’s user, limited by rlimits, its own data directory and the ACL of its own branch and its grants. Install only packages you trust, and read the grants an install lists.
- Fetching makes the broker connect to the URL you give. Credentials in
a URL (
https://user:token@…) are refused: the source is shown undersys/packagesand kept in the audit. from Git takes public repositories only. - WASM links run in the sandbox described in section 8.
- Threat model entries:
docs/security/threats.md(Link packages, WASM links).
14. Limits
| What | Limit |
|---|---|
| Package zip | 64 MiB; 256 MiB unpacked; 1000 files |
| A file from the app (from Zip, from WASM) | 64 MiB, sent over POST /api/invoke; two uploads at a time, one per user, 120 s to send |
| Download (from Url, from Repository) | 64 MiB, 90 s, 3 redirects, HTTPS (HTTP to loopback only) |
| Repository index | 4 MiB, 1000 packages |
| Install action | 120 s |
Update: health check (auto_rollback_s) | default 120 s, 0 (report only) to 600 s |
| Restore point | 8 GiB of private data, 50 000 files; kept packages.keep_previous_days (7, 1 to 365) |
last_update | 200 keys of new and of gone |
git clone | 120 s, depth 1, HTTPS only, needs git on the broker host |
| WASM component | 16 MiB |
WASM call, driver/point component (section 8) | call_ms (2 s, at most 10 s), 100 M fuel, 16 MiB memory |
WASM call, app component (section 9) | call_ms (2 s, at most 10 s), fuel 1 M per ms of call_ms, memory_mb per instance (64 MiB, at most 512 MiB) |
| Portable link (every mode) | 10 000 nodes, 64 actions per node, 1 000 timers, 1 000 subscriptions, 100 requests in flight, 1 000 commands per event; a set/invoke waits call_ms + 1 s |
| Portable link store | store_mb (1 MiB, at most 64 MiB); each entry at least 4 KiB (rounded up to 4 KiB); 10 000 keys; key 1–256 bytes |
| WASM network | 4 connections, 64 KiB per send or receive, IP literals only (host names: TLS of portable apps) |
15. When an install fails
| Message | Meaning |
|---|---|
no wyrm-link.json at the zip root | The manifest is missing or in a subdirectory. |
built for link protocol N, this broker speaks M | Rebuild the package with this broker’s wyrm-link-sdk. |
no entry for this host (linux-aarch64) | Add a binary for this host to entries. |
unsafe path …, symlinks are not allowed | The zip has a path that leaves its directory, or a symlink. |
… is installed with other content | Same version, different bytes: raise the version. |
link … exists and runs … | Name is taken by another link. |
process links need a tls/ listener on the broker | Add a tls/ listener to listen in wyrmd.json5. |
url: no credentials in the URL | Remove user:token@ from the URL. |
… plain http only to a loopback address | Use HTTPS. |
repository unreachable: … | The index could not be fetched; check packages.repository. |
the broker is restarting; try again | Another install rebuilt the router; repeat the action. |
the update of … is being checked | The health check of an update of this package runs (section 5a): wait for last_update, or stop it with Roll back. |
… changes the store format … | The new version does not read the installed state: update with restore_point: true. |
… asks for more than its links have: … | The new version needs new grants or network entries: read them, then update with Accept Requested Rights. |
… is on disk with other content | The version is the kept previous one with other bytes: raise the version. |
… is not in the link's net list (point error) | Add the device address and port to the connection’s Network. |
16. Try it in the demo
- Run
examples/packages/build.sh. It builds every link oflinks/official.jsonfrom this workspace in every form it lists (WASM, and a process for this host), indexes them with their titles, adds the example packages, and writes all of it toexamples/packages/out/.build.sh telegram s7builds only those official links (and the examples). Run it again after a link changes. - Run
examples/demo/run.sh. It servesout/on127.0.0.1:18070; thepackages.repositoryof all three sites points there, so Studio’s Add a link lists every link in development on every site. The list shows them without the official mark: only the released index (repository: "official") carries it. - Log in to the edge gateway (
http://127.0.0.1:8444, useradmin). - Open
wy/edge/sys/links▸ Install Link ▸ from Zip, chooseexample-link-<os>-<arch>.zip, Nameexample, Invoke. Then openwy/edge/downstream/example▸ Add Connection, Add Device, Add Point. - Install Link ▸ from WASM, choose
register.wasm, Namereg. Openwy/edge/downstream/reg/main▸ Add Device, then Add Point with Writable on. The point reads 7; write a number below 24 and read it back. The example zips are underout/<name>/<version>/, the official links’ inout/. - Install Link ▸ from Repository, Package
register, Namereg2. - Install Link ▸ from Repository, Package
portable-echo, Nameecho(the portable link as WASM), and Packageportable-echo-process, Nameechop(the same app as a process). Install Link ▸ from Driver, Driverportable-echo, Nameechoe(embedded). In each, setn, ▸ Ping, thensys/links/<id>▸ Stop and ▸ Start:ncomes back from the store andstartsgoes up by one. - Install Link ▸ from Repository, Package
recorder, Namerec(a requester), and ▸ from Urlhttp://127.0.0.1:18070/average/1.0.0/average-1.0.0-<os>-<arch>.zip, Nameavg(both). Seeexamples/links/README.mdfor what they do.
WYRM Studio on macOS needs the entitlement
com.apple.security.files.user-selected.read-only in
studio/app/macos/Runner/DebugProfile.entitlements and
Release.entitlements for the file picker, and network.client to reach a
gateway (docs/studio.md).
Modbus
The modbus link reads and writes Modbus devices as a master (Modbus
TCP, RTU over TCP, RTU on a serial port) and serves the tree’s values to
Modbus masters as a slave (Modbus TCP, RTU on a serial port). It runs
on the driver framework of wyrm-link-sdk, so its tree, actions, states
and quality work like those of every framework driver. Decisions: ADR 0004
(the driver framework) and ADR 0024 (server kinds, the slave mode).
Code: links/modbus (wyrm-link-modbus): src/lib.rs (the driver and
its params), src/codec.rs (data types, batches), src/slave.rs (slave
mode), src/dsa.rs (import_dsa), src/sim.rs (the test simulator).
The link is a built-in driver of wyrmd (Install Link ▸ from Driver,
driver modbus) and the package modbus (wyr link pack).
1. Read this first: scaling is not DSA’s
A DSA (dslink-java-modbus) user who types the same numbers into the same
labels gets wrong values without an error. Our Scaling multiplies;
DSA’s divides. Use import_dsa (section 11) to move a DSA tree: it
converts every point.
| DSA attribute | DSA meaning | Our form label | Our key (json5, ~def, export) | Our meaning |
|---|---|---|---|---|
offset | register or bit address | Offset | addr | register or bit address |
scaling | divisor: raw / scaling | Scaling | scale | multiplier: raw × scale |
scaling offset | added after the division | Scaling Offset | offset | added after the multiplication |
write of v | v × scaling − scaling offset (not the inverse when scaling offset ≠ 0) | (v − offset) / scale, rounded for integer types (the exact inverse) |
- Read: value = raw ×
scale+offset. DSA: value = raw /scaling+scaling offset. - In json5 and in an export, the key
offsetis the added offset, not the address. The address isaddr. - Example. A DSA point has
scaling = 10,scaling offset = 2, raw 250. DSA shows 27.0. The same numbers typed into our form show 250 × 10 + 2 = 2502.import_dsasetsscale = 0.1,offset = 2: the point shows 27.0, and a write of 27.0 sends raw 250. - Writes of imported points differ from DSA when
scaling offsetis not 0. A write of 27.0 sends 250 here; DSA sent 27 × 10 − 2 = 268. A device or a procedure tuned around DSA’s raw values sees other raw values after the move. - Float noise.
scale = 1 / scalingis not exact in binary: withscaling = 10, raw 3 shows0.30000000000000004where DSA showed0.3, and raw 7 shows0.7000000000000001. Trends and equality tests in flows see this. Writes to integer types are not affected: the raw value is rounded. scale = 0is refused (scale: must not be 0); DSAscaling = 0is not imported.
2. Tree and actions
wy/<site>/downstream/<link>/<connection>/<device>/[<folder>/…]/<point>
A connection is a socket or a serial port (or, for a slave, a listener).
A device is one unit id on it. A point is a value at an address. Folders
(section 10) group points below a device. Connections and devices have a
status leaf (Unknown, Connecting, Connected, Failed, Stopped, Stopped by
Parent), an error leaf while there is an error, and the diagnostics
leaves (section 12).
| Node | Actions | Level |
|---|---|---|
| link root | add_ip_connection, add_serial_connection, add_ip_slave, add_serial_slave, export (the whole tree), import (a connection branch), import_dsa, rescan (Rescan For Serial Ports) | config |
| connection | add_device, edit, remove, copy, restart, stop / start, export, import (a device branch) | config |
| master connection | scan_units | config |
| device | add_point, add_folder, edit, remove, copy, restart, stop / start, export, import (a folder branch) | config |
| master device | read_registers, read_device_id | read |
| folder | add_point, add_folder (while less than 4 deep), remove, copy, export, import (a folder branch) | config |
| point | edit, remove, copy | config |
| point value | ~set (writable points; every point of a slave) | write |
Only the action that applies is declared: stop while a node runs,
start while it is stopped. DSA puts every action at READ, so anyone
who can read can reconfigure; here a change of the tree needs config.
3. Parameters
Every default and bound below is the code’s (links/modbus/src/lib.rs).
A param with a default may be left out. Edits are checked first: a refused
edit changes nothing.
IP connection (ip_connection)
| Key | Label | Default | Bounds | Notes |
|---|---|---|---|---|
host | Host | (required) | name or IP literal; the first address it resolves to | |
port | Port | 502 | 0…65535 | |
transport | Transport Type | tcp | tcp, rtu_over_tcp | rtu_over_tcp: RTU frames (CRC, no MBAP header), as serial-to-Ethernet gateways send |
timeout_ms | Timeout (ms) | 1000 | 100…10000 | bound on each request |
write_mode | Write Mode | auto | auto, single, multiple | section 6 |
retries | Retries | 0 | 0…5 | repeats after a timeout only (section 7) |
Serial connection (serial_connection)
| Key | Label | Default | Bounds | Notes |
|---|---|---|---|---|
serial_port | Serial Port | (required) | a serial device path | /dev/ttyS*, ttyUSB*, ttyACM*, ttyAMA*, ttySC*, ttyM*, ttyMXUSB* and other numbered Linux UART names, /dev/tty.* and /dev/cu.* (macOS), /dev/serial/by-id/*, /dev/serial/by-path/*, /dev/rfcomm*; COMn on Windows. Another path is refused (some device files have side effects on open). rescan lists the ports found. |
baud_rate | Baud Rate | 9600 | 300…4000000 | |
data_bits | Data Bits | 8 | 5…8 | |
stop_bits | Stop Bits | 1 | 1…2 | |
parity | Parity | none | none, odd, even | |
timeout_ms | Timeout (ms) | 1000 | 100…10000 | |
write_mode | Write Mode | auto | as above | |
retries | Retries | 0 | 0…5 | 1 is a good value on RS485 |
Slave connections (ip_slave, serial_slave)
| Key | Label | Default | Bounds | Notes |
|---|---|---|---|---|
listen_host | Listen Host | 127.0.0.1 | ip_slave: every address the name resolves to (section 13) | |
listen_port | Listen Port | 502 | 1…65535 | ip_slave; 502 needs privileges on Linux; 0 is refused (the system would pick a port no master can know) |
master_idle_s | Master Idle Timeout (s) | 60 | 1…86400 | ip_slave: a master that sends no complete request for this long is closed (section 13) |
serial_port, baud_rate, data_bits, stop_bits, parity | as the serial connection | serial_slave |
Device
| Key | Label | Default | Bounds | Notes |
|---|---|---|---|---|
unit | Slave ID | 1 | 0…255 | 0 and 255 are ordinary units on Modbus TCP; on RTU 0 is the broadcast address and is refused (section 6) |
ping | Ping | probe | probe, fc17, none | probe reads probe_table/probe_addr, and an exception reply means alive; fc17 sends Report Server ID (often unsupported); none sends no ping |
probe_table | Probe Table | holding | coil, discrete, input, holding | |
probe_addr | Probe Address | 0 | 0…65535 | |
ping_s | Ping Rate (s) | 5.0 | 0.1…3600 | |
contiguous_only | Contiguous Batch Reads Only | false | false: a read may span gaps between points | |
max_regs | Max Registers per Read | 125 | 1…125 | 1 = each register point read alone |
max_bits | Max Bits per Read | 2000 | 1…2000 | 1 = each bit point read alone |
republish_s | Republish Unchanged Values (s) | 0 | 0…3600 | 0 = publish on a change only; DSA republishes every 60 s |
Point
| Key | Label | Default | Bounds | Notes |
|---|---|---|---|---|
table | Object Type | (required) | coil, discrete, input, holding | |
addr | Offset | (required) | 0…65535 | the value may not run past 65535 |
dtype | Data Type | u16; binary on coil and discrete | section 4 | a bit table holds binary only |
bit | Bit | 0 | 0…15 | the bit of a register for binary on input/holding |
regs | Number of Registers | 1 | 1…125 | registers of a char/varchar value |
poll_s | Poll Rate (s) | 1.0 | 0.01…86400 | |
scale | Scaling | 1.0 | not 0 | multiplier (section 1) |
offset | Scaling Offset | 0.0 | added after scale | |
writable | Writable | false | coil and holding only | |
unit | Unit | "" | shown beside the value | |
writable_by_master | Writable by Master | false | slave connections only (coil and holding) |
writable_by_mastershows in every point form but does nothing under a master connection.- Under a slave connection
poll_sandwritabledo nothing, and so do the device’sping,probe_table,probe_addr,ping_s,contiguous_only,max_regs,max_bitsandrepublish_s. Every point of a slave takes~set(section 13). - The link root takes
poll_unsubscribed(default true: points are polled all the time; false polls a group only while one of its points has a subscriber, which only process links can see: a subscription of the point or of a pattern under the link,wy/<site>/downstream/<link>/**; a wider pattern such asdownstream/**does not reach the link).
4. Data types
Register words are big-endian on the wire. A multi-word value puts the
most significant word first. _wswap reverses the word order, _bswap
swaps the two bytes in each word, _wbswap does both (all bytes in
reverse order). For the 32-bit value 0x11223344 (bytes A B C D) the
registers are:
| Order | Registers | Our suffix |
|---|---|---|
| ABCD | 0x1122 0x3344 | none |
| CDAB | 0x3344 0x1122 | _wswap |
| BADC | 0x2211 0x4433 | _bswap |
| DCBA | 0x4433 0x2211 | _wbswap |
| Ours | Registers | Value | DSA name |
|---|---|---|---|
binary | a bit, or bit bit of 1 | bool | BOOLEAN (any type on a coil or discrete table) |
bits16 | 1 | array of 16 bools, bit 0 first | BOOLEAN with bit = -1 on a register |
u16, i16 | 1 | number | UINT16, INT16 |
u16_bswap, i16_bswap | 1 | number | UINT16SWAP, INT16SWAP |
u32, i32 | 2 | number | UINT32, INT32 |
u32_wswap, i32_wswap | 2 | number | UINT32SWAP, INT32SWAP |
u32_wbswap, i32_wbswap | 2 | number | UINT32SWAPSWAP, INT32SWAPSWAP |
u32_bswap, i32_bswap | 2 | number | none |
u32_m10k, i32_m10k | 2 | hi × 10000 + lo | UINT32M10K, INT32M10K |
u32_m10k_wswap, i32_m10k_wswap | 2 | as above, words swapped | UINT32M10KSWAP, INT32M10KSWAP |
f32 | 2 | IEEE 754 | FLOAT32 |
f32_wswap | 2 | FLOAT32SWAP | |
f32_wbswap | 2 | none | |
u64, i64, f64 | 4 | UINT64, INT64, FLOAT64 | |
u64_wswap, i64_wswap, f64_wswap | 4 | the four words reversed | UINT64SWAP, INT64SWAP, FLOAT64SWAP |
bcd16 | 1 | 4 BCD digits | BCD16 |
bcd32 | 2 | 8 BCD digits | BCD32 |
bcd32_wswap | 2 | words swapped | BCD32SWAP |
char | regs | ASCII, trailing spaces and NULs cut | CHARSTRING |
varchar | regs | ASCII up to the first NUL | VARCHARSTRING |
- An unscaled integer (
scale1,offset0) publishes exactly as an unsigned or signed integer; 64-bit values never pass through a float. A scaled value publishes as a float. bits16,charandvarcharignorescale,offsetandbit(without an error).m10k:lomust be 0…9999 for the unsigned types and −9999…9999 for the signed ones, else the point showsbad/device_error. The signed types read both words asi16, as DSA does, so halves of mixed signs are accepted.- An invalid BCD digit or a non-ASCII text is a point error
(
bad/device_error), not a value.
5. Reads
- Points are grouped by
(device, poll_s). One ticker per group; a tick is skipped while the group’s last poll is still running (no pile-up). - A group’s reads are planned once per table and kept until an edit:
points merge into requests of at most
max_regsregisters ormax_bitsbits; gaps are read too unlesscontiguous_only. There is no batch switch:max_regs = 1andmax_bits = 1read each point alone. - An exception reply to one request fails only the points of that request
(
bad/device_error, the last value kept). A timeout of every request is a device miss (section 8). When some requests of a poll time out and others answer, only the points of the timed-out requests gouncertain/stale(thenbad/comm_fail), and the device staysConnected. An I/O or protocol error drops the connection; it reconnects.
6. Writes
A ~set is a request with a reply. The value is not shown before the
device has it: after a write the point is read back, and after a failed
write too (a series of writes may have stopped part-way), so the point
shows what the device holds.
| Point | auto | single | multiple |
|---|---|---|---|
| coil | FC5 | FC5 | FC15 |
| holding, 1 register | FC6 | FC6 | FC16 |
| holding, more registers | FC16 | a series of FC6, lowest address first (DSA “Never”) | FC16 |
binary bit of a holding register | FC22 mask write; if the unit answers Illegal Function, read and FC6 from then on (remembered per unit while the connection lives) | same | same |
- The read-modify-write of a bit always sends FC6, also in
multiplemode. - One FC16 carries at most 123 registers. A writable
char/varcharpoint with moreregsloads and polls, but each write of it is refused (regs: a value of N registers cannot be written). - A value outside its type’s range, of the wrong kind or longer than its
text writes nothing (
invalid_parameter). - In
singlemode a failure part-way names how many registers went out. - Unit 0 on RTU (serial and RTU over TCP) is the broadcast address,
which needs a request without a reply.
tokio-modbus0.17 always waits for a reply, so such a device sends nothing. It is accepted atadd(the device does not know its connection’s kind), then showsFailedwithbroadcast (unit 0) is not supported on RTU; a write answers the same. - A set during
scan_unitson the same connection answersbusyat once: send it again after the scan. It never waits for the scan, so it never holds the sets, actions and edits of the link’s other connections, and it is never written late. Duringread_registersorread_device_id(levelread, one bounded request each) a set waits for that one action and then runs. The wait holds the link for up to 5 s: aread_registersto a unit that does not answer, withtimeout_msabove about 4 s, outlasts it, and the set answerstimeoutand is not written. Keeptimeout_mslow on lines where operators runread_registerswhile sets arrive. - A write that waited behind a long poll until its caller stopped
waiting is dropped and answers
timeout: equipment is never written late. - A write to a device that does not answer, with a long
timeout_msandretries, and its read-back can take longer than a client waits (10 s by default). The client then getstimeout; the point still shows what the read-back finds. A write or action that arrives during a configuration change of the same connection answersbusy: send it again.
7. Timeouts, retries and RTU timing
- Every request is bounded by
timeout_ms. After a timeout it is sent again up toretriestimes; an exception or an I/O error is not retried. When every request of a poll times out, the poll counts as a device miss; when only some do, their points take the ladder alone (section 5). - After an unanswered request the transport is reopened before the next
request, on every transport. On RTU a late reply would be taken for
the next request of the same unit and function (
tokio-modbuscannot drain input). On Modbus TCP its old transaction id would fail the next request and drop the connection. A reopened serial port first waits a guard (3.5 character times, at least 50 ms, plus the rest of the unanswered request’s window), then clears its input. Each reopen counts in thereopensdiagnostic. - The cost of a dead unit: each of its timed-out requests costs one
reopen. Behind a TCP gateway with few client slots, or on a serial port
that toggles DTR on open, this can disturb the other units. Stop a dead
device (
stop) instead of leaving it polled. - Bounds on whole operations: opening the connection and a ping
4 × timeout_ms × (1 + retries); a polltimeout_ms × (1 + retries) × requests + 1 s; a write the same with its requests (one per register in a FC6 series, up to three for a bit), never less than the open bound. The 1 s covers the reopens; a poll with very many timed-out requests (about 20 or more) can still reach its bound. It is then cut and counts as a miss. - A failed connection reconnects after
1 s × 2^n, at most 60 s, ±20 % jitter, for ever. An edit of the connection closes it completely before the new one opens.
8. Quality
| What happened | Value | Quality |
|---|---|---|
| read | the value read | good |
| first poll of the device missed (timeout) | last value | uncertain/stale |
| 3 polls missed | last value; the device Failed | bad/comm_fail |
| one batch of the device timed out while its other batches answered | last value; the device stays Connected | uncertain/stale, after 3 such polls bad/comm_fail |
| the poll could not run for 3 poll periods (it waits behind a driver action, a long write series or another device’s polls that time out) | last value | uncertain/stale; good again at its next read |
| polls miss while pings answer (a probe register that answers, a span the device drops) | last value; the device Failed with the poll’s error | bad/comm_fail after 3 missed polls; it stays bad, and the device Failed, until a poll answers |
| exception reply for the point’s request, or a value that does not decode | last value | bad/device_error |
| connection down | last value; devices Stopped by Parent | bad/disconnected |
| slave: the tree’s value does not fit the point after an edit | last value | bad/config_error |
| the next good read | the value read | good |
No miss lifts a quality: a point already bad stays bad until it is
read, even when its device answers for its other points again.
There is no “zero on failed poll” (DSA writes 0, false or “” when a
poll fails). A made-up value at good quality cannot be told from a real
one. Here the last value stays and its quality says that it is old. A
consumer checks the quality first: a flow or a display that needs a value
it can act on treats uncertain/* as “may be old” and bad/* as “do not
use”, and acts on its own fallback (an alarm, a safe default) if it needs
one.
republish_s is a heartbeat: a value read again unchanged is published
again once its last publish is that old. It follows reads, so a device
that does not answer is never republished as good.
9. RS485 advice
- Set
retries = 1: one lost frame on a noisy line then does not make the points stale. - Give each unit a
timeout_msthat fits the slowest device on the line; the whole line waits for it. - Stop devices that are gone (section 7).
serial_slavemust be the only slave on its line (section 13).
10. Folders, copy, export, import
Folders
add_folder {name}on a device or folder. Folders nest at most 4 deep below the device. They have no params and noedit(no rename: ids are keys of history watches, ACL rules and flows;copyandremovemove a branch).- A point id is unique on its device, in every folder. Its key gains the folder path; polls and writes do not see folders.
- A folder may not take the name
statusorerror, a diagnostics leaf name (section 12) or an action name. removeof a folder removes everything in it, stops its polling and removes it from the stored tree.- A stored tree with a wrong folder structure stops the link from
starting (a point id twice on a device, folders deeper than 4, an
unknown key in a folder, an invalid name). This is unlike a node whose
params fail: that node stays,
Failed, and can be edited.
Copy
copy {name} on a connection, device, folder or point puts a deep copy
beside the source.
- A copied connection or device starts stopped: it does not poll a device twice, and a copied slave does not take its port.
- A folder copy gives its points new ids
<id>_<n>and replies with therenamedmap (flows and history that name copied ids need it). - A copy keeps the sealed secrets (the destination is the same).
Export and import
export on a connection, device or folder replies {json}:
{"format": "wyrm-driver-branch/1", "driver": "modbus", "kind": "device",
"name": "ahu1", "params": {…}, "enabled": true, "children": [ … ]}
- Secrets are never exported: a secret with a value is
"<not exported>". import {json, name?, overwrite?}: a connection branch at the root, a device branch on a connection, a folder branch on a device or folder.namerenames the top node;overwrite: truereplaces a node of that name. It replies{name, reenter}:reenterlists the secrets to enter again withedit(an import never takes secrets from the text). Overwrite keeps a stored secret while the node’s destination fields stay the same.- A copy or import whose save fails (a full disk) changes nothing: it
answers
internal_error(“not saved for a restart, nothing changed”), and a node it would overwrite keeps running. Run it again once the disk works. - An imported connection or device starts stopped. A folder imported into a running device is polled at once (folders have no stop).
- Bounds: 4 MiB of text, 5000 nodes, 60 s per call. The text is checked
like
add_*before anything changes. - The file format is JSON (
serde_json), as the storage export of ADR 0017: a user file, not the wire codec (principle 5 keeps CBOR on the wire).
11. Import from DSA (import_dsa)
import_dsa {json, name?} at the link root takes the nodes.json of
dslink-java-modbus (commit 0745d7d), or the DSA export of one
connection (then name is required). Every connection is checked before
the first one is imported; each imports stopped (start it after you read
the report).
The report
| Key | Holds |
|---|---|
created | the connections imported |
reenter | secrets to enter again (none in DSA Modbus) |
dropped | [{path, field, reason}]: what is not carried, or not as it was (with what was set instead) |
disabled | [{path, reason}]: nodes imported stopped that would only fail as they are |
renamed | [{from, to}]: names changed |
What is converted
| DSA | Ours |
|---|---|
scaling, scaling offset, offset | scale = 1 / scaling, offset = scaling offset, addr = offset (section 1) |
polling interval of a device (ms) | poll_s of each of its points (10 ms…24 h) |
suppress non-cov update duration (ms) | republish_s; missing: 60 s; 0 (publish on every poll): half the interval; at most 3600 s |
Timeout (ms), retries | timeout_ms (100…10000), retries (0…5) |
use multiple write commands Always / Never / As Appropriate | write_mode multiple / single / auto |
max read register count, max read bit count (connection) | max_regs, max_bits (each device) |
use batch polling false | max_regs = 1, max_bits = 1 |
| data types | section 4 |
| folders | folders; deeper than 4 go into the deepest |
| two-tier IP devices (no connection node) | one connection per host and port; the first device’s connection attributes win, and the differing ones of the others are reported |
- Units are ms.
polling interval,suppress non-cov update durationandTimeoutare stored in ms by DSA. - Missing attributes get the defaults DSA restores with, not ours:
Timeout500 ms,retries2,contiguous batch requests onlytrue,use batch pollingtrue; each is reported. A new connection made here hastimeout_ms1000 andretries0. - Not imported, reported in
droppedwith the connection’s devices: UDP and ASCII transports, parity MARK and SPACE, 1.5 stop bits (section 14). No node is made, so astartcannot run them on another framing. - Not carried, reported in
dropped:zero on failed pollset (section 8),discard data delayabove 0,max write register count(one write carries up to 123 registers), values outside our bounds (clamped), local slaves (“setup local slave”: add anip_slaveby hand), nodes DSA itself does not load. - Imported stopped, reported in
disabled: a serial connection whose port is not a serial device path on this host (COM3on Linux or macOS):edititsserial_port, thenstart; a device with unit 0 on a serial connection (section 6). - Names: characters outside
[A-Za-z0-9_.-]become_; a reserved name (status,error, a diagnostics leaf, an action name) or a taken one gets_2,_3, …; each change is inrenamed. - A name clash refuses the whole import (a connection of that name
exists): remove it, or give
namefor a one-connection file. - A failure while saving (a full disk) after some connections were imported leaves those connections imported; the error does not list them. The connection whose save failed is not imported. Look at the tree before you run the import again.
12. Diagnostics and commissioning
Diagnostics
Each connection and each device has the value leaves requests, errors,
timeouts, exceptions, reopens, last_rtt_ms and avg_rtt_ms
(moving average, α = 0.1). Every request sent counts, a retry too.
- A leaf is published when it changes, at most once every 10 s, and at
once when someone reads the node (its
~metaor a leaf’s). - A connection’s counts start at 0 when it starts or restarts, a device’s
on its own
startandrestart. A reconnect after a failure keeps them. - They are ordinary values: the historian can watch them.
Commissioning actions (master connections)
| Action | Node | Level | Args | Reply |
|---|---|---|---|---|
read_registers | device | read | table, addr, count (1…125, default 1), dtype (optional) | {words} or {bits}; with dtype also value, decoded from the first registers and unscaled (or error) |
read_device_id | device | read | FC43/14 basic objects, and the regular ones when the device’s conformity level has them: {vendor_name, product_code, revision, vendor_url, product_name, model_name, user_application_name} (others as object_<id>) | |
scan_units | connection | config | from (default 1), to (default 247), timeout_ms (20…1000, default 200) | the unit ids that answer |
- The actions run on the connection’s owner task, between polls, one
request at a time.
read_registersandread_device_idsend each request once at the connection’stimeout_ms; the action is bounded by 12 s. A device that does not support FC43 answersnot_supported. - One action at a time per connection. Another action of the same
connection, from any caller, answers
busyat once while one is queued or running; a set does duringscan_unitsand waits during a read action (section 6). So actions delay the polls of the connection by one action at most, even when areadcaller sends them without a pause. scan_unitssends one read of holding register 0 per unit. Any reply, an exception too, counts as an answer, except a gateway’s “target did not respond” or “path unavailable”. A transport error stops the scan (disconnected, naming the units found so far). Unit 0 is skipped on RTU. A scan whose worst case is above 165 s is refused: scan a smaller range or use a shortertimeout_ms.- A scan pauses the polling of its connection for its whole run:
about 62 s for 247 silent units at the defaults (up to 165 s). Point
values are not refreshed: after 3 poll periods they go
uncertain/stale(section 8), andgoodagain at the first poll after the scan. Sets answerbusymeanwhile (section 6). - A scan shows in the diagnostics: a full scan of a silent range adds about one timeout and one reopen per silent unit (about 245 for the default range). That is the scan, not a failing bus.
13. Slave mode
An ip_slave (Modbus TCP) or serial_slave (RTU) connection serves its
devices to masters. A device is a unit id served; a point is a view on the
served coils, discrete inputs, input or holding registers of its unit
(devices with the same unit, and overlapping points, share them).
Values
- A point’s value comes from the tree: every point takes
~set(level write), input registers and discrete inputs too. What a master reads is the value after its encoding (data type,scale,offset). - A master may write a point with
writable_by_master(coil and holding only). The written value is published as the point’s new value. The write is logged at info by point (never the value) and counted in the diagnostics; it is not in the site’s audit trail (no WYRM caller). - Tree sets and master requests go through one queue, so the last writer wins and the published value is what the next master read returns.
- A point the tree never set has no value. Nothing is published for it, and a master read that touches it answers exception 4 (server device failure), never a made-up 0. The served values live in memory: a fresh link process serves nothing until the tree sets values.
- A register of flags (
binarypoints with differentbiton one register): each bit is known when its point is set. A master read of that register answers exception 4 until every flag point on it is set; bits that no point reads are served as 0. A word view of a register needs all 16 bits. - A point edited to another data type gets the tree’s last value again;
when that value does not fit (50000 for an
i16), the point serves nothing and shows its old value asbad/config_erroruntil it is set again.
Answers
| Request | Answer |
|---|---|
| an address no point covers | exception 2 (illegal data address) |
a write touching a point without writable_by_master | exception 3 (illegal data value) |
a write that a point it touches cannot decode (invalid BCD, non-ASCII text, m10k low word ≥ 10000) or that makes a float NaN or infinite | exception 3; nothing changes |
| more registers or bits than one request carries | exception 3 |
| a read touching a point without a value | exception 4 |
| FC22 on a register whose points’ bits are not all known | exception 4 |
| FC8, FC17, FC23, FC43 and every function code but FC1–6, 15, 16 and 22 | exception 1 (illegal function) |
| a unit no device serves | TCP: exception 0x0B (gateway target failed to respond); RTU: no reply (another slave may have it) |
| the queue is full, or the answer takes more than 1 s | TCP: exception 6 (busy); RTU: no reply. A request still waiting is never applied late. Under heavy load a write taken just before its 1 s ends can be applied and still answer busy; a master that sends it again writes the same value again (FC5, 6, 15, 16 and 22 give the same result twice). |
| RTU broadcast (unit 0) write | applied to every served unit that takes it, no reply; counted once on the connection |
| RTU broadcast read | ignored |
- Many TCP masters send unit 255 or 0 by default. They get 0x0B unless
a device has that unit: add a device with
unit255 (or 0), or set the master’s unit id. Unit 0 is refused underserial_slave(it is the broadcast).
Exposure
- Modbus has no authentication. Anyone who reaches the port reads
every served value and writes every point with
writable_by_master. listen_hostis127.0.0.1by default. Another address is allowed: the link logs a warning atwarnwhen the listener opens and shows it asattr.warningon the connection’sstatusleaf. Open the port only to the network of the masters (firewall, VLAN).- At most 16 masters are served at once by one
ip_slave(on all its addresses together). A 17th master is closed as soon as it connects; it is served once another master disconnects. The request queue (64) bounds requests, this bounds sockets. - An idle master is closed after
master_idle_s(60 s by default) without a complete request, and its place is free again: idle or half-sent connections cannot hold all 16 places. The deadline also holds while the slave waits to send a reply: a master that sends requests but never reads the replies is closed the same way. A master that polls less often than that reconnects for each poll; raisemaster_idle_sfor it. There is no limit per source address. ip_slavelistens on every address the host name resolves to (localhost:::1and127.0.0.1). An address the host lacks, or an address family it lacks (IPv6 turned off), is left out; no address left is an error. Any other bind error fails the connection: a port in use (after 1.5 s of retries), or no permission.- Port 502 needs privileges on Linux (ports below 1024): the
connection shows
Failedwith “Permission denied”. Use a port above 1023 (for example 1502) and point the master there, or give the binaryCAP_NET_BIND_SERVICE. serial_slavemust be the only slave on its line (point to point to one master). Thetokio-modbus0.17 RTU server reads every frame on the line as a request; other slaves’ replies on a shared RS485 bus end it, and the connection fails and reopens after backoff, losing the masters’ requests meanwhile.- A copy or import of a slave connection starts stopped, so two slaves never fight for a port.
- An
ip_slavebinds its port when the connection starts. If the port is still held (for example by another process, or for a moment while the broker rebuilds its router), the connection goesFailedwith the bind error and tries again with backoff. Nothing else is needed: wait, or pick another port (ADR 0029, decision 9).
14. Not supported, and why
| What | Why | Instead |
|---|---|---|
| Modbus ASCII, Modbus UDP | tokio-modbus has neither; rare in the field | a gateway to TCP or RTU |
| parity MARK and SPACE, 1.5 stop bits | the serial library lacks them | |
rename | ids are keys: history watches, ACL rules and flows would break | copy, then remove |
| “zero on failed poll” | a dishonest value at good quality | the quality ladder (section 8) |
| a batch polling switch | max_regs = 1, max_bits = 1 | |
| RTU broadcast writes from a master (unit 0) | tokio-modbus 0.17 always waits for a reply | write each unit |
serial_slave on a shared RS485 bus | the RTU server decoder (section 13) | one slave per line |
discard data delay, max write register count (DSA) | reopen and guard after a timeout (section 7); one write carries up to 123 registers | |
| local slave over UDP (DSA) | no UDP | ip_slave |
15. Better than DSA
What the DSA link (dslink-java-modbus, commit 0745d7d) does wrong and
this link does not. These come from reading the DSA source, not from
running it.
- Rights: every DSA action is at
READ, so a read-only user can add, edit and remove connections. Here a tree change needsconfig. - Reconnects: a DSA connection that fails at link start is never retried, and a serial one reconnects once only. Here a connection retries for ever with capped, jittered backoff.
- Bit writes: DSA has no FC22 or read-modify-write: a write of a bit
in a register fails with only a log line (“not a numeric array”) and
writes nothing (
SlaveFolder.java:551-553, 635-639, 602-605). Here: FC22, or read and FC6. - Inverse scaling on write: DSA writes
v × scaling − scaling offset, which is not the inverse of its read when the offset is not 0. Here a write is the exact inverse of the read. - Writes: DSA writes fire and forget (an error goes only to the log) and the node shows the new value even when the write fails. Here a write has a reply and the point shows what the device holds.
- Non-batch polling: in DSA one missing point ends the poll cycle for every point after it. Here each point is its own request.
- Bad config: DSA silently deletes a node with incomplete attributes
at start, and a failed add or edit only logs. Here a node that fails
validation stays
Failedand editable, and a refused add or edit answersinvalid_parameternaming the field. - Edits: a DSA connection edit always stops and restores, even without a change, and does not validate. Here an edit is checked first, does nothing when nothing changed, and closes the old connection before the new one opens.
- Storage: DSA keeps node attributes in plain
nodes.json. Here the tree is sealed (ChaCha20-Poly1305) in the link’sdata_dir. - Request order: DSA polls and pings under its master lock but sends writes outside it (whether modbus4j orders them itself was not checked). Here one owner task per connection sends every request in order.
- Quality: DSA’s “zero on failed poll” publishes invented values; here the quality ladder tells the truth (section 8).
- Integers: DSA passes every value through
double, so aUINT64above 2^53 loses precision. Here unscaled integers are exact. - DSA local slave: a write from a master after a link restart throws
(the address map is not restored), an edit changes the listener only
when the transport changes (not the port), a holding write takes one
register as a raw
short, and a UDP listener is made again for each slave on the same port. Here the slave mode serves the tree’s values in one order with the tree’s sets (section 13).
16. Test without hardware
wyrm-modbus-sim(cargo run -p wyrm-link-modbus --features bin --bin wyrm-modbus-sim -- --listen 127.0.0.1:5020): a Modbus TCP device with 1000 coils, discrete inputs, input and holding registers (all 0 at start), FC1–6, 15, 16, 17, 22 and 43/14. The demo’s edge site runs one for its linkmodbus.- The probe scenario
modbus(links/probe/scenarios/modbus.json) runs on every site that has the linkmodbuswithline1/ahu1and skips the others (amodbusthat is down fails it):wyr probe modbus --gateway http://127.0.0.1:8444 --site edge. - The driver is tested against this simulator only. It is not yet
verified against
diagslaveor a real device.
BACnet link
The bacnet link reads and writes BACnet/IP devices: controllers, chillers,
air handling units, lighting and energy meters in buildings. It runs on the
driver framework (ADR 0004), so connections, devices and points have the
same actions, states and quality as every framework link
(docs/links.md).
Code: links/bacnet (wyrm-link-bacnet). The BACnet codec (BVLC, NPDU,
APDU, application tags) is in the crate (src/codec.rs): no maintained
async BACnet crate with a fitting licence covers this.
1. Run it
| Mode | How |
|---|---|
| Built in | Install Link ▸ from Driver, driver bacnet; or wyrmd link bacnet as a process link. |
| Package | bacnet (wyr link pack --manifest-path links/bacnet/Cargo.toml), binary wyrm-link-bacnet. |
2. Tree
<connection> a BACnet/IP port (one UDP socket)
<device> a BACnet device (device instance)
<point> one property of one object
The framework adds to each connection and device the status and error
leaves, the actions add_*, edit, remove, restart, stop/start,
copy, export, import and the diagnostics leaves (section 8).
3. Parameters
Connection (add_connection)
| Param | Default | Bounds | Meaning |
|---|---|---|---|
bind_host | 0.0.0.0 | IPv4 address | Local address of the UDP socket. |
bind_port | 47808 | 0–65535 | Local UDP port (0 = any). |
broadcast | 255.255.255.255:47808 | IPv4[:port] | Where Who-Is goes (the subnet’s broadcast address), when no BBMD is set. |
bbmd | empty | IPv4[:port] | Register as a foreign device at this BBMD. Empty = no registration. |
bbmd_ttl_s | 300 | 30–65535 | Time to live of the registration. The link renews it at half of it. |
apdu_timeout_ms | 3000 | 100–60000 | Bound on each confirmed request. |
apdu_retries | 1 | 0–5 | Repeats of a request after a timeout (not after an error reply). |
max_apdu | 1476 | 50–1476 | The largest reply the link accepts. |
Device (add_device)
| Param | Default | Bounds | Meaning |
|---|---|---|---|
instance | required | 0–4194302 | Device instance. |
address | empty | IPv4[:port] | Address of the device, or of its BACnet router. Empty = find the device by Who-Is. Port default 47808. |
network | 0 | 0–65534 | Network number of a device behind a BACnet router (MS/TP behind an IP router). 0 = on this IP network. Needs address and mac. |
mac | empty | 1–7 hex octets | MAC address of the device on that network (MS/TP: one octet, 0A). |
use_rpm | true | Read with ReadPropertyMultiple. false = ReadProperty per property. | |
max_apdu | 0 | 0 or 50–1476 | Largest APDU the device takes. 0 = from its I-Am (480 if it does not answer Who-Is). |
ping_s | 10 | 0–3600 | Ping period. 0 = no ping. |
republish_s | 0 | 0–3600 | Publish unchanged values again after this long. 0 = on change only. |
Point (add_point)
| Param | Default | Bounds | Meaning |
|---|---|---|---|
object_type | required | see below | Object type. |
instance | required | 0–4194303 | Object instance (4194303 = the device object’s wildcard). |
property | present_value | see below | Property to read. |
property_id | 0 | 0–4194303 | Property identifier, only with property = other. |
array_index | -1 | -1–4294967294 | Array index; -1 = the whole property. Index 0 is the array length. |
dtype | auto | see section 4 | Type of the value. |
check_status | true | Read status-flags beside present_value (section 6). | |
poll_s | 5 | 0.05–86400 | Poll period. |
scale, offset | 1, 0 | scale ≠ 0 | Read: value × scale + offset. Write: the reverse. Numbers only. |
writable | false | The point takes ~set (level write). | |
priority | 16 | 1–16 | Write priority (1 is the highest). |
unit | empty | Unit shown in ~meta. list_objects suggests one per object. |
Object types: analog_input, analog_output, analog_value,
binary_input, binary_output, binary_value, multi_state_input,
multi_state_output, multi_state_value, accumulator,
pulse_converter, integer_value, positive_integer_value,
large_analog_value, characterstring_value, loop, averaging,
calendar, command, schedule, device.
Properties: present_value, status_flags, reliability, units,
out_of_service, event_state, object_name, description,
relinquish_default, priority_array, min_pres_value,
max_pres_value, high_limit, low_limit, cov_increment,
system_status, relinquish (section 5), other (with property_id).
BACnet/IP has no secrets: no param is a secret.
4. Data types
dtype = auto takes the type from the object type and the property:
| Object type / property | BACnet tag | WYRM value |
|---|---|---|
analog_*, loop, pulse_converter, averaging: present_value, relinquish_default, limits, cov_increment | REAL | number (float) |
| large_analog_value | DOUBLE | number (float) |
binary_*: present_value | ENUMERATED inactive/active | bool |
| multi_state_*, accumulator, command, positive_integer_value | UNSIGNED | number (whole) |
| integer_value | SIGNED | number (whole, signed) |
calendar, out_of_service | BOOLEAN | bool |
characterstring_value, object_name, description | CHARACTER STRING | string |
status_flags | BIT STRING | map {in_alarm, fault, overridden, out_of_service} |
reliability, units, event_state, system_status | ENUMERATED | number |
priority_array, other, schedule and device present_value | any | dynamic: the value as sent; several values as an array; NULL as null |
An explicit dtype (real, double, unsigned, signed, enumerated,
boolean, character_string, bit_string) sets the tag for writes and
the type in ~meta. A read takes any compatible tag (an ENUMERATED for a
bool point, a REAL for a number). Other conversions:
- A REAL is shown as the shortest decimal that reads back as the same
32-bit float (
0.1, not0.10000000149011612). - With
scaleoroffset, every number is a float. - Character sets: UTF-8 (and ANSI X3.4), UCS-2, UCS-4, ISO 8859-1. Others are a point error.
- A value of another type than the point’s, or NULL on a typed point, is a point error. The link never makes up a value.
- Dates and times (dynamic points) are strings,
*for an unspecified field.
5. Writes
~seton a point withwritable = truesends WriteProperty with the point’spriority. A SimpleACK is success; the framework then reads the point back. The link never updates~valitself.- A REAL write checks the range of a 32-bit float (a float written to a dynamic point is a REAL too); a DOUBLE refuses NaN and infinity; UNSIGNED, ENUMERATED and SIGNED round and check their range. A value out of range is refused before it is sent.
- An Error, Reject or Abort reply fails the write with its text (for
example
write: property: write-access-denied). - A point that is not writable refuses the write; nothing is sent.
status_flagsand bit strings cannot be writable.- Relinquish (NULL at a priority):
- A point with
property = relinquish(on the object, withwritableand thepriorityto free) is a bool. It readstruewhile that slot of the priority array is empty. Writingtruewrites NULL to the object’spresent-valueat that priority;falseis refused. So a user with write rights frees only the priority that this point names. - The device action
relinquish {object_type, instance, priority = 16}frees any object at any priority. It needs levelconfig(a write user must not free, for example, priority 1, life safety).
- A point with
6. Errors and quality
| What happens | Result |
|---|---|
| Error PDU for one property (inside an RPM-ACK, or a ReadProperty) | That point is bad, with the class and code text, for example object: unknown-object. |
| Error or Reject for a whole RPM of several properties | Each property is read again with ReadProperty, so one bad point does not fail the others. |
Reject unrecognized-service (or Error services) for RPM | The device is read with ReadProperty from then on. |
Abort segmentation-not-supported, buffer-overflow or apdu-too-long for an RPM | The request is split in two; the limit on properties per request is kept for that poll group only (until the connection reopens), so a group of long strings does not slow the others. A single property that does not fit is a point error. |
No reply after apdu_retries | A device miss: points uncertain/stale, after 3 misses bad/comm_fail and the device failed. A poll stops at its first timeout. The last value stays. |
| One RPM of a poll has no reply, the others do | Only the points of the requests without a reply (and those after it: the poll stops) go uncertain/stale, then bad/comm_fail after 3 polls in a row; the device stays connected. A point whose status-flags request has no reply is treated the same. |
| The socket does not bind, the BBMD refuses or does not answer | The connection is failed with the reason in error; its devices are stopped_by_parent. The framework reopens it with backoff. |
status-flags with fault set (check_status) | The point is bad: status-flags: fault. |
Out-of-service and overridden values are published as good: the driver
framework has no way for a driver to mark one point uncertain. Read the
status_flags point beside the value to see them.
Invoke ids are counted per remote device, for the life of the link
process: a connection that reopens on the same port goes on from the last
id. A reply is taken only from the device’s address (and network) with the
request’s invoke id and (in an ACK or Error) its service; a reply that
comes after its timeout is dropped and counted in late_replies.
7. Discovery and bindings
- Who-Is. The connection action
who_is {low?, high?, wait_ms = 3000}(level config) sends a global Who-Is (through the BBMD when one is set) and returns every I-Am in the window:[{instance, address, network?, mac?, vendor_id, max_apdu, segmentation}].lowandhighgo together;wait_msis 100–30000. The list keeps at most 10 000 answers (8 addresses per instance); past that the list is cut and the link logs a warning. Narrowlow…highthen. - A device without an address is bound by its own Who-Is: the link
waits the whole window, exactly one address must answer, and that address
must answer a read of the device’s
object-identifier. The binding stays until the device stops answering; an I-Am that comes at another time does not change it. Two answers for one device are refused (set its address). For devices with writable points, prefer a fixedaddress. - A device with an address gets one unicast Who-Is per connection open
to learn its max APDU (when
max_apdu = 0). Its I-Am ends the wait; a device that does not answer costs oneapdu_timeout_msand gets 480. Setmax_apduto skip the Who-Is. - Forwarded-NPDU (from a BBMD) names the original source. The link
believes it only from the configured
bbmd; from anyone else it is dropped. So on a subnet with its own BBMD, I-Ams from other subnets (forwarded by that BBMD) are dropped whilebbmdis empty:who_isand devices without an address then see the local subnet only. For devices on other subnets, setbbmd(foreign-device registration) or give each device a fixedaddress. - BBMD. With
bbmd, the link registers as a foreign device when the connection opens and renews the registration before a request once half of the TTL has passed.
8. Actions and diagnostics
| Node | Action | Level | Result |
|---|---|---|---|
| connection | who_is {low?, high?, wait_ms} | config | Devices that answered (section 7). |
| device | list_objects {limit = 1000} | config | {objects: [{object_type, instance, name, units?, unit?}], count, truncated}. Reads object-list whole, or index by index when it does not fit one reply, then the names (and the units of analog objects). Stops at 160 s with truncated = true. |
| device | read_property {object_type, instance, property = present_value, array_index?} | read | {value} as sent; for units also units (name) and unit (symbol). property takes the point names and object_list, object_identifier, object_type, vendor_identifier, max_apdu_length_accepted, segmentation_supported, number_of_states, or a number. |
| device | relinquish {object_type, instance, priority = 16} | config | NULL at that priority (section 5). |
Diagnostics on each connection and device: requests, errors,
timeouts, exceptions (Error, Reject and Abort replies), late_replies,
rpm_splits, who_is_sent, last_rtt_ms, avg_rtt_ms.
Ping: ReadProperty of the device object’s system-status. Any reply, an
Error too, means the device is alive.
9. Simulator
src/sim.rs (feature sim) is a BACnet/IP device on its own UDP port:
device object, analog-input 1, analog-value 1 (commandable), binary-input
1, binary-value 1 (commandable), multi-state-value 1 (commandable),
integer-value 1, large-analog-value 1 (DOUBLE), calendar 1 (BOOLEAN),
characterstring-value 1, a writable out-of-service on analog-value 1 and
a BIT STRING in vendor property 1000 of analog-input 1. It answers Who-Is (unicast I-Am),
ReadProperty, ReadPropertyMultiple and WriteProperty with priorities, can be
a BBMD for one foreign device, or sit behind a router. Failure modes:
silence, dropped requests, slow replies, Reject, RPM not supported, an Error
for a whole RPM, a small max APDU (aborts), a second (forwarded) I-Am and a
wrong device identifier.
Run it for a demo:
cargo run -p wyrm-link-bacnet --features bin --bin wyrm-bacnet-sim -- \
--listen 127.0.0.1:47809 --instance 1234 --extra 20
Analog-input 1 moves between 18 and 26 °C once per second. A link tree for it (the link on its own port, Who-Is straight to the simulator):
{connections: {sim: {
bind_host: "127.0.0.1", bind_port: 47810, broadcast: "127.0.0.1:47809",
devices: {d1: {instance: 1234, address: "127.0.0.1:47809",
points: {
temp: {object_type: "analog_input", instance: 1, unit: "°C"},
sp: {object_type: "analog_value", instance: 1, writable: true, priority: 8},
sp_free: {object_type: "analog_value", instance: 1, property: "relinquish",
writable: true, priority: 8},
}}}}}}
Tests: cargo test -p wyrm-link-bacnet --all-features (codec unit tests on
byte sequences of the standard’s examples; the driver against the
simulator).
10. Known limits
- Discovery needs the BACnet port. Many devices answer Who-Is with a
broadcast I-Am to port 47808 (the simulator answers unicast). Keep
bind_host = 0.0.0.0andbind_port = 47808for discovery: on Linux a socket bound to one address does not get the subnet’s broadcasts. - One BACnet stack per port. Another BACnet program on the host that
holds UDP 47808 makes the connection
failed(bind … address in use). Use anotherbind_portand a fixedaddressfor each device then. - Devices on other subnets need
bbmdor a fixedaddress: withoutbbmd, forwarded I-Ams from a local BBMD are dropped (section 7). - The BBMD registration is renewed only while requests flow: a connection without devices lets it lapse.
- No segmentation: long replies are split into more requests; one property longer than the max APDU cannot be read.
- Not supported: BACnet MS/TP on a serial port (a routed MS/TP device behind a BACnet/IP router is supported), COV subscriptions (follow-up), alarms and events, BACnet/SC, BACnet/IPv6, the link’s own device object (it does not answer Who-Is or ReadProperty).
- The unit comes from the
unitparam, not from the device:~metais fixed by the params.list_objectsandread_propertyshow the device’s units to copy. - UDP sources can be forged on the network. The link checks addresses, invoke ids and identities, but BACnet/IP has no authentication: keep the BACnet network separate (BACnet/SC is not supported).
OPC UA link
The opcua link is an OPC UA client. It reads and writes the Value
attribute of nodes on OPC UA servers (PLCs, SCADA servers, machines) and
shows them as points in the WYRM tree. It runs on the driver framework
(ADR 0004): the framework gives the tree, the add_* / edit / remove /
restart / stop / start actions, the states, polling, read-back writes
and the quality ladder. The link does the OPC UA part.
Code: links/opcua (wyrm-link-opcua), on async-opcua 0.19 (MPL-2.0;
its crypto is RustCrypto, so no OpenSSL). Driver name: opcua, embedded in
wyrmd or as a process (wyrmd link opcua, package opcua).
1. Tree
wy/<site>/downstream/<link>/
<connection>/ one session to one endpoint
status, error (framework) state and error text
requests, errors, … (framework) diagnostics
~act/get_endpoints
<device>/ a group of nodes, optional namespace URI
status, error, requests, …
~act/browse
<point> the Value attribute of one node
2. Parameters
Connection (add_connection)
| Param | Default | Bounds | Meaning |
|---|---|---|---|
endpoint | required | opc.tcp://host:port/path; no user info, query or fragment | The endpoint URL. The link connects to this URL even when the server advertises another host or port (NAT, relays). |
security_policy | None | None, Basic256Sha256, Aes128_Sha256_RsaOaep, Aes256_Sha256_RsaPss | Security policy of the secure channel. |
security_mode | none | none, sign, sign_and_encrypt | none goes only with policy None; sign/sign_and_encrypt only with the others. |
identity | anonymous | anonymous, username, certificate | The user identity token. |
username | "" | required for username | A user identity to another host needs security mode sign or sign_and_encrypt (section 5). |
password | "" | secret | |
user_cert_pem | "" | PEM | The X.509 user certificate (certificate). |
user_key_pem | "" | secret, PEM | Its RSA key. Sealed by the framework like every secret; the link gives it to the library in memory and never writes it to a file. |
cert_pem | "" | PEM | The application instance certificate. Empty: the link makes a self-signed one (section 5). |
key_pem | "" | secret, PEM | Its RSA key. With cert_pem or not at all. Written to a plain-text file while the connection opens (section 5). |
server_cert_pem | "" | PEM | Pin: only this server certificate is trusted. |
trust_on_first_use | false | Trust the first server certificate seen, then only that one. | |
application_uri | urn:wyrm:opcua:client | a URI | The client’s application URI (in the certificate it makes). |
session_timeout_ms | 60000 | 10000…3600000 | Requested session timeout. Keep-alive reads run every third of it (1…30 s). |
request_timeout_ms | 5000 | 100…60000 | Bound on each service request (Read, Write, Browse). |
connect_timeout_ms | 15000 | 1000…120000 | Bound on one open (GetEndpoints, CreateSession, ActivateSession) and on one ping. |
Secret params are entered in add_connection and edit, kept sealed by
the framework in the link’s data_dir, and never shown in ~meta,
export, replies or logs. endpoint, security_policy, security_mode,
server_cert_pem and trust_on_first_use are destinations: an edit that
changes one drops the stored secrets unless it gives them again.
Device (add_device)
| Param | Default | Bounds | Meaning |
|---|---|---|---|
namespace_uri | "" | Points without ns=/nsu= are in this namespace. The link finds its index by URI on every connect, so a server restart that reorders its namespaces does not break the points. Empty: namespace 0. | |
max_nodes_per_read | 500 | 1…10000 | Nodes per Read request. The link lowers it to the server’s MaxNodesPerRead (read at connect, i=11705). |
ping_s | 5.0 | 0.1…3600 | Ping period: a Read of Server_ServerStatus_State (i=2259). |
Point (add_point)
| Param | Default | Bounds | Meaning |
|---|---|---|---|
node_id | required | ns=2;s=Line1.Temp, ns=3;i=1001, nsu=<uri>;s=…, g=<guid>, b=<base64>, or s=… / i=… in the device’s namespace. | |
poll_s | 1.0 | 0.01…86400 | Poll period. Points with one period on one device are read together. |
writable | false | ~set allowed. | |
scale | 1.0 | not 0 | Value = raw × scale + offset (numbers and arrays of numbers). |
offset | 0.0 | ||
unit | "" | ~meta.unit. |
A point without a namespace part uses the device’s namespace_uri; give
ns=0;i=… for a standard node on such a device. nsu=<uri>;… is always
found by URI; ns=<n>;… is taken as it is.
3. Values
Reads ask for the Value attribute with maxAge 0. The type comes from the
server; ~meta.type is dynamic, or number when scale/offset is set.
| OPC UA | WYRM |
|---|---|
| Boolean | bool |
| SByte, Int16, Int32, Int64 | integer (Int, or UInt when ≥ 0) |
| Byte, UInt16, UInt32, UInt64 | UInt |
| Float, Double | float |
| String | string (null string → null) |
| DateTime | RFC 3339 string |
| ByteString | bytes |
| LocalizedText | its text |
| NodeId, ExpandedNodeId, QualifiedName, Guid | their text form |
| StatusCode | UInt (the code) |
| arrays of these | array (a matrix is flattened) |
| empty | null |
| ExtensionObject, XmlElement, DataValue, DiagnosticInfo | point error (“not supported”) |
With scale/offset a number becomes a float. Without them integers stay
integers.
4. Writes
~set on a point with writable: true:
- The link reads the node’s DataType and ValueRank once per session (and the current value when the DataType is not a built-in type). The target type is that DataType (Duration → Double, UtcTime → DateTime), else the type of the current value; ValueRank 0 or 1 means an array, and ValueRank 2 or more (a matrix) is refused: multi-dimensional writes are not supported.
- It undoes
scale/offset: raw = (value −offset) /scale. - It converts and refuses lossy conversions with
invalid_parameterand a clear text: a fraction to an integer type (only rounding noise of a few ulps, relative to the number, counts as a whole number, so that the scaled write 21.5 / 0.1 = 214.99999999999997 lands on 215; a real fraction such as 600000000.4 is refused at any size), a number out of the type’s range, an integer above 2^53 to Double or above 2^24 to Float, a nonzero number too small for Float (it would become 0), a number to Boolean or String, a text that is not RFC 3339 to DateTime. Other numbers to Float are rounded to f32 precision (0.1 is not exact in either type, so an exact round trip cannot be the rule). - It sends one Write. A non-Good result (BadNotWritable, BadUserAccessDenied, BadTypeMismatch, …) is the write’s error. There is no optimistic update: the framework reads the point back.
A point with writable: false refuses ~set before any request.
5. Security and certificates
The link’s PKI is in its data_dir, in opcua-pki/:
| Path | Content |
|---|---|
own/app-<hash>.der, private/app-<hash>.pem | The generated application certificate (self-signed, RSA 2048, 10 years, SAN: application_uri and this host’s names) and its key (mode 0600). Made on the first open of a connection without cert_pem when the link has a data_dir (also for policy None, which does not use it), then reused. One per application_uri. |
own/user-<hash>.der, private/user-<hash>.pem | cert_pem and key_pem as files, named by a hash of both: the library reads its certificate and key from files when it builds the client and the secure channel and for ActivateSession; it keeps the key in memory for channel renewals. The key file is plain text (not sealed), mode 0600 in the 0700 private/ inside the 0700 data_dir. The files exist only while a connection that uses them opens (seconds): they are removed once the session is active or the open failed or was cut, and at link start the link removes any that a stopped process left. The sealed secret stays the only lasting copy. |
servers/<url hash>-<trust>/trusted, …/rejected | Server certificates per endpoint and trust mode. <url hash> is of the endpoint with a lower-case host, the port (4840 when absent) and the path (/ when empty), so opc.tcp://PLC1:4840 and opc.tcp://plc1/ are one endpoint; localhost and 127.0.0.1 are two. <trust> is pin-<hash>, tofu or strict. |
servers/<url hash>-tofu/tofu-ok | Marks that a session was made with the certificate in trusted/ (first use done). |
The thumbprint (SHA-1, hex, as server trust lists show it) of the
application certificate is logged at info when the certificate is made
and on every secured open that fails (with the server’s thumbprint), and
it is in the connection’s error leaf when a secured open fails. The
advice in error comes from the server certificate of GetEndpoints and
the link’s trust store, so it stays the same on every retry:
- The link does not trust the server certificate (and, with
trust_on_first_use, it is not a first use any more):… the server certificate (thumbprint 9C02…) is not trusted: pin it (server_cert_pem) or set trust_on_first_use. Before the first session withtrust_on_first_use, the link would trust the server, so a refusal gets the advice for the client certificate (the last item). - The link trusts it, but a host name, application URI or validity check failed (BadCertificateHostNameInvalid, …): both thumbprints.
- Otherwise the server refused this client, for example:
connect to opc.tcp://plc1:4840/: BadSecurityChecksFailed; if the server does not trust this client yet, trust its application certificate (thumbprint 5A1F…) on the server. Trust that certificate on the server (most servers put it in a “rejected” list) and the next attempt connects.
Server certificate trust (for policies other than None; the library
always checks the certificate’s validity time, host name and application
URI):
| Setting | What is trusted |
|---|---|
server_cert_pem (pin) | Only that certificate. |
trust_on_first_use: true | The first certificate with which a session was made at that endpoint, then only it. |
| neither (the default) | Nothing: the open fails with the server certificate’s thumbprint in error (… is not trusted: pin it (server_cert_pem) or set trust_on_first_use). |
Trust on first use:
- First use counts only after a session was made. The library stores an
unknown certificate in
trusted/before it checks its host name, validity and application URI; until the store hastofu-ok, the link emptiestrusted/before each attempt, so a refused (or cut) first attempt does not pin a certificate that never validates. - To reset it (the server got a new certificate), delete the directory
<data_dir>/opcua-pki/servers/<url hash>-tofu/while the link runs or is stopped; the next open is a first use again. Or set a pin. A failed secured open logs the store’s path atinfo(store=…). - The first answer at the endpoint is trusted without a check of who
sent it. Until a session was made, every attempt is a first use: also
every retry while the server still refuses this client during
commissioning. With a
usernameorcertificateidentity, each such attempt sends that identity to whoever answers (a man in the middle at any time before the first session gets the password). Pin the server certificate for a connection with a user identity on a network you do not control.
Rules:
- A secured connection needs the link’s
data_dir. Without one only policyNoneworks (the error says so). - A user identity (
usernameorcertificate) to another host needs security modesignorsign_and_encrypt;add_connection/editrefuse it with modenone, and only loopback takes one without. The link does not trust a server’s user token policy that says it encrypts the password on a channel without security: that policy comes from GetEndpoints, before any checked channel, so a man in the middle could name its own certificate. - On a
signchannel (signed, not encrypted) to another host, the user token policy protects the identity. Before ActivateSession the link refuses a token policy with security policy None (a password in clear text, an X.509 token without a signature) or a deprecated or unknown one; it takes an empty one (it means the channel’s policy, OPC UA Part 4, 7.41) and Basic256Sha256, Aes128_Sha256_RsaOaep, Aes256_Sha256_RsaPss. On every secured channel the link writes the channel’s policy into an empty token policy before the open: the library would read an empty one as None for an X.509 token and send it without a signature (a password it encrypts either way). The token policy comes from GetEndpoints (the library offers no hook between CreateSession and ActivateSession), so whatever a man in the middle writes there ends in a refusal or in a password encrypted with a strong policy to the server certificate that CreateSession checked.sign_and_encrypthas no such limit: the channel encrypts the token. key_pemmust be the key ofcert_pem, anduser_key_pemthe key ofuser_cert_pem(a test signature must verify with the certificate);add_connection/editrefuse another key.endpointis parsed with the URL parser the library connects with, and a URL with user info (opc.tcp://a@b/), a query or a fragment is refused, so the host the link checks (loopback rules above) is the host it connects to.- Keys are written only into
private/, created with mode 0700; a key file is created with mode 0600 (the generated key is made in memory and written by the link, never by the library with default permissions). - A connection with security mode
noneto another host shows a warning on itsstatusleaf (attr.warning): values travel unsigned and unencrypted.
6. Errors and quality
| What happens | Result |
|---|---|
| The item’s status is Good | the value, quality good |
| The item’s status is Uncertain or Bad (BadNodeIdUnknown, BadSensorFailure, UncertainLastUsableValue, …) | that point bad/device_error, its last value kept; other points and the device are not affected |
| The namespace URI of a point is not on the server | that point bad/device_error |
One Read request of a poll times out (request_timeout_ms) while another answers | the points of that request uncertain/stale, then after 3 misses in a row bad/comm_fail, last value kept; the device stays connected and its other points good |
| Every Read request of a poll times out | device miss: uncertain/stale, then after 3 misses the device failed and its points bad/comm_fail |
| The session or connection is lost (closed socket, BadSessionIdInvalid, BadSecureChannelClosed, …) | the connection failed with error, its devices stopped_by_parent, points bad/disconnected; the framework reopens with backoff (1 s … 60 s, ±20 %) |
| A whole Read answers BadTooManyOperations (the server enforces a lower limit than it publishes, or publishes none) | the link halves the nodes per Read for this session and reads that batch again in halves; a single node that still gets it fails bad/device_error with the remedy in the text (lower max_nodes_per_read) |
| Another service fault for a whole Read | those points bad/device_error |
Uncertain values: the framework has no uncertain quality for a fresh
value from a driver, so an Uncertain status fails the point like a Bad one.
The link never shows a non-Good status as good.
Late replies: the library matches replies to requests by request handle, so a reply that comes after its timeout is dropped and never taken for a later request.
Reconnect: the library’s own reconnect is off. A lost session ends the
session’s event loop; the next call answers “transport”, and the framework
opens a new session, which reads the namespace array and MaxNodesPerRead
again. Secure channel renewals run inside the session and do not drop
values.
7. Actions
| Node | Action | Level | Args | Result |
|---|---|---|---|---|
| device | browse | config | node (default i=85, the Objects folder; without ns= it is namespace 0), depth 1…5 (default 1), limit 1…5000 (default 500) | [{node_id, namespace_uri, browse_name, display_name, node_class, data_type}], hierarchical references forward, breadth first, each node once; data_type for variables (built-in name or node id) |
| connection | get_endpoints | config | — | [{endpoint_url, security_policy, security_mode, security_level, user_tokens, server_certificate_thumbprint}] |
Both are commissioning actions at level config: browse walks the
server’s address space (not only the configured points) on the
connection’s owner task, so polls of that connection wait behind it (at
most 30 s); get_endpoints opens a second TCP connection.
8. Simulator
wyrm-opcua-sim (feature bin) is an OPC UA server made with the same
library:
cargo run -p wyrm-link-opcua --features bin --bin wyrm-opcua-sim -- --port 4840
It serves, in namespace urn:wyrm:opcua-sim:data, folder Line1 under
Objects: Double (counts up every 100 ms), Int32 (42), Boolean,
String, Array (Double[]), Time, Bytes, writable Setpoint
(Double), Small (Int16), Text and Flags (Int32[]), Locked
(read-only on the server), Bad (BadSensorFailure), Uncertain
(UncertainLastUsableValue), Slow (7.0; tests make its reads wait) and
writable Matrix (ValueRank 2). Line1 also has a second reference to
Int32. Endpoints at /: None, Basic256Sha256 Sign and
SignAndEncrypt; users anonymous and operator / sim-password. Its
certificate is made in --pki (default opcua-sim-pki) on the first start.
--strict-clients makes it refuse client certificates it does not know.
A link on it (wyrmd.json5 link params):
{
connections: {
sim: {
endpoint: "opc.tcp://127.0.0.1:4840/",
devices: {
line1: {
namespace_uri: "urn:wyrm:opcua-sim:data",
points: {
counter: { node_id: "s=Line1.Double" },
setpoint: { node_id: "s=Line1.Setpoint", writable: true },
},
},
},
},
},
}
The tests (links/opcua/tests/sim.rs) also use sim::relay, a TCP relay
in front of the server that goes silent, slow or drops connections, or
(security None only) hides the server’s MaxNodesPerRead from the client
while the server still enforces it.
9. Known limits
-
No subscriptions. OPC UA Subscriptions with MonitoredItems (values pushed by the server) are not used: the driver framework has no way for a client connection to deliver values between polls. The link polls with batched Read requests. (Framework hook needed.)
-
Uncertain is shown as bad (section 6). (Framework hook needed: a quality with a fresh value.)
-
No certificate leaf. The thumbprint is in the
errorleaf, the log and the PKI files, not in a leaf of its own: the framework has no driver-owned leaf on a connection. (Framework hook needed.) -
Only the Value attribute; no other attributes as points, no
IndexRange. -
No Method calls, History Read, events and alarms, or node management.
-
Structured values (ExtensionObject) and XmlElement are not decoded.
-
Writes to other than built-in types (an enumeration DataType with no current value, structures) are refused.
-
No reverse connect, no discovery server (FindServers), no
opc.httpsor WebSockets transports, onlyopc.tcp. -
Security policies Basic128Rsa15 and Basic256 (deprecated) are not offered; CA-signed trust chains and CRLs are not checked beyond the library (a pin or trust on first use trusts one certificate).
-
The application certificate is not renewed before it expires (10 years).
-
RUSTSEC-2023-0071 (“Marvin”,
rsa0.9 underasync-opcua): a timing side channel in RSA decryption; no 0.9 release fixes it. Where the link uses its private key:- Decryption (the exposed operation): the response to every
OpenSecureChannel, on the first open and on every token renewal, in
both
signandsign_and_encrypt(the library decrypts before it checks the signature). Anyone who answers at the endpoint, or a man in the middle, can send ciphertexts, before the server certificate is checked in CreateSession, at one per open (the framework’s backoff limits the rate). A trusted server also sets the renewal rate through the token lifetime it grants. - Signatures (not exposed by this advisory): the OpenSecureChannel request, the client signature of CreateSession/ActivateSession, the X.509 user token signature.
- Not on the client: the decryption of user tokens is server side (the simulator only).
What is at stake is the application key, which every connection with the same
application_urishares; with it an attacker can act as this client to every server that trusts it. The practical risk is low (remote timing, one query per handshake). Give each trust domain its ownapplication_uri(so its own key), or its owncert_pem/key_pem. Basic128Rsa15 (PKCS#1 v1.5 padding, the classic padding oracle) is not offered. Whencargo auditorcargo denyruns in CI, this advisory needs a tracked ignore with this rationale (neither runs in CI today). - Decryption (the exposed operation): the response to every
OpenSecureChannel, on the first open and on every token renewal, in
both
-
The bound on one poll is (
request_timeout_ms+ 1 s) per Read request. It counts the requests with the server’sMaxNodesPerReadas the last open of that endpoint read it (the framework’spoll_timeoutgets no transport, so the link keeps that limit per endpoint in the process).
S7 link (s7)
The s7 link reads and writes Siemens S7-300, S7-400, S7-1200 and S7-1500
PLCs over S7comm on ISO-on-TCP (TCP port 102). It uses absolute addresses
(DB10.DBW6, MW20, IB0, …), not the symbols of a TIA Portal project.
It runs on the driver framework (ADR 0004), so the tree, the add_* /
edit / remove / restart / stop / start actions, the states,
polling, read-back writes and the quality ladder work as in the other
framework links (see links.md).
The protocol codec is part of the crate (links/s7/src/proto.rs): TPKT
(RFC 1006), COTP class 0 (ISO 8073), and the S7 PDUs Setup Communication,
Read Var, Write Var and the SZL read. The link uses no third-party S7
library.
Prepare the PLC
- S7-1200 / S7-1500: in the CPU properties, Protection & Security →
Connection mechanisms, turn on Permit access with PUT/GET communication
from remote partner. Without it, the CPU answers every read and write
with error
0x8104, and the link reportsPLC error 0x8104: this service is not implemented on the module … enable "Permit access with PUT/GET communication". - Data blocks on S7-1200 / S7-1500: absolute addressing needs a
non-optimized DB. In the DB properties, turn off Optimized block
access, then compile and download again. An optimized DB answers
item error
0x05(address out of range) or0x03(access not allowed), and the link shows the code and this hint. - S7-300 / S7-400: no settings are needed. A protection level that needs a password blocks writes; this link cannot send the password (see Limits).
Tree
<link>/
<connection>/ one PLC (Add Connection)
status, error framework leaves
requests, errors, timeouts, exceptions, late_replies, last_rtt_ms, avg_rtt_ms
<device>/ one CPU (Add Device)
status, error, diagnostics leaves as on the connection
<folder>/… optional folders (add_folder)
<point> one value (Add Point)
A connection is one TCP connection to one CPU (rack and slot). A device is the CPU on that connection. Normally a connection has one device. More devices on one connection read the same CPU; you can use them to group points with different device settings (ping, batching, clock offset).
Connection parameters
| Param | Display | Default | Bounds | Meaning |
|---|---|---|---|---|
host | Host | (required) | IP address or host name of the PLC or its CP | |
port | Port | 102 | 0…65535 | ISO-on-TCP port |
rack | Rack | 0 | 0…7 | rack of the CPU |
slot | Slot | 1 | 0…31 | slot of the CPU: 1 for S7-1200/1500, 2 for S7-300, as configured for S7-400 |
conn_type | Connection Type | pg | pg, op, s7_basic | connection resource of the remote TSAP (PG 0x01, OP 0x02, S7 basic 0x03) |
timeout_ms | Timeout (ms) | 2000 | 100…10000 | bound on each request and on each step of connecting |
pdu_size | PDU Size | 480 | 240…960 | the PDU size the link asks for; the PLC can agree on less |
The remote TSAP is conn_type << 8 | rack * 32 + slot (rack 0, slot 1, PG:
0x0101). The local TSAP is 0x0100. The link cannot set other TSAPs.
The PLC agrees on the PDU size in Setup Communication. Typical values are
240 (S7-300, S7-1200) and 480 or 960 (S7-400, S7-1500). The connection
action Connection Info (connection_info) shows the agreed size; see
Actions. The link refuses a PLC that agrees on less than 96
bytes.
Device parameters
| Param | Display | Default | Bounds | Meaning |
|---|---|---|---|---|
ping | Ping | szl | szl, read, none | szl: read SZL 0x0011 (module identification); read: read 1 byte at ping_address; none: no ping |
ping_address | Ping Address | MB0 | an address | the byte that ping = read reads |
ping_s | Ping Rate (s) | 5 | 0.1…3600 | time between pings |
max_gap | Max Gap (bytes) | 4 | 0…256 | points of one area and DB at most this many bytes apart are read as one item; 0 = only touching ones |
max_items | Max Items per Read | 20 | 1…20 | items in one Read Var request |
tz_offset_min | PLC Clock Offset (min) | 0 | −720…840 | the offset of the PLC clock from UTC, for DATE_AND_TIME values |
republish_s | Republish Unchanged Values (s) | 0 | 0…3600 | publish an unchanged value again after this time; 0 = only on a change |
Any answer to a ping means that the CPU is alive, an error answer too (for example a CPU without the SZL list). Only no answer counts as a miss.
Point parameters
| Param | Display | Default | Bounds | Meaning |
|---|---|---|---|---|
address | Address | (required) | see below | where the value is |
dtype | Data Type | auto | see below | the data type |
poll_s | Poll Rate (s) | 1 | 0.01…86400 | time between reads |
scale | Scaling | 1 | not 0 | published = raw × scale + offset (numbers only) |
offset | Scaling Offset | 0 | ||
writable | Writable | false | the point takes ~set (not on inputs, timers and counters) | |
unit | Unit | “” | shown in ~meta.unit |
The link checks the address and the data type when you add or edit a point.
An error tells what is wrong, for example address "DB10.DBX4": a bit address needs a bit number (X4.3, M1.0) or dtype: REAL takes 4 bytes; use a D address (DBD, MD).
Addresses
Siemens notation; case and spaces do not matter.
| Area | Bit | Byte | Word | Double word |
|---|---|---|---|---|
| Data block | DB10.DBX4.3 | DB10.DBB5 | DB10.DBW6 | DB10.DBD8 |
| Bit memory | M1.0, MX1.0 | MB1 | MW20 | MD24 |
Inputs (I or E) | I0.1, IX0.1, E0.1 | IB0 | IW2 | ID4 |
Outputs (Q or A) | Q1.0, QX1.0, A1.0 | QB1 | QW2 | QD4 |
| Timers | T5 | |||
Counters (C or Z) | C3, Z3 |
The DB number is 1…65535. The byte offset is 0…2097151 (the limit of the S7 address field). A timer or counter number is 0…65535.
An address can carry its type after a colon: DB10.DBD8:REAL,
DB1.DBW0:INT, DB1.DBB20:STRING[16], DB1.DBB30:DT, C3:COUNTER.
Data types
The type comes from the :TYPE suffix, else from dtype, else from the
width letter: X → BOOL, B → BYTE, W → WORD, D → DWORD, T →
S5TIME, C → WORD. If the suffix and dtype are both set, they must be
the same type.
dtype | Suffix | Bytes | Width | Published as |
|---|---|---|---|---|
bool | BOOL | 1 bit | X | bool |
byte | BYTE | 1 | B | number 0…255 |
word | WORD | 2 | W, B, T, C | number 0…65535 |
dword | DWORD | 4 | D, B | number 0…4294967295 |
int | INT | 2 | W, B | number −32768…32767 |
dint | DINT | 4 | D, B | number |
real | REAL | 4 | D, B | number (the shortest decimal of the float: 0.1, not 0.10000000149) |
lreal | LREAL | 8 | B | number |
string | STRING[n], STRING | n + 2 | B | text; STRING without a length is STRING[254] and reads 256 bytes: a short string near the end of a DB then fails with item error 0x05, so give the real length |
s5time | S5TIME | 2 | W, B, T | seconds (number) |
time | TIME | 4 | D, B | seconds (number; TIME is DINT milliseconds) |
date_and_time | DATE_AND_TIME, DT | 8 | B | RFC 3339 text |
counter | COUNTER | 2 | C | number 0…999 (3 BCD digits) |
Conversions:
- All values are big-endian, as the PLC stores them.
- BOOL is one bit of a byte (
.0….7). - STRING[n]: byte 0 is the maximum length, byte 1 the actual length,
then the characters, one byte each. The link reads them as Latin-1. An
actual length above the maximum is an error. If
nis less than the PLC’s maximum, the text is cut toncharacters. - S5TIME: bits 12–13 are the time base (10 ms, 100 ms, 1 s, 10 s), bits 0–11 three BCD digits. Range 0…9990 s. A write picks the finest time base that holds the value and rounds to it (12.34 s → 12.3 s).
- TIME: signed milliseconds, published in seconds.
- DATE_AND_TIME: 8 BCD bytes (year 1990…2089, month, day, hour,
minute, second, milliseconds, weekday). The PLC clock has no time zone;
the link writes it with the device’s
tz_offset_min(Zfor 0, else+02:00and so on). A write takes any RFC 3339 time (Zor an offset,Tor a space between date and time) and converts it to the PLC’s zone. The link computes the weekday. - Timers (
T5): an S5TIME value in seconds, or withdtype = wordthe raw timer word. - Counters (
C3): withdtype = word(the default) the raw counter word; withC3:COUNTERthe word read as 3 BCD digits. Not verified on hardware: S7 documentation says the counter value is BCD in some places and binary in others. Usewordand compare with the PLC before you usecounter. scaleandoffsetapply to number types only. An unscaled integer is published as an integer, a scaled one as a float.
Reads
The framework polls each group of points with the same device and poll rate. The link:
- merges the points of one area and DB into spans when they are at most
max_gapbytes apart (timers and counters:max_gap / 2numbers); - cuts a span that is longer than one reply item into several items
(a reply item carries at most
PDU − 18bytes); - packs the items into Read Var requests. A request carries at most
max_itemsitems, and both the request (12 + 12 × itemsbytes) and the reply (14 + Σ (4 + item bytes, rounded up to even)) must fit the agreed PDU.
The plan is kept until the group changes or the PDU size changes.
Each item has its own return code. An error code fails only the points of that item. If a merged item fails, the link reads its points again, each one alone, in the same poll. Only the points that fail alone get the error. A point that fails alone while a neighbour of the same item reads is read alone from then on (until the group changes). So one bad address does not fail its neighbours. When all points of the item fail alone too (for example a DB that is missing for a moment during a download), there is nothing to isolate: the item stays merged and is read as one again when the DB answers. A header error (the PLC refuses the whole request, for example PUT/GET off) fails all points of that request alike; the link does not read them one by one, and merging stays as it is.
Writes
A write is one Write Var request for the point. There is no optimistic update: the framework reads the point back and publishes what the PLC holds.
- BOOL: the bit transport size, one bit. The other bits of the byte do not change, and there is no read-modify-write of the byte.
- STRING: the link writes the actual-length byte and the characters,
from the second byte on. It never writes the maximum-length byte, so the
PLC’s declared length stays. A text longer than
n, or with characters outside Latin-1, is refused. The PLC does not stop a byte write at the string’s end, so the link first reads the maximum-length byte and refuses a text longer than the PLC’s declared length (text of 15 characters does not fit the PLC's STRING[10]); nothing is written then. A write is bounded by the PLC’s length, whatevernsays. - A value longer than one request (a long STRING on a small PDU) goes
in parts of at most
PDU − 28bytes, the last part first. A STRING’s actual-length byte is in the first part, so it goes last: if a part fails, the PLC keeps the old length, and the old text stays valid up to it. The error says how many parts went out, and the read-back shows what the PLC holds. - A value out of range for its type is refused (
invalid_parameter), and nothing is sent. - Points on inputs (
I), timers and counters cannot be writable. A point that is notwritablerefuses~set.
Errors and quality
| What happens | Error class | Result |
|---|---|---|
| I/O error, closed socket, COTP disconnect, garbled frame | transport | the connection goes to failed with its error leaf; its devices go to stopped_by_parent; the framework reconnects with backoff (1 s … 60 s) |
no reply within timeout_ms | device | the points of that request and of the requests after it in the poll (not sent) go to uncertain/stale, after 3 misses in a row to bad/comm_fail; the last value stays. If other requests of the poll were answered, the device stays connected; if none was, the device takes the same ladder |
header error in the reply (PLC error 0x…) | point | the points of that request are bad; the device stays connected |
item return code (PLC item error 0x…) | point | that point only is bad |
Item return codes: 0x01 hardware fault, 0x03 access not allowed,
0x05 address out of range, 0x06 data type not supported, 0x07 data
type inconsistent, 0x0A object does not exist (no such DB). Write
replies and the read actions return the text of the code.
Each request carries a PDU reference. A reply that comes after its
timeout has the reference of an earlier request; the link drops it and
counts it in late_replies. It is never taken for a later request. A
request cut while it was being sent leaves the TCP stream in an unknown
state; the next request then reports a transport error and the link
reconnects.
Diagnostics (on the connection and on each device): requests, errors
(I/O or protocol errors), timeouts, exceptions (replies with a header
error or a failed item), late_replies, last_rtt_ms, avg_rtt_ms.
Actions
Driver actions run on the connection’s owner task, between polls. They
need the connection to be connected. read_szl and read_address send a
request and hold the connection while they wait (polls of the connection
wait too), so they are commissioning actions at level config.
| Node | Action | Level | Arguments | Result |
|---|---|---|---|---|
| connection | connection_info (Connection Info) | read | {pdu_size, max_amq_calling, max_amq_called, local_tsap, remote_tsap, late_replies} | |
| device | read_szl (Read SZL) | config | id (number), index (number, 0) | {id, index, record_length, records, more}, and order_code for SZL 0x0011 |
| device | read_address (Read Address) | config | address, dtype (optional) | {value, dtype}, unscaled |
read_szl reads the first part of an SZL list only (more = true if the
PLC has more parts). read_address reads any address once, without adding
a point; use it to check an address or the PUT/GET setting.
Simulator
wyrm-s7-sim is an S7 server for tests and demos (feature bin). It
answers COTP connect, Setup Communication, Read Var, Write Var and SZL
0x0011 over DB1 (1000 bytes), DB2 (100 bytes), M, I and Q (1024 bytes
each), and 256 timers and counters.
cargo run -p wyrm-link-s7 --features bin --bin wyrm-s7-sim -- --listen 127.0.0.1:10102
cargo run -p wyrm-link-s7 --features bin --bin wyrm-s7-sim -- --pdu 240 # a small PDU
In the demo values, DB1.DBW0 (INT) counts up once per second,
DB1.DBD2:REAL is 21.5, DB1.DBX6.0 toggles, DB1.DBB8:STRING[16] is
“WYRM” and MW10 is 1234. Then add a link with driver s7 and this tree:
{
connections: {
plc1: {
host: "127.0.0.1", port: 10102, rack: 0, slot: 1,
devices: {
cpu: {
points: {
counter: { address: "DB1.DBW0:INT", poll_s: 1 },
temp: { address: "DB1.DBD2:REAL", unit: "°C" },
name: { address: "DB1.DBB8:STRING[16]" },
mw: { address: "MW10", writable: true },
},
},
},
},
},
}
The tests (links/s7/tests/sim.rs) use the simulator in process
(wyrm_link_s7::sim, feature sim) with its failure modes: an address
out of range (item error 0x05, a missing DB 0x0A), a small PDU (a request
or reply that does not fit is answered with header error 0x8500 and
counted), silence, one late reply, closing the connection, PUT/GET
refused (0x8104) and no SZL (0xD401).
Limits
What S7 PLCs have that this link does not do:
- S7comm-plus (the protected protocol of S7-1200 from firmware 4 and of S7-1500) and symbolic access: optimized DBs and tag names cannot be read. Use non-optimized DBs and PUT/GET, or the OPC UA server of the CPU.
- Protection-level password of S7-300/400 (userdata function group 5): a CPU that needs a password for writes refuses them.
- Other TSAPs: the local TSAP is always 0x0100 and the remote TSAP comes from rack, slot and connection type. LOGO! and S7-200 with their own TSAPs are not supported.
- Routing through a CP to another subnet, and several CPUs on one connection.
- Writes to inputs, timers and counters; peripheral areas (
PI,PQ), V memory (S7-200), WSTRING, DTL, DATE, TIME_OF_DAY, CHAR as its own type. - Program upload or download, block info, PLC run/stop, alarms and cyclic data (userdata push functions).
- More SZL parts after the first in
read_szl. - A status leaf with the agreed PDU size: the framework has no hook for a
driver leaf on a connection, so the size is in
connection_info. - The link is tested against its simulator only. It has not been checked against a real CPU yet; the counter encoding in particular is not verified.
SNMP link
The snmp link polls SNMP agents — switches, routers, UPS, PDUs, printers,
controllers — like any other device. It speaks SNMPv2c (community) and
SNMPv3 (USM: HMAC-SHA-1 or HMAC-192-SHA-256, AES-128 privacy). It runs on
the driver framework (ADR 0004): the tree, the add_* / edit / remove /
restart / stop / start actions, states, scheduling, read-back writes
and the quality ladder are the framework’s, as in every framework link
(links.md).
Install it with Install Link ▸ from Driver, driver snmp (embedded or
process), or as the package snmp (wyr link pack, binary
wyrm-link-snmp).
1. The tree
downstream/<link>/
<connection> Add SNMP v2c | Add SNMP v3 (one agent address)
status, error the framework's state leaves
requests, errors, timeouts, exceptions, late_replies, rejected_replies,
undecodable_replies, last_rtt_ms, avg_rtt_ms
▸ Reset Engine Clock (snmp_v3 only, config; §7)
<device> Add Device (one view of the agent: a v3 context or a v2c community)
status, error, diagnostics as above
▸ Walk
<point> Add Point (one OID)
A connection is one agent (host:port, one UDP socket). A device is one view
of it: usually one device per connection with the defaults; add more when the
agent shows other data under another v3 context or another v2c community (some
switches select a VLAN by community).
2. Parameters
Connection snmp_v2c (Add SNMP v2c)
| Param | Default | Bounds | Meaning |
|---|---|---|---|
host | — (required) | Agent host name or address. The addresses of a name are tried in turn, IPv4 first, then IPv6, while the bound of opening the connection (the lookup and two addresses) has room; the error lists each address tried. | |
port | 161 | 1…65535 | Agent UDP port. |
community | — (required, secret) | Community string. Entered in add_snmp_v2c/edit, kept sealed; never shown. | |
timeout_ms | 1000 | 100…10000 | Bound on each request. |
retries | 1 | 0…5 | Repeats of a request after a timeout. |
Connection snmp_v3 (Add SNMP v3)
| Param | Default | Bounds | Meaning |
|---|---|---|---|
host, port | —, 161 | 1…65535 | As above. |
user | — (required) | 1…32 characters | USM user name. |
auth_protocol | sha256 | sha1, sha256 | usmHMACSHAAuthProtocol (HMAC-SHA-96) or usmHMAC192SHA256AuthProtocol (RFC 7860). |
auth_passphrase | — (required, secret) | ≥ 8 characters | Authentication passphrase. |
priv_protocol | aes128 | aes128, none | AES-128-CFB (RFC 3826), or none for authNoPriv. |
priv_passphrase | "" (secret) | ≥ 8 characters with aes128 | Privacy passphrase. |
engine_id | "" | 5…32 octets in hex (0x8000…, 80:00:… or plain) | Optional: the agent’s snmpEngineID, as net-snmp -e. When set, a discovered engine id that is another fails the connection, and a report naming another engine never starts a rediscovery. |
timeout_ms, retries | 1000, 1 | as above |
The engine id is discovered when the connection opens (RFC 3414 §4) and the
keys are localized for it. The agent’s boots and time come from authenticated
messages only, never from the unauthenticated discovery report. The link keeps
them across reconnects (per agent address, engine id and user, for as long as
the link runs); the first time, they come from the authenticated answer to
the first request, sent at boots/time 0/0: a usmStatsNotInTimeWindows
report, or, from an agent that skips that check, a response whose values are
not used (the request is sent again). noAuthNoPriv is not offered.
host, port, user, the protocols and context are the destination of the
secrets: an edit that changes one of them drops the stored secrets unless it
gives them again (the framework’s rule).
Device
| Param | Default | Bounds | Meaning |
|---|---|---|---|
context | "" | SNMPv3 contextName; empty = the default context. | |
community | "" (secret) | v2c only: this device’s community instead of the connection’s; empty = the connection’s. | |
max_varbinds | 20 | 1…100 | Scalars per GET request. |
max_repetitions | 25 | 1…100 | Rows per GETBULK request (table columns, walk). |
max_pages | 20 | 1…200 | GETBULK requests per table column and poll. |
ping | true | Ping the device. | |
ping_s | 10 | 0.1…3600 | Ping period (s). |
republish_s | 0 | 0…3600 | Publish an unchanged value again after this long (0 = on a change only). |
Point
| Param | Default | Bounds | Meaning |
|---|---|---|---|
oid | — (required) | ≤ 128 arcs | Numeric OID: 1.3.6.1…, .1.3.6.1… or iso.3.6.1… (stored as 1.3.6.1…). For table_column: the column’s OID. |
kind | scalar | scalar, table_column | scalar: GET of oid. table_column: the cell oid.index, read by GETBULK. |
index | "" | dotted numbers | Row index of a table_column point (3, 1.4.192.0.2.1); refused on a scalar. |
conv | auto | see §3 | Value conversion. |
scale, offset | 1, 0 | scale ≠ 0 | value = raw × scale + offset, numeric conversions only. |
unit | "" | Shown in ~meta.unit. | |
poll_s | 10 | 0.01…86400 | Poll period (s). |
writable | false | The point takes ~set (SET). | |
set_type | integer | integer, octet_string, gauge32 | SMI type of a SET. |
Rules checked when a point is added or edited: table_column needs an
index; scale/offset only on auto and numeric conversions; a writable
integer/gauge32 point uses auto or gauge, a writable octet_string
point auto or string.
3. Conversions
conv | Takes | Gives |
|---|---|---|
auto | any | INTEGER → integer; Counter32/Gauge32/TimeTicks/Counter64 → unsigned; OCTET STRING → text (UTF-8 without trailing NULs, else hex de:ad:be:ef); IpAddress → 192.0.2.1; OBJECT IDENTIFIER → 1.3.6.1…; Opaque → bytes. ~meta.type is dynamic. |
counter32 | Counter32 | the raw counter |
counter64 | Counter64 or Counter32 | the raw counter |
rate_per_s | Counter32 or Counter64 | (new − old) / seconds between two polls; see below |
gauge | Gauge32, INTEGER, TimeTicks, counters | the number |
timeticks_s | TimeTicks | seconds (hundredths / 100) |
string | any but NULL | text, as auto gives it |
ip | IpAddress, OCTET STRING of 4 or 16 octets | IPv4 or IPv6 text |
mac | OCTET STRING of 6 octets | 00:1b:21:0a:0b:0c |
Numbers are scaled with scale/offset. With scale = 1 and offset = 0 an
integer stays an integer; otherwise the value is a float.
rate_per_s: the first poll gives no value (a rate needs two samples). A
Counter32 that goes down wrapped once (new + 2³² − old); a Counter64 that
goes down was reset, and that poll gives no value. A plan with rate points
also reads sysUpTime.0; when it goes down the agent restarted, and every
rate starts again without a value. The time base is the link’s clock: the
time each answer came (the answer of the request that carried that varbind,
not the end of the poll). scale = 8 turns octets per second into bits per
second.
A Counter32 can wrap more than once between two samples, and the link cannot
see it: a 1 Gbit/s ifInOctets wraps every 34 s. So a Counter32 sample older
than max(2 × poll_s, poll_s + 5 s) (after an outage) gives no rate; the rate
starts again from the new sample. Keep poll_s well below the wrap time, and
use the 64-bit ifHC* counters for links faster than about 100 Mbit/s. A
counter that is cleared without an agent restart (clear counters, an
interface reset) looks like one wrap to the link: one rate up to
2³² / seconds. The link does not read ifCounterDiscontinuityTime.
A varbind of the wrong type for its conversion is a point error (conv mac: cannot convert a counter32), never a made-up value. A varbind whose value
does not fit its own type (an INTEGER of 5 octets or of none, a Counter32
above 2³², a known agent bug) is a point error too (“malformed INTEGER
encoding from the agent”); the other varbinds of that answer keep their
values.
4. Reads
- Scalars of one device and poll period are read with GET, at most
max_varbindsper request. - Cells of a table column are read with GETBULK, from just below the first
wanted row, jumping over the gaps between wanted rows, at most
max_pagesrequests per column and poll. Rows the column does not have are point errors (noSuchInstance). - An answer with
tooBigsplits the request in two; a single varbind that is still too big is a point error. An error status with an index (genErr) fails that point and reads the others again. noSuchObject,noSuchInstanceandendOfMibViewfail that point only.- A request without an answer (after its retries) fails the points it asked for, and the poll goes on with the next request: an agent whose handler for one OID hangs does not stop the other points. Two requests in a row without an answer stop the poll; every point not read yet misses with them.
Every request has a new request id (v3: and msgID). Only an answer with one of
the ids of that request is taken; an answer that comes after its timeout is
dropped and counted in late_replies. A timeout sends the request again (a new
id) up to retries times. Two more counters show datagrams the link drops:
| Counter | Counts |
|---|---|
late_replies | Answers to an earlier request (their id is not one of this request’s). A late v3 answer is authenticated first, and its boots and time move the link’s notion of the agent’s clock forward. |
rejected_replies | v3 messages that are not taken, late ones included (they are authenticated before their id is matched): the MAC does not verify, the authoritative engine id or the user name is another, the security level is lower than the request’s (no MAC, or not encrypted for an authPriv request), it does not decrypt, it is outside the time window (§7). |
undecodable_replies | Datagrams that are not an SNMP message the link reads (framing, header or PDU malformed). |
5. Writes
A writable point takes ~set: the link sends one SET of set_type and the
framework reads the point back; the value is never updated before the
read-back. A number is scaled back ((value − offset) / scale, rounded) and
must fit the type (INTEGER: 32 bits signed, Gauge32: 0…4294967295). The
agent’s refusal (notWritable, wrongType, noAccess, authorizationError,
…) is the error of the ~set and changes nothing. A read-only point refuses
the write. Only INTEGER, OCTET STRING and Gauge32 are written.
6. Errors and quality
| What happens | Result |
|---|---|
noSuchObject / noSuchInstance / endOfMibView, a conversion that does not fit, a value whose encoding does not fit its type, an error status for one varbind | That point bad; the device stays connected. |
No answer within timeout_ms × (1 + retries) to any request of a poll | A device miss: points uncertain/stale, after 3 misses bad/comm_fail and the device failed. |
| No answer to one request while others of the poll are answered | The points of that request uncertain/stale, after 3 polls in a row bad/comm_fail; the device stays connected. |
authorizationError on a poll or ping | The device failed: “authorizationError: the agent’s access control (VACM) refuses this request; check the community, user or context”. |
v3 report usmStatsWrongDigests, usmStatsUnknownUserNames, usmStatsUnsupportedSecLevels, usmStatsDecryptionErrors | When the connection opens: the connection failed with the reason (e.g. “the agent refused the authentication digest (usmStatsWrongDigests): check auth_protocol and auth_passphrase”); later: the device fails with it. |
v3 report snmpUnknownContexts | The device’s context is not one the agent has: the device fails with “the agent does not know this context (snmpUnknownContexts): check the device’s context”. Another report names its OID in the error. |
v3 report usmStatsNotInTimeWindows (authenticated) | The agent restarted or its clock moved: the link takes the agent’s boots/time (forward only) and sends again once. |
| v3 answer outside the time window (lower boots, or more than 150 s behind) | Dropped (rejected_replies): a replay. When no answer is taken the device misses with “the agent’s answers are outside the time window …”. An agent whose boots counter went down is refused (RFC 3414) until Reset Engine Clock runs on the connection; a connection that opens with only such answers stays connected, says so in attr.warning of its status, and its devices fail. |
v3 report usmStatsUnknownEngineIDs with another engine id | The engine id changed (a replaced device): the connection reopens and discovers it again. The report is not authenticated, so this happens at most once per 30 s per agent (the wait doubles up to 15 min while such reports keep coming); within the wait the device fails with “… not discovering it again for N s”. |
v3 report usmStatsUnknownEngineIDs with the engine id the link has | Not authenticated and not true (a forged or broken report): the device fails with it; the connection stays. |
| ICMP port unreachable (nothing listens on the port) | The connection drops; it reopens with backoff and stays failed with error while nothing answers; its devices are stopped_by_parent. |
| No answer when the connection opens | The connection failed (“no answer from the agent …”). |
A wrong v2c community gets no answer at all: agents drop such requests without a reply (RFC 3584). It shows as an agent that does not answer, not as an authentication error.
The connection opens with a GET of sysUpTime.0 (v3: after engine discovery)
with the connection’s community and the default context: UDP has no
connection, so this is how an agent that cannot be reached fails the
connection. The device ping is the same GET in the device’s view; any answer,
noSuchObject included, means alive.
7. Security
- The community and both passphrases are secret parameters: entered in
add_*/edit, kept sealed in the link’sdata_dir, never in~meta,export, replies or logs. No datagram is ever logged (a v2c datagram holds the community). Bootstrap params inwyrmd.json5are plain text in that file: prefer the actions. - SNMPv2c sends the community and the values in clear text. A v2c connection
beyond loopback says so in
attr.warningof itsstatusleaf; usesnmp_v3withaes128beyond a trusted network. A v3 connection withpriv_protocol: nonebeyond loopback says that values travel unencrypted. - An answer to a v3 request is taken only when its MAC verifies, its authoritative engine id is the agent’s, its security level is the request’s and it is in the time window (RFC 3414 §3.2 7b): lower boots, or a time more than 150 s behind the link’s notion of the agent’s clock, is a replayed old message and is dropped. The clock moves forward only, and only on authenticated messages, late ones included (RFC 3412 §7.2: authentication and timeliness come before the msgID); the unauthenticated discovery report sets the engine id, never the clock. The values of a response to a request sent before the clock is known are never taken (it may be a replay): only its boots and time, and the request is sent again.
- Discovery is not authenticated: an on-path attacker can redirect the
requests to another agent that has the same user and passphrases (common
across a fleet) and relay them; every check then passes, and that device’s
values show as this one’s. Set
engine_id(the agent’ssnmpEngineID, e.g. fromsnmpget -v3 … 1.3.6.1.6.3.10.2.1.1.0) to refuse any other engine. A replaced device then needs its new id inengine_id. - The clock is kept across reconnects, so a forced reconnect (a forged ICMP
error or report) does not open a window for replays. Reset Engine Clock
(connection action,
config, v3) forgets it; run it only when the agent really lost its boots counter (it was reinstalled or reset), or its engine time went back within the same boots (an agent that takes its engine time from the wall clock, after an NTP step): both are refused the same way. RFC 3414 expects the keys to change after the boots go down: change the passphrases then (on the agent and here), because messages recorded in the old boots period stay valid against a link whose clock was just reset. When it succeeds, the connection reconnects once at its next request (its devices showstopped_by_parentfor a moment), learns the clock again, and the warning on itsstatusclears. A connection restart does not forget it: to the link a restart is one more open, like any reconnect, and a reconnect can be forced from the network. The kept clock is in the link’s memory: restarting the link process (orwyrmdfor an embedded link) forgets it too. - Walk is a
configaction: it reads any subtree of the agent with the link’s credentials (interface, ARP, vendor tables beyond the configured points) and costs the agent up to hundreds of requests, so areadorwritecaller is refused.
8. Walk
Device action Walk (walk {oid, max = 500}, level config, at most 60 s):
GETBULK from oid while the answers stay below it, at most max (1…10000)
entries → [{oid, type, value}], type the SMI type (integer,
octet_string, counter32, …) and value as auto converts it. Use it to
find the OIDs and row indexes for points. The walk holds the connection’s
owner while it runs: the connection’s polls wait.
9. Common OIDs
| Object | OID | Point |
|---|---|---|
| sysDescr | 1.3.6.1.2.1.1.1.0 | scalar, string |
| sysUpTime | 1.3.6.1.2.1.1.3.0 | scalar, timeticks_s |
| sysName | 1.3.6.1.2.1.1.5.0 | scalar |
| ifDescr | 1.3.6.1.2.1.2.2.1.2 | table_column, index = ifIndex |
| ifOperStatus | 1.3.6.1.2.1.2.2.1.8 | table_column (1 up, 2 down, …) |
| ifInOctets / ifOutOctets | 1.3.6.1.2.1.2.2.1.10 / .16 | table_column, rate_per_s (Counter32) |
| ifName | 1.3.6.1.2.1.31.1.1.1.1 | table_column |
| ifHCInOctets / ifHCOutOctets | 1.3.6.1.2.1.31.1.1.1.6 / .10 | table_column, rate_per_s, scale: 8 for bit/s |
| hrProcessorLoad (HOST-RESOURCES-MIB) | 1.3.6.1.2.1.25.3.3.1.2 | table_column, gauge, unit % |
| hrStorageUsed / hrStorageSize | 1.3.6.1.2.1.25.2.3.1.6 / .5 | table_column, gauge (× hrStorageAllocationUnits .4) |
| upsBatteryStatus (UPS-MIB) | 1.3.6.1.2.1.33.1.2.1.0 | scalar (2 normal, 3 low, 4 depleted) |
| upsEstimatedChargeRemaining | 1.3.6.1.2.1.33.1.2.4.0 | scalar, unit % |
| upsInputVoltage | 1.3.6.1.2.1.33.1.3.3.1.3 | table_column, index 1, unit V |
| upsOutputPercentLoad | 1.3.6.1.2.1.33.1.4.4.1.5 | table_column, index 1, unit % |
10. Try it with the simulator
wyrm-snmp-sim is an SNMP agent with community public and the v3 users
sha1user (SHA-1, AES), sha256user (SHA-256, AES) and authonly
(SHA-256, no privacy), each with the passphrase <user>-pass. Its MIB: the
system group (writable sysContact), ifNumber, an ifTable and ifXTable
of 4 rows whose octet counters grow every second (row 1’s ifInOctets starts
just below the Counter32 wrap), and one object of each SMI type under
1.3.6.1.4.1.64999.1 (.1.0 INTEGER and .2.0 Gauge32 writable, .3.0
IpAddress, .4.0 TimeTicks, .5.0 Opaque, .6.0 Counter64, .7.0 binary
OCTET STRING, .8.0 writable text).
cargo run -p wyrm-link-snmp --features bin --bin wyrm-snmp-sim -- --listen 127.0.0.1:1161
snmpwalk -v2c -c public 127.0.0.1:1161 1.3.6.1.2.1.2.2.1.2 # net-snmp, if installed
A link in wyrmd.json5 against it (the community in the file is for the demo
only; enter real ones with add_snmp_v2c):
links: {
net1: {
driver: "snmp",
params: {
connections: {
sim: {
kind: "snmp_v2c", host: "127.0.0.1", port: 1161, community: "public",
devices: {
agent: {
points: {
uptime: { oid: "1.3.6.1.2.1.1.3.0", conv: "timeticks_s", unit: "s" },
eth0_in: { oid: "1.3.6.1.2.1.31.1.1.1.6", kind: "table_column", index: "1",
conv: "rate_per_s", scale: 8, unit: "bit/s", poll_s: 5 },
contact: { oid: "1.3.6.1.2.1.1.4.0", conv: "string", writable: true,
set_type: "octet_string" },
},
},
},
},
},
},
},
}
Or add the connection at run time: downstream/net1 ▸ Add SNMP v3 with host
127.0.0.1, port 1161, user sha256user, both passphrases
sha256user-pass; then Add Device, ▸ Walk 1.3.6.1.2.1.2.2.1, and Add Point
for the OIDs found.
The simulator’s failure modes (tests, links/snmp/src/sim.rs): silence, a
reply delayed past the timeout, authorizationError, tooBig above a number
of varbinds, genErr on one OID, a restart (new boots, sysUpTime from 0),
unknown OIDs and communities.
Against a real agent (net-snmp snmpd):
WYRM_SNMP_AGENT=127.0.0.1:16163 WYRM_SNMP_USER=sha1user WYRM_SNMP_PASS=sha1user-pass \
cargo test -p wyrm-link-snmp --test interop -- --ignored
11. Known limits
- No trap or inform receiver (follow-up): the link polls only.
- No MIB files: OIDs are numeric; §9 lists common ones.
- No SNMPv1, no noAuthNoPriv v3, no MD5 or SHA-224/384/512, no DES, 3DES, AES-192 or AES-256 privacy.
- No v3 key change (
usmUserTable) or user management on the agent. - One OID per point; no table point that publishes a whole column as an array.
- A SET carries one varbind; INTEGER, OCTET STRING and Gauge32 only.
rate_per_suses the link’s clock at each answer, not the agent’ssysUpTimedeltas; a counter cleared without a restart gives one spike (§3).- SNMP over TCP, TLS (RFC 6353) or DTLS is not supported; UDP only.
- Interop was checked against net-snmp 5.6 (v2c, v3 SHA-1/AES-128); SHA-256 is checked against the built-in simulator and an independent key derivation.
HTTP link
The http link polls JSON REST APIs: energy meters, inverters, weather
stations, building gateways and cloud services that offer only HTTP. One
generic link covers them without code per vendor. It runs on the driver
framework (ADR 0004), so its tree, actions, states and quality work as in
every framework link (links.md).
Code: links/http (wyrm-link-http): src/lib.rs (params and driver),
src/client.rs (the HTTP/1.1 client), src/select.rs (the selector),
src/sim.rs (the simulator).
1. The tree
<link>/<connection>/<device>/<point>
| Level | Is | Example |
|---|---|---|
| Connection | A base URL with its authentication, TLS, default headers and rate limit. | https://10.0.1.20/api, bearer token |
| Device | One request below the base URL: method, path, query, body. | GET /v1/status |
| Point | A selector into the JSON reply of its device, with a value type. | $.meter.power → number, W |
The framework adds to each connection and device the status and error
leaves, the actions add_*, edit, remove, restart, stop/start,
export/import, and the diagnostics leaves (section 7). A device may hold
folders (add_folder) between it and its points.
One request per period. The points of one device with the same
poll_s form one group. Each group sends one request per period and
all its points take their values from that reply. Give the points of a
device the same poll_s (the default is 10 s) to send one request. Two
rates on one device send two requests.
2. Parameters
Connection (add_connection)
| Param | Default | Bounds | Meaning |
|---|---|---|---|
base_url | required | — | http:// or https://, host, port, path prefix. No user, password, query or fragment in it. |
timeout_ms | 5000 | 100…60000 | Bound on connecting, and on each request (reply and body). |
auth | none | none, basic, bearer, api_key | How requests authenticate. |
username | "" | — | User for basic. |
password | "" | secret | Password for basic. |
token | "" | secret | The token for bearer; the key for api_key. |
api_key_in | header | header, query | Where api_key puts the key. |
api_key_name | X-API-Key | — | The header or query parameter name of the key. |
ca_pem | "" | — | https: trust only these CA certificates (PEM). Empty = the host’s CA certificates (rustls-native-certs, loaded once; section 9). |
cert_pem | "" | — | https: the client certificate chain for mTLS (PEM). |
key_pem | "" | secret | The private key of cert_pem (PEM). |
insecure_skip_verify | false | — | https: accept any server certificate. The handshake signatures are still checked. |
insecure_plaintext | false | — | Allow credentials over http:// to a host that is not loopback. |
headers | "" | 32 lines, 8 KiB | Default headers, one Name: value per line, sent with every request. Not secret: no credentials. |
secret_header_name | "" | — | One more credential header (for an API that needs two), sent with every request. |
secret_header_value | "" | secret | Its value. |
rate_limit | 5 | 0.1…1000 | Requests per second on this connection (all its devices and actions). |
max_body_kib | 4096 | 1…65536 | A longer reply is a device error. |
Rules (an add_* or edit that breaks one is refused with
invalid_parameter and changes nothing):
basicneedsusername(no:in it);bearerandapi_keyneedtoken.ca_pem,cert_pemandinsecure_skip_verifyonly withhttps://;ca_pemandinsecure_skip_verifynot together;cert_pemneedskey_pem. A PEM that does not parse is refused at once.- Credentials are never sent over
http://to a host that is not loopback, unlessinsecure_plaintextis set. The connection then shows a warning on itsstatusleaf (attr.warning), as withinsecure_skip_verify. headersmay not setHost,Content-Length,Transfer-Encoding,Connection,Upgrade,TE,Trailer,Keep-Alive,Range,If-Range,Accept-Encoding,Content-Encoding(a partial or compressed body could not be masked; every request sendsAccept-Encoding: identity),Authorization,Proxy-Authorization,Cookie, the API key header or the secret header, nor a header whose name holdsauth,token,key,secret,session,cookie,password,passwdorcredential:headersis not secret (it shows in~metaandexport, and it is not masked). Credentials belong inauth, or insecret_header_nameandsecret_header_value.secret_header_nameneedssecret_header_value, and it may not be a framing header, the API key header, orAuthorizationwithbasicorbearer. A secret header counts as credentials for the plaintext rule.- The device
queryand a point’swrite_pathare not secret either: never put a key in them (useapi_key_in: query).
Secrets. password, token, secret_header_value and key_pem are
entered in add_connection or edit and kept sealed by the framework in
the link’s data_dir. They never show in ~meta, export, errors or
logs. An edit that leaves a secret empty keeps the stored one while
base_url, auth, api_key_in, api_key_name, secret_header_name,
headers (a header changes what the server sends back), ca_pem,
insecure_skip_verify and insecure_plaintext stay the same; an
edit that changes one of them drops the stored secrets unless it gives
them again.
Device (add_device)
| Param | Default | Bounds | Meaning |
|---|---|---|---|
method | get | get, post | The request’s method. |
path | "" | — | Path below the base URL’s prefix, starting with /; percent-encoded. No ?. |
query | "" | — | Query without ? (a=1&b=2); percent-encoded. |
body | "" | 64 KiB | JSON body, post only (sent as is, with Content-Type: application/json). |
expect_status | 200-299 | 100…599, 16 ranges | Status codes that count as a good reply: 200-299,304. |
Point (add_point)
| Param | Default | Bounds | Meaning |
|---|---|---|---|
path | required | 512 characters, 32 segments | Selector into the reply (section 3). |
type | number | number, bool, string | The value type (section 4). |
aggregate | none | none, first, sum, max, min, avg, count | How several matches become one value. none = exactly one match. |
scale | 1 | ≠ 0 | Numbers: value = raw × scale + offset. |
offset | 0 | — | See scale. |
unit | "" | — | Shown as ~meta.unit. |
bool_true | "" | — | bool: a string equal to this (any case) is true. |
bool_false | "" | — | bool: a string equal to this is false; empty = every other string. |
poll_s | 10 | 0.1…86400 | Poll period. Points of a device with one period share one request. |
writable | false | — | The point takes ~set (level write). |
write_method | put | put, post, patch | Method of a write. |
write_path | "" | — | Path and query of a write below the base URL; empty = the device’s. |
write_body | {{value}} | 64 KiB | JSON body of a write; {{value}} becomes the value. |
Rules: sum, max, min, avg and count need type number;
bool_true/bool_false need type bool; a writable point has
aggregate none or first, a write_body with {{value}} that is JSON
once it is replaced, and a writable bool with strings needs both
bool_true and bool_false. A stored point that breaks a rule is kept as
a failed node (quality bad) and is never deleted.
3. Selectors
A subset of JSONPath (RFC 9535 syntax), parsed when the point is added:
| Selector | Selects |
|---|---|
$ | the whole reply |
$.a.b | member b of member a (names: letters, digits, _, -) |
$['a b'], $["a"] | a member with any name |
$.items[0], $.items[-1] | an array element (negative: from the end) |
$.items[*], $.a.* | every element, or every member value |
$.items[?(@.id=="x")].v | v of the elements whose id is "x" |
$.items[?@.v > 2] | elements by a comparison: ==, !=, <, <=, >, >= with a string, number, true, false or null |
$.items[?(@.ok)] | elements that have ok |
Numbers compare by value (1 == 1.0). An element without the compared
member is unequal to every literal. < and friends compare two numbers or
two strings; other pairs never match.
Not supported: recursive descent (..), slices ([1:3]), unions
([0,1]), functions (length()), &&/|| in filters.
Several matches. A wildcard or a filter can find several values. With
aggregate none the point needs exactly one; first takes the first;
sum, max, min and avg need numbers and at least one match; count
is the number of matches (0 is a value, not an error).
4. Values and conversions
type | From JSON | Result |
|---|---|---|
number | number; string with a number (" 230.1 "); true/false as 1/0 | float, × scale + offset |
bool | true/false; number (≠ 0 = true); string: bool_true/bool_false, or "true"/"false" (any case) when they are empty | bool |
string | string; a number, bool, object or array as its JSON text | string |
null is an error for every type. A count is never scaled. Numbers are
floats: an integer above 2^53 loses precision.
5. Writes
~set on a writable point sends write_method to write_path (or the
device’s path and query) with write_body, where every {{value}} is the
value as JSON:
number:(value − offset) / scale, sent as an integer when it is whole ({"setpoint": {{value}}}with scale 0.1 and value 21.5 →{"setpoint": 215});bool:true/false, or the text ofbool_true/bool_falseas a JSON string when they are set;string: a JSON string with escapes.
Put {{value}} where a JSON value goes, never inside quotes. A 2xx reply
is success; then the framework reads the point back at once (one request of
the device) and the tree shows what the server holds. There is no
optimistic update. Any other status fails the write (invalid_parameter,
“HTTP 400”; 401/403 “authentication failed”), a timeout answers timeout.
A point without writable refuses ~set.
6. Errors and quality
| What happens | Class | Effect |
|---|---|---|
| Connection refused, DNS, TLS failure, a broken socket | transport | The connection goes failed with error, its devices stopped_by_parent, points bad/disconnected; reconnect with backoff (1 s…60 s). |
No reply within timeout_ms | device miss | First miss: points uncertain/stale; after 3 misses the device failed with error, points bad/comm_fail. |
Status outside expect_status (4xx, 5xx, …) | device miss | As above; error = GET /api/v1/status: HTTP 503, 401/403 …: HTTP 401: authentication failed. |
Body over max_body_kib, a reply that is not JSON, more than 3 redirects, a redirect to another host | device miss | As above, with the reason. |
A partial reply (HTTP 206) or an encoded one (Content-Encoding other than identity) | device miss | …: partial reply (HTTP 206): not read, …: encoded reply (Content-Encoding): not read: the masker cannot see into such a body, so it is never read; try_request hides it with its length. |
Selector finds nothing, several values without aggregate, wrong type, null, a number equal to a secret (“value hidden”) | point | That point only: quality bad with its last value; the device stays connected. |
Values are never invented: a failed point keeps its last value with a bad quality.
Echoed secrets. Some servers echo the request (its headers or its
query) in the reply. The connection’s secrets are password, token,
secret_header_value (and, when it is a scheme and a token such as
Bearer abc…, the token alone), the basic credentials in base64 and the
percent-encoded query key.
Selectors run on a view of the reply in which every value that holds
a secret is masked; member names stay raw. So a filter (<, >,
==, !=) compares *** or Bearer ***, never the secret, and a count,
“nothing found” or “selects N values” cannot depend on the secret’s
characters: a secret cannot be read back one character at a time. Two
limits remain (section 9): masking still tells whether a text equals or
holds a secret, so a short secret can be guessed through an echoing
server, and member names stay raw. $.adminState with the password
admin still selects, and 51234.5 with the PIN 1234 stays a number.
The masking rules, the same for selectors and for what is shown:
- a text: every secret in it (longest first) is shown as
***. The JSON is parsed first, so a JSON escape (\/, a unicode escape) cannot hide a secret. A text that still holds a secret once JSON-unescaped (JSON inside a string) is hidden whole:*** hidden: it holds a connection secret; - numbers, and numeric texts (
"230.1"): a secret that is a plain decimal number (a PIN, a numeric key) is matched by value, with its leading zeros stripped, and only by equality, never by substring: the PIN0123hides the number123(and the text"0123"), but not1234or51234.5. The values 0 to 9 are too common and are never matched as numbers (the PIN0000leaves the reading0alone; the text"0000"is still hidden). A matched number shows as"***"; - a
numberpoint whose match is masked fails with “value hidden: it holds a connection secret” (qualitybad). This also happens to a reading that equals a numeric secret by chance, as long as it holds that value: with the PIN0100, a level of100goesbadeach time it is 100 (an explicit error, never a wrong value). Acountof masked matches is not hidden; - a point whose filter compared a masked value (
[?(@.id == 1234)]with the PIN1234,[?(@.level > 50)]on a level equal to it) fails with “value hidden: a filter compared a value that holds a connection secret” (test_selectorgives it aserror), never a count one too low or another element; - member names in what is shown (a
stringpoint of an object,try_request,test_selectorvalues) are masked too, and two names that mask alike are both shown (***,***#2). An object of more than 10 000 members, or more than 10 000 renamed names in all, is not masked name by name: the value is hidden (“value hidden: too many member names to mask”), and so is atry_requestbody; - a
boolshows no secret and is never masked.
try_request on a body that is not JSON: after a BOM or an anti-XSSI
prefix ()]}') the JSON is masked as above; otherwise the text is masked,
and the body is hidden whole (*** body hidden: it holds a connection secret) when it still holds a secret once JSON-unescaped, or when a
number in it equals a numeric secret. Every run of digits is tried on its
own too (code123, id-123, v1234.5, 1.0123.4), with the same
leading-zero and 0 to 9 rules. A masked reply reports masked: true and
the masked length in bytes, and it shows only the headers
Content-Type, Date, Cache-Control, Server, Vary, Retry-After
and Location (masked like the body). Every other header may give the
raw length, a range, a hash or a checksum of the raw body
(Content-Length, Content-Range, ETag, Digest, X-Checksum-*, …):
they are left out and counted in hidden_headers.
Secrets shorter than 3 characters are not masked. Errors name the method and the path; they never hold the query (an API key may be in it), headers, bodies or selected values.
Redirects: 301, 302, 303, 307, 308, at most 3 per request, to the same
scheme, host and port only (the scheme in any case). On a poll, 303, and
301/302 after a POST, continue as GET without a body. A write never
follows 301 or 302 (the write fails: “redirected (HTTP 301); write not
applied”; put the target in write_path), takes 303 as applied without
following it, and follows 307 and 308 with its method and body.
Connections: one keep-alive HTTP/1.1 connection per link connection,
one request on it at a time. A connection the server closed while idle is
opened again without a failure (counted in reconnects). A request that
timed out or was cut drops its connection, so a late reply arrives on a
closed socket and is never taken for a later request.
7. Actions and diagnostics
On each device, at level config: they send real requests (also on a
post device), show reply headers and the whole reply, and share the
connection’s rate limit with the polls, so they are commissioning tools,
not reading.
- Try Request (
try_request): sends the device’s request now and returns{status, headers, body, truncated, masked, hidden_headers, bytes}: any status, the body up to 64 KiB as text.Set-Cookie,Authorizationand every header named like one the connection sends with a credential are left out; the other headers and the body are masked as in section 6 (on a connection with secrets a JSON reply is shown as its masked, compact JSON).bytesis the reply’s length, or the masked text’s length whenmasked; a masked reply shows the allowlisted headers only (section 6), andhidden_headerscounts the others. A JSON reply is also kept fortest_selector. - Test Selector (
test_selector {path, type?, aggregate?}): runs a selector against the last JSON reply of the device’s request (a poll’s ortry_request’s), without I/O, on the same masked view as the points (section 6). Returns{count, values, truncated}(the first 20 matches; a match whose JSON text is longer than 2 KiB is shown as that text, cut) and, withtype,value(a string cut at 8 KiB) orerroras a point would show it (unscaled). Replies are kept up to 1 MiB each and 4 MiB per connection (the last 16 requests); a longer reply answersnot_available“… is not kept”.
Diagnostics leaves on the connection and each device (framework, ruling
12): requests, errors, timeouts, exceptions (replies with a status
≥ 400), reconnects, redirects, last_rtt_ms, avg_rtt_ms.
8. Run it with the simulator
The simulator wyrm-http-sim (src/sim.rs, feature sim) serves:
| Endpoint | Reply |
|---|---|
GET /api/data | {"meter": {"power", "energy", "voltage", "on", "state", "name"}, "items": [{"id", "v"}…], "nested": {"deep": {"x": 42}}, "nothing": null}; power and energy move on each request |
POST /api/query | {"got": <the request body>, "data": …} |
GET /api/echo | the request’s headers and query |
GET /api/resource, PUT/POST/PATCH /api/resource | a writable object (setpoint, mode, enabled, label); a write merges a JSON object, anything else is 400 |
PUT/POST/PATCH /api/moved, /api/found, /api/temp, /api/done | writes redirected with 301, 302, 307 (nothing applied); done merges, then 303 |
GET /redirect/<n>, GET /offsite | redirect chains, a redirect to another host |
Tests also use its failure modes: a fixed status (401, 500, …), silence, slow replies, invalid JSON, a huge body, a close after each reply, and TLS.
cargo run -p wyrm-link-http --features bin --bin wyrm-http-sim -- --listen 127.0.0.1:8090
# with auth: --basic user:password, or --bearer <token>
Then add the link (embedded) in wyrmd.json5:
links: {
meter: {
driver: "http",
params: {
connections: {
sim: {
base_url: "http://127.0.0.1:8090/api",
devices: {
data: {
path: "/data",
points: {
power: { path: "$.meter.power", unit: "W", poll_s: 2 },
energy: { path: "$.meter.energy", unit: "Wh", poll_s: 2 },
b: { path: "$.items[?(@.id==\"b\")].v", poll_s: 2 },
total: { path: "$.items[*].v", aggregate: "sum", poll_s: 2 },
},
},
resource: {
path: "/resource",
points: {
setpoint: {
path: "$.setpoint", writable: true, poll_s: 5,
write_body: "{\"setpoint\": {{value}}}",
},
},
},
},
},
},
},
},
},
or install it from Install Link ▸ from Driver (driver http) and build
the tree with the add_* actions. As a package (ADR 0021):
wyr link pack --manifest-path links/http/Cargo.toml (binary
wyrm-link-http, feature process).
9. Known limits
- Addresses the link never connects to: link-local (
169.254.0.0/16,fe80::/10, where cloud instance metadata hands out credentials), other cloud metadata endpoints (fd00:ec2::254,100.100.100.200,168.63.129.16,192.0.0.192), unspecified, multicast and broadcast addresses, also inside IPv6 forms that carry an IPv4 address. The check runs on the address the host name resolves to, so DNS cannot lead there either. Loopback and private networks stay reachable: devices and simulators live there (security review, ADR 0031). - Poll period on the point, not the device: the framework groups points
by the point’s period (
Driver::poll_periodsees only the point). Points of a device with differentpoll_ssend one request per period. - No OAuth2 flows (client credentials, refresh tokens): a static bearer token works. A follow-up.
- No XML/SOAP, no WebSockets, no server-sent events, no webhooks (push in).
- No HTTP/2; no compression (
Accept-Encodingis not sent); no proxies; no cookies or sessions (aCookieheader is refused: it is a credential). - No digest or NTLM authentication.
- Device requests are GET or POST; the body has no placeholders.
- Numbers are floats (
f64). - Selector subset only (section 3).
- Masking is by text (section 6): a string shown that holds a secret
is masked even when the match is by chance (
administratorwith the passwordadminshows***istrator, and a filter on it compares***istrator). Secrets shorter than 3 characters are not masked. - A reading equal to a numeric secret fails “value hidden” while it
holds that value (the PIN
0100and a level of100), and so does a point whose filter compares such a reading: the point flapsbad. Choose a PIN that is not a likely reading, or keep the echo endpoint apart from the readings. - Masking tells whether a text holds a secret, so guesses can be
tested. A
configuser who can put candidates into a device’squeryorheaderson an endpoint of the same origin that echoes the request sees***in place of the one candidate that equals the secret: a 4-digit PIN falls in about 10 requests, a 6-digit one in about 1000, a common password to a dictionary. A long random token does not fall this way. Use long random secrets; a PIN or a short password is not protected from aconfiguser of an echoing server. - Member names stay raw for selectors (so
$.adminStateworks). When a server uses a secret as a member name,$['<guess>']is an equality test, and the order of$.obj.*follows the raw names. Only a server that puts a configured secret into a member name is affected. - Other encodings of a secret are not masked: a query key re-encoded by
the server (
%2fin lower case,+for a space) or HTML entities in an error page. - System CAs (
ca_pemempty) are loaded once per process, at the firsthttps://connection; CAs the host adds later need a restart. The first load reads the host’s store (files, or the macOS keychain) on the thread that parses the connection.SSL_CERT_FILEandSSL_CERT_DIRwork in an embedded link; a process link gets a cleared environment, so there they do not apply: giveca_pem.
Prometheus link
The prometheus link scrapes endpoints that publish metrics in the
Prometheus text format (0.0.4) or OpenMetrics 1.0 text: node_exporter,
databases, Kubernetes components, PLC gateways, inverters and more. It
turns the series you select into WYRM points, so the historian, flows and
alarms work on them. Crate: links/prometheus, on the driver framework
(ADR 0004). Points are read-only.
1. The tree
downstream/<link>/
<connection> one HTTP(S) endpoint, e.g. http://host:9100/metrics
<device> a label filter applied to all its points
<point> a series selector and what to compute from it
- Connection = one endpoint. The link scrapes it once per
scrape_s, whatever the number of devices and points. Each scrape uses a new HTTP connection. - Device = a logical group under the connection: a label filter such
as
instance="a". Use one device per instance, job or machine behind a federating endpoint. - Point = a series selector (
node_cpu_seconds_total{mode="idle"}), with an aggregate when several series match, a mode (raworrate_per_s) and a function (valueorhistogram_quantile).
The framework gives every connection and device the status and error
leaves, the actions add_*, edit, remove, restart, stop/start,
copy, export and import, and the diagnostics leaves (section 6).
2. Add it
- Install the driver:
sys/links▸ Install Link ▸ from Driver, driverprometheus(or the packageprometheusfrom a repository). - On the link ▸ Add Connection: name, URL, and the other params in section 3.
- On the connection ▸ List Series shows what the endpoint serves.
- On the connection ▸ Add Device: name, Label Filter (empty = all series).
- On the device ▸ Add Point: name, Selector, and the other params.
A wyrmd.json5 example (one link, two devices fed by one scrape):
links: [{
id: "metrics", driver: "prometheus",
params: { connections: { node: {
url: "http://10.0.0.5:9100/metrics", scrape_s: 15,
devices: {
host: { labels: "", points: {
load1: { selector: "node_load1" },
cpu_idle: { selector: "node_cpu_seconds_total{mode=\"idle\"}",
aggregate: "sum", mode: "rate_per_s" },
rx: { selector: "node_network_receive_bytes_total{device=\"eth0\"}",
mode: "rate_per_s", scale: 8, unit: "bit/s" },
}},
disk_root: { labels: "mountpoint=\"/\"", points: {
free: { selector: "node_filesystem_avail_bytes", scale: 1e-9, unit: "GB" },
}},
},
}}},
}]
3. Parameters
Connection
| Param | Default | Bounds | Meaning |
|---|---|---|---|
url | (required) | http:// or https://, no user info | The endpoint. IPv6 as [::1]. |
timeout_ms | 5000 | 100 … 60 000 | Bound on one scrape: connect, TLS, headers and body. |
scrape_s | 15 | 1 … 3600 | Time between two scrapes. |
username | "" | no : | Basic auth user. |
password | "" | secret | Basic auth password. |
bearer_token | "" | secret | Authorization: Bearer … instead of basic auth. |
ca_pem | "" | PEM | CA certificates for https; empty = the system roots. |
cert_pem | "" | PEM | Client certificate for mutual TLS. |
key_pem | "" | secret, PEM | Private key of cert_pem. |
insecure_skip_verify | false | Accept any server certificate. For tests only: the status leaf shows a warning while it is on. | |
headers | "" | at most 32 | Extra request headers, one Name: value per line. Not for credentials. |
gzip | true | Send Accept-Encoding: gzip and decode gzip bodies. | |
max_body_mib | 8 | 1 … 64 | Bound on the body, on the wire and after gzip decoding. The parsed exposition may take up to 16 times this in memory (section 9). |
max_series | 100 000 | 1 … 1 000 000 | Bound on the series of one scrape, and on its # TYPE and # UNIT entries. |
Rules checked when you add or edit a connection (the edit is refused and nothing changes):
ca_pem,cert_pemandinsecure_skip_verifyneed anhttps://URL.cert_pemandkey_pemgo together. A PEM that does not parse is refused.- Give
username/passwordorbearer_token, not both. A password needs a username. - Credentials are never sent in plaintext to a host that is not loopback:
use
https://. headersmay not setAuthorization,Proxy-Authorization,Cookie,Host,Content-Length,Transfer-Encoding,Connection,Accept-EncodingorTE.
Secrets (password, bearer_token, key_pem) are entered in
add_connection or edit. The framework keeps them sealed in the link’s
data_dir. They never show in ~meta, export, replies or logs. An edit
that changes url, ca_pem or insecure_skip_verify drops the stored
secrets unless the edit gives them again.
Device
| Param | Default | Meaning |
|---|---|---|
labels | "" | Label matchers applied to every point of the device, with or without braces: instance="a", job=~"node.*". Empty = all series. |
Point
| Param | Default | Bounds | Meaning |
|---|---|---|---|
selector | (required) | a metric name is required | name or name{matchers}. |
aggregate | none | none, sum, max, min, avg, count | How the matching series become one value. |
mode | raw | raw, rate_per_s | rate_per_s: increase per second between two scrapes. |
function | value | value, histogram_quantile | histogram_quantile: the q quantile from the _bucket series. |
q | 0.5 | 0 … 1 | The quantile for histogram_quantile. |
scale | 1 | The point value is value · scale + offset. | |
offset | 0 | ||
unit | "" | Shown in ~meta.unit. |
4. Selectors and values
Matchers are as in PromQL: =, !=, =~ and !~. Label values are
quoted strings with the escapes \\, \" and \n. A regex matches the
whole value (^(?:re)$) and uses the regex crate (no backreferences;
compiled size at most 1 MiB). A missing label has the value "", so
l="" matches series without l. A series matches a point when it has
the point’s metric name, matches the point’s matchers and the device’s
filter.
Names are the exposed series names. In OpenMetrics a counter foo
is exposed as foo_total; select foo_total. Histograms and summaries:
select <name>_bucket{le="0.5"}, <name>_sum, <name>_count or a summary
quantile <name>{quantile="0.99"} like any other series.
Aggregate:
aggregate | Value | No series matches |
|---|---|---|
none | the one matching series; more than one is a point error | point error |
sum, max, min, avg | over all matching series | point error |
count | the number of matching series | 0 |
rate_per_s computes, per series, the increase since the last scrape
divided by the time between the two scrapes (the time each request
started). A counter reset (the value goes down, for example after the
exporter restarts) counts as an increase from 0, as in PromQL. The rates
of all series are then aggregated. A point has no value until its second
scrape. A series new since the last scrape is left out for one scrape.
histogram_quantile: the selector names the histogram (<name> or
<name>_bucket). The link sums the buckets of all matching series by le
(PromQL histogram_quantile(q, sum by (le) (…))), then interpolates
linearly inside the bucket of the rank. A le="+Inf" bucket and two
buckets at least are required. A rank in the +Inf bucket gives the
highest finite bound. With mode: rate_per_s the buckets are the
increases since the last scrape, so the quantile is that of the last
interval; with raw it is that of all observations since the exporter
started. aggregate must stay none. With rate_per_s, a point gets no
new value (it keeps its last one) while a bucket is new since the last
scrape, and for an interval with no observations (PromQL gives NaN
there): a quiet service does not flap to bad.
Value type: every point is a number (f64). Exposition values NaN,
+Inf and -Inf are parsed; a point whose result is not a finite number
is a point error (bad), never a made-up value.
Timestamps in the exposition are checked and then ignored. The sample time of a point is the time the link publishes it.
5. Scrapes, errors and quality
Every point is evaluated once per second on the last good scrape. The
connection scrapes again when that scrape is scrape_s old (a poll up to
0.5 s early, at most a quarter of scrape_s, takes the next scrape: two
scrapes are never closer than that). Polls of several devices in the same
second share one attempt. A value is
published only when it changes.
| What happens | Class | Effect |
|---|---|---|
| connect refused, DNS, TLS or I/O error, broken response | connection | connection failed with the error leaf; devices Stopped by Parent; points bad/disconnected; reconnect with backoff (1 s … 60 s) |
body over max_body_mib, more than max_series series, a parsed exposition over 16 × max_body_mib of memory | connection | as above; the error names the param |
no complete response within timeout_ms | device miss | points uncertain/stale; after 3 misses in a row the device is failed and points are bad/comm_fail |
| HTTP status other than 2xx (500, 404, …) | device miss | as above; the device error leaf shows HTTP <code> |
no series matches, several match with none, not a finite number, broken histogram (no le="+Inf" bucket, fewer than two buckets, a bad le, no observations at all with raw) | point | that point bad; its device stays connected |
histogram_quantile with rate_per_s: a new bucket, or no observations in the interval | none | no new value; the point keeps its last value and quality |
| a line of the exposition that does not parse or is over a line bound (section 9) | none | the line is skipped and counted in parse_errors |
A failed scrape is not kept: the next second tries again, so each failed
attempt is one miss. After 3 misses the link tries again only scrape_s
after the end of the last attempt (polls and List Series alike), however
long timeout_ms is.
Opening the connection is a first scrape: a 401, a 404 or a timeout there
fails the connection with that reason.
Each scrape opens its own HTTP connection and closes it after the body. A reply that comes after a timeout dies with its connection and is never taken for a later scrape.
Gzip decoding and parsing run on a blocking thread, not on the broker’s
async workers. A poll is bounded by timeout_ms + 5 s + 250 ms per MiB of
max_body_mib. A poll cut while the body is parsed is a miss, and the
next poll waits for that same parse instead of fetching a second body.
A device without points stays Connecting: the link has no device ping,
because a ping would mark a device good between failed scrapes.
6. Actions and diagnostics
- List Series (
list_series {match?, limit = 200}, levelconfig: it may scrape and holds the connection) on a connection: the series of the last scrape (or a new one when it is old):total,truncated,bad_lines,age_msandseries, each withname,type(from# TYPE),labelsandvalue("NaN","+Inf","-Inf"as text).matchis a selector (empty = all),limit1 … 10 000. - Diagnostics on connections and devices:
requests(scrapes),errors(I/O, oversize),timeouts,exceptions(non-2xx replies),parse_errors(skipped lines),last_rtt_ms,avg_rtt_ms. A scrape counts for the connection and for the device whose poll started it.
7. Writes
Prometheus endpoints are read-only. Every point has writable: never, and
a ~set is refused; the value does not change.
8. Simulator
wyrm-prometheus-sim serves a test exposition on
http://127.0.0.1:9101/metrics:
cargo run -p wyrm-link-prometheus --features bin --bin wyrm-prometheus-sim -- \
--listen 127.0.0.1:9101 [--openmetrics] [--malformed]
It serves sim_requests_total{path="/a"|"/b"} (counters that grow on
every scrape), sim_temperature_celsius{instance="a"|"b",sensor="t1"}
(gauges that drift), the histogram sim_latency_seconds (buckets 0.1,
0.5, 1, +Inf, growing every second), the summary sim_rpc_seconds,
sim_escaped (escaped label values) and sim_nan. In tests
(links/prometheus/tests/sim.rs, feature sim) the shared state also
gives the failure modes: 500 replies, silence, a slow body, an oversized
body (with or without Content-Length), malformed lines and a disconnect, plus basic or bearer auth and
gzip.
Try it with the simulator and a link:
- Start the simulator (above).
- Add a link with driver
prometheusand a connection with URLhttp://127.0.0.1:9101/metricsandscrape_s5. - Run ▸ List Series on the connection.
- Add a device with Label Filter
instance="a", and a point with Selectorsim_temperature_celsius. - Add a point with Selector
sim_requests_total, Aggregatesum, Moderate_per_s.
9. Limits
- Addresses the link never connects to: link-local (
169.254.0.0/16,fe80::/10, where cloud instance metadata hands out credentials), other cloud metadata endpoints (fd00:ec2::254,100.100.100.200,168.63.129.16,192.0.0.192), unspecified, multicast and broadcast addresses, also inside IPv6 forms that carry an IPv4 address. The check runs on the address the host name resolves to, so DNS cannot lead there either. Loopback and private networks stay reachable: devices and simulators live there (security review, ADR 0031).
What Prometheus has that this link does not do:
- PromQL beyond one selector with an aggregate, a rate and
histogram_quantile: noby/withoutgrouping, no arithmetic between series, no range functions other than the rate between two scrapes, nooffset. - Exposition timestamps do not become the sample time: the driver framework publishes a point with the time it publishes it.
- Native histograms and the protobuf exposition format are not read (only text). Quoted UTF-8 metric names (Prometheus 3) are skipped as malformed lines. Exemplars are skipped.
- No remote-write receiver, no service discovery, no relabelling, no
honor_labels, no export of WYRM values to Prometheus. - One endpoint per connection; HTTP/1.1 only (no HTTP/2), no proxy, no keep-alive between scrapes.
- An edit of a device or point re-plans its connection’s points, and their rates start again: the first scrape after it gives no rate.
- An HTTP redirect (3xx) is a device miss; the link does not follow it.
- Memory. One scrape is bounded at 16 ×
max_body_mibof memory: the decoded body, a copy of it when it has invalid UTF-8, and the parsed exposition. The link counts the parsed exposition while it parses: the vector slots it holds (spare capacity too) and every non-empty name or value as one allocation of at least 32 bytes. Over the bound is a connection error that namesmax_body_mib. The real heap is within about 1.3 times this count (allocator headers). A typical exposition takes 4 to 8 times its size, so the default 8 MiB uses about 30 to 70 MiB, and never more than about 128 MiB counted (about 170 MiB of heap). At 64 MiB the bound is 1 GiB counted (about 1.3 GiB of heap): keepmax_body_mibat 16 or less on a 2 GB board. The last scrape is dropped before the next one arrives, and a parse whose connection was edited, stopped or failed to open stops within milliseconds, so two never live at once. - Line bounds. A line over 1 MiB, a sample with more than 128 labels,
a metric or label name over 1 KiB and a label value over 16 KiB are
skipped and counted in
parse_errors.# TYPEand# UNITlines pastmax_seriesnames are skipped the same way.
File store links: S3, Google Drive, WebDAV, local directories
Four links show a file store as a tree of folders and files, keep it fresh, and let people (and flows) create folders, upload, download and delete files:
| Link (driver, package) | Stores | Crate |
|---|---|---|
s3 | AWS S3, MinIO, Ceph RGW, Cloudflare R2, Wasabi, Backblaze B2, DigitalOcean Spaces, Google Cloud Storage (HMAC keys) | links/s3 |
gdrive | Google Drive: My Drive, a folder shared with a service account, a shared drive | links/gdrive |
webdav | Nextcloud, ownCloud, Synology, QNAP, Apache/nginx DAV, rclone serve, pCloud, Yandex Disk, … | links/webdav |
localfs | a directory of the host: a local disk, a USB stick or SD card, an NFS / SMB / sshfs mount, a NAS volume, a sync folder | links/localfs |
All four run on crates/wyrm-filestore (ADR 0027): the same tree, the
same actions, the same limits. They run embedded in wyrmd or as
processes (wyrmd link s3, or the packages’ binaries).
1. The tree
downstream/<link>/
<connection> one bucket / drive folder / collection
status Unknown, Connecting, Connected, Failed, Stopped
error while there is one (also "truncated: …")
entries files and folders shown
total_bytes sum of the file sizes (B)
last_refresh when the whole tree was read (UTC)
files/ the connection's root folder
reports/ a folder
2026/
october.csv a file: value = size (B), at the file's time
- A file is a leaf whose value is its size in bytes, timestamped with
its last change. Its
attrholdsname,path(below the root),modified,etagandcontent_typewhen the store reports them. - A node’s key is the file’s name when that is a valid key segment
(letters, digits,
_,-,.). Other names (a b (1).txt,Звіт.pdf) get a safe key with a stable hash (a_b_1_.txt_1f2e3d4c); the real name is the node’s display name. A node keeps its key while its file exists, so history watches and flows on it keep working. - The tree is read at start, every
refresh_s(default 300 s; 0 = only on Refresh) and on Refresh. What the store no longer has is removed.
2. Actions
| Node | Action | Level | What it does |
|---|---|---|---|
| root | Add S3 Bucket / Google Drive / WebDAV Folder (add_connection) | config | a new connection: its name and params (below) |
| connection | Edit, Remove, Stop / Start | config | secrets left empty in Edit keep the stored ones (while the destination stays the same) |
| connection | Refresh | read | read the whole tree again → {entries, truncated} |
folder (and files) | Refresh | read | read this folder again |
folder (and files) | Create Folder {name} | write | → {path, node} |
folder (and files) | Upload File {name, file | text, content_type?, overwrite?} | write | → {path, node, size}; without overwrite a file of that name is refused |
| folder | Delete {recursive?} | write | without recursive the store itself is asked whether the folder is empty (not the tree, which may miss hidden names, deep levels and new files) |
| file | Download {text?} | read | the bytes (or UTF-8 text with text) |
| file | Delete | write |
Uploads take a file (the explorer’s file picker; larger than a WebSocket
frame goes through the gateway’s POST /api/invoke) or text. The
content type comes from the name’s extension when not given. A file is
found by its real name (Overwrite replaces the file called that, not
another whose key looks the same).
Each connection runs one tree read at a time (a Refresh while one runs
answers busy) and two uploads or downloads at a time (a third answers
busy): the bytes of a transfer are held in memory.
Stop, Remove and Edit of a connection cut its actions in flight: they
answer disconnected and send nothing more to the store.
Without overwrite an upload never replaces a file: S3 and WebDAV send
If-None-Match: *, localfs creates the file new. Some servers ignore
that header (nginx dav, some Ceph RGW versions, Wasabi, Backblaze B2,
the GCS XML API): there a file made by someone else after the last refresh
can be replaced.
Common connection params (all four links):
| Param | Default | Range | |
|---|---|---|---|
refresh_s | 300 | 0, 5–86 400 | 0 = only on Refresh |
max_entries | 2000 | 1–9000 | more are left out; the connection says truncated |
max_depth | 8 | 1–12 | folder levels shown |
max_upload_mib | 32 | 1–64 | Upload File in one request |
max_file_mib | 4096 | 1–65 536 | a file uploaded in parts (at most 64 GiB since 2026-11-01: a larger stored value makes the connection failed until it is edited) |
max_download_kib | 1024 | 1–16 384 |
A connection name is one key segment. The names . and .. are
refused (invalid_message) by Add Connection. A connection with
one of these names in the bootstrap params or in filestore.conns is left
out (the link logs a warning and starts the other connections).
Connections and their secrets are kept sealed in the link’s data_dir
(filestore.conns, the link’s store key), never shown in ~meta or
replies. Bootstrap params (wyrmd.json5) may list connections too:
params: {connections: {<name>: {…}}}; when they change, they replace
what was added at runtime.
3. S3 (s3)
| Param | Default | |
|---|---|---|
endpoint | https://s3.amazonaws.com | AWS https://s3.<region>.amazonaws.com; MinIO https://minio:9000; R2 https://<account>.r2.cloudflarestorage.com; GCS https://storage.googleapis.com |
region | us-east-1 | R2 and GCS: auto |
bucket | — | |
addressing | auto | auto = virtual-hosted on *.amazonaws.com, path-style elsewhere; path, virtual |
prefix | — | the connection’s root inside the bucket (site1/reports) |
access_key_id, secret_access_key (secret), session_token (secret) | — | empty keys: unsigned requests (a public bucket) |
timeout_ms | 10000 | |
ca_pem, insecure_skip_verify, insecure_plaintext | TLS; keys over http:// only to loopback unless insecure_plaintext |
S3 has keys, not folders: every / in a key is a folder level, and Create
Folder stores the empty marker <folder>/ as the S3 consoles do. Delete
of a folder deletes every key below it (at most 10 000). The bucket needs
the list, get, put and delete permissions (s3:ListBucket, s3:GetObject,
s3:PutObject, s3:DeleteObject). A bucket in another region than
region fails with the region the store names.
MinIO example:
links: [{ id: "minio", driver: "s3", params: { connections: { reports: {
endpoint: "https://minio.plant.local:9000", bucket: "reports",
access_key_id: "wyrm", secret_access_key: "…", refresh_s: 600 } } } }]
Better: leave the secret out of wyrmd.json5 and add the connection at
runtime (Add S3 Bucket), where the key is sealed.
4. Google Drive (gdrive)
| Param | Default | |
|---|---|---|
auth | service_account | or refresh_token |
service_account_json (secret) | — | the whole JSON key file of a service account |
subject | — | Workspace domain-wide delegation: act as this user |
client_id, client_secret (secret), refresh_token (secret) | — | auth: refresh_token: an OAuth client and a user’s refresh token (scope https://www.googleapis.com/auth/drive) |
folder_id | root | the connection’s root: root (My Drive) or the id in the folder’s URL (…/folders/<id>) |
shared_drive_id | — | a shared drive; with folder_id: root its top |
trash | true | Delete moves to the trash; false deletes for good |
timeout_ms | 15000 | |
api_url, token_url | Google’s | a proxy or the simulator |
ca_pem | — | a TLS-inspecting proxy |
A service account sees only what is shared with it: share the folder with
its client_email, and use that folder’s id. Drive allows two files of one
name in a folder and / in names; the tree shows both (the second with a
part of its id in the key), with the real names. Google Docs, Sheets and
Slides show with size 0 and their type; they cannot be downloaded (export
is not supported).
5. WebDAV (webdav)
| Param | Default | |
|---|---|---|
url | — | the collection: Nextcloud https://<host>/remote.php/dav/files/<user>/<folder> |
auth | basic | none, basic, bearer |
username, password (secret) | — | Nextcloud and ownCloud: an app password |
token (secret) | — | auth: bearer |
timeout_ms | 10000 | |
ca_pem, insecure_skip_verify, insecure_plaintext | as S3 |
The tree is read folder by folder with PROPFIND Depth: 1 (servers often
refuse Depth: infinity); folders are real collections (MKCOL).
6. Large files: transfers in parts
Upload File and Download carry a file in one request (at most 64 MiB and 16 MiB). Larger files go in parts (ADR 0028):
| Node | Action | Level | |
|---|---|---|---|
folder (and files) | Upload in Parts (upload_begin {name, size, part_size?, content_type?, overwrite?, sha256?}) | write | → {upload, part_size, parts} |
| connection | upload_part {upload, index, data} | write | one part, from index 0; any order, again after a cut |
| connection | upload_status {upload} | write | state (receiving, committing, done with result, failed with error), missing parts |
| connection | upload_commit {upload} | write | → committing; the file goes to the store in the background |
| connection | upload_abort {upload} | write | drops it and its parts |
| file | download_part {offset, length?} | read | → {data, offset, size, eof}, up to 16 MiB a part |
- Parts are 64 KiB … 16 MiB (4 MiB by default); every part but the last
has
part_sizebytes. A file is at mostmax_file_mib(4 GiB by default). Send parts through the gateway’sPOST /api/invoke(dataiseditor: file, so the gateway takes it there; ADR 0028 amendment 2026-11-15). - The link keeps the parts in a spool file on its own disk
(
<data_dir>/uploads/) until the commit, so its disk needs room for the file. The commit sends it to the store as it reads it: S3 multipart (multipart_mib, 16 MiB parts), a Drive resumable upload (upload_chunk_kib, 8 MiB chunks), one streamed WebDAVPUT, a copy forlocalfs. Memory holds one part, not the file. - The link keeps 1 GiB free on the disk of its spool.
upload_beginrefuses a file larger than the free space minus 1 GiB (resource_exhausted). Eachupload_partchecks again before it writes: the parts not received yet must still fit. When another upload took the space, the part is refused (resource_exhausted); send it again when there is room. - An upload belongs to whoever began it; at most 4 per connection; one idle for an hour is dropped. Stopping or editing the connection, or restarting the link, drops its uploads: begin again. A commit cut by Stop, Edit or Remove does not leave parts in the store: S3 gets an AbortMultipartUpload before the connection closes.
- Give
sha256at begin to have the parts checked before the file goes to the store.
A client loop: upload_begin, then upload_part for each index (several
at once is fine, two run at a time), upload_status to find what is
missing after a cut, upload_commit, then upload_status until done.
A download: download_part from offset 0 until eof.
- Each part the store sends is checked. A
206reply must carry aContent-Rangethat starts at the asked offset and has the length of its body. Otherwise the part is refused (invalid_parameter) and not used. - When the file in the store is now shorter than the tree shows, a part at
or past its end answers
{data: [], offset, size, eof: true}.sizeis the file’s real size: from the416reply of S3, Google Drive and WebDAV (Content-Range: bytes */<size>), or from the disk forlocalfs. Refresh the folder to see the new size. A416without that size is an error.
7. Local directory (localfs)
The link’s own params (set by the broker’s admin in sys/links or
wyrmd.json5, not by Add Local Directory) list the directories its
connections may use:
links: [{ id: "files", driver: "localfs", params: {
allowed_roots: "/srv/plant\n/mnt/usb" } }]
One absolute path per line; a connection’s root must be one of them or
below one. Empty (the default) allows none: an embedded localfs reads and
writes with the broker’s permissions, so a user with config on the link
must not choose any path of the host. /proc, /sys and /dev are never
allowed. The check runs on add, edit, start and before every probe. A
directory that does not exist yet is checked where it would be made (its
existing part resolved, links followed), so a link inside an allowed
directory that leads out does not take a new root with create_root out
with it. The params are read when the link starts: narrowing
allowed_roots takes effect on the link’s next restart (the admin’s
update restarts it).
| Param | Default | |
|---|---|---|
root | — | an absolute path: /srv/plant/reports, /mnt/usb, /Volumes/NAS/share, D:\reports, \\nas\share |
create_root | false | create it (and its parents) when missing |
read_only | false | refuse Create Folder, Upload File and Delete |
show_hidden | false | show names starting with .; while off they are not written either |
follow_symlinks | false | show symbolic links that resolve inside root (others are never shown) |
fsync | true | sync each upload and its folder (power loss; slower on SD cards) |
timeout_ms | 10000 | bound on each file system call (a hung network mount) |
Where it runs: std::fs only, so the same link on Linux, macOS, Windows
and the BSDs, on x86-64 and ARM boards, embedded in wyrmd or as a process
link (wyrm-link-localfs, package localfs). A process link on another
host shows that host’s directory: run it on the machine with the disk.
Anything the operating system mounts works the same way (NFS, SMB/CIFS,
sshfs, a USB or SD card, a cloud drive’s sync folder).
What it guarantees:
- Nothing outside
root: paths are built name by name below it, and before every change the folder is resolved and must still be inside the resolved root (a folder swapped for a symlink to elsewhere is refused). Symbolic links out ofrootare never shown or followed; deleting a link deletes the link, not its target. rootmay not overlap the broker’s data directory (registry, keys, link data), nor contain it. The link reads and writes with the permissions of its process: for least privilege run it as a process link under its own OS user that may see only the directories it serves.-
- Names for new files and folders are valid on every system: no `/ \ < >
- “ | ? *
, noCON,NUL,COM1…, no.` or space at the end.
- An upload with
overwritegoes to a hidden temporary file (.wyrm-<id>.tmp) and is renamed over the old file, so readers never see half a file; the old file’s permissions stay (its owner and extended attributes do not). Without it the file is created new and a file made meanwhile is never replaced; a failed write removes only what it made. - A hung mount fails the call after
timeout_ms(and the connection probes again); the blocking thread stays until the kernel returns, and while it does the next calls on that directory answertimeoutat once (also after a Stop and Start or an Edit), so one hung mount holds one thread, not one per retry. The place check runs on that pool too. - The root is pinned where the probe resolved it; a root swapped for a link after that is refused on the next change, and the probe checks the new place before it pins it again.
- The temporary file of an overwrite has a name no other process can guess and is removed only when this upload made it; the old file’s permission bits stay, without setuid, setgid or sticky.
- Left: the checks resolve a path, then act on it. On a shared NFS/SMB mount another writer could swap a folder for a link between the two.
- Names that are not UTF-8 (possible on Linux) are left out; sockets, devices and FIFOs are not shown.
8. Failures
- Addresses the link never connects to: link-local (
169.254.0.0/16,fe80::/10, where cloud instance metadata hands out credentials), other cloud metadata endpoints (fd00:ec2::254,100.100.100.200,168.63.129.16,192.0.0.192), unspecified, multicast and broadcast addresses, also inside IPv6 forms that carry an IPv4 address. The check runs on the address the host name resolves to, so DNS cannot lead there either. Loopback and private networks stay reachable: devices and simulators live there (security review, ADR 0031). - The probe (S3: a list of one key; Drive: the root folder; WebDAV:
PROPFIND Depth: 0) or a tree read failing marks the connectionFailedwith theerrorleaf; it reconnects with backoff (1 s … 60 s). The tree stays as last read meanwhile. - An action whose request shows the store is down (no connection, a 5xx,
a timeout) answers
disconnectedortimeoutand makes the connection probe again at once. - A request refused for one object (403, 404, a name taken) fails that
action only (
invalid_parameter,not_found).
9. Simulators
The network links have a simulator binary (feature bin) for demos; localfs needs none (its tests run on temporary directories):
cargo run -p wyrm-link-s3 --features bin --bin wyrm-s3-sim -- --listen 127.0.0.1:9100
cargo run -p wyrm-link-gdrive --features bin --bin wyrm-gdrive-sim -- --listen 127.0.0.1:9101
cargo run -p wyrm-link-webdav --features bin --bin wyrm-webdav-sim -- --listen 127.0.0.1:9102
- S3: bucket
plant, keysAKIASIM/sim-secret-key, path-style (endpoint: http://127.0.0.1:9100). - Drive:
api_url: http://127.0.0.1:9101,token_url: http://127.0.0.1:9101/token,auth: refresh_token,client_id: sim-client,client_secret: sim-client-secret,refresh_token: sim-refresh-token. - WebDAV:
url: http://127.0.0.1:9102/dav/files/alice, useralice, passwordsim-password.
Not yet verified against the real services: the tests run the simulators, and S3 signing is checked against the AWS Signature V4 test vectors.
Messenger links: bots, recipients, templates
The messenger links send messages from the site to chat platforms — alarms, reports, values —
and, where the platform allows, let paired chat users ask for values or switch things. Each
platform is a link of its own on one shared core (crates/wyrm-messenger); this page is what
they share. Design and reasoning: ADR 0039.
| Link | Packages | Guide | Can |
|---|---|---|---|
telegram | telegram (WASM), telegram-process | telegram.md | send; chat users with /get, /set, /do; command buttons |
slack | slack (WASM), slack-process | slack.md | send; mrkdwn and Block Kit |
Install
A messenger link is a package, not built into wyrmd (it reaches the internet with a
third-party token, so a site installs it on purpose):
sys/links▸ Install Link ▸ from Repository:telegram/slack(WASM) or the-processpackage.- Give it network:
api.telegram.org:443orslack.com:443in the link’snet. - Grant what templates (and chat users) may name (
sys/links/<id>/~act/grant):readon, say,wy/<site>/downstream/**;writeon the points chat users may/setor/do.
A bot
downstream/<link> ▸ Add … Bot {name}, then on the bot ▸ Set Token (the platform’s
guide says which token).
status goes no_token → checking → ready; username shows whose bot it is. ▸ Test Connection
checks again. The token is kept in the link’s sealed store, never shown. Edit fields: api_url, ca_pem, timeout_ms, format (the default markup),
queue_max, and on platforms that read updates commands, poll_s, leave_unknown,
rate_per_min. An Edit that
moves api_url or ca_pem deletes the token: set it again.
Recipients
The bot writes only to recipients. ▸ Add Recipient {name, chat, thread, silent} (and
commands where the platform reads updates); the platform’s guide gives the forms of chat
and thread.
Templates
▸ Add Template turns a message into a node with its own Send form:
name high_temp
kind text (text | photo | document | location)
format html (Telegram html | markdown | plain; Slack mrkdwn | plain)
text 🔥 <b>{{who}}</b>: {{temp:.1}} °C (limit {{limit}}) at {{now}}
values temp = wy/plant/downstream/plc1/boiler/temp
who = wy/plant/downstream/plc1/boiler/name
buttons Trend | https://grafana.example/d/boiler ;; Ack | /do downstream/alarm/boiler acknowledge
to ops_group
silent false protect false preview false
{{name}}— a variable of the send (limitabove): the Send form has a field for it; one the send leaves out shows asn/a(Preview shows it so too).{{alias}}— a live value fromvalues({{alias:.1}}decimals,{{alias.q}}quality,{{alias.t}}time);n/auntil it has one, and for a key the template’s author may not read (.qthen saysbad). Up to 32 values per template; the link watches each distinct key once, at most 1000 keys in all.{{site}},{{bot}},{{now}}.- A value map after
|turns the text into another:{{state|NORMAL=🟢,UNSTABLE=🟡,*=⚪}},{{temp.q|good=,bad=❗}}. It looks up the text the placeholder gives without it (after:.N,.q,.t);*is what any other text becomes, and without*the text stays. Up to 16 pairs in 256 bytes; a key or a value holds no,,=,|or braces. What it gives is escaped as any value. - Values are escaped for the format: a device named
<Boiler & Co>shows as such and never breaks the HTML. MarkdownV2 is strict: if Telegram cannot parse a message it is sent once more as plain text (the log says so). buttons: a row per line,;;between buttons.https://…opens a link;/commandruns a chat command for whoever presses it, within that person’s own pairing.- Slack:
blockstakes Block Kit JSON; put placeholders inside JSON strings ("text": "*{{who}}* is at {{temp:.1}}").textis the notification fallback. photo/document:mediais anhttps://URL (Telegram also takes afile_id);textis the caption.location:lat,lon(numbers or placeholders).
Send it: templates/high_temp ▸ send {limit: 80} (write) — from a flow invoke node, the alarm
link or by hand; to overrides the template’s recipients. ▸ Preview returns the request it
would make, without sending.
One message kept up to date. send {…, update: "return"} posts the message the first time
and edits it in place every later time it is sent with the same update name, at each recipient
(a progress line, a state card): text, a photo’s or document’s caption, Block Kit. An edit that
changes nothing is done, not failed; a message deleted in the chat is posted again and edited
from then on. A location is always a new message. update is a name of a-z, 0-9 and _; a
bot keeps the 64 used last (an older one is forgotten: its next send posts a new message), and
<bot> ▸ forget_update {update} (write) forgets one at once. The ids are kept in the link’s
store, so a restart goes on editing the same messages. It needs only write, so a flow can do it (no send_raw). Every recipient shows
recipients/<r>/last_message_id, the platform’s id of the last message it got (Telegram
message_id, Slack ts). to, update and vars are the Send form’s own fields: a template
cannot use them as variables.
A template keeps the rights of whoever added or last edited it: values must be readable by
them.
Ad hoc and raw
<bot> ▸ send {to, text, format, kind, media, lat, lon, silent}andrecipients/<r> ▸ send {text}(write): a one-off message; only{{site}},{{bot}},{{now}}are filled in.<bot> ▸ send_raw {method, params}(config): any other method of the platform’s API the link offers, by exact name (its guide lists them); every param that names a chat or an account must name a recipient’s chat or a paired user’s, and a request whose chat cannot be checked is refused.
Who may talk to a bot
Nobody, until an operator invites them, on platforms that read updates (Telegram today): see
telegram.md. Unknown chats and accounts are ignored and counted in
<bot>/rejected.
Status and limits
<bot>/{status, error, sent, failed, dropped, queued, rejected, last_sent}, totals in stats/.
sent, failed and dropped count the queue (templates, send); send_raw goes out at once,
outside it: its answer is the action’s result, and the audit names it.
429 Too Many Requests holds the bot as long as the platform asks; network errors back off up to
a minute and keep the message (5 attempts); refused messages are dropped and counted failed.
Pacing per chat is the platform’s (Telegram: one message per chat per second). Up to 8 bots, 64 recipients, 64 templates
and 100 users per bot.
Telegram link
links/telegram, packages telegram (WASM) and telegram-process; bots, recipients and
templates as in messenger.md. ADR 0039.
Token and network
@BotFather ▸ /newbot gives the token (123456789:AA…): <bot> ▸ Set Token. net:
api.telegram.org:443 (or a local Bot API server named in api_url). Turn the bot’s Group
Privacy off in @BotFather only if paired users should command it in groups.
Recipients
chat: a chat id (-1001234567890), @channel, or user:<paired user> (that user’s private
chat, once paired). thread: a forum topic id. commands: true lets paired users command the
bot in that group.
A person can also get messages without pairing: a recipient whose chat is their numeric
Telegram id (123456789). They must have written to the bot first (Telegram lets a bot open no
chat); until they are a recipient, the link’s log names them (rejected account 123456789: not paired). They can receive only: commands need pairing (Chat users, below).
To find a group’s id: add the bot to the group; it is no recipient yet, so it leaves and the
link’s log names the chat (rejected chat -100… (supergroup)). Add the recipient, add the bot
again.
Templates
Formats html (default; values escaped as HTML entities), markdown (MarkdownV2; values
backslash-escaped; a message Telegram cannot parse goes again as plain text), plain. Kinds
text, photo / document (media = URL or file_id, text = caption ≤ 1024), location.
buttons take links and /commands (≤ 64 bytes after filling in), a command run for whoever
presses it. silent, protect (no forwarding or saving), preview (link previews).
send {update} edits with editMessageText (a text) or editMessageCaption (a photo’s or a
document’s caption; the media stays); Telegram’s “message is not modified” counts as done,
“message to edit not found” posts it again.
Raw requests
send_raw {method, params} (config) for the rest of the Bot API. It fails closed: only these
methods, by exact name, are offered:
sendMessage,sendPhoto,sendAudio,sendDocument,sendVideo,sendAnimation,sendVoice,sendVideoNote,sendMediaGroup,sendLocation,sendVenue,sendContact,sendPoll,sendDice,sendSticker,sendChatAction;editMessageText,editMessageCaption,editMessageMedia,editMessageLiveLocation,stopMessageLiveLocation,editMessageReplyMarkup,stopPoll,deleteMessage,deleteMessages,pinChatMessage,unpinChatMessage,unpinAllChatMessages,setMessageReaction,getChat,getChatMemberCount(all needchat_id);forwardMessage,forwardMessages,copyMessage,copyMessages(needchat_idandfrom_chat_id);getMe.
Every chat_id, from_chat_id, user_id and sender_chat_id in the params must be a
recipient’s chat or a paired user’s, whether the method needs it or not; a method’s chat param
that is missing refuses the request, and so do inline_message_id and business_connection_id
(their chat cannot be checked). getUpdates, webhooks, logOut, close, commands and the bot’s
profile are never offered: they would take the bot’s updates or the bot itself from the link.
{"method": "sendPoll", "params": "{\"chat_id\": -1001234567890, \"question\": \"Shift OK?\", \"options\": [\"yes\", \"no\"]}"}
Updates
The link reads getUpdates every poll_s (3 s) — no webhook, no inbound port, works behind
NAT; the next offset is kept in the link’s store, so a restart never runs a command twice.
commands: false makes a send-only bot (no polling). A webhook set on the same token by
another client makes Telegram answer 409, shown as the bot’s error.
A failed getUpdates holds only the reading: status stays ready while messages go out,
error says updates: <why>, and the reading tries again after 1 s, doubled up to a minute.
status is waiting only when sending waits (a 429, a network error on a send).
Chat users
Nobody, until an operator invites them. Telegram bots are public: anyone can write to one or add it to a group, so the messenger ignores everyone it does not know.
- ▸ Invite User {name, level, select} (config).
level:read(/get) orwrite(also/set,/do).select: the keys their commands may name, one per line, each a full node key without wildcards (wy/plant/downstream/plc1,wy/plant/storage/dvpsm/cmd); a key covers its whole subtree. Empty:wy/<site>/downstream. You cannot invite anyone beyond your own rights, and a command works only where the link’s grants reach too (sys/links/<id>▸ Grant Access; storage since ADR 0046), so give the link the same keys. - The answer shows a pairing code once, valid 15 minutes, single use. Give it to that person only (not in a group chat).
- They open a private chat with the bot and send
/start ABCDE-FGHJK. The bot binds their Telegram account (its numeric id) to the user;users/<name>/statusbecomesactive.
Then, in the private chat:
/get downstream/plc1/boiler/temp the value, its quality and time
/set downstream/plc1/boiler/sp 65 write (level write)
/do downstream/alarm/boiler acknowledge
/whoami /help
A command runs only if all three allow it: the user’s level and keys, the rights of the operator who invited (or last edited) them, and the link’s grants. The messenger itself is never written from a chat.
- Groups: commands work only in a recipient with
commands: true, and only from paired users. Groups the bot is added to that are no recipient are left. - A code sent in a group is void at once; 5 wrong codes lock an account out for an hour.
- Lost phone or new account: ▸ New Pairing Code (unpairs the old account). ▸ Disable / Enable / Edit / Remove at any time. New Pairing Code, Enable and Edit hand the user’s rights to an account, so only an operator who holds the user’s level on all its keys may run them.
- Every rejected update counts in
<bot>/rejectedand the log; every command is logged with the user and key (never values). 20 commands a minute per user (rate_per_min).
Slack bots send only, for now (receiving needs Socket Mode; ADR 0039).
Slack link
links/slack, packages slack (WASM) and slack-process; bots, recipients and templates as in
messenger.md. ADR 0039.
Token and network
Create a Slack app, add the bot scope chat:write (and reactions:write, pins:write for
those raw methods), install it to the workspace and copy the Bot User OAuth Token
(xoxb-…): <bot> ▸ Set Token. net: slack.com:443. Invite the bot to each channel it posts
in (/invite @bot).
Recipients
chat: a channel id (C0123456789, from the channel’s details). thread: a thread_ts
(1700000000.000100) to post in a thread.
Templates
Formats mrkdwn (default; values escaped as &, <, >) and plain. blocks
takes Block Kit JSON, an array; put placeholders inside JSON strings
("text": "*{{who}}* is at {{temp:.1}}"). A value filled in there is escaped for mrkdwn first
(&, <, >) and then for JSON, so it can be neither a mention (<!channel>) nor a
link (<https://…|text>); in a plain_text object Slack shows those entities as the characters.
text is the notification fallback. A photo is an image block; a document a link; a location an
OpenStreetMap link. buttons are links only (an actions block). preview turns unfurls on.
Raw requests
send_raw {method, params} (config) fails closed: only these methods, by exact name, are
offered: chat.postMessage, chat.update, chat.delete, chat.meMessage,
chat.getPermalink, chat.scheduleMessage, chat.deleteScheduledMessage, reactions.add,
reactions.remove, reactions.get, pins.add, pins.remove, pins.list,
conversations.info (all need channel) and auth.test. Every channel, channel_id, user
and users in the params must be a recipient’s channel; a missing channel refuses the
request, and so do file and file_comment (their channel cannot be checked).
Send only
A Slack bot does not read messages yet: receiving needs Socket Mode or the Events API
(ADR 0039), so it has no chat users, no /command buttons and no user:<name> recipients.
429 and ratelimited hold the bot for 30 s; invalid_auth, token_revoked, missing_scope
make it failed until Set Token.
Operations: run, restart, back up and restore a broker
This page is for whoever keeps a wyrmd running: how to run it under a
supervisor, what a restart recovers on its own and how long that takes, and
what to copy for a backup. Design: ADR 0003 (the broker owns only itself),
ADR 0036 (fault tolerance; this page is its option 1, “supervised restart”).
1. What a restart recovers
A broker that stops, for any reason, and starts again comes back whole from
its data_dir and from its links:
| What | Where it comes from after a start | Lost by a kill (SIGKILL, power) |
|---|---|---|
| Links, ACL, PKI, tokens, peers, profiles, flow definitions, users, history settings | the control-plane WAL (state/, flows/, gateway/, audit/), every append fsynced; a snapshot only speeds the start up | nothing; a record cut off at the end (a crash while it was written) is dropped, wyrmd verify shows it as a torn last record |
The node tree and ~val | the links: each one re-declares its subtree and its last values when it sees the broker’s liveliness token wy/<site>/sys/broker again | nothing; values are back as soon as each link polls again |
Values of storage, scheduler events, alarm records, DQL queries, uplinks, runtime edits of drivers | their redb files and sealed stores in data_dir (every write is synced) | nothing |
| History rows | history/days/*.redb | the rows still in the write buffer: up to buffer_flush_time of each watch group (5 s by default) |
| Gateway sessions | nothing: users log in again (the explorer’s client reconnects and reopens its streams) | all |
A set or an action in flight | nothing: the caller gets an error and repeats it | that one request |
| The audit journal | audit/ | nothing already written; a link’s records that the broker had received and not yet written (at most 1024, about one fsync of time); records a link put while the broker was away are not sent again (ADR 0029, decision 7) |
The audit journal: what is durable when. One thread writes the journal.
It takes the records that wait (at most 256) and writes them as one batch:
one write, one fsync, then the anchor (state_anchor_dir). The records,
their order, their CRC and their HMAC chain are the ones a write per record
makes; only the number of fsyncs differs.
- A record the broker makes itself (an admin action, a login, a change of
role, an update: everything but the next item) is on disk before the
operation goes on. The caller waits for the
fsyncthat covers its record; a failed write is logged asaudit write failed. - A record a link reports for its own
set/invokewas never acknowledged: the link puts it after the command and does not wait (ADR 0029, decision 7). The broker queues it in the order it arrived and writes it with the next batch. A failed write is logged. - The queue holds 1024 records. When it is full, who adds a record waits;
nothing is dropped to make room. (The limit of 50 records per second for a
link over the network, ADR 0031, is apart and is itself audited as
audit_dropped.) - A stop (SIGTERM) writes the whole queue before the store closes. A kill loses only link records that were still in the queue.
- With
state_anchor_dir, a batch of two or more records first writes the anchor as<lsn> <mac> +<n>: “nrecords follow this head”. After the batch the anchor is the plain head again. A start after a kill inside a batch finds that announcement and accepts any whole prefix of the batch; no caller had an answer for those records. Without the announcement the rule is as before: at most one record after the anchor. - While the broker’s own update is in its trial (
update.jsonsaystrial, §2: from the moment the update is staged untilupdate_confirmed), the journal writes record by record: one write, onefsync, the anchor at the plain head, exactly as every earlier version did. A kill in a trial is followed by the previous version (the guard goes back), and that version must open what this one left; a version from before group commit does not read an announcement. So in a trial the files never hold one. This is a rule, not a case for one version: what a version in its trial leaves on disk is what the version before it opens. The journal takes about onefsyncper record for those minutes (the rate of before); after the confirmation it writes batches again. The same holds from the momentrollback_updateis asked for a confirmed update (update.jsonnames who asked): the guard starts the previous version next, however this process ends. The action answers only after the switch holds: a batch that was being written is on disk and the anchor is the plain head. - A downgrade by hand, outside a trial, to a version from before group
commit: stop the broker first (a stop leaves the plain head). Only after
a kill inside a batch can such a version refuse the anchor (
records behind the WAL): start the newer version once, or runwyrmd verifyand thenwyrmd init-anchors. - A write to a control-plane WAL that fails (all stores: registry, flows,
users, audit) leaves no bytes behind: the file is cut back to the length
it had, and the store goes on. If the cut fails too, or if it was the
fsyncthat failed (what the disk holds is then not known), the store takes no more writes until the broker starts again: every later change is refused withthe store takes no more writes until it is opened again, an audit record is logged asaudit write failed. A start reads the file, drops a torn record and goes on. Nothing is appended after bytes the store does not know (before: the next record followed them, and the next start read a broken log). - If the journal’s writer thread ever ends by a panic, the queue is closed:
every caller that waits, and every later one, gets an error (logged as
audit write failed); nobody waits for ever. The broker’s operations go on unaudited until a restart, and the log says so (the audit writer ended by a panic).
So the broker needs no cluster to survive its own crash: it needs to be
started again, quickly, with the same data_dir. That is the supervisor’s
job.
2. Run under a supervisor
systemd
# /etc/systemd/system/wyrmd.service
[Unit]
Description=WYRM broker
After=network-online.target
Wants=network-online.target
[Service]
User=wyrm
Group=wyrm
ExecStart=/usr/local/bin/wyrmd -c /etc/wyrm/wyrmd.json5
WorkingDirectory=/var/lib/wyrm
# First start only: creates the gateway's first admin; remove the file after.
EnvironmentFile=-/etc/wyrm/first-admin.env
# A crash, a kill or an exit code: start again after one second.
Restart=always
RestartSec=1
# SIGTERM ends the broker cleanly (history flushed, links told to stop);
# the process links are in the same control group and die with it.
KillSignal=SIGTERM
KillMode=control-group
TimeoutStopSec=20
LimitNOFILE=16384
# data_dir holds the keys of the site: nobody else reads it.
UMask=0077
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/lib/wyrm
PrivateTmp=yes
NoNewPrivileges=yes
[Install]
WantedBy=multi-user.target
Notes:
data_dirmust belong to the user the broker runs as. The broker makes it 0700 whenwyrmd keys importwritesstate.keyand the other key files into it, and a standby does the same when it copiessecrets.binand the replicated files;data_dir/pki,links/<id>,links/<id>/data,operators, the backups’ and restore points’ directories are made 0700 too. Each of them must be a real directory owned by that user: one that is a symlink (belowdata_dir), or that another user owns, is refused with its path, and the broker does not write keys into it.data_diritself may be a symlink the operator set up (/var/lib/wyrm→/srv/wyrm).wyrmdstops cleanly on SIGINT and SIGTERM. A clean stop flushes the historian’s buffers and gives each process link its SIGTERM (10 s, then a kill). A process link whose broker vanished without a signal sees its parent go and exits by itself within a second, so aKillModeofcontrol-groupis a belt on top of braces.Restart=alwayswithRestartSec=1: the broker refuses to start on a bad configuration or a port in use, and systemd will then retry for ever at that pace;StartLimitIntervalSec/StartLimitBurstin[Unit]stop that if you prefer a loud failure.wyrmd -c … checkvalidates a configuration before a restart.WYRM_GATEWAY_ADMIN_PASSWORDis read once and cleared from the process environment; the file it came from is still on disk, so delete it after the first start (EnvironmentFile=-tolerates a missing file).- A listener port still held by something else ends the broker with that
error (Zenoh tries a listener once); with
Restart=alwaysthe next attempt comes a second later, which covers a port the kernel releases late after a kill. A port held by another program stays an error in the journal. wyrmdas a container: one container per broker,data_diron a volume,restart: unless-stopped(compose) or a restart policy of the orchestrator,stop_grace_periodof 20 s so SIGTERM has time to flush. The process links run inside the same container.
Gateway TLS from the site CA (ADR 0051 §3)
A gateway that listens beyond loopback needs TLS. Without a certificate of your own, let the broker issue one from its site CA:
gateway: { listen: "0.0.0.0:8445", tls: "site_ca" },
- At each start, before the gateway opens, the broker asks its site CA
(
data_dir/pki, made on the first start) for a server certificate with CNgateway:<site>and writes it todata_dir/gateway/tls.pemandtls.key(0600). - The certificate names
<hostname>.local,wyrm-<site>.local(the name the DNS-SD announce gives) and the addresses clients use: every non-loopback address of the host (IPv4, and IPv6 except link-local) whenlistenis0.0.0.0or[::], else only the listen address. On Linux (OpenWrt too) the broker reads/proc/net/if_inet6and leaves out IPv6 addresses that are temporary (privacy addresses, RFC 8981), deprecated, tentative or failed their duplicate check. On macOS and BSD the address list gives no such flags, so every global IPv6 address is named, and a host with privacy addresses gets a new certificate each time one rotates; to avoid that, setlistento one address. The host name is cut at its first dot; a host whose name cannot be read useswyrm-<site>. While the host has no usable address (before DHCP), the certificate names only the.localnames; it is issued again when an address comes. - A restart keeps the certificate as it is while it names exactly the same names and has more than 30 days left; otherwise the broker issues a new one from the same CA. A certificate that names more (an address the host no longer has) is issued again too. Clients pin the CA, not the certificate, so a new one needs nothing on their side.
- While the gateway serves, the broker reads the host’s addresses every
30 s. When the names differ from the names of the certificate it serves
(an address from DHCP after the start, a new or lost address), or that
certificate has less than 30 days left, it issues a certificate for the
names and serves it from the next connection on, without a restart. A key
that is not the certificate’s (a power cut between the two writes) also
makes a new pair. Open connections keep the old one. The log says
gateway: certificate issued for <n> names.GET /api/infonamesand the device-key origins follow the new certificate at the same time. - Clients trust
data_dir/pki/ca.pem.ca_fpinGET /api/info, thefpkey of the DNS-SD announce andwyrmd ca fingerprintare the code of that CA. - Files of your own (
tls_cert/tls_key) are read at the start and again at each router rebuild (an ACL change): a renewed pair is served from then on. At the start, a pair that cannot be read or does not match stops the broker:wyrmddoes not start, and the error names the gateway. Fix the files and start again. At a rebuild, such a pair leaves the certificate in force, with a warning in the log. - A key restore from another site’s backup (other keys, ADR 0048) sets
aside
data_dir/gateway/tls.{pem,key}with everything else the replaced CA issued, and the site CA issues the gateway’s certificate again at the next start. A certificate that the site CA did not sign is never kept. tlsexcludestls_cert/tls_key. A certificate from a public CA (for the remote MCP connector, claude.md) still goes intls_cert/tls_key.
First admin from a setup code (ADR 0051 §3)
A broker made from an image carries no password. Its first admin comes from a one-time setup code; the image holds only the code’s hash.
-
Make a code on any machine:
wyrmd setup-code. It prints the code on the first line (ABCD-EFGH-…, 26 base32 characters) and its hash (64 hex digits) on the second. It needs nowyrmd.json5. -
Write the hash line into a file and name it in the configuration:
gateway: { listen: "0.0.0.0:8445", tls: "site_ca", setup_file: "/etc/wyrm/setup" }, -
Give the code to the person who sets the broker up, apart from the image. Keep it secret: whoever has it makes the first admin. Keep the hash like a secret of the image too (the file, the image, the build service): whoever holds it can prove a CA to a client that has the code.
-
Start the broker. While no user exists, it moves the hash into
data_dir/gateway/setup.hash(0600) and deletessetup_file. The log saysgateway: setup code taken in. -
The person opens Studio.
GET /api/infoshowssetup: true, and Studio asks for the code, an admin name and a password. The right code makes that admin, and the setup is over: the code cannot be used again.
The first contact is how the client learns which CA to trust (owner’s answer 3 of ADR 0051), so the code proves the server to the client before the client proves the code to the server. A client does this, in this order:
- Read
GET /api/infoover TLS, accepting the certificate for now. With a setup pending and TLS on, the answer holdsca(the DER of the CA) andsetup_proof: HMAC-SHA-256 keyed with the setup hash over"wyrm-setup-proof-v1\n"and the bytes ofca. - Compute the hash from the typed code and verify
setup_proofagainst thecait was shown (wyrm_gateway::setup::verify_setup_proof). Check that the certificate of the connection chains to thatca. If the proof is missing or does not verify, stop: send nothing, and say that the device is not the one the code belongs to. - Only then send
POST /api/setup {code, user, password}on a connection that trusts thatcaalone. - Pin that
cafor every later connection.
Without the hash, nobody can make a proof for a CA of their own, so a
device that answers in place of the broker gets neither the code nor the
new admin’s password. Over plain HTTP (loopback) there is no ca and no
proof.
- The code may be typed in lower case, with spaces or
-between the groups, or with none. - Wrong codes count against the failed-login limits, as wrong passwords
do: 5 failures per 60 s for one user name from one address, and 20
failures per 60 s from one address over all user names (an IPv6 address
counts by its /64). Logins and setup attempts share both budgets; past
them the gateway answers
429. They are audited as failed logins with the reasonsetup_code_wrong; the first admin as a user added bysetup. Neither the code nor its hash is logged. - Once a user exists, a setup is void. A
setup_fileis then ignored and deleted, and asetup.hash(a restored backup, a crash between the new admin and the removal) is deleted at the next start./api/setupanswers409 no_setup. - A
setup_filethat is not 64 hex digits (white space around them aside) stays where it is, with a warning in the log that names it. Asetup_filethat cannot be deleted is a warning too; it is void once a user exists. - A damaged
data_dir/gateway/setup.hashwith no user is logged at start with its path and reason, and/api/infoshows nosetup. To recover, stop the broker, make a new code withwyrmd setup-code, write its hash intosetup_file, and start again: the new hash replaces the damaged file. WYRM_GATEWAY_ADMIN_PASSWORDstill works. When it creates an admin, a setup file of the same start is void.- A warm standby (ADR 0036) does not receive
data_dir/gateway/setup.hash: a pending setup belongs to its host. Make each host of a pair from an image with its ownsetup_file. Users replicate, so once the first admin exists on the active, the setup of the other host is void. A following standby does not read itssetup_file; the file is dropped when that host’s broker opens as an active (at its promotion), as above.
Seed packages (ADR 0051 §1)
A broker made from an image can install link packages on its first start.
The image cannot put them into data_dir/packages: data_dir is made at
the first start, and the broker removes a package directory that its
registry does not know. So the image carries the packages in a read-only
directory with a list:
packages: { seed_dir: "/usr/share/wyrm/seed" },
/usr/share/wyrm/seed/seed.json:
{
"format": "wyrm-seed/1",
"links": [
{ "link": "modbus", "file": "modbus.zip", "accept": true },
{ "link": "mqtt", "file": "mqtt.zip" }
]
}
formatmust bewyrm-seed/1. An unknown field is an error.linkis the id of the new link.fileis a package zip (as forinstall_zip) in the same directory.accept(defaultfalse) is the Accept requested rights ofinstall_zip: without it, a package that asks for a network allowlist or grants is not installed.fileis a plain name: no/or\, no leading., not empty. The broker opens it without following a symlink. The seed directory itself may be a symlink. A zip is bounded as forinstall_zip(64 MiB).- On the first start, once the router listens, the broker installs each
entry as
sys/links ▸ install_zipdoes, with the same checks, as the subjectbroker:seed(in the audit journal). An entry whose link exists already (a restored backup) is skipped before its file is read: the seed never changes that link or updates its package. A new link of a package that is installed at another version is an update, as withinstall_zip: the package moves to the seed’s version, with every link that runs it (links.md §5a). - One entry that fails does not stop the others. When every entry was
tried, the broker writes
data_dir/seed.done(0600, written whole) and never runs the seed again. The file holds the time and, per link,ok,skipped: the link exists,started and not finished: …(below), or the message of the failure. The log saysseed: link <id> installed,… skipped (exists), or a warning with the message. - The seed runs at the first start that finds
seed.jsonand noseed.done. Normally that is the first start. A broker that has run for a long time without a seed (aseed_dirwith noseed.json) also installs the links of aseed.jsonthat an image update adds, at its next start. - To run the seed again, delete both
data_dir/seed.doneanddata_dir/seed.progress.jsonand restart. Links that exist are skipped, failed entries are tried again. Withseed.progress.jsonleft in place, entries that have an outcome in it are not tried again. - Each install is one operation of its own: a router rebuild (an ACL
change, a process link that the seed installed) waits for the install in
progress, not for the whole seed. While a rebuild holds the broker, the
seed waits (up to 60 s). If the broker closes meanwhile, the seed stops
without
seed.doneand goes on when the admin starts again. data_dir/seed.progress.json(written whole) records, per link, when its install started and its outcome; it goes whenseed.doneis written. A run that stops beforeseed.done(a rebuild, a stop, a power cut) goes on at the next start from this file:- an entry with an outcome keeps it and is not tried again;
- an entry that started and has no outcome was cut short during its
install. Its link or package may be half made (a link without its
grants). The broker logs a warning, writes
started and not finished: …inseed.doneand does not install it again. Check the link and its package: install it again withinstall_zip, or remove it; - the other entries are tried.
- A warm standby (ADR 0036) receives
seed.doneandseed.progress.jsonwith the other replicated files. A promoted standby never runs a finished seed again, so links that the operator removed do not come back; an unfinished seed goes on where the active stopped. The standby copies the files and the registry WAL in separate polls, so the two can differ by a poll at a failover. A link the active was installing just before the failover can then show asskipped: the link exists(the registry has the link, the copied progress file does not) or asstarted and not finishedon the promoted host. Check such a link as above. - An entry whose install succeeded but whose outcome could not be written
to
seed.progress.json(a full disk) shows asstarted and not finishedat the next run. The link is there; check it as above. - A
seed.jsonthat is missing or cannot be read (bad JSON, anotherformat, a link listed twice, more than 256 links) installs nothing and writes noseed.done. The broker logs a warning and tries again at every start. Aseed.progress.jsonthat cannot be read does the same.
Recovery time
The recovery time (RTO) of a restart is the sum of:
- the supervisor’s delay (
RestartSec); - the router build: the state is read from the snapshot and the WAL tail, the ACL generated, the listeners opened — one to three seconds;
- embedded links: started at once with the router;
- process links: spawned by the supervisor when the admin attaches, which
is before the listeners open, so a link’s first connect is usually
refused (one
cannot connectwarning per start) and its next one comes 1 s later; then it opens its mTLS session and sendshello. A refused connect andhelloare retried with a back-off of 1 s, ×2, capped at 5 s, which matters more for a link that starts before the broker answers (a link under its own supervisor, or on another host); - the first poll of every device, at that device’s poll rate.
The e2e test broker_restart_rto measures 2–5 for one embedded and one
process mock link: a real wyrmd process is killed with SIGKILL and started
again at once; the clock stops when both links show state connected in
sys/links and each has published a live sample to a subscriber opened
after the restart. It also prints the resident memory of a broker that runs
no link. A failed wait names its phase (first start or start after
SIGKILL) and shows what the test’s session and a new session see, the link
processes and the last output of the link process. Run it on the target
hardware:
cargo test --release -p wyrmd --test e2e broker_restart_rto -- --nocapture
Measured figures live in docs/backlog.md item 13 beside the wyr bench
numbers (first figure: 1.6 s from the start command to both links live, in
a debug build on an x86_64 container). Without a figure from the reference
board (4-core ARM64, 2 GB) assume ten seconds for the broker and add the
slowest device’s poll period.
Several endpoints (ADR 0036, option 2)
A client or a link may name several broker endpoints, comma-separated, in the order to try. Today a site has one broker, so the list is the one broker’s addresses; with a standby broker (option 3, “Warm standby” below) it is both brokers, and nothing on the client side changes at a failover.
wyr --connect tls/a:7448,tls/b:7448,wyrm_open("tcp/…,tcp/…")in the C API and Dart FFI: Zenoh’s client mode connects to the first endpoint it reaches and tries the list again when the connection drops.- Links run by hand (external links, a package on another host):
WYRM_ENDPOINTtakes the list. The link opens one session per endpoint and serves a router only while the site’s broker is behind it, told by the liveliness tokenwy/<site>/sys/broker: a router without the token, or whose token has been gone forWYRM_BROKER_WAIT_S(15 s), is left for the next endpoint. The token is one key, so two brokers that claim one site are never both served by a link. Links the broker supervises get the broker’s own endpoint and die with it, so they need no list. - Gateway clients: the Dart
WyrmGateway.loginAny([url1, url2], …)logs in on the first gateway that answers and keeps the credentials, so itsclient()logs in again on the next gateway when the one in use is gone or does not know the session (each broker holds its own sessions).
Warm standby (ADR 0036, option 3)
Two brokers of one site on two hosts, one active, one following. The
standby copies the control plane (the registry, flow definitions, gateway
users), secrets.bin, the link tokens, the links’ private data (the
sealed stores of the scheduler, alarm, DQL and uplink links, runtime edits
of drivers, the agent’s store), the installed packages, the seed’s
seed.done and seed.progress.json, and the broker storage and the
historian’s rows as they change, and takes over when
the active is away. It runs no router and polls no device until then.
What it does not copy: files over 64 MiB in a link’s data or a package
(they are logged and skipped), the audit journal (it stays on the
host that wrote it), and a pending setup code (gateway/setup.hash,
“First admin from a setup code” above).
Set it up once:
-
Both
wyrmd.json5files are the same but for the addresses, and both have a QUIC peer listener and astandbysection naming the other host (tls_namesmust contain the host name or address the other side uses):peers: { listen: "quic/0.0.0.0:7449" }, // host A standby: { peer: "quic/10.0.0.2:7449", takeover_s: 10, primary: true, witness: ["10.0.0.254:443", "10.0.1.10:502"] }, // host B standby: { peer: "quic/10.0.0.1:7449", takeover_s: 10, primary: false, witness: ["10.0.0.254:443", "10.0.1.10:502"] },primary: trueon one host only: it takes over aftertakeover_s, the other after three times that, and when both are active after a network split, the other steps down.witnessis required: TCP addresses on the plant network that each host must reach to be active, typically the network gateway and one or two PLCs the site polls (any port that accepts a connection: 443 of a router, 502 of a Modbus device). Any one answering is enough. A host that reaches none of them is the side that is cut off: it does not take over, and an active broker that reaches none and no longer hears its standby steps down after half oftakeover_s, before the other side can take over. Keeptakeover_sat 10 or more, so that both sides see the split in time. List more than one witness: if every witness is down while the standby is down too, the active steps down and the site has no broker until a witness answers again.A witness cannot tell a host whether the other host is active. When both hosts reach a witness but not each other (a firewall between them, a hung process), both would be active. Add a lease arbiter on a third host to close that case (section “Lease arbiter” below):
standby: { peer: "quic/10.0.0.2:7449", takeover_s: 10, primary: true, witness: ["10.0.0.254:443"], arbiter: ["10.0.0.3:7450"] },Without
arbiterthe broker logs a warning at start. -
On the broker that has run (host A), export the site’s keys with a passphrase of at least 12 characters, and carry the file to host B:
WYRM_KEYS_PASSPHRASE='…' wyrmd -c wyrmd.json5 keys export site-keys.wykb -
On host B, with an empty
data_dir:WYRM_KEYS_PASSPHRASE='…' wyrmd -c wyrmd.json5 keys import site-keys.wykbthen delete the file on both hosts: it is the site.
-
Start
wyrmdon host B as on host A (section 2). It logsstandby: following; host A showssys/standby_connected1 andsys/standby_lag0 once it has caught up.
What happens at a failover: host A goes; after takeover_s (three
times that for a host that is not primary), and while a witness answers,
host B logs standby: promoted, opens the broker on the followed
data_dir, and the links, gateway clients and upstream brokers that know
both addresses (section “Several endpoints”) come to it.
There is no automatic failback. When host A comes back it finds host B
active, follows it (standby: following) and stays the standby, primary
or not: a switch back would cost another gap. To make host A active
again, stop wyrmd on host B at a quiet moment; host A takes over after
takeover_s and host B, started again, follows it.
The primary rule matters only when both hosts became active across a split that has healed: the one that is not primary sees the primary’s broker token, steps down and follows it. What it wrote while it was active is moved aside on that host, not merged:
- registry, flow and user records: as
state.stale.<n>(andflows/state.stale.<n>,gateway/users.stale.<n>); - files the active does not hold or holds otherwise (sealed stores of the
scheduler, alarm, DQL and uplink links, driver edits, packages): into
standby/stale/<t_ms>/files/; - a broker storage tree that differs from the active’s: exported as
standby/stale/<t_ms>/storage.json(the format of the storage’sexportaction, forimport).
The active writes one audit record standby_forked per set (the detail
names the place on the other host) and counts them in
sys/standby_forks. A value above 0 means: look at what the other host
moved aside, and enter again what must stay.
History-sync links (ADR 0026) go on from where they were after a
failover: the standby carries each sink’s confirmed cursor over in its own
journal numbers. A sink sends again at most the last page it had not
confirmed (≤ 2 000 rows); the targets replace on (key, t). A former
active whose sinks had not confirmed all of its own rows keeps their
cursors until it is active again: then it sends those rows, and the rows
it copied after them, again.
A router rebuild on the active (a link installed, a peer added, new signing keys) closes its listeners for a moment; the active first tells its standby to wait (up to 60 s, released as soon as the router is up), so a rebuild never looks like a failure. With a standby connected each rebuild starts 2.5 s later, for the standby to read that.
Each change of role is an audit record by system: promoted, or
demoted with the reason (the primary is back; cut off; another broker
holds the arbiters’ lease; the lease ran out and the standby is quiet).
Lease arbiter
An arbiter is wyrmd in a mode of its own on a third host (any small
machine on the network of both brokers: the upstream site’s host, a
gateway PC). It holds one lease per site in memory and grants it to one
broker at a time:
- the standby takes over only once a majority of
standby.arbitergrants it the lease, so a running active keeps the role however the two hosts see each other; - the active renews the lease every second; told that another host holds it, it steps down at once; when it cannot reach the arbiters, it runs on while its standby still follows it, and steps down when the lease has run out and the standby is quiet;
- the lease lasts half of
takeover_s(3 s at least, 30 s at most); a started arbiter grants nothing for 30 s, since a lease it forgot may still run on a broker.
Set it up:
- On a broker of the pair, write the arbiter’s files (the site CA, a
certificate
arbiter:<site>for the address the brokers dial, the site name):wyrmd -c wyrmd.json5 arbiter issue --host 10.0.0.3 --out arbiter-demo - Copy the directory to the third host and run the arbiter under a
supervisor, as
wyrmditself:wyrmd arbiter serve --dir arbiter-demo --listen 0.0.0.0:7450 - Add
arbiter: ["10.0.0.3:7450"]to thestandbysection on both hosts and start them again, one after the other.
The arbiter checks that a broker’s certificate is standby:<site> from
the site’s CA, and the brokers check that the arbiter’s is
arbiter:<site>; nobody else (links, downstream brokers) can take or
grant the lease. Its directory holds no private key of the site, only its
own; its certificate lasts 20 years. The active shows the seconds left of
its lease as sys/arbiter_lease_s (0: none) and logs a warning when no
arbiter answers.
Caution: one arbiter is a single point: when it is down while the standby is down too, the active steps down. Run three arbiters on three hosts for a site that must ride out that (a majority of two decides). With one arbiter down the pair keeps working, and a failover still needs a majority.
Rules of thumb:
- Keep the two
wyrmd.json5files the same. A link named in host A’slinksand not in host B’s is gone after a failover. - The standby’s
data_diris as sensitive as the active’s: it holds the site’s keys. - The standby follows asynchronously: the operation made in the second the active died may be lost; the administrator sees it missing.
- The links the broker supervises (
mode: "process") die with it and are started again by the new active; links run by hand and external links need both addresses inWYRM_ENDPOINT. - With
state_anchor_diron the standby, the follower keeps the anchors at its head; a history that forked (a record the standby never got) is moved aside asstate.stale.<n>and copied again from the active.
A broker that updates itself (ADR 0048 §2)
By default a broker is updated by hand: replace the binary, restart
(updates.mode: "off"). Two other modes are set on the host, in
wyrmd.json5:
updates: {
mode: "self", // "off" (default), "external", "self"
channel: "https://…/releases.json", // the signed channel file; optional for "self"
keys: ["<Ed25519 public key, hex>"],// release keys trusted besides the built-in ones
trial_s: 180, // 10 to 3600: how long a new version has to prove itself
keep_days: 7, // 1 to 90: how long a confirmed update can be rolled back
}
external(a container, a distribution package): the broker reads the index and showssys/latest,sys/update_availableand, insys/update_hint, what to run. It never replaces itself:updateis refused with that text. Change the image tag where the container is defined and rundocker compose pull && docker compose up -d, or install the new package andsystemctl restart wyrmd. Make a backup first (section 3).self:sys/~act/updatereplaces the broker and takes the new version back when it does not prove itself. It needs the layout and the unit below. Linux and macOS only.
updates.channel is a public URL: https:// (plain http:// only to a
loopback address, for a mirror on the broker host). A URL with a user or
password, a query string or a fragment is refused when the configuration
is read: the channel is shown in sys and in the config copy of a
backup, so it must hold no credential. A private mirror is reached
through the network (a VPN, a mirror on the plant network), not through a
token in the URL.
The release key: this version of wyrmd has no built-in release key.
A broker trusts only the keys in updates.keys; with none, every update
is refused. packaging/wyrmd/README.md says how a key is made.
Layout and unit
/opt/wyrm/versions/0.1.0/wyrmd one directory per version
/opt/wyrm/versions/0.2.0/release.json, release.sig the signed release a version came from
/opt/wyrm/current -> versions/0.1.0 a symbolic link, switched by one rename
/opt/wyrm/bin/wyrmd-guard a copy of the previous version's binary
/opt/wyrm/bin/trusted.json versions put there by hand, with the SHA-256 of each binary
- As root, make the layout from the binary you have:
wyrmd install-layout /opt/wyrm. It prints the unit lines and names that binary inbin/trusted.json. - Set the owners. The broker writes new versions and switches
current; it must not be able to change the guard:chown root:wyrm /opt/wyrm && chmod 1775 /opt/wyrm # sticky: the broker cannot move bin/ away chown -R root:root /opt/wyrm/bin && chmod 755 /opt/wyrm/bin chown -R wyrm:wyrm /opt/wyrm/versions chown -h wyrm:wyrm /opt/wyrm/current chown root:wyrm /etc/wyrm/wyrmd.json5 && chmod 640 /etc/wyrm/wyrmd.json5 - Change the unit of section 2:
# as the broker's user: takes a failed update back, verifies what starts ExecStartPre=/opt/wyrm/bin/wyrmd-guard -c /etc/wyrm/wyrmd.json5 update-guard # as root ("+"): keeps the guard the verified binary of the current version ExecStartPre=+/opt/wyrm/bin/wyrmd-guard -c /etc/wyrm/wyrmd.json5 guard-refresh ExecStart=/opt/wyrm/current/wyrmd -c /etc/wyrm/wyrmd.json5 ReadWritePaths=/var/lib/wyrm /opt/wyrm Restart=alwaysRestart=alwaysis needed: a new version that gives its trial up ends with code 76, and the guard acts at the next start. Do not list 76 inRestartPreventExitStatus, and do not set a start limit (StartLimitBurst) below 8 starts: an update that fails uses up to three starts of the new version and three of the old one. systemctl daemon-reload && systemctl restart wyrmd.sys/update_hintis empty when the layout and the guard are in place; else it says what is missing, andupdateis refused with the same text.
CAUTION: without ExecStartPre a failed update is not taken back. The
broker checks that the guard ran before it started and refuses update
when it did not.
A simpler unit (one ExecStartPre, everything under /opt/wyrm owned by
the broker’s user) works too: the broker then replaces the guard itself.
It gives up the protection of the next section.
What is verified, and what that does not stop
With updates.mode: "self" the guard verifies the version that current
names before every start, and the broker verifies its own binary when it
starts: the SHA-256 of versions/<v>/wyrmd must be the one a release
document names that a key of updates.keys (or the built-in key) signed
and that is kept beside the binary, or the one bin/trusted.json names
for a version put there by hand. A binary that fails is never started.
The guard makes the other version of the update current if that one
verifies; else it ends with code 1 and the journal says why.
A bin/trusted.json that cannot be read (damaged, not a plain file, more
than 1 MiB) trusts nothing: a version put there by hand is then not
verified, the refusal names the file, and the log has an error line with
it. wyrmd install-layout refuses to write such a file again, because it
would lose the versions the file named. To recover, as root: look at the
file; put it back from a copy, or remove it and run
<prefix>/versions/<v>/wyrmd install-layout <prefix> with the binary of
each version that was put there by hand (a version with a signed release
needs no entry).
CAUTION: each such run also makes its own version the current one and
puts its own binary in place of the guard. Do it with the broker stopped
and not during a trial. Run the version that must stay current last. If
the current version has a signed release and so needs no entry, note
where current points before you start and put it back afterwards
(ln -sfn versions/<v> <prefix>/current.new && mv -T <prefix>/current.new <prefix>/current); the unit’s guard-refresh step then makes the guard
the binary of that version again at the next start. A wrong order starts
an older binary on the data of a newer one at the next restart. In the
layout of step 2, set the owners again afterwards (chown -R wyrm:wyrm <prefix>/versions, chown -h wyrm:wyrm <prefix>/current): what root made
the broker cannot replace at its next update.
The pre-update backup is sealed for this broker (how: broker): the guard
checks its manifest with the key of secrets.key, every file against the
manifest, and the file’s SHA-256 against update.json.
What this stops, with the owners of step 2: a process that runs as the
broker’s user (a process link, a package) cannot make the host run a
binary of its own by replacing versions/<v>/wyrmd or by pointing
current at a directory it made. It cannot replace the guard,
bin/trusted.json or the configuration with its keys.
What it does not stop:
- Without the owners of step 2 (everything owned by the broker’s user),
the same process can replace the guard or
bin/trusted.json, and then nothing is verified. - It can point
currentat another release that the key did sign and that is still inversions/(an older one, with a known fault). The check proves that a binary is a signed release, not which one. - It owns
data_dir: the keys of the site, the control plane, the backups. It needs no binary to change a link or a user. - A process link runs under the broker’s uid: it is inside the trust boundary until links get a uid of their own. Install packages you trust.
What update does
sys/~act/update {version, confirm_site} (config; confirm_site is the
site name). It answers at once; follow sys/update_state and
sys/update_last.
- The release document is checked against the pinned keys. A version
that is not newer, that needs a newer starting version (
min_from), that has no build for this host, that writes an older SCHEMA thandata_dirholds or that names a store this version does not know is refused. - The archive is fetched (https only; plain http only to loopback) and
its size and SHA-256 are compared with the signed document. Then it is
unpacked into
versions/<v>: plain files only, the broker’s own modes. The binary’s own SHA-256 must be the one the document names. The document and its signature are kept beside it. - The new binary is asked what it is (
wyrmd release-info) and run against a copy of the control plane (wyrmd -c <config> check --state <copy>). It runs with an empty environment. The livedata_diris not touched. - A backup of the control plane is made (
sys/backups, kindpre-update, sealed for this broker, kept while a rollback is possible). data_dir/update.jsonis written,currentis switched, the broker stops with code 0, and systemd starts the new version.- The trial lasts
trial_sseconds of run time of the new version. The version writes how long it has run every 5 s. Time the host is off, or the broker is down, is not part of a trial: a host that was off for a day comes back into the trial it left. At its end the version is confirmed when the admin answers, the gateway listens and every link that was connected before is connected again.sys/update_stateis thenconfirmed. - Else the new version ends with code 76 and the guard, at the next
start, restores the control plane from the pre-update backup where the
update moved a SCHEMA, points
currentback, and the old version serves:sys/update_stateisrolled_back,sys/update_last.reasonsays why. The same happens after three starts that did not end the trial. The clock is not asked.
CAUTION: where an update moved a SCHEMA, a rollback restores the control
plane of the moment before the update. Changes made under the new version
(links, users, flows, tokens) are lost; the directories it replaced stay
in data_dir/update.aside until the next rollback. A store that did not
exist before the update (the gateway’s users on a broker that had no
gateway) is moved there too.
The guard does not leave the broker without a version to start:
- When the control plane cannot be restored (the backup is gone or was
changed, a file cannot be written), the old version is started on the
state as it is.
sys/update_stateisfailed, the reason is insys/update_last.reasonand in the audit (update_rollbackwith an error status). - When the version that a rollback made current does not come up in three starts, the guard makes the other version current, and so on, until one comes up.
- When the old version’s directory is gone, the new version stays
(
failed). - The one case in which nothing starts: no binary that verifies (the
section above). The guard ends with code 1; read
journalctl -u wyrmd.
A new version that hangs without ending (no exit, no restart) is not seen
by the guard. Add WatchdogSec= to the unit only if you also accept a
kill of a slow start; the broker sends no watchdog pings.
sys/~act/rollback_update {confirm_site} goes back on purpose, while the
old version and the backup are kept: keep_days after the update was
confirmed. A host without a clock battery may start with a wrong time, so
one reading of the clock removes nothing: the time must be past
keep_until at two starts of the broker, or for a full hour of one run.
rollback_update is refused for a session that reaches the site through
an upstream. update itself is allowed through an upstream with
allow_config: what may run is decided by the keys this host pinned.
An update is refused with busy while a backup is made or sent, a
restore is staged, a package or a link is being installed, updated or
restored, or another update runs. With state_anchor_dir set, a release
that moves a SCHEMA is refused: update that broker by hand, then run
wyrmd init-anchors.
The channel file holds the releases index and its signature. Each entry
of the index is a release document with its own signature, and the index
carries a sequence number: a broker refuses an index older than one it
has read (data_dir/update.seen), so an old index that is put back hides
no release. A read that fails is tried again after 5 minutes; the index
read before stays in use.
update.seen holds that sequence as one decimal number. A host that has
no such file starts at 0. A file that is there and cannot be told (not
readable by the broker’s user, not a plain file, more than 32 bytes, not
a number) refuses every index: the broker does not guess 0, because then
any old index would pass. sys/update_hint and the answer of
check_updates name the file (releases index: … update.seen …). The
broker runs on, an index read before in this run stays in use, and a
signed archive brought by hand is still taken. To recover:
- Look at the file:
ls -l <data_dir>/update.seenand its content. It must be a plain file of the broker’s user, mode 0600, with one number. - If only the owner or the mode is wrong, set them right.
- If the content is lost, write the sequence of the index that the
channel serves now (the
sequencein itsindextext), when you trust that the channel is current. Then runcheck_updates. - Or remove the file. Removing it drops this guard once: the next index that verifies is taken whatever its sequence, also an old one that was put back, and the broker counts from there. Before you remove it, check that the channel serves the newest index.
Without a releases index
There is no published index yet. Bring a signed archive:
- Upload
wyrmd-<v>-<target>.tar.gzin parts:sys/backups/~act/restore_begin {size}, thenrestore_part {upload, offset, data}. - Call
sys/~act/update {upload, release, signature, confirm_site}with the text ofwyrmd-<v>.release.jsonand of its.sigfile.
A standby pair
The standby goes first. It runs no router, so the active carries the order:
- Set
updates.mode: "self", the sameupdates.keys, the layout and the unit on both hosts. - On the active, call
update {target: "standby", upload, release, signature, confirm_site}. The standby fetches the archive from the active, checks the signature with its own keys, proves the binary and restarts on it.sys/standby_updateshowsordered <v>, then<v> trial, then<v> confirmed(orrolled_back/failed), andsys/standby_versionthe version it runs. - When the standby is confirmed, call
updatefor the active (the same arguments withouttarget). It is refused while the standby runs another version or is not confirmed.without_standby: trueupdates the active alone when the standby is not connected.
While the active restarts, the standby waits up to 120 s. If the new version does not come up in that time the standby, already on it, takes over. A release that changes the replication protocol cannot be done this way: stop the standby, update both hosts by hand, start the active first.
Several sites
A site does not depend on its upstream: it keeps polling, recording and
alarming while the upstream is away, and the upstream catches up through the
history and alarm sinks (next {after, max}) when the link is back. A
restart of the upstream therefore costs the downstream nothing but a gap in
what the upstream saw live. The same holds the other way round: the upstream
shows the downstream site as not connected and serves everything else.
downstream/<d>/connected (and upstream/<u>/connected on the other side)
is true when queries reach the peer, not only when its broker token
wy/<peer>/sys/broker is there. After the token comes, the broker sends a
probe to the peer’s sys/signing_keys (3 s timeout; 50 ms between probes,
doubled up to 5 s) and sets connected when a probe has an answer. A router
that has just connected has its token routed before queries to it are, so
the token alone can be true up to about 100 ms before any query answers
(docs/backlog.md §6). When the token goes, connected is false at once.
3. Back up and restore
Everything the broker owns is under data_dir. What cannot be regenerated:
| Path | What it is | Without it |
|---|---|---|
state/, state.key | the control-plane WAL and the key of its HMAC chain | no links, ACL, peers, tokens, history settings; the WAL of a backup is refused with another state.key |
pki/ | the site CA and its key, the broker’s certificates | every link, operator, downstream broker and process link needs a new certificate; upstreams must trust the new CA |
secrets.bin, secrets.key | link secrets, store keys of every link, the keys of sealed peers | links lose their credentials; the sealed stores of links and runtime driver edits cannot be opened |
gateway/ | users, roles, the gateway’s signing key | users gone; whoever holds gateway.key is an administrator, so the backup is as sensitive as data_dir |
flows/, flows.key | flow definitions and their signing key | flows gone |
links/<id>/ | each link’s certificate, token and private data (data/: runtime edits, portable stores) | the link starts from its registry parameters |
history/, storage/ | the historian’s day files and index, broker storage | history and stored values gone |
audit/ | the audit journal | the record of who did what |
packages/, peers/, operators/ | installed link packages (and the previous version of an updated one), certificates issued for downstream brokers, operator certificates | reinstall, reissue |
update.json, update.guard, update.seen, update.aside/ | the state of the broker’s own update (ADR 0048 §2), when the guard ran last, the highest sequence of a releases index read, and the control-plane directories a rollback replaced | a rollback of a confirmed update is not possible |
restore/<link>/ | restore points of links taken before a package update or a restore from a backup (docs/links.md §5a): link backups (.wyrm-link) sealed with a key derived from secrets.key, and their .meta | a rollback of an update restores no private data |
How to take a backup:
- Online, from the broker itself (ADR 0048).
sys/backups/~act/create {sections, passphrase}makes a.wyrm-backupwhile the broker runs: the WALs as of one sequence number, the storage at one revision, each history file inside one read transaction, keys and secrets sealed with the passphrase. Read it withdownload_part, or let the broker write it into a file store withsend(the host names the link and the folder inbackups.send_links). One link goes withsys/links/<id>/~act/backup. The keys section and a passphrase needbackups.export_secrets: trueon the host; without it a backup holds no keys and its link secrets open only on a broker with this site’s keys. Restore withsys/backups/~act/restore_checkandrestore_apply:mode: addworks live;mode: replacerestarts the broker once, is refused for a caller that comes through an upstream, and restores keys only withexport_secrets, the passphrase and, for keys that differ from this broker’s,replace_keys. Sections, limits and the restore of a link are in backups.md. This is the way for a broker that runs; the two ways below stay for a broker that does not start. - Stopped broker (simplest, consistent).
systemctl stop wyrmd, copydata_dirwhole, keep its modes (cp -a,tar --same-permissions), start again.wyrmd -c … verifyon the copy checks the WALs (CRC, HMAC chain, anchors) offline. - Running broker. Take a filesystem snapshot (LVM, btrfs, ZFS, a cloud
volume snapshot) and copy from the snapshot. The WALs are append-only and
a torn last record is dropped at open; the redb files are transactional and
a snapshot sees a committed state. A plain
cpof a runningdata_dirmay copy a redb file in the middle of a write: do not restore from such a copy withoutverifyand a look at the history. - The backup holds the site’s keys: encrypt it and keep it where only the broker’s administrators can read it.
How to restore:
- Stop the broker; move the damaged
data_diraside. - Copy the backup to the configured
data_dir, owner the broker’s user, mode 0700 for the directory and the key files. wyrmd -c … verify. Withstate_anchor_dirset (the WAL head anchors on another medium), a backup older than the anchors is refused at start as a rolled-back WAL, which is what the anchors are for; if the older state is what you want, runwyrmd -c … init-anchorsonce, with the broker stopped, on a store you trust.- Start the broker. Links that were installed after the backup are not in
the registry and do not come back: the links re-declare only what the
registry starts. Runtime driver edits made after the backup are gone with
links/<id>/data.
What a backup does not replace: a second host that holds the same keys and follows the WAL while the first one runs. That is option 3 of ADR 0036, the warm standby: see “Warm standby” in section 2.
Official links offline
packages: { repository: "official" } (ADR 0043, docs/links.md §12a) makes
the broker fetch the official index from github.com at each start and
rebuild. It is off by default. A broker that cannot reach github.com logs
repository index: … and starts as usual. For a site without internet
access, mirror one release on a host that the broker reaches:
- On a computer with internet access, download all assets of one release
links-v…(the zips,official.json,SHA256SUMS):gh release download links-v… --repo gencto/wyrm --dir mirror. - Check the files:
(cd mirror && sha256sum -c SHA256SUMS). - Write an index with relative URLs:
wyr repo index --manifest mirror/official.json --zips mirror --out mirror/index.json. - Copy
mirror/to a web server on the plant network. Serve it over HTTPS, or over HTTP on the broker host itself (plain HTTP only to loopback). - Set
packages: { repository: "https://<mirror>/index.json" }and restart the broker.
The broker checks every zip against the SHA-256 of the mirror’s index, as it does for the official one.
4. Checks
wyrmd -c … check: the configuration parses and validates; exit code 1 otherwise. Run it before a restart with a changed file. With--state <dir>it also opens every control-plane store of a copy of adata_dirwith this binary (what a broker does with a newer version before it updates to it); it never opens the livedata_dir.wyrmd release-info: what this binary is (version, target, the SCHEMA of each store, the replication protocol).wyrmd -c … verify: every control-plane store offline (broker stopped).- Running:
wy/<site>/sys/uptime,links_total,links_connected,quarantined,acl_denied,cpu,memory,disk_free,data_size(wyr list wy/<site>/sys),sys/links/<id>/stateanderrorper link,sys/history/disk_space_remaining; per flowdataflows/<id>(~val:stateand the countersstats.samples_in,dropped,commands.error, ADR 0045, flow-blocks.md). The liveliness tokenwy/<site>/sys/brokeris what links and peers watch; a monitor can watch it too (wyr sub). sys/~act/get_logand per-linkget_loghold the recent log ring; the level issys/log_level(RUST_LOGat start).
Backups (ADR 0048 §3)
A broker makes backups of itself and of one link while it runs. Every action is config on sys (the admin role through the gateway) and is in the audit. A backup is as sensitive as data_dir: with its passphrase it makes an administrator.
1. The file
A .wyrm-backup (broker) or .wyrm-link (one link) is a zip. Its first entry is manifest.json: wyrm_backup: 1, kind, site, broker (version), created, schemas (registry, users, flows, audit), sealed, and sections[] with each file’s path, size and SHA-256. The format is in wyrm_admin::backup.
- Files with secrets are always sealed: everything in
keys, each link’ssecrets,tokenandfiles/**, and a link backup’sdata. The reader refuses a file that lists one of them as not sealed. - Without a passphrase they are sealed for the site (
sealed.how: "broker", a key fromsecrets.key). Such a file opens only on a broker that holds this site’s keys. Restore points and pre-update backups are made this way. - With a passphrase (Argon2id, at least 12 characters) the file opens anywhere. This needs
backups.export_secrets: true(§1.1). - A sealed backup carries a MAC over its whole manifest. The broker opens nothing of it before the key proves the manifest unchanged.
- A backup with no secret-bearing part is not sealed. Its SHA-256 (
sys/backups/<id>/sha256) proves it unchanged.
1.1 Secrets leave the broker only when the host allows it
config on sys must not be enough to take the site’s identity. The option backups.export_secrets in wyrmd.json5 (default false) is set on the host alone.
export_secrets: false | export_secrets: true | |
|---|---|---|
section keys | refused | made with a passphrase |
| a passphrase | refused, the message names the option | seals keys, link secrets and private data |
| link secrets and private data | sealed for the site | sealed for the site, or with the passphrase |
| everything else | works | works |
- A caller whose authority comes from another site (an upstream with
allow_config) never getskeysor a passphrase-sealed file, whatever the option says. The admin tells such a caller by its token: a limited key signed it. - The audit record
backup_createcarrieskeys: true|falseandsecrets: true|false, and the broker logs a warning for a passphrase-sealed backup. sys/backupshas the attributeexport_secretsfor UIs.- A refusal by these two rules is
permission_denied, with the reason in the message:create, a link’sbackup,download_part, andrestore_apply(§4;restore_checkonly reads the file and refuses nothing by rights). No other argument of the same caller passes. A wrong argument isinvalid_parameter:keyswithout a passphrase, a short passphrase, keys that differ withoutreplace_keys. A denied call is counted and logged as everypermission_deniedof the broker (refused: …insys ▸ get_log); the audit journal records what was done, so a refused call of either kind leaves no record there. - Secrets a broker makes for a link’s identity (its requester key, an agent’s signing key) are in no link data of any backup. A link’s token is only in
keys. - The
configsection iswyrmd.json, a copy for people to read. It is never restored. It is masked by default: a text is in clear only when its field is on the list of fields known to hold no secret (the site, the profile, endpoints, paths of certificates, link ids and drivers, the options ofbackups, and the like;CONFIG_SHOWNinwyrmd). Every other text is***, whole: every text under a link’sparams, underuplink.upstreams, under a section this broker does not know. Numbers and flags stay. On a shown field, the text loses everything after its first?or#(the query of a URL, the config of an endpoint) and the userinfo before an@, and a name that says secret is masked all the same. Field names stay, so you see which params a link had and enter the values again.
2. Back up the broker
| Node | Action | Result |
|---|---|---|
sys/backups | estimate {sections, links?, history_days?} | {sections: {name: bytes}, total} before compression |
sys/backups | create {sections, links?, history_days?, passphrase?} | {id}; one job at a time (busy beyond) |
sys/backups/<id> | values status (running, done, failed), progress (%), step, size, sha256, created, expires, error, sent_to, send_status, send_progress (%), send_error; attributes kind (full, link, pre-update, pre-restore), name, sections, sealed, link | |
sys/backups/<id> | download_part {offset, len?} | {data, offset, size, eof}; len at most 16 MiB, default 4 MiB |
sys/backups/<id> | remove | |
sys/backups/<id> | send {link, connection, path?} | {to, upload, parts}; the file goes to a file store in the background (§2.1) |
Sections:
| Section | Holds | Consistent because |
|---|---|---|
control (always) | the WALs of the registry, the flow store, the gateway users and the audit | each is copied as of one sequence number, checked against its HMAC chain |
keys | the site CA, state.key, secrets.key, flows.key, the gateway keys, the flow signing key, secrets.bin, link tokens; all sealed | needs the passphrase |
dataflows | the flow engine’s artifacts; the flow store itself is control/flows | content-addressed files |
storage | the storage tree (tree.cbor) and its JSON export | the whole tree at one revision |
history | the day files of the last history_days days (all without it) and the index | each file is copied inside one read transaction; days first, the index last |
links | per link of links (all without it): link.cbor (its definition, without the token hash), its secrets and private data, sealed | files as the standby copies them |
packages | every installed package as its files (wyrm-link.json among them). Without this section, the packages of the chosen links still go in | versions are immutable |
config | wyrmd.json, the configuration masked by default (only fields known to hold no secret are in clear); never restored |
The job stages its files in data_dir/backups/.stage-*, then writes the zip. It needs about twice the estimate on the disk of data_dir and is refused (resource_exhausted) when that is not free. Links, flows and the historian go on while it runs.
Backups stay in data_dir/backups for backups.keep_days (default 7) within backups.max_mb (default 2048). The oldest are removed first; the newest one and a pinned one (the pre-update backup of an update not yet confirmed) never.
backups: { keep_days: 7, max_mb: 2048, export_secrets: false, send_links: [] },
A client loop: create, read status until done, download_part from offset 0 until eof, compare the SHA-256.
2.1 Send a backup to a file store
sys/backups/<id>/~act/send {link, connection, path?} writes a kept backup into a file store (S3, WebDAV, Google Drive, a local directory: filestores.md) through a file-store link of this broker.
- On the host, name the link and the folder in
wyrmd.json5, then restart the broker:
A link id alone (backups: { send_links: [{ link: "files", folder: "site/backups" }] },send_links: ["files"]) means the folderbackups. One folder for each link. The default is an empty list:sendis refused.sys/backupsshows the list as the attributesend_links([{link, folder}]). - Make the folder in the store (Create Folder on the link, or in the store itself).
senddoes not create it. - Call
sendwithlink(one of the list) andconnection(a connection of that link). The file goes to<connection>/files/<folder>/under the backup’s own file name. - To give another name or a sub-folder, set
path:nightly.wyrm-backup, or2026/nightly.wyrm-backup(the sub-folder must exist). - The broker begins an upload on the link (
upload_beginwith the size and SHA-256), answers{to, upload, parts}, and sends the parts (1 MiB each) in the background, thenupload_commit. - Read
send_statusofsys/backups/<id>:sending(withsend_progress),done, orfailed(withsend_error).sent_tois<link>/<connection>/files/<folder>/<path>.
The broker writes with its own key, for any caller with config on sys. So the host decides where the files go, not the caller:
- Only below the host’s folder.
pathis a file name or a sub-path of plain names. An absolute path,.., an empty segment,\or:is refused before the link is called.connectionis one name. - A narrow token. The broker signs these calls with its backup sender key. Only the links in
send_linkstrust that key (atwrite, on their own subtree, for the subjectbroker:backup). Each token of a send is good for the keys of<connection>/files/<folder>/**and the connection’s four upload actions only. The broker makes the key on first use; it is no link’s secret and is in no link backup. - Nothing is overwritten. A name that exists in the folder is refused. Give another
path. - The audit names the caller.
backup_sendin the admin’s journal, at the start and at the end: who called, the backup, the link, the path, the size and the SHA-256. The link’s own audit records each upload call underclaimed:broker:backup; the upload actions carry no note, so the caller’s name is only in the admin’s journal. - A backup that holds the
keyssection is never sent. Download it on the broker’s own gateway. - A caller that reaches the site through an upstream may send a backup without
keys: the host named the destination. - One send runs at a time (
busybeyond). A backup that is being sent is not removed or pruned. If the broker stops during a send, startsendagain. - The link spools the file on its own disk before it goes to the store (
<data_dir>/links/<id>/data/uploads/), so that disk needs room for it.
3. Back up and restore one link
sys/links/<id>/~act/backup {sections, history_days?, passphrase?} → {id}: a job in sys/backups with kind: link.
| Section | Holds |
|---|---|
settings (always) | the link’s definition: driver, mode, params, grants |
data | its secrets and its private directory (framework.tree, a portable app’s store), sealed for the site, or with the passphrase for another broker (§1.1). An external link has none here |
package | the package it runs, as its files |
history | the rows of its points (the last history_days days, all without it), keys relative to the link |
The framework’s runtime edits (connections, devices, points) are in data. A backup of settings alone restores the link as it was installed.
Restore: sys/links/~act/install_backup {file | upload, id?, accept, passphrase?} → {success, message}.
- Give the file as
file(up to 64 MiB through the gateway’sPOST /api/invoke), or upload it in parts:sys/backups/~act/restore_begin {size}→{upload, part_size}, thenrestore_part {upload, offset, data}in order (at most 16 MiB each; a part is larger than a WebSocket frame, so through a gateway it goes byPOST /api/invoke, which takes it becausedataiseditor: file), and giveupload.restore_abort {upload}drops it. An upload without a new part for an hour is removed. idis the new link’s id. Without it, the id in the backup is used.accept: trueis needed when the link has requester grants or a network allowlist. Without it, the answer lists them and nothing is installed.- The whole file is checked first. The link’s definition passes the checks of a new link: its id (reserved ids refused), its driver, its params, every grant. The package’s files pass the validator of every install (
packages::unpack): the entry inside the package, requester grants, WASM world and capabilities. Its registry record is built from the files, never read from the backup.acceptcovers what the link and a package this install brings ask for. Then the package is installed when this broker does not have it. A broker that has it in the same version must hold the same files; another version is refused: one version per package. - A new link is installed, stopped, given its secrets and private data, and started. Its token, certificate and requester key are new: they belong to the broker.
When a step after the install fails, the broker removes the new link again, as
removedoes, and the message says so: the same restore can be run again. A new link with a certificate (a process or an external link) is the exception: the id of a removed link that had a certificate is never used again, so the broker leaves that choice to you. The message names the link that stays and how to go on: install its link backup again (the link is replaced in place), or remove it and restore under anotherid. A package that the restore installed stays in both cases. - An existing link of that
idmust run the same driver in the same mode. A restore point of it is taken first (data_dir/restore/<id>/<UTC>.wyrm-link, as before a package update: links.md §5a), shown insys/links/<id>/restore_pointsand pruned afterpackages.keep_previous_days. Then the link is stopped, replaced in place and started. To go back, install that file withinstall_backupon this broker: it is sealed for it and needs no passphrase.
Not carried over: the link’s display name and log level, the history watches (only the rows), and the secrets a broker makes for a link’s identity.
4. Restore the broker
Upload the .wyrm-backup (restore_begin, restore_part), then:
| Action | Result |
|---|---|
sys/backups/~act/restore_check {upload, passphrase?} | `{site, same_site, created, broker, sealed, schemas: {name: {backup, here}}, sections: {name: bytes}, keys: none |
sys/backups/~act/restore_apply {upload, sections, mode, passphrase?, accept?, replace_keys?} | add: {done[], skipped[], restart: false}; replace: {sections, restart: true} |
mode: addworks live. Sectionslinksandstorage. Links that do not exist are installed asinstall_backupdoes; storage nodes that do not exist are added. Nothing is replaced.dataflowsis skipped with a note: a flow is deployed with proofs of its deployer.mode: replacetakescontrol,keys,dataflows,storage,history,links,packages. A caller whose authority comes from an upstream (allow_config) is refusedreplacealtogether, before the file is read: it would replace this site’s control state, links and packages.addstays open to it, with itsaccept.- The broker makes a
pre-restorebackup of the same sections. - It stages the sections in
data_dir/restore.pending(written whole or not at all) and checks all that the next start will read: each WAL opens with the keys that will be in place, the storage is built from its tree, the history files open, the secret store opens with its key. - It answers, then stops. The supervisor starts it again (
Restart=always). - The next start applies the folder before any store opens. What it replaces or removes is set aside in the folder, not deleted. When the stores have opened, the folder is removed and the audit gets
restore_applied. A start that stops halfway is taken up by the next one. - A restore that cannot be applied does not stop the broker. When a step of the plan fails, or a store does not open on the restored state, the broker puts everything back as it was. It keeps the plan and the reason in
data_dir/restore.failed(plan.json,error.txt) and runs on the state it had. The audit getsrestore_failedonce. If a store did not open, the start that tried ends with a message and the next start runs on the old state.
- The broker makes a
- A backup of another site name is refused. Set
siteinwyrmd.json5to the backup’s first. - A backup whose store SCHEMA is newer than this broker reads is refused.
- The
keyssection is restored only through three gates, whatever the keys are (also the keys of this very broker):backups.export_secrets: trueon the host, a caller of this site, and the passphrase. replace_keys: trueis needed too unless every key file of the backup is byte for byte this broker’s.restore_checkanswerskeys:same(all identical),differ(this CA, other key files:state.key,secrets.key, a gateway key,secrets.bin, a link token),other(another CA), and lists the files inkeys_differ. With another CA, the certificates it issued are removed; link processes, operators and peer brokers enrol again. Thepre-restorebackup holds the old keys, under the same passphrase, whenever keys are replaced.- Only defined files are restored. Each file of a backup must be one its section defines, or the whole backup is refused by the check and by both modes: under
keys/exactly the key files (pki/ca.pem,pki/ca.key,state.key,secrets.key,flows.key,gateway/hmac.key,gateway/gateway.key,flows/flow.key),secrets.binandlinks/<link id>/token;control/<store>/<file>of the four WAL stores;dataflows/artifacts/**;storage/tree.cborandexport.json;history/index.redbandhistory/days/<day>.redb;links/<link id>/{link.cbor, secrets, files/**};packages/<name>/files/**;config/wyrmd.json. The broker builds every destination from these checked parts; it never joins a path of the archive to a directory. - A
controlsection is what a broker makes. For each store it holds one WAL segment (wal.<first lsn>.wyw) with every record, and says the number of the last record. The check refuses the whole backup (invalid_parameter) when a file undercontrol/is no segment, when the registry (control/state) is missing, or when a store opens with other records than the backup says. Such a section would put an empty control state in place. The staging ofreplacechecks every store again with the key that will be in place. A backup of a broker with nothing installed is a real one: its registry has no record, it says so, and it is restored. - Packages of a
replacepass the validator of every install (packages::unpack). What a package asks for (requester grants, network) needsaccept: true, unless this broker has the same version with the same files; without it the answer lists them and nothing is staged. - Link secrets. Without
keys, a link’s secrets go into this broker’s store, and the ones a broker makes for a link’s identity (requester key, agent signing key) are dropped, as ininstall_backup. Withkeys,secrets.binof the backup comes back whole, the broker-made ones among them: they are that site’s own identity, restored under the gates above. controlof a backup under other keys is restored only together withkeys.- With
state_anchor_dirset,controlis restored offline (docs/operations.md§3). linkswithcontrolrestores the private data of every link of the backup; withoutcontrol, of the links this broker has.- The audit journal is replaced only when
state.keyis.
To move a site to a new host: install wyrmd with the same site and backups.export_secrets: true, start it, upload the backup, restore_apply with mode: replace, replace_keys: true and every section.
5. For code
Control::link_backup_to(id, path)writes a link backup without history topath, sealed for this broker (no passphrase, noexport_secrets). The link keeps running.Control::link_restore_data(id, path)gives a stopped link the secrets and private data of such a file. The data directory is built new and swapped in.- Restore points (
wyrm_admin::restore_point,Control::restore_point_now) are such files without the package, with a.metabeside them. - A link’s private data is read only through
wyrm_admin::nofollow: the link may run and owns the directory, so no symlink is followed and every file is sealed from the handle the walk opened. Entries that are not files or directories are skipped; the section’sinfo.skippedcounts them.
Architecture decisions
One file per decision, in the order they were made. The status says whether a decision is proposed or accepted, and when.
ADR 0001 — Zenoh as transport, WYRM as semantics
Status: accepted · 2026-10-19
Decision
Eclipse Zenoh 1.x is the transport and data fabric (routing, pub/sub, query/reply, liveliness, storage, TLS/ACL, mesh). WYRM adds DSA semantics strictly on top: key-space conventions, CBOR attachment header, SDKs, and three static plugins compiled into a single wyrmd binary. Zenoh itself is never patched or forked.
Consequences
- Dynamic Zenoh plugins (
.so) are not used (ABI lock-step with the router). - Extension happens through data (
dataflows/**) and processes (connectors), not plugins. - Per-message authorization is done in the responder SDK and gateway, not in the router (no public interceptor hook).
ADR 0002 — One wire codec: canonical CBOR via minicbor
Status: accepted · 2026-10-20
Decision
All wire payloads (~meta, ~val, attachment, ~def) are CBOR with integer keys, canonical encoding (RFC 8949 §4.2.1; text keys ordered length-first then bytewise; floats in shortest lossless form). minicbor in Rust; serde/json5 only for wyrmd.json5.
Why
One codec = one fixture set for Rust, Dart and C (zenoh-pico). minicbor is no_std, zero-copy for strings/bytes, and gives us control over key order. Equivalent in size to msgpack.
ADR 0003 — The broker owns only itself
Status: accepted · 2026-10-20
Decision
wyrmd persists and restores only control-plane state (connector registry, ACL, PKI, profiles, flow definitions, users) via WAL + postcard snapshot. The node tree is owned by connectors, which re-declare it on every (re)connect; last values are owned by storage and refilled by live owners. What is not re-declared does not exist.
Why
Instant restart without a zero-copy index; no second source of truth; the same liveliness signal that requesters see defines “connected”.
ADR 0004 — Driver framework inside wyrm-link-sdk
Status: accepted · 2026-10-20
Context
DSA v2 connectors (reference: dslink-java-v2-modbus + driver-framework-java-v2-prototype) proved a concept worth keeping: a connector is a tree Connection → Device → Point, every level is an editable node with declarative parameters and Add/Edit/Remove/Restart actions, and a change at any level reactively rebuilds only what depends on it. The Java implementation has defects (non-atomic edits, races on reconnect, optimistic writes, unbounded backoff, silent config loss) that we must not port.
Decision
wyrm-link-sdk ships two layers:
- Raw layer —
trait Link,LinkCtx,NodeTree, one queryable per link, liveliness,ptokcheck. For drivers with their own topology (MQTT, OPC UA browse, gateways). - Driver framework (
wyrm_link_sdk::driver) — opinionated layer on top of (1) for protocol drivers. A driver declares node kinds and the framework provides everything else.
What the framework provides
| Concern | Design |
|---|---|
| Parameters | One declarative schema per node kind: #[derive(Params)] on a config struct → name, type, enum, default, bounds, description, placeholder, secret flag. Generates ~meta.cfg schema, Add <Kind> action form (pre-filled with defaults), Edit action (pre-filled with current), load-time validation, fuzz values for tests. Parameters are typed structs, parsed once, never string-keyed maps. Amended 2026-10-22 (owner decision: node structure as in the DSA driver framework, dslink-java-v2-modbus): a level may have several node kinds, as DSA’s Add IP Connection beside Add Serial Connection: #[derive(Params)] on an enum of newtype variants gives one kind per variant (Params::kinds), each with its own add_<kind> action and form; the tree stores the node’s kind beside its params on such levels (their params may not be named kind). Fields carry display (label), desc (description), placeholder and editor; a secret is a password field (spec 02 0.1.6). A driver may offer found values for a param (Driver::choices, e.g. serial ports) and a root rescan action (Driver::RESCAN, DSA “Rescan For Serial Ports”). |
| Edit semantics | Validate first, atomically. validate(new) → Err aborts with invalid_parameter{path} and nothing changes. Then diff(old, new) → Rebuild::{None, Self, Subtree, Connection} decides what restarts; drivers may override on_edit(old, new) for fine-grained reaction (e.g. only reschedule a point). Teardown with old config completes before bring-up with new — no async close racing a new open. |
| Lifecycle & liveness | Typed state machine per node: New → Connecting → Connected → Failed → Stopped → StoppedByParent. A child runs only while its parent is Connected; parent failure cascades StoppedByParent. Published as ~val of the node (status) plus ~meta.q. Never a free-form string. Amended 2026-10-22: status is an enum leaf (wy:df-status: Unknown, Connecting, Connected, Failed, Stopped, Stopped by Parent; ~val = index), and the error text is a separate string leaf error (wy:df-error) that exists only while there is an error, as DSA’s Status and Error values. |
| Scheduling | Per-connection owner task that exclusively holds the transport and consumes an mpsc of requests (ping, poll batch, write) — the Rust equivalent of a fair lock. Tick launches I/O only if the previous I/O finished (no pile-up). Backoff on failure: exponential with cap and jitter (1s..60s, ±20 %). |
| Polling | Points are polled all the time by default (amendment 2026-10-20, owner decision: the in-process ~val storage of wyrmd always counts as a subscriber, and reads must be fresh); poll_unsubscribed: false polls only while subscribed (SDK knows subscriber count per key; reliable for process links only). Points grouped into batches by (device, poll_rate); batch plan (address partitioning, max read count, contiguity) is cached and invalidated on edit, not rebuilt every tick. Per-point errors are distinct from whole-batch transport failure. Amended 2026-10-30 (Modbus DSA parity plan, rulings 8 and 9): a poll is bounded by Driver::poll_timeout(conn, plan) (default io_timeout; Modbus: timeout_ms × (1 + retries) × requests + 1 s), so a large plan on a slow line is not cut; Driver::republish(dev) (default none) publishes an unchanged value again once its last publish is that old (a heartbeat, after reads only). Every request of the owner carries the connection’s plan generation; one planned before a re-plan is dropped, never run on what replaced it (a dropped write or action answers busy; rulings P19, P20). |
| Writes | ~set is a request/response: no optimistic update. Framework calls write(point, value); ~val is updated only from read-back (immediate read after write, or next poll) with the write’s status returned in attachment. Write strategy knob per connection (`single |
| Quality | Timeout → uncertain/stale for N misses, then bad/comm_fail; parent down → bad/disconnected; recovery → good. Exact codes in attachment key 1. Amended 2026-10-30: N is Driver::stale_misses (default 3); a point error is bad/device_error and a value a server does not take after an edit bad/config_error, the last value kept in both. There is no “zero on failed poll” (ruling 14). Amended 2026-10-30 (P30): when a device answers for some points of a poll but a point’s result is DriverError::Device (its batch timed out), that point takes the same ladder on its own (uncertain/stale, then bad/comm_fail after N such polls in a row) while the device stays Connected. Amended 2026-10-30 (final review M1–M3, ruling P31): no miss lifts a quality: the stale mark changes only good points, and a point already bad that gets no answer starts its ladder at N. An answered ping forgives only ping misses: the misses its polls earned stay, so a device whose polls time out while its pings answer reaches bad/comm_fail for its points and stays Failed with its error (no Failed/Connected flapping, no Connected over bad points) until a poll answers; a device that fails past N by any mix of misses is Failed too. A poll that cannot run (it waits in the queue behind an action, a long write series or other devices’ polls that time out, or the queue is full) for N poll periods in a row marks its group’s good points uncertain/stale (the ticker, under the plan’s read lock). |
| Persistence | Amended 2026-10-21 (owner decision: the connector owns its config, credentials come with the connection as in DSA). The framework keeps the whole tree, secret fields included, in the link’s data_dir/framework.tree, sealed with ChaCha20-Poly1305 under the link’s store key (secret .store_key, created by the admin per link and delivered with the link secrets), and writes it after every add_*/edit/remove/start/stop. ~def.params is the bootstrap: the file stores its SHA-256, and new bootstrap params (json5 edit, admin update/rollback) replace the stored tree. A file that does not open (other key, tampering) falls back to the bootstrap. Without a data_dir or store key the tree lives in memory. Secret params (#[param(secret)]) never show in ~meta.cfg, export or replies; an edit that leaves a secret empty keeps the stored one only while the destination fields (#[param(dest)], or every field when none is marked) stay the same. Load-time validation failure keeps the node in Failed with ~val.error, never deletes it. Amended 2026-10-30: that holds for params. A tree whose structure is wrong (an invalid name, a point id twice on a device, folders deeper than MAX_FOLDER_DEPTH, an unknown key in a folder) fails the link’s start with that error, stored or bootstrap alike: there is no node to keep it on. |
| Slave/server mode | ServerKind for drivers that can expose the tree as a protocol server (Modbus slave, OPC UA server): shared listener per port keyed by (transport, port), process image per unit, ref-counted shutdown, strict duplicate/overlap rejection at registration.Driver::is_server), not polled; its points take ~set and serve the tree’s values. A server’s Driver::write must not do I/O: the framework calls it under the plan’s read lock after serve, where a re-plan waits for it (final review M6). |
| Actions | Add <Kind>, Edit, Remove, Restart, Start/Stop generated per kind; Start/Stop only on branches, not on points. Drivers add their own (Rescan ports, Discover). Amended 2026-10-22: as in DSA, only the action that applies is declared: stop while the node runs, start while it is stopped. Every action has a name for people and a menu group (spec 02): add_* → new; edit, remove → edit; restart, start/stop, export, rescan → top level. Amended 2026-10-30 (rulings 11, 13, P12, P14–P18): copy {name} on connections, devices, folders and points (group edit; a copied connection or device starts stopped; a folder copy renames its points <id>_<n> and replies renamed); export of the whole tree, a connection, device or folder → {json} (format wyrm-driver-branch/1, branch.rs; secrets "<not exported>"); import {json, name?, overwrite?} of a connection at the root, a device into a connection, a folder into a device or folder (the top node starts stopped, a folder is polled at once; secrets never imported, listed in reenter; an overwrite keeps sealed secrets while the destination fields stay the same); bounds 4 MiB, 5000 nodes, 60 s. Driver actions: Driver::actions(level, kind) on connections and devices, run on the owner task by Driver::invoke between polls (queued with try_send: a full queue answers busy); a framework name is refused. Amended 2026-10-30 (final review I1, ruling P31): one driver action per connection is queued or running at a time; another (any caller, any level) answers busy at once, so actions delay the connection’s polls by one action at most. The Driver::actions/invoke signatures do not change. Root imports: Driver::root_imports + Driver::convert turn another system’s export into connection branches, checked all before the first is imported (Modbus import_dsa). |
| Observability | rtt_ms, errors, polls), rate-limited logs with link=/node= fields, state transitions audited.Driver::DIAGNOSTICS, default false; a driver that does not report outcomes would show counters stuck at 0). With it, each connection and device has value leaves requests, errors, timeouts, exceptions, the driver’s DIAG_EXTRA (Modbus reopens), last_rtt_ms, avg_rtt_ms (EWMA α = 0.1), counted from Driver::take_outcomes after every operation, published on a change at most every 10 s and at once on a read of the node; counts start at 0 on (re)start, a reconnect after a failure keeps them. Those names are reserved for children. |
| Folders | Added 2026-10-30 (ruling 10): with Driver::FOLDERS (default false; Modbus true), folders between a device and its points, at most MAX_FOLDER_DEPTH (4) deep, names only: add_folder, remove (cascades), copy, export, import; no edit (no rename: ids are keys of history watches, ACL and flows). A point id stays unique on its device, so polls, plans and writes go by (device, id) and never see folders; the point’s key gains the folder path. The tree stores folders: {<f>: {points, folders?}} beside a device’s points. |
Driver surface (what a Modbus driver writes)
Corrected 2026-10-30 (ruling 16) to what links/modbus declares; the full params and their bounds are in docs/modbus.md section 3.
#![allow(unused)]
fn main() {
#[derive(Params)] enum Conn { Ip(IpConn), Serial(SerialConn), IpSlave(IpSlaveConn), SerialSlave(SerialSlaveConn) } // one add_<kind> each
#[derive(Params)] struct IpConn { host: String, port: u16 = 502, transport: IpTransport = Tcp, timeout_ms: u32 = 1000 @bounds(100..=10000), write_mode: WriteMode = Auto, retries: u8 = 0 @bounds(0..=5) }
#[derive(Params)] struct Device { unit: u8 = 1 @bounds(0..=255), ping: Ping = Probe, probe_table: Table = Holding, probe_addr: u16 = 0, ping_s: f64 = 5.0 @bounds(0.1..=3600), contiguous_only: bool = false, max_regs: u16 = 125, max_bits: u16 = 2000, republish_s: f64 = 0.0 @bounds(0..=3600) }
impl Params for Point { /* by hand: table, addr, dtype = u16 (binary on bit tables), bit = 0, regs = 1, poll_s = 1.0, scale = 1.0, offset = 0.0, writable, unit, writable_by_master */ }
impl Driver for ModbusDriver {
type Conn = Conn; type Dev = Device; type Point = Point; type Transport = Transport; type Plan = Plan;
async fn open(conn: &Conn) -> Result<Transport, DriverError>;
async fn ping(t: &mut Transport, dev: &Device) -> Result<(), DriverError>;
fn plan(dev: &Device, points: &[(PointId, Point)]) -> Plan;
async fn poll(t: &mut Transport, dev: &Device, plan: &Plan) -> Vec<(PointId, Result<Value, DriverError>)>;
async fn write(t: &mut Transport, dev: &Device, id: &str, p: &Point, v: &Value) -> Result<(), DriverError>;
// optional hooks with defaults: io_timeout, poll_timeout, write_timeout, read_back_on_error, republish,
// stale_misses, choices, RESCAN, actions, invoke, root_imports, convert, DIAGNOSTICS, DIAG_EXTRA,
// take_outcomes, FOLDERS, and the server hooks of ADR 0024
}
}
Everything else — tree, actions, edit, states, scheduling, subscription gating, quality, diagnostics, folders, branches — is the framework.
Consequences
- Drivers are ~300–600 lines and behave identically to operators (same actions, same states, same error reporting).
links/mockis the first framework driver;links/modbusthe first real one. BACnet/DLMS reuse the same kinds with discovery actions.- The framework adds iteration-1 scope;
wyrm-link-sdkis delivered in two steps: raw layer, thendrivermodule beforelinks/modbus.
ADR 0005 — AI surface: MCP over the tree, agent as a connector
Status: accepted · 2026-10-20
Decision
tools/wyrm-mcp: an MCP server overwyrm-client(stdio and HTTP) exposingtree_list/resolve/meta,value_get/history,node_set/action_invoke(alwaysdry_runfirst; config-level only withapproval_id),profiles/device_models,flow_*,link_*,spec. Runs with a service-accountptok; auditorigin=ai:<agent>.links/agent: an ordinary connector exposing tasks as nodes (tasks/<id>/~valstate machineplanning → awaiting_approval → running → done|failed,~act/approve|reject|cancel). Uses an LLM + the same MCP tools + a device-model catalog underpub/models/<vendor>/<model>. Human approval is enforced byptok.maxperm, not by prompt.- Flow node
llmfor small in-flow tasks with token budget and caching. wyrgains dev commands:new link|flow,dev(hot-reload),sim,replay,ai,mcp. Repo ships.claude/skills/wyrm-linkandwyrm-flow.
Why
The tree is self-describing (~meta types, action param schemas, profiles, resolve filters), so the MCP layer is mechanical and the agent needs no privileged path. Safety comes from the existing authorization model, not from the model’s behaviour.
Phase
Iteration 9, after core, control-plane, flow and security.
ADR 0006 — ACL changes rebuild the router runtime
Status: accepted · 2026-10-20
Context
wyrm-admin generates the Zenoh access_control section from the link registry (and, since iteration 4, from the peers section, ADR 0007). Zenoh 1.10.1 has no public live reload of it: TablesLock::update_config is pub(crate) and only Zenoh’s own tests call it.
Decision
- Rebuild on ACL change. Install/remove of a process or external link and quarantine
approvecallControl::schedule_reload, which waits 300 ms (so the current reply leaves first) and sends a signal on the reload channel.Daemon::run_untilstops the currentBrokerand starts a new one with a freshly generated ACL. Embedded installs/removes do not rebuild: embedded links have no ACL rule. - What survives a rebuild is owned by the
Daemon: the adminControl(registry, audit, CA, link secrets, supervisor with its child processes), theFlowHost(flow store, flow signing key) and theGateway(user store, signing key, sessions, WebSocket tickets). What is rebuilt is theBroker: router runtime, storage/REST plugins, one in-process session, the admin responder with its watchers, embedded links, the flow engine and the gateway’s HTTP/WS server. - Order. Start: build the runtime, open the in-process session, attach admin + embedded links + process supervision, spawn the flow engine, then
runtime.start()opens the listeners (so the first remote query finds their queryables and tokens), then the gateway server. Stop: gateway server, flow engine, admin (watchers, embedded links, responder), thensession.close()beforeruntime.close(). - Process links are not restarted.
Attached::stopleaves processes running; on the next attachSupervisor::startis a no-op for a live process. The processes reconnect by themselves and re-publish~meta/~valwhen thewy/<site>/sys/brokerliveliness token returns (LinkConfig::republish_on). - Coalescing is partial. After the old broker has stopped,
run_untildrains the reload signals already queued (e.g. several installs in a row) and rebuilds once. A signal that arrives after the drain causes one more rebuild. - ACL shape. Default deny.
- Each remote link gets, by certificate CN and only over
tls: everything onwy/<site>/downstream/<id>/**,query/replyon its ownsys/links/<id>/~act/hello, ingressputonsys/audit/<id>, and liveliness onsys/broker(broker-watch). - Loopback (
tcp,unixsock-stream) inprodand operator CNs (overtls) are requesters only: they ask (query, subscribe, liveliness) and receive (put, delete, reply, liveliness token) onwy/<site>/**and onwy/<d>/**of every downstream site, but cannot put, serve queries or declare tokens outside**/@adv/sub/**(advanced subscriber bookkeeping;@adv/pubbelongs to the owning link only). - In
dev, loopback has full rights onwy/<site>/**. - Peer brokers get the rules of ADR 0007.
- In-process sessions (admin, embedded links, flow engine, gateway, plugins) bypass the ACL.
- Each remote link gets, by certificate CN and only over
- Local process links use loopback mTLS with their own CN, not UDS + uid as the wiki describes, because the Zenoh ACL has no uid subject. UDS stays for later.
- Removed ids are retired. Without a CRL a removed link’s certificate stays valid until it expires, so its id is never installed again and its CN is not quarantined again (
Registry::retired). Exception, 2026-10-22 (owner decision, DSA Deauthorize):sys/quarantine/~act/deauthorize {link}puts a runtime external link back into quarantine instead (Op::Deauthorize,Registry::held): its token, secrets and ACL rules go, and so does every gateway grant that widens a role on exactly its branch (restrictive ones stay; Remove does the same), the CN keeps no rights, and only a manual Authorize admits it again —allow_all_linksskips held CNs. Remove still retires. - Authorize (DSA form, 2026-10-22):
sys/quarantine/~act/authorize {dsid, group, name, driver, params};dsidis an enum of the quarantined CNs, re-declared on every change (as are the link list of Deauthorize and the role list ofgroup).nameis the link’s display name (the id stays the CN, which the ACL matches).groupgives that gateway rolewriteonwy/{site}/downstream/<id>/**(as Update Permissions, audited). Eachquarantine/<cn>node keeps its ownapprovewith the same form. Test:authorize_and_deauthorize. - Quarantine. An unknown CA-signed CN is seen through
link_events_listener()→auth_identifier(). Default deny already blocks it (stricter than the wiki’s “may putsys/quarantine/<cn>”).approveinstalls it as an external link and triggers a rebuild. Only sessions on thetlslink listener count (it trusts our CA alone; a peer site’s CA on QUIC can sign any CN). - Admission options (2026-10-22, DSA
allowAllLinks/quarantine), persisted in the registry (Op::SetOption, SCHEMA 5), set asconfigvaluessys/allow_all_links(default off) andsys/enable_quarantine(default on), audited (set_option). Withallow_all_linksan admissible CN (admissible: not a known, rejected or retired id, an operator, a peer broker or a downstream site name) is installed as an external link on first sight (auditauto_install), then the runtime rebuilds; the link token goes only tolinks/<id>/tokenon the broker, and the operator copies it to the device as afterapprove. With both off, unknown CNs are ignored. Setting an option does not rebuild by itself. The broker logs a warning at start whileallow_all_linksis on. - Link grants (2026-10-22, ADR 0013): a link’s policy also holds
grant-<id>-{query,watch,sub,back}for the paths it was granted (acl::grant_rules), so a requester link reaches other branches by its CN. A grant change rebuilds the runtime like any other ACL change. sys/acl_denied(wassys/metrics/broker/acl_denied_totaluntil 2026-10-22) = sum ofzenoh_{rx,tx}_network_message_dropped_payload_bytes_count{reason="access-control"}read from@/<zid>/router/metrics(gzip). It needs the Zenohstatsfeature and a read-only admin space; remote sessions cannot read@/**under the ACL.
Consequences
- A rebuild drops all Zenoh sessions for about 1 s. The memory
~valstorage starts empty and the owners refill it. - A rebuild also closes every user WebSocket. Gateway sessions and unspent tickets survive (they live in
Gateway), so clients reconnect without a new login. The Dart client does it itself (2026-10-24):WyrmGateway.client()gives aReconnectingClient, which opens a new socket with a fresh ticket, opens itslistandsubscribestreams again (aliststarts over withrefreshed), lets reads wait and go again, and fails asetorinvokecut by the close (it may have run); the explorer shows “Reconnecting…” meanwhile. - ACL changes are rare (lifecycle operations), so the cost is acceptable for one site.
- On a clean shutdown
Control::shutdownstops the supervised children; they are not adopted by PID on the next start. The wiki wants process links to survive a broker restart (systemdKillMode=process); that needs PID adoption and is not done yet. - Revisit when Zenoh exposes a public live ACL reload.
Open
Failed rebuild orphans process links— fixed:run_untilcallsControl::shutdownalso whenBroker::start/stopfails.- Coalescing relies on a fixed 300 ms delay plus one drain; there is no debounce window.
- PID adoption of process links (see Consequences).
Alternatives
- Patch Zenoh to expose
TablesLock::update_config. Rejected: principle 1 (Zenoh is never patched or forked). - Permissive ACL plus authorization only in the responder SDK. Rejected: the SDK checks
ptokon~set/~act, but cannot stop a session from publishing into another link’s~valor declaring its liveliness token. - A second router per link class. Rejected: more processes and hops for a rare event.
ADR 0007 — Peer brokers: QUIC + mTLS, read-only upstream
Status: accepted · 2026-10-20 · “read-only upstream” reversed by ADR 0018 (2026-10-24: commands from above on devices, flows and storage; sys with allow_config) · trust and admission amended by ADR 0015 (2026-10-23): downstream brokers hold certificates from the upstream’s CA; peer-trust.pem, peers.downstream[].ca and sys/downstream are gone, and the accepted peer-CA risk below no longer applies. The text below records the design before that
Context
Iteration 4 connects brokers of different sites (plant → central, edge → cloud). Each site has its own CA (wyrm-admin PKI) and its own ACL (ADR 0006). An upstream site must see a downstream site’s tree and values without becoming able to command its devices, and a peer CA must not be able to mint identities that the local ACL treats as links or operators. Full site names are used everywhere (spec 01), so routing needs no prefix rewriting.
Decision
- Config.
wyrmd.json5gets apeerssection (PeersSectionincrates/wyrmd/src/lib.rs):
Validation: sites are valid segments, unique and not our own; endpoints arepeers: { listen: "quic/0.0.0.0:7448", // only with downstream downstream: [{ site: "edge", ca: "edge-ca.pem" }], upstream: [{ site: "central", endpoint: "quic/central.example:7448", ca: "central-ca.pem" }], upstream_val_hz: 1.0, // optional }quic/<host>:<port>without#/?; CA paths are UTF-8 without;#?(they become endpoint parameters);listenanddownstreamcome together;upstream_val_hz > 0. - Transport: QUIC + mTLS. Any non-empty
peersturns on broker certificates. The broker has CNbroker:<site>for both its server certificate (SANs =tls_names) and its client certificate, both issued by its own CA. - Per-endpoint trust. The global
transport/link/tls/root_ca_certificatestays our own CA alone. Peer CAs are trusted only on the QUIC broker endpoints, through the endpoint parameter#root_ca_certificate_file=. Zenoh merges endpoint config over the global link config, and the endpoint wins:- the
peers.listenendpoint getsdata_dir/pki/peer-trust.pem(a bundle of all downstream CAs, written byControl::configure_zenohon every broker build); - each upstream
connectendpoint gets that site’scafile. The maintls/listener for links and operators therefore never trusts a peer CA.
- the
- ACL (
access_control_with_peersincrates/wyrm-admin/src/acl.rs). Peer subjects matchcert_common_names: ["broker:<site>"]andlink_protocols: ["quic"]; link and operator subjects aretlsonly. The two cannot overlap.- Upstream sites are read-only on our
wy/<site>/{downstream,dataflows}/**: ingressdeclare_subscriber,declare_liveliness_subscriber,liveliness_query; ingressqueryonly on…/**/{~meta,~val,~def,~state}; egressput,delete,reply,liveliness_token,declare_queryable,declare_subscriber. No~set/~actquery passes, and nothing undersys/**is visible. - Downstream sites serve their own
wy/<d>/**: all messages, both directions, on that key space only. - Our requesters may read downstream sites. The user gateway does too (
GatewayConfig.read_sites=peers.downstream):meta,children,listandsubscribeonwy/<d>/**, checked under the user’s roles for the own site (wy/<d>/xaswy/<site>/x) and sent without a ptok, which the downstream links would not trust;set/invokethere are refused by the gateway (testread_sites_map_to_own_roles_without_a_token). - Requesters (direct Zenoh sessions): Loopback and operator requester rules extend to
wy/<d>/**(andwy/<d>/**/@adv/sub/**). The downstream broker’s own ACL keeps them read-only there.
- Upstream sites are read-only on our
- Peer nodes in the tree (spec 01 0.1.5). Downstream is what connects to a broker, so a downstream site is a node beside the links:
wy/<site>/downstream/<d>. An upstream site, which this broker connects to, iswy/<site>/upstream/<u>. Each is a reference node served by the admin (wyrm_admin::peers):wy:broker,@site,@root=wy/<peer>and a bool pointconnected, fed by the peer’s liveliness tokenwy/<peer>/sys/broker. The ACL lets only that liveliness pass between peers, split by direction: a peer may watch oursys/brokertoken and declare its own, never ours (per upstream site:presence-<u>-token-inonwy/<u>/sys/brokeronly; per downstream site:presence-<d>-watch-in,presence-<d>-token-out). Links get the same split (broker-watchingress,broker-tokenegress).sys/**data stays closed. Test:presence_tokens_by_direction. A client follows@rootto open a peer site inside the tree of the broker it is connected to; the peer’s keys keep their one name. A link id may not be a downstream site name (wyrmd config andinstallrefuse it). Test:two_brokers_over_quic. - Egress downsampling. With
upstream_val_hz, the router config gets one Zenohdownsamplingitem (link_protocols: ["quic"],flows: ["egress"],messages: ["put"]) with one rule per link:key_expr: wy/<site>/downstream/<link>/**/~val,freq: upstream_val_hz(wyrmd::upstream_downsampling). Amended 2026-10-21 (owner decision): before, one rule forwy/<site>/downstream/**/~valgave all links one shared budget. Withupstream_val_hzset, installing or removing any link (also embedded) rebuilds the broker, so the rules follow the registry. - Peers at runtime (2026-10-22, owner decision, as DSA’s
/sys/upstreamthat editsserver.json).sys/upstream/~act/add {name, url, ca, enabled}andsys/downstream/~act/add {name, ca}(levelconfig) store a peer in the registry (Op::AddPeer, SCHEMA 6) with that site’s CA certificate as PEM;upstream/<site>/enabled(writable) andremovechange or drop it. Peers fromwyrmd.json5are shown read-only (origin: config). Every consumer uses the merged list (Control::peers): the ACL, the peer nodes, the router’s connect endpoints (Control::upstream_endpoints),peer-trust.pem(runtime CAs are written todata_dir/pki/peers/<site>.pem; the bundle file is deleted when no downstream CA is left), the link-id checks and the gateway’s readable sites. A disabled upstream is out of all of them.peers.listenmay now stand alone inwyrmd.json5; the QUIC listener opens only while a downstream site exists. A CA must parse as one PEM certificate with the CA basic constraint (16 KiB max). Each change is audited (peer_add,peer_remove,peer_enable) and rebuilds the router. Test:runtime_peers_over_quic(no peers in either json5; central adds the edge’s CA, the edge adds central as upstream and sees it connected, central reads the edge tree; disabling the upstream drops it). - Upstream reads
sysandupstream; chains of brokers (2026-10-22, owner decision, as a DSA upstream that browses its downstream broker whole). The upstream may also readwy/<site>/sys/**andwy/<site>/upstream/**: queries, subscriptions and the data sent up (put,delete,reply) cover only**/~metaand**/~valthere (upstream-sub,upstream-data), so nothing else published undersys, such as the audit records ofsys/audit/<link>, leaves the site; declarations and liveliness cover the sections whole.~setand~actstay closed everywhere, so nosysaction (Get Log, Install, Purge, …) runs from above. A chainplant → edge → centralworks throughvia: a downstream entry lists the sites that broker relays from further down (downstream: [{ site: "edge", ca, via: ["plant"] }], alsosys/downstream/~act/add {via},PeerDef::via, registry SCHEMA 13). The upstream’ssite-<d>rule then coverswy/<d>/**andwy/<via>/**, its requesters and gateway (read_sites) may read them, and the middle broker lets its own upstream read the sites below it with the same read-only rules (acl::Peers::reachable). Each upstream decides by configuration which sites a downstream may serve; a site name appears once among all peers and theirvialists (wyrmd.json5validation,sys/downstreamAdd and the registry refuse a peer named like a relayed site, and a site relayed twice).wy/<site>/upstreamis always served (empty without upstream), so a client opening a site finds its four sections. Tests:peer_brokers,chains_of_brokers(ACL),chain_of_three_brokers(e2e: central lists plant’s links through edge, readssys/upstreambelow, receives plant samples;setand asysaction below fail). - Test.
two_brokers_over_quicincrates/wyrmd/tests/e2e.rs:central(downstreamedge) andedge(upstreamcentral, mock link,upstream_val_hz: 50). A client on central listswy/edge/downstream, receives samples ofwy/edge/downstream/mock/g0/p0, and itsseton that point fails at the edge ACL.
Consequences
- No write across sites. An upstream site cannot
set/invokeon a downstream site, even with a validptok: the edge ACL drops the query before it reaches the SDK. Reading is open ondownstream,dataflows,sysandupstream(2026-10-22): the upstream’s administrators see the downstream’s links, packages, peers, history settings and status values, as in DSA. Cross-site commands need a later design (e.g. a relay on the downstream site that re-signs with a local token). - Downsampling selects by link protocol, not by peer CN. Zenoh downsampling has no certificate subject. Any
quic/session (also a link or operator iflistenever containsquic/) gets the same rate limit on our~val. - The rate is per rule, so per link, not per key. Zenoh 1.10.1 keeps one timestamp per rule per transport (
TimeStateininterceptor/downsampling.rs) and picks one matching rule per key (so the rules must not overlap). Each link getsupstream_val_hzsamples/s towards each peer: a busy link cannot starve another link, but a busy point can still starve a slow point of the same link. Keys of a link that is not in the registry (devprofile only) are not limited. Per-key limits would need a WYRM-side relay. Test:two_brokers_over_quic(a 160 samples/s link and a 2 samples/s link underupstream_val_hz: 5; the slow one gets its samples). - Trusting a peer CA means trusting that site not to impersonate others. All downstream CAs share one
peer-trust.pem, and ACL subjects match the CN, not the issuer. A trusted downstream CA can mintbroker:<other-downstream>(and receive that site’ssite-<d>rule) orbroker:<upstream>(and read ourdownstream/**anddataflows/**). Zenoh 1.10 cannot bind a CN to a CA. Accepted (owner decision 2026-10-21): each site runs its own PKI and the operators exchange CA certificates on purpose; adding a downstream CA is a trust decision about that site’s administrators. A federation CA and certificate pinning were considered and rejected as more operational work than the risk warrants. Note: quarantine does not cover this case, because an impersonating certificate carries a CN that is already configured (broker:<site>). - The e2e tests use
tcp/main listeners, so the isolation of peer CAs from atls/main listener is not covered by a test yet.two_brokers_isolationcovers the rest between real brokers: no upstream read ofsys/**, no upstreaminvoke, no downstream put or query outside itswy/<d>/**, and no peer from an untrusted CA. - A change of
peersneeds a broker restart (the section is read atDaemon::open); peer CA files are re-read on every broker build.
Alternatives
- Broker links on a separate
tls/…:7448listener (the wiki’s design). Rejected: link, operator and broker subjects would all betls, so a peer CA could mint a CN that matches a link rule. QUIC keeps the subjects apart bylink_protocols, and suits WAN/4G better. - Add peer CAs to the global root. Rejected: every peer CA could then authenticate on the link listener.
- Upstream gets write with
ptokchecks only. Rejected for now: when sites share an admin key (as in the e2e test), a valid token would pass the SDK check. The ACL is a boundary that does not depend on how keys are distributed. - Prefix rewriting (virtual site names). Rejected by spec 01: full site names everywhere.
ADR 0008 — Flow engine trust and deploy proofs
Status: accepted · 2026-10-20
Context
The flow engine (crates/wyrm-flow, responder for wy/<site>/dataflows/**) runs invoke/set sinks that command devices. Each flow acts with a ptok that the engine signs with its own key (flows.key, subject flow:<id>, max = maxperm, grants = the flow’s command targets at maxperm). Links must trust that key, or flows cannot command anything. But if a config right on dataflows/** were enough to deploy a flow, anyone who may deploy flows could write to every device through the flow key: config on dataflows/** would become write on downstream/**.
Decision
- Who trusts whom.
- Links trust admin keys plus
ControlConfig.link_keys= the flow key and the gateway key (ADR 0009). The admin responder (sys/**) trusts admin keys only: a flow may command devices, never the control plane. - The flow engine trusts admin keys plus the gateway key, never the flow key: flow tokens cannot deploy, start, stop or remove flows (no flow can widen itself).
- Links trust admin keys plus
~defis read-only.dataflows/<id>/~defis served as a document; there is noputdeploy, because a bareputcarries no verified caller. Deploying goes throughdataflows/~act/deployonly (levelconfig,ptok, audit).deploy {def, proofs}. Before compiling, the engine checks (crates/wyrm-flow/src/engine.rs):caller_covers:permissions.maxperm≤ the deployer’s effective permission on the deploy action.proves_targets: for every command target of the definition (command_targets: full keys of…/~act/<a>and…/~set, relative keys resolved underwy/<site>/):- the target is an exact key under
wy/<site>/downstream/or, since ADR 0017,wy/<site>/storage/(no*, no$, so nosys/**, nodataflows/**, no other site); proofs[target]is aptokfor that exact key, verified by the engine’s keys (admin keys and the gateway key, so admin- or gateway-signed);- the proof has the same subject as the deploy caller;
- the proof gives at least
max(maxperm, write)on that key. Any failure ispermission_denied(orinvalid_parameterfor a bad target) and nothing is stored.
- the target is an exact key under
- Client side.
WyrmClient::proof(key)(crates/wyrm-client/src/lib.rs) returns a token for one key from the client’s token source;wyr flow deploybuilds{def, proofs}with it (tools/wyr/src/flow.rs::deploy_args) and fails early if it cannot sign a proof.
Consequences
- A flow can do on a device only what its deployer could do there at deploy time, and only on the keys the definition names.
- Command targets are static. A flow cannot compute target keys at run time or use patterns; a fan-out needs one sink per key.
- Proofs are checked at deploy time only. Stored flows redeploy on every engine start (every broker build, ADR 0006) without proofs. Revoking a deployer’s rights does not stop or re-check a running flow; an operator must
stop/removeit. Accepted (owner decision 2026-10-21): flows are infrastructure, like a PLC program, and keep running until an operator stops them. The flow store keeps the deployer’s subject with each definition (PutDef.by,FlowStore.deployers, schema 3), and the flow~valshows it asdeployed_by(spec 06, 0.1.4), so an operator can find the flows of a removed user. - Gateway users cannot deploy flows with command sinks yet. The gateway mints a ptok per request and never hands tokens to the user, so a gateway user has no way to send
proofs. Flows without command sinks need no proofs. Deploying with sinks currently needs a key holder (wyr --key). caller_coversis weak by itself (the deploy action already needsconfig); the per-target proofs carry the real check.
Alternatives
- Engine checks the deployer’s grants from the deploy
ptok. Rejected: requester tokens are scoped to the request key (dataflows/~act/deploy), so they say nothing about the targets. - Links do not trust the flow key; flows forward the deployer’s token. Rejected: tokens live 5 min and flows run for months.
- Separate flow key per deployer, trusted per link. Rejected: key management per user, and every link reconfigured or restarted (
LinkConfig.admin_keys) for every new deployer. - Allow wildcard targets with a wildcard proof. Rejected for now: a pattern proof is easy to over-grant, and the flow token would then cover keys that appear later.
ADR 0009 — User gateway: sessions, per-request ptok, trust boundary
Status: accepted · 2026-10-20
Context
People use WYRM through a browser or app, not with an Ed25519 key or a client certificate (wiki “Користувачі — gateway чи mTLS”). Links already authorize every ~set/~act by ptok (spec 04). The gateway must turn a password login into such tokens without becoming a master key for the whole broker, and without leaking long-lived credentials into URLs or logs.
Decision
- Hosting.
crates/wyrm-gatewayruns insidewyrmdwhenwyrmd.json5has agatewaysection (GatewaySection:listen,tls_cert/tls_key,session_ttl_sclamped to 60 s … 7 d,admin_userdefaultadmin). TLS (rustls) is required off loopback, checked in bothConfig::from_json5andGateway::open. State lives indata_dir/gateway/:hmac.key,users/(wyrm-stateWAL + snapshot, ADR 0003) andgateway.key(Ed25519, 0600). TheGatewaysurvives broker rebuilds; its HTTP/WS server is per broker (ADR 0006) and talks to Zenoh through the in-process session. - API. Canonical CBOR bodies and frames:
POST /api/login,GET /api/me,POST /api/ws-ticket,GET /api/ws, and user management under/api/usersfor users withconfigonwy/<site>/sys/**. - Users. argon2id PHC hashes (hashed before the WAL sees the operation), passwords 8–1024 bytes, names
[A-Za-z0-9._-]{1,64}. Unknown names run a dummy verify of the same cost. At most 4 argon2 runs at once. - Sessions. Stateless token
base64url(0x01 ‖ cbor{sub, roles, exp, iat, jti, gen} ‖ HMAC-SHA256); the MAC key is derived fromhmac.key(HMAC(key, "wyrm-gateway/session/v1")), never the key itself. Default lifetime 8 h. On every request the token is resolved against the store: the user must exist, be enabled and have the samegen; grants come from the user’s roles now, not from the token. - Generation counter is store-wide.
UserDb.next_genonly grows and survivesRemoveUser. Creation, password change and disable take a new value, so they end older sessions, including those of an earlier user with the same name: a re-created name never revives a session. - Per-request
ptok.Gateway::tokens_forsigns one token per request withgateway.key: subjectuser:<name>, the user’s grants and max permission, scoped to the request key, 5 min lifetime. The gateway checks grants itself before sending (list/meta/children≥ list,subscribe≥ read on part of the pattern,set≥ write,invoke≥ read with the action level left to the responder) and drops samples and children the user may not see. Refusals are audited asDenied. - Trust boundary. Links (
ControlConfig.link_keys) and the flow engine trust the gateway key. Amended 2026-10-22 (owner decision): the admin trusts it too (ControlConfig.control_keys), so the control plane (sys/**: link install, start/stop, update, secrets, quarantine, profiles) is reachable from the app. The token of every request carries the user’s grants, so only roles withconfigonwy/<site>/sys/**(the defaultadminrole) pass;viewer,operatorandengineergetpermission_denied. Each action is audited withuser:<name>. Test:gateway_in_wyrmd. Gateway user management is local to the gateway store, not an admin operation. - WebSocket tickets.
POST /api/ws-ticket(bearer session) returns a random 128-bit ticket, single use, 30 s;GET /api/ws?ticket=…spends it and re-resolves the session. The long-lived session never appears in a URL. At most 8 live tickets per user; a new one replaces that user’s oldest, so one user cannot crowd out the others.Authorization: Beareris also accepted for non-browser clients. Open sockets re-read the user every 15 s and close at session expiry. - Role grants at runtime (2026-10-22, owner decision, as DSA
updatePermissions/getPermissions).sys/~act/update_permissions {role, path, level}(config) adds a grant, changes its level, or at levelnoneremoves it; a new role starts empty. The stored list of a role (users storeOp::SetRole, SCHEMA 3) replaces the configured role of the same name. A new grant goes before the first grant of that role whose key expression includes it, so a narrower grant is not shadowed (first match wins). A change that leaves no enabled user withconfigonwy/<site>/sys/**is refused. Sessions see the change on their next request (grants are resolved per request).sys/~act/get_permissions(config) lists the role grants and the generated router ACL, one row per subject and rule. Every change is audited (update_permissions). Tests:grant_edits_keep_narrow_grants_first,role_grants_change_persist_and_keep_an_admin,gateway_in_wyrmd. - First admin. At start, if
WYRM_GATEWAY_ADMIN_PASSWORDis set andadmin_userdoes not exist, that user is created with theadminrole. The variable is removed from the process environment right after reading, and the supervisor starts link processes with a cleared environment (env_clearplusRUST_LOG,RUST_BACKTRACE,TZ,LANG,LC_ALL,PATH). The password never comes fromwyrmd.json5. - Login rate limit. At most 5 failed logins per
(user, ip)and 20 peripover all user names in a sliding 60 s window; a success clears the(user, ip)record; at 10 000 records expired ones go first, then the one with the oldest last failure. - Audit.
AuditEvents (LoginOk,LoginFailed{reason},UserChanged,Denied) go into the admin journal throughControl::record: logins and refusals with subjectuser:<name>, user changes with the acting user’s name as subject. They never carry passwords or tokens.
Consequences
- A stolen gateway key gives
write/configon devices, flows and (since the 2026-10-22 amendment) the control plane of this site, not on other sites (their links do not trust it). The gateway runs insidewyrmdwith the samedata_dir, so its key is as exposed as the broker itself. - Role changes take effect on the next request without a new login; sessions can only be ended by password change, disable or removal (no logout list).
- The default roles grant nothing on
sys/**except theadminrole’sconfig, which governs gateway user management and the control plane. - Flow deploys through the WebSocket get their proofs from the gateway (ADR 0008): for
invoke wy/<site>/dataflows deploy, the gateway replaces any clientproofswith one token per command target, signed with that user’s grants. A user without rights on a target gets no proof, and the engine refuses the deploy. - Spraying from many addresses is bounded only by the argon2 cost (4 concurrent hashes).
- A broker rebuild (ADR 0006) closes all WebSockets; sessions and tickets stay valid.
Alternatives
- Users with client certificates (mTLS) and an operator CN each. Rejected for people: certificate handling in browsers and phones; kept for engineering tools (
operators). - The admin trusts the gateway key. First rejected (a web-facing process would hold the control plane); adopted on 2026-10-22 by owner decision, with the role grants as the limit.
- Server-side session table. Rejected: the store-wide
gengives revocation without per-session state. - Session token in the WebSocket URL. Rejected: URLs end up in proxy and browser logs; replaced by single-use tickets.
ADR 0010 — WASM host for flow nodes (and later drivers)
Status: accepted · 2026-10-20
Context
Principle 2 forbids dynamic Zenoh plugins; extensions come as data and processes. Iteration 8 adds sandboxed code: a flow node or a driver delivered as a WebAssembly component, loaded without a restart, unable to touch the host beyond what WYRM passes in.
Decision
crates/wyrm-wasm-host: wasmtime=50.0.3(the newest release line, pinned exactly; was=40.0.4until 2026-11-01 and=36.0.20, the LTS line, until 2026-11-20: see the note of 2026-11-20 below and ADR 0031), component model, no WASI. The linker is empty: a component that imports anything is refused at load (Error::Denied).- WIT worlds (
crates/wyrm-wasm-host/wit/):wyrm:flow/node—init(config),process(port, sample, state) -> (outputs, state);wyrm:link/point—init,read,write. All data is canonical CBOR (principle 5). The host keeps node state and passes it on every call, so a trap that destroys the instance never loses state. - Limits per call: fuel (default 10 M, max 1 G), memory via a resource limiter (default 16 MiB, max 256 MiB), wall time via epoch interruption (100 ms, max 1 s). A trap drops the instance; the next call re-instantiates and re-runs
init. - Components are content-addressed:
put_artifact {bytes}(flow engine root action,config) stores<flow dir>/artifacts/<sha256>.wasm(temp file + rename, hash checked on every read) and accepts onlywyrm:flow/nodecomponents without imports. A~defnode is{type: "wasm", artifact: "<sha256>", inputs, outputs, config, fuel, memory_mb}. - Hot load =
put_artifact+deploy: the flow hot-swaps (no process restart).
Consequences
- A guest cannot open files, sockets or clocks; capabilities (
net:*,secrets:*) are a later, explicit host-import design. - Guest calls run synchronously on a tokio worker for up to the time limit.
validate(read) loads the artifact and runsinit; bounded by the limits and the per-caller invoke rate limit.- Not yet: driver-framework integration of
wyrm:link/point, artifact list/remove, per-node time limit, metrics for fuel and errors,placement: "wasm"from spec 06.
Alternatives
- wasmer / wasm3: rejected; wasmtime has the component model, fuel and epoch interruption.
- WASI preview 2 with a deny-all policy: rejected for now; an empty linker is simpler to audit.
- Core modules with a hand-made ABI: rejected; WIT gives typed, versioned interfaces.
Note of 2026-11-20: wasmtime 36.0.20 → 50.0.3
Three advisories of 2026-11-16 made cargo audit fail on 36.0.20 (RUSTSEC-2026-0566, -0569, -0571; fixed in 36.0.21). The owner’s rule is the newest version of a dependency, not the oldest one that passes, so the host moved to the newest release line and not to 36.0.21. Two more advisories of that day exist only on the newer lines (RUSTSEC-2026-0567 from 39, -0573 from 47); 50.0.2 fixed all five.
- Pin.
=50.0.3, featuresruntime,cranelift,component-model,stdas before: no WASI, async, cache, GC, threads or profiling. Thewasm-toolscrates (wasmparser,wit-component,wit-parser) follow it to 0.261, the version wasmtime 50 is built on. - Rust. wasmtime 50 needs Rust 1.97, so the workspace
rust-versionwent from 1.89 to 1.97. CI and the container images build with stable (1.99 and later). - Code. The engine API the host uses (
Config,Storelimiter, fuel, epochs,component::Linker,bindgen!) did not change. Two calls of thewasm-toolscrates did: an import or export name is now a structure (full_name()), andembed_component_metadatatakescanonical_names(false). - WebAssembly features. The engine’s defaults grew between 36 and 50: wasmtime 50 turns on the GC proposal, function references and wide arithmetic, and a build without the
gccargo feature removes only the GC types and exceptions. So with a defaultConfiga guest could use typed function references (call_ref), function subtypes,ref.test,ref.cast,i31andi64.add128, none of which 36 took. That is the path of RUSTSEC-2026-0570 (a guest aborts the process of a build withoutgc; fixed in 50.0.2). An abort is no trap: it ends the broker with every link. Rule: the host names every feature a guest may use (GUEST_FEATURESincrates/wyrm-wasm-host/src/lib.rs) andHost::newturns these on and every other feature off (Config::wasm_featureswith the set and with its complement), so the engine’s defaults decide nothing and an upgrade cannot widen the set. The set is what 36.0.20 took: WebAssembly 2.0 (mutable globals, sign extension, saturating conversions, multi-value, bulk memory, reference types withfuncrefonly, SIMD), multi-memory, relaxed SIMD, tail calls, extended constants, 64-bit memories, the component model. Multi-memory and 64-bit memories stay: they were on, installed components may use them, and the memory limit counts all memories of an instance together (the limiter sees every growth). Off, among others: GC, function references,externref, exceptions, threads, wide arithmetic, stack switching, custom page sizes, compact imports, every component-model extension (async,map,implements). RUSTSEC-2026-0567 (atomics in a build withoutthreads) and -0573 (GC heap with a set reservation) are not reachable for the same reason, and 50.0.3 has all three fixes. A feature is added only with a guest that needs it, a test and a line here. Tests:features_outside_the_set_are_refused_at_load(it fails on a defaultConfig),features_of_the_set_load_and_run,an_import_that_only_implements_a_known_interface_is_refused. - What the guest toolchain needs. Checked on 2026-11-20 with this set: the 11 WASM packages of
wyr repo build --form wasm(alarm, dql, dynamodb, influxdb, mongodb, mysql, postgres, scheduler, slack, telegram, uplink) andportable-echoofwyr link pack, all built withwyrm-link-guest(wit-bindgen 0.57.1) forwyrm:app@0.3.0, load on the host. The testbuilt_packages_loadrepeats the check on a directory of unpacked packages (WYRM_WASM_PACKAGES); run it after an engine upgrade or a change of the set. - Host calls. The engine bounds what one call from a guest may make the host allocate for its arguments (“hostcall fuel”; default 128 MiB in wasmtime 50, 2 GiB in 36). The host sets it to the instance’s memory limit (
Limits::memory_bytes, 16 MiB by default): a guest cannot hold more than that, so no call that fits the memory limit is refused, and the bound follows the limit instead of the engine’s default. - Limits. Memory, time and import refusals behave as before, with the same error texts. Fuel is counted a little differently (wasmtime 46 charges a bulk memory instruction by its size, 50 charges more host allocations): one call of the test node
adduses 207 units, was 200. The defaults stay. - Compiled code. The host compiles a component in memory at load and keeps it by SHA-256 for the life of the process. Nothing compiled is written to disk, so no file of an older engine can be loaded.
ADR 0011 — Installing links at runtime (packages, process and WASM)
Status: accepted (owner decisions 2026-10-22) · 2026-10-22
Context
The DSA broker installs links while it runs: Install Link ▸ from Git | from Url | from Zip | from Repository, and the link appears under /sys/links/<name>. The owner wants the same, with three ways to run a link: as WASM, as a separate process, or in the broker’s own space. No other languages for now.
Today a link runs a driver compiled into wyrmd: embedded (in-process), process (wyrmd link <driver>) or external (a device with a CA certificate).
Rust has no stable ABI, and principle 2 forbids dynamic plugins. Code that arrives at runtime therefore cannot be loaded into the broker as native code. Inside the broker’s process, only WASM can run it, in the sandbox of ADR 0010.
Decision
- Modes for a runtime-installed link.
embedded: built-in drivers only (unchanged, “from Driver”).process: a built-in driver (wyrmd link <driver>, unchanged) or the binary of a package. The binary linkswyrm-link-sdkand callsprocess::run::<D>(). It gets the same supervision as today: mTLS certificate with CN = link id, link token, private data dir, rlimits, cleared environment.wasm: a component of the WIT worldwyrm:link/point(ADR 0010), hosted in-process by the framework driverwasmunder fuel, memory and time limits. The component has no I/O until host imports exist (a later ADR:net:tcpgated by capabilities), so its points are computed.
- Package = a zip with
wyrm-link.jsonat its root:{ name, version, description?, wyrm_link: <protocol>, kind: "process" | "wasm", entries?: { "<target triple>": "<path>" }, args?: [..], entry?: "<path>.wasm" }.wyrm_linkis the link protocol version ofwyrm-link-sdk(helloreply shape, trust lists). A package built for another version is refused (success: false), so it cannot misread the trust lists.- A
processpackage lists one executable per target triple;argsare its arguments (for example["link", "mock"]). Process mode needs the broker’stls/listener (link_endpoint); without it the install answerssuccess: false. - Unpacked into a temp dir and renamed to
data_dir/packages/<name>/<version>/, so a failed install leaves nothing: at most 64 MiB compressed, 256 MiB unpacked and 1000 files; relative paths only, no.., no symlinks, regular files only; the entry for this target gets the executable bit. - Upgrade: a package with an installed name and a new version replaces the old one; the links that use it restart on the new version, then the old directory is removed. The same version again is refused.
- The registry keeps one active version per name (
Op::PutPackage,Op::RemovePackage) with its kind, entry, SHA-256 of the zip and its source. A link of a package has driverpkg:<name>. sys/packages/<name>shows version, kind, source and SHA-256;removerefuses while a link uses the package.
- Sources (actions of
sys/links, in the group “Install Link”, each withname= the new link id; each declares atimeout_mslong enough for a fetch and unpack):- from Driver
{id, driver, mode, params}: the currentinstall(same action id, sowyr installandwyrm-mcpkeep working; only its display and group change). - from Zip
{name, zip}: the zip as a binary parameter with thefileeditor (spec 02 0.1.7). - from Url
{name, url}: HTTPS only, at most 3 redirects, size and time limits, roots from the OS store. - from Git
{name, url, ref}:git -c protocol.allow=never -c protocol.https.allow=always clone --depth 1 --no-recurse-submodules --branch <ref> -- <url> <dir>withGIT_TERMINAL_PROMPT=0and no hooks; aurlorrefthat starts with-is refused. The checkout root must holdwyrm-link.jsonwith built artifacts: the broker does not compile. - from Repository
{name, package}: an index atpackages.repositoryinwyrmd.json5(as DSA’slinkRepositoryUrl), JSON[{name, version, description, url, sha256}]. It is fetched in the background, never on the start path;packagebecomes an enum once it arrives (declared again like the quarantine lists). Without the index the action answerssuccess: false, "repository unreachable". The download must matchsha256. - from WASM
{name, wasm}: onewyrm:link/drivercomponent (ADR 0012), wrapped as awasmpackage; awasmpackage zip from any other source works the same.
- from Driver
- Large arguments. A WebSocket frame of the gateway is at most 64 KiB, so a zip or a component cannot travel over it. The gateway gets
POST /api/invoke?key=…&action=…(bearer session; body = the CBORargsmap, at most 64 MiB). Before the body is read it checks the key (downstream sites stay read-only), that the action has aneditor: "file"parameter (spec 02 0.1.7, from the node’s expanded~meta) and that the user’s grant reaches the action’s level; then it counts the CBOR items (at most 10 000, so the size goes to file contents and not to a tree that decodes to many times its size) before decoding, and runs two such calls at a time. The DartFrameClientsends arguments over 60 KiB this way on its own; the explorer picks the file (the macOS app needs the user-selected read-only file entitlement). Amended 2026-11-15 (ADR 0028 amendment): everybinaryparameter that can be larger than a frame iseditor: "file", a part of a file included; a refusal before the body is read reaches the client (the gateway reads and drops the body first). Amended again 2026-11-15 (ADR 0028 amendment 2): the Rustwyrm-gateway-clienttakes the same route for arguments over 60 KiB, withExpect: 100-continue, so a refusal comes before the body; astringormapargument has no route and stays under 60 KiB. - Rebuilds wait for installs. A process link install rebuilds the router (ADR 0006). Package installs count as busy (
Control::busy). Before it stops the broker,wyrmdcloses the door and waits for them (Control::quiesce, at most 180 s), so an install in flight is not cut off halfway on the old broker; an install that arrives meanwhile answersbusy(“try again”) instead of starting, and the new broker opens again (Control::reopen). - Fetching (
wyrm_admin::fetch): webpki roots, ring provider, at most 3 redirects, 64 MiB per package and 4 MiB per index, 90 s; plainhttp://only to loopback.gitruns with a cleared environment, no system or global config, andfile://only in thedevprofile (tests). - Result of every source:
{success: bool, message: string}, as in DSA, so the explorer shows two output rows; a failed fetch or a bad package issuccess: falsewith the reason, not an error status. - Trust (owner decision 2026-10-22): no package signing; level
configis enough, as in DSA. Aprocesspackage is code that runs on the broker host with the link’s rights. Every install and removal is audited with the SHA-256 and the source. - Requester grants (2026-10-22, ADR 0013): a package may ask for grants in
wyrm-link.jsonrequester: [{path, level}](at mostwrite, neversys). Each new link of the package gets them at install; the install message lists them.
Consequences
- A
configuser (also through the gateway, ADR 0009) can run arbitrary code on the host as the broker’s user, limited by rlimits and the process link’s ACL. Recorded indocs/security/threats.md; signing, a separate uid and seccomp stay possible later. - A WASM link cannot reach devices until host imports exist; until then it serves computed points (simulations, conversions, tests).
- “from Git” needs
giton the host; it fetches built packages, not sources. - Packages and their files survive broker restarts (
data_dir); the registry WAL holds their metadata.
Alternatives
- Native plugins in the broker (
.so/dylib). Rejected: principle 2, no stable Rust ABI, a crash takes the broker down. - Links in other languages over a stdio protocol. Deferred by the owner: no other languages for now.
- Signed packages only. Rejected by the owner for now: DSA has no signing, and the
configlevel already gates installs.
ADR 0012 — Network for WASM links (wyrm:link/tcp)
Status: accepted (owner decision 2026-10-22: WASM links get network in this iteration) · 2026-10-22
Context
ADR 0011 lets a link run as a WASM component inside the broker. The component world wyrm:link/point (ADR 0010) imports nothing, so such a link cannot reach a device: it only computes. The owner wants WASM links that talk to devices now. A WASM component has no ambient rights; every capability is a host import.
Decision
- WIT. Package
wyrm:link@0.1.0getsinterface tcpand worlddriver:connect(addr: string, port: u16, timeout-ms: u32) -> result<u32, string>—addris an IP literal (192.168.1.20,fd00::5), never a host name;send(conn: u32, data: list<u8>) -> result<_, string>— at most 64 KiB per call; the time left is checked again before each piece written;recv(conn: u32, max: u32, timeout-ms: u32) -> result<list<u8>, string>— at most 64 KiB per call, an empty list at EOF;close(conn: u32);- world
driver= worldpoint(init,read,write) plusimport tcp. Apointcomponent (no imports) runs as adrivertoo. The linker defines exactly this interface: any other import is still refused at load (Error::Denied).
- Allowlist (capability). Each instance has a list of
<ip>/<prefix>:<port>entries (10.0.5.0/24:502,[fd00::]/64:502); empty = no network.connectpasses only when the address is inside one entry and the port is that entry’s port. IP literals only, in the list and inconnect:stdresolution has no timeout, and resolve-then-check invites rebinding. Special addresses pass only an entry of the same class that is no wider than the class: loopback, link-local (and IPv6 site-local), multicast, broadcast, “this network” (0.0.0.0/8), IPv6 that carries an IPv4 address (IPv4-compatible, NAT6464:ff9b::/96and64:ff9b:1::/48, 6to42002::/16) and cloud metadata (169.254.169.254is link-local;fd00:ec2::/32). So0.0.0.0/0or[::]/0never reaches the broker’s own listeners (indev, loopback has full rights). Private ranges (10/8,172.16/12,192.168/16, ULA) are ordinary: field devices live there. IPv4-mapped IPv6 is checked as IPv4. - Who sets it. The list is a connection parameter of the
wasmframework driver (net). The framework’sadd_*andeditactions needconfig(ADR 0004), so onlyconfigwidens it; the parameter is a destination field (dest), so a stored secret does not follow a changed list. - Time. Epoch deadlines count wall time inside host calls too. A link call has its own budget: 2 s by default, at most 10 s (
call_ms); flow nodes keep theirs (ADR 0010). Every host I/O timeout is capped at the time left in the call, so a blockingrecvcannot outlive the call; the next guest instruction after the deadline traps, the instance is dropped (its connections closed) and the next call instantiates it again. - Handles. At most 4 open connections per instance, kept in the store; they close when the instance drops (trap, slot swap, link stop).
- Threads. Host I/O is blocking
std::net. Each WASM connection of the driver runs on its own OS thread that owns the store; the framework’s per-connection owner task sends itread/writerequests over a bounded channel. Noasyncin wasmtime, no blocked tokio workers. - Driver
wasm(links/wasm, a framework driver, embedded): connection paramscomponent(the package name: the admin puts eachwasmpackage’s entry atdata_dir/packages/.wasm/<package>.wasm, replacing it in one rename on an upgrade, and restarts the package’s links so they load the new file; naming another installed package only selects that one),net,config(JSON, passed toinitas CBOR),call_ms; devicenote(devices only group points: no ping); pointvalue(number,bool,text,any: the node type, so an app sends the right type onset),cfg(JSON, passed toread/writeas CBOR),poll_s,writable,unit. Awasmpackage (or one component through “Install Link ▸ from WASM”, wrapped as package<name>, version0+<sha256 prefix>) installs as an embedded link with driverpkg:<name>and one connectionmain; its devices and points come from the connection’sAddactions and survive upgrades (the framework keeps its tree). Test:wasm_link_reads_a_device_over_tcp.
Consequences
- A WASM link implements its protocol (Modbus framing, …) inside the guest, with the network limited to the listed addresses and ports.
- Not in v1: TLS, DNS, UDP, serial ports, clocks. Each would be another explicit import.
- A guest can still use its time and fuel on network waits; the per-call budget bounds it.
Alternatives
- WASI sockets (
wasi:sockets): rejected for now; a deny-all WASI policy is harder to audit than one small interface (ADR 0010). - Host names with a resolver: deferred; needs a resolver with timeouts and a resolve-once rule.
- Async host functions (
async_support): rejected; it would change the flow-node path too.
ADR 0013 — Links as requesters (link grants)
Status: accepted (owner decision 2026-10-22: grants per link) · 2026-10-22
Context
A DSA link can be a responder (it serves nodes), a requester (it reads and commands other nodes) or both (isRequester). In WYRM a link served only its own branch: the generated ACL let a link’s certificate reach wy/<site>/downstream/<id>/** and nothing else, and a link held no key that other links trust. Historians, bridges and aggregators need to read, and sometimes command, other links.
Decision
- Grants per link, as gateway roles have them:
LinkDef::grants=(path, level). The path is a node key prefix with{site}:wy/{site}/downstream[/…]orwy/{site}/dataflows[/…], plain segments only (no wildcards, no suffixes), neversys/**. Levels:list,read,write;configstays with people (MAX_LINK_GRANT), anddataflowsgrants stop atread. - Set with
sys/links/<id>/~act/grant {path, level}(the caller needsconfig; levelnoneremoves), audited (link_grant), shown insys/~act/get_permissions(sourcelink). A package asks for its grants inwyrm-link.jsonrequester: [{path, level}]; each new link of the package gets them at install, and the install result lists them. A package cannot ask for a whole root (wy/{site}/downstream,wy/{site}/dataflows): only an operator grants that, with Grant Access. - ACL (process and external links, by their certificate CN;
acl::grant_rules):list→~metaqueries and liveliness under the path;read→ also~valqueries and subscriptions;write→ any query (~set,~act) under the path; the answers flow back (egressput,delete,reply,liveliness_token). - Requester key. A link with grants gets a signing key as the link secret
.requester_key(wyrm_link_sdk::REQUESTER_KEY), created by the broker, delivered like its other secrets (hellofor a process link). Every link trusts it as oneLimitedKeyper grant: up to that grant’s level, only under that grant’s path, and only for the subjectlink:<id>(LimitedKey::subject;Verifiertakes the highest cap among the keys that cover a request and accept itssub), so the audit names the real caller.hellosends such keys inbound_keys([key, cap, scopes, subject]); a link built before this ignores the field and does not trust them. The link signs itsptoks with it (LinkCtx::requester_key, subjectlink:<id>); reads of~meta/~valneed no token. - A grant change rebuilds the router (ACL) and so every link’s trust list (embedded links restart, process links say
helloagain).
Consequences
- Embedded links run on the broker’s in-process session and bypass the ACL: they can read every branch already. A grant gives them only the trusted key for
~set/~act. - The flow engine and the admin do not trust requester keys: a link cannot deploy flows or reach the control plane.
- Grants are additive; a link has no “deny” grant. Removing the link removes its grants and its key.
- Examples:
examples/links/requester(read grant),examples/links/both(write grant); testslink_grants,link_grants_open_other_branches,link_grants_make_a_requester.
Alternatives
- Read-only requesters. Rejected by the owner: bridges must command.
- Requesters only as separate clients (operator certificates, gateway users). Kept for tools; a link that is both responder and requester would need two identities.
ADR 0014 — Embedded historian (sys/history)
Status: accepted (owner decision 2026-10-22: the history store is built into the broker, with statistics and actions in sys, as DSA’s etsdb link; other historians stay possible as requester links). The store engine (redb, one file per day) is a proposal the owner can change. · 2026-10-22
Context
- Zenoh’s storage manager keeps
wy/**/~valin thememoryvolume: the last value of each point, in RAM, lost on restart. It keeps no history. - Zenoh volumes that persist or keep history (rocksdb, filesystem, influxdb) load only as dynamic
.soplugins, which principle 2 forbids. Of them only influxdb keeps more than the last value, and it needs an external server. - Spec 01/03/05 already define the read side:
get <point>/~val?history=<from>..<to>[&agg=&window=]→ CBOR array of[t, v, q]. - The owner wants the historian of the DSA etsdb link (its nodes and functions, not its database) in the broker, and external historians as links that read through requester grants (ADR 0013; example
examples/links/requester).
Decision
- Crate
wyrm-history: the store, the watch-group engine and the query folder. The admin hosts its nodes underwy/<site>/sys/history; its settings are control-plane state in the registry (Registry::historian, opsPutWatchGroup,RemoveWatchGroup,AddWatch,SetWatchEnabled,RemoveWatch,SetHistoryOptions, SCHEMA 12). - Store: redb (pure Rust, ACID, no C/C++ toolchain;
~4.1, the newest line for MSRV 1.89), one file per UTC day indata_dir/history/days/YYYY-MM-DD.redb, plusindex.redb(point key → series number). Row key(series u32, t µs), value canonical CBOR[v, q]; a row with the same key replaces the old one. A day is the unit of retention: redb reuses freed pages but never shrinks a file, so purging by whole files is what gives the disk its space back. Page cache 8 MiB per file, at most 4 files open. - Engine (DSA historian): watch groups with
Logging TypeNone / Interval (the last value everyinterval, changed or not) / All Data (every update) / Point Change (value or quality changed), andBuffer Flush Time(rows wait in memory, then one transaction per day file). A watch follows<key>/~valon the broker’s in-process session withwyrm-client’ssubscribe(stored value first, then live). All Data and Point Change compare with the last stored row, so a restart or a router rebuild does not store the initial value twice. Pending rows are capped at 200 000 for all groups; more are dropped and counted. A row’s time is the source’s: a sample more than 5 minutes ahead of the broker’s clock or more than 31 days back is dropped and counted, so a wrong clock cannot make day files that retention and Auto Purge never reach. - Rebuilds (ADR 0006): the historian lives in
Controland outlives a router rebuild;attachbinds it to each new session,detachflushes the buffers before the old one closes. Samples published during the rebuild gap (about a second) are not recorded. - Watch paths: one point each,
wy/<site>/downstream/<link>/…orwy/<site>/dataflows/<flow>/…of this site or of a downstream site (its data arrives over the peer link); neversys, no wildcards. At most 64 groups and 10 000 watches. - Nodes (lowercase keys, DSA display names):
sys/history: Rows Written, Writes Per Second, Rows Pending, Rows Dropped, Last Flush Duration, Database Size, Space Available, Series, Day Files, Oldest Day; writable Auto Purge (default on), Disk Space Remaining (MiB, default 1024), Retention Days (default 0 = keep); actions Add Watch Group, Purge {Timerange}.sys/history/<group>: Logging Type, Interval, Buffer Flush Time; actions Edit, Add Watch Path {Path}, Delete {Purge}.sys/history/<group>/w<N>(display = the point key): Enabled (writable), Start Date, End Date; actions Get History {Timerange, Interval, Rollup, Rows}, Purge {Timerange}, Unsubscribe, Unsubscribe and Purge. No Last Written Value (DSA has one):syswould republish point values to everyone who may readsys.- 2026-10-23 (backlog item 2): these nodes show their keys (
rows_written,auto_purge,logging_type,start_date, …), no display names; actions and parameters keep theirs.
- Get History answers a table (array of records): raw rows
{time, value, quality}; with an Interval or a Rollup one row per interval{time, value}(interval start, aligned to the range start). Rollups: none (first), and, or, avg, min, max, sum, first, last, count, delta; they skipbadsamples. Timerange<from>/<to>(DSA) or<from>..<to>(spec 01), RFC 3339, empty end = now. At most 10 000 rows (1 000 by default). - Purging: every minute, days older than Retention Days go, then, with Auto Purge, the oldest days while the disk has less free space than Disk Space Remaining. The current day is never deleted. Each deletion is logged and audited (
history_purge); so are the Purge actions and every settings change (history_group,history_watch,history_options). - Access: every action, Get History included, needs
configonsys/**: the rows are point values, and a role withreadonsysneed not havereadon the points. Through the gateway only theadminrole reachessys/**(ADR 0009). Reading history with the rights of the point itself comes with~val?history=on the point’s own key (D2).
Consequences
- Principle 3 (“the broker owns only itself”) gets one exception: the broker keeps time series of points it watches, by the owner’s decision. The node tree and the last values are still owned by links and the memory storage.
data_dir/historygrows with the watches; Auto Purge and Retention Days bound it. It is not HMAC-protected like the registry (it is data, not control state);wyrmd verifydoes not check it.- Read path (D2, spec 0.1.10): the historian answers
get <point>/~val?history=…with a queryable onwy/<site>/{downstream,dataflows}/**/~valbeside the memory storage; it ignores selectors withouthistory/sinceand points it does not record, and answers one or more arrays (≤ 5000 rows each), errors as a status attachment. The storage still answers the same query with the last value (a map):WyrmClient::historykeeps the arrays. Rights assubscribe(owner decision 2026-10-22): the session ACL on~val, nohistory:readtoken; the gateway’s ophistoryneedsreadon the point. Bounds:limit≤ 100 000, 5 000 000 rows scanned (refused beyond, never cut), 4 reads at a time. Clients: Rusthistory,wyr values, Darthistory(gateway and FFIwyrm_history), explorer “View History” (chart and rows). - The CLAUDE.md layout named
history/{rocksdb,influxdb}asHistoryStorebackends. RocksDB would bring a C++ build into every cross-compile for the ARM boards; InfluxDB is an external server and fits better as a requester link.
Alternatives
- Zenoh storage volumes (rocksdb, influxdb): dynamic plugins only (principle 2); rocksdb keeps the last value only.
- One redb file for everything: simpler, but purging would not give the disk space back without a compaction that needs the space it frees.
- Own append-only files per day (as etsdb): no index per series, so reading one point scans all points of a day.
- fjall (LSM, pure Rust): younger; compaction runs in the background on the reference board.
- External historian only (a requester link): kept as an option (the recorder example), but the owner wants one in the broker.
ADR 0015 — Downstream brokers admitted by the upstream’s CA
Status: accepted · 2026-10-23 (owner decisions, backlog item 3; revised the same day after a review of how a DSA broker admits a downstream broker). Amends ADR 0007 (trust and admission only; the ACL shape, the read-only upstream and the chains stay).
Context
ADR 0007 let a downstream broker connect with a certificate of its own CA; the upstream learned that CA from peers.downstream[].ca or from sys/downstream ▸ Add Downstream Broker. ADR 0007 also accepted a risk: every CA in the shared peer-trust.pem could mint broker:<any site>.
The owner asked for the DSA layout and behaviour. In a DSA broker:
- the downstream broker adds the connection itself (
/sys/upstream ▸ Add Upstream Connection {Name, Url, Broker Name, Token, Group}) and connects to the upstream as a link, with its own key pair; - the upstream admits it as it admits any link: a valid token (
/sys/tokens, with a count and a time range) puts it straight into/downstream/<name>; withallowAllLinksit goes there too; with quarantine on it waits in/sys/quarantineuntil Authorize; otherwise it is refused; - Deauthorize lists every connection under
/downstream, brokers included; there is no install step and no/sys/linksentry for a broker.
WYRM brokers talk over QUIC with mTLS, so a downstream broker needs a certificate the upstream trusts before it can open the peer link. A first version of this ADR had the upstream issue it in advance (Install Link ▸ Downstream Broker, files copied by hand). The owner rejected that: a broker must come in on its own, as in DSA.
Decision
- One CA on the QUIC peer listener.
peers.listentrusts only this broker’s CA, as the link listener does;peer-trust.pemand per-site downstream CAs are gone. The listener opens wheneverpeers.listenis set. - Enrollment listener (owner decision: a separate port).
peers.enroll: "quic/<host>:<port>"opens a QUIC listener with server-auth TLS only (#enable_mtls=false). The ACL gives any QUIC session one key there: querywy/<site>/sys/~act/enrolland its reply (ruleenroll, a subject without a CN, so it also matches every QUIC broker, which gains nothing). The admin answers it as an open action (ashello): noptok, the unverified-caller rate limit, a 16 KiB request. - The downstream asks for its certificate.
sys/upstream ▸ Add Upstream Connection {name, url, ca, token, enabled}:urlis the upstream’s enrollment endpoint;caits CA (PEM, required: the downstream trusts nothing it was not given);tokenoptional, a secret parameter, never shown back.- The downstream makes its own key (sealed in the
SecretStoreaspeer:<site>, written 0600 for Zenoh; it never leaves the site) and sends{site, csr, token, via}(csrfor CNbroker:<own site>,viathe sites it relays). It asks again every 10 s while the answer ispending. - The answer
issuedcarries the certificate and the port ofpeers.listen; the downstream connects to the same host on that port with#root_ca_certificate_file=…;connect_certificate_file=…;connect_private_key_file=…(files: Zenoh logs endpoint strings). sys/upstream/<u>showsurl,enabled,ca(subject),status(waiting,pending authorization,issued, or the refusal),key(SHA-256 of its public key, to compare with the upstream’s quarantine entry) andcertificate(subject, valid until).
- The upstream admits it as DSA does. For an enrollment request, in this order:
- a downstream already admitted with the same key gets its certificate again; another key is refused;
- a held name (Deauthorized) waits in quarantine for a manual Authorize;
- a valid token signs at once (its count goes down;
sys/tokens ▸ Add Token {count, hours}returns the token once, the registry keeps its SHA-256); allow_all_linkssigns at once (owner decision: as DSA’sallowAllLinks) when everyviasite is free; otherwise the request goes to quarantine;- with
enable_quarantinethe request waits insys/quarantine/<site>(kind: broker,key,via); Authorize{key, via}signs it —keymust be the SHA-256 of the waiting request (the form offers exactly that one), so a request that expired and came back with another key in between is not signed; Reject blocks the name; - otherwise it is refused.
A second request for a waiting name with another key is refused and counted (
conflicts), never swapped in: the administrator compares the key on both sides before Authorize. A waiting request is written once (and again only when its key orviachanges); the polls every 10 s are counted in memory (only for names that wait) and shown in the quarantine node; a request with another key counts as a conflict and does not keep the waiting one alive. A request nobody asked again for 10 minutes leaves quarantine (as a DSA link that disconnects); a held broker stays. Every name-related refusal gives the same reason, so the open endpoint does not tell peers, links or relayed sites apart.
- Where it shows. Only
wy/<site>/downstream/<d>(live,connected) beside the links, andsys/quarantine/<d>while it waits. Deauthorize lists the runtime external links and the runtime downstream brokers; a Deauthorized broker is held in quarantine (its certificate stays valid; its sessions are recorded there; only Authorize admits it again, also with anothervia). wyrmd.json5keeps an offline path:peers.downstream: [{ site, via }]on the upstream andwyrmd caissuedata_dir/peers/<d>/broker.{pem,key}; the downstream’speers.upstreamentry namesca,cert,key. A name inpeers.downstreamis not enrolled at runtime.- Invariants (each with a test):
- The CA never signs
broker:<own site>,broker:<an upstream site>or a name a peer relays. A name signed once (Registry::issued_brokers) never becomes an upstream site: its certificate cannot be revoked and would match that upstream’s ACL subject. - A Deauthorized broker does not come back by itself (held; Reject: never).
- A key never leaves the site that made it; no key or token enters the registry WAL,
~meta,~val, the audit journal or a log (tokens are kept as SHA-256; action arguments are not logged; the gateway audits their SHA-256). - A session without a certificate on the enrollment listener reaches
sys/~act/enrollonly (enroll_listener_reaches_one_key).
- The CA never signs
- Rebuilds. A broker start waits (up to 30 s) until the QUIC peer port is free: after a router rebuild (ADR 0006) the old runtime keeps the UDP socket while its connections drain, and Zenoh 1.10.1 tries a listener once. Both the peer listener (
peers.listen) and the enrollment listener (peers.enroll) ports are waited for, under one 30 s deadline for both (#145).
Consequences
- ADR 0007’s accepted risk is gone: only this broker’s CA signs
broker:*identities on its listener, and it signs one per admitted site. - The enrollment listener is a new unauthenticated endpoint. It is bounded by the ACL (one key), the rate limit, the request size, the number of waiting requests (64, each gone after 10 minutes without a request) and writes only on change.
- With
allow_all_linkson, anyone who reaches the enrollment port gets a broker certificate for a free name and may servewy/<name>/**on this broker (read-only for our upstream, never our own keys). This is the DSA behaviour the owner chose; keepallow_all_linksoff on exposed brokers. - A certificate cannot be revoked (Zenoh 1.10 has no CRL); invariants 1 and 2 keep a removed broker from gaining rights. Certificates live one year; renewal (a request with the same key before expiry) is future work.
viais fixed at admission; to change it, Deauthorize and Authorize again with the new list.- Old configs with
peers.downstream[].cafail to parse (deny_unknown_fields); old registries replay. - Residual (as in ADR 0007): on our own connection to an upstream site, that site’s CA is trusted for the server certificate, and Zenoh 1.10 matches ACL subjects by the CN on either side. An upstream whose CA signs a server certificate
broker:<one of our downstream sites>would get that downstream’s rules. Accepted: an upstream site is chosen by our administrators.
Alternatives
- Install the downstream in advance and copy its files (the first version of this ADR): rejected by the owner, not how DSA works.
- Each site’s own CA, trusted after approval (ADR 0007): the listener must know the CA before the handshake, so quarantine could not see a new broker, and the peer-CA risk stays.
- Enrollment through the user gateway (HTTP): not every broker runs a gateway; a Zenoh query keeps one protocol (principle 4).
ADR 0016 — Broker-held meta overlays; attr.history
Status: accepted · 2026-10-23 (owner decisions, backlog item 10: overlays, an array of keys, existing watches included).
Context
The owner asked that a recorded point carry the path of the store that records it (@history), and that the explorer mark such a node with an icon that opens its history. A point’s ~meta belongs to its link; the historian lives in the broker.
A DSA broker does this with attributes it holds itself: setAttribute on a node of a link is stored by the broker (override attributes, persisted per path) and merged into that node’s attributes in every answer; the historian sets @@getHistory = {"@": "merge", "val": [<path of its Get History action>]} on each watched node, the UI marks the node (hasHistory), and the broker aliases <node>/getHistory to the store’s action.
WYRM requests reach a link’s queryable directly; the broker does not proxy them, so it cannot merge on the way.
Decision
- Overlays are broker state, merged by the link’s SDK. The admin publishes one CBOR map per link at
wy/<site>/sys/overlays/<link>/~val:{<node path>: {<attr name>: value}}. The key carries a value only (aput, kept by the router’s memory storage; a name that is gone is deleted): there is nosys/overlaysnode, so the tree people browse shows no service maps (amended 2026-10-31). The SDK reads it (get, then subscribe) and keeps it as a separate layer: a re-declared node keeps its overlay (principle 3: links re-declare their tree). On output it merges the layer into~meta(attr) and into theview=listsummary; a change bumps the node’srev(and its parent’s, whose list changed) and republishes~meta. - Today’s only source is the historian, and the content is derived.
attr.historyof a point is the array of the watch node keys that record it (wy/<site>/sys/history/<group>/<watch>), computed from the registry’s watches; nothing new is persisted, existing watches show up at once, and every broker build publishes the maps again (the memory storage starts empty). A disabled watch stays in the list; Unsubscribe removes it. A link’s ownattr.history(a link that records points itself) is merged with it as a union. - The SDK accepts only known names (
history): a forged sample on the overlay key cannot rewritedisplayor anything else. Only the admin writessys/**inprod; each process or external link may query and subscribe its own overlay key and nothing else undersys. - Spec 02 0.2.1:
view=listsummaries carry key 16has_history(true whenattr.historyis not empty), so a tree or a Metrics row shows the icon without a~metaper row.attr.historyis an array of store keys: a key underwy/<site>/sys/history/is that site’s historian, which answers at the point’s own key (<point>/~val?history=, rights as reading the value, D2); any other store key answers<store>/~val?history=itself. - Explorer: a history icon after the name of a node with
has_history/attr.history, in the tree and in Metrics rows; a click opens the history window (as View History) on that point, with the store’s name; several stores: a picker. - General channel, one source: any attribute the broker holds for a node can use it later (
~set?field=attr.<name>from people, the ADR 0003 TODO); it is not built now.
Consequences
- A point on a downstream site recorded by our historian gets no
attr.history: its link belongs to another broker. Revisit with backlog item 1 (actions on downstream brokers). - One map per link: 10 000 watches on one link make a map of about 1 MB, sent again on each watch change (rare).
- Clients that cache
~metabyrevsee the change: the overlay bumpsrev.
Alternatives
- A history index next to the tree (
<point>/~hist): not in the meta, a new suffix in spec 01. - Links set it themselves: cannot cover the broker’s historian.
- The explorer asks the historian per row: a query per row, and every other client would need the same code.
ADR 0017 — Broker storage: wy/<site>/storage
Status: accepted · 2026-10-24 (owner decisions, backlog item 5: the section is storage; it works as a DSA broker’s /data).
Context
The owner asked for a store in the broker where people create nodes of any structure and set their values, for preprocessing. A DSA broker has it at /data: the root offers Add Node, Add Value {Name, Type, Editor}, Publish {Path, Value, Timestamp} (creates the path and sets the value), Export and Import (JSON); every data node offers the same Add actions plus Delete Node {Recursive}, Rename Node, Duplicate Node, Export and Import; values are writable (write), every action needs write, and the broker keeps the tree and the values across restarts.
Decision
- A site section of its own:
wy/<site>/storage/**(spec 01 0.2.2), served by a responder insidewyrmd(cratewyrm-storage, a link with rootwy/<site>/storage, link idstorage). It is broker data, not control-plane state: like the historian (ADR 0014) it is a second documented exception to principle 3, in its own file. - Nodes as in DSA, names are key segments (no display names, backlog item 2):
- root:
add_node {name},add_value {name, type, editor},publish {path, value},export,import {data | file}; - a folder:
add_node,add_value,delete {recursive},rename {name},duplicate {name},export,import {data | file}; - a value:
~set(writablewrite),delete,rename {name},duplicate {name}. A value has no children (a WYRM leaf), unlike a DSA node. type:string,number,bool,array,map,binary,dynamic(spec 02 type codes); a set of another type is refused,dynamictakes any.editor(none,textarea,date) is kept asattr.editorfor UIs. Nopasswordeditor: anyone withreadreads a storage value, and secrets never go in the tree (principle 6).deleteof a folder with children needsrecursive(as DSA).renameandduplicaterefuse a name a sibling has.publishcreates the missing folders and adynamicvalue at the end ofpath(relative tostorage), then sets the value; a path through a value, or to a folder, is refused. No timestamp and no open stream (DSA’sCloseStream).exportanswers the subtree as JSON text ({"<child>": {"$type": "number", "@editor": "textarea", "?value": 21.5}, "<folder>": {...}}, as DSA); binary values are{"$hex": "…"}.importreplaces a folder’s children with such a JSON, given as text (data) or as a file (file,editor: file, so the gateway takes it overPOST /api/invokewhen it is larger than a WebSocket frame, ADR 0011); other$/@keys (a DSA export’s$is,$name) are ignored. The whole import is checked (names, types, values, limits) before anything changes.typeandeditortravel as text, as every action’s choices.
- root:
- Rights as in DSA: every action and every
~setneedswriteon the node. Trusted keys: the admin keys; the user gateway’s (users’ grants decide; default roles: viewerread, operatorwrite, engineerconfig); the flow engine’s atwrite(a flow’sset/invokesinks may targetwy/<site>/storage/**, ADR 0008 amended); an upstream site reads it (~meta,~val) like the other sections. Roles already changed in a users store keep their grants; an admin addsstoragegrants to them. - Persistence:
data_dir/storage/storage.redb, one record per node (path → {type, editor, value, t}); structure changes are written at once, values at most once a second (a crash loses at most the last second of values, as DSA’s debounce).wyrmdopens the file once (redb allows one open per file) and hands it to every start of the link; it is flushed when the link stops and when the store is dropped. On start the tree is declared again and the last values are published with their times. - Limits: 10 000 nodes, 16 levels, 32 KiB per value (CBOR; half the gateway’s 64 KiB WebSocket frame), 64 MiB for all records together (CBOR), 4 MiB per import and per export.
add_*,duplicate,publishandimportcount toward the node and size limits; an export stops as soon as its text passes the limit. - Reserved id: a new link may not be called
storage. A registry that holds a link of that name (installed before spec 0.2.2) still loads, butwyrmdrefuses to start: the link would share the storage’s audit records, overlays and logs. Remove it with the previouswyrmdfirst. - History: the historian can watch storage values (
wy/<site>/storage/…), and they getattr.history(ADR 0016).
Consequences
- Anyone with
writeonstoragecan grow it up to the limits; the SDK’s rate limits apply to~setand actions (50 per second per caller, burst 100). A flow is one caller: all itssetandinvokesinks intostorageshare that budget, and requests above it are refused (rate_limited) and counted in the next audit record. - Every
~setand action is audited (one record in the HMAC-chained audit journal, arguments as SHA-256), as on every link. A flow that writes a storage value 20 times a second adds 20 records a second, as one that writes a device does; the audit journal is not trimmed today. That growth is the audit’s, not the storage’s: the storage file holds one record per node. - Values written faster than once a second keep only the last one per second on disk; every value is still published at once.
- Attributes set by people (
~set?field=attr.) are not supported yet (as for links, ADR 0003 TODO);editorcomes fromadd_valueandimport.
Alternatives
- Registry WAL for values: every set would append a record that is never deleted.
- A link package: the store belongs to the broker (backup, rights, the flow engine’s targets), not to a replaceable connector.
ADR 0018 — Requests from upstream sites
Status: accepted · 2026-10-24 (owner decision, backlog item 1: a downstream accepts write from above on downstream/dataflows always; config on sys only when that downstream allows it explicitly). Reverses the “read-only upstream” of ADR 0007. Amended 2026-10-31 (owner decision): allow_config opens config on the whole site, links included, as the group of a DSA upstream connection.
Context
An upstream broker shows its downstream sites in its tree (ADR 0007, 0015), but nobody there can set a value or run an action on them: the downstream’s ACL drops every ~set/~act query from broker:<upstream>, the downstream’s links trust only their own site’s keys, and the upstream’s gateway refuses non-read operations on downstream sites.
A DSA broker lets requests through: the downstream names a permission Group on each upstream connection (sys/upstream/<name>/group), and a request from above is checked twice, by the upstream against its user’s permissions and by the downstream against that group. WYRM keeps both checks with the means it has: the router ACL, ptok signatures and the LimitedKey caps of ADR 0004/0013.
Decision
- What a downstream accepts from each upstream (one flag per upstream entry, as DSA’s group, fixed to the owner’s two levels):
- always
writeonwy/<d>/downstream/**,wy/<d>/dataflows/**andwy/<d>/storage/**(the broker storage of ADR 0017 is device-like data; DSA’s group covers/datatoo); configonwy/<d>/sys/**, andconfiginstead ofwriteondownstream,dataflowsandstorage(link actions such as Export, Edit, Stop, Restart; amended 2026-10-31), only withallow_configon that upstream:wyrmd.json5peers.upstream[].allow_config, orsys/upstream/<u>/allow_config(writable atconfig) for one added at runtime. A change rebuilds the broker (the ACL changes).
- always
- Router ACL on the downstream. For the own site and the sites it relays: ingress
queryand egressreplyon…/{downstream,dataflows,storage}/**/~setand…/**/~act/*for every upstream (upstream-write-in/-out); the same on…/sys/**only for an upstream withallow_config(upstream-<u>-config-in/-out, subjectupstream-<u>), with adenyon…/sys/links/*/~act/hello(it checks a link token, not aptok, and answers with the link’s secrets: only the link’s own session asks it;denywins in a Zenoh policy, and no other policy of a peer session allows it). A relayed site’ssysneedsallow_configat every hop (edge for central, plant for edge), as DSA checks the group at each broker. - Keys: the upstream publishes them, the downstream follows them. A token for a key of site
dcarriessite = dand is signed at the upstream (its gateway, or an operator’s admin key). The upstream’s admin answerswy/<u>/sys/signing_keys={write: {<site>: [key…]}, config: {…}}from a queryable on that one key (the router’s~valstorage and the admin’ssys/**queryable do not cross brokers): forwrite, its own admin keys and gateway key and every key it learned from its own upstreams (so plant, below edge, trusts central’s keys too); forconfig, its own keys and theconfigkeys of the upstreams it allowsconfig, so a key reachesconfigbelow only if every hop on the way allows it. Never a flow key: flows do not reach other sites (owner decision 8).- The downstream’s admin asks each upstream for it every 10 s over the peer link (ACL:
signers-<u>-out/-inhere,signers-<d>-in/-outthere, exactly that key, the queryable’s declaration included). It is checked (at most 16 sites, 8 keys each, 32-byte keys) and stored in the registry (Registry::signers,config_signers, SCHEMA 18). Only a real change rebuilds the broker, so a reconnect does not loop; the first connection to an upstream rebuilds once. Keys of an upstream that is gone are not trusted. - Every key is trusted as a
LimitedKey, never as an admin key:writekeys by links underwy/<d>/downstream, the flow engine underwy/<d>/dataflows, the storage underwy/<d>/storage;configkeys atconfigby all four (the admin underwy/<d>/sys, links, flow engine and storage under their sections), only from an upstream withallow_config. Process links get them inhelloafter the rebuild. The token’s own grants andmaxstill apply: the effective right is the smaller of the user’s grant at the upstream and the downstream’s cap.
- The downstream’s admin asks each upstream for it every 10 s over the peer link (ACL:
- Gateway on the upstream.
setandinvokeon a downstream site are allowed (WebSocket andPOST /api/invoke). The user’s grants are checked as for the own site (wy/<d>/xaswy/<u>/x, as reads already were), and the token is minted for sitedwith the own-site grants rewritten towy/<d>/…(wy/**grants stay) and the subjectuser:<name>@<u>, so the downstream’s audit names where the user came from. Grants are therefore a policy for every site below: an operator on the upstream writes every downstream site’s devices, as far as each downstream allows. - Clocks. Tokens live 5 minutes (
PTOK_TTL) and are checked against the downstream’s clock: sites must keep their clocks within a few minutes (NTP).
Consequences
- A downstream that trusts an upstream for
writetrusts every site above it (the keys come through its upstream); refusing that means not connecting to that upstream. - Requests from above are audited on the downstream like local ones (
sys/audit/<link>, subjectuser:<name>@<site>) and share the per-caller rate limits. - An operator at the upstream with an admin key reaches a downstream with a token for that site (
SigningTokens::new(key, "<d>"));wyrkeeps the own site by default. - Rotating a key at the upstream reaches the downstream within about 10 s, with one rebuild.
- A
sysaction from an upstream withoutallow_configis dropped by the ACL: the caller waits for its timeout instead of gettingpermission_denied. - A
configaction on a link from an upstream withoutallow_configreaches the link (the ACL lets every~actondownstreamthrough) and getspermission_denied, without detail (spec 04).
Alternatives
- Keys in the enrollment answer (ADR 0015):
wyrmd.json5upstreams never enroll, and a rotated key would need a new enrollment. - Keys typed into
sys/upstream: manual, and a chain would need central’s keys typed at plant. - The downstream re-signs requests from its upstream: Zenoh routes queries end to end; the downstream sees no hop where it could.
ADR 0019 — Dataflow editor in the explorer
Status: accepted · 2026-10-24 (owner decisions: a separate large window; changes go live with a Deploy button; WYRM node types drawn as DSA blocks).
Context
Flows (spec 06) could only be deployed as JSON (wyr flow deploy, dataflows/~act/deploy). The owner asked for editing in the explorer, as a DSA client edits a dataflow: blocks on a canvas, wires between their pins, a palette, properties. The DSA editor (remote_dataflow.html) is studied in the DSA repository’s docs/dataflow/editor.md and its prototype tool/dataflow_editor/index.html; it binds inputs to outputs and saves each edit at once.
Decision
- Window:
Edit Dataflowon a flow node (dataflows/<id>) andNew Dataflowondataflowsopen one large window over the explorer, as View History does: the palette on the left, the canvas in the middle, the properties of the selected block (or of the flow) on the right, the state, the check result and Deploy on top. - Model stays spec 06: nodes with a type and a config, edges
["<node>.<port>", "<node>.<port>"]. The DSA look is kept (a block is a header and one row per port, inputs with a pin on the left, outputs on the right; S-curve wires; drag from an output pin to an input pin links them, a double click on an input pin unlinks it; an input takes one link, a new one replaces it, as DSA binds an input to one source), the DSA model (bindings on inputs, saving each edit) is not. - Positions:
~def.layout={<node>: [x, y]}(spec 06 0.2.5), outside every node’s config, so moving a block keeps its state on a hot swap. - Palette and forms from the engine:
dataflows/~act/node_types(levelread) answers the catalog (wyrm_flow::catalog): type, category, description, ports (fixed, or named by a parameter:expressionin.<name>,wasmports), parameters with type, choices, default and editor hint. A test checks every type’s sample configuration againstnodes::ports, so the catalog cannot drift from the compiler. - Load, check, deploy: the current definition is the last item of
dataflows/<id>/~act/history(levelread); every edit is checked withdataflows/~act/validate(debounced) and the error shown; Deploy sends the whole definition withversion+ 1 throughdataflows/~act/deploy(the gateway adds the deployer’s proofs forset/invoketargets, ADR 0008). A flow with asetorinvokenode getspermissions.maxperm: writewhen it has none. Fields the editor does not know (policy, …) are kept.
Consequences
- Deploying needs
configondataflows(as before);validate,historyandnode_typesneedread, so a viewer can open a flow and see it, not change it. - Each Deploy is a version with history and rollback; there is no undo in the window.
- Live values on pins are not shown yet (a later slice).
Alternatives
- Saving each edit (DSA): every move or link would deploy a version and restart the flow; a half-made flow does not compile.
- Positions in each node’s config:
only()refuses unknown keys, and a moved node would get a new hash and lose its state.
ADR 0020 — History of a downstream site’s point, as seen through this site
Status: accepted · 2026-10-28 (owner decision: support it as DSA does).
Context
A site’s historian may watch a point of a downstream site (central records wy/edge/downstream/lab/bench/rig1/wave). ADR 0016 left such points without attr.history (their link belongs to another broker), and the historian answers ~val?history= only on its own site’s keys, so the rows were recorded but could not be read, and the explorer had nothing to show.
A DSA broker keeps override attributes on the node as the broker sees it (RemoteNode.overrideAttributes, persisted per path by that broker, not forwarded below), so @@getHistory set through central shows to central’s clients only. A Get History on the point is an alias: the broker runs the store’s action named in @@getHistory, after checking the caller’s permission on the point and on the store (broker-dart/lib/src/broker/responder.dart, invoke).
Decision
- The overlay lives in the site that records. The admin publishes the points of other sites its historian records at
wy/<site>/sys/overlays/.sites/~val:{<point key>: {"history": [<watch keys>]}}..sitescannot be a link id (they may not start with.). - The gateway lays it on, as the DSA broker does for its remote nodes: on
meta,childrenandlistof a key of another site, it mergesattr.history(union) andhas_history(spec 02 key 16). A change of the map sendschangedfor each affected child of an openlist, so the mark shows without selecting the node again. - The store is read at the watch key. The historian answers
wy/<site>/sys/history/<group>/<watch>/~val?history=for every watch (the rows of its point). Points of the own site keep answering at the point key too (ADR 0016, D2). Spec 02 0.2.7: asys/historystore of another site’s point is read at its own key. - Rights are the DSA double check, in the gateway: a
historyread at a watch key in this map needs Read on the point’s~val(as reading it at the point); any other key undersyskeeps its own check. Nothing reaches the downstream site: the rows are this site’s.
Consequences
- Clients that do not go through a gateway (
wyr, FFI, MCP) do not see foreign overlays; they can readsys/overlays/.sites(admin) and the watch key. - A point recorded both here and on its own site shows both stores; the explorer offers the choice (ADR 0016).
- No queryable of this site lives in another site’s keys: a read of that point’s value never waits on this broker.
Alternatives
- Answer at the point’s key on the downstream site’s keys (
wy/edge/…/~val): every value read of that point would also route to this broker and wait for it; two historians could answer one query. - Forbid watches on other sites’ points: simpler, but not as DSA, and the owner chose support.
ADR 0021 — Link packaging from Cargo, one package format, per-host assets in the repository
Status: accepted · 2026-10-28 (owner decisions: packaging and the repository standard first; the CLI and the SDK share the format; per-host assets).
Context
A link package (ADR 0011) is a zip with wyrm-link.json. The format was parsed only in wyrm-admin (packages.rs); packages were written by hand or by the Python in examples/packages/build.sh, which also wrote the repository index. A link kept in its own repository had no tool to build its package, and an index entry had one url, so one repository could not serve a macOS and a Linux build of the same link (names are unique in the index).
DSA described a link with dslink.json next to its code and listed links in a repository index for “Install Link”.
Decision
- One format, in the SDK.
wyrm-link-sdkfeaturepackage: the manifest (Manifest,wyrm-link.json), the repository index (RepoEntry,parse_index), the host key (platform()), a reproducible zip writer (pack: sorted files, fixed time) andsha256_hex. The broker checks installs with it;wyrbuilds packages with it. Link crates do not pay for it: the feature is off by default. - The manifest comes from Cargo.
[package.metadata.wyrm-link]in the link’sCargo.tomlholds what Cargo does not:kind(process, default),name(default: the crate name),bin(default: the crate’s only binary),args,requester. Version and description are Cargo’s.wyrm-link.jsonis generated, never written by hand. wyr link packbuilds the release binary (for each--target, default the host) and writes one zip per host,<name>-<version>-<host>.zip, whose manifest names that host’s entry.--component <file.wasm> --name --versionpacks a WASM component (no Cargo).wyr repo add <zip>… --repo <dir> [--url <base>]copies each zip to<repo>/<name>/<version>/and updates<repo>/index.json: a new version replaces the entry; the same version adds the zip’s host to it.- Index entry:
{name, version, description, assets: {<host>: {url, sha256}}}for process packages;{…, url, sha256}for a package that runs on any host (WASM). A broker installs the asset of its own host and lists only packages it can install. Aurlwithout a scheme is relative to the index URL, so a repository directory can move or be mirrored as it is.
Consequences
- An index written for ADR 0011 (
url+sha256) still loads. - One zip per host keeps downloads small; a zip with several hosts’ entries stays valid for Url and Zip installs.
examples/packages/build.shrunswyr link packandwyr repo add.
Alternatives
- One zip with every host’s binary: no index change, but each broker downloads every binary.
- A separate packaging CLI next to the SDK: a second place for the format, and one more tool to install.
ADR 0022 — Scheduler link: broker-side schedules that drive equipment
Status: accepted · 2026-10-29, built (proposed 2026-10-28; owner decisions in that conversation: the link writes to equipment itself, retries until confirmed, respects a manual change until the next transition; confirmation may come from another data path). Built as a portable App (ADR 0023): crates/wyrm-schedule, links/scheduler; user guide docs/scheduler.md. The text below states the behaviour as built: where the build differs from the proposal, the plan’s rulings (numbered, from the plan docs/superpowers/plans/2026-10-29-scheduler-link.md) say why.
Context
The owner needs a scheduler that controls equipment from the broker when the site has no connection upstream: people (explorer) and AI (the agent link, through actions) create schedules; the broker turns devices on and off by them, offline, for months. Dataflows may edit schedules later; that needs other changes and is not part of this work.
The reference is DSA dslink-dart-localschedule (2.0.4, analysed 2026-10-28). Kept: a schedule with a default value and events; event priority 1 (highest) … 9, 0 = none; special days that block other events; Add/Edit/Remove/Import/Export; current, next value and time. Not kept, because they are its defects:
- windows across midnight, the hour or the week wrap break after the first occurrence; day 29–31 and Feb 29 roll over into the next month;
- edits through writable child nodes are not saved; a restart loses them;
nextshows the next event start, not the next transition (a return to default is missed);- timers do not follow wall-clock steps; DST shifts window ends; time zone = host zone, stored times have no offset;
- a 1 Hz countdown node per schedule (N updates per second at idle);
- restart and import are O(n² log n); the whole state file is rewritten on every edit;
- it never writes to equipment (consumers bind its value).
Goals
- Correct state at any instant, from the definition alone: after a restart, a power cut or a clock step the link computes “now” and acts; it does not replay missed transitions.
- Writes to equipment, confirmed, with retries, visible state per target, audit.
- A manual change after a confirmed write wins until the next transition.
- An action API people and AI can use safely: validated parameters, stable ids, errors that say what is wrong, a preview of what will happen (
get_events). - Zero messages between transitions at idle; one timer for all schedules.
- One evaluation core for every way the link runs.
Non-goals
- iCal/Outlook/Google import or remote calendars (not how schedules arrive).
- Dataflows editing schedules (later, separate change).
- Targets on other sites or under
sys/**(no upstream needed offline; same rule as flowset, owner decision 8).
Anti-goals (a failure even if it works)
- A missed or wrong transition after a restart, a clock step or a DST change.
- An edit accepted but not on disk.
- Fighting a person who changed a device by hand.
- Load at idle that grows with the number of schedules.
Decision
Model (crate wyrm-schedule, no I/O, no async)
- Schedule:
id(key segment),display,tz(IANA name, stored explicitly; without one,add_scheduletakes the link paramdefault_tz),default(Value),events,targets,enabled. - Default zone (ruling 3): a WASM app cannot read the host’s zone, so the zone of a schedule added without
tz(and of a DSA import) is the app paramdefault_tz(IANA name, defaultUTC). The embedded scheduler gets the system zone fromwyrmd(jiff::tz::TimeZone::system().iana_name(), elseUTC); packages use their params. Zones come from the tz database bundled inwyrm-schedule(jiff,tzdb-bundle-always); a native build may read the host’s newer database first. - Event:
id(stable, generatede<n>, never reused in a schedule),display,value,priority(0–9, integer, validated),special(bool),startandendas local wall-clock date-times in the schedule’s zone (the first occurrence’s window), andrecurrence. - Recurrence: an RRULE subset —
FREQ(HOURLY|DAILY|WEEKLY|MONTHLY|YEARLY),INTERVAL(1 … 1 000),COUNT(≤ 10 000) orUNTIL(a local time; not both),BYDAY(weekdays; with MONTHLY and YEARLY an ordinal within the month, e.g.1MO,-1FR),BYMONTHDAY(1…31, −1 = last),BYMONTH.None= one-off. Canonical text order:FREQ, INTERVAL, COUNT|UNTIL, BYMONTH, BYMONTHDAY, BYDAY.BY*parts: with HOURLY and DAILY they filter; WEEKLY expandsBYDAYwithin the week (Monday first); MONTHLY expandsBYMONTHDAYandBYDAY(both given: their intersection); YEARLY expandsBYMONTH(default the start’s month), thenBYMONTHDAY/BYDAYwithin each month;BYMONTH(andBYMONTHDAYwith WEEKLY) filter otherwise (ruling R5). At most 100 events per schedule. The caps are constants ofwyrm-schedule, which validates them; the link re-exports them (ruling R1). DSA’sSingle/Hourly/…/Yearlyimport asFREQwithINTERVAL=1. A moment event (DSA “Add Moment Event”) is an event withstart == end: the value is written once at that instant; there is no window and no return to default from it. - Occurrence arithmetic is in local wall time, then mapped to UTC: each occurrence’s start and end are computed as local date-times (day 31 in a month without it is skipped, not rolled over;
BYMONTHDAY=-1gives the last day), then each end of the window is mapped to an instant with the zone’s rules. A local time in the spring-forward gap moves to the first instant after the gap; in the fall-back overlap it takes the first (earlier) instant. Windows keep their wall-clock length (08:00–17:00 stays 08:00–17:00 on a DST day). A window may cross midnight or the period boundary. - Moment events obey the same precedence: a moment fires (writes its value) only if no window of higher precedence is active at that instant; after it,
currentkeeps the moment’s value (source: Moment(id, t)) until the next transition. A moment missed while the link was down is not replayed (goal 1). Ruling 8:state_atis the window state only (DefaultorEvent) and never returns a past moment;next_transitionreturns moments as transitions (Source::Moment); the link holds a moment’s state until the next transition. Ruling R17: that held moment survives a restart: the link keeps it in the store (h/<s>, put in the transition event, deleted when the next transition replaces it) and a loaded schedule is evaluated with it (the moment while it is still the state, else the window state). This is not a replay: a moment missed while the link was down still does not fire. - Precedence at an instant: if any special event has an occurrence that touches that local day, only special events count for the whole local day (midnight to midnight in the schedule’s zone; this is the DSA promise, which DSA did not keep). Among active events: higher priority wins (1 > 2 > … > 9 > 0); on equal priority, the later-starting occurrence wins; on equal start, the lower event id wins. No active event →
default. The result is defined for any number of overlaps. - Core API:
state_at(def, t) -> State { value, source: Default | Event(id, occurrence_start) | Moment(id, at) }next_transition(def, t) -> Option<(Instant, State)>— the first instant aftertwherestate_atchanges (an event start, an event end, a day boundary under a special day, a moment).occurrences(def, from, to, limit) -> Vec<Occurrence>for the timeline: every event’s occurrences that touch the range, precedence not applied; a moment exactly atfromis included (ruling R6).- Bounded work: scanning stops at the horizon of
next_transition(366 days ahead, then “none”).COUNTis resolved once, when a schedule is compiled, and walks at most 400 years. Ruling R18: for an enabled schedule with “none”, the link wakes again 365 days on and evaluates it, so a transition further ahead still fires. - Values (the default, event values, a target’s
map/feedback_map) hold finite numbers only: NaN and ±infinity are refused, also inside arrays and maps. ABYDAYordinal is 1…5 (or −1…−5) with MONTHLY and YEARLY: it counts within a month. - Instants are
i64microseconds since the Unix epoch, UTC. The crate reads no clock and no OS zone and builds forwasm32-unknown-unknown.
The link (links/scheduler: an App on the portable API, ADR 0023)
- One timer for all schedules: a min-heap of each schedule’s next transition, and of the targets’ retries and confirm timeouts (no timer per target); one
Host::set_timerfor the earliest; onon_timer, computestate_at(now)for due schedules, write their targets, arm the next. - Wall-clock steps: the one timer fires at least every 30 s and compares
now_us(wall clock) with the elapsed monotonic time (set_timeris monotonic, ADR 0023); a step of more than 2 s (either way) re-evaluates every schedule at “now” and rebuilds the heap (retries and confirm timeouts are put back). This also covers a host resumed from sleep. Every event (also an action, a value, a reply) checks the clock before it arms the timer, so a backward step seen there is not lost. - Host bounds (ruling 5): the host allows 1 000 commands per event and fails the event (and restarts the instance) over that. Every event of the app spends at most 800 commands and at most 500 ms of wall time on batched work (ruling R7):
startdeclares the root and loads the definitions, then declares and evaluates schedules in batches; a timer burst handles due wakes in batches; leftover work goes on in0ms timer events. A continuation more than 30 s late counts as a clock step: the link goes tostate_at(now)and does not replay the lag (ruling R11). Writes beyond 50 in flight wait in a FIFO queue drained byon_reply. While schedules are still loading,importand the target actions answerbusy. - Node budget (ruling 1, R8): the host bounds a link at 10 000 nodes; the app counts its nodes and refuses an add over 9 500 with
resource_exhausted, so the host never fails the event. A schedule takes 6 nodes (the folder,current,default,enabled,events,targets), plus one per event and one per target: 1 000 schedules × 2 events × 1 target = 9 000. - What a transition is: a change of
state_at(value or source occurrence), an edit or import that changes the current state,enabledturned on, or a change of a target. A re-evaluation after a clock step that finds the same state is not a transition. - Restart: load, evaluate every schedule at “now” (with its held moment, R17). A target whose stored record says it was confirmed or overridden for this same state (value and source occurrence) and whose
valid_untilis still ahead is left alone; the others are written: anacktarget at once, aread_back/feedbacktarget after it waits 2 s for a first sample of its confirm key (a sample that already shows the value confirms without a write). So a manual change survives a restart inside the same window. Ruling R19: a record carriesvalid_until, the instant of the next transition after its state (the R18 re-check when there is none); a record at or past it is stale, so an outage across a whole window does not keep an override of the state before it. An edit, a clock step or the re-check that moves the next transition puts the records again. A record without the field (an older store) is stale. - Bad samples: a sample that is not
goodconfirms nothing and clears the key’s last value, so anokreply cannot confirm on a value from before it. - Persistence: the host store (ADR 0023):
index(the schedule ids: the store has no key listing),s/<schedule>(the definition with its targets),o/<schedule>/<target>(the last outcome(state it was for, confirmed | override, valid_until), kept only for those two) andh/<schedule>(the held moment, R17), written bystore_putin the event that accepts the edit, so it is durable before the action replies. Keys at most1 + 2 × schedules + targets: 8 031 within the node budget, below the host’s 10 000. A store that refuses a write fails the action withresource_exhausted; nothing is half-saved or declared, and the instance goes on. Embedded store 64 MiB (scheduler.store_mb), packages 16 MiB (capabilities).
Targets: writes, confirmation, override
- A target is
{ point: <key under wy/<site>/downstream/>, confirm: read_back | feedback | ack, feedback?: <key>, map?: {<schedule value>: <value to write>}, feedback_map?: {<schedule value>: <value the feedback key shows>}, tolerance? }. At most 20 targets per schedule. Map keys are the schedule value as text (true,false, a number in its shortest decimal, text as it is). Through an actionconfirmis the enum index (0, 1, 2), in an import the text. - On each transition (and at start), for each enabled target:
~setthe value (mapped ifmap). Confirmation:read_back: the next~valof the same point equals it (numbers withintolerance, default 1e-6 relative);feedback: a~valof another key equals the expected value (feedback_mapmay name it, else the written value) — for devices whose write register is not the one read back (Modbus coil written, status register read);ack: anokreply to the~setis enough (no feedback path). A matching sample counts while the write waits for its reply or after anok; none 10 s after theokfails the write. Links publish a value only when it changes, so a key whose last sample already shows the value confirms on theok. A target holds a subscription on its confirm key while it is enabled, notoverrideand notack; targets that confirm on the same key share one; at most 1 000 subscriptions (an add over that, or one the host refuses, fails withresource_exhaustedor the host’s error).
- Retry until confirmed: exponential backoff 1 s → 60 s cap, jitter ±20 % from an FNV-1a 64 hash of
now_usand the target id, notrand(ruling 4); never gives up within a transition; a newer transition cancels it. Each transition gives the target a new generation: replies and wakes of an older one are ignored, and a target has one write in flight at most. - Override: after a target is confirmed, a
~valon its confirm point that differs from the expected value marks itoverride(the person wins); the link does not write it again until the next transition. Inackmode there is no feedback, so no override is detected. - Per-target state in the tree: the target node’s value is its state,
pending | writing | confirmed | retrying | override | disabled;last_error,last_write(time),attemptsare attributes. - Audit (ruling 2): the
HostAPI has no audit call and thewyrm:app@0.1.0WIT stays frozen. Every write is a~set, audited by the target link’s responder (sys/audit/<target link>, subjectlink:<scheduler id>) as any~set. Confirmations and overrides go to the link log atinfo(ids and states only, never values) and to the target node. - Who may point a schedule at a device (ruling 6; an owner decision, the plan’s default): the proposal had
add_targetcheck the caller’s ownwriteon the target point from the request’sptok. That is not possible: every token carries one grant, narrowed to the request key (wyrm_client::SigningTokens::scoped, also used by the gateway), so a request to…/scheduler/s1/~act/add_targetsays nothing about the caller’s rights on…/plc/fan. Targets are configuration:add_target, a target’sedit/enable/disable/remove, andimport(it carries targets) areconfigactions, and the responder enforces the level before the app runs. Schedules and events stay atwrite. Who hasconfigon the scheduler may point it at any device the scheduler can reach (embedded: all ofwy/<site>/downstream; packages: their grants). The gateway’soperatorrole haswriteand cannot add targets;engineerandadmincan (ruling R12). The agent link (capped atwrite) and upstream sites (ADR 0018, atwrite) can edit events but cannot add targets. The app does not readWhogrants;created_by=who.subject. As with flows (decided 2026-10-21), a schedule keeps writing after its author loses rights. Amended 2026-10-31 (ADR 0029, decision 10): spec 04 0.2.10 added that claim (auth); a target now also keeps its author’s rights and writes only within them (checked when it is defined and before each write). - Site check (ruling 7): the app does not know its site; the host refuses a key outside the link’s site (or grants) at
subscribe/set.add_target(and an import with targets) subscribes the point and the feedback key inside the action: an error refuses the target with that error, and nothing stays subscribed. The app itself checks the key’s shape (wy/<site>/downstream/<link>/<path>, no*,~or empty segment). - One writer per point: a point may be the target of one schedule only;
add_targetrefuses a point another target of this link already writes (two schedules would see each other’s writes as overrides). A flow that also writes the point is not detected, nor a feedback key that is another target’s point; the guide says not to. - Rights of the writes: the embedded link signs its writes with its own key, created as a link secret by the admin (as the agent’s); links trust it as a
LimitedKeyatwrite, scoped towy/<site>/downstream, bound to the subjectlink:scheduler; the key is not insys/signing_keys. Package grants (ruling 10): a package carries norequestergrants (a package cannot ask for a root); an operator grantswriteon each target link withsys/links/<id>/~act/grant(ADR 0013). A grant that changes restarts a running process link, because grants and the requester key reach a process only in its firsthello(ruling R13); WASM links get it with the router rebuild. Without a grant,add_targetfails withpermission_deniedand no message: the SDK strips the detail of that status (ruling R14). Ruling R21: the embedded scheduler does not trust its own key (its ownLinkConfigleaves it out), so a schedule cannot write the scheduler’s own nodes in a loop. The app does not know its own link id or root, soadd_targetcannot refuse such a point; its writes fail withpermission_deniedand retry (the guide says not to). A package scheduler still trusts its own requester key under its grants, so a grant that covers its own link (an operator step) would let it write itself.
Tree and actions (all actions at write except where noted; ids are key segments)
Ruling 1 and R8: the proposal’s tree took 9+ nodes per schedule, so 1 000 schedules (this ADR’s benchmark) did not fit the host’s 10 000 nodes; and a value node cannot have children (spec 02: type only on leaves). So the schedule is a folder with attributes, and its value is the leaf current; an event is one node with its fields as attributes; a target is one node whose value is its state.
<link>/
add_schedule {id, display?, tz?, default, enabled?}
import {json, id?, overwrite?} (config) -> {id} # DSA localschedule JSON or this link's own export (ruling R9)
<schedule>/ folder; attrs display, tz, source (default | <event id>),
next_time (RFC 3339 instant | null), next_value
current the value now (read-only)
default writable value; saved
enabled writable bool; saved
add_event {display?, value, start, end, recurrence?, priority?, special?} -> {id}
add_target {point, confirm, feedback?, map?, feedback_map?, tolerance?} (config) -> {id}
get_events {timerange, limit?} (read) -> rows {start, end, event, value, priority, special}
export (read) -> {json}; edit {display?, tz?, default?}; remove
events/<e> folder; attrs display, value, start, end, recurrence, priority, special;
edit {…}, remove
targets/<t> the state; attrs point, confirm, feedback, last_error, last_write,
attempts, created_by; edit {…}, enable, disable, remove (config)
removeof a schedule is atwriteand is refused while the schedule has targets (invalid_parameter, “remove its targets first”; ruling R20): targets are configuration (ruling 6), and awritecaller must not drop them.importwithoverwriteis atconfigalready.- Writable values are only
defaultandenabled, and they are saved.enabledturned on is always a transition: the targets are written even with the same state (ruling R10). Event fields change only throughedit(one validated, saved step; DSA’s unsaved writable fields are not repeated). import {json, id?, overwrite?}: withoutidthe export’s id is used, for a DSA export itsnamewhen that is a valid id, else it is refused (ruling R9). A schedule with that id is refused unlessoverwritereplaces it as a whole. The targets of an own export are checked as byadd_target;created_bybecomes the importer.- Every action validates fully before saving: ids, zone name, RRULE, priority range,
end >= start, window not longer than its period, targets underwy/<site>/downstream/. Errors name the field and the rule. get_eventsuseseditor: daterange(spec 02 0.2.4).
Run modes (one core, three hosts)
One source, three hosts (ADR 0023):
- Embedded in
wyrmd— the default: one fixed instance atwy/<site>/downstream/scheduler, started with the router like the storage link, grants and key fromwyrmd(ADR 0023, embedded built-in apps); not an operator-created driver instance. Ruling 9:schedulerjoins the reserved ids of new links, andDaemon::openrefuses a stored link with it, as withstorage; it is not insys/links(not a registry link) but is in the broker’s overlays (publish_overlays), so history marks show on its nodes.wyrmd.json5scheduler: { enabled: true, store_mb: 64 }(both optional) turns it off or sizes its store;peers.downstreamcannot name a sitescheduler. Ruling R22: when the admin cannot save the scheduler’s keys (ensure_builtin_keys), it logs that aterrorand the broker runs without the scheduler; the broker start does not fail. The next router build tries again. - Process package
scheduler-process—process::main::<Portable<Scheduler>>()(--features process), packed bywyr link pack --kind process --name scheduler-process(ADR 0021);wyrmd link schedulerruns the same app as a process link. Norequestergrants: an operator grants each target link (ruling 10). - WASM package
scheduler— the sameAppbuilt with--features wasmon worldwyrm:app/app, store 16 MiB (capabilities); targets work as in the other modes (requests within its grants). Thewyrm-schedulecrate builds forwasm32-unknown-unknown(no std time; tz data compiled in).examples/packages/build.shpacks both packages.
Benchmarks and tests (in the crate and on the demo)
- Correctness fixtures: windows across midnight, the hour, the week wrap; day 31 and Feb 29;
BYDAYordinals; three or more overlaps; special days; DST spring-forward and fall-back inEurope/KyivandAmerica/New_York(window boundaries, the missing and the repeated hour); clock step forward and backward.next_transitionagrees withstate_atsampled every 5 minutes. cargo bench -p wyrm-schedule --bench eval(Apple M4 Max, release), per call:state_atp50 0.21 µs (E = 1), 5.5 µs (E = 10), 53.7 µs (E = 100);next_transitionp50 0.62–0.67 µs, 11.6 µs, 113 µs, the same for S ∈ {1, 10, 100, 1000}. E = 1000 is not measured: at most 100 events per schedule. Cold start of the evaluator (Compiled::new+state_at), 1 000 schedules × 10 events: p50 8.96 ms.occurrencesover a year, 10 events (7 198 rows): p50 0.83 ms. WorstCOUNTcompile (100 events whose rule never matches): 17–84 ms.cargo bench -p wyrm-link-scheduler --bench cold_start: the link’s cold start onSimHost, 1 000 schedules × 2 events × 1 target (9 000 nodes; the node budget forbids 10 events each at this size, ruling R3), 10 rounds, from the start ofScheduler::start, p50 / max:ack—startevent 1.71 / 1.94 ms, tree complete 26.22 / 29.96 ms, last write sent 40.34 / 45.50 ms, all confirmed 40.85 / 46.03 ms;read_back— 1.67 / 1.76 ms, 25.84 / 26.53 ms, 44.27 / 45.02 ms, 44.92 / 45.74 ms, plus on a real host the 2 000 ms first-sample wait before the writes.- WASM package (e2e
scheduler_three_modes), 200 schedules × 10 events × 1 target:startanswered in 0.29 s, all 200 back in the tree in 1.7 s. - On the demo (
examples/demo/scheduler-load.sh; Apple M4 Max, demo edge site, embedded scheduler, release build, 2026-10-29; ruling R4: measured by the controller):- idle samples in 60 s with 1 000 schedules: 0 (target 0 between transitions; 3 000 stored values at subscribe); the 1 000 schedules were made in 47.1 s and removed in 42.8 s (50 requests per second per caller);
- transition latency of 100 moments,
current: p50 16.0 ms, p99 23.7 ms, max 26.7 ms (target < 50 ms embedded); at the written mock point (acktarget): p50 16.9 ms, p99 24.8 ms, max 27.6 ms; - a target on the Modbus simulator (
plc1/line1/ahu1/fan) withfeedbackonfan_status:confirmedafter 390 ms,override973 ms after a manual write offalse, writtentrueagain andconfirmedat the next transition.
Left to the builder (as built)
- Crate layout:
crates/wyrm-schedule(model,rrule,occur,eval,convert,dsa) andlinks/scheduler(lib(schedules, events, the wake loop),targets,tree,store,wake,limits: the link’s constants, one place each). The tz library isjiffwith its bundled database. - The own export format is
wyrm-schedule/1:{format, id, display, tz, default, enabled, next_event, events: [{id, display, value, priority, special, start, end, recurrence?}], targets: [{id, point, confirm, feedback?, map?, feedback_map?, tolerance?, enabled, created_by}], next_target}. It round-trips. - DSA import:
name→display(and the id),value→default,timeRange.sDate+sTime→start,eTime−sTime→ the window length,freq0 … 5 → once orFREQwithINTERVAL=1andUNTIL= the date ofeDatewith the time ofsTime; instants withZor an offset are converted todefault_tz.
Consequences
- The link id
scheduleris reserved likestorage. - Spec 02 does not change (only existing editors and value types are used).
- Built-in probe scenario
links/probe/scenarios/scheduler.json; user guidedocs/scheduler.md. - Open items:
- an audit record put while the target link reconnects (a router rebuild) can be lost: records are sent once; a fix needs ack and resend (spec 01/04; owner decision);
rustlsis pinned to=0.23.45:zenoh-link-tls1.10.1 gives its reader and writer oneTlsStream, and 0.23.46 crashes on it (ruling R16); the durable fix is upstream Zenoh or process links on QUIC (owner decision);- a forward clock step under 30 s while a long burst still runs replays the transitions of that span (moments too) instead of skipping them; a step over 30 s is caught;
- targets as configuration (ruling 6), within their author’s rights since ADR 0029 (decision 10).
ADR 0023 — Portable links: one link API for embedded, process and WASM (WASM world v2)
Status: accepted · 2026-10-28 (owner approved the document with the builder-check resolutions; owner decisions in this conversation: WASM is for fault isolation and hot start of links an engineer or integrator installs, not a sandbox for hostile code; a WASM link gets the full link API with capabilities granted at install; one source for all three run modes; this comes before the scheduler, ADR 0022).
Amended 2026-10-30 by ADR 0025: Host::list(key, full) and App::on_list (bound max_lists 2 000), subscribe of <prefix>/**, reads (subscribe, list) of other sites under an explicit grant, Who grants capped at the effective level, and the world wyrm:app@0.2.0 (wit/app2) beside the frozen 0.1.0, which the host still runs.
Amended 2026-11-01 by ADR 0030: the world wyrm:app@0.3.0 (wit/app3) adds the imports tls-connect, tls-upgrade and random-bytes (Host::random_bytes); 0.1.0 and 0.2.0 stay frozen and run beside it.
Context
A WASM link today (ADR 0010, 0012) is a polled point driver: init, read, write, plus outbound TCP to an allowlist. It has no node tree of its own, no actions, no clock, no timers, no storage and cannot write other points. That fits a third-party protocol driver in a sandbox, not the owner’s goal: install a link (a scheduler, a calculation, a gateway to some protocol) so that whatever happens to it, the broker keeps running, and replace it without restarting the broker.
The native SDK (trait Link, LinkCtx) is async and hands drivers a raw Zenoh session; it cannot run in a component as it is.
What already holds and stays: a trap, an out-of-memory, fuel exhaustion or a call over its time kills only that instance; the host instantiates again; Slot::swap replaces a component with no broker restart; no WASI.
Goals
- One link source builds as an embedded link, a process package and a WASM component (cargo features), with the same behaviour.
- A WASM link has what a native link has: its own tree (nodes, values, actions,
set), a clock, timers, a key-value store, subscriptions to other points and requests to them (set,invoke) within grants. - Every capability is granted explicitly at install; nothing else is reachable.
- A misbehaving link never takes the broker down and comes back by itself (with backoff); its last good tree is not left behind half-declared.
- Building a WASM link needs only
cargoandwyr(no externalwasm-tools/cargo component).
Non-goals
- Hostile-code hardening beyond what exists (fuel, memory, time, no WASI, explicit imports). The trust model is “installed by someone with
config”. - Streaming action replies and raw Zenoh access in the portable API (native links that need them keep
trait Link). - Rewriting existing links on the new API (they may move later).
- New network kinds (TLS, UDP, serial, DNS); the
tcpinterface of ADR 0012 is reused as it is.
Decision
The portable API (crate wyrm-link-api; depends on wyrm-core only; builds for wasm32-unknown-unknown)
An actor: the host calls the app one event at a time; the app answers synchronously and acts through a Host handle. No async in the app.
#![allow(unused)]
fn main() {
pub trait App: Sized {
const NAME: &'static str;
const VERSION: &'static str;
fn start(host: &mut dyn Host, config: Value) -> Result<Self, AppError>;
fn on_set(&mut self, host: &mut dyn Host, path: &str, value: Value, who: &Who) -> Result<(), AppError>;
fn on_invoke(&mut self, host: &mut dyn Host, path: &str, action: &str, args: Value, who: &Who) -> Result<Value, AppError>;
fn on_timer(&mut self, host: &mut dyn Host, timer: TimerId) {}
fn on_value(&mut self, host: &mut dyn Host, sub: SubId, key: &str, sample: Sample) {}
fn on_reply(&mut self, host: &mut dyn Host, req: ReqId, result: Result<Value, AppError>) {}
fn stop(&mut self, host: &mut dyn Host) {}
}
pub trait Host {
// tree (the app owns its subtree, principle 3)
fn declare_node(&mut self, path: &str, meta: NodeMeta);
fn declare_action(&mut self, path: &str, name: &str, action: ActionMeta);
fn remove_node(&mut self, path: &str);
fn update(&mut self, path: &str, sample: Sample);
// time
fn now_us(&self) -> u64; // wall clock, UTC µs
fn set_timer(&mut self, after_ms: u64) -> Result<TimerId, AppError>; // one-shot, monotonic
fn cancel_timer(&mut self, t: TimerId);
// storage (the link's own, survives restarts and upgrades)
fn store_get(&self, key: &str) -> Option<Vec<u8>>;
fn store_put(&mut self, key: &str, value: &[u8]) -> Result<(), AppError>; // durable when the event returns
fn store_delete(&mut self, key: &str);
// other points, within grants
fn subscribe(&mut self, key: &str) -> Result<SubId, AppError>;
fn unsubscribe(&mut self, sub: SubId);
fn set(&mut self, key: &str, value: Value) -> Result<ReqId, AppError>; // reply via on_reply
fn invoke(&mut self, key: &str, action: &str, args: Value) -> Result<ReqId, AppError>;
// network, within the link's `net` allowlist (ADR 0012 rules in every host)
fn tcp_connect(&mut self, addr: &str, port: u16, timeout_ms: u32) -> Result<ConnId, AppError>;
fn tcp_send(&mut self, c: ConnId, data: &[u8]) -> Result<(), AppError>;
fn tcp_recv(&mut self, c: ConnId, max: u32, timeout_ms: u32) -> Result<Vec<u8>, AppError>;
fn tcp_close(&mut self, c: ConnId);
fn log(&mut self, level: Level, msg: &str);
}
}
- Effects are applied after the event returns, in order (a command buffer), in every host: the same semantics native and WASM. Reads (
now_us,store_get) are immediate, andstore_getsees the event’s own earlierstore_put/store_delete(read your writes).store_putis durable when the event’s commands are applied and before the reply to aset/invokeleaves. TCP calls are immediate (blocking, bounded by the call’s time), as in ADR 0012. - An event fails as a whole: if the app traps or runs out of fuel, memory or time during an event, its buffered commands are dropped. If applying a command fails (bad meta, a bound reached, the store full or its disk failing), the rest of that event’s commands are dropped, a
set/invokegets that error (resource_exhausted,invalid_parameter,internal_error), and the instance is restarted so its memory and its store cannot disagree. Bounds are checked when a command is buffered too, so the app seesresource_exhaustedfrom theHostcall itself where it can (set_timer,subscribe,set,invoke,store_putreturnResult). - Replies:
on_invokeanswers synchronously; there is no deferred reply in this version (an app that must ask another point first answers with what it has, or the caller polls). Streaming stays out. - Timers are monotonic (
set_timercounts elapsed time, unaffected by clock steps);now_usis the wall clock. An app compares the two to detect a clock step (ADR 0022). - Subscriptions deliver the point’s current value first (as
wyrm-clientsubscribe), then changes. A full event queue coalesceson_valueper subscription (the newest sample wins);set/invokeare never dropped: when the queue is full they getbusy. - Errors carry a WYRM status and a message (
AppError { status, msg });whocarries the verified subject and grants of the caller (for checks such as ADR 0022’s targets). - Requests to other points are refused at once (
permission_denied) when no grant covers them; grants are the link’s (below).
Three hosts
- Native adapter
Portable<A: App>inwyrm-link-sdkimplementstrait Link: one task ownsA; SDK callbacks, tokio timers, subscriptions and replies become events; commands map toLinkCtx; requests are signed with the link’s requester key (ADR 0013) or, for an embedded link the admin keys, with that link’s own key. The store is a sealed file in the link’sdata_dir(one record per key, atomic replace), asdriver::persist.- Embedded: registered in
wyrmdas any driver (Portable<A>). - Process:
process::main::<Portable<A>>()(ADR 0021).
- Embedded: registered in
- WASM host (new world, driver
appinlinks/wasm): the component runs on one OS thread that owns its store; events arrive over a bounded channel; each event is one guest call under the existing limits (fuel, memory, epoch time; default 2 s per call, at most 10 s), and its returned commands are applied by the thread throughLinkCtx. Imports are thehostinterface below and, when granted,tcp(ADR 0012). - Guest crate
wyrm-link-guest: implementsHostover the imports and exports the world for anAppwith one macro,wyrm_link_guest::export!(MyApp).
WIT: package wyrm:app@0.1.0, world app (a new package: wyrm:link@0.1.0 with point, driver and tcp stays byte for byte, so existing components keep loading)
interface host {
declare-node: func(path: string, meta: list<u8>); // CBOR ~meta
declare-action: func(path: string, name: string, action: list<u8>);
remove-node: func(path: string);
update: func(path: string, sample: list<u8>); // CBOR ~val {0:v,1:q,2:t}
now-us: func() -> u64;
cancel-timer: func(id: u64);
store-get: func(key: string) -> option<list<u8>>;
// errors are CBOR {status, msg}, as the exports' (no status lost on the boundary)
set-timer: func(after-ms: u64) -> result<u64, list<u8>>;
store-put: func(key: string, value: list<u8>) -> result<_, list<u8>>;
store-delete: func(key: string);
subscribe: func(key: string) -> result<u64, list<u8>>;
unsubscribe: func(id: u64);
set: func(key: string, value: list<u8>) -> result<u64, list<u8>>;
invoke: func(key: string, action: string, args: list<u8>) -> result<u64, list<u8>>;
tcp-connect: func(addr: string, port: u16, timeout-ms: u32) -> result<u32, list<u8>>;
tcp-send: func(conn: u32, data: list<u8>) -> result<_, list<u8>>;
tcp-recv: func(conn: u32, max: u32, timeout-ms: u32) -> result<list<u8>, list<u8>>;
tcp-close: func(conn: u32);
log: func(level: u8, msg: string);
}
world app {
import host; // always linked; a capability not granted fails its calls with permission_denied
export start: func(config: list<u8>) -> result<_, list<u8>>; // errors: CBOR {status, msg}
export on-set: func(path: string, value: list<u8>, who: list<u8>) -> result<_, list<u8>>;
export on-invoke: func(path: string, action: string, args: list<u8>, who: list<u8>) -> result<list<u8>, list<u8>>;
export on-timer: func(id: u64);
export on-value: func(sub: u64, key: string, sample: list<u8>);
export on-reply: func(req: u64, %result: result<list<u8>, list<u8>>);
export stop: func();
}
All data on the boundary is canonical CBOR (principle 5); the guest uses wyrm-core’s codec. declare-node, declare-action, remove-node and update return nothing: a bad meta or a bound reached fails the event when the commands are applied (above). The installer tells an app component from a point/driver one by its exports.
Capabilities, granted at install
The package manifest (ADR 0021, [package.metadata.wyrm-link]) gains capabilities:
net: thetcpallowlist entries (ADR 0012 syntax) or[];requester: grants on other points (ADR 0013 syntax; the existing top-level field, not insidecapabilities);store_mb: store size (default 1, at most 64);- limits, flat beside them:
memory_mb(default 64, at most 512),call_ms(default 2000, at most 10000).
Installing shows them, records them in the package_install audit record (with the requester grants; on an upgrade too) and applies them as the link’s settings. A process package of a portable app may carry the same capabilities: they become its params the same way (without component), so the process twin gets the same net, store and call time as the WASM one. Later changes go the existing ways: requester grants through sys/links/<id>/~act/grant (ADR 0013, router rebuild), net, store_mb and limits through the link’s update (params; rollback too). The broker checks new params with the driver the link runs on: an app component’s link with the app driver’s rules, a driver or point component’s with the wasm framework’s; a process package’s params are parsed by its own binary at hello, so the broker does not check them (as at install). A capability not granted fails its calls with permission_denied.
- The link knows its grants: the admin sends them in the
helloreply (process) and inLinkConfig(embedded, WASM), so a request outside them is refused in the link before it reaches the router (the router ACL still refuses it too). Reading another point (subscribe) needs areadgrant in every mode: ADR 0013’s “embedded links read everything” is not used by portable links. - Embedded built-in apps (the scheduler, ADR 0022) get their grants from
wyrmdat start, not from an operator: the scheduler getswriteonwy/<site>/downstreamand signs with its own admin-made key (as the agent’s); its own checks (ADR 0022 targets) narrow what a caller may make it do.
Faults and restarts
The guarantees below hold for WASM in full. A process link gets them from the OS (a separate process, restarted by the supervisor with backoff). An embedded native app is trusted code shipped with wyrmd (the scheduler): the adapter runs it on its own thread and catches panics (restart with the same backoff and tree rules), but an endless loop in native code cannot be stopped; such a link is reported stuck (no event completed for 30 s) and needs a broker restart. Third-party code therefore runs as WASM or as a process, never embedded.
- A trap, out-of-memory, fuel exhaustion or a call over time: the host drops the instance, marks the link
restarting(status node, as ADR 0004’s state machine) with the error, waits (1 s, ×2, cap 60 s, jitter), instantiates again and callsstart. Timers and subscriptions of the dead instance are dropped; the store is kept. - The tree: before calling
startagain the host keeps the old tree but marks its valuesbad/comm_fail; nodes the newstartdoes not declare again within 10 s are removed (re-declare, principle 3; no half tree left behind). The link root node ("") belongs to the host: it carries the link status as attributesstatus(running | restarting | stuck) anderror; the app declares nodes under it but never the root itself, so the sweep never touches it; the app’s paths may not start with.. - Config:
startgets the link’s params (a CBOR map; the app validates it and failsstartwithinvalid_parameternaming the field). A change of params is a stop and a start (noreconfigure). - Hot start: a new component (package upgrade, “Install ▸ from WASM” again) goes through
stopon the old instance (bounded 2 s), then the new one starts; the store carries over; requests in flight getbusy. On an upgrade of an app package the broker swaps the code inside each running link of the package (links/wasmreload_component): the link is not stopped, its tree stays (nodes the newstartdoes not declare again go by the sweep), audit ophot_start. Links of process packages, driver/point components and links that are not running stop and start from the new files. One link that fails to start does not stop the others: the result names it (not restarted: <id> (<error>)) and the old files are removed in every case. - Bounds: at most 10 000 nodes, 1 000 timers, 1 000 subscriptions, 100 requests in flight, 1 000 commands per event, 64 actions per node; going over one fails that call with
resource_exhausted(not a trap). An action name is one key segment (not.or..): another one failsdeclare_action(the event) orinvokewithinvalid_parameter. - Store bounds: each entry counts its key and value length rounded up to 4 KiB, and at least 4 KiB, toward
store_mb(one file per key on disk: a 1 MiB store holds at most 256 entries); at most 10 000 keys; a key is 1 to 256 bytes. Going over one failsstore_putwithresource_exhausted. A write that does not grow the store passes even over a smallerstore_mb, so the app can shrink it;store_mb: 0refuses every write. - Memory:
memory_mbbounds the instance, all its linear memories together. - Call time and the caller: the SDK’s bound on one
set/invokeof a portable link iscall_ms+ 1 s (it raisesLinkConfig.driver_timeout, and an app action’s owntimeout_ms, to that), so the caller is not answeredtimeoutwhile the call still runs. A request that waits in the event queue until its caller gottimeoutis dropped, not run later (a retry would run it twice); that includes aninvokethe SDK answered while it waited in the SDK’s own queue (its reply sink is closed). A request that waited in the queue longer than the SDK’s bound lesscall_ms(LinkCtx::driver_timeout−call_ms, at least 1 s) is answeredtimeoutand not run:call_msmore could end after the SDK’s bound, which counts from when the SDK took the request.
Building: one crate, three outputs
[features]
process = ["wyrm-link-sdk/process"] # bin: process::main::<Portable<App>>()
wasm = ["dep:wyrm-link-guest"] # cdylib: wyrm_link_guest::export!(App)
[package.metadata.wyrm-link]
kind = "wasm" # or "process"; `wyr link pack --kind` overrides
capabilities = { net = [...], store_mb = 4, memory_mb = 64, call_ms = 2000 }
requester = [...]
wyr link packforkind = "wasm":cargo build --release --target wasm32-unknown-unknown --lib --features wasm, then turns the core module into a component in-process with thewit-componentcrate (bindings fromwit-bindgeninwyrm-link-guestcarry the component type), then packs it (ADR 0021). One zip for every host.rust-toolchain.tomladds the targetwasm32-unknown-unknown.wyr new link <name> --appscaffolds such a crate (lib with theApp,src/binfor process, thewasmfeature, a test on the native adapter).
Tests and benchmarks
- One test app run on all three hosts with the same scenario (tree,
set,invoke, timer, store across a restart,seton another point within and outside its grant), compared event by event. - Faults: a guest that panics in
on_timer, loops forever, allocates past its memory, keeps the broker up and comes back; a hot swap keeps the store. - Benchmarks: event round trip (native vs WASM), memory per instance, restart time after a trap, commands per second.
Consequences
- ADR 0022 (scheduler) is written as an
App: its persistence is the host store, its timers and writes go throughHost. That ADR is updated when this one is accepted. wyrm-link-sdkgains the adapter;links/wasmgains theappdriver next towasm(point/driver worlds unchanged).wyrm-coremust keep building forwasm32-unknown-unknown(CI checks it).
Left to the builder
- Crate names and module layout; whether
Portable<A>lives inwyrm-link-sdkor its own crate. - The exact CBOR of
whoand ofAppError; the store’s file format (sealed with the link’s store key). - The native adapter’s thread and channel layout, within the rules above.
ADR 0024 — Server kinds in the driver framework (Modbus slave)
Status: accepted · 2026-10-30 (Modbus DSA parity plan, ruling 15; master writes as ruling P4; values and master requests as rulings P24–P27). Replaces the “Slave/server mode” row (ServerKind) of ADR 0004.
Context
DSA’s Modbus link can also be a slave: it serves values from its tree to Modbus masters (SCADA, PLCs) and takes their writes. ADR 0004 sketched an optional ServerKind trait with a shared listener per port and a process image per unit, but nothing was built. The framework knew only connections that poll devices: an owner task per connection holds the transport, tickers send polls and pings, a ~set is a device write followed by a read-back.
A server has the same shape seen from the other side: a listener (or a serial port) instead of a socket to a device, unit ids instead of devices, and points that a master reads instead of points the link reads. What differs is where values come from and that they flow both ways.
Decision
- A server is a connection kind.
Driver::is_server(conn) -> bool(defaultfalse) marks it; the Modbus link adds the kindsip_slave {listen_host, listen_port}andserial_slave {serial params}besideip_connectionandserial_connection. Its devices are the units it serves, its points are what it serves. The tree keeps its shape and its actions:add_*,edit,remove,start/stop, folders,copy,exportandimportwork as for any connection (a copy or import starts stopped, so two servers never fight for a port). What is new: the two connection kinds, the point paramwritable_by_master(Modbus) andattr.warningon a connection’sstatusleaf (below).openreturns the running server; dropping the transport closes it. - Not polled, not pinged. A server connection gets no tickers. Its devices are
Connectedwhile it runs, except those the server refuses (Driver::servereturns them with why; they showFailed: Modbus refuses unit 0 underserial_slave, the RTU broadcast address). - Values from the tree. Every point of a server takes
~setat level write, whatever the driver’spoint_metasays (Modbus: input registers and discrete inputs too, which a master cannot write).Driver::writeputs the value into what the server serves; there is no device read-back: the framework publishes what the driver now serves (Driver::take_changed), which is the value a master reads (after its encoding: anf32, a scale). The framework hands each plan to the server (Driver::serve; at once: a re-plan wakes the owner), then writes the tree’s last value of every point that is new to the server or whose params or device params changed (after open: every point). So a restarted or edited connection, a device started again and a point edited to another scale serve the tree’s value; a point that stays as it was keeps what it serves (a master may have written it). Amended 2026-10-30 (ruling P29, O1): a tree value the server does not take (it does not fit the point’s new data type, or the write is cut) is logged at warn (the point, never the value) and published again asbad/config_errorwith the old value kept, also when the point is bad already (bad/disconnectedwhile the server was down), until a value is served. - A point the tree never set has no value (ruling P24). Nothing is published for it, so a link that starts afresh does not overwrite the broker’s stored
~valwith an invented 0, and a new point never takes over the words of a removed or changed one. Modbus answers a master read that touches such a point with exception 4 (server device failure). Modbus knows the bits of a register one by one (ruling P28): a bit point has a value once its bit is known, a word view once all its bits are, and a master read (or FC22) of a register needs the bits its points read; setting one flag of a register leaves its sibling flags without a value. - Values from the remote side, in one order. A master’s request goes through a channel to the connection’s owner task, the same task that applies the tree’s sets:
Driver::remotetakes it (cancel-safe: it awaits only the receipt),Driver::apply_remoteanswers it under the plan’s read lock once the server has the plan in force. The framework passessince, when that plan began; by the hook’s contract the driver answers busy, changing nothing, to a request received before it (a re-plan came while it waited), like a tree set planned before a re-plan (P19). Modbus also drops a request whose master stopped waiting (it got busy), so it is never applied late. So the last writer wins, and the value published is what the next master read returns. The remote side gets its answer only after the framework published what the request changed. A master write is logged at info by point (never the value) and counted in the device’s and the connection’s diagnostics; there is nosys/auditrecord (no WYRM caller). - Listener on loopback by default (
listen_host = "127.0.0.1"). Modbus has no authentication: anyone who reaches the port reads every served value and writes those a master may write. Another address is allowed (adding a connection is already aconfigaction). The server listens on every address the host name resolves to (localhost:::1and127.0.0.1), and the bound addresses are checked: one that is not loopback is logged at warn when the server opens and shown asattr.warningon the connection’sstatusleaf (Driver::status_note; an attribute, not a new leaf, so no new reserved name). - Driver actions of their own. A server connection and its devices offer
Driver::server_actionsinstead ofDriver::actions(Modbus: none; the commissioning actions are a master’s).
Modbus rules (the driver’s, in links/modbus/src/slave.rs): points are views on the served registers and bits of their unit, so devices with the same unit and overlapping points share them. An address no point covers answers exception 2; a write touching a point without writable_by_master exception 3, and so does a write that a point it touches cannot decode (invalid BCD, text, m10k) or that makes a float NaN or infinite (ruling P25); a tree set that would do that to an overlapping point of another type is refused the same way; a refused request changes nothing. ip_slave leaves out an address the host does not have, and (ruling P29, R1) one whose address family it lacks (EAFNOSUPPORT: an IPv6-disabled host binding ::1 for localhost); any other bind error (the port in use, no permission) fails the connection. A unit not served gets no reply on RTU and exception 0x0B on TCP. An RTU broadcast (unit 0) write goes to every served unit that takes it, with no reply, and counts as one request of the connection; a broadcast read is ignored (ruling P26).
Consequences
- Every hook has a default; drivers without server kinds compile and behave as before.
- One request at a time per server connection: a master’s reads wait behind the tree’s sets. The owner does no device I/O for a server, but each publish is a Zenoh put on the owner task, so a burst of changes delays the next master request by those puts.
- A stored point loads unchanged:
writable_by_masterdefaults tofalse; it does nothing under a master connection, andpoll_sand the device’s ping and batch params do nothing under a slave. - The served values live in memory: a restart of the connection serves the tree’s values it has; a fresh link process serves nothing until the tree sets values (masters get exception 4 meanwhile).
serial_slaveis supported only as the only slave on its line (point to point to one master, ruling P27). Thetokio-modbus0.17 RTU server decodes every frame on the line as a request: other slaves’ replies on a shared RS485 bus make its decoder drop bytes, and after 20 tries in one decode it gives up, which ends the server; the connection then fails and reopens after backoff, losing the masters’ requests meanwhile. Framing by the 3.5-character gap of our own is a separate task.
Alternatives
- A
ServerKindtrait besideDriver, one listener per port shared by connections (the ADR 0004 sketch): a second registration path, ref-counting and overlap rules across connections, for a case (two connections on one port) that a second device under one connection already covers. - Answering reads in the server task from a shared image (a mutex): faster reads, but tree sets and master writes would be ordered in two places, and the diagnostics would miss the reads.
- Showing the warning in the
errorleaf: that leaf means the node failed; a running server is not failed. - Serving 0 for a point never set: what many slaves do, but it invents a value at good quality and, published, overwrites the broker’s stored one.
ADR 0025 — DQL link: standing queries over the tree, as a portable link
Status: accepted · 2026-10-30, built (owner request: bring DSA dslink-dart-dql into WYRM so that it runs in every mode and works as the scheduler does — a portable App, embedded in every wyrmd, also a WASM and a process package). Owner decisions D1 … D6 of 2026-10-30 are listed at the end. Built: crates/wyrm-dql, links/dql, wyr query, the Host API amendment; user guide docs/dql.md; plan docs/superpowers/plans/2026-10-30-dql-link.md. Where the build differs from the text below, the rulings at the end (B1 …) say why.
Context
DSA DQL (“distributed query language”, IOT-DSA/dslink-dart-dql 0.6.2, analysed 2026-10-30) is a responder and requester link with one action, /query {query}, whose result is a streaming table. A query is a pipeline of commands separated by |:
list /downstream/System/* | filter $type="number" @unit!="%" | subscribe :name value | expression double="row.value * 2"
list /downstream/System | filter :metric | subscribe | invoke /downstream/MongoDB/local/SystemValues/publish(Path=%path, Value=%value)
Each command takes the stream of row updates ({values, remove}, row id = path) and gives another: list/lista (reactive recursive list; * any depth, ? one segment; , for more roots; directive brokers), path (one node), sublist (a list relative to each row), filter/where (tests on $config, @attribute, :name, columns; = != < <= > >= ~ like contains anyContains in, and or xor not, function calls; a test on a column subscribes it by itself), subscribe/child (value, value.timestamp, a child’s value, $config, @attr, :name, :displayName, :children/:configs/:attributes, as column names), expression (a column from a script over row), rename, drop, option (qos, traverseBrokers, listActions, invokeAllowNull, brokersIncludeQuarantine) and invoke (call an action for each row with params from columns, %col, again when they change). Identical query texts share one running query (QueryManager); the link shows counts (uniqueQueryCount, totalQueryCount, virtualListCount, virtualSubscribeCount, actionInvokeCount) and getRunningQueries.
Kept: the pipeline language and its command names, row id = node path, columns in first-seen order, shared execution of identical texts, the counters, sinks that act on rows (invoke). Not kept, because they are its defects (read in the source):
- a query lives only while a requester holds its stream; nothing survives a restart, and a site without a client runs no query;
/queryis$invokable: read, andinvokeruns with the link’s own rights: whoever may read the link makes it call any action the link can reach (privilege escalation);- no bounds:
list *lists the whole network, onelistper visited node, one subscription per row and column, unbounded rows, columns and invokes; one query can stall the broker; expressionis a 5 600-line embedded JavaScript-like interpreter without a step or time bound;- the
>=test is an assignment (result = v = against), so it is always true for a non-null value;sublistremoves rows with the parent’s path instead of the child’s, so rows of a removed parent stay; - a removed row re-sends every row after it (
replace <id>-<len>), O(n) per removal; - an error in any stage closes the whole query with a stack trace as its message;
invokefires on every change with no rate limit and no bound on calls in flight.
WYRM already has what made DQL expensive in DSA: one key space with patterns (wy/<site>/downstream/plc/**), resolve (view=keys&match=) and pattern subscriptions for fan-in (spec 01). A query can be one subscription per root, not one per row.
Goals
- A query is configuration: stored, validated, running on the broker offline for months, back by itself after a restart (as a schedule, ADR 0022).
- One language core for every way DQL runs: the link (embedded, process, WASM) and the CLI.
- Results are ordinary nodes: anyone with
readsubscribes to a query’s table; a dataflow, the explorer, the MCP server and an upstream site use it with no new protocol. - Bounded cost: per query and per link limits on rows, lists, subscriptions and sink calls; zero messages at idle when nothing changes.
- A query cannot do more than its author may do; reading results never gives more rights than defining the query.
- DSA queries import with a converter (
/downstream/X/*→wy/<site>/downstream/X/**).
Non-goals
- SQL, joins between queries, aggregation over time (history has
Get Historywith rollups, ADR 0014; dataflows have windows). - Streaming action replies (ADR 0023 non-goal); the results are a node, not a stream on
~act. - Queries that write
sys/**or another site (owner decision 8, as flow sinks and scheduler targets).
Anti-goals (a failure even if it works)
- One query, however wide, stalls the router, another link or the other queries.
- A user who may only read a part of the tree reads more through DQL.
- An
invokerepeated after a restart that the author did not ask for. - Load at idle that grows with the number of rows.
Decision
Language core (crate wyrm-dql: no I/O, no async, no clock; builds for wasm32-unknown-unknown)
- Parser (hand-written, no parser generator): text →
Plan(stages, the columns each one adds or drops, sink targets, the roots), or an error with the stage index, the column and what was expected. At most 16 stages and 4 KiB of text. - Engine: a pure state machine. Input: list changes of listed nodes, value samples, sink replies,
tick(now). Output: row changes (upsert(path, columns),remove(path)) and the effects it wants (list,unlist,subscribe,unsubscribe,invoke,set). The host (link or CLI) performs the effects and feeds the results back. Every step is bounded; the same inputs give the same outputs (fixture tests, aswyrm-schedule). - Standards before our own code (D1): the pipeline syntax is DSA DQL’s (its users know it); paths are Zenoh key expressions (
*,**, the transport’s own standard); every expression and predicate is CEL (Common Expression Language, the Google specification used by Kubernetes, Envoy and Firebase rules), evaluated by the cratecel-interpreter(0.10, featuresregex,chrono; checked 2026-10-30 to build forwasm32-unknown-unknown); regular expressions are CELmatches()(RE2 syntax, crateregex). Our own code is only the pipeline parser and the row engine. CEL is not Turing-complete (no loops, no recursion; macros likeall/existsare bounded by their list), so its cost is bounded by the expression and the row; the link adds a bound on expression text (1 KiB) and on list sizes in a row. Amended 2026-10-31 (local review; a nest of 5maps over a 30-item literal took 4.8 s per row, and cel-rust cannot stop an evaluation): the bound is static, checked on the parsed expression (a scan of the text was fooled by spaces, raw strings and comments, and a chain like.map(b, b + b)doubled every step): no macro inside another macro’s body, at most 4 macros chained, no+and no list or map literal inside a macro’s body (only the expansion’s own@result + [x]), list literals ≤ 64 items, a bound value of more than 1 000 items or 16 KiB of text isnull. Row variables reach an evaluation only through a resolver that counts lookups (≤ 10 000) and, natively, watches a 20 ms deadline: past either the variables are gone and the evaluation stops withtoo costly(the only way to stop cel-rust). The dearest expression the static check allows, over the largest values, takes about 1 ms per row (debug build); cel-rust’s parser stops nesting at 96 levels, and every form within 1 KiB evaluates on a 2 MiB stack in release; the engine thread gets 8 MiB. - Keys are full keys (
wy/<site>/…, “full site names everywhere”); the core does not know its own site. Wildcards follow Zenoh, not DSA:*is one segment,**any depth. A DSA text goes throughconvert_dsa {text, site}(?→*, a trailing*→**,/downstream/…→wy/<site>/downstream/…).
The language (WYRM dialect; DSA names kept where they map)
| Command | WYRM meaning |
|---|---|
list <pattern>[, <pattern>…] | Rows for nodes under the patterns, reactive (added, changed, removed, link gone). Folders and values; actions are not nodes in WYRM (lista and listActions are dropped, see :actions). |
list sites | Rows for this site and the sites it sees (upstream/*, downstream/* brokers, attr.root); DSA brokers. A pattern under another site’s key (wy/plant/downstream/**) lists that site through the peer link within the ACL (ADR 0018) — in the first version (D4); DSA traverseBrokers is not needed, the key says where. |
path <key> | One row for one node. |
sublist <pattern> | A list relative to each row (./*, ./**); its rows replace the parent’s. |
where <CEL> | A CEL predicate over the row: type == "number" && attr.unit != "%", name.matches("^ahu[0-9]+$"), value > 20.0. Variables: the columns, and meta fields as type, unit, writable, is (profile), display, name, attr (map), actions (list of names), path. |
filter <DSA tests> | DSA syntax kept for imported queries ($type="number" @unit!="%" :name); the parser turns it into the same CEL ($x → x, @a → attr.a, a bare key → has(...), like → matches()), so there is one evaluator. A test on a column that no earlier stage made subscribes that column first (as DSA). |
subscribe [<key> [as <col>]]… / child | value (default), value.timestamp → the sample’s t, value.quality (new), a child’s value (./setpoint), $…, @…, :name, :display, :children. |
expression <col>="<CEL>"… | A column from a CEL expression over the row (value * 2.0, string(value) + " " + unit); DSA’s JavaScript-like row.value is accepted as row.value (the row is also bound as row). |
rename <a> as <b>, drop <cols>, option <k>=<v> | As DSA. Options: invoke_allow_null, throttle_ms, max_rows, timeout_s (see “Wide and deep trees”). qos is accepted and ignored (spec 03 QoS belongs to the point, cfg.qos). |
invoke <node>/~act/<action>(<p>=%<col>, <p>=<literal>…) | For each row, call the action when the referenced columns change. <node> is a full key or relative to the row (./, ../). |
set <node> = <expr> | New: write a value to a point for each row when it changes (~set; a write sink is more common in WYRM than an action). |
- Expressions: CEL as specified, with its standard functions and macros;
wyrm_core::Valuemaps to CEL values one to one (map, list, int, uint, double, string, bytes, bool, null; the sample time as a CELtimestamp). No functions of our own in the first version. An expression that fails on a row (a type error, a missing key) givesnullin that column and a count in the query’serrors, not the end of the query; a text that does not compile is refused atadd_query/runwith the stage and CEL’s message. - Rows: id = node key; columns in first-seen order; values are
wyrm_core::Value.
Host API: two additive changes (an amendment to ADR 0023)
DQL needs what the scheduler did not: to see the tree and to subscribe a subtree with one subscription.
Host::list(key, full) -> Result<SubId, AppError>(B2) — reactive one-level list (aswyrm-clientlist):App::on_list(sub, key, change)withchange = Refreshed(children) | Added(child) | Changed(child) | Removed(name) | Disconnected, a child =(name, NodeMeta). Needsreadon the key; ended byunsubscribe; counts toward a new boundmax_lists(2 000 per instance). A full queue coalesces a list’s changes into aRefreshed.Host::subscribe(key)accepts one final/**segment: one subscription for a subtree (fan-in);readon the prefix; each sample comes with its node key (on_valuealready has it). No other wildcard.- WIT:
wyrm:app@0.1.0stays frozen (ADR 0022 ruling 2), so components built on it keep loading. A newwyrm:app@0.2.0world is a superset: importlist, exporton-list; the WASM host tells the two worlds apart by their exports (as it tellspointfromdriver). The scheduler moves to 0.2.0 only when it is rebuilt.
The link (links/dql: an App, as links/scheduler)
<link>/ attrs: queries, rows, lists, subscriptions, sink_calls (DSA counters)
add_query {id, display?, text, enabled?, publish_ms?} (write; sinks need config) -> {id}
explain {text} (read) -> {stages, columns, roots, sinks, errors}
run {text, id?, ttl_s?} (write; sinks need config) -> {id, table} # ad-hoc, shared by identical text
import {json, id?, overwrite?} (config) # own export or a DSA text
convert_dsa {text, site} (read) -> {text}
<query>/ folder; attrs display, text, status (collecting | ready | error | disabled),
error, rows, columns, errors, created_by, expires (ad-hoc only),
progress: lists, lists_pending, depth, sites, collect_ms, last_publish
table the table: an array of row maps, columns order in attr `columns`
enabled writable bool; saved
get_table {from?, limit?} (read) -> rows
edit {display?, text?, publish_ms?} (as add_query); export (read) -> {json}; remove (write)
- Results as nodes:
tableis published when it changed, at most everypublish_ms(default 500 ms, 100 … 60 000) — coalesced, never per sample; with no change there is no message. Readers subscribe to it (explorer, flows, MCP, upstream sites);get_tablepages it (≤ 5 000 rows per reply). No per-row nodes: rows come and go faster than a tree should change, and the node budget would bound rows. - Ad-hoc queries (DSA
/query):runreturns the id and thetablekey of a temporary query withttl_s(default 300 s, ≤ 3 600);get_tableorrunagain with the same text renews it; identical text shares one (DSAQueryManager). Withidthe caller names it, so a dataflow can subscribe a fixed key (…/dql/<id>/table) in its definition. It is not stored: it ends with the instance. - Who asks (D2): engineers (explorer,
wyr, the agent through actions) and, later, dataflows: the broker collects data through the DQL link from a flow — a flowinvokesink callsrun {id, text}(or the engineer defines a standing query) and a flowsubscribesource reads<id>/table, waiting forstatus: readywhen it needs a complete table. A one-shotquery {text, timeout_ms} -> rowsthat answers when the table is complete needs deferred replies in the portable API (ADR 0023 non-goal today); it is left for the dataflow work. - Persistence: host store
index(the ids) andq/<id>(definition:{id, display, text, enabled, publish_ms, created_by}), written in the event that accepts the edit. Results are not stored; after a restart the query is evaluated again from the live tree (principle 3: what is not re-declared does not exist). - One subscription per root: the engine subscribes
<topmost fixed prefix>/**once for all value columns of a root and drops samples of keys that are not rows;listruns only on the levels the pattern can reach. - Bounds (constants of
links/dql, one place each, refused withresource_exhaustedbefore the host would fail the event): 200 queries; rows per querymax_rows(default 1 000, ≤ 5 000; over it the query showserror: max_rowsand keeps the first rows); lists 1 000 per query (B3) and 2 000 per link; subscriptions 1 000 per link; sink calls 50 in flight per link (the rest wait in a FIFO, as scheduler writes) and at most one in flight per row; at most 800 commands and 500 ms of batched work per event, the rest in0ms timer events (ADR 0022 ruling 5); nodes 5 per query (1 000 queries’ worth below the 10 000-node host bound). - Sinks (D3, D5):
setandinvokefire when the values they use change, and not for a row whose values are null (unlessinvoke_allow_null). After a start (a restart, an edit,enabledon, a row that appears) the first values seen are the baseline: neither sink fires until the state changes from it (D5: no write and no call repeated after a restart). There is no option to fire on start.throttle_ms(default 0) holds a row’s next call. A failed call is counted inerrorsand logged atinfo(ids only, never values); it is not retried (an action is not idempotent). - Rights (D2; as ADR 0022 ruling 6): a
ptokcarries one grant narrowed to the request key, so the link cannot see the caller’s rights on the keys a query lists; it does see the caller’s level on its own action key (SigningTokens::scopedkeeps the level). So:- a query without sinks (
add_query,run,edit,remove) iswrite: engineers, the agent (capped atwrite) and dataflows (the flow key is trusted atwrite; a deploy proof per target, ADR 0008) may define and run them; whoever haswriteon the DQL link may read what the link reads — the guide says so, and roles that must not see the whole site get nowriteon it; - a query with a sink (
set,invoke) needs the caller’s effective levelconfigon the action key: the app checkswhoand refuses withpermission_deniedotherwise. The SDK must give the app the effective level (the claim capped by aLimitedKey’s limit), so a flow or agent key never passes asconfig; the builder checkswho_ofand fixes it if it passes the raw claim. Flows therefore cannot create sink queries (they have their ownset/invokesinks). Switching a sink query on (enabled), editing it, replacing it byrunwith its id, and removing it needconfigtoo;writemay switch it off (stop its writes, as an operator stops a schedule), never start them again or drop an engineer’s query (review item 5, 2026-10-31); importisconfig(it may carry sinks); reading results (table,get_table,explain) isread. A query keeps running after its author loses rights (as flows and schedules);created_by=who.subject. The full-grants claim inptok(the scheduler’s open item) would allow checks against the author’s own rights on every key; not in this version.
- a query without sinks (
- Grants of the link: embedded —
readonwy/<site>/{downstream,dataflows,storage,upstream}andwriteonwy/<site>/downstream(sinks), signed with its own admin-made key (subjectlink:dql), trusted by links as aLimitedKeyatwrite, and not by itself (no query writing its own nodes in a loop, ADR 0022 ruling R21). Packages carry norequestergrants; an operator grants each root (sys/links/<id>/~act/grant, ADR 0013). A query on keys outside the grants showsstatus: errorwith the host’spermission_denied.
Wide and deep trees, other sites (D4)
Collecting a table can take time: one list round trip per level the pattern reaches, a peer hop per site (QUIC, ADR 0007), links that answer slowly. The link does not hide it, and the numbers tell us where the time goes once trees are big and deep:
status: collectinguntil every list the query started gave its firstRefreshed(or failed), thenready; a change later keepsready.timeout_s(default 30 s, ≤ 600) marks a queryreadywitherror: incomplete (<n> lists pending)when lists are still pending, and keeps waiting for them in the background.- Progress attributes on the query:
lists(running),lists_pending,depth(deepest level reached),sites(sites touched),collect_ms(start toready),last_publish. Counters on the link root:rows,lists,subscriptions,sink_calls,slowest_collect_ms. - The guide (
docs/dql.md) states the cost: a pattern with**near the top of a big site, or across sites, lists every level under it; prefer the narrowest fixed prefix (wy/plant/downstream/plc1/**, notwy/plant/**). - Lists of another site go through the router to that site’s links like any request from above (ADR 0018 read rules); the first-query timeout across peers in the backlog applies to them.
Run modes (one core, four hosts)
- Embedded in
wyrmd— the default, as the scheduler: one instance atwy/<site>/downstream/dql,dql: { enabled: true, store_mb: 16 }inwyrmd.json5; the iddqlreserved (validate_new_link_id,Daemon::openrefuses a stored link with it,peers.downstreamcannot name a sitedql); in the broker’s overlays; a failure to make its keys logs and the broker runs without it (ADR 0022 ruling R22). - Process package
dql-process—process::main::<Portable<Dql>>();wyrmd link dqlruns the same app as a process link. - WASM package
dql— the sameApp,--features wasm, worldwyrm:app@0.2.0,capabilities = { store_mb = 4 }. - CLI
wyr query "<text>"— the same engine overwyrm-clientwith the user’s own token: the ad-hoc, streaming DSA experience in a terminal (rows printed as they change,--json), rights checked by the router for the user, nothing stored. Later the same core can back an MCPquerytool and a flow source node (DSA “DQL as an embedded library”).
Tests and benchmarks
- Parser fixtures: DSA’s
statement_grammar.yamlcases converted, every example of the DSA README converted byconvert_dsaand parsed; errors name stage and column. - Engine fixtures (no host): list add/change/remove, link disconnected, sublist removal (the DSA bug),
>=(the DSA bug), filter that stops matching (row removed), auto-subscribe of filter columns, expression errors as null, sinks on change only and never on start (D5: a restart with the same values calls nothing), throttle, CEL errors as null, DSAfilter→ CEL translation. - The app on all three hosts with one scenario (as
scheduler_three_modes): a query overmock, its table, a restart (definition back, table rebuilt, no repeatedinvoke), a sink outside the grants. - Probe scenario
links/probe/scenarios/dql.json; user guidedocs/dql.md. - Benchmarks (targets on the reference board): 10 000 mock points,
list wy/<s>/downstream/mock/** | where type == "number" | subscribe— table complete < 2 s, one subscription; at 50k samples/s the query adds < 10 % of one core; table publication p99 <publish_ms+ 50 ms; idle: 0 messages. Deep and remote trees (D4), measured and recorded, not yet targets:collect_msfor depth 2, 4, 8 and fan-out 10, 100 under mock, on this site and across the demo chain (centralqueryingplantthroughedge).
Consequences
- ADR 0023 gains
Host::list,App::on_list, the/**subscribe pattern and thewyrm:app@0.2.0world;wyrm-link-api,wyrm-link-portable,wyrm-link-guest,wyrm-wasm-host,links/wasmchange; the 0.1.0 world and its components are untouched. - New crates
crates/wyrm-dql,links/dql;wyr query; the iddqlis reserved likestorageandscheduler. - Spec 02 does not change (existing value types and editors; the table is an array of maps).
examples/packages/build.shpacksdqlanddql-process.
Rulings of the build (B1 …)
- B1 — CEL crate:
cel0.15 (cel-rust, the maintained successor ofcel-interpreter), featuresregexonly.cel-interpreter0.10 panics on some invalid texts (1 +: an antlrunreachable!), which would restart the instance; 0.15 answers them as errors. Nochrono(its tz database is large in WASM): no CELtimestamp/duration; sample times are microseconds (value.timestamp). - B2 — full meta on demand:
view=listsummaries carry noattrand noactions, which DSA filters use (@mytag).Host::list(key, full): withfullthe host fetches each child’s whole~meta(one request more per child). A query asks for it only when a stage readsattr,actionsormeta(orlist sites). - B3 — lists per query: 1 000 (not 500): a site of 900 devices under one pattern fits; over it the query is
readywitherror: max_lists …. - B4 — other sites in the host:
BufferHostlet a portable link reach only its own site.subscribeandlistnow reach another site’s keys under an explicit grant;setandinvokestay on the link’s own site (owner decision 8). The embedded link getsreadondownstream,dataflows,storageof every sitePeers::reachablenames, per router build. - B5 — effective level in
Who: the portable runtime gave the app the rawptokgrants; it now caps each at the request’s effective level (Caller.perm, aLimitedKey’s limit), so a flow or agent token never showsconfig. - B6 — counters: the link root belongs to the host (ADR 0023), so the DQL counters are values under
stats/(statsis a reserved query id). - B7 — node ownership: the embedded DQL link does not trust its own key (as the scheduler, R21), so no query writes the DQL link’s own nodes.
- B8 — a fixed
sublist: aslist, a pattern without a wildcard lists that node’s children (sublist ./temp= the children oftemp). - B9 — not yet: a probe scenario on the demo, the three-mode e2e of the DQL link with its WASM and process packages, and benchmarks on the reference board. Tested: the engine and the link on
SimHost, both world versions inwyrm-wasm-host, and e2edql_embedded_queries_the_tree(the embedded link through a real router: a live table, its publication, asetsink only after a change);scheduler_three_modesandone_app_three_modespass with guests built on 0.2.0. - B10 — the grant a request carries: a
ptokcarries the first configured grant that covers its key, so areadgrant ondownstreamlisted before thewriteone sent sink writes atread(found by the e2e). The portable runtime now orders the link’s grants by level, highest first.
Owner decisions (2026-10-30)
- D1 — standards, fewer own solutions: CEL for expressions and predicates (
cel-interpreter), Zenoh key expressions for paths, RE2-style regex in CEL; DSA DQL pipeline syntax kept; no own expression language, norhaihere (not a standard). - D2 — who asks: engineers now and dataflows later (the broker collects data through the link): queries without sinks at
write, sink queries at effectiveconfig. - D3 —
setsink: added. - D4 — other sites: in the first version; collection time is shown (
collecting/ready, progress,collect_ms) and measured on deep and remote trees. - D5 — after a restart: wait for a change of state; no sink fires on start.
- D6 — WIT world (confirmed: a new
wyrm:app@0.2.0): a WASM link is built against a contract (WIT world) that lists what the broker gives it and what it must export. DQL needs one new broker function (list) and one new export (on-list). The scheduler’s WASM package, already installed on sites, is built onwyrm:app@0.1.0, which lackson-list. Changing 0.1.0 in place would make the broker expecton-listfrom every component and refuse the installed scheduler until it is rebuilt and reinstalled everywhere. A newwyrm:app@0.2.0beside 0.1.0 (proposed) lets old components keep running untouched and new ones (DQL, a rebuilt scheduler) use the new functions; the broker supports both.
Measured (2026-10-31, Apple M4 Max, loopback, release; dql_perf_local, dql_perf_chain)
- Collection of 1 000 points (
list …/** | where type == 'number' | subscribe,publish_ms100): the link’scollect_ms29–95 ms at depth 1–4 or fanout ≤ 100; 240 ms at fanout 2, depth 8 (511 lists); 871 ms at fanout 900 (901 lists); 5 000 points, fanout 50: 115 ms. A full table is published 1–2publish_mslater. - Across peers (1 000 points, fanout 10, depth 2):
collect_ms55 ms here, 61 ms one hop down, 69 ms two hops down. - A write on a point → the engine’s table: p50 4.9 ms, p99 12.3 ms (two hops down: p50 6.0 ms, p99 7.4 ms); a source write → the sink’s write of its target: p50 3.4 ms, p99 10.6 ms.
- Found by the first run: a 5 000-row subscription lost a value to the portable runtime’s overflow bound (256 + 4 096), and the refetch met the same bound. The overflow is now 16 384, and a subscription that lost values is opened again (at most 3 times) once the overflow has drained.
- Not yet: the reference board (4-core ARM64, 2 GB).
Item 4 — a query runs with its author’s rights (owner decision 2026-10-31)
Before, whoever had write on the DQL link defined a query over everything the link reads, and a sink wrote as link:dql: a user with a narrow read saw more through DQL (also found by the automated security review). Now:
-
The rights travel in the token. A
ptokon~act/*carries the optional claimauth(spec 04 0.2.10): the caller’s whole grant set on the site. It never authorizes the request; the SDK’s verifier caps each of its grants as the effective level (max,maxperm, the key’s cap) and to a limited key’s scopes (cap_auth), and the portable runtime hands it to the app asWho::authority. Owner decision: only on action tokens, so a link that is read or written never learns a caller’s grants. -
Kept with the definition.
add_query,run,importand aneditof the text store the caller’s rights (Rights {site, grants}) with the query, in the link’s store (not in the JSON export). The query keeps them after a restart and after its author’s grants change (as flows and schedules keep running). -
Applied while it runs. The engine (
Engine::with_rights) makes no row of a node its author may notread, takes no value of a key they may notread, and refuses a sink target they may notwritewhen it would fire (..may climb out of a root): the query’serrorscount it anderrornames the key. Keys of a downstream site are checked with the own-site grants rewritten to it, by the gateway’s rule (wyrm_core::ptok::grant_for_site). -
Unknown rights are refused (owner decision): a token without
auth(a flow, an old client) cannot define a query, and a stored query without kept rights showsstatus: erroruntil its text is edited or it is added again. -
Ad-hoc queries are shared only by callers with the same text and the same rights: a table made with one user’s rights is never handed to another through
run. -
wyr queryruns the engine without a bound: the user’s own token reads and writes there. -
Who reads a table (owner decision 2026-10-31):
get_tableanswers each caller with the rows it may read itself (its ownauth; noauthis refused), so the author’s rights make the table and the reader’s decide what of it they see. The live value<id>/tableexists only for a query withpublish: true(set withconfigonadd_query,run,editorimport): one value cannot be filtered per subscriber, so an engineer decides that a table is for whoever may read that node (the gateway filters it by the user’s grants, as any key). Dashboards and dataflows read published queries.
ADR 0026 — History sync to external databases
Status: accepted · 2026-10-31 (owner request: send the edge historian’s data to MySQL, MongoDB, PostgreSQL, InfluxDB and DynamoDB; not native in the broker, extensions installed as links; owner decisions 1–3 taken 2026-10-31, see the end).
Context
The embedded historian (ADR 0014) records watched points into day files of redb on the edge. Sites need the same data in a central database. The owner named five targets: MySQL, MongoDB, PostgreSQL, InfluxDB, DynamoDB.
The reference is DSA dslink-java-historian-dynamodb 0.2.2 (read 2026-10-31: DynamoDBProxy, BufferPurger). It is a whole historian of its own: its watch groups write to DynamoDB, which is the primary store, and Get History reads DynamoDB. A local ETSDB database is only a buffer while DynamoDB cannot be reached: queued records go there, a background runner sends them back in batches (Batch Write Max Records, Batch Write Min Interval), deletes what was sent (delete(series, 0, lastTs)), and BufferPurger deletes the oldest unsent hour of every series while the buffer is over Maximum Buffer Size. Records are keyed by watch path and time, so a resend overwrites. Records carry an expiration for DynamoDB TTL, as deletes there cost write capacity.
WYRM differs in one point that drives this design: the broker’s historian is the primary store on the edge. Get History, the history mark and chart in the explorer (ADR 0016), ~val?history= (D2) and the history of downstream points (ADR 0020) all read it. A sync that deletes each row once it is sent would leave the edge with no history.
What a link can do today:
- A portable App (ADR 0023) runs the same code as a WASM component (world
wyrm:app) or as a process package; the scheduler and the DQL link ship both ways. - The WASM host gives
tcp-connect(addr, port)with an IP literal only, checked against the link’sNetPolicy. No DNS, no TLS. Every managed database (RDS, Atlas, DynamoDB, InfluxDB Cloud) needs a host name and TLS. - History is read with
get <point>/~val?history=(rights assubscribe, at most 5 000 rows per reply, 4 reads at a time) or Get History onsys/history/…(config). Neither has a cursor: a reader cannot ask “everything written since my last batch”. - The store keeps rows
(series, t) → [v, q]; a row with the same key replaces the old one, and a row may arrive up to 31 days late. A cursor on time misses a late row written into an earlier day.
Decision
-
Not in the broker binary. A database client in
wyrmdwould grow the binary for every site, and adding one would need a new build and a restart of the edge. Each target is a link package that the operator installs where it is needed (ADR 0011, 0021). -
The historian stays the store; links forward. The historian gets a change feed with a cursor per sink. Sinks read batches from it and confirm them. Only the historian deletes, by its own rules. A sink never deletes and never needs
configonsys. -
Change journal in each day file. Table
CHANGES: seq u64 → (series u32, t u64), written in the same transaction as the row, so a row and its sequence number commit together.seqis one counter for the store, kept inindex.redband taken in blocks so a crash leaves gaps, never repeats. A row written again (same key, a late or replaced value) gets a newseq, so it is sent again. Each day file records its lowest and highestseq; a read from a cursor opens only files whose range is above it. Deleting a day file deletes its journal with it. -
Sinks are historian state.
sys/history/sinks/<name>: the link id and the watch groups it takes (owner decision 3: a list per sink, empty = all groups, so two sinks may take different groups) in the registry (HistorianDef::sinks, opsPutSink/RemoveSink, SCHEMA 19); the cursor (confirmed_seq) in the history store’sindex.redb, as it moves with every batch. Valueslink,groups,confirmed_seq,lag_entries(journal entries after the cursor, rows of other groups included),rows_sent,rows_dropped_unsent,last_request. Actions Add Sink {name, link, groups, from: start | now}, Edit, Reset Cursor {start | now}, Remove; audited (history_sink). A removed link takes its sinks with it. -
The feed. The link invokes
next {after?, max?}on its sink node; the answer is{rows: [{seq, key, t, v, q}], next}: rows withseq > afterof its watch groups, oldestseqfirst, at mostmax(≤ 5 000) and 1 MiB.after(default: the confirmed entry) confirms every row up to it, so the confirmation is the next request (at least once); the link asks next afternext, which covers entries it does not take. Only numbers committed when the read starts are read (a write holds the journal until its last day commits), so a cursor never passes a row still being written. The link signs with its requester key (ADR 0013, subjectlink:<id>); the admin trusts that key atreadon that sink’s node alone, and refusesnextfrom any other subject: a person who ran it would confirm rows the database never got. The router ACL lets a process link’s session query its sinks’~act/nextonly (sinks-<id>-in/-out). Adding or editing a sink makes the link’s requester key, starts a process link again (it takes the key inhello) and rebuilds the broker. -
Deleting. The current rules stay and never wait for a sink (owner decision 1): Retention Days, then Auto Purge by Disk Space Remaining (ADR 0014) delete the oldest day, sent or not, because the equipment keeps working and recording on the edge while the cloud may be down for long; the unsent rows lost that way are counted (
rows_dropped_unsenton the historian and on each sink). New:keep_after_sync_days(default 90, owner decision 2; empty = off): with at least one sink, a whole day file goes once every sink has confirmed its highestseqand the day is older than that many days.0keeps only what is not sent yet, as the DSA buffer does. With no sink the rule does nothing. -
Delivery is at least once. A batch can be sent twice after a lost reply or a restart. Every sink writes with the key
(site, point key, t)and replaces on conflict, so a resend changes nothing. -
One package per target, one shared core, one form for all (owner, 2026-10-31). A crate
wyrm-history-sync(cursor, batch size, wait between batches, back-off while the target is down, the counters, secrets in the connection parameters, sealed by the framework) and one package per target, so a device installs only what it uses. Every target is a portable App with its own protocol client over the host’stcp-connect/tls-connect, no native driver crates (sqlx,mongodb, AWS SDK): the same code ships as a WASM package (the default) and as a process package, and behaves the same in both. A process package is not faster here in any way that matters: a batch is one or two round trips to the database, and encoding 5 000 rows in WASM takes well under a millisecond; what native drivers would save is our own protocol code, at the cost of a build per architecture and a process per sink. -
One target interface, as DSA’s historian SDK (owner, 2026-10-31). DSA keeps all common work in
sdk-dslink-java/sdk/historian(nodes, watch groups, Get History, subscriptions); a database link implements onlyDatabaseProvider(createDbAction,createDb,dbPermission,deleteRange) andDatabase(performConnect,write,query,queryFirst,queryLast,close,initExtensions). Herewyrm-history-syncowns everything but talking to the database: the link’s nodes (one per connection:status,error, the counters; actions Add, Edit, Remove, Test Connection, Pause/Resume), the feed loop (next, confirmation), batch sizes, back-off, secrets. A target implements one trait:#![allow(unused)] fn main() { pub trait Target: Sized { /// The package and the link's root: "influxdb", "postgres", "mysql", "mongodb", "dynamodb". const KIND: &'static str; const VERSION: &'static str; /// Check the target's params before anything connects; an unknown key is an error. fn check(cfg: &Map) -> Result<(), String>; /// Open and authenticate (TCP or TLS through the host), with the secret from Set Password. fn connect(net: &mut dyn Host, cfg: &Map, secret: Option<&str>) -> Result<Self, TargetError>; /// Create the table, index or bucket if the parameters allow; safe to repeat. fn prepare(&mut self, _net: &mut dyn Host) -> Result<(), TargetError> { Ok(()) } /// Store one batch, replacing on `(key, t)`; `Ok` only when every row is stored. fn write(&mut self, net: &mut dyn Host, rows: &[Row]) -> Result<(), TargetError>; /// A cheap check of the connection. fn ping(&mut self, net: &mut dyn Host) -> Result<(), TargetError>; /// The largest batch it takes, e.g. DynamoDB 25 items per request. fn limits(&self) -> Limits { Limits::default() } fn close(self, _net: &mut dyn Host) {} } /// `key` is the point's full key (`wy/<site>/…`), so `(key, t)` is unique across sites. pub struct Row { pub seq: u64, pub site: String, pub key: String, pub t: u64, pub v: Value, pub q: Quality } pub enum TargetError { Retry(String), // network, throttling: wait, send the same batch again Reconnect(String), // connection lost: connect again, then the same batch Fatal(String), // auth, schema, a refused row: the link stops with `error` until a change } }The network is the portable host’s TCP/TLS (
tcp_connect,tls_connect), the same in WASM and in a process.SyncApp<T>(cratewyrm-history-sync, done 2026-10-31) runs a target as an App: paramssink(the sink’s key),batch(≤ 5 000),idle_s,retry_s, the rest the target’s; nodesstatus,error,rows_sent,last_batch,cursor; actions Set Password (the secret kept in the link’s sealed store, never a param), Test Connection, Pause/Resume (kept across restarts). A link param holds no secret: the registry keeps params in the clear. Shared helpers serve families:http(HTTP/1.1 overNet: InfluxDB, DynamoDB),sql(a dialect: table definition, multi-row insert with the conflict clause, quoting: PostgreSQL, MySQL),auth(SCRAM-SHA-256 for PostgreSQL and MongoDB, SigV4). A family member then costs little: TimescaleDB speaks PostgreSQL, MariaDB speaks MySQL, QuestDB and VictoriaMetrics take InfluxDB line protocol. A new target is one crate: the trait, itsParams,export!, package metadata. Not in the trait, unlike DSA:query/queryFirst/queryLast(reads stay on the edge historian; a read-back from the central database would add an optional method that answersnot_supportedby default) anddeleteRange(the central database keeps its own retention, DynamoDB by TTL). -
Host: TLS for portable Apps.
Host::tls_connect(host, port, timeout_ms, ca_pem)(and the same onServices): the host resolves the name on a thread of its own within the call’s time, connects to the first addressNetPolicy::allows_namedaccepts (an IP entry, or a listed namedb.example.com:5432/*.example.com:443resolving to a public address: a name never reaches loopback, link-local, metadata or, since 2026-11-01, private addresses by itself; ADR 0031), and verifies the certificate forhostagainst the system roots, or only againstca_pem, with rustls (ring) thatwyrmdalready links. The connection then takestcp_send/tcp_recv/tcp_closelike a plain one; the keys never leave the host.Host::tls_upgrade(conn, host, timeout_ms, ca_pem)starts TLS on an open plain connection (PostgreSQL and MySQL ask for TLS in band,SSLRequest), andtcp_connecttakes a listed host name too, under the same rule. Done 2026-10-31 in the native host (wyrm-link-portable), so the native and process forms have it. The WIT importstls-connectandtls-upgradecame with the worldwyrm:app@0.3.0(ADR 0030, 2026-11-01), withrandom-bytesfor SCRAM nonces: a WASM package built for 0.3.0 has TLS through the same host code; one built for 0.2.0 still getsnot_supported.
| Target | Protocol | TLS | Idempotent write | Our client covers |
|---|---|---|---|---|
| InfluxDB (v2, v3) | HTTP, line protocol | cloud: yes | same measurement, tags and time overwrite | HTTP/1.1 request and status only |
| PostgreSQL | v3 wire protocol (own), SCRAM-SHA-256, TLS by SSLRequest | usually | INSERT … ON CONFLICT (key, t) DO UPDATE, one (key, t) per statement | startup, auth, one multi-row insert per batch, ping |
| DynamoDB | HTTPS, JSON, SigV4, BatchWriteItem (25 items, 16 MiB) | always | partition key site/key, sort key t; TTL attribute as DSA | SigV4 signing, retry of UnprocessedItems |
| MySQL | protocol 41 (own), TLS by SSLRequest | usually | INSERT … ON DUPLICATE KEY UPDATE, primary key (key, t), text as hex literals | handshake, caching_sha2_password over TLS only (no RSA exchange), multi-row insert, ping |
| MongoDB | OP_MSG, own bounded BSON, SCRAM-SHA-256 | Atlas: always | _id {k, t}, update of replace-upserts with ordered: false; TTL index on ts | hello, auth, insert, ping |
- Order of work. 1) journal, sinks and the feed in
wyrm-historyand the admin, with e2e (late row resent, resend after a lost reply,keep_after_sync_days); 2)tls-connectin worldwyrm:app; 3)wyrm-history-syncand the InfluxDB and PostgreSQL packages; 4) DynamoDB, MySQL, MongoDB. Done 2026-10-31: 1 (journal, sinks, feed, purge rule); 2 in the native host (the WIT import waits for the next world version); 3 core (wyrm-history-sync), the sink grant for the link, InfluxDB and PostgreSQL (withtls_upgradein the host). Step 4 done: DynamoDB, MySQL, MongoDB (SigV4 and SCRAM shared inwyrm-history-sync, withhttp::Client). Done 2026-11-01 (ADR 0030): the WIT importstls-connect,tls-upgradeandrandom-bytesinwyrm:app@0.3.0, and an e2e through an installed package (wasm_app_world_0_3_0_has_tls_and_random). A SCRAM nonce now takes 18 bytes fromHost::random_bytes; only a host without a random source (a 0.2.0 component) still hashes it from the clock, a counter and the connection, unique but guessable; it never comes from the secret, since it goes to the server. Each client is tested against an in-crate fake server and, in an ignored e2e, against the real database in a container.
Consequences
- The broker grows by the journal and the feed only; targets add nothing to sites that do not use them.
- Each row costs about 16 more bytes on disk (the journal entry).
- A sink that stops confirming keeps its unsent days on the edge until Retention Days or Auto Purge remove them; its
lag_rowsgrows androws_dropped_unsentcounts what is lost. - Adding the first sink starts deleting days older than 90 days once they are sent. A site that wants a longer local history sets
keep_after_sync_dayshigher or empty. - The central database keys rows by the point’s full key (
wy/<site>/…), so several sites can share one table without the prefixes DSA needs.
Alternatives
- A sink inside
wyrmdfor each database: a new build and restart for each target, a larger binary everywhere (the owner’s two objections). - Remote database as the primary store (as DSA): the edge would read its own history over the WAN; offline sites lose Get History.
- Delete each row once sent (as the DSA buffer): possible as
keep_after_sync_days: 0, not as the only mode, for the same reason. - A cursor on time instead of a journal: misses late rows and rows written again.
- Sinks read
~val?history=per point: one query per point per batch, no cursor, no confirmation. - TLS inside the component (rustls with RustCrypto): about a megabyte per component, slower under the fuel limit, and every package would carry its own copy of the roots.
Owner decisions
Disk full with unsent rows— decided 2026-10-31: delete the oldest data, sent or not; local work goes on while the cloud may be stopped.— decided 2026-10-31: 90 days.keep_after_sync_daysdefaultWhat a sink takes— decided 2026-10-31: a list of watch groups per sink, empty = all; e.g. InfluxDB takesenergyanddiagnostics, DynamoDB onlyenergy.
ADR 0027 — File store links (S3, Google Drive, WebDAV, local directories) on the raw layer
Status: accepted · 2026-10-31 (owner request: links to popular file stores — S3, MinIO, Google Drive and other providers — that connect to a bucket, create folders, read the tree of folders and files, build it as nodes, and upload files; separate links where the stores need different code).
Context
The driver framework (ADR 0004) is Connection → Device → Point: people configure every node, the framework polls points. A file store is the other way round: people configure one connection (a bucket, a drive folder, a WebDAV collection), and the nodes below it are whatever the store holds, found by reading it. Points do not fit either: a file has a size, a time and bytes, read on demand, not a value polled every second.
The stores differ in protocol, auth and model: S3 has flat keys and Signature V4; Google Drive has ids, duplicate names, OAuth 2 (service-account JWTs, refresh tokens); WebDAV has real collections, PROPFIND multistatus XML and basic or bearer auth.
Decision
- Three links, one toolkit.
links/s3(AWS S3 and the S3-compatible stores: MinIO, Ceph RGW, Cloudflare R2, Wasabi, Backblaze B2, DigitalOcean Spaces, Google Cloud Storage with HMAC keys),links/gdrive(Drive API v3),links/webdav(Nextcloud, ownCloud, Synology, …). Each implementswyrm_filestore::Backend(probe, scan, mkdir, put, get, delete) and runs asFileStore<B>, a raw-layerLinkincrates/wyrm-filestore. Each is its own driver, package and process binary; none adds a dependency the workspace did not have (SigV4 and the JWT onring, XML by a small reader in the toolkit, Drive JSON onserde_jsonas store data, not the wire). - Raw layer, the framework’s conventions. Connections come from
add_connection(the backend’s params plusrefresh_s,max_entries,max_depth,max_upload_mib,max_download_kib; one form built from#[derive(Params)]),edit(secrets left empty keep the stored ones while thedestfields stay the same, as the framework’skeep_secrets),remove,stop/start. They are kept sealed indata_dir/filestore.connswith the link’s store key, bootstrap params win when they change — the framework’spersist, reimplemented on the publicseal. A connection node has the framework’sstatusenum leaf (wy:df-status) and theerrorleaf while there is one, andentries,total_bytes,last_refresh. - The tree is the store’s, re-declared on every read (principle 3).
<conn>/filesis the root folder; a folder node per folder, a leaf per file (value = size in bytes, at the file’s time;attrname,path,modified,etag,content_type). What a read does not report is removed. A node keeps its key while its entry exists; a name that is not a key segment gets a safe form with a stable hash, the real name isdisplay. - Bounded reads. A read stops at
max_entries(≤ 9 000) andmax_depth(≤ 12) and saystruncated; S3 reads at most 500 pages, a whole read at most 10 minutes. Uploads at most 64 MiB (the gateway’sPOST /api/invokebody), downloads at most 16 MiB. - Levels. Reads (
refresh,download) atread, changes of the store (create_folder,upload,delete) atwrite, connections atconfig. I/O of an action runs on a task of its own, so a slow upload never holds the link’s other calls. - Failures. The probe (an S3 list of one key, Drive
files.getof the root, WebDAVPROPFIND Depth: 0) failing, or a read failing, fails the connection; it reconnects with the framework’s backoff. A request of an action that shows the store is down (connect, 5xx, timeout) wakes the connection task, which probes again. A refused request of one object (403, 404, a taken name) fails that action only. - No silent overwrite. An upload without
overwritesendsIf-None-Match: *(S3, WebDAV) or creates a new Drive file only when the tree has none of that name. - Credentials never leave in clear:
http://with credentials only to loopback unlessinsecure_plaintext; Drive’s API and token URLs must behttps://off loopback.
Consequences
- Big buckets show in part (
truncated); people setprefix(S3) or a subfolder URL (WebDAV) or folder id (Drive) as the connection’s root to see the part they need. - File contents are not values: no history, no flows on them. A flow can invoke
upload(a report) ordownloadthroughinvokesinks like any action. - Google Docs files have no bytes to download (export is not built); S3 uploads are one PutObject (no multipart upload, so up to the 64 MiB cap).
- Each link has an in-crate simulator (
wyrm-s3-sim,wyrm-gdrive-sim,wyrm-webdav-sim) and runs one shared scenario (wyrm_filestore::testkit); SigV4 is checked against the AWS test vectors. Not yet verified against the real services.
Alternatives
- The driver framework with devices as folders: people would add every folder by hand, and files are not polled points.
- One link with a
providerenum: one package pulls in every store’s code and params; the owner asked for separate links. - The AWS and Google SDKs: large dependency trees, aws-lc (refused, see the rustls pin), and three async runtimes’ worth of HTTP stacks for what is a handful of requests.
Amendment 2026-10-31 — local directories (links/localfs)
Owner request: local storage too, working in as many places as possible.
std::fsonly, every call on the blocking pool undertimeout_ms: one link for Linux, macOS, Windows and the BSDs, embedded or as a process link on the host that has the disk. Mounted storage (NFS, SMB, sshfs, USB/SD, NAS) needs nothing of its own.- Confinement: names checked one by one (portable names: what Windows refuses is refused everywhere), the parent resolved and checked inside the resolved root before every change, symlinks out of the root never shown or followed,
remove_dir_all(which does not follow links) for folders. Backend::check_place(default: nothing): called with the link’sdata_diron add, edit and start;localfsrefuses a root that overlaps the broker’s data directory (<data_dir>/links/<id>/data→<data_dir>) in either direction.- Atomic overwrite (temporary file + rename),
create_newotherwise,fsyncof the file and its folder by default,read_only. - Not done: Windows ACLs and hidden attributes (only names starting with
.are hidden).
Amendment 2026-10-31 — review of gencto/wyrm#7 (owner)
Renumbered 0025 → 0027 (0025 is the DQL link on another branch, 0026 history sync).
- Delete asks the store.
Backend::delete(e, below, recursive): withoutrecursivethe backend checks the store itself (localfsremove_dir, S3 a list of two keys under the prefix, WebDAVPROPFIND Depth: 1, Drive the folder’s children) and answers “not empty”; the tree may miss hidden names, deep levels, entries overmax_entriesand new files. localfsneedsallowed_roots(Backend::link_options: bootstrap params besideconnections, set by the admin; checked bystore::validate::<B>inwyrmdand on start). Empty = no directory;/proc,/sys,/devnever;Backend::check_place(data_dir, options)also runs before every probe. Built-in roles withconfigondownstream/**(engineer) can no longer point it at any host path.- Bounded concurrency. One tree read per connection (
busyotherwise), two transfers per connection; upload bytes are taken out of the args, not copied. - One hung call per connection (
localfsGate): while a timed-out blocking call still runs, new calls answertimeoutat once. - Files by their real name (
View::child_named): Overwrite never patches another file whose path form is the same (Drivea/b.txtvsa_b.txt); an entry a request made whose path another id holds gets the id in its path; Drive lists byname,createdTimeand gives a duplicate of a suffixed path the whole id. - An older read never undoes an action (
View::gen/touched): entries an action created or deleted after a read started are left as the action made them. - Smaller: a failed
create_newwrite removes only the file it made; hidden names are not written while not shown; the temporary name is short and keeps the old permissions; more Windows reserved names;refresh_s0 or ≥ 5; a short Drive token life is renewed halfway; a header that cannot be set fails the request (never sent unauthenticated); WebDAV bearer tokens checked; names a store sends that are./../empty/control are left out; a stored connection the link cannot show is skipped, not the link. - Actions end with their connection (review item 7, done after the first round): Stop, Remove, Edit and the link’s stop cut every action in flight at its next await (
Session::close→stopped); the caller getsdisconnected, and nothing more of it reaches the store (a recursive S3 delete stops before the next key). A blockinglocalfscall already in the kernel still ends there. - Still open:
localfsresolve-then-act races on shared mounts (openat2(RESOLVE_BENEATH)/O_NOFOLLOWare Linux-only and not used).
Amendment 2026-10-31 — second review of gencto/wyrm#7 (owner)
- A root that does not exist yet is resolved through its existing part (
localfs::resolve: the longest existing ancestor canonicalized, the rest appended), also forallowed_rootsand the broker’s data directory. Before, a missing root kept its raw path, soallowed/link/.sshwithcreate_root(whereallowed/linkleads out) passed the check andcreate_dir_allfollowed the link out. The probe checks the place again on the root as it resolves aftercreate_dir_all, then pins it; every change refuses a root that no longer resolves to the pinned path (a root swapped for a link after the probe) and makes the probe run again. On macOS (/var→/private/var) the check now compares resolved paths on both sides. Backend::check_placeis async;localfsruns it on the blocking pool behind itsGate, so a hung mount never blocks a tokio worker. TheGate’s count is kept per directory for the life of the process (Gate::for_root): Stop and Start or an Edit no longer forget a call that still hangs.- Overwrite temporary file: named from per-process random hash keys (not guessable), removed only when this upload made it (
write_new), permission bits copied asmode & 0o777. - WebDAV delete without
recursivefails closed: anyPROPFIND Depth: 1response but the collection itself, mapped or not, counts as content. - An id from a store’s answer is shortened by characters, not bytes.
- Still open: the limits on concurrent actions are per connection only (no link-wide bound;
create_folderanddeleteunbounded); a narrowedallowed_rootstakes effect on the link’s restart (noreconfigure).
ADR 0028 — File transfers in parts (file store links)
Status: accepted · 2026-10-31 (owner request: files of 1 GB and more through the brokers and the file store links of ADR 0027).
Context
ADR 0027 moves a file as one action: upload takes it as one argument, download returns it as one reply. Every hop holds it whole (the args, the Zenoh query, the HTTP body to the store), so the links cap uploads at 64 MiB (the gateway’s POST /api/invoke body) and downloads at 16 MiB. A file of 1 GB would take several times its size in memory on a board with 2 GB, and one query of that size through a chain of brokers.
Decision
-
Uploads in parts, spooled on the link’s disk (
wyrm_filestore::parts). A folder’supload_begin {name, size, part_size?, content_type?, overwrite?, sha256?}(level write) answers{upload, part_size, parts}. The connection’supload_part {upload, index, data}writes one part at its offset into a sparse spool file (<data_dir>/uploads/c-<conn>/<id>.part, 0700; the prefix keeps a connection named.or..belowuploads). Parts may come in any order, and again after a cut;upload_status {upload}lists the missing ones (at most 1000).upload_commit {upload}answerscommittingat once and sends the spool file to the store in the background (a large file takes longer than a request may wait);upload_statusthen saysdonewith the Upload File answer, orfailedwith why.upload_abortdrops it. Parts are 64 KiB … 16 MiB (default 4 MiB); a file is at mostmax_file_mib(default 4 GiB, at most 1 TiB). -
To the store as it is read:
Backend::put_file(parent, name, src, size, …):- S3: CreateMultipartUpload, parts of
multipart_mib(default 16 MiB, at least 5 MiB, larger for files over 10 000 parts), CompleteMultipartUpload withIf-None-Match: *unless it overwrites, AbortMultipartUpload on a failure. - Drive: a resumable session (
uploadType=resumable, PATCH to replace), chunks ofupload_chunk_kib(a multiple of 256 KiB) withContent-Range, resumed from Drive’sRangeon 308. The session URL must be on the API’s origin. - WebDAV: one
PUTwhose body is streamed from the spool file (http::Request::file_body). - localfs: a copy from the spool file, through the same temporary file and rename as an overwrite.
One part (S3, Drive) or one 256 KiB read buffer (WebDAV, the HTTP client) is in memory at a time.
- S3: CreateMultipartUpload, parts of
-
Downloads in parts: a file’s
download_part {offset, length?}(level read, length ≤ 16 MiB, default 4 MiB) answers{data, offset, size, eof}, throughBackend::get_range: an HTTPRangerequest (S3, Drive, WebDAV; a store that ignoresRangefor an offset past 0 is refused rather than read whole), a seek and a read (localfs). -
Ownership and bounds. An upload belongs to the
ptoksubject that began it: another subject’s request answersnot_found. At most 4 uploads hold a spool file per connection (receiving, committing, or failed and kept for another commit; counted and taken under one lock), so the spool is at most 4 ×max_file_mib; parts, downloads and commits share the connection’s two transfer slots. An upload idle for an hour is dropped with its spool file; so are all of a connection’s when it stops or is edited, and all spool files on the link’s start. Asha256given at begin is checked before the file goes to the store. -
Same path through the brokers: each part is an ordinary action, so a chain of brokers carries it as any other (one query per part, at most 16 MiB). A client sends parts through the gateway’s
POST /api/invoke(a WebSocket frame holds 64 KiB).
Consequences
- Memory no longer grows with the file: a 512 MiB transfer in parts of 8 MiB (debug build, the link, the client and Zenoh in one process) peaked at 133 MiB of resident memory.
- The link’s disk holds a file in progress whole (sparse at first);
max_file_mibbounds it, andupload_beginrefuses a file larger than the free space of the spool’s disk minus 1 GiB (resource_exhausted), checked again at each part for the bytes still to come (ADR 0029, decision 11). - A connection’s uploads in progress are lost when it stops or the link restarts (the spool is not kept; the client begins again).
- Not done: presigned URLs (bytes past the brokers when a client can reach the store); a server-side copy between connections; a hash of a download (the client checks it against the store’s
etagwhere that is a digest).
Alternatives
- Parts straight to the store at each
upload_part(S3 parts, Drive chunks): no spool, but parts must come in order for Drive and WebDAV, S3 parts must be at least 5 MiB, and a retry from the client has to match the store’s rules. The spool takes parts in any order for every store. - A stream action for downloads: one request, but a stream reply cannot be resumed at an offset after a cut, and the gateway’s HTTP invoke returns the last item only.
Amendment 2026-11-15 — parts through the user gateway
Found live: a restore of a 5.8 MB backup from Studio failed with SocketException: Write failed (Broken pipe), nothing in the broker log. A part (4 MiB by default, never under 64 KiB for a file store) does not fit a gateway WebSocket frame (64 KiB), so the Dart client sends it by POST /api/invoke. The gateway takes that route only for an action with an editor: "file" parameter (ADR 0011), and restore_part (ADR 0048 §3) and upload_part declared none: every part was refused with 400 takes no file. The client never saw the refusal: the gateway read at most 64 KiB of the body and closed, and Dart’s HttpClient writes the whole body before it reads the answer.
Decided (ADR 0029):
- The marker stays
editor: "file"(spec 02 unchanged: the value is the contents of a local file, and a part is a piece of one). Everybinaryparameter that can be larger than a frame carries it:restore_part.data, a connection’supload_part.data, the flow engine’sput_artifact.bytes,sys/profiles ▸ put.profile, asinstall_zip,install_wasm,install_backup, a folder’suploadand storageimportalready did. A generic action form shows a file picker for it. The gateway rule is unchanged: a large body only for an action that declares such a parameter. Astringormapargument (a branchimport,import_dsa, a flowdef) cannot take the route and stays within a frame; rule for link authors indocs/links.md§1. - A refusal reaches the client. A declared
Content-Lengthover the limit (64 MiB + 64 KiB) is answered 413 before anything is read. Any other refusal before the body is read (key, file parameter, level, step-up, the user’s upload in progress, both upload permits in use) is answered after the gateway reads and drops the body: at most the limit, within 120 s, one chunk in memory, at most 4 at once; the refused request holds neither the user’s upload slot nor a permit. With all 4 in use, or when the client sentExpect: 100-continue(it reads the answer first), the body is not read. An unauthenticated request is not read either: a client whose session ended can still see a reset, and the Dart client then throws aWyrmException(disconnected, “the gateway closed the connection while <action> sent <n> bytes …”) instead of aSocketException. - Tests:
wyrm-gatewayhttp_invoke_takes_large_arguments(a 4 MiB refused body gives 400 and the text, 403 before 4 MiB are taken, a 4 MiB upload after them, 413 by the declared length),wyrmde2euploads_in_parts_through_the_gateway(a backup read through the gateway,restore_begin+restore_partbyPOST /api/invoke+restore_check;upload_begin+upload_part+upload_committo a localfs store), Dartbulk_invoke_test.dartand the gateway e2e case of a 4 MiB refusal.
Amendment 2026-11-15 (2) — the Rust client and large text arguments
After #99 the Rust client (wyrm-gateway-client: wyrm-agent, the MCP connector wyrm-mcp --gateway, wyr probe) still sent every invoke in a frame: an argument over 64 KiB closed its socket. Decided (ADR 0029):
- The Rust client takes the route as the Dart client does.
Conn::invokesends encodedargsover 60 KiB (MAX_FRAME_ARGS) byPOST /api/invokeon the endpoint and session of its login, with the same TLS roots, and smaller ones in a frame. It sendsExpect: 100-continueand the body only after100 Continue(or after 10 s without an interim answer, RFC 9110): the gateway checks the session, the key, the file parameter, the level and the step-up before it reads the body, so every refusal (also 401 for a session that ended, which the gateway never drains) comes back before the body goes, asError::Refused {status, message, http}with the gateway’s text. Timeouts: 15 s for the head, 125 s for the body, 185 s for the answer. Over 64 MiB + 64 KiB (MAX_INVOKE_BODY, the gateway’s value; a gateway test asserts both limits are the same) it refuses withError::TooLargebefore anything is sent. - No frame over 64 KiB leaves the client. A
set,check,historyor any other request overMAX_FRAMEisError::TooLargeat once: the gateway would close the socket and every stream on it. The MCP dry run does not ask the link’s check for such arguments (“not asked …; checked against ~meta only”); the call itself goes by the route. AConn::from_rawconnection (the gateway’s own/mcp, in process) has no HTTP route: an invoke over 60 KiB isTooLargethere. - A large
stringormapargument has no route; the limit stays. A branchimport {json},import_dsa {json}, a flowdef(deploy,validate,put_block) and a storagepublishvalue must fit 60 KiB. They are not markededitor: file: spec 02 makes that abinaryparameter with a file’s bytes, and none of them is one. They get no file form now: a large tree goes as several branches (exported and imported one connection or one device at a time), and storage values stop at 32 KiB. The gateway’s refusal says what to do: “<action> takes no file: invoke it over the WebSocket, with arguments under 60 KiB; only a parameter witheditor: filetakes more”. When a real case needs more, that action gets abinaryeditor: fileparameter beside the text one, as storageimport {data | file}has; the gateway and the clients need no change. wyrm-agent invoketakes--args-file <path>and--file <param>=<path>(the bytes of a file as a binary parameter, at most 64 MiB + 64 KiB).- Tests:
wyrm-gatewayrust_client_sends_large_arguments_by_http(frame and route give the same result up to 4 MiB; a non-file action’s 4 MiB refused with the text; 403 for a viewer;TooLargeover the limit and for aset/checkover a frame, the socket still open; 401 with “log in again” after the user is disabled),wyrm-mcpa_large_file_argument_goes_by_http(300 KiB$bytesover TLS with--gateway-ca, the dry run, a text argument refused),wyrmde2euploads_in_parts_through_the_gateway(nowrestore_partandupload_partby the Rust client, a 100 KiB storage value refused with the text),wyrm-agentinvoke_arguments_from_files.
ADR 0029 — Decisions delegated by the owner
Status: accepted · 2026-10-31 (owner: “my answers decide nothing; make the changes yourself and record each rule in the documentation”).
Context
Several questions stayed open in CLAUDE.md and in the notes of earlier work (ADR 0022, 0024, 0027, 0028, the Modbus parity plan). Most of them were already answered by the code; they were only not written down as decisions. The owner delegated them on 2026-10-31. This ADR records each one in one place, with what it costs if it is wrong. User guides carry the rules that users meet.
Decisions
1. Selector parameters are joined with &
Spec 01 writes key?param=value&…; a match value uses ; inside it (is:<code>;unit:°C). Zenoh 1.10 Parameters splits on ;, so every SDK reads the raw selector string and splits on & itself (checked through a router hop). No spec change.
If wrong: a client that builds selectors with Zenoh’s Parameters sends one long parameter; the responder answers invalid_message.
2. The requester sets the QoS of a request
A Zenoh reply takes the QoS of its query, so the requester chooses it: wyrm-client (and through it the gateway, the flow engine, the FFI and wyr) sends ~set and ~act/* queries with InteractiveHigh + Block + express, and ~meta/~val reads with the defaults of spec 05. A process link’s SDK does the same for its own requests. Spec 05’s QoS table describes the query; the responder does not set a reply QoS.
If wrong: a third-party client with default QoS gets its command replies at Data priority behind value traffic.
3. A ptok is used once per responder
Spec 04 0.2.11 states it: each responder remembers a token’s jti until its exp and refuses it a second time (permission_denied). The memory is per process and not kept across a restart, so after a restart a token seen before can be used again until its exp. The SDK refuses a token whose exp is more than 15 minutes ahead (MAX_TOKEN_TTL_S), which bounds that window. A full cache (65 536 tokens that have not expired) refuses new tokens until one expires rather than forgetting one.
Amended 2026-11-01 (spec 04 0.2.12, security review): the responder remembers a jti only after it found a grant for the request key, and one sub holds at most a quarter of the cache (16 384 tokens). Without this, any caller with a valid signature could fill the cache with tokens for keys it has no rights on and lock every writer out of a link for 15 minutes. A caller that needs more than 16 384 live tokens on one responder (about 270 per second at the default 60 s lifetime) is refused until its tokens expire.
If wrong: a captured token replays once after a responder restart, within 15 minutes. TLS on every non-loopback hop makes capture the hard part.
4. The broker persists its own state with wyrm-state, not a Zenoh volume
The registry (links, grants, ACL inputs, peers, profiles pub/**, history watches, options), the gateway users, the flow definitions and their node state, broker storage and the historian are kept by their owners (WAL + postcard snapshot, or redb for storage and the historian). Zenoh’s storage manager keeps only wy/**/~val in memory (the last value for a late subscriber). The rocksdb volume is not used: it exists only as a dynamic .so, which principle 2 forbids.
If wrong: nothing is lost on restart that the owner of a key does not declare again; a ~val of a link appears again on its next sample.
5. Links are tested against their own simulators
Every protocol link has a simulator in its crate, and the tests run against it. No link has been checked against a real device or a third-party simulator (diagslave for Modbus) yet; the guides say so in their limits. This is a gap in evidence, not a decision to skip it.
6. rustls stays pinned at =0.23.45
zenoh-link-tls 1.10.1 reads and writes one TLS session from two tasks; rustls 0.23.46 checks the shared state on every write, and the race shows as SIGBUS or dropped TLS sessions. The pin is in the root Cargo.toml with the reason. Revisit it when Zenoh is upgraded (quarterly, with the fixture suite): drop the pin when the TLS link no longer shares one session between tasks.
If wrong: rustls fixes after 0.23.45 do not reach the broker until then.
7. Audit records sent during a reconnect can be lost
A link puts an audit record (sys/audit/<link>) at Background priority, without an acknowledgement. A record put while the link has no session to the router is dropped. The responder still refuses or answers the request as usual; only the record is missing. A resend needs an acknowledged audit path (a spec change); it is not done.
If wrong: the audit misses commands that ran during a broker restart or a network cut.
Added 2026-11-20 (audit write path, docs/backlog.md §14). The broker’s side of the same record: what a link put and the broker received is queued (at most 1024 records, the subscriber waits when the queue is full) and written by the journal’s one writer thread with the next batch, one fsync per batch. Nobody is answered for such a record, so a kill of the broker loses the ones still in the queue (before: the ones still in the subscriber’s queue); a stop writes them all. The broker’s own records are not in this class: Control::record returns after the fsync that covers the record. docs/operations.md §1 states both.
8. RUSTSEC-2023-0071 (rsa 0.9, Marvin timing) is accepted in links/opcua
async-opcua uses rsa for the RSA security policies of OPC UA, and no fixed rsa release exists. The attack needs many timed decryptions by the server under attack; the link is a client that decrypts only the server’s replies to its own session. docs/opcua.md states it.
If wrong: an attacker who can time many of the link’s decryptions on the network could recover a session key.
9. Modbus residuals stay as built
- A
~setwaits behind a running read action (read_registers,scan_units) on the same connection for at most the driver timeout (5 s) and may answertimeout(Modbus parity plan, ruling P33;docs/modbus.md). ip_slavebinds its port when the connection starts. If the router still holds the port during a rebuild, the connection goesFailedand retries with backoff (finding M8): no separate wait is added.- A slave answers exception 0x04 for a register whose bits the tree has not set yet, never a made-up 0 (rulings P24, P28).
10. A scheduler target writes only within its author’s rights
Defining or changing a target stays a config action (ADR 0022, ruling 6). The scheduler now also keeps the author’s auth grants (spec 04 0.2.10) with each target, as DQL does with a sink (ADR 0025 item 4), and refuses a target write outside them when it fires. A target stored before this change has no author grants and is refused until a user with config edits it again.
If wrong: a target that worked before stops until it is edited once.
11. File stores: the low items of ADR 0027/0028 are closed
- A connection name
.or..is refused (invalid_message). - A
206reply must carry aContent-Rangethat starts at the asked offset; otherwise the part is refused, not used. - A
416reply for an offset at or past the end of a file answers{data: [], eof: true}with the size fromContent-Range: bytes */<size>. upload_beginrefuses a file larger than the free space of the link’s disk (minus 1 GiB), checked again at each part.- Spool cleanup runs on the blocking pool, not on a tokio worker.
- An S3 multipart upload cut by Stop or Edit is aborted (AbortMultipartUpload) before the connection closes.
12. An unknown level code in a stored role grant refuses the users store
Added 2026-11-15 (typing audit). The gateway users store keeps each runtime role grant as a typed RoleGrant { key, perm: Perm }, on disk in the layout it had as (String, u8) (so SCHEMA stays 5 and older stores open unchanged). A level code that this build does not know is a decode error of the WAL record and of the snapshot: the store does not open, and the gateway, so wyrmd, does not start; the error names the key and the code. It is never read with the grant dropped, and the role never gets “no grants” either: grants match first-intersect (ADR 0031), so a dropped restricting grant before a broad one widens access, and a silently emptied role would hide the problem until a user notices. Replay already refused such a code through apply; only a snapshot loaded it. The code can come only from a newer WYRM (a downgrade) or a restore from one: go back to that version, or remove the role’s runtime grants with it, before downgrading.
If wrong: a downgrade over a store that a newer version wrote with a new level stops the broker at start instead of starting with that role reduced.
13. A history selector names each parameter once
Added 2026-11-15 (typing audit, spec 01 0.2.35). The historian parses a ~val?history= selector into the typed wyrm_core::history::HistoryQuery that requesters encode, and refuses history with since, a parameter given twice, and any parameter other than history, since, agg, window, limit (invalid_parameter). Names that start with _ belong to Zenoh and are skipped, so a Zenoh option on the query never breaks a read. A selector without history or since stays the storage’s, whatever else it carries.
If wrong: a third-party client that adds its own parameter to a history read gets invalid_parameter.
14. An agent task of an unknown state is kept, not loaded
Added 2026-11-16 (owner decision, typing audit of #127, commit b961157c). The agent link keeps each task’s state by its name as OrUnknown<TaskState> (links/agent/src/store.rs). A name this build does not know (a newer build wrote it) does not refuse the whole task store, as a closed set otherwise would (item 12): only that task is not loaded. It is logged, its id stays taken, and its record stays as written, byte for byte, through reloads, compaction and later writes, so the build that wrote it reads it again. A task is one operator request, not a grant: dropping it from the running set narrows nothing and widens nothing. This is the one closed set that tolerates an unknown value; every other one refuses it (docs/rust-rules.md §6).
If wrong: after a downgrade, a task a newer build made is not listed until the newer build runs again.
Not decided here
- New framework hooks that links asked for (per-point quality,
poll_periodwith connection and device params, the sample time from the driver,~metafrom device data, a driver-owned connection leaf) are work items indocs/backlog.md, not decisions. - The
wyrm:appworld after 0.2.0 (TLS imports, a host random source) gets its own ADR.
ADR 0030 — World wyrm:app@0.3.0: TLS and a random source for WASM apps
Status: accepted · 2026-11-01 (decisions of 2026-11-01: a new world beside the frozen ones, the three imports, the bound on random bytes, the manifest world with its version, the SCRAM nonce from the host, the packages rebuilt as 0.3.0, an e2e through an installed package).
Context
Host::tls_connect and Host::tls_upgrade exist in wyrm-link-api since ADR 0026. The native and process hosts (wyrm-link-portable) have them. The WIT worlds wyrm:app@0.1.0 and @0.2.0 have no such imports, and both are frozen. So a WASM component answers not_supported to TLS. The history sync packages (postgres, mysql, mongodb, influxdb, dynamodb) are WASM packages by default, so they reached only plain databases.
A component also has no random source. The SCRAM nonce of PostgreSQL and MongoDB is hashed from the clock, a counter and the connection: unique, but guessable.
Decision
-
A new world
wyrm:app@0.3.0(crates/wyrm-wasm-host/wit/app3/app.wit). It is 0.2.0 with every function and export unchanged, plus three host imports:tls-connect(host, port, timeout-ms, ca-pem?) -> result<u32, list<u8>>;tls-upgrade(conn, host, timeout-ms, ca-pem?) -> result<_, list<u8>>;random-bytes(n) -> result<list<u8>, list<u8>>.
Errors are CBOR
{status, msg}, as in the other imports. -
0.1.0 and 0.2.0 stay frozen. The host links all three versions. 0.3.0 has the exports of 0.2.0, so the host tells it by its import
wyrm:app/host@0.3.0(AppWorld::pre,app_version). A component that imports no host function is told by its exports, as before. Awyrm:app/hostversion that the host does not run is refused at load (Denied). -
The same services in every mode. The WASM host forwards the three imports to the
BufferHostof the call, and so to theRuntimeServicesthat the native engine uses. Thenetallowlist (NetPolicy::allows_named), the time budget of the call, the 4 connections and the host-name rules of ADR 0026 are therefore the same. An address outsidenetgivespermission_denied, as fortcp-connect. The keys stay in the host: the guest sees a connection id and plain bytes throughtcp-send/tcp-recv. -
Random bytes.
Host::random_bytes(n)andServices::random_bytes(n), with a defaultnot_supported.BufferHostrefusesnaboveMAX_RANDOM_BYTES(1024) withinvalid_parameter, before the services see it.RuntimeServicesfills the bytes from the OS (getrandom, already in the workspace). -
The SCRAM nonce (
wyrm_history_sync::scram::nonce(host, conn)) takesrandom_bytes(18). Only a host without a random source (not_supported: a component of 0.2.0, a test host) falls back to the clock hash (nonce_from_clock). A host that has one and fails, or answers fewer bytes, fails the login withRetry(amended 2026-11-15, audit of #125: any error fell back to the clock before). -
The guest and the packages.
wyrm-link-guestbuilds components of 0.3.0, so the scheduler, DQL, the five history sync links andexamples/links/portablebuild as 0.3.0.wyr link packwrites the version into the manifest:world: "wyrm:app@0.3.0". The broker checks a versionedworldagainst the component’s version. A plainappstill takes any version, so old packages install as before.
Consequences
- A WASM history sync package reaches a TLS database through the same host code as its process twin.
- SCRAM nonces in every mode built since this ADR come from the OS.
- A package built for 0.2.0 keeps working, but has no TLS. It must be rebuilt to get it. Its manifest may say
apporwyrm:app@0.2.0. - A broker older than this ADR refuses a manifest that says
wyrm:app@0.3.0(an unknown world). It could not run such a component anyway. - Tests:
every_app_world_version_loadsandan_unknown_app_world_version_is_refused(wyrm-wasm-host),tls_and_random_as_native(links/wasm: the same component and native app against a local TLS server),wasm_app_world_0_3_0_has_tls_and_random(wyrmde2e: an app package built from source and installed from Zip).
Alternatives
- Change 0.2.0 in place. Components built on 0.2.0 import the old interface; a changed 0.2.0 would refuse them or make two different 0.2.0 worlds. Refused.
- WASI (
wasi:sockets,wasi:random). A second, larger import surface besidewyrm:app/host, and TLS would then live in the guest with its keys. Refused: the host already has rustls and the allowlist. - Randomness in the guest (a seeded generator). The seed would still come from the clock. Refused.
ADR 0032 — Logic blocks in the flow engine
Status: accepted · 2026-11-01 (owner: a server-side list of blocks like the editor prototype’s; decided under ADR 0029).
Context
The owner keeps a Dart prototype of a block editor with its own engine (not in this repository). Its blocks are variables, arithmetic, if, hub, stopwatch, trace and text blocks. The flow engine (wyrm-flow, spec 06) had expression, scale, window and other node types, but not these. The owner asked for the same list on the server.
The prototype binds an input to an output by a path stored on the input. The flow engine sends samples on edges between ports. The blocks follow the engine’s model.
Decision
- One module,
wyrm_flow::blocks. Types:number,string,bool,add,subtract,multiply,divide,max,min,abs,round,modulo,not,if,hub,stopwatch,trace,concat,length.nodes::portsandnodes::buildask it first. The catalog lists them for the editor. - A parameter is config and, where it makes sense, a port. The value comes from the config or its default; a sample on
in.<parameter>replaces it. Variable inputs are the config listinputs(default0,1, at most 64), portsin.<name>; a name may not be a parameter’s. - Names are snake_case, as every other node type’s (
input_min,reset_value,ignore_null,on_change,on_loop). The prototype’s camelCase names are not taken. - Change-only outputs, by value and quality. A good-to-bad change of the same value goes out (honest quality). Events always go out, as
{event, id}. - Operators do not calculate at start. Only the variables send at start. A deploy, a hot swap or a restart never fires a command by itself. The prototype calculates every block when it is attached; the engine does not.
- Numbers as in the prototype where it matters: integers stay integers while they fit,
dividegives a float, non-finite results arenull,modulo’s quotient goes toward 0 and its remainder is never negative,roundto 0 places gives an integer. scalekeeps its meaning.k × in + bstays; the range form (input_min…output_max, outputinput_out_of_range) applies only once a range parameter is set or arrives. An existingscalewith no config stays the identity.stopwatchruns on a 50 ms clock (the runtime readstick_everyonce), counts at most every 0.05 s, and keeps its count across a hot swap.tracelogs attraceonly: its lines hold values.- The editor draws fixed ports and named ports together (
if:in.then,in.else, thenin.0, …);dyn_inputsadds toinputsinstead of replacing it. - Texts a block makes are at most 4 KiB (
concat,string), as the expression engine’s strings; a longer one isnull(concat: qualitybad). Aconcatin a loop through adelaywould otherwise grow without end (automated review ofe89b1d4).
Amended 2026-11-11 (spec 06 0.2.30, owner’s screenshots of the flow editor). A block whose
inputs are all typed constants showed nothing: add of 2 and 3, a CSV typed into
table_from_csv, a now with no wire. Since ADR 0040 the runtime marks a sample born at the
start, so the rule is narrowed, not dropped: a pure block (no state, no events, no clock of
its own; 83 types, listed in docs/flow-blocks.md “What calculates at start”) with no edge
into any of its ports calculates once at start from its constants and parameters. What it
sends is made of constants (Msg::constant): born at the start, carried on by the runtime
like that mark, and it runs no command anywhere, not even through in of set or invoke. A
block with a wired input waits for its first sample, as before; the blocks after a pure one
calculate from its start sample. A deploy, a hot swap or a restart still never fires a command
through a constant. A variable wired to in of a command still writes at deploy (ADR 0038 §6):
changing that would change deployed flows.
If wrong: a flow that expects an operator’s value right after deploy must start from a variable or a const; a block that should send every sample (not only changes) needs a filter or an expression in front of its sink.
Found on the way
publish, set and invoke started one task per sample, so two samples close together could be written in the other order: a published value could end on the older one, and a set could leave a device at the older value (true then false arriving as false then true). Each of these nodes now has one writer task: publish and invoke keep the order (a queue of 256; more are dropped and logged at debug), set writes the newest value (older ones not yet written are skipped). The test logic_blocks_in_a_deployed_flow failed 5 times in 6 before this.
Not done
The prototype’s own editor protocol (binding paths, its save format) is not taken: flows stay spec 06 definitions. Further block types come as the owner names them.
ADR 0033 — wyrm-agent: a command line for operators and AI assistants
Status: accepted · 2026-11-01 (owner: “the agent is what you run locally from the CLI to do things: a tool for you”).
Context
The agent driver (ADR 0005) is an LLM inside the broker. The owner wants a tool that an AI assistant working on a workstation (Claude Code) runs to work on the broker network: create a device through the nodes’ actions, set up history and upstream storage, deploy a dataflow that transforms points and writes a control value to another link. wyr talks Zenoh with an admin key; the demo’s sites have none, and a key is the wrong identity for a person or an assistant. wyrm-mcp serves MCP clients over stdio.
Decision
wyrm-agentis a binary oflinks/agent(featurecli). It logs in to a gateway as a user and uses its WebSocket (wyrm-gateway-client). The user’s role decides everything; the gateway reaches downstream sites, so one gateway drives a chain of brokers.- JSON lines out, so an assistant reads the answers without parsing text.
- Plans:
run <plan>checks each step against the live~meta(action, argument schema, value bounds, throughwyrm_mcp::check) and prints what it would do;--applyruns the steps in order and stops at the first failure. A step on a node an earlier step creates is checked when it runs.unlessmakes a plan safe to run again;deployraises the flow’s version itself;waitandexpectlet a plan prove its own result. - The password only from the environment (
WYR_GATEWAY_PASSWORD), never an argument. - Skill
.claude/skills/wyrm-agenttells an assistant in this repository how to use it.
Found on the way
A flow deployed from an upstream site with a command target was refused: the deploy request itself was trusted (upstream keys, ADR 0018), but the engine checked the deployer’s proofs with the admin keys only. The proofs of targets are now checked with the upstream keys as the links and storage trust them (EngineStart::proof_keys). e2e chain_of_three_brokers deploys such a flow from central.
A second refusal followed once the flow had a source: the engine knew an upstream key with the scope dataflows only, so the deployer’s auth lost its grants on downstream and the source check (ADR 0031) refused. The engine now knows the upstream keys also with the scopes downstream and storage give them; a request to the engine is still authorized within dataflows only, and only the deployer’s rights on sources and targets are kept. The e2e flow has a source too.
The third and last: central’s gateway added the proofs of a deploy only for its own site (wy/central/dataflows), so a deploy on wy/edge/dataflows arrived without proofs. It now adds them for a site below too, with that site’s targets. e2e chain_of_three_brokers deploys through central’s gateway as a user (it timed out before).
If wrong: nothing is widened: a proof still has to be a token of the same subject at the flow’s maxperm on that exact target, from a key the target itself trusts.
ADR 0034 — Alarm link: broker-side alarms, records that survive, export through the history sync links
Status: accepted · 2026-11-04, built (owner request: an alarm link for the broker, better than the DSA reference in performance and in how it keeps its data; keep the records in the broker’s own store, send them on through the database links that exist already; run in every mode as the scheduler does). Built as a portable App (ADR 0023): links/alarm; user guide docs/alarm.md.
Context
Sites need alarms on the broker: a point out of range, a boolean that says “fault”, a device that stopped sending, a sample of bad quality. People acknowledge them, add notes and look back over a time range; a central database wants the same records. The owner’s reference is DSA dslink-java-alarm (IOT-DSA, read 2026-11-04). Kept from it: alarm classes; watches on source points with an algorithm (Boolean, Out Of Range, Staleness) that creates an alarm record; alarm types alert, warning, fault; a record’s life — created, back to normal, acknowledged (by whom and when), closed when both; inhibit times before an alarm and before a return to normal; two escalation levels on records nobody acknowledged; notes on records; Get Alarms over a time range, open alarms, acknowledge all; an alarm database with providers. Not kept, because they are its defects (read in the source):
- the records live in a database inside the link (H2 or another JDBC database through a provider), a second store beside the broker’s own, with its own files, locks and upgrades; sending records to a central database means swapping that provider, so the local copy is gone;
- the alarm streams (open alarms, escalations, return to normal) poll the database every few seconds for every client holding them, so the load grows with clients and never reaches zero at idle;
- staleness is a timer per watch and the escalations a sweep of every open record, both on their own threads;
- the watches and classes are node configs written back to
nodes.jsonby the SDK’s periodic save, so an edit can be lost by a crash in the minute after it; - nothing is bounded: open records, the rows of Get Alarms, the records a class holds in memory;
- anyone who reaches the link acknowledges any record; nothing of the caller’s rights on the source point is checked.
What WYRM has that the link can use: a portable App with a sealed host store that survives restarts (ADR 0023), one subscription for a whole subtree (<prefix>/**, ADR 0025), the caller’s rights in the token of an action (auth, spec 04 0.2.10, ADR 0029), and five history sync links that pull rows from a sink with next {after, max} and write them, replacing on (key, t), to MySQL, MongoDB, PostgreSQL, InfluxDB and DynamoDB (ADR 0026).
Goals
- An alarm comes from the live tree (a watch’s condition) or from a caller (
raise: a dataflow’sinvokesink, the agent, a person); the record is on disk before the event that made it ends. - After a restart the state follows from the records and the first samples: an open record stays open, a watched point that is normal on its first sample closes it; nothing missed is replayed.
- Bounded: nodes, subscriptions, open records, records on disk, rows per answer, work per event; zero messages at idle.
- Records go to a central database through the history sync links as they are, with no new protocol: the alarm link is a sink with the same
nextas the historian’s. - A watch sees only what its author may read; a reader sees only the records of sources they may read; every acknowledgement names its subject.
- One core in three modes (embedded, process, WASM), as the scheduler.
Non-goals
- Alarm routing to e-mail, SMS, chat: a later link or a dataflow on the class’s
alarmstable. - Expressions as conditions (CEL as in DQL): later; the four algorithms cover the DSA link.
- Records as nodes: thousands of records would exhaust the node budget; they are rows of actions and of one table value per class.
Anti-goals (a failure even if it works)
- A record accepted and lost (a crash after the reply, a store that refused the write unnoticed).
- A storm of alarms (a PLC off: every point bad) that stalls the link or the router.
- A reader who may not read a point learning its alarms.
Decision
Model (crate links/alarm, an App on wyrm-link-api; no clock, no I/O of its own)
- Class:
id(key segment),display,escalation1_s,escalation2_s(0 = off),created_by, its watches. - Watch:
id(w<n>, never reused),source(a keywy/<site>/<section>/…, or<prefix>/**for every value under it),algorithm, its parameters,type(alert | warning | fault),message(a template:{source},{name},{value},{quality}),to_alarm_s,to_normal_s,enabled,created_by, the author’s rights (Rights, ADR 0029). - Algorithms:
boolean: in alarm while the value equalsalarm_value(defaulttrue; a number istruewhen not 0, texttrue/false);out_of_range: in alarm while the value is belowminor abovemax(either may be absent); back to normal only inside bydeadband(hysteresis; a value that is not a number is ignored);staleness: in alarm when no sample came forstale_s; the next sample ends it;quality: in alarm while the sample’s quality isbad, or alsouncertainwithinclude_uncertain.
- Record:
id(one counter for the link, never reused),class,watch(none forraise),source,type,message,value(the sample that raised it, scalars only),created,normal,ack,ack_by,escalation(0, 1, 2),notes(≤ 20 of ≤ 1 KiB, each with time and subject). Open = active (nonormal) or unacknowledged; closed = both set. A watched point with an open active record raises no second one; after its record is normal, the next alarm is a new record (DSA’s rule). - Inhibit: a condition must hold
to_alarm_sbefore a record is made and be goneto_normal_sbefore the record is normal; a flip in between cancels the wait. Instants come from the host’s wall clock at the sample’s arrival, not from the sample’st(links stamp samples on their own clocks). - Escalation: a record unacknowledged
escalation1_safter it was created is at level 1,escalation2_safter it at level 2 (a journal entry each, so sinks see it); an acknowledgement ends the wait. - Bounds (constants of
links/alarm::limits, one place each, refused withresource_exhaustedbefore the host would fail the event): 9 500 nodes; 200 classes; 500 watches per class and 1 000 in all (one subscription each; a subtree watch keeps state for at most 2 000 keys, beyond which its node showserror); 10 000 open records (over it, the oldest record that is normal but unacknowledged is acknowledged bysystem:overflow, so a storm cannot grow without end; with none such, the record is still made: an active alarm is real); 800 commands and 500 ms of batched work per event, the rest in0ms timer events (ADR 0022 ruling 5); 5 000 rows per answer.
Store (the host store, ADR 0023: at most 10 000 keys, 64 MiB embedded)
A record is not a key: a store of 10 000 keys cannot hold one per record, and a value of thousands of records cannot be rewritten on each change. So:
index: the class ids;c/<class>: the class with its watches (CBOR), written in the event that accepts the edit.p/<n>: pagenof records, ids64n … 64n+63(CBOR array). Ids grow with time, so a page is found by its ids and a time range by a binary search on the pages’ first records (≤ 12 reads for 4 096 pages). A record changes (normal, acknowledged, a note, an escalation) by rewriting its page: a page is at most about 64 × 400 B.open: the ids of the open records (one array; at most 10 000 ids, so about 50 KiB), rewritten when a record opens or closes. At start the open records are read from it; closed records stay on disk only.j/<n>: journal pagen, the ids of the records that changed, entryseq = 256n + i(CBOR array). Every creation and change appends one entry; sinks read from a cursor onseq. At most 400 pages (102 400 entries): older pages go, confirmed or not, and what a sink has not confirmed of them is counted on it (dropped_unsent), as the historian does (ADR 0026, owner decision 1). The journal is written whether a sink exists or not, so a sink added later (from: start) takes the records of the last 102 400 changes.sinks: the sink definitions with their cursors (one map; a cursor moves with every batch).meta:first_page,first_jpage(the oldest pages kept) andpage_hint,jpage_hint(the newest pages made, written when a page begins); the next record id and journal number follow from the last page after each hint (pages are contiguous), sometais not written per record and a crash between a page andmetaloses nothing. After a purge of every page the ids go on after the pages that went (first_page × 64).- Retention:
retention_days(365) andmax_records(100 000) are link params; once a day (and at start) the oldest pages whose every record is closed go while they are older than the retention or the store holds more than the maximum; a page with an open record stays, as DSA never deletes an open alarm.purge {before}(config) removes closed records before an instant. - A write the store refuses fails the action with
resource_exhaustedand leaves the state as before; for a record made from a sample it is logged aterrorand the record is dropped (counted instats/dropped): nothing is half-saved.
Sinks: the records go out through the history sync links (goal 4)
sinks/<name>on the link, added withadd_sink {name, link, classes?, from: start | now}(config): the link id that reads it (it signs aslink:<id>with its requester key), the classes it takes (empty = all), and where its cursor starts. Its node’s value isconfirmed_seq; attributeslink,classes,lag_entries,rows_sent,dropped_unsent,last_request. Actionsnext {after?, max?}(read; refused for any subject butlink:<its link>: a person who ran it would confirm rows the database never got),edit,reset {from},remove(config).nextanswers exactly assys/history/sinks/<name>does:{rows: [{seq, key, t, v, q}], next},afterconfirms every entry up to it, at mostmax(≤ 5 000) rows and 1 MiB. A row is a record as the sync links already write it:key= the record’s source point,t= the record’screated,v= the record as JSON text (wyrm-alarm/1:{id, class, watch, source, type, message, value, created, normal, ack, ack_by, escalation, notes}),q=good. The SQL and InfluxDB targets refuse a map value (ADR 0026: a row is one scalar), so the text form is the one every target takes;(key, t)is unique for a record, so a change rewrites the same row in the database, and the central database ends with the record’s last state, as DSA’s alarm database does. A target made for alarms (columns per field) is a laterTargetofwyrm-history-sync; nothing here changes for it.wyrm-history-synctakes asinkparam of either shape,wy/<site>/sys/history/sinks/<name>orwy/<site>/downstream/<link>/sinks/<name>; nothing else in it changes. A package link reaches the sink under an operator’s grant (sys/links/<id>/~act/grant,readon the sink’s key, ADR 0013); a sink’slinkmust be a link id, and the admin’s audit of thenextcall names it.
Rights (ADR 0022 ruling 6, ADR 0025 item 4, ADR 0029)
add_class, a class’sedit/remove,raise,acknowledge,normal,add_note,ack_all:write.get_alarms,get_alarm,get_notes, a class’sexport:read.add_watch, a watch’sedit/enable/disable/remove,import,add_sinkand the sink actions,purge:config(a watch subscribes a point; a sink confirms what left the site).- A watch keeps its author’s rights:
add_watchandimportrefuse a caller whose token carries noauth(DQL’s rule), refuse a source the author may notread, and keep the rights with the watch; a subtree watch drops the keys its author may not read. A watch keeps running after its author loses rights (as flows, schedules and queries). - A reader sees their own records:
get_alarms,get_alarm,get_notes,acknowledge,normal,add_noteandack_allcheck the caller’sauthforreadon the record’s source, and refuse a caller withoutauth(their rights are unknown).raiseneeds none beyondwriteon the link (a dataflow’s token carries noauth); itssourcemust be a key of this site’s tree. A class’s table value<class>/alarmsand the counters are for whoever may read those nodes (as a published DQL table): an engineer who gives a rolereadon the alarm link gives it the site’s alarms. - The embedded link reads
wy/<site>/downstream,dataflowsandstorage(ADR 0025 D4: not other sites in this version); it writes nothing, so links need not trust its key. Packages carry no grants: an operator grantsreadon each root.
Tree and actions
<link>/
add_class {id, display?, escalation1_s?, escalation2_s?} (write) -> {id}
raise {class, source, type?, message?} (write) -> {id} # a record no watch owns; `normal` ends it
acknowledge {id, note?} normal {id} add_note {id, note} ack_all {class?} (write)
get_alarm {id} -> map; get_notes {id} -> rows; (read)
get_alarms {timerange?, class?, source?, state?, type?, limit?} -> rows (read; newest first)
import {json, overwrite?} purge {before} add_sink {name, link, classes?, from?} (config)
stats/ open, active, unacked, records, watches, raised, dropped (values)
sinks/<s> value confirmed_seq; attrs link, classes, lag_entries, rows_sent, dropped_unsent,
last_request; next {after?, max?} (read, the sink's link only); edit, reset, remove (config)
<class>/ folder; attrs display, escalation1_s, escalation2_s, created_by;
add_watch (config); edit, remove, ack_all (write); export (read)
open, active, unacked counts (values)
alarms the open records, newest first, at most 200 rows, published when
they changed and at most every 500 ms
watches/<w> value: the state (normal | alarm | to_alarm | to_normal | disabled | error),
for a subtree watch `alarm` while any key is; attrs source, algorithm, type,
message, params, keys, in_alarm, last_change, last_record, error, created_by;
edit, enable, disable, remove (config)
A record’s state in answers: active (not normal, not acknowledged), acked (acknowledged, still active), normal (normal, not acknowledged), closed. get_alarms state filters open | active | unacked | closed | all (default open); timerange is <from>/<to> in RFC 3339 on created (default: the open records, any time).
The link
- One timer (as the scheduler): a min-heap of wakes — a watch’s inhibit end, a staleness deadline per key, a record’s escalations, the table publication, the daily purge — behind one host timer, at most 30 s ahead (the clock watchdog). A wall-clock step moves every wake by the step: inhibit and staleness are durations, not instants.
- Batched work:
startdeclares the root, reads the open records, then loads the classes and, after each, its watches (a class may hold 500) in batches within the event budget, the rest in0ms timer events; a storm of samples is one record per sample event (two or three store writes each: the page,open, the journal page), so the cost per alarm is bounded and no event grows with the number of alarms. Through an action an enum is given by its index (the SDK’s rule forenumparams, as the scheduler’sconfirm); in an import, by its name. - Restart: the classes and watches come from the store, the open records from
open; a watched point’s state starts as “record open” when an open active record names it, so its first normal sample closes it and its first alarm sample makes no second record; a staleness watch counts from the start. Manual records (raise) wait fornormal. - Run modes: embedded in
wyrmdatwy/<site>/downstream/alarm(alarm: { enabled: true, store_mb: 64 }; the id reserved likescheduleranddql; its store key and requester key made by the admin, R22 on failure); process packagealarm-process(wyrmd link alarm); WASM packagealarmon worldwyrm:app@0.3.0, store 16 MiB.
Consequences
- The id
alarmis reserved likestorage,scheduleranddql;wyrmd.json5gainsalarm. wyrm-history-syncaccepts a link’s sink as a source; the five database links take alarm records with no change of their own, as JSON text rows keyed by the source point and the creation time.- Spec 02 does not change (existing editors and value types).
- At the built-in links (scheduler, DQL, alarm, uplink) the keys the storage link and the flow engine trust (the gateway’s at config, the upstream brokers’ by
upstream_trust; not the flow or agent keys) are trusted on this site’sdataflowsandstoragetoo: the verifier caps a caller’sauthto its signer’s scopes, so a watch onstorage/…was refused (found on the demo, 2026-11-05). These links answer only underdownstream/<id>, so no request they accept widens. - A link grant at
readlets the router pass<path>/**/~act/next(a sink’snext) as well, assinks-<id>-indoes for the historian’s sinks; no other action, never~set(areadaction can still hand out data: a file store’s Download). Found on the demo (2026-11-05, Docker run with PostgreSQL): apostgres-processlink withreadonalarm/sinks/<name>could not reachnextthrough the router ACL, while a WASM package (in the broker’s process, no ACL) could. Decided under ADR 0029 and written intodocs/links.md§ 10. - Open items: an alarm target with one column per field (a
Targetofwyrm-history-syncfor the SQL links); CEL conditions (DQL’s bounded CEL); alarms over other sites’ points (ADR 0025 D4 grants); a probe run on the demo with a real database container.
ADR 0035 — Platform upstreams: live data to MQTT/UNS, Sparkplug B, ThingsBoard, Azure IoT Hub and AWS IoT Core
Status: proposed · 2026-11-04 (owner request: an extension that raises data to popular platforms, set up the way an upstream broker is (sys/upstream ▸ Add), several platforms at once).
Context
An upstream broker (ADR 0007, 0015, 0018) is added at runtime with one action (sys/upstream ▸ Add Upstream Connection {name, url, ca, token, enabled}) or in wyrmd.json5, and shows as sys/upstream/<site>/{url, status, enabled, …}. It carries the whole tree up to another WYRM broker over Zenoh. Sites also need their live values in the platforms the rest of the plant already uses: a Unified Namespace on an MQTT broker (HiveMQ, EMQX, Mosquitto), Ignition’s MQTT Engine and other Sparkplug B hosts, ThingsBoard, Azure IoT Hub, AWS IoT Core.
What exists: history sync (ADR 0026) sends the historian’s rows to databases in batches from a change journal, with a cursor, for watched points only, seconds behind. The mqtt link (links/mqtt) reads from an MQTT broker as a device driver. A portable App (ADR 0023, 0030) runs the same code embedded, as a process and as a WASM component, with tcp_connect/tls_connect under the link’s net allowlist, subtree subscriptions (<prefix>/**, ADR 0025), a sealed store and random_bytes.
Decision
- One portable App,
links/uplink, embedded atwy/<site>/downstream/uplinkin everywyrmd(uplink: {enabled, store_mb, net, upstreams}; id reserved asscheduleranddqlare; packagesuplink(WASM, worldwyrm:app@0.3.0) anduplink-processfor a broker that runs it elsewhere). It only reads:readon this site’sdownstream,dataflows,storageand on the sections of the downstream sites this broker reads (as the DQL link), neversys. It has no requester key use: nothing it does is a request to another link. - Set up as an upstream broker is. The link root has one Add action per platform (
add_mqtt,add_sparkplug,add_thingsboard,add_azure,add_aws), each withname,url,enabled, the keys to send (select) and the platform’s own fields;set_passwordkeeps the one secret (an MQTT password, a device access token, an Azure device key, an AWS secret key) in the link’s sealed store, never in a param (as history sync). Each upstream is a node<name>/{kind, url, status, error, enabled, connected_since, published, dropped, queued, last_publish}withedit,set_password,test_connection,remove;enabledis writable. Entries fromwyrmd.json5(uplink.upstreams) show withorigin: config, read-only but forset_password, assys/upstreamshows its config-file peers. Definitions live in the link’s store and come back after a restart; secrets with them. - What goes up: values, live. Each upstream names the keys it sends:
selectis a list of full node keys (wy/<site>/downstream/plc1,wy/<site>/storage); everything under each is sent as it changes, within the link’s grants. The link’s own subtree is never sent. Per pointmax_hz(0 = every change) keeps the latest value while the rate is over; a bounded queue per upstream (queue_max, default 10 000) drops the oldest when the platform is slower than the site and countsdropped. Delivery is live and at most once: the complement for completeness is a history sink (ADR 0026), which replays from the journal. - Formats, one engine. An MQTT 3.1.1 client of our own over the host’s TCP/TLS (CONNECT with username/password and a will, PUBLISH QoS 0 and 1 with a bounded window of unacknowledged packets, SUBSCRIBE, PINGREQ, a parser for CONNACK/PUBACK/SUBACK/PINGRESP/PUBLISH) serves four of the five platforms; AWS IoT Core goes over HTTPS.
mqtt(a UNS): topic<prefix>/<site>/<path>per point (the site’s name and the node path belowwy/<site>/), payload JSON{"v": …, "q": "<quality>", "t": <µs>}or the value alone (payload: value),retainon by default,qos0 or 1.sparkplug(Sparkplug B 3.0):spBv1.0/<group>/NBIRTH|NDATA|NDEATH/<edge node>andDBIRTH|DDATA|DDEATH/<device>; the edge node is the site (edge_node_id), a device is a link (downstream/<link>;dataflows,storageas devices of their own; another site’s link as<site>.<link>), a metric is the path below the device. Payloads encoded by a protobuf writer of ours (timestamp,metrics{name, timestamp, datatype, value},seq,bdSeq); numbers as Double, bools as Boolean, text as String;seq0..255;bdSeqfrom the store; NBIRTH on every connect with the metrics known so far, a DBIRTH again when a device gets a new metric; NDEATH as the will;Node Control/RebirthonNCMD(andDCMD) answered with a full rebirth.thingsboard: the gateway API over MQTT (username = the gateway’s access token):v1/gateway/connect {"device"}once per device per session,v1/gateway/telemetry {"<device>": [{"ts", "values": {<path>: v}}]}per flush; a device is a link, named<site>-<link>(device_prefixchanges the site part).azure: IoT Hub over MQTT with a SAS token from the device key (HMAC-SHA256,sr=<hub>/devices/<id>, renewed beforesas_ttl_sruns out by connecting again), username<hub>/<id>/?api-version=2021-04-12, topicdevices/<id>/messages/events/$.ct=application%2Fjson&$.ce=utf-8, payload a JSON array of{"key", "v", "q", "t"}per flush. X.509 devices wait for client certificates intls_connect.aws: IoT Core’s HTTPS publish (POST https://<endpoint>:8443/topics/<topic>?qos=1, Signature V4 foriotdatawith an access key id and the secret key from Set Password): one request per flush with a JSON array of samples to<topic>(default<prefix>/<site>). MQTT with mTLS waits for client certificates intls_connect.
- Flushing. One timer per upstream:
flush_ms(250 by default) while connected and anything is queued, a back-off (1 s ×2 up toretry_s) while it is not; a keep-alive ping at half the keep-alive. Each flush sends at most 64 KiB (the host’s bound per send) and reads what the platform sent back within the same event. A connection lost or a refused publish drops the connection, keeps the queue and connects again after the back-off; a refusal at CONNECT (bad credentials, not authorized) isfaileduntil Edit, Set Password or Resume. - Network. The embedded link’s
netcomes fromwyrmd.json5(uplink.net, ADR 0012 syntax:broker.example:8883, *.azure-devices.net:8883, 10.0.0.5:1883), as every portable link’s does: the app cannot widen it. An Add whose host no name or address entry covers is refused with the entry to add.
Consequences
- Amended 2026-11-05 (automated security review after the merge, decided under ADR 0029): an upstream keeps its author’s rights (
rights/<name>in the store,wyrm_link_api::Rights); Add and Edit refuse a token withoutauthand aselectoutside the caller’sread, and samples the author may not read are dropped, as DQL queries and alarm watches do. An Edit that moves the endpoint (host, port, TLS,insecure_plaintext,ca_pem) deletes the secret. - A site sends its live values to up to 16 platforms at once from one link, each with its own selection and rate; the same point may go to all of them.
- Values only. Meta (units, names) is not sent; a UNS consumer reads it from the broker or from the topic names. Sparkplug hosts get metric names and types.
- Live, at most once: a platform down for an hour misses that hour (the queue holds
queue_maxsamples, then drops the oldest). History sync (ADR 0026) is the path for complete data. - MQTT 3.1.1 only (no MQTT 5 properties); QoS 2 is not offered (Azure and AWS refuse it).
- No client certificates: AWS IoT Core goes over HTTPS, Azure needs SAS. A later world may add a client certificate to
tls_connect. - One more always-on in-process link with site-wide
read; nothing it does is a write. Off withuplink: {enabled: false}.
Alternatives
- A node under
sys/upstreamwith akind. An upstream broker is a peer with a CA, a certificate and an ACL subject; a platform upstream is a client with a secret. Mixing them would put platform clients into the admin actor (security review) and into the registry’s peer model. Refused; the root node is a link, as the scheduler and DQL are. - History sync targets for MQTT and the clouds. Complete and ordered, but seconds behind and only for watched points; a UNS needs the latest value as it changes. Both exist; a site uses either or both.
rumqttcor the AWS/Azure SDKs. Native crates would make the link process-only and pull in their own TLS and runtimes; the portable form needs a client over the host’s sockets, as history sync has for PostgreSQL and MongoDB.
ADR 0036 — Broker fault tolerance: supervised restart, endpoint lists with liveliness arbitration, warm standby by WAL replication
Status: accepted · 2026-11-05, built (options 1, 2 and 3 with stages A, B and C; amended 2026-11-08: lease arbiters, healed-split reports, history-sync cursors) (owner question: what can WYRM do for broker redundancy, what do the alternatives do, what does each option cost; owner choice: options 1 + 2 + 3 of the assessment below). Option 3 stages A and B done 2026-11-05, stage C 2026-11-06 (see “Built, stage A/B/C” under Decision). Option 2 done 2026-11-05: WYRM_ENDPOINT and wyrm_client::endpoint (wyr --connect, the FFI) take comma-separated lists; a link process opens one session per endpoint and serves a router only while wy/<site>/sys/broker is there (WYRM_BROKER_WAIT_S, default 15 s, then the next endpoint; a round of unreachable endpoints backs off 1 s ×2 up to 5 s); Dart WyrmGateway.loginAny keeps the credentials and logs in again on the next gateway; e2e link_process_walks_its_endpoints (a dead port, a plain router without the token, the broker; then the broker stops and a second broker on the dead port takes the link over). Option 1 done 2026-11-05: docs/operations.md, wyrmd stops cleanly on SIGTERM as on SIGINT, the process link hello back-off is capped at 5 s (process::HELLO_BACKOFF_MAX), e2e broker_restart_rto kills a real wyrmd with SIGKILL and prints the recovery time and the base RSS.
Context
Today a site is one wyrmd on one host. Process links know one WYRM_ENDPOINT; wyr, the FFI and the Dart packages know one endpoint or one gateway URL. All state sits in that host’s data_dir: the control plane in the WAL + snapshot of wyrm-state (ADR 0003: append-only, HMAC-chained, every append fsynced, the snapshot only a cache), and beside it secrets.bin with secrets.key, the PKI (the site CA, link.pem, gateway.key, flows.key, .requester_key), the historian’s redb files (ADR 0014), the storage redb (ADR 0017), the sealed stores of the portable Apps (scheduler, alarm, dql, uplink; ADR 0023) and the sealed runtime edits of framework drivers in data_dir/links/<id>/data (ADR 0004, driver::persist). ~val lives only in the router’s memory storage (ADR 0029, decision 4). A lost host or disk is a lost site, and a link has nowhere else to connect.
What the design already gives:
- Restart is the recovery path. Links own and re-declare their subtree on every (re)connect; what is not re-declared does not exist (ADR 0003). Every ACL change rebuilds the router runtime (ADR 0006) and links, gateway clients and peers survive it: each rebuild is a rehearsed broker outage.
- Links already watch the broker. A process link subscribes to the liveliness token
wy/<site>/sys/brokerbefore it starts, trusts no key while the token is gone, and repeatshelloand the re-publication when it is back (process.rs,LinkConfig.republish_on). - Journals with a cursor exist. The historian’s change journal with
next {after, max}(ADR 0026) and the alarm sinks (ADR 0034) replay from a sequence; the WAL is itself such a journal, keyed bylsn. - Sites are autonomous. A downstream site runs without its upstream and catches up through sinks (store-and-forward), as DSA and Sparkplug sites do.
Failure classes used below: F1 process crash, F2 host down, F3 disk lost, F4 network split between the two broker hosts (split brain), F5 network lost between a link and the broker, F6 upstream unreachable.
What the alternatives do (2026-11-05 survey):
| System | Model | What it tells us |
|---|---|---|
| IOT-DSA | No cluster; upstream/downstream hierarchy, dslinks reconnect, HA at the VM level | Where WYRM is today |
| Sparkplug B | An edge node holds a list of MQTT servers; the Primary Host publishes STATE ONLINE/OFFLINE; the node walks the list until it finds a server where the host is online; store-and-forward meanwhile | Option 2, one to one, with sys/broker as STATE |
| Ignition | Master/backup pair, full state sync over its own channel, warm or cold backup, clients and drivers follow the active | Option 3; “warm” = configuration ready, devices not polled |
| OPC UA Part 4 | Non-transparent redundancy: cold/warm/hot, the client knows the ServerUriArray and fails over itself; transparent redundancy at the network level | The cold/warm/hot vocabulary |
| EMQX, HiveMQ, VerneMQ | Real clusters: metadata in Mnesia/Mria or CRDTs, sessions sharded by consistent hashing, clients behind a load balancer, their own split-brain rules | Option 5, for cloud MQTT, not for a site broker |
| Mosquitto | No cluster: a bridge, or active/passive with keepalived and a mirrored persistence file | Option 1 plus a VIP |
| NATS JetStream, Kafka, RabbitMQ quorum queues | Raft-replicated logs, 3 or 5 replicas, leader election | Option 5 |
| Zenoh itself | A mesh of routers, a client with a list of connect/endpoints and retry, storage replication through an aligner (needs timestamping); no consensus, no leader election | Options 2 and 4 without patching Zenoh (principle 2) |
Options assessed
Effort in person-days of one engineer who knows the code base, tests included (tests dominate). Target platform: the reference board, 4-core ARM64, 2 GB. All figures are estimates.
| 1. Supervised restart | 2. Endpoint lists + liveliness arbitration | 3. Warm standby, WAL replication | 4. Mesh of two routers | 5. Raft cluster, 3 nodes | |
|---|---|---|---|---|---|
| Effort, days | 2–3 | 5–8 | 40–60 | +10–15 on top of 3 | 90–130 |
| Extra hardware | none | none | +1 host of the same board | +1 host (the one of 3) | +2 hosts |
| CPU/RAM of the standby | 0 | 0 | base wyrmd without links, ~1 % CPU | the whole ~val flow on the second router: a second memory storage, inter-router traffic = every sample | as 4 plus consensus on every write |
| Network between hosts | 0 | 0 | WAL: bytes per operation, rarely; history ≈ write rate × ~40 B per row | all of ~val, always | log + heartbeats |
| Operations | a systemd unit, a data_dir backup | nothing new | key sharing, a VIP or arbitration, replication lag monitoring | one more ACL subject, two gateways | quorum, 3 hosts, runbooks |
| RTO | 5–40 s (restart 1–3 s; link back-off today up to 30 s) | only with 3 or 4 | 10–30 s (detection T + router build + hello) | ~0 s for readers, as 3 for commands | 5–15 s |
| RPO, control plane | 0 (every WAL append fsynced) | 0 | ≈ 0 (asynchronous: the last operation may not have arrived) | as 3 | 0 |
RPO, history and ~val | history rows pending a flush at SIGKILL; ~val until re-publication | the same | the same plus replication lag | the same | 0 for replicated stores |
| Covers | F1, F5, F6 | F5 (which router) | F1, F2, F3, F6; F4 only with fencing | F5 for readers | F1–F4, F6 |
Why 4 and 5 are not taken:
- Option 4 adds a path for readers connected to Zenoh directly and read scaling. Gateway clients, upstreams and links are covered by 2 + 3 already (same CN, same endpoint list). The price is the whole
~valflow between routers, always, and a second memory storage, which a 2 GB board feels. Deferred until a real need for reader scaling or “zero seconds for dashboards”. - Option 5 does not remove the hard part: links are single-active because of the devices (Modbus TCP connection limits, serial ports, OPC UA sessions), so the link failover of option 3 is needed anyway, and principle 4 (nobody reads another component’s state) would put a replicated log into every component that owns state. Its one gain is fencing without an external VIP, which option 2 provides more cheaply. Refused before 1.0.
Decision
Options 1, 2 and 3 together; 3 in three stages, each useful on its own.
Option 1 — supervised restart (now)
wyrmdis run under a supervisor (systemdRestart=always, or the container runtime);docs/operations.mddocuments the unit, thedata_dirbackup (the WAL and the key files are what cannot be regenerated) and the restore.- The process link back-off cap goes from 30 s to 5 s (
process.rs): with 30 s the link’s timer, not the broker, sets the RTO. The SDK runtime keeps its own schedule. - An e2e test
broker_restart_rtokills the active broker (SIGKILL, not a rebuild), starts it again and measures the time until every link’s liveliness token and last value are back; the number goes todocs/backlog.mdbeside thewyr benchfigures and is measured on the reference board. - The historian’s pending rows are lost on a kill (
flush_ms, pending cap 200 000): accepted as the RPO of history on F1; the flush interval is the knob.
Option 2 — endpoint lists and liveliness arbitration
WYRM_ENDPOINTtakes a comma-separated list;wyrm_client::endpoint(shared bywyr, the FFI and Dart) takes a list too, and the DartWyrmGateway.client()takes a list of gateway URLs. Zenoh’s client mode connects to the first endpoint it reaches and tries the list again when the session drops; nothing in WYRM re-implements that.- Arbitration by the broker’s token. A link declares its tree and answers
helloonly on a router where the liveliness tokenwy/<site>/sys/brokeris present (it already waits for it). Two brokers claiming the same site at once are therefore never both served by a link: the token is one key, and Zenoh liveliness shows a link the tokens it can reach. This is Sparkplug’sSTATErule with a key WYRM already has. - Alone, option 2 changes nothing in a one-broker site; it is the fencing of option 3 and the reason no VIP is required.
Option 3 — warm standby by WAL replication
A second wyrmd on a second host, role standby, the same site name, with the site’s keys. It holds the control plane and the sealed stores current and runs no router, no links, no engines until it is promoted. “Warm” as in Ignition and OPC UA: configuration ready, devices not polled.
- Role and keys (stage A).
wyrmd.json5getsstandby: { of: "quic/<active>:7448", ca, enroll }on the standby andpeers.standby: { allow }on the active. The standby needs the site’s own keys, or links and upstreams would not trust it after promotion: the site CA,state.key,secrets.key,gateway.key,flows.key, the requester keys and the link store keys (the last ones live insecrets.binand come with it). They are shared once, by an operator, as a sealed bundle (wyrmd keys export --to <file>with a one-time passphrase, Argon2id + ChaCha20-Poly1305,wyrmd keys importon the standby), never over the network. The standby then enrolls on the active’speers.enrolllistener as ADR 0015 brokers do and gets a certificate with CNstandby:<site>, a subject of its own in the ACL (QUIC only, read of the replication keys only, nothing else). - WAL replication (stage A). The active serves one queryable,
wy/<site>/sys/replication/wal, answeringnext {after: lsn, max}with the raw WAL records fromlsn + 1(the HMAC chain comes with them: the standby verifies every record with the sharedstate.key, so a tampered or reordered feed is refused as a local tampered WAL is). The standby appends them to its own WAL and applies theOps to its registry with side effects off (no router build, no process start, no audit record of its own). Replication is asynchronous;sys/replication/{lag_records, lag_ms, standby_connected}on the active andsys/standby/{status, lag_records, lag_ms, last_lsn}on the standby show it. Secrets go the same way:secrets.binrecords are already ciphertext undersecrets.key, so the active ships(seq, name, ciphertext)fromsys/replication/secretsand the standby writes them as they are. - Promotion and demotion (stage A). The standby keeps a liveliness subscriber on
wy/<site>/sys/brokerthrough its QUIC session to the active. When the token is gone forstandby.takeover_s(default 10 s; the session loss itself counts), it promotes itself: opens the router with the full configuration, declaressys/broker, starts embedded links and engines, and the process links, gateway clients, peers and upstreams come to it through their endpoint lists (option 2). A promoted standby writes aPromoted {from_lsn}record into the WAL and the audit journal. The former active, when it comes back, first looks forsys/brokeron its standby peer; if the token is there it starts as the standby of that host (Demotedrecord) instead of building a router. Two brokers that cannot see each other (F4) each believe they are alone: the links decide, since they serve only one token (option 2), and the upstream refuses a secondbroker:<site>connection while one is up (ADR 0007 peers: one presence token per CN). Roles swap by design; there is no “primary host” fixed in configuration, onlystandby.ofas the initial pair. - Built, stage A (2026-11-05; the three bullets above record the design before it, decided under ADR 0029 where it differs).
- Configuration is symmetric. Both brokers carry
peers.listen(a QUIC listener) andstandby: { peer: "quic/<other>:7449", takeover_s: 10, primary }. There is nopeers.standbyon the active and nostandby.of: either host may be the active one, andwyrmddecides at start. Bothwyrmd.json5files should otherwise be the same (links,gateway,admin_keys): a promotion opens the daemon on the followeddata_dirwith the standby host’s configuration. - No enrollment. The key bundle (
wyrmd keys export <file>on the active,wyrmd keys import <file>into the standby’s emptydata_dir;WYRM_KEYS_PASSPHRASEor stdin, at least 12 characters;"WYKB1" | salt | ChaCha20-Poly1305(Argon2id(passphrase, salt), cbor {name: bytes})) carries the site CA with its key,state.key,secrets.key,flows.keyand the gateway’shmac.keyandgateway.key, so the standby issues itself astandby:<site>certificate from the CA (data_dir/standby/). Import refuses to overwrite any of those files. The ACL subjectstandby(CNstandby:<site>, QUIC) exists wheneverpeers.listenis set: only the site’s own CA can mint that name. - Three WALs, by file, no apply. The active answers
wy/<site>/sys/replication/wal/<store>/<after>/<max>(state= the registry,flows,users; ≤ 512 records) with{chain, last, records: [[lsn, mac, op], …]}from its segment files (wyrm_state::replicate::records_after); the standby (wyrm_state::replicate::Follower) appends each record after checking its MAC against its own chain with the shared key, and holds the store’sLOCK. It applies nothing: a promotion isDaemon::open, which replays the WAL as after any restart. The audit journal is not replicated (it stays on the host that wrote it). Withstate_anchor_dirthe follower keeps the anchors at its head. - A fork is a restart from zero. When the active’s chain MAC at the standby’s LSN is not the standby’s own (a former active with records its standby never got), the follower moves the store aside as
<store>.stale.<n>and follows from LSN 0. No walk back: the control-plane WALs are small. - Files.
secrets.bin(one sealed blob, rewritten whole) and everylinks/<id>/token(the plaintext a link’shellocarries; its argon2 hash is in the registry) are listed bysys/replication/files[{name, sha256}]and fetched bysys/replication/file/<name>as{name, sha256, sealed}, sealed with SHA-256("wyrm-replication-files"‖secrets.key): the peer link is mTLS, and still no secret crosses it in clear. Link certificates are not copied: the promoted broker issues them from its copy of the CA. - Away means no answer. The follower polls every second (WALs; the file list every fifth poll); the active counts as away from the first poll without an answer, from a liveliness
Deleteofwy/<site>/sys/broker, or from a failed connect. Aprimary: truehost takes over aftertakeover_s, the other after three times that (a cold start of both ends with the primary active; a lone start takes over after its own wait). An ACL rebuild of the active that waits long for its QUIC port (QUIC_PORT_WAIT, up to 30 s) can look like an absence: the primary rule below resolves it. - Promotion and demotion are audit records,
promotedanddemotedbysystem, not WAL records (no registry schema change). An active broker that is not primary asks the peer every 5 s whether the primary’s broker token is there and, when it is, ends its daemon and follows again; the primary never steps down. The former active, at start, follows (it counts the peer as away until the first answer, so with the peer up it never takes over). - No failback (amended 2026-11-07). A returning primary finds the other host active and follows it; it does not take the role back, since that would cost a second gap. The primary rule above applies only when both are active, after a split has healed. An operator moves the role back by stopping the active at a quiet moment.
- Witnesses and fencing (amended 2026-11-07, review of the split case). Links decide by the broker token only when they are external; embedded and supervised links, the scheduler, alarm, uplink and dataflows run on every active broker, so two actives across a split would poll and write the devices twice.
standby.witness(required, one or morehost:porton the plant network) closes that: the standby takes over only while at least one witness accepts a TCP connection (witness_reachable, all at once, 1 s each), and an active broker that reaches no witness and has not been asked by its standby for 3 s steps down after half oftakeover_s(isolated, auditdemoted“cut off”), before the other side’s full takeover time ends. A fenced broker follows and takes over again on its own when a witness answers and no active does. Left open then and closed by the lease arbiters below (2026-11-08; withoutstandby.arbiterit stays open): a split where both hosts still reach a witness but not each other (a firewall between them, a hung process, an expired standby certificate, which the follower now issues again whenever it opens a session) still gives two actives until they see each other again; an active whose witnesses are all down while its standby is down too steps down, and the site has no broker until a witness answers. - Lease arbiters (amended 2026-11-08, decided under ADR 0029). The case left open above (both hosts reach a witness, not each other) needs something both sides talk to that holds who has the role; a TCP port cannot.
standby.arbiter(optional, ≤ 9,host:port; a warning at start without it) names lease arbiters:wyrmd arbiter serve --dir <d> --listen <addr>on a third host, its directory written bywyrmd arbiter issue --host <h> --out <d>on a broker of the pair (the site CA certificate,arbiter:<site>forh, the site name; no private key of the site). TLS over TCP with the site CA on both ends; the arbiter takes only astandby:<site>client certificate. One request per connection,u32length + canonical CBOR:{op: hold|release, holder, ttl_ms}→{state: granted|held|recovering|released, holder?, left_ms};holderis the host’s own random id (standby/host.id, not replicated) joined with a hash of itsstandby.peer(adata_dircopied from the other host still gives another name). The broker checks that the arbiter’s certificate isarbiter:<site>(the site CA signs links and lower brokers too), builds its TLS client from the currentstandby:<site>certificate on every round (issued again when due), and warns once when no arbiter answers; the arbiter’s certificate lasts 20 years (nothing renews it on its host).sys/arbiter_lease_son the active shows the seconds left of its lease (0: none). The active’s renewals count from the send time of the takeover’s own grant (Arbiters::granted_at, shared withfollow_with). The lease lasts half oftakeover_swithin 3–30 s, lives in the arbiter’s memory, and a started arbiter grants nothing for 30 s (a lease it forgot may still run). Rules: the standby takes over only when a majority grants it the lease (acquire; a minority’s grants are released at once), and waits at least 5 s with arbiters (the active’s quiet rule below must fire first); the active renews every second from the moment of the takeover, before the daemon opens; told held by a majority it cannot win, it steps down at once (demoted“another broker holds the arbiters’ lease”); without answers it keeps its lease until the send time of its last granted renewal plus the lease less 1 s (the arbiter counts from its read, later), then steps down only if its standby has not asked for 3 s (a standby that asks follows it and cannot take over). It releases the lease on a stop or step-down. One arbiter is a single point only together with the standby: both down, the active steps down; three arbiters ride that out. A hung active that resumes after its lease ran out acts for at most a second before its renewal is refused. The primary rule stays (with arbiters both can only be active for that second). Tests:arbiter_keeps_a_split_to_one_active(the standby’s peer is a dead port; no takeover while the active renews; takeover once it stops; the former active is told held and steps down),a_broker_without_its_lease_steps_down(the realwyrmdprocess: no takeover without the arbiter, active with it, steps down when the lease runs out though the witness answers, active again with a new arbiter), unit tests of the lease, the frames and the majority. - Healed split, what the loser wrote (amended 2026-11-08). A host is marked while it is active (
standby/active, written at promotion). Its first follow after that moves aside, instead of removing or overwriting, the files the active does not list or lists with other contents (standby/stale/<t_ms>/files/), and exports its storage tree when it differs from the active’s first full tree (standby/stale/<t_ms>/storage.json,wyrm-storageJSON); then the mark goes. A forked WAL is moved aside as before (<dir>.stale.<n>), with or without the mark. Each set is reported to the active assys/replication/forked/<t_ms>/<what>/<count>/<n>(kept instandby/forksuntil answered; any answer counts, an older active answers with an error), and the active writes one audit recordstandby_forked(key = the set, detail = the place on the other host) per(t_ms, what)and counts them insys/standby_forks. Nothing is merged: an operator enters again what must stay. History rows are not moved: the loser’s rows stay in its store beside the copied ones (stage C). - History-sync cursors (amended 2026-11-08). The history page carries the active’s sink cursors (
sinks: {name: seq},standby-*left out; absent from an older active). The standby keeps a markactive seq → local last_seqafter each copied page (≤ 4 096 per active store, in memory) and sets each sink’s local cursor to the mark at or below the active’s cursor, so after a failover a sink sends again at most the page between the mark and its cursor (the targets replace on(key, t)); a sink further behind than the oldest mark keeps its local cursor; a local sink the active no longer has is forgotten. A former active’s sinks that had not confirmed all of its own rows are not moved (standby/own_sinks, until it is active again): they send those rows, and the copied ones after them, again. One case is left: a sink created on the other host during a split, which a former active never had, is mapped past the former active’s own rows (its first mark holds them); those rows reach that sink’s target only if they had reached the other host before the split. Tests:sink_cursors_are_carried_in_local_numbers,own_sinks_are_kept_until_this_host_is_active; the moved-aside sets instandby_takes_over_and_the_old_active_demotes. - Rebuild hold (amended 2026-11-07). Before an ACL rebuild the active stores a hold of 60 s (
Control::hold_standby), carried ashold_until(unix ms) in every registry page it serves, and, with a standby asking in the last 5 s, waits 2.5 s for it to be read; the standby moves its takeover deadline past the hold (at most 120 s ahead). The hold is released as soon as the new router is up. An active that really dies during a rebuild is taken over up to 60 s later. - What the active shows:
sys/standby_connected(1 while the standby’s last registry query is younger than 15 s) andsys/standby_lag(registry records it had not received). The standby runs no router and shows nothing; its log says what it does. - Tests:
standby_waits_for_a_witness,standby_holds_during_a_rebuild,cut_off_active_steps_down(the realwyrmdprocess: takes over, steps down when cut off, takes over again),standby_follows_the_wal,standby_takes_over_and_the_old_active_demotes(e2e),follower_*/a_forked_follower_moves_its_history_aside(wyrm-state),bundle_roundtrip_and_refusals,pages_roundtrip_and_file_names,standby_reads_replication_only. Not tested: two brokers active at once stepping down (needs two routers of one site in one process).
- Configuration is symmetric. Both brokers carry
- Built, stage B (2026-11-05). No journals in the stores after all: the sealed stores of the portable Apps (one file per key, ciphertext under the link’s store key, which
secrets.bincarries), the framework trees (links/<id>/data/framework.tree, sealed the same way), the agent’s WAL and every installed package (packages/**, the component store included) are files, written by a temporary name and one rename, so the active lists them (sys/replication/files: name, length, mtime; scratch names anduploads/left out) and the standby copies the ones whose listing changed, in parts of 1 MiB (file/<offset>/<len>/<name>, each part sealed with the key fromsecrets.key, SHA-256 of the whole file with the first part, checked before the rename), and removes what the active no longer lists. A file over 64 MiB is skipped and logged. Since ADR 0051 §1 the seed’sseed.doneandseed.progress.json(top level ofdata_dir) are listed too, so a promoted standby never runs a finished seed again and goes on with an unfinished one. The broker storage is a redb database, which a file copy cannot take safely while it is written:wyrm_storage::Storekeeps a revision counter with an epoch (set at open) and a journal of its last 20 000 changes, and the active answersstorage/<epoch>/<since>/<max>with the changes aftersinceas{epoch, rev, full, put: [[path, rec]], delete: [path]}, the whole tree whensinceis from another epoch, ahead, or older than the journal; the standby applies them into its own storage database, open while it follows. The sealed stores of a link are copied as the link wrote them:secrets.binwith the store keys comes along, and a promoted broker opens them as after a restart. Tests:standby_follows_stores(e2e),changes_since_pages_journal_and_falls_back_to_full(wyrm-storage),file_lists_walk_the_replicated_roots_only,storage_changes_roundtrip. - Built, stage C (2026-11-06). Not a history-sync target after all: the standby holds no link identity, so it reads the historian’s change journal where it reads everything else,
wy/<site>/sys/replication/history/<after>/<max>(wyrm_history::Store::changes, every series, ≤ 2 000 rows or 4 MiB per answer), as{id, next, last, rows: [[seq, key, t, v, q], …]}, and writes the rows into its own historian store (data_dir/history, open while it follows; a row with the same series and time replaces the stored one, so a page read twice does no harm). The cursor lives in the standby’s store under the sink namestandby-<id>, whereidis the active store’s identity (meta/idinindex.redb, made once at creation): after a failover the new active is another store with journal numbers of its own, so the cursor starts again for it, and the former active, now following, carries its own rows on beside the copied ones. Watch groups come with the registry (stage A), so the promoted broker records on and answers Get History from both. Tests:standby_follows_history(e2e),history_pages_roundtrip. - Sealed stores and driver edits (stage B, as designed). The portable runtime’s store already applies writes per job with a
committedsequence;store_put/store_deleteget a journal(seq, key, ciphertext)under the store key, served assys/replication/stores/<link>withnext {after, max}; the framework’sdriver::persistwrites join the same journal for framework links. The standby writes the ciphertext files as they are. Storage (wyrm-storage) gets aseqper change and the samenext, served assys/replication/storage. - History (stage C). The standby is one more history sink reader: a
Targetofwyrm-history-syncthat writes into the standby’s ownwyrm-historystore (crates/wyrm-history-sync, ADR 0026), readingsys/history/sinks/standbywithnext {after, max}. After promotion the day files continue from what arrived; the gap is the sink lag. Until stage C ships, history is a gap after a failover, by decision. - What is not replicated.
~val(links refill it), gateway sessions (users log in again; tokens still verify, the key is shared), the audit journal of the former active (it stays on its disk; the standby’s own audit starts at promotion), process link output logs, a pending setup code (data_dir/gateway/setup.hash, ADR 0051 §3: it belongs to its host; each host of a pair is made with its ownsetup_file, and since users replicate, the other host’s setup is void once an admin exists), packages indata_dir/packages(stage B copies package files by SHA-256 throughsys/replication/packages, since a link install is anOpthat names them; until then an operator keeps the two package directories equal). - Tests. e2e on two brokers in one process space over QUIC:
standby_follows_the_wal(installs, ACL change, a secret, a scheduler event; the standby’s registry equals the active’s),standby_takes_over(SIGKILL the active; links, a gateway client and an upstream are back on the standby within the measured RTO; asetworks),old_active_demotes(it comes back and becomes the standby; its stale WAL tail after the fork point is refused and archived aswal.stale.<lsn>),split_brain_links_serve_one_token,standby_refuses_a_tampered_feed.
Consequences
- Two hosts hold the site’s keys. Adding a standby is a trust decision of the same weight as adding a downstream CA was (ADR 0007): whoever holds the standby’s
data_diris the site. The bundle never crosses the network in WYRM’s own protocol; the operator carries it. - RPO is not zero and is not meant to be. Asynchronous replication can lose the operation an administrator was making at the moment of the crash; they will see it. Synchronous replication (waiting for the standby’s acknowledgement on every
Op) would make the active depend on the standby, one more way to fail. Refused. - Exactly one active, always. Everything that owns state (admin, flow engine, storage, scheduler, alarm, dql, uplink, every link) runs on the active only; a standby is idle. This follows principle 3 (the broker owns only itself) and principle 4 (nobody reads another’s state directly: the standby reads journals through
get, not files). - Links stay single-active. No link polls a device from two hosts at once; a warm standby cannot be a hot one for devices. OPC UA “hot” is out of reach by the devices’ nature, not by design.
- A failover costs seconds, not zero.
takeover_splus a router build plus every link’shelloand re-publication. On F4 the links serve whichever broker they reach; two reachable brokers with two tokens are an operator error visible insys/standby/statusand in the audit, not a data corruption: each link serves one. - Base RAM of
wyrmdwithout links on the board is not measured yet. Option 1’s test measures it beside the RTO; it decides whether one 2 GB board can be the standby of a site and a working node for something else. docs/backlog.md(section 13) records what is done of each option and stage and what is left; option 4 stays an item with its estimate.
Alternatives
- A VIP (keepalived, VRRP) in front of two brokers. Needs a shared L2 segment and a privileged daemon, which edge boards and cloud networks often cannot give; still needs the state replication of option 3. Kept as an operator’s choice on top of option 2, never required.
- Replicating
data_dirat the block or file level (DRBD, rsync). Copies redb files mid-write, carries the WAL anyway, and gives no replication lag figure the broker can show. Refused in favour of the journals the components already have. - Zenoh storage replication for
~val. The aligner needs timestamping and a storage on both sides; the owners refill~valon reconnect anyway. Not needed. - A standby that also runs the links read-only (“hot”) to shorten the RTO. Devices refuse second connections or answer both, and every driver would need a dry mode. Refused; the RTO is spent in
helloand re-publication, which a hot link would not skip. - Options 4 and 5, above.
ADR 0037 — WYRM Studio: the Flutter app as an AsyncRedux monorepo made with frx
Status: accepted · 2026-11-08 (owner: “the Flutter project is built on the flutter_redux_templates approach and structure; what WYRM has in Flutter was the development version and is replaced”).
Context
dart/wyrm_flutter (iteration 7) was a development explorer: a lazy tree, an action flyout, a history chart and the dataflow editor of ADR 0019, styled as the DSA explorer (WyStyle constants), with one example app. It proved the gateway and FFI paths, but it has no state model, no navigation, no localization and no tests above widget level, and every screen added to it grew explorer.dart (1 800 lines).
The owner designed WYRM Studio (a design canvas of every screen and its states: Explorer, Links and Add a link, Sites, Flows and the field-based flow editor, History, Access, System, Assistant) and chose flutter_redux_templates as its base: a Pub-workspace monorepo (app, ui, business, models, storage, localization) on AsyncRedux, with the frx CLI that creates and wires every artifact (substates, actions, fields, selectors, pages, routes, navigation, services, widgets) and audits the wiring (frx doctor).
Decision
studio/is the app, created byfrx create wyrm_studio --org uk.gencto --title 'WYRM Studio' --without http_client(frx 0.3.7). Its ownCLAUDE.md,.claude/skillsand hook come with it; work on Studio fromstudio/.dart/wyrm_flutteris removed. Its code stays in git history (6199482) as a reference for the tree’s lazy loading,editor: fileuploads and the ADR 0019 editor.dart/wyrm_core,wyrm_client,wyrm_ffistay where they are, outside the Studio workspace, so the fixture job in CI keeps running with plaindart.studio/businessdepends onwyrm_clientby path; it takes the place of the template’shttp_client(the gateway has four REST routes; everything else is CBOR frames over one WebSocket).- Every artifact is made with
frx, by hand only inside bodies. The scaffold is declared as batch files instudio/docs/batches/(checked with frx 0.3.7: applied in order on a fresh project,frx doctorreports only the codegen it has not run). After a hand edit:frx doctor, thendart analyze. - Live values do not go into the store one sample at a time. A service subscribes only to the keys on screen and dispatches one batched action at most every 200 ms; connectors select only their keys.
- Generated UI in the assistant is a closed catalogue of cards (plan, step, choices, run, result, error) rendered from the task record (
tasks/<id>~state); the model never chooses widgets. A step shows its key andargsverbatim (security review). - The look comes from the design canvas: its tokens replace the template’s
_Brand/_Neutralsconstants andAppColors; IBM Plex Sans/Mono are bundled (no font download at run time: edge machines are often offline); icons are the canvas’s SVG paths inui/assets/svg/icons/.
The plan, phase by phase with the commands, is docs/studio.md.
Consequences
- Studio targets desktop and mobile first.
wyrm_clientusesdart:io(HTTP, WebSocket), so the web build needs a second transport before it works. - What the design needs from the broker and the agent link that does not exist yet is listed in
docs/studio.md§10; each item becomes its own change on the Rust side. - The template’s machinery (the
frxsources, its CI) is not in this repository;frxis installed as a binary (frx upgrade).
Alternatives
- Keep
wyrm_flutterand grow it: no state model or navigation to grow into; the owner called it the development version. - Put the Studio packages and
dart/in one workspace:dart pub getindart/wyrm_corewould then resolve Flutter packages and the fixture job would need Flutter. - Riverpod or Bloc instead of AsyncRedux: no generator that wires and audits, which is what keeps a large app consistent when assistants write much of it.
ADR 0038 — Flow fields and live values
Status: proposed · 2026-11-08 (owner: the flow editor must show live values and treat every input as “a value or a binding”; screen spec studio/docs/design/specs/flow-editor.md; decided under ADR 0029).
Context
The flow editor spec (flow-editor.md §3) draws a block as fields: every parameter and every input is one row with a value, a left port (input) and a right port (output); outputs have only a right port. Values are live. One field holds a typed value and an optional binding, and feeds other blocks.
The engine today (research 2026-11-08):
- publishes only the flow’s
~valand thepublishnodes’ values; nothing per port (runtime.rsrun_nodeonly routes outputs); - lets a logic block’s parameter be config and port
in.<p>(ADR 0032 §2), last sample wins, butnode_typesdoes not say which parameter has a port, givesdefaultonly for choices and as a string, and gives no port types; - has no output for a parameter or an input, so a field cannot feed another block;
- has no way to watch a running flow or to run a draft.
ADR 0019 chose Deploy-only: no live ~set of a field.
Decision
1. Every field is also an output
- For each parameter
pof a node: an output portpcarrying the parameter’s effective value (config or default, replaced by the last sample onin.<p>where that port exists). It sends once when the node starts and then on every change. - For each input port
xthat is not a parameter’s port (in,in.0,in.1, …): an output portxthat repeats every sample the node receives onx, before the node handles it. - Names: the output is named exactly like the parameter or the input (
scale1.input_min,if1.in.0). Edges already split at the first dot (def.rsendpoint), soa.in.0is nodea, portin.0. - A clash with an existing output of the node (a parameter named like an output) keeps the existing output; that field has no echo output and the catalog says so (
echo: false). An input’s echo comes before a parameter’s:latchhas the inputresetand the parameterreset, so the parameter has no echo (echo: false). This is the only static clash today. - Cost: an echo output that no edge reads is never built. The compiler knows the edges; the runtime does not copy a sample for an unwired echo.
2. The catalog says what a field is (additive)
node_types keeps inputs, outputs, dyn_inputs, dyn_outputs and params as they are, and adds:
- per parameter:
port("in.<p>"when the parameter has an input port, absent otherwise),defaultas a typed value for every parameter that has one (a number stays a number; choices keep their string),echo(trueunless §1’s clash rule removes it); - per node type:
port_types: {<port>: <type name>}for inputs and outputs (number,bool,string,any, … asPortType::name), andecho_inputs: truewhen inputs repeat as outputs.
3. dataflows/<id>/~act/watch — live values of a deployed flow
- Level
readondataflows/<id>,stream: true,timeout_ms: 30000. - Args:
nodes(optional list of node ids; absent = all),max_hz(optional, default 4, at most 20, per node). - Rights: the caller’s
ptokauth(spec 04, as DQL queries) must cover reading every source (subscribe,liveliness) and every command target (the node of eachinvoke/set) of the flow; otherwisepermission_deniednaming the first key the caller cannot read. The values of a flow are derived from its sources, aninvokenode’s output carries its target’s answer and asetnode’s input is what it writes there (security review 2026-11-08). - Rows:
- first:
{t, snapshot: true, nodes: {<node>: {in: {<port>: [v, q]}, out: {<port>: [v, q]}, params: {<p>: v}}}}— the last value of every port and the effective value of every parameter; - then: the same shape with
snapshot: falseand only what changed since the last row, at mostmax_hzrows per node per second (the latest value wins inside a period); - a heartbeat
{t, nodes: {}}when nothing changed for 10 s (the gateway’s idle wait per reply istimeout_ms+ 5 s); - the stream ends after 30 min (
ttl), on a redeploy ({t, redeployed: <version>}as its last row), on remove, or when the caller goes; the editor opens it again.
- first:
- Cost:
the runtime records the last sample of a port only while at least one watch of that flow is open(changed 2026-11-08, spec 06 0.2.18, see §6 “From the start”): the runtime keeps the last sample of every port from the start. Watches per flow ≤ 8, per site ≤ 64 (busybeyond). - Values are never logged above
trace.
4. dataflows/<id>/~act/ports — one snapshot
Level read, same rights check, returns row 1 of §3. For tools (wyrm-agent, MCP) that do not keep a stream.
5. dataflows/~act/preview — live values of an undeployed draft (2026-11-08, spec 06 0.2.16)
The owner added a concat block to a draft in the Studio editor and saw no values: the engine runs only deployed flows. The editor must show live values on every field of the draft while it is edited, with no risk to devices.
- On the
dataflowsroot: levelread,stream: true,timeout_ms: 30000. Args:def(a spec 06 definition, the shapedeploytakes),nodes(optional list of node ids),max_hz(optional, default 4, at most 20). - Compile: the definition compiles as for deploy and validate (every step of spec 06, the sources’ sections and the
wasmartifacts included); an error isinvalid_parameterwith the compiler’s message.version,enabledandpermissions.maxpermare not checked against anything: nothing is deployed, and noproofsare needed, because nothing is written. - Rights: as
watch(§3): the caller’sauthcovers read on every source (subscribe,liveliness) and every command target (the node of eachinvoke/set); otherwisepermission_denied. Areaduser may preview a draft with asetit may not write: it sees what the set would write, which it may read anyway. - Sandbox: a real runtime instance of the draft that nothing persists: no store, no
~def, no node states (it starts with none and drops them at the end), no node in the tree. Its place is the preview registry, never the engine’s flows, so a draft with the id of a deployed flow touches neither that flow nor its watches. It reads through a session client without tokens. - Sinks cannot write by construction: the node builder has a preview mode (
nodes::Mode::Preview) in whichset,invokeandpublishare capture nodes. A capture node holds no client, no writer task and noctx, and never reads itsIo. It applies the deployed node’s own rule (allow_bad,on,deadband,$ininargs; one function for both modes) and reports the result. Aninvokecapture sends nothing onout(there is no answer). - Rows: exactly
watch’s (§3: snapshot row, change rows at mostmax_hzper node, heartbeat{t, nodes: {}}after 10 s), and any row may carrysinks: [{node, op, key, value}]:opisset,invokeorpublish;keyis the full key it would write:wy/<site>/<path>/~set,wy/<site>/<path>/~act/<action>,wy/<site>/dataflows/<def.id>/nodes/<node>;valueis the value it would write, or forinvokethe arguments map after$in. The snapshot holds each sink’s latest; a change row holds the sinks that acted since the previous row, the latest per node (a row of sinks alone is a change row withnodes: {}andsnapshot: false).nodesfilters sinks too.
- Recorded from the start: the probe is held before the first node runs, so every port’s last sample is kept from the start. The first row waits (at most 500 ms) until every node task runs and a round of asks passes in which no node records anything (each task answers an ask only once its inbox is empty). So the snapshot shows the variables’ start values and what they fed.
- Ends: after 10 min (
ttl; the editor opens it again with its latest draft), when a newer preview of the same subject takes its place, on a node panic (the stream ends withinternal_error; a preview never restarts) and when the engine stops (the engine waits up to 2 s for each preview to stop its runtime). Timers,stopwatch,delayandwindowrun as in a deployed flow. - Caps: at most 2 previews per subject (
origin, elsesub; a third ends that subject’s oldest) and 16 per site (busybeyond). The caps use the watch registry with the subject in the flow’s place. - Cost (measured 2026-11-08, Apple M4 Max, release,
tests/preview_cost.rs): live heap about 8 KB per node (10 nodes: 105 KB, 100: 0.85 MB, 1000: 8.2 MB), with the inbox growing on demand rather than reserved; a node task is one tokio task. The first row came after 25 ms (10 nodes) to 94 ms (1000 nodes in one chain, the start value passing every hop). Idle, a preview of blocks wakes only for its heartbeat; a source costs what it costs in a deployed flow, plus one lock and one value copy per port sample for the recorder. Bounds: at most 1000 nodes per flow (new compiler limit, spec 06 step 8; it applies to deploy and validate too), so one preview is at most about 8 MB, and 16 previews at most about 130 MB.
5a. Not now
- Live
~setof a field stays out (ADR 0019): a field changes by Deploy. - Done 2026-11-08 (spec 06 0.2.17): the older node types take the parameters the editor binds on
in.<p>, as ADR 0032 §2 (the config or default first, the last good sample wins):scalek,b;alarmhigh,low,hysteresis,delay_s,return_delay_s;delayms;windowsize_s;deadbandabs,pct;timerperiod_ms. Each is anumberport, listed in the catalog’sinputsand as the parameter’sport. A sample that is not a finite number, or is outside the parameter’s bounds (period_ms≥ 10,size_s> 0,ms≥ 0,delay_s/return_delay_s≥ 0), is ignored. The config rules stay (highorlow,absorpct,period_ms,size_s,msrequired): the config gives the start value. A parameter that changes a node’s clock (period_ms,ms,size_s, the alarm’s delays) takes effect at once: the runtime starts the new clock one period after the change. Adelaysample already waiting keeps its time. Not ported:expression,filter(their parameters are scripts), and choices (kind,fn,on_bad,max_samples).
6. Implementation notes (2026-11-08, §1–§4 built; spec 06 0.2.15)
- Echo types: an input’s echo has the input’s port type; a parameter’s echo is
number,boolormapas the parameter’s catalog type, every other type (string,dynamic,array)any. Every parameter has an echo,inputs/outputs/argsincluded, and every node type,wasmincluded (there a declared output keeps its name over an echo at compile time). port_typeslists the fixed inputs and outputs, the dynamic ports of theirdefaultnames (in.0,in.1) and every echo output; dynamic ports of other names areany.- A parameter’s echo sends at start, so an edge from it to
invoke/setfires a command at deploy (the one exception to ADR 0032’s rule;docs/flow-blocks.mdwarns). - The caller’s going is not seen. The SDK keeps a stream’s reply channel open until the action ends, and a reply to a gone requester does not fail, so a dropped watch lives until its ttl. At a cap, a new watch of the same subject (
origin, elsesub) ends that subject’s oldest watch (on the flow; at the site cap, anywhere on the site); another subject’s watch isbusy. An editor that reopens on every start stays within the caps. permission_deniedtravels without its text (the SDK never sends one with that status); the engine’s error names the first key, but the requester gets the status only.- Snapshots hold what was recorded: a port with no sample since the flow started is absent from
in/out(all three maps are always in row 1). - From the start (2026-11-08, spec 06 0.2.18; owner review of the Studio editor): on the demo,
ahu2_ctlhas variables feedingconcat1; a variable sends once at deploy, so a watch opened later showedin/outempty forever. The runtime now keeps the last sample of every input and output of a deployed flow from the start, watched or not;watch’s snapshot andportsshow them. Design: one record per node, each behind its own lock, made when the flow starts (a node task locks only its own record and never waits for another node; a watch locks each record in turn); one slot per port, made on the port’s first sample and overwritten in place afterwards; one change counter per flow (an atomic). A watch is woken only while one is open. Measured (Apple M4 Max, release,watch::tests::record_cost): one record of an input and an output costs about 20 ns for numbers and 54 ns for texts (a text is copied; a number or a bool allocates nothing after the port’s first sample); a node call records twice (its input before it runs, its outputs after), so about 25–65 ns per node call, against one atomic load before. Memory: about 100 bytes per port that had a sample, plus a text’s or a map’s own bytes, once per port and not per sample. The 5 sKEEPtime is gone. - Ends: ttl, remove and an engine stop end the stream without a row; a redeploy ends it with
{t, redeployed: <version>}.nodesabsent or empty = every node; an unknown id isinvalid_parameter;max_hzoutside (0, 20] isinvalid_parameter. - Stop/start, reload and a panic restart keep the watches (one recorder per deployed version).
- Preview (§5, built 2026-11-08): a preview’s caller going is not seen either, as for
watch: a dropped preview runs until its ttl, and the per-subject cap (a third preview ends the subject’s oldest) bounds what one editor leaves behind. - Ask barrier: a node task answers a request for its parameters only once its inbox is empty, after the iteration that emptied it. A watch’s snapshot and a preview’s first row so hold what start queued (a variable’s value); a busy node answers within the 200 ms wait or not at all.
- Source tasks end with their node:
subscribeandlivelinesskeep their I/O tasks and abort them when the node drops (a stop, a hot swap, the end of a preview). Before, every redeploy left one Zenoh subscriber per source running. - A stop leaves nothing running (2026-11-09; CI flake
InUseon a restart ofpeak_shaving_hot_swap_and_restart): the store (FlowHost, its WAL andLOCK) is free when the link’sstopreturns, so a restarted engine opens it at once (ADR 0036 restarts). Rules: (1) an aborted task is awaited afterabort(): tokio drops an aborted task’s future only later on a worker, and a flow’s supervisor holds the engine’s state; this holds for the supervisor (halt), node tasks cut at the 1 s drain (one deadline for the whole run, not 1 s per task) and streams cut at the 2 s stop deadline; (2) a supervisor stays the flow’s supervisor through its back-off after a node panic (it was detached before, so it outlived a stop, kept the store and started the flow again on a stopped engine; a start or deploy during the back-off made a second run); (3) the engine tracks itswatchandportstasks with the previews and ends them at stop (flows’ probes end first, then all streams are awaited); (4) the SDK drops the driver before it answersCmd::Stop(before,LinkHandle::stopcould return while the actor thread was still dropping the engine). Watches and previews never held the store; PR #32 only changed the timing. Tests:stop_releases_the_store_at_once(15 stop + immediate reopen rounds, a watch and a preview open at every other stop,Weak<FlowHost>count 0 after each stop), SDKstop_returns_after_the_driver_is_dropped.
5b. Ports for the remaining block parameters (2026-11-08, spec 06 0.2.20)
So every field can be bound: concat in.strict, if in.op, hub in.ignore_null, trace in.tracing, in.msg, with the blocks’ rule (config first, the last sample wins). if.op takes only an operator it knows; another text is ignored and the last good one stays. Every logic-block parameter now has a port, apart from a variable’s value (its input in does that) and inputs (it names the ports).
7. Operands hold a typed value (2026-11-08, spec 06 0.2.19; owner review of the Studio editor)
A block field is one entity: a typed value that a binding can replace. A parameter already is (config, then its port). An operand input (in, in.0, in.1, … of add, concat, if, …) had no constant.
- Config shape: one node key
values: {<port>: <value>}, e.g.{type: "concat", values: {"in.0": "AHU-", "in.1": 2}}. Chosen over flat"in.0": 5keys: a node’s config keys stay its parameters (spec 06 schema,only()checks), port names with a dot never become config keys, and one key is easy to check and to drop. A key must be an operand input of the block:in(where the block has it) orin.<name>of itsinputs; never a parameter’s port (that parameter’s config is its constant), neverstopwatch.reset(an event), and not the variables (number,string,bool: theirvalueis the constant). Anything else is a compile errornodes.<id>: values.<port>: not an operand input …; the value can be any value. - Meaning: the constant is the input’s value until a sample on that input replaces it (a binding wins). Removing the edge and deploying again falls back to the constant. Quality and time come only from inputs that had a sample.
watch/ports/previewshow each constant as the input’s value from the start (Node::seeds). - Safety (ADR 0032’s rule kept): a constant seeds its input and calculates nothing. A block calculates on its first real sample (on any input or parameter port), as before. So a deploy, a hot swap or a restart never fires a
setorinvokebecause of a constant. A block of constants only stays without output: a constant expression is a variable’s job. Refused alternative: evaluate at start and make command sinks drop start-time samples; it needs a start mark carried through every block and changes what a variable feeding asetdoes today. - Amended 2026-11-11 (spec 06 0.2.30): a block of constants only no longer stays without output when it is pure and has no wired input: it calculates once at start, and its sample is made of constants (
Msg::constant), a second mark the runtime carries on as it carries “born at the start” (ADR 0040 §2). Command sinks drop such a sample on every port,inincluded, so a variable feeding asetkeeps today’s behaviour. This is the refused alternative above in a narrow form: the mark is one bool set at two places (the pure block’s start,now’s start) and carried by the runtime, not by the blocks. See ADR 0032’s amendment anddocs/flow-blocks.md“What calculates at start”. - Scope: the logic blocks (
crate::blocks). Notexpressionand the older types (their singleinis the sample they act on). - Catalog: per type
values: truewhen its operand inputs (fixedinputsand thedyn_inputsports that are not a parameter’sport) take a constant.
8. Text operators, round.text and case (2026-11-08, spec 06 0.2.21)
if.opgains!=(the first input equals none of the others, compared as=),contains,starts_with,ends_with(the first input as text with any of the others; anullother never matches; anullfirst is empty text). Names are snake_case (ADR 0032 §3): camelCase spellings are refused at compile.round.min_precision(portin.min_precision, no default =precision) and a new outputtext: a rounded number is often shown as text with its places; WYRM keepsouta number (its port type, its edges) and addstextwithprecisionplaces, trailing zeros trimmed down tomin_precisionplaces.- A
caseblock: inputin;op(=,!=,>,<,>=,<=,contains,starts_with,ends_with, default=) andelse(defaultnull), both with ports; the variable inputsinputsare pairs (case value, then value), usually given as constants invalues(§7). It sends the then of the first pair whose case matchesin, elseelse; it calculates on any sample, as every block. An empty case text matches nothing in the text operators.regexpis left out: a pattern from a port can take any time to match, and the flow crate has no bounded regex engine.
If wrong: a field that should not feed other blocks gets an output anyway (harmless while unwired); a watch that misses a sample between two periods shows the latest value only, which is what an editor needs.
Studio
The flow editor builds fields from the catalog (§2; until the broker has it, from a matching in.<p>), draws a right port on every field (§1), and fills values from watch (§3) for a deployed flow and from preview (§5) for a draft, re-opening either when it ends (a preview also on every change of the draft). The old lookup of dataflows/<flow>/nodes/<block id> for live values is removed: that key exists only for publish nodes.
ADR 0039 — Messenger links: Telegram and Slack, templates as nodes, chat users by pairing
Status: proposed · 2026-11-07, amended 2026-11-08 (two links on one core, owner remark), numbered 0039 at the merge on 2026-11-09 (written as 0037 on its branch; 0037 and 0038 were taken on main) (owner request: a link for Telegram and Slack; the bot must be configurable for the many message kinds and formats Telegram has, “through actions or by creating nodes” — analyse which; and a structured answer to who may use the bot, so that other people cannot reach it).
Context
Sites want notifications and a small amount of remote interaction in the chats people already carry: an alarm in a Telegram group, a shift report in a Slack channel, “what is the boiler temperature” from a phone. Telegram’s Bot API has dozens of send methods and options (text in HTML or MarkdownV2, photos, documents, locations, polls, media groups, inline keyboards, forum topics, silent and protected messages, link previews, edits, reactions); Slack has chat.postMessage with mrkdwn and Block Kit. Both are HTTPS APIs with a bearer-like token.
What exists: portable Apps (ADR 0023, 0030) run one source embedded, as a process and as WASM, with tls_connect under the link’s net, a sealed store and random_bytes; the uplink (ADR 0035) is the pattern for “a platform client set up by Add actions with a secret from Set Password”; ADR 0029 makes a stored definition keep its author’s rights. Flows, the alarm link and the scheduler can invoke actions at write.
How to customise what a bot sends: actions or nodes
Three shapes were weighed:
- Everything in the action’s arguments (
send {chat, method, text, parse_mode, reply_markup, …}). Full coverage, nothing to set up, but every caller (a flow, the alarm link, an operator) has to know the platform’s API, the chat ids and the escaping rules; a caller withwritecould send to any chat the bot is in; nothing is reusable or reviewable. - One node per message kind / option (
photos/…,polls/…). Mirrors the API but multiplies node kinds with every Telegram release and still leaves “to whom” and “what text” to the caller. - Nodes for what is configured, actions for what happens — the DSA way the rest of WYRM follows (connections, devices, points are nodes; Add/Edit/Remove are actions on them). The configuration that needs review — who receives and what a message looks like — becomes nodes made at
config; sending is an action atwritewhose form is generated from the node.
Who may use a bot
A bot token is the bot: whoever holds it reads every update and writes anywhere the bot is. Telegram bots are public — anyone can find one by its name and write to it, and anyone can add it to a group. Slack bots are reachable by everyone in the workspace once invited to a channel. So the question has two sides: who on the WYRM side may make the bot do something, and who on the chat side the bot listens to.
Decision
- One link per platform on a shared core (amended 2026-11-08, owner remark: the platforms differ in what they can do and will grow apart, and more will come).
crates/wyrm-messengerholds what every chat platform shares — bots, recipients, templates and their escaping, the queue and its pacing, pairing, chat commands and the three bounds — asMessenger<C>, a portable App over aPlatformdescription: the API’s paths, request bodies and reply classes, the token’s shape, chat and thread ids, thesend_rawallowlist, and what it can do (inbound: updates, chat users,user:<name>recipients;command_buttons;blocks; per-chat pacing; bearer or path token). Each platform is a link crate that fills that in and nothing else:links/telegram(Messenger<Telegram>, packagestelegramandtelegram-process) andlinks/slack(Messenger<Slack>, packagesslackandslack-process). What a platform cannot do is not declared in its tree (a Slack bot has nousers, no Invite User, nocommands). Another messenger (Teams, Discord, Mattermost, Viber, Signal…) is one more crate with onePlatform; a feature only one platform has is a field ofPlatformor an action of that link, never a branch on the platform’s name in the core. The test kit (wyrm-messengerfeaturetestkit) runs any of them against a fake API on loopback. - Not embedded in
wyrmd: a link needs egress to the internet and a token from an operator, which is a site’s decision (net: "api.telegram.org:443"or"slack.com:443", areadgrant on the roots templates and chat users name,writefor/setand/do). Root actionadd_bot(config); a bot is<bot>/{status, error, username, sent, failed, dropped, queued, rejected, last_sent, enabled}withset_token,test_connection,edit,remove(config). The token goes in with Set Token into the sealed store, never in a param, never shown or logged; an Edit that moves the API endpoint (URL or CA) deletes it (as ADR 0035’s amendment).api_urldefaults to the public API and may name a local Telegram Bot API server; plainhttponly to loopback. - Option 3: nodes for configuration, actions for sending.
recipients/<r>(config): the only chats a bot writes to — a Telegram chat id,@channeloruser:<paired user>, a Slack channel id; forum topic /thread_ts;silent;commands(whether paired users may command the bot in that group). Recipients are addressed by name, so callers never handle chat ids.templates/<t>(config):kind(text, photo, document, location),format(Telegramhtml/markdown= MarkdownV2 /plain; Slackmrkdwn/plain, or Block KitblocksJSON),textwith{{placeholders}},media,lat/lon,buttons(rows ofLabel | https://…or, on Telegram,Label | /command),silent,protect,preview, defaultto, andvalues(alias = wy/<site>/…): live values the link subscribes to and the text may name ({{alias}},{{alias:.1}},{{alias.q}},{{alias.t}}); built-ins{{site}},{{bot}},{{now}}. Every filled-in value is escaped for the template’s markup (HTML entities, MarkdownV2 backslashes, mrkdwn entities; in Block Kit blocks mrkdwn entities and then JSON string content, amended 2026-11-09, as JSON alone left<!channel>and<url|text>active in text objects), so a value — a device name, an alarm message — never changes the markup or injects a link. Each template node declares its ownsendandpreview(write) whose parameters are the template’s variables: a flow or the alarm link callstemplates/high_temp ▸ send {limit: 80}and needs no knowledge of the API. A template keeps its author’s rights (ADR 0029):valuesoutside them are refused at Add/Edit and never rendered after.<bot> ▸ send {to, text, kind, format, media, lat, lon, silent}andrecipients/<r> ▸ send(write): ad hoc messages, built-ins only (a variable is refused: “use a template”).<bot> ▸ send_raw {method, params}(config): the rest of the API (polls, media groups, edits, pins, reactions) without a node kind per method. It fails closed (amended 2026-11-09, security review): methods are an explicit list of exact names per platform (Platform::raw_methods, the guides list them), each with the params that must name a chat (chat_id,from_chat_id,channel); every param of the API that names a chat or an account (Platform::raw_chat_params: Telegramchat_id,from_chat_id,user_id,sender_chat_id; Slackchannel,channel_id,user,users) must be a recipient’s or a paired user’s chat wherever it appears; a missing chat param of the method, or a param whose chat cannot be checked (inline_message_id,business_connection_id, Slackfile,file_comment), refuses the request.getUpdates, webhooks,logOut,closeare never offered (they would take the bot’s inbound channel from the link). A prefix allowlist (send*,chat.*) and a check of one chat field only were the first version and let other fields and new methods through.
- Delivery. One queue per bot (
queue_max, default 500; the oldest is dropped and counted), flushed every 200 ms, at most 4 requests per event, one message per chat per second on Telegram;429holds the whole bot forretry_after; network errors and5xxback off (1 s ×2 to 60 s) and keep the message (5 attempts); a refused message (400,403,channel_not_found) is dropped and countedfailed; a message whose markup does not parse is sent once more as plain text; a refused token (401/404,invalid_auth, …) makes the botfaileduntil Set Token. Delivery is at least once per attempt and best effort overall: an alarm that must not be lost is kept by the alarm link, not by the chat. - Who may use a bot: five layers, deny by default.
- The token is a secret of the link (sealed store, never logged, removed when the endpoint moves). The Telegram token is in the request path, so no error message is built from the request.
- WYRM levels. Defining bots, recipients, templates, users and raw requests is
config; sending iswrite; the host checks the action’s level. Definitions keep their author’s rights (ADR 0029); a token withoutauthcannot define anything that acts later. - The bot only talks to known chats. Sends go to recipients by name; raw requests only to a recipient’s or a paired user’s chat. A Telegram group or channel the bot is added to that is no recipient is left (
leaveChat,leave_unknown, default on) and countedrejected; nothing from it is acted on. - Chat identity by pairing, never by name. An operator invites a named user (
<bot> ▸ invite_user {name, level: read | write, select: keys}); the link draws a one-time code from the host’s random source (10 Crockford base32 characters, 50 bits), returns it once, and keeps only its SHA-256 with an expiry of 15 minutes. The person sends/start <code>to the bot in a private chat; the link binds that account’s numeric Telegram id (from.id, which Telegram authenticates; usernames change hands and are never used). A code is single use, compared in constant time, typed leniently (case, dashes, O/0, I/L/1); 5 wrong codes lock an account out for an hour; a code posted in a group is void at once (it was exposed); an account already paired cannot take a second user.new_codere-pairs (a lost phone) and needs the caller to hold the user’s rights; so doeditandenable(amended 2026-11-09:enablehands the rights back to the paired account, the rights kept with the user stay the inviter’s);disable/removeat config. Unknown accounts are ignored; in a private chat they hear “not authorized” at most once an hour (the bot is no amplifier) and every rejection is counted and logged. - Every command within three bounds at once: the user’s own
levelandselect(key prefixes), the rights of the operator who invited or last edited the user (kept with it, ADR 0029; an invite or edit beyond the caller’s own rights is refused), and the link’s grants (the host). Writes never target the messenger itself. Commands:/get <key>(read),/set <key> <value>,/do <key> <action>(write),/whoami,/help; keys full or below the site. Group commands only where the recipient hascommands: trueand only from paired users. Inline buttons carry a command; a press runs it for the presser, under the presser’s pairing — a button in a group message gives nobody more than they have. Per userrate_per_min(20); each command is logged with the user, command and key (never a value).
- Slack: send only, for now. Slack has no polling API for messages; receiving needs Socket Mode (a WebSocket client over the host’s TLS) or the Events API (an inbound HTTPS endpoint with signing secret verification). Both are later work; until then Slack bots refuse
commands,/commandbuttons andinvite_user. The pairing model carries over unchanged (Slack user id + team id instead of the Telegram id). - Updates by polling, not webhooks.
getUpdateswithtimeout=0everypoll_s(3 s) — no inbound port, no public URL, works behind NAT; the nextoffsetis kept in the store so a restart never replays commands. A webhook set by someone else on the same token makes Telegram answer409, shown as the bot’s error.
Consequences
- Configuration a reviewer cares about — who receives, what is said, which values leave the site, who may command — is in the tree as nodes, with their rights kept; senders (flows, the alarm link, the scheduler, operators) see one Send form per template.
- New Telegram features need no new node kind:
send_rawreaches them atconfig, and a template kind can be added when a feature becomes common. - A chat user can do no more than the operator who invited them, the user’s own level and keys, and the link’s grants all allow — the narrowest wins. Taking over a bot needs the token (the store) or a fresh, unexposed pairing code within 15 minutes.
- Polling every 3 s costs one HTTPS request per bot per poll;
commands: falseturns it off for send-only bots. - No delivery guarantee beyond the queue; no message history in the broker; no inbound media.
- Bounds: 8 bots, 64 recipients, 64 templates, 100 users per bot; 16 values and 4 KiB text per template; 16 KiB blocks; 10×8 buttons.
Alternatives
- One
messengerlink for every platform (the first version, 2026-11-07). Refused by the owner: one package and one release for platforms that differ in features, anadd_<platform>per platform on one root, and every new messenger touching the shared link. The core crate keeps the shared code in one place without that. - Everything in the send’s arguments (option 1). Refused as the main interface: callers need the API, chat ids and escaping;
writewould mean “any chat”. Kept assend_rawatconfig. - A node kind per Telegram method (option 2). Refused: the API grows faster than the tree should, and it still leaves recipients and text to the caller.
- Allow lists of usernames or chat ids typed by the operator. Refused: usernames are reassigned, an operator typing ids proves nothing about who holds the account, and nothing would bind the chat account to rights. Pairing proves possession of the account once and binds rights to it.
- Webhooks. They need a public HTTPS endpoint on the broker; polling needs only egress. A later option for a site with a reverse proxy.
- Embedding it in every
wyrmd, as the uplink. Refused: a messenger reaches the internet with a third-party token; it is installed where a site decides so.
ADR 0040 — Flow behaviours: keys from a port, the action block, custom blocks
Status: proposed · 2026-11-09 (owner requirements of 2026-11-09 for the next round of the Studio dataflow editor: bind a block’s output into the path of another block; the action block with behaviour fields; custom blocks; the blocks still missing; decided under ADR 0029). Goal: a service block takes path as a field that a binding can drive, and has a trigger, an interval, auto run and the events sent, ok and error. Names are WYRM’s (ADR 0032 §3).
Context
ADR 0038 made every parameter and input a field with a value, a port and an output. Three things stayed fixed in the config:
- the key a source reads (
subscribe.key) and the target of a command (set.path,invoke.path); - when a command runs (only a sample on
in); - the set of block types (no block made of blocks).
The key is the hard one. The engine reads through the broker’s own session, which no ACL sees. Today a deploy checks every source against the deployer’s rights (reads_sources, security review) and every command target against a proof token (ADR 0008). Both checks are static: they read the config. A key that arrives on a port at run time passes neither.
Decision
1. A key from a port stays inside a scope approved at deploy (spec 06 0.2.22)
- Field.
subscribe.keyandliveliness.keyget the input portin.key. The configkeystays the start value and may be absent. - Scope. A node whose
in.keyis wired must carrykey_scope: a key expression, relative towy/<site>/or absolute, for exampledownstream/modbus/line1/**. No scope and a wired port is a compile error (nodes.<id>.key_scope: required when in.key is wired). There is no default scope. - Where a scope may lie. Inside this site’s
downstream,dataflowsorstorage, as a static source (spec 06 step 9). The section is a literal prefix of the scope, so no wildcard of it can reachsys,pub,upstreamor another site. Checked by deploy, validate, preview and the start of a stored flow. - Deploy. The deployer’s
auth(spec 04) must givereadon all of the scope, as it must on a static key.reads_keywalks the grants in the responder’s order: a grant belowreadthat touches the scope refuses it; a read grant that covers all of it accepts it; a read grant on a part leaves the rest to the grants after it. So a deny grant on one point inside the scope refuses the deploy, and every key inside an accepted scope is a key the deployer reads. watch,ports,preview. The same check for their caller (reads_flow): a flow’s values come from whatever the scope lets it read.- Run time.
Scope::admittakes a value from the port only when it is: a text; not empty; at most 512 bytes; one concrete node key (every segment[A-Za-z0-9_.-]+: no*,**,$*, no~meta/~valsuffix, no empty segment, no selector); inside this site’sdownstream,dataflowsorstorage; and included by the scope. A statickeyof the config may still be a pattern; a key from a port never is. - A new key. The old read ends first.
outsendsnullwith qualityuncertain, and stays so until the new key’s first sample. The node’s effectivekey(its echo output andparams.keyinwatch) is the key as written. A sample of a read that has ended is dropped (each read has a number). - A refused value. Nothing is read.
outisnull/uncertain, the effectivekeyisnull, and the new outputerrorcarries the reason as a text.errorgoes back tonullwith the next admitted key. The refused value is never logged. nullon the port reads nothing and is no error.- Rate limit. Two changes are at least 100 ms apart. A value that comes earlier waits; the latest one wins.
- After deploy. A flow keeps running when its deployer loses rights (ADR 0008). The same holds for a scope.
The security argument. The engine’s read power is the broker’s. The deployer’s rights bound it at deploy, key by key. A scope is a set of keys named in the definition, so the same bound holds: (a) the set is in the definition that the deployer signs for and that ~def and the history show; (b) the deployer reads every key of the set, deny grants included; (c) the runtime reads one key at a time and only a member of the set; (d) a member is a node key, so the read cannot become a wildcard read, a ~meta read or a query with a selector; (e) whoever watches the flow reads the set too. A flow with a scope reads no more than a flow with one static subscribe per key of the scope would, and that flow can be deployed today.
Refused alternatives.
- A scope by default (the static key’s parent). A wired port would widen what the node reads without a word in the definition.
- Check the deployer’s rights at run time for each key. The engine has no token of the deployer after the deploy, and ADR 0008 lets a flow outlive its deployer’s rights.
- Wildcards from a port. One sample could then read the whole scope at once; a pattern is a decision for the config, where the deploy check sees it.
1a. Command targets stay static in this round
set.path, invoke.path and invoke.action get no port. Reasons:
- A command target is approved by a proof: a token of the deployer for the exact key
…/~setor…/~act/<a>, checked by the engine’s verifier, and the flow’s own tokens grant exactly these keys (ADR 0008). A scope would need a proof for a pattern. A token for a pattern does not show a deny grant inside it, so the engine could not tell whether the deployer writes every key of the scope. Spec 04 would have to say what a pattern proof means, and the gateway would have to mint one. - A wrong read shows a value. A wrong write moves a device.
- The use case of the owner (a text block builds a path, the path drives a
subscribe) needs reads only.
What a flow can change at run time on a command is its arguments (§2) and the value it writes. publish.node stays static too: it is a node of the tree, declared at deploy.
If wrong: a scope that is too wide lets a flow read more points than its author meant, but never more than the deployer reads. A dynamic command target can be added later as a scope with pattern proofs without a change to this section.
2. The action block: invoke with fields, behaviours and events (spec 06 0.2.23)
A node action dropped from the tree becomes an invoke block. The type keeps its name and its old behaviour; it gains argument fields, behaviour fields and events.
Arguments are fields. args stays one map. Each key is an argument: its value is the argument’s constant, and the port arg.<name> replaces it with the last sample (the field rule of ADR 0038 §7: a typed value that a binding can replace). An argument without a constant is null. An argument is also an output arg.<name> (ADR 0038 §1). At most 64 arguments; a name is 1 to 128 bytes and does not start with __. The prefix arg. keeps arguments apart from the block’s own ports, so an argument name never clashes with a port and is never changed to fit. "$in" as a constant still stands for the last value on in. The catalog says dyn_inputs: {param: "args", prefix: "arg.", default: [], keys: true}: keys means the parameter is a map and its keys name the ports.
Behaviour fields (config, and a port each):
| Field | Port | Default | Meaning |
|---|---|---|---|
interval_ms | in.interval_ms | 0 | Above 0: a run every period. 0 is off; else 100 … 86 400 000. A value from the port outside these is ignored. |
auto_run | in.auto_run | invoke: false · set: true | invoke: a sample on arg.<name> that changes the argument runs the action. set: a value on in is written (today’s behaviour). |
enabled | in.enabled | true | False: nothing runs the block, the trigger action included. |
One block, not one per behaviour (owner decision 2026-11-09). “The trigger block and the deploy-run block are in essence one block, only their behaviour differs.” There is no trigger, button, run_on_deploy or periodic block type. invoke is the one action block and set follows the same model; the fields above and below set what runs it.
run_on_start (config, bool, default false, no port: a value from a port would come after the start). True: the block runs exactly once each time the flow starts (a deploy, a hot swap, a reload, a broker restart, a restart after a node panic), 250 ms after the node started, so the start values of bound arguments and of in are in. This is the one sanctioned exception to ADR 0032 §5 / ADR 0038 §7, and the owner’s explicit choice per block; the default keeps the rule. Details: a disabled block makes no start run, and none later when it is enabled; a set writes the value in got by then (nothing when there is none), and not twice when auto_run already wrote it; the answers of the start run carry the start mark (below), so they run no other block through a trigger. The catalog’s description of the field starts with WARNING:. In a preview the start run is a sinks row and never a write.
The older on of invoke stays as it is, for in only, so deployed definitions keep working unchanged. How it maps onto the fields: on: any on in is “every sample runs it”; on: change is what trigger does with a value; on: rising / falling is a rising_edge / falling_edge block (§4) into trigger. New flows wire trigger; in and on are kept, not extended.
trigger is an input without a config value. An event ({event, id}) runs the block. Any other value runs it when it differs from the last sample on trigger; the first real sample runs it. null runs nothing; a sample of bad quality runs nothing unless allow_bad. An unbound trigger is a button: see the action below.
in keeps its meaning: invoke runs on every sample that passes on; set takes the value to write.
Outputs.
| Output | Type | When |
|---|---|---|
sent | event | The request leaves the engine. |
ok | event | The target answered without an error. |
error | event {event, id, code, message} | The target, the transport or the node’s queue refused. code is the status code (spec 04), message its text. |
result | any | invoke only: the last result. |
running | bool | True from the first run handed to the writer until the last one answered. |
last_run | number | The time of the last sent, µs since the epoch. |
out | any | invoke only, kept: the result with quality good, or the error text with quality bad. |
One writer task per node keeps the order. invoke holds at most 256 calls; one more is refused with error {code: busy}. set writes the newest value. A period of interval_ms is skipped while the run before it has not answered. |
set gets the same fields where they make sense: trigger (write the held value now, on/deadband aside), interval_ms (write it again every period), auto_run (default true; false: in only holds the value), enabled, and the outputs sent, ok, error, running, last_run.
The start rule. ADR 0032 §5 says a deploy never runs a command by itself. The new behaviours keep it by a mark on a sample, born at the start:
- what a node sends because the flow started: a variable’s and a
const’s start value, a parameter echo’s start value, a clock’s tick at the start (timersends 1 at once), the first sample of a read (subscribe,liveliness, also after a new key: the value that was already there); - everything a node sends while it handles a sample with the mark. The runtime carries the mark on, not the blocks:
variable → add → triggeris marked, and so is the answer of a command that a marked sample ran.
A sample with the mark on trigger only gives the port its value. A sample with the mark on arg.<name> only fills the argument. interval_ms counts from the start of the node (and from a change of the period, and from enabled going true): the first run is one full period later. So a deploy, a hot swap, a reload and a restart after a crash run no command through trigger, auto_run or interval_ms. Only run_on_start: true does, by the owner’s choice for that block. Tests: a_deploy_never_runs_a_command_through_the_new_behaviours and tests/commands.rs.
in is not part of the rule: a variable wired to set.in or invoke.in still writes at deploy, as ADR 0038 §6 warns. Changing that would change deployed flows. A flow that must not act at deploy uses trigger.
Amended 2026-11-11 (spec 06 0.2.30): a second mark, made of constants (Msg::constant, always with start), is set where a pure block with no wired input calculates at start and on now’s start value, and the runtime carries it on in the same way. A sample with it runs no command on any port, in included: it only gives the field its value. Deployed flows do not change: before 0.2.30 such blocks sent nothing at start. Cost: a block fed at start by both a pure block (made of constants) and a read or a variable (not) calculates twice, in the order the samples come. If the read’s sample comes first, a set after it writes a value without the constant, then holds the full one without writing; the next real sample writes the right value. Before 0.2.30 the constant never came, so the value written at start was always without it. Tests: pure_blocks_calculate_at_start_and_run_no_command, a_real_sample_through_a_constant_chain_writes, operand_constants_never_fire_a_command_at_deploy (also the control: a variable on in still writes).
This is the alternative ADR 0038 §7 refused (“a start mark carried through every block”), in a narrower form: one bool on a sample, set at five places and carried by the runtime, and it changes no existing port’s behaviour. Cost: a point that has no value when the flow starts gives its first value with the mark, so a trigger bound to it misses that one sample.
dataflows/<id>/~act/trigger {node} runs one block once.
- Level
writeondataflows/<id>. The caller’sauth(spec 04) must also givemax(maxperm, write)on the block’s own target (…/~act/<action>or…/~set), by the same grant walk as §1. This is the level the deploy asks of the deployer’s proof (proves_targets): the flow’s token for the target carries up tomaxperm, so a caller with less would run through the flow what it may not run itself (security review 2026-11-09). The compiler capsmaxpermatwritetoday (spec 06 step 7), so the level iswrite; the gate followsmaxpermso it holds if that cap ever moves. The engine cannot see the target action’s own declared level without a read of its~meta; the target checks the flow’s token against that level itself, and that token never carries more thanmaxperm. The flow’s token only says that the deployer could; a button is pressed by a person, and that person needs the right. Noauth:permission_denied. nodeis aninvokeorsetof the flow (the catalog marks these typestrigger: true); another node isinvalid_parameter.- Only a deployed, running flow: a stopped flow or a flow in error is
not_supported(“the flow is not running”). A preview has no such action. - The run goes into the node’s inbox on an internal port, in order with its samples. It runs with the block’s current arguments, whether
triggeris wired or not. A disabled block ignores it. - The responder SDK audits the call as every action, with the caller as its subject; the target audits the command it gets with the subject
flow:<id>, as every flow command.
Preview. set and invoke in a preview are the same nodes without a client or a writer (Sink::Capture): they decide as a deployed node does, record what they would send in the row’s sinks, fire sent and set last_run. They never fire ok or error, never set result, out or running: there is no answer, and a made-up ok would show a success that did not happen.
Found on the way. Two command blocks with one target could not be deployed: proves_targets checked the target’s proof once per block, and a proof token is taken once (jti, spec 04 0.2.11). It now checks one proof per target key.
3. Custom blocks: a sub-flow as one block (spec 06 0.2.24)
The owner selects blocks in the editor and says “create custom block”, later “edit custom block” (docs/studio.md §10 item 8). The engine’s part is small: the compiler replaces an instance by the block’s nodes. The runtime, watch, preview, the rights checks and the proofs never see a custom block.
In the definition.
"blocks": { "<name>": {
"description": tstr?,
"inputs": [ { "name": tstr, "to": "<inner>.<port>" | [ "<inner>.<port>", … ], "default": any?, "description": tstr? } ],
"outputs": [ { "name": tstr, "from": "<inner>.<port>", "description": tstr? } ],
"nodes": { <inner_id>: { "type": tstr, …config } },
"edges": [ [ "<inner>.<port>", "<inner>.<port>" ] ],
"layout": { <inner_id>: [ x, y ] }?
} }
"nodes": { "<id>": { "type": "block:<name>", "values": { "<input>": <value> }? } }
inputsandoutputsare lists: an editor draws the fields in their order. A name is[A-Za-z0-9_]+, unique among inputs and outputs together. At most 64 of each; an input feeds 1 to 16 inner inputs.- Parameters are inputs with a
default. The brief asked forparams; a separate list would be a second kind of field. A field of an instance is an input: a constant (values.<input>of the instance, else the input’sdefault) that a wire can replace, as every field since ADR 0038 §7. - An instance takes
valuesonly. Its ports are the block’s inputs and outputs:["x.out", "m1.a"],["m1.out", "y.in"]. An input is also an output of its name (["m1.a", "z.in"]): the echo of the first inner input it feeds. - At most 64 blocks in a definition, names
[A-Za-z0-9_]+.
Inlining (def::parse).
- An inner node gets the id
<instance>/<inner>; in a nested block<instance>/<inner instance>/<inner>. A/is the engine’s: an author’s id stays[A-Za-z0-9_]+. - An edge into an instance input becomes one edge per inner input it feeds; an edge from an instance output starts at the inner output.
- A constant goes where the inner input keeps one: a parameter’s port → that parameter’s config; an operand of a logic block → its
values;arg.<name>of aninvoke→args;inof a variable →value; an input of an inner instance → that instance’svalues. An inner input that keeps no constant (filter.in,set.in) refuses one:nodes.<id>.values.<input>: <inner>.<port> takes no constant. So a constant never sends a sample, and ADR 0038 §7 holds inside a block. - An inner node’s config hash is computed after the constants. Two instances with the same values have the same inner hashes; a redeploy keeps the state of every inner node that did not change.
- A block may hold instances of other blocks of the same definition. Depth at most 4; a block that holds itself is refused. The limit of 1000 nodes counts the expanded nodes.
- The expansion is charged while it is made (security review 2026-11-09).
validateandpreviewcompile a draft at levelread, so a block that multiplies must cost bounded work. Limits: every plain node and every instance, at every depth, counts against the 1000 nodes as it is added; the edges, as written and as rewired, count against 4000 edges per flow (new, validation step 8), and the walk from an instance input to its inner inputs stops when that room is used up; one block holds at most 64 instances of other blocks, at most 1000 nodes and 4000 edges; a definition holds at most 64 blocks; depth at most 4. A block that contains itself, directly or through others, is refused on the definitions before anything is expanded (blocks.a: a custom block may not contain itself (a → b → a)). Tests (expansion_bombs_are_refused_quickly): 64⁴ nested instances, hollow blocks of instances only, and an input that fans out to 16 at each of 4 levels are each refused in under 50 ms. - Compile cost at the limits (measured 2026-11-09, Apple M4 Max,
the_largest_definition_compiles_in_bounded_time: 909 nodes in blocks 4 deep, 85 instances, 1816 edges): 2.6 ms in a release build (expansion 1.6 ms, checks 1.0 ms), 12 ms in a debug build. So the compile stays under the engine’s state lock, as before. On the way: the compiler made a script engine for every node, with or without a script, which was 55 ms of 56 ms for this definition; it now makes one only forexpressionandfilter. A definition of 1000expressionnodes still pays for 1000 engines (about 60 µs each), as it did before this ADR. - The compiler’s messages name the place as written:
blocks.mean.edges[0] in m1: …,edges[2]: m1 (mean) has no input x. - A
publishinside a block has the samenodename in every instance, so such a block can be used once per flow (validation step 7a). ~defand the history keep the definition as it was sent, withblocks.
The inside in watch, ports and preview. Rows carry the inner nodes under their ids: nodes: {"m1/sum": {in, out, params}}. The argument nodes takes an instance id and then means all its inner nodes (nodes: ["m1"]). An instance has no row of its own: its field a is the inner input to[0] of the block’s input a, and its output is the inner output from. The editor has the block’s definition and reads both there. The trigger action takes an inner id (node: "m1/call").
The library (dataflows, in the flow store, replicated with it; store SCHEMA 4).
| Action | Level | Args | Answer |
|---|---|---|---|
put_block | config | name, def (one block, the shape above) | {name, version}; each put is the next version |
get_block | read | name | {name, version, def, requires: {<name>: def}}: with every library block it uses |
list_blocks | read | — | [{name, version, description?, inputs: [names], outputs: [names]}] |
remove_block | config | name | — (not_found when absent) |
put_blockchecks the block as a deploy would: alone in a probe flow with the library blocks it uses (invalid_parameterwith the compiler’s message; a used block the library does not hold is refused). At most 256 blocks, 256 KiB each.- A flow copies, it does not link. The editor takes a block with
get_blockand writes it (and itsrequires) into the definition’sblocks. The engine never reads the library when it compiles. Reasons: a deploy stays self-contained (the definition, its history and a rollback hold all of it; a standby and a downstream site need no library); the gateway and the tools compute command targets and proofs from the definition alone (command_targets); and a change in the library cannot change a running flow without a deploy and its rights checks. The cost: an update of a library block reaches a flow only when the editor copies it again.versiontells the editor that a newer one exists. - A block holds config, not values;
readis the level ofhistory, which shows definitions too.
If wrong: a team that wants one change to reach every flow needs “update all” in the editor (copy and deploy each flow); the engine side stays as it is.
4. The second set of blocks (spec 06 0.2.25)
Added: what a flow on a broker needs and the engine could not do with its blocks. Each block has a port for every parameter, typed defaults and port_types in the catalog, and rows in docs/flow-blocks.md. The catalog has 55 types (36 before).
Readers (src/readers.rs):
load_value: one read of a point’s stored value. Fieldskey(portin.key, scopekey_scope),interval_ms,auto_run(default true),enabled; inputtrigger; outputsout(the value with its quality and time),ok,error({event, id, code, message}),running,last_run.list_children: the children of a node as a list of rows{name, path, type?, display?, is?, unit?, writable, has_children}, at most 1000 (more:errorresource_exhausted). Fieldspath(portin.path, scopepath_scope) and the same behaviour fields and outputs.- Both are sources for §1: their static key is checked as a source, their scope as a scope, at deploy and for
watch/ports/preview. A refused key from the port is anerrorevent withinvalid_parameter. list_childrenreads the children (security review 2026-11-10). A row shows a child’s name, type, display, unit and whether it is writable. So the deployer, and every caller ofwatch,portsandpreview, must read<path>/*as well as<path>, and for a scope<scope>/*as well (downstream/l/**→downstream/l/*/**), by the grant walk of §1: one child that is denied refuses the block, and a reader of the folder alone is refused. Chosen over filtering rows at run time by the deployer’s grants: the engine keeps no grants after a deploy (ADR 0008), and a row that silently goes missing is harder to see than a deploy that is refused. A deny below the children does not matter: the rows are one level.- A read is no command, so the start rule of §2 does not apply to
auto_run: a reader reads at the start, and when its key changes.triggerstill ignores a sample born at the start (the start read covers it). The latest read wins; a read without an answer after 5 s iserrortimeout.load_valuereads the broker’s value storage: a point that has no stored value isnot_found. - The
triggeraction (§2) is for command blocks only. A reader has no button yet.
Text: substring (start, length, by characters), replace (from, to; plain text, every occurrence), split (separator; a list of at most 1000 texts), join (separator). Results stay within 4 KiB (ADR 0032 §11); a longer one is null with quality bad.
Data: make_object (a map of its named inputs: a map argument for an action), make_array, get (path a.b.0 into maps and lists), stats (a list’s min, max, avg, sum, count).
Events and state: changed (on_change), rising_edge, falling_edge (on_edge), counter (step, initial, reset), toggle (initial, reset), sample_and_hold (in, trigger), select (index). These are what feeds trigger of §2. They follow the start rule: a sample born at the start gives the block its value and fires nothing, so variable → rising_edge → trigger does nothing at deploy while alarm.out → rising_edge → trigger fires on the first real alarm (for rising_edge nothing before counts as false). counter and toggle keep their state across a hot swap.
Time: debounce (the last value after ms without another) and throttle (the first at once, then the latest at the end of each ms). They have a clock only while a value waits (a quarter of ms, 5 to 50 ms), so the value goes out at most that much late.
Numbers from a port are bounded (security review 2026-11-10). debounce.ms as NaN reached Duration::from_secs_f64 and panicked the node task. Rules now: (1) a block never takes a float that is not finite as a number (num: NaN, ±inf, and the texts NaN/inf), from a port or from the config; (2) a sample on a parameter’s port that is such a float is not stored, the last good value stays; (3) debounce/throttle ms falls back to 500 when it is no number and is clamped to 0 … 3 600 000; substring start below 0 is 0 and length is at most 4 KiB; select.index is a whole number within the inputs or gives null; counter keeps its count when a step would leave the finite numbers; get.path longer than 4 KiB names nothing (a value nests at most 32 deep, README rule 6); split gives at most 1000 parts, join and replace at most 4 KiB; (4) interval_ms of the command blocks and readers, and the older period_ms, size_s, ms (ADR 0038 §5a), already took only a finite number in range. The runtime now calls tick_every, first_tick_now and state under its panic guard too, as it did start, input and tick: a panic there ends the run and the supervisor restarts it. Tests: numbers_from_ports_are_bounded, interval_from_a_port_is_bounded (NaN, ±inf, negative, huge, text).
Left out, and why.
| Candidate | Why not now |
|---|---|
json_parse, CSV parser and writer, table to JSON | Principle 5 keeps serde_json to user files, and the flow crate has no JSON parser. A parser for values from a port needs a size and depth bound and an owner decision on the dependency. |
to_number, to_string, parse_number | The variables do it: a number or string block converts what comes on in. |
string_format, format_number, trim, left, right | concat, round.text and substring cover the common cases; a format language is a design of its own. |
now, format_time, time_range, the date blocks | They need IANA time zones. wyrm-schedule has the bundled tzdb; whether the flow crate may depend on it is an owner decision. |
Table blocks (table_filter, sort, group by, join, rollup, aggregation, …) | WYRM has no table value. A list of maps (list_children.out) with get, stats, length and expression covers reading a column; a table type comes with DQL results in flows, if at all. |
timer/interval trigger source | timer exists; interval_ms on the block is the direct way. |
min_max_avg | It is stats. row_count is length. |
regexp in case, router, event_gate, catch_error, a block per table row, statistics (median, mode, deviation), trigonometry, power, root, log, factorial, bound | expression (rhai) computes all of the math; no bounded regex engine in the crate (ADR 0038 §8); routing, event and error blocks wait for a design of their own. |
| Browser, file, zip, history and project blocks | They belong to a page, not to a broker. History in a flow is its own design (DQL, ADR 0025). |
Deferred
- Dynamic command targets (
set.path,invoke.path/actionfrom a port): §1a. Needs pattern proofs in spec 04. - A reader’s button: the
triggeraction forload_value/list_children, with read rights. - Library blocks by reference (a flow that follows the library’s newest version): §3 chose copies.
- A row for an instance in
watch(its fields as one node): the editor maps them from the block’s definition. - An echo for every instance input fan-out: an instance input’s output is the echo of its first inner input only.
run_on_starton a port, and a start run that waits for bound arguments by cause instead of 250 ms.- The blocks of the table above.
- MCP and
wyrm-agentdo not know the new actions (trigger, the library) by name; they reach them as any action.
ADR 0041 — Claude connector: MCP through the user gateway
Status: accepted · 2026-11-10. Stage A (Claude Desktop extension) and stage B (a remote connector with OAuth on the gateway) are built and tested against a real gateway in-process. Stage B awaits a live test with claude.ai, once a public HTTPS name exists. Owner: “Claude should have a connector to WYRM. The chat we have needs a token; make it simpler for the user. Start with the desktop app, which we can test now; the HTTPS one we test later, when there is a domain.”
Context
Today an AI reaches WYRM three ways, and none of them is simple for an operator:
- The agent link (
links/agent, ADR 0005): an LLM inside the broker. It needs an Anthropic API key in a link secret and is paid per token, not from the person’s Claude plan. wyrm-mcp(ADR 0005): talks Zenoh to a router as the service accountai:<agent>with at mostwrite. Config-level work needs a human approval token minted with an admin signing key (wyr token …). That is a key file and a command line for each change. Its HTTP transport is loopback only, with no TLS and no user login.wyrm-agent(ADR 0033): logs in to a gateway as a user. The identity is right: the user’s role decides. But it is a command line for Claude Code.
Claude Desktop installs a local MCP server from one file (a .mcpb extension) with a settings form. Claude (web, Desktop and mobile) adds a remote MCP server by URL and logs in by OAuth 2.1. In both cases the person needs no API key and no token.
Decision
1. One identity: a gateway user
The connector works as one user of a user gateway (ADR 0009), as Studio and wyrm-agent do. The gateway checks every request against that user’s grants and signs a fresh ptok per request. The audit names user:<name>. The gateway reaches the sites below it (ADR 0007, 0018), so one connector reaches a chain of brokers. A user of its own for Claude (for example claude with the operator role) keeps Claude’s changes apart in the audit. No new trust: whatever Claude can do, that user could do in Studio.
2. The tools (wyrm_mcp::gateway::GatewayMcp)
whoami, tree_list, node_meta, value_get, value_watch, history, node_set, action_invoke, flow_deploy, plan_run, spec, and the spec as resources. The operations are those of wyrm-agent. They moved from links/agent/src/cli.rs to wyrm_mcp::gw, so the CLI and the connector share one implementation (feature gateway of wyrm-mcp; wyrm-agent re-exports them).
- A path without
wy/is taken below the gateway’s own site (/api/mesite).wy/<other>/…is passed as given, and the gateway decides. - Changes default to
dry_run: true. A dry run checks against the live~meta(type, enum, bounds, action schema, level) and returnswould_send, plusrefused_by_connectorwhen a local switch would stop it. - MCP annotations: reads are
readOnlyHint, changes aredestructiveHint, so the client asks the person before a change runs.
3. Two local switches on top of the role
The person who installs the connector sets them. They only narrow the role.
read_onlyrefuses every change.allow_config(off by default) lets config-level changes through: a~setonwritable = config, an action of levelconfig, anything underwy/<site>/sys/**on any site, a flow deploy. When it is off, they are refused before anything is sent. A plan is checked step by step against the live~metabefore each step runs, and a node that does not exist yet counts as config.
The approval tokens of wyrm-mcp’s Zenoh mode are not used here. The gateway already signs for a person, and the person approves each tool call in the client.
4. Stage A — Claude Desktop extension (done)
wyrm-mcp --gateway <url> --user <name>, with the password fromWYR_GATEWAY_PASSWORD, serves stdio. Without--gateway,wyrm-mcpworks as before.wyrm-gateway-clientspeakshttps://host[:port]: rustls on ring, HTTP/1.1 ALPN, WSS. The roots are a PEM file (--gateway-ca: the broker CA, or a self-signed certificate) or the public web roots. Plainhttp://stays loopback only, because the password would go in clear.- The session is opened lazily. It is opened again when the socket closes (expiry, a revoked session, a broker rebuild) or within 60 s of expiry. A read that fails on a dying socket runs once more. The password stays in memory (
Zeroizing) and is never logged. packaging/claude-desktop/:manifest.json(MCPB 0.3, binary server; settingsgateway_url,user,password(sensitive: kept in the OS keychain by Claude Desktop),gateway_ca,read_only,allow_config),pack.py(the zip) andbuild.sh(this machine;--universalgives one macOS binary). CI workflowpackaging/claude-desktop/ci-workflow.yml(to be copied to.github/workflows/claude-desktop.yml) builds the macOS and Windows bundles.- Settings arrive as environment variables. An optional setting left empty may arrive as an empty string or as the raw
${user_config.x}. Both mean “not set”. A switch is on only fortrue/1/yes/on, so an unfilledallow_configis off.
5. Stage B — a remote connector (built; gateway.mcp, off by default)
The gateway serves /mcp (streamable HTTP) itself and is its own OAuth 2.1 authorization server:
/.well-known/oauth-protected-resourceand/.well-known/oauth-authorization-server(RFC 9728, RFC 8414);- dynamic client registration (RFC 7591) at
/oauth/register, which Claude uses to register itself. Clients are stateless: theclient_idis a sealed token of the redirect URIs and the name. Redirect URIs are limited to an allowlist ingateway.mcp.redirect_uris: by default Claude’s two callbacks andloopback(any port on 127.0.0.1/localhost/::1, RFC 8252); /oauth/authorizewith PKCE S256 only: one page with the gateway’s own login (the same users, argon2id, failure limits, audit) and the consent, which names the client, where it returns, and the site. Allow changes (on) and Allow config-level changes (off; it needs the first) become the session’sread_only/allow_config. The page isno-store,X-Frame-Options: DENY, andframe-ancestors 'none'. A bad client or redirect shows an error page and never redirects. The redirect carriescode,stateandiss(RFC 9207). Each sign-in is audited (McpGranted,mcp_sign_in);/oauth/token: codes live in memory (60 s, single use, ≤ 1024 waiting), bound to the client, the redirect URI and the challenge. Access tokens (≤ 1 h) and refresh tokens (30 days) are sealed (Sealer, own keywyrm-gateway/oauth/v1, a kind byte per sort) and carry the user’s generation. A new password, a disabled user or a removed user ends them. A refresh token is bound to its client. Refresh tokens are not single use: they are stateless, like the sessions, and end by expiry or by the user’s generation;/mcp(rmcp streamable HTTP,Hostlimited to the public name) checks the bearer on every request and resolves the user as now. It runs the sameGatewayMcptools in process, over the WebSocket protocol handler through an in-memory pipe (ws::serve_frames,Conn::from_raw), one pipe per live access token. Grants, rate limits, the socket budget and the audit are those of any gateway socket. An access token is never a gateway session (/api/*refuses it).- OAuth and MCP are JSON by their own standards (
serde_jsonat this edge only); the WYRM wire stays CBOR.
Off by default (gateway.mcp in wyrmd.json5, GatewayConfig::mcp; feature mcp of wyrm-gateway, default on). It needs TLS and a name that Claude’s servers can reach. That is the cost: the gateway is reachable from the internet. Put it behind a reverse proxy with an allowlist of Anthropic’s published egress ranges, or use the stage A extension, which needs no inbound access.
Consequences
- An operator installs one file, enters a gateway URL, a user and a password, and Claude works within that user’s role. There is no API key, and the use counts against the person’s Claude plan.
wyrm-agent’s operations live inwyrm-mcpnow. A fix there reaches both the CLI and the connector.wyrm-gateway-clientis no longer loopback only. Tools that used it (probe, tests) are unchanged: they still passhttp://127.0.0.1:….
If wrong: nothing is widened. The gateway, the user’s grants and the responders decide as they do for Studio. The switches only remove options.
ADR 0042 — Names people read: one rule for actions, parameters and nodes
Status: accepted · 2026-11-11 (spec 02 0.2.28). Decided under ADR 0029 (owner delegates: decide, write the rule down). Owner: “Some actions have names in snake style like a_ab; that does not read well, while part of them have normal readable names. Go through all of Studio and the links to fix such things. Nodes can have such names too, and they are paths, let them stay so, but maybe we add a name field that lets us replace or style nodes and actions.”
Context
- Spec 02 0.1.6 gave actions and parameters an optional
display. Most links set one, in Title Case (“Add Device”, “Poll Rate (s)”). Some left it out, and a client then showed the key (add_class,timeout_ms). - A node already has a name for people:
attr.display, sent as key 12 inview=listrows (spec 02 from 0.1.0; fixturemeta_view_list). Links set it at declare time (scheduler, alarm, DQL, storage). The driver framework had no way for a user to set it on a connection, device or point. - The texts had no common style: Title Case beside sentence case,
UrlbesideURL,IdbesideID.
Decision
1. Keys stay; people read display
A key (of a node, an action, a parameter) is a wire name: a path segment or an args name. It never changes for style; plans, tests, ACL grants and docs use it. What a person sees is display. Enum values (param-meta key 3) and group are wire values too: they are not renamed.
2. One rule, in wyrm_core::display
humanize(key)derives a name from a key: tokens split at_,-,.; the first word capitalised, the others lower case; words ofWORDSwritten as listed (url→URL,id→ID,mqtt→MQTT,bacnet→BACnet); a last token ofUNITS(ms,s,hz,kb,kib,mb,mib,pct,days,us) in brackets.add_device→Add device,unit_id→Unit ID,timeout_ms→Timeout (ms).check(text)is the style of an explicitdisplay: sentence case, no_, no trailing dot, acronyms asWORDSwrites them, names only fromWORDS,NAMES(one word) andPHRASES(IoT Hub,Socket Mode,Block Kit). Text in brackets is free (units,(GETBULK)).sentence(text)turns a Title Case text into sentence case under the same lists; the framework uses it where it builds a name (Add+ a kind’s display).
3. The SDK fills what a link leaves out
NodeTree (the responder SDK, so every native, process, portable and WASM link served by the SDK) fills a missing action display and a missing param-meta display with humanize of the key, on declare, declare_action and the root. An explicit display wins. A new link gets readable names without writing any; it writes a display only where the derived text is wrong or too thin. A link built before this change and not rebuilt sends no display: a client may derive one from the key (Studio does; the exact rule with the acronym list lives in wyrm_core::display).
4. A user-made node gets a name: display in Add and Edit
The driver framework takes an optional display on add_* and edit of connections, devices and points and shows it as attr.display (key 12 in view=list). It is structural like kind: kept beside the params in the sealed tree, in Export, Import and Copy, never in ~meta.cfg, never a driver param (no driver has a field named display; the name is reserved). edit without display keeps the name, null or "" clears it; at most 128 bytes. An edit with display alone is a rename: the stored params stay as they are (nothing goes back to a default). A rename, or the full form with unchanged params and a new name, re-declares the node and restarts nothing (no rebuild, the connection stays up, stored secrets stay). The sealed tree is saved after it like after any edit. Folders (names only, add_folder) get no display name: a folder is its key.
No twin field: the node’s name is the existing attr.display. Points with an own description keep it beside (attr.description is a hint, display the name).
5. The tests hold every link to it
wyrm_core::displayunit tests: the derive rule with acronyms and units, sentence case, the check.wyrmde2eevery_action_has_a_name_people_read: a broker with every embedded driver (each framework driver with one connection, device and point), the embedded apps (scheduler, alarm, DQL, uplink),sys/**,storageanddataflows; it walks every node and fails on any action or parameter whosedisplaybreaks the check (433 actions, 1 122 parameters today).- The test hosts of the apps that
wyrmddoes not embed (messenger links, history sync targets) lint every action they are handed.
Consequences
- 295 hand-written texts went from Title Case to sentence case by a script, and about 30 were fixed by hand (
Url,Id,Clear conns,from zip,Poll s). Error messages that name an action follow the new names (use Set password). - Docs still quote some menu paths in the old case (
Install Link ▸ from Zip); they are fixed as each guide is touched. - Not covered: enum choices have no
display(they are wire values; a client may humanize them), and action results have no column names in spec 02.
ADR 0043 — The official links manifest: one checked-in list, one published index
Status: accepted · 2026-11-11 (owner request: one file that lists the official links, their versions and their GitHub release files, read by the broker and Studio; CI builds the packages in every form. Decisions delegated, ADR 0029).
Context
ADR 0011 and 0021 give a broker a repository: packages.repository names an index ([{name, version, description, url | assets, sha256}]), the broker fetches it in the background and Install Link ▸ from Repository installs a package after it checks the SHA-256. The only index today is the demo’s (examples/packages/build.sh), with a hand-written list of crates. Nothing says which links the project releases, and nothing publishes them. Studio’s Add a link reads the drivers and the repository packages from sys/links ▸ install and ▸ install_repo and keeps its own table of titles and categories (studio/business/lib/wyrm/catalog.dart).
Decision
1. The manifest: links/official.json
One JSON file beside the link crates, format: "wyrm-official-links/1". JSON, not JSON5: every reader is serde_json (wyrm-link-sdk::official), the same as the index; principle 5 keeps JSON5 for wyrmd.json5.
{ "format": "wyrm-official-links/1",
"releases": "https://github.com/gencto/wyrm/releases",
"hosts": ["linux-aarch64", "linux-x86_64", "macos-aarch64"],
"links": [
{ "id": "alarm", "crate": "wyrm-link-alarm", "title": "Alarms",
"summary": "Alarm classes on points, records, acknowledgement and export",
"category": "Apps", "version": "0.1.0", "wyrm_link": 1, "min_broker": "0.1.0",
"forms": { "wasm": "alarm", "process": "alarm-process" } } ] }
idis the link’s name in lists;cratethe workspace crate it is built from.forms:builtin(a driver compiled intowyrmd, itsinstallname),wasm(a package name: one component for every host),process(a package name: one zip per host ofhosts). At least one.versionis the crate’s;wyrm_linkthe link protocol (LINK_PROTOCOL);min_brokerthe oldest broker that runs it.- The file states intent: which links are official, in which forms, at which version. It holds no URL of a file and no hash. Unknown fields are refused (a typo fails).
It lists the links with [package.metadata.wyrm-link] and a release purpose (protocol links, file stores, history sync, apps, messengers), plus agent (built-in only) and mockdev (trials). It leaves out probe (a test tool), the examples and the drivers mock, wasm, app, portable-echo (hosts for other code, or tests).
2. The published index is generated from it, in the ADR 0021 format
The release job builds the packages, hashes them and writes the index: wyr repo index --tag <tag> (Official::index). One entry per package form, with ADR 0021’s fields and a superset: title, category, link (the official id), kind, wyrm_link, min_broker; description is the manifest’s summary. The broker reads it with the parser it has (parse_index); there is no second reader and no second format. wyr repo add still writes indexes without the new fields.
The index is checked when it is made: every zip must be a form of a listed link, of the listed version, kind and protocol, for a listed host; in a release every form and host must be there (no --partial). The result passes the broker’s own parse_index before it is written.
RepoEntry and Asset now ignore unknown fields (they refused them). An index is read by brokers of many versions and a newer one may say more. Brokers built before this ADR refuse the extended index; no official index existed before it, so no deployed broker is affected.
3. Hashes come from CI, after the build; the broker never trusts what it cannot check
The checked-in file has no hashes, so it is never stale and a release cannot depend on a commit that writes them back. The release job computes SHA-256 of each zip it just built and writes them into the index, and publishes the zips, the index, the manifest (official.json) and SHA256SUMS as the assets of release <tag>. The broker installs only an index entry whose zip matches its SHA-256 (ADR 0021, unchanged).
Package zips are reproducible from their inputs (package::pack: sorted files, fixed time), but the compiled binaries are not bit-for-bit reproducible across toolchains; the hash is of the file that was published.
4. Where the index lives: a fixed release, absolute URLs per tag
- Each links release has tag
links-v*and keeps its files:<releases>/download/<tag>/<zip>. The index written for it uses these absolute URLs, so an index read just before the next release still names files that exist and match. - The index brokers read is the one asset of release
links-index:https://github.com/gencto/wyrm/releases/download/links-index/links-index.json. Each links release replaces that asset (--clobber). Notreleases/latest/download/…: “latest” follows any newest release of the repository (a futurewyrmdrelease would make the URL a 404), and links releases are created with--latest=false. - Relative URLs (no
--tag, no--base) are for mirrors: the zips beside the index.
5. Trust: what the manifest adds and what it does not
It adds: one reviewed list of what the project releases; packages built by CI from a tagged commit, not by a person; an index whose hashes match those files; HTTPS to github.com with the webpki-roots store (fetch.rs, redirects to the release CDN followed, at most three).
It does not add: a signature. Whoever can replace the links-index asset (a repository writer, a stolen token, GitHub itself) can point brokers at other zips with matching hashes. Packages stay unsigned (ADR 0011), and installs still show the requested network and grants before anything runs (security review).
official in the catalogue (security review of this ADR, 2026-11-11). A package name alone proves nothing: any repository can publish a package called modbus. A package row is official: true only when (1) the configured repository is the official index (packages.repository: "official", or the same URL written out), and (2) the broker’s embedded manifest lists that package name, in that form (wasm or process, from the shape of the entry), at that version. A package row’s title, summary, category and link come from its own index entry, never from the manifest, so a repository cannot borrow an official description. The manifest holds no hashes (§3), so the hash cannot be compared with it; the SHA-256 of the index entry is checked against the downloaded zip at install, as for every repository. A mirror (another URL) is shown as not official, even with the official files. A built-in driver row is official when the manifest names it: it is compiled into the binary that embeds the manifest. Next step: sign the index (Ed25519, a key that is not in CI secrets of the same repository, the public key embedded in wyrmd), and refuse an official index that does not verify. Not done here.
6. Default: off; one word to opt in
wyrmd fetches no index unless packages.repository is set (as before). packages: { repository: "official" } means the official index URL of the manifest this broker was built with (wyrm_admin::official::repository_url). A broker on a plant network must not call the internet because it was installed; an air-gapped site cannot reach GitHub at all and would log an error every start. The demo and the Docker example carry the line as a comment. A site that cannot reach GitHub mirrors the release (docs/operations.md, Official links offline).
7. The broker is Studio’s one reader: attr.catalog of sys/links
The broker embeds the manifest (include_str!, wyrm_admin::official::EMBEDDED) and publishes on the ~meta of wy/<site>/sys/links an attribute catalog: an array of maps, one per built-in driver this broker hosts and one per repository package built for its host (after the index loads; declared again then):
| key | value |
|---|---|
id | driver:<code> or package:<code> (Studio’s CatalogItem.id) |
code | the name install (driver) or install_repo (package) takes |
link | the official link id, empty when none |
title, summary, category | a driver: from the embedded manifest; a package: from its index entry only. Missing: the name, empty, empty |
version | a driver: the broker’s version; a package: the index entry’s |
form | builtin, wasm or process |
official | a driver: the embedded manifest names it; a package: the rule of §5 |
Built-in drivers get titles with no network. The install/install_repo enum choices stay as they are; the catalogue only describes them. attr is free-form (spec 02), so the spec does not change.
8. CI
packaging/links/release-workflow.yml (to be copied to .github/workflows/links-release.yml by someone with the workflow scope, as packaging/claude-desktop/ci-workflow.yml): on a links-v* tag or a manual run, check (wyr repo check), wasm (wyr repo build --form wasm), process on three hosts — x86_64-unknown-linux-musl (ubuntu-latest), aarch64-unknown-linux-musl (ubuntu-24.04-arm), aarch64-apple-darwin (macos-latest) — static musl on Linux so a binary runs on any board, and publish (the only job with contents: write) for a tag. No secrets beyond GITHUB_TOKEN; actions pinned by commit; persist-credentials: false. The workflow has no link list: wyr repo build reads the manifest. A manual run without a tag builds and keeps the zips as artifacts only.
cargo test holds the manifest against the workspace (wyr test official_manifest_matches_the_workspace: crate exists, version is the crate’s, a wasm form is a kind = "wasm" crate with a cdylib under that name, a process form has a binary and, for a process crate, its package name) and wyrmd test official_builtin_forms_are_drivers_of_wyrmd. CI’s existing cargo test --workspace runs both.
Consequences
- A link version moves in its
Cargo.tomland inlinks/official.jsontogether, or the tests fail. - The demo keeps its own repository (
examples/packages/build.sh): examples and test tools are not official. - Studio can drop its table of titles (
catalog.dart) and readattr.catalog; until it does, both agree because both come from the same names. - Windows and
macos-x86_64hosts are not built (no broker host key for Windows; Intel Macs are not a target). Adding a host = one line inhostsand one matrix row.
Alternatives
- Commit the resolved index back to
main(raw URL of a tag): reproducible URL, but the release job needs push rights to the default branch and the index commit races other work. releases/latest/download/links-index.json: no extra release, but any other release breaks the URL.- The manifest is the index (hashes checked in): one file, but every release needs a commit with hashes the CI computed, and a hash in review is not a check.
- On by default: easier for a first trial; refused for plant and air-gapped sites (§6).
ADR 0044 — Flow blocks, third set: computation on the server
Status: accepted (2026-11-11, owner request “implement everything that can work in Rust and on the platform”; decisions delegated under ADR 0029).
Context
WYRM had 55 node types (ADR 0032, 0038, 0040). Flows on a broker also need
math, text and codecs, time, events, tables and reads of history and of a
node. Everything that is computation, data shaping, time, text, events, state
or a read of the tree belongs on the broker. What needs a screen, a browser,
the editor, a style, a device sensor or a file API does not. This set adds 70
types: node_types lists 125.
Decision
1. One block machinery
The new types are logic blocks of crates/wyrm-flow/src/blocks.rs (ADR 0032:
a value per parameter, a port in.<p> for every parameter that a wire may set,
change-only outputs, the worst quality of the inputs, nothing at start but the
variables; amended 2026-11-11: a pure block with no wired input calculates once
at start, spec 06 0.2.30). Their calculations are pure functions in blocks/*.rs with unit
tests. The readers (load_history, get_node) are kinds of
the reader of ADR 0040 §4 (readers.rs): load_history and get_node.
2. Tables
A table is a value:
{"columns": ["name", "kw"], "rows": [{"name": "pump", "kw": 3}, {"name": "fan", "kw": 7}]}
columnsgives the order; a row is a map. A cell that a row lacks isnull.- Every table input also takes a list of maps (the rows of
list_children, of asplit, ofmake_array): its columns are the keys in the order they first appear, sorted within one row (a WYRM map has sorted keys). Rows given as lists ({"columns": […], "rows": [[…]]}) are taken by position. - There is no
rowcolumn: a row’s index is its position from 0. No table gets an index column of its own. - Bounds: 10 000 rows, 128 columns, a column name of 256 bytes, 512 KiB of
encoded cells, nesting 32 (spec README rule 6). A table block whose result is
larger sends
nullwith qualitybad. - Mutators (
table_add_row,table_edit_rows,table_remove_rows) are pure transforms of their input: they write into no stored table; in a stream engine the output is the next table. A flow that keeps a table across samples wires it throughtable_recorderor keeps it in broker storage. - Per-row scripts (
table_filter,table_map_columns,table_edit_rows,table_remove_rows) are rhai over the variablesrow(the row as a map) andindex. A column name is not a variable: names come from the data and the compiler checks a script against fixed names. The scripts of one table have 100 ms in all (past that:nulland the reason onerror), each row the engine’s 10 000 operations.
3. Time
- A date value is a number of microseconds since the Unix epoch, as
tof every sample,HistRow.tandlast_run. A date input also takes RFC 3339 text,yyyy-M-d[ HH:mm[:ss]],yyyy/M/d,M/d/yyyy. Not milliseconds: WYRM keeps one unit for all its times. - Wall time is computed in the zone of the parameter
time_zone: an IANA name (Europe/Kyiv),UTC, or±HH:MM. The default isUTC, not the host’s zone: a broker in a container often has no zone file, and a flow must give the same result on every host. The tz data isjiff’s bundled tzdb, as inwyrm-schedule. A wall time in a DST gap moves forward, a repeated one takes the earlier instant (as the scheduler). - A block that depends on the clock (
now, a relativedate_range) reads it once per calculation through the runtime’s clock; the pure functions takenowas an argument, so tests are exact. A relative range is calculated again on a clock of 1 s while its input is relative, sotodayrolls over. date_rangetakesweek_start(defaultmonday) andtime_zone;previousN<unit>is the period beforecurrentN<unit>.
4. Readers
load_historyreads the historian (~val?history=, ADR 0014) throughWyrmClient::history: its rows{t, v, q}as a table, at mostlimit(1 … 10 000) rows. An answer that reachedlimitmay have more: theokevent saystruncated: trueandrows, so the cut is never silent. A table past 512 KiB is anerrorevent withresource_exhausted. A query field that changes while a read runs reads again after it, never cancels it.- Several keys merge by time with one
load_historyeach (the samewindow) andtable_joinont: one key per reader keeps the scope rules as they are. get_nodereads one node’s summary and its actions with their parameters.- Each is a read field in
nodes::read_fields, so the deployer, every watcher and every previewer must read its key or scope, asload_value(ADR 0040 §1). - A reader runs on
dataflows/<id>/~act/trigger {node}too (Studio §10 item 8): the caller must read the reader’s key and its scope (levelread), instead of a command target’smax(maxperm, write). - A trigger starts a run that flows on along the edges (security review
2026-11-11): the caller also needs
max(maxperm, write)on the target of everysetandinvokedownstream of the triggered node, found by a walk over every edge, transitively, with the custom blocks inlined. A reader with no command downstream needs read alone. The same rule holds for a command block: a command whose answer runs another command needs the rights of both.
5. Stream rules the blocks keep
WYRM is a stream engine: a block calculates on each sample, not on a timer.
- Numbers are integers while they fit, then floats; a result that is not
finite is
null(no NaN or Infinity in a WYRM value). There is no NaN constant:constwithnullstands for it. - A block calculates on each sample and sends its outputs in its declared
order; the compiler refuses a cycle that has no
delay. - An output goes out when its value or quality changed; events always.
- The catalog’s
defaultis the effective value. - A trigger is an event or a value that differs from the last one; a sample
born at the start never acts (ADR 0040 §2). The same
bornrule covers the start of a flow. - No block panics; a bad input gives
null(qualitybadwhere the input was valid but too large). medianof an even count is the mean of the two middle numbers;date_mathcounts years, months and days on the calendar oftime_zone, so a day over a DST change keeps the wall time.modulo’s remainder is never negative,max/minof no number arenull,scaledoes not clamp,splitgives a list,substringclamps an overrun: existing WYRM behaviour that deployed flows rely on.
6. Patterns
case, router and replace take regexp. A pattern is compiled by the regex crate
(linear time, no backreferences) with a compiled-size limit of 64 KiB and at
most 256 bytes of pattern; the input is at most 4 KiB. A pattern that does not
compile matches nothing.
7. Left out
repeat(one block instance per table row): the instance count is known only at run time, but the 1000-node budget and the deploy proofs are computed when the definition is compiled. A later set may bound it by amax_rowsin the config.- Archive parsing (zip): needs an archive codec with bounds on expansion; files reach a flow through the file store links.
- A PID block: it needs a decision on its form and its bounds.
- Error groups without wires: an implicit route between blocks would bypass
the cycle check,
watchandpreview;catch_errortakes wires. - Blocks that need a screen, a browser, the editor, a style, a device sensor or a file API.
Amendment 2026-11-11: now has a clock (spec 06 0.2.30)
now gave the time only on a sample of in, and its in took a typed
constant. A clock block that shows nothing until something is wired into it is
of no use (owner’s screenshot: today typed into in, no output), and the
value on in meant nothing. Now:
interval_ms(portin.interval_ms, default 1000; 0: only on samples ofin; else 100 … 86 400 000, as a command’s period; a value outside is refused in the config and ignored on the port).- With a period,
nowsends the time once at start, made of constants (it runs no command), and then every period; those ticks are ordinary samples, as atimer’s. A sample ofingives the time at once too. inis only a trigger: it takes no constant (values: trueis dropped from its catalog entry). Avaluessaved before is read and ignored, so a stored flow still compiles.- ОБЕРЕЖНО: a
nowstored before 0.2.30 has nointerval_ms, so after the upgrade it also sends every second (the default). Its ticks are ordinary samples: anowwired toinof asetor aninvoke, or to atrigger, then runs that command every second. Setinterval_ms: 0to keep the old behaviour (only on samples ofin). No deployed flow of the demo has anow(checked 2026-11-11).
Consequences
node_typeslists the new types; the catalog gainsdisplayper parameter (spec 06 0.2.29). Studio draws them from the catalog; its follow-up is in the pull request.- The guide (
docs/flow-blocks.md) has a section per group with fields, behaviour and bounds.
ADR 0045 — Flow metrics in ~val
Status: accepted (2026-11-12; decisions delegated under ADR 0029).
Context
A deployed flow shows only its state in dataflows/<id>/~val:
{state, error?, version, since, deployed_by?} (spec 06). running says the node
tasks exist, not that samples reach them, that the inboxes keep up or that the
commands get answers. An operator who asks “does this deployment work?” has to
open a watch (ADR 0038), which needs read rights on every source and target and
shows values, not totals. The runtime already counts the samples an inbox drops
(runtime::Inbox::dropped), but nobody publishes the count.
Two limits shape the answer:
~valofdataflows/**has watchers: gateway users (Studio follows every flow’s~val), historian watches and peers upstream. A value that changes every second per flow would reach all of them.- The runtime’s hot path (one task per node, a sample per message) must stay free of locks and allocation.
Decision
1. ~val.stats
~val gets one more text key, stats (additive: old readers ignore it):
"stats": {
"nodes": uint, // nodes of the compiled flow, custom blocks expanded
"edges": uint, // edges of the compiled flow
"samples_in": uint, // samples the nodes took in
"samples_out": uint, // samples the nodes sent on a wired output
"dropped": uint, // samples the inboxes dropped (policy.overflow)
"restarts": uint, // restarts after a node panic
"commands": {"sent": uint, "ok": uint, "error": uint},
"last_sample_t": uint? // µs, when a node last took in a sample; absent before
}
samples_incounts each sample a node takes from its inbox when it came from an edge, or from the node’s own source (subscribe,liveliness,const, and the “owner gone” mark of asubscribe). Internal messages are not samples: a command’s or a reader’s answer, a reader’s own read request and~act/trigger.samples_outcounts each sample a node sends on an output that has at least one edge (once, however many edges leave it). Writes ofpublish,setandinvokeleave the flow throughcommands(or the published node), not here.commandscounts the eventssent,okanderrorof theinvokeandsetblocks (spec 06 0.2.23).errorincludes a run refused before it was sent (busy: the call queue is full), sook + errormay exceedsent.droppedcounts the inbox drops ofdrop_oldest/drop_newestand of a source that pushes into a full inbox underblock. Apublishthat skips a sample while its writer is busy is not an inbox drop and is not counted.
The counters are atomics (runtime::FlowStats, Relaxed), shared by the node
tasks of one run: an increment per sample and one clock read per sample taken in,
no lock, no allocation. A node task knows at start whether its node is a command
block, so only those look at their event ports.
2. When the counters reset
The counters belong to a run that an operator or a deploy started:
- a new set at each deploy (also a hot swap and every stored flow that the engine
deploys again at its start, so at every broker start and every ACL rebuild,
ADR 0006), at
startand atreload; - kept across the supervisor’s restart after a node panic (
restartsgrows); - kept, frozen, while the flow is stopped or in
error: the last totals stay visible; - a deploy that does not compile changes nothing: the running version keeps its counters.
3. When ~val is published
- A state change (deploy, start, stop, reload, error, restart) publishes
~valat once, as before, with the counters of that moment. - Between state changes one engine-wide clock looks at every flow once per period
and publishes a flow’s
~valonly when its counters differ from what its last~valcarried. An idle or stopped flow publishes nothing. - The period is
FlowHost::set_stats_every.wyrmdsets it tometrics_interval_ms(thesysmetrics period, default 10 s), and never below 5 s. Without a setting the engine uses 10 s.
So a busy flow sends at most one more ~val per period, and an idle site sends
none.
- A draft that does not compile shows
state: 2and itserrorwhile the old version runs (spec 06). The engine keeps that error with the flow (FlowRt::refused), so the counters’ later~vals carry it too, until the next state change (deploy, start, stop, reload, restart). Without this, the first counters-only~valwould hide the refusal.
4. Out of scope
Per-node counters (rates per edge, per-node drops) would grow ~val with the flow
and change it on every sample of any node. They stay out; ~act/watch and
~act/ports already show per-node values to a caller with the rights.
Consequences
- An operator sees in one value whether samples arrive (
samples_in,last_sample_t), whether the flow keeps up (dropped) and whether its commands work (commands.okagainstcommands.error), with only read rights on the flow. - Gateway subscribers and historian watches of
dataflows/**get at most one more sample per busy flow per metrics period. A historian watch that records a flow’s~valnow records its counters too. - Counters reset at every broker restart and ACL rebuild: they describe the current run, not the life of the flow. Long-term totals belong to a historian watch.
last_sample_tchanges with every sample, so a flow that keeps receiving always publishes once per period, even when the other counters hold still.- The clock is one task per engine. A stop of the engine cuts it first, so it never delays the release of the flow store.
- Tools:
wyrm-mcpreturnsstatswith a flow’s state. Studio andwyr flowdo not show it yet.
Alternatives
- Separate nodes
dataflows/<id>/stats/*. Rejected: more keys to declare and re-declare per flow, more subscriptions for a UI, and the same rate question. - Publish every second. Rejected: every watcher of
dataflows/**would get one sample per flow per second whether anyone looks or not. - An action
~act/statsinstead of a value. Rejected: an operator wants to see the counters next to the state, in the tree and in the historian, without polling. - Counters across runs (persisted). Rejected: the broker would write flow traffic into its control-plane store; a run’s counters are enough to tell whether a deployment works.
ADR 0046 — Link grants on the site’s storage
Status: accepted (2026-11-13; decisions delegated under ADR 0029).
Context
A link gets rights on other parts of its site through grants (sys/links/<id>
▸ Grant Access, a package’s requester; ADR 0013): a path under
wy/{site}/downstream (any level up to write) or wy/{site}/dataflows (at
most read). check_grant refused every other root, storage included.
The demo bot of 2026-11-13 (DVPSM, links/telegram) needed storage: its
buttons and /set from the chat write the points of storage/dvpsm/cmd, and
its templates and chat users read storage/dvpsm/**. A flow reads and writes
storage with its deployer’s rights; a link could not, so the buttons did
nothing and Invite User with a storage key failed with an empty
PermissionDenied. The only way round was a register link in downstream
mirrored into storage by a flow.
Storage (ADR 0017) is the site’s shared folder tree, not one link’s branch: several flows, users and links keep values there side by side.
Decision
check_granttakeswy/{site}/storage[/…]as a third root.listandreadon any path in it, the root included.writeonly on a folder below the root (wy/{site}/storage/<folder>[/…]): one grant never lets a link write the whole of the site’s storage. A link that writes several folders gets one grant each.configstays for people, as everywhere.
- The router ACL needs no change: grant rules are built from the path
(
grant-<id>-*). - The embedded storage link trusts a link’s requester key (subject
link:<id>) at the grant’s level and only under the grant’s path, beside the admin keys, the gateway, the flow key and upstream sites (Control::requester_keys_under). A grant change rebuilds the router, and the storage link starts again with the new keys. - A package may ask for storage in
requesterwith the same rules.
Consequences
- A chat bot, a report link or any requester can keep its working values in storage without a mirror flow.
- An operator who grants
writeon a folder lets that link change every value under it; the grant shows in Get Permissions and in the audit (link_grant) as before. - Not changed: a link still never reaches
sys/**and never writes flows. - Tests:
registry::tests::link_grants(paths and levels), e2elink_grant_on_a_storage_folder(writes its folder, refused in another, refused on all of storage).
ADR 0047 — Checking an action without running it (~act/<a>?check)
Status: accepted (2026-11-13; decisions delegated under ADR 0029).
Context
The MCP connector runs every change dry first: it reads the node’s ~meta, checks the
arguments against the action’s schema (types, enums, required, bounds) and shows the person
what would be sent. A link that parses its arguments further found errors only when the
action ran. In the DVPSM demo (2026-11-13) the dry run of add_bot {format: "html"} was “ok”,
and the bot refused the real call (format: one of html, markdown, plain: the messenger read a
typed enum by name). A dry run that says “ok” for what the link then refuses gives the person
a false sense that all is well.
The link is the only one that knows its own rules (its form parsing, the author’s rights of a template, its recipients, its network allowlist). It must be asked. Asking an older link is the danger: a selector parameter it does not know is ignored, and it would run the action.
Decision
- Spec 05 0.2.33:
get path/~act/<a>?checkwith the action’s arguments. The responder checks the call as the action would take it:ptokand the level, the arguments against the action’s meta, then its driver’s own check. It does nothing: no write, no command, no change of state. The answer isstatus=okwithout a payload, or the refusal the action would give (same status, same text). The audit recordscheck. - A responder that answers
checksays so:attr.check = trueon its root~meta(wy/<site>/downstream/<link>,sys,dataflows,storage). The SDK sets it on every root it declares, so every link built with this SDK has it. A requester sends?checkonly where the root says so; without it the check ends at the action’s meta on the requester’s side, as before. - SDK:
Link::on_check(path, action, args, who), defaultOk(the SDK’s checks are all there is). Portable links:App::on_check, defaultOk; the runtime runs it on the engine thread like an event and drops whatever the app asked of the host during it. The messenger implements it with the same parsing as its actions (bots, recipients, templates and their sends, chat users). - A WASM component of world
wyrm:app0.3.0 has no check call: its check ends at the meta (the host checks that). A component gets its own check with the next world; the world stays frozen until then (ADR 0030). - Gateway op
check {key, action, args}(rights asinvoke);WyrmClient::invoke_check;wyrm-gateway-client::Conn::check. The MCP connector’s dry runs ofaction_invokeand of a plan’sinvokesteps ask the link when it says it can and showchecked_by_link.
Consequences
- A dry run catches what the link would refuse, before anything runs.
- Links built before this have no
attr.checkand are never asked; they behave as before. checkcosts one request to the link and one audit record; it is rate limited as any call.- Tests: telegram
a_check_refuses_what_the_action_would_and_does_nothing, e2ea_check_does_nothing, wyrm-mcp gateway test (dry run withchecked_by_link).
ADR 0048 — Updates, restore points and backups from Studio
Status: proposed (2026-11-13, owner request). Design: canvas row Updates, restore points, backups (LinkUpdate*, BrokerUpdate*, Backup*, LinkBackup); Studio side: studio/docs/design/specs/updates-backups.md.
Context
What exists today:
- Packages (ADR 0011, 0043). Installing a newer version of a package (from the repository, a zip, a URL or git) replaces the old one:
install_packageunpacks the new version, restarts every link that runs it (upgrade_links; a WASM app gets a hot start) and deletes the old version’s directory. There is no way back and no check that a link came back with its nodes. The repository index is read every hour, but nothing says that an installed package has a newer version. - Link state. A framework link keeps its runtime edits and secrets sealed in
data_dir/links/<id>/data(framework.tree, ADR 0004); a portable app keeps its sealed store there (ADR 0023). Framework links export and import their settings as JSON (wyrm-driver-branch/1); there is no export of a link as a whole (settings, private data, package, grants, net). - The broker.
wyrmdis updated by hand: replace the binary, restart under systemd (docs/operations.md§2). No release index, no signature, no way back once the registry SCHEMA moved (today 19). - Backups are offline copies of
data_dirwith the broker stopped (docs/operations.md§3), pluswyrmd keys exportfor the keys. The standby (ADR 0036) already knows how to copy every store consistently while the broker runs: WAL records, sealed files in parts, the storage journal and history rows (control/replication.rs,sys/replication/**).
The owner asks (2026-11-13): update links and the broker from Studio by a remote command, with a way back that restores the state; official links update from the repository, custom ones by bringing a new archive, and the nodes and state of the previous version are kept; export a link as one zip; back up the broker from Studio with checkboxes per section (history, storage, dataflows, links, …).
Decision
1. Package updates with restore points
sys/packages/<name>showsversion,latest(from the repository index; empty for custom packages),update_available(bool),previous(the version kept for a rollback, withkeep_until) andlast_update(a map:from,to,at,result=ok | rolled_back | failed,kept,new,gonecounts and up to 200 keys ofnewandgone).sys/linksgainsupdates_available(count) so Studio can badge it.- Action
sys/packages/<name>/~act/update {version?, accept, restore_point = true, auto_rollback_s = 120}(config, audited): installsversion(defaultlatest) from the repository with its SHA-256, the same flow asinstall_repo. A custom package is updated by the existinginstall_zip/install_url/install_gitwith the same package name; they take the same three new arguments. - Before anything stops, for every link that runs the package: a restore point, which is a link backup (§3.5) without history, written to
data_dir/restore/<link>/<UTC>.wyrm-link, and the link’s current key list (~meta?view=keysof its root). Restore points are listed atsys/links/<id>/restore_points(at,version,size) and pruned afterpackages.keep_previous_days(default 7). - The previous version’s directory is kept (no
remove_dir_all) untilkeep_until; the registry’sPackageDefkeepsprevious. - Health after the restart: every link of the package must say
helloand declare at least every key it had, withinauto_rollback_s. Keys that do not come back aregone; new ones arenew. Withauto_rollback_s > 0and anythinggone(or a link that never says hello), the broker rolls back by itself (§1.6) and auditsupdate_rollbackwith the reason. With0, it keeps the new version and reports. sys/packages/<name>/~act/rollback {to?}(config): reinstallspreviousfrom its kept directory, stops the links, restores each link’s private data from its newest restore point taken before that update, starts them. A rollback is itself recorded inlast_update.- Store format: the package manifest gains
state(integer, default 1) andreads_state(list, default[state]). An update whosereads_statedoes not contain the installedstateis shown as changes the store format (Studio’s review says so); the rollback then needs the restore point and Studio does not let the person untick it. - One version per package stays the rule: every link of a package is updated together (Studio lists them).
Rules fixed when §1 was built (2026-11-13; the guide is docs/links.md §5a):
- Values.
version,latest,update_available,previous,last_updateare value nodes ofsys/packages/<name>(they move while an update runs), besidestateandchanges_state(the update tolatestchanges the store format).previousis{version, keep_until, changes_state}; times are unix seconds.last_updatecarries the countskept,new,gone, the listsnew_keysandgone_keys(<link>/<path>, ≤ 200 each),reason,links,changes_state,restore_point. Itsresulthas a fourth, passing value:checking, while the health check runs.updates_availableis an attribute ofsys/links, besidecatalog(a child node there would read as a link to whoever lists the links: Studio’s Links page does), and counts links (the rows of Studio’s tab). - Custom. A package is custom when the repository index does not list its name for this host.
update_availablecompares versions (dotted numbers as numbers, a release over its pre-release);update {version}takes only the index’s version (an index names one), and a version that is not newer only when it is named. - The update answers at once. The admin serves one action at a time and a link’s
hellois one of its actions, so the health check runs after the action answered ({success, message}, like an install); Studio followslast_update. Until it ends, installs of the package, its Remove and its links’ Start/Stop/Remove answerbusy;rollbackstops it and rolls back. - Health. A link is back when it answers
~meta?view=keysof its root, read without a token (restricted subtrees are not counted). The check ends early when every link is back with every key and nothing changed for 3 s (12 s after a hot start: the old code’s nodes are swept 10 s after it).auto_rollback_sis 0 to 600. With0the report is made when every link answers and its keys are stable for 3 s (ok, withgoneand a reason), orfailedafter 120 s without an answer. A link without a key list (stopped before, or over 10 000 keys) only has to answer. - Rebuilds. A rebuild of the router waits for the update up to the restart of the links, and for a rollback, as it waits for an install. It does not wait for the polling of the health check: a link may need that rebuild to say
hello(one installed a moment before, a grant the update added), and waiting would hold every ACL change for the window. The check steps aside and goes on with the new router with the time it had left (at least 30 s). A broker process that ends during the check leavesfailedat the next start; the new version stays. - Rights.
acceptcovers grants andnetentries the new version asks for and a link lacks; they are added to each link and stay after a rollback. - Restore points.
data_dir/restore/<link>/<UTC>.wyrm-linkand<UTC>.meta(CBOR: time, package, version, size, the key list for the health check, entries skipped). The archive is the link backup of §3.5, made byControl::link_backup_to’s code with the sectionssettingsanddata(no history, no package: the package a link ran is kept once, as the package’spreviousversion of §1.4, not once more in every link’s restore point). It is sealedhow: broker(a key fromsecrets.key), so a restore point needs no passphrase and nobackups.export_secrets, and never leaves the broker by itself;install_backupon the same broker takes one as any link backup. A rollback gives the stopped link its secrets and private data back (Control::link_restore_data): the data directory is built new beside the old one and swapped in with two renames.wyrm_admin::restore_pointkeeps the directory only (names,.meta, list, prune); it knows no archive format. The provisional sealed zip of the first build is gone. The order of §1.3 is kept (the copy is taken while the link runs), so the copy follows no symlink: each entry of the link’s data is opened once withO_NOFOLLOW, checked against the held parent directory and sealed from that handle; what is not a file or directory is skipped and counted; a restore creates every directory and file new. This walk iswyrm_admin::nofollow, and every copy of a link’s private data into a backup goes through it (a link backup, thelinkssection of a broker backup, a restore point). Scratch (uploads/,tmp,*.tmp,agent.next) is left out; at most 50 000 files and 8 GiB (what the reader of a link backup takes). Replacing a link throughinstall_backuptakes the same kind of restore point first (§3.5), listed inrestore_pointsand pruned with the others; it has no key list (a restore has no health check). Not copied to a warm standby. - After a rollback nothing is kept:
previousis empty and the directory of the version that was rolled back is deleted. Installing the kept version again (same bytes) reuses its directory. - Store format.
state≥ 1;reads_statehas 1 to 32 entries and must hold the package’s ownstate. The repository index may carry both (wyr repo addand the official index copy them from a manifest that names them), sochanges_stateis known before the fetch; the manifest in the zip decides.restore_point: falseis refused when the format changes, and such a rollback is refused for a link that has no restore point.
2. Broker updates
- Install layout for self-updating brokers:
<prefix>/versions/<v>/wyrmd,<prefix>/current→versions/<v>,<prefix>/bin/wyrmd-guard(a copy of the running binary, refreshed only after an update is confirmed). The systemd unit runsExecStartPre=<prefix>/bin/wyrmd-guard update-guardandExecStart=<prefix>/current/wyrmd.docs/operations.mdgains the layout and the unit. - Config:
updates: {mode: "off" (default) | "external" | "self", channel: <URL of the releases index>, keys: [<Ed25519 public keys>], trial_s: 180, keep_days: 7}. The WYRM release key is built in;keysadds others (a company mirror).external(containers, distribution packages) refusesupdatewith a message and shows how to update outside. - Releases: a new release workflow publishes
wyrmd-<version>-<target>.tar.gz, a signed release document with its SHA-256, and a signedreleases.json(version, date, notes URL, targets, minfromversion,schemasit writes, replication protocol version). Until that workflow exists,update {file}takes an uploaded archive with its signature (parts, as ADR 0028). sysshowsupdate_available,latest,update_state(none | staged | trial | confirmed | rolled_back) andupdate_last(map). Actionsys/~act/update {version, confirm_site}(config, audited;confirm_sitemust equal the site name):- download into
versions/<v>.part, check signature and SHA-256; - run
versions/<v>/wyrmd check -c <config>(the new binary checks this configuration); - pre-update backup of the control plane and keys (§3 sections
controlandkeys, sealed with a key derived fromsecrets.key, so no passphrase is needed) intodata_dir/backups/pre-update-<v>.wyrm-backup; - write
data_dir/update.json{from, to, state: "trial", attempts: 0, deadline, backup}, pointcurrentatversions/<v>, copy the running binary tobin/wyrmd-guard, and stop cleanly (exit 0; systemdRestart=alwaysstarts the new one).
- download into
- Trial: the new
wyrmdincrementsattemptsfirst thing. It is healthy when the router is up, the gateway listens, the admin answers and every link that was connected before the update sayshello(process links gettrial_s). Healthy →state: confirmed, auditupdate_confirmed, the guard binary is replaced by the new one. Not healthy bydeadline, orattempts ≥ 3: it exits with code 76. update-guard(the previous binary) runs before every start: withstate: trialand (attempts ≥ 3or the deadline passed or a 76 recorded), it pointscurrentback atfrom, restores the control-plane files from the pre-update backup when the new version moved a SCHEMA, setsstate: rolled_backand lets systemd start the old binary. Auditupdate_rollbackis written by the old binary at start.sys/~act/rollback_update(config) after a confirmed update, untilkeep_days: same as §2.6, on purpose. Changes made after the update are lost (the pre-update backup is restored); the review says so.- Standby pair (ADR 0036):
updaterefuses on the active while the standby runs an older version and the release changes the replication protocol; Studio offers to update the standby first (through its ownsys, reached via the peer link). The same action reaches a downstream broker through its upstream withallow_config(ADR 0018).
Rules fixed when §2 was built (2026-11-13; the guide is docs/operations.md §2 “A broker that updates itself”, the release side packaging/wyrmd/README.md). Code: wyrm_admin::release (format, unpack, layout, guard: files only), wyrm_admin::control::broker_update (what a running broker does), wyrmd::update (identity, check mode, the standby’s side, release tooling), tests crates/wyrmd/tests/update.rs.
- Mode.
updates.modeisoffby default: nothing is fetched,updateis refused.externalneedsupdates.channel, reads the index and showslatest,update_availableand, inupdate_hint, what to run outside the broker;updateis refused with that text.selfis refused with the reason (update_hintshows it too) when the running binary is not<prefix>/versions/<its version>/wyrmdwith<prefix>/currenta symbolic link to that version and a file<prefix>/bin/wyrmd-guard, and when the guard did not run before this start (it leavesdata_dir/update.guard; without the guard a failed update could not be taken back).wyrmd install-layout <prefix>makes the layout from a binary. Unix only; other targets compile and refuse. - Signature and keys. A release is one JSON document:
wyrmd_release: 1,version,date,notes,min_from,schemas(registry,audit,users,flows),replication, and per target (<arch>-<os>[-musl]) the archive’sfile,size,sha256,urlandbin_sha256(the SHA-256 of the binary in the archive). Its signature is detached: Ed25519 overwyrmd-release-v1\n+ the document’s bytes, hex, one a line (several lines: one good one is enough, for a key that is replaced). The index is{wyrmd_releases, sequence, created, releases}with entries{release, signature}: each a release document as text with its own signature; the index as a whole is signed overwyrmd-releases-v1\n+ its bytes. The two domains keep an index signature from signing a release.updates.channelserves one file,{wyrmd_channel, index, signature}: the index text and its signature together, so a reader never has one without the other (review of PR 74, point 7; a read that fails is also tried again after 5 minutes and never replaces the index read before). A broker checks the index’s signature and then every entry’s own; one entry that does not verify refuses the whole index, and nothing of an entry is used that its signature does not cover (version, SCHEMA numbers, size and SHA-256 of each archive, SHA-256 of each binary). So an index that was signed without being checked cannot carry an unsigned entry (security review of the workflow, 2026-11-13). The keys are the ones built into the binary (release::RELEASE_KEYS, empty today: the project has no release key yet) andupdates.keys; with no key pinned nothing is trusted. No key is ever read from a release file. The archive is.tar.gz(the workspace hasflate2, no zstd). - Freshness of the index (review of PR 74, point 5).
sequencegoes up by one with every index published and is under the index’s signature. A broker keeps the highest sequence it has read indata_dir/update.seenand refuses a lower one: an old, validly signed index that is put back (to hide a release with a fix) is refused, and the index read before stays in use. The file is not in the registry (no SCHEMA change for it); a host whosedata_diris new starts at 0. Only a missing file is 0: a file that is there and cannot be read as one number (not readable, not a plain file, over 32 bytes, not au64) refuses every index and is never written over, and the directory is synced after the file is renamed into place, so a power loss does not bring an older number back (issue 184; recovery indocs/operations.md§2).wyrmd release index --from <channel file>writes the next index (sequence + 1) only when the published one verifies and holds every version given with--have; the workflow passes every release tag that exists, so it does not sign on top of an index that was put back. - The signing job (review of PR 74, point 6). The workflow builds without a build cache. The key is in the environment of two steps of the job
sign(environmentwyrmd-release), which builds its tool from the tagged source itself and hascontents: read; the jobpublishhascontents: writeand no key.release docchecks each archive against its description and the binary in it against the hash that is signed. - The channel holds no credential.
updates.channelishttps://(plain http only to loopback), without userinfo, query string or fragment: refused when the configuration is read, with a message that does not repeat the URL. It is shown insysand in the config copy of a backup (CONFIG_SHOWN; the mask’s second net strips userinfo and what follows?or#all the same). A private channel that needs a credential would take it from the secret store; not built. - Before anything is unpacked or run: the signature of the document, its bounds, the rules below, then the size and SHA-256 of the archive against the signed document.
- Version and SCHEMA rules (
Release::compatible). A build for this host must exist. The version must be newer than the one that runs (dotted numbers as numbers, a release over its pre-release; a name that is not dotted numbers is never newer): an update never goes down,rollback_updateis the only way back.min_frommust not be newer than what runs. Every SCHEMA the release writes must be at least the one this broker writes, and none may be left out: a release never goes below whatdata_dirholds. A release (or a running version) that names a store other thanregistry,audit,users,flowsis refused: the guard of this version could not put such a store back (review of PR 74, point 1); it is installed by hand. Withstate_anchor_dirset, a release that moves a SCHEMA is refused (a rollback would put back a WAL older than its anchor): update by hand. - Unpack. Into the new directory
versions/.<v>.part, renamed toversions/<v>when all of it is on disk. Plain files only, by plain name (no directory, no.., no leading.), at most 9, the binarywyrmdamong them and executable in the archive; symbolic and hard links, devices, pipes, directories and extension headers refuse the whole archive, and so do the namesrelease.jsonandrelease.sig; each file is created new; the modes are the broker’s (0755 the binary, 0644 the rest), no owner or time is taken; the binary at most 1 GiB, another file 1 MiB, the archive 512 MiB; data after the end mark refuses it. The SHA-256 of the unpacked binary must be thebin_sha256of the signed release. The release document and its signature are then written beside the binary (versions/<v>/release.json,release.sig). - The new binary proves itself before the switch, each time with an argument vector, an empty environment and 120 s:
wyrmd release-infomust say the version, schemas and replication of the signed release and this host’s target;wyrmd -c <config> check --state <copy>must take this broker’s configuration and open every control-plane store with its own state types. The copy isdata_dir/update.check(0700): each WAL as of one sequence number (wyrm_state::replicate::copy_to) with its key file, removed after the check. The live stores are never opened by the new binary before the switch. - The pre-update backup is a job of
sys/backupswithkind: pre-update, pinned, of the sectioncontrolalone, sealed for this broker (how: broker: its manifest carries a MAC under a key fromsecrets.key). Decided: nokeyssection (§2.4.3 said both). An update replaces a binary, never a key file, the guard restores WALs only, andkeyswithout a passphrase is refused by §3.4. The guard checks the file’s SHA-256 againstupdate.json, the manifest’s MAC withsecrets.key, and every file it reads against the manifest. It is unpinned when the update is rolled back, when it is no longer kept (below), or when the next update is committed. updateanswers at once ({success, message, version, restart}), like a package update: the admin serves one action at a time and the fetch, the check and the backup take minutes. Studio followsupdate_state(none,staged,trial,confirmed,rolled_back,failed) andupdate_last(from,to,result,at,by,reason,attempts,deadline,keep_until,restored,without_s,links,backup,schemas_moved;stepwhile one is prepared:fetching,checking,staged,backup). An update that ends before the switch leavesupdate_state: none,update_last.result: failedwith the reason, an audit record, and no version directory.update?check(ADR 0047) refuses whatupdaterefuses before it fetches the archive; it answersokor a refusal, not a list.- Without a releases index (today): the archive is uploaded in parts with the upload of the backups (
sys/backups/~act/restore_begin,restore_part,restore_abort; ADR 0028 bounds), thenupdate {upload, release, signature, confirm_site}with the release document and its signature as text.check_updatesreads the index now. - One job at a time.
updateandrollback_updateare refused withbusywhile a backup is made or sent, a restore is staged, a package or a link is held by an operation (the claims of §1.9), another update is prepared or in its trial, and while the router is rebuilt; the check is made again after the pre-update backup, right before the switch. From its first step an update of the active holds the broker with the claim a restore withmode: replacetakes (Control::replacing): no install, update, rollback or restore of a package or link starts until the update ended before the switch or the broker has restarted. (The refusal others then get is the one of a staged restore: its text names a restore.) - Commit order: the guard becomes the binary that runs (if it is not, and if the broker may write it: with the hardened unit a root step keeps it),
update.jsonis written (trial,attempts: 0,trial_s,ran_s: 0, the backup’s id, file and SHA-256, both sets of schemas, the stores that exist, the links that are connected),currentis switched by one rename of a new symbolic link,update_startis audited, the broker stops with code 0. A broker that stops between the file and the switch is found by the guard (currentstill names the old version):rolled_back, nothing restored. - Trial. It is counted in the time the new version ran, not in wall time (review of PR 74, point 2): the version adds to
ran_sinupdate.jsonevery 5 s and the trial ends whenran_sreachestrial_s. A host that is off for longer than the trial, a broker that is down, a clock that jumps: none of them ends a trial or fails it.deadlineinupdate.jsonandupdate_lastis an estimate for people (now + what is left), set at each start; nothing is decided by it. The guard counts the starts (not the new binary, §2.5: a binary that cannot start is counted too) and lets three go; a power cut during a trial is one of them. At the end of the trial the new version is healthy when its admin answers onsysthrough the router, the gateway accepts a connection (if it is configured) and every link ofupdate.jsonthat is still installed has its liveliness token; asked again for 10 s. Healthy:confirmed,update_confirmed, the guard becomes the new binary. Not healthy: the reason goes intoupdate.jsonand the process ends with code 76 (Restart=alwaysstarts the guard).update_confirmedis never written before the version rantrial_s. A link stopped by hand during the trial counts as not back. A new version that hangs without ending is not seen by the guard (it acts at a start). - Guard (
wyrmd update-guard, run as<prefix>/bin/wyrmd-guard). It takes the update back when the new version gave up (76 and its reason), when three starts did not end the trial, or whenrollback_updateasked. It never asks the clock. Where the update moved a SCHEMA (told by the two sets inupdate.json), it first puts those stores back from the pre-update backup (release::restore_control): a store that existed before the update (update.jsonstores) is replaced by the backup’s; one that did not (the gateway’s users on a broker that had no gateway) is moved intodata_dir/update.asideand left out. Everything is read intodata_dir/update.restorefirst, so an error up to there changes nothing; then the directories are swapped, and a swap that fails is undone. Thencurrentgoes back by one rename and the state isrolled_back. - The guard never leaves the broker without a version to start because a restore failed (review of PR 74, point 1; before, it ended with code 1 and neither version started). When the stores cannot be put back (the backup is gone, changed or not sealed for this broker; a file cannot be written), the old version is made current on the state as it is: state
failed, the reason inupdate.json,update_last.reasonand the audit (update_rollback, statusinternal_error). When the version a rollback made current does not come up in three starts (the old binary cannot read what the new one wrote), the guard makes the other version current, three starts each, until one comes up; a version that came up marksupdate.jsonsettledand the guard leavescurrentalone from then on. When the old version’s directory is gone the new version stays (failed). Errors of writingupdate.jsonare said and passed over. The one case in which the guard ends with an error and nothing starts is a binary that is not verified (next rule). - Only a verified binary is started (review of PR 74, point 4a). With
updates.mode: "self", the guard before it lets a version start, and the broker at its own start, check that the SHA-256 ofversions/<v>/wyrmd(a plain file, no link) is thebin_sha256that a release document kept beside it names for this host’s target, that a pinned key signed that document, and that the document is of version<v>; or thatbin/trusted.jsonnames<v>with that hash (a version put there by hand withwyrmd install-layouthas no signed release). A binary that fails is never started: the guard makes the other version of the update current when that one verifies (statefailed, with the reason), else it ends with code 1. A broker outside the layout is not checked (it cannot update itself either). - Threat model of the layout: a known limit (review of PR 74, point 4). A process link runs with the broker’s uid. If the broker’s user owns the whole layout, such a process can replace
bin/wyrmd-guard,bin/trusted.json, a version’s binary,current,update.jsonor a backup, and gain code execution that survives restarts. Mitigation, indocs/operations.md§2:<prefix>owned by root with the sticky bit,bin/and the configuration owned by root,versions/andcurrentby the broker; the guard is then refreshed by a root step of the unit (ExecStartPre=+… guard-refresh, which reads the current binary once, through no link, verifies it and writes what it hashed). With that, replacing a binary or pointingcurrentat an unsigned one is stopped. Not stopped, also with it:currentpointed at another release the key did sign and that is still inversions/(the check proves a signed release, not which one;update.jsonis the broker’s to write); everything indata_dir(the site’s keys, the control plane, the backups: the seal of the pre-update backup is undersecrets.key, which the same user reads, so it stops a file that was damaged or swapped by mistake, not that user); the configuration when the broker’s user may write it. A process link under the broker’s uid is inside the trust boundary until links get a uid of their own. rollback_update {confirm_site}while the old version and the backup are kept: marksupdate.json, stops; the guard does the rest. Refused for a caller that comes through an upstream, asrestore_apply replaceis: it puts the control plane back.- How long a confirmed update can be rolled back (review of PR 74, point 2).
keep_untilis the confirmation +keep_days. One reading of the clock removes nothing (a host without a clock battery starts with a wrong time): the old version’s directory goes and the backup is unpinned only when the time was pastkeep_untilat two starts of the broker, or for a full hour of one run (UpdateFile::expire); a clock that is beforekeep_untilagain forgets the starts counted. Never during a trial, and after a rollback only once the version it left current came up. updatethrough an upstream (allow_config) is allowed, as §2.8 says: what may run is decided by the keys this host pinned and by the version rules, not by the caller, and both hosts opted in (updates.mode: "self",allow_config).- Standby pair (§2.8), as built. The standby runs no router, so it has no
sys: it cannot be reached “through its ownsys”. Instead the active stages a release for it:update {target: "standby", upload, release, signature, confirm_site}checks the release and the archive’s SHA-256 and keeps both indata_dir/update.standby. With every fifth poll the standby tells the active its version and update state (sys/replication/update/<version>/<state>/<to>) and gets the order; it fetches the archive in parts of 1 MiB (update_part/<offset>/<len>), checks the signature under its own pinned keys, the rules, the SHA-256, unpacks, runsrelease-infoandcheck --stateon its followed stores, writesupdate.jsonwithrole: standby, switches and stops. It is proven when it has made one complete sync on the new version by the end of its trial; else it ends with 76 and its guard takes the version back (nothing is restored: a standby follows).updatefor the active is then allowed only when the standby is connected and reports that version, confirmed;without_standby: trueallows it when the standby is not connected. A release whose replication protocol differs from the running one is refused for a pair (one host after the other cannot follow across it): both hosts are updated by hand. Before it stops, the active asks the standby to wait 120 s; if the new active is not back by then the standby, already on the new version, takes over. The active auditsupdate_startandupdate_confirmed/update_rollbackwith the keystandbyand showssys/standby_versionandsys/standby_update. An order carries the release document and its own signature, from the upload or from the index entry. The guard is looked for before the start of the process (UpdateConfig::process_start), not of the daemon: a promoted standby opens its daemon hours after it started, andupdatewas refused on it until a restart (review of PR 74, point 3). A standby in its trial counts run time as the active does. When its guard takes a version back it restores nothing: a standby follows, and what it holds are the active’s records as they were sent (the old version reads them). A standby that was promoted during its trial and wrote with the new version has no pre-update backup: if the old version then does not come up, the guard’s three-starts rule makes the new one current again. - Audit:
update_start(at the commit, with the archive’s SHA-256, the backup, the SCHEMA moved; with statusinternal_errorwhen an update ends before the switch),update_confirmed,update_rollback(at the call ofrollback_update, and by the version that serves after a rollback, with the reason and whether the control plane was restored). - Looked at after the review (the places it did not read).
fetch::get: TLS with the webpki roots and the default verifier, at most three redirects, each target parsed again (https, or http to loopback only: an https URL may be redirected to the broker’s own loopback, and what comes back is still checked against a signature or a signed hash), a size limit (the signed size for an archive) and one time limit for the whole exchange.backup_now: the job is pinned from the moment it is made, before a byte is written, and the SHA-256 inupdate.jsonis of the finished file.sys/replication/updateandupdate_part: the queryable is the standby’s alone (ACL subjectstandby, a certificatestandby:<site>of the site’s CA); version, state and offset are checked, a part is at most 1 MiB; a holder of that certificate could report a standby as updated, which lets the active update without one (aswithout_standbydoes). Exit code 76 under the documented unit:Restart=alwaysstarts the guard again; the guide says not to prevent it and not to set a start limit below 8. - Not built: a built-in release key and a published index (the workflow file is in
packaging/wyrmd, not enabled); a list of checks as the answer ofupdate?check; the link’swyrm_linkprotocol check before an update; cross-version replication; a uid of their own for process links; a watchdog for a new version that hangs; Windows.
3. Backups
- Format:
.wyrm-backup, a zip withmanifest.jsonfirst:wyrm_backup: 1,site,broker(version),created,schemas(registry, users, flows, audit),sealed(how keys and secrets are sealed:passphrasewith Argon2id parameters, orbroker), andsections[], each with its files, sizes and SHA-256. A link backup is the same format withkind: "link", extension.wyrm-link. The format lives inwyrm_admin::backup(wyrmdreaches it too). Rules of thesealedfield and of the reader (2026-11-13, after the security review of the first commit):sealed: {how, kdf?, check, id, mac}.howisnone,passphrase(Argon2id, parameters inkdf, bounded by the reader) orbroker(a key derived fromsecrets.key).idis 16 random bytes per backup; it is part of every file key, so a sealed part of another backup under the same passphrase does not open.macis HMAC-SHA-256 over the whole manifest (every path, size, SHA-256,sealedandexecflag, everyinfo) under a key from the master key andid.- A manifest with
how: passphrase | brokerand noid,checkormacis refused. The master key is handed out only after the MAC matches (Manifest::key); a restore of a sealed backup always asks for the key, also for its plain sections. - The reader, not the file, decides what must be sealed: every file of
keys; inlinkseach link’ssecrets,tokenandfiles/**; every file of a link backup’sdata. A manifest that lists one of them withsealed: falseis refused, and so is any such file in a backup withhow: none.link.cborholds no secret (no token hash; params are linted at install). - A sealed file is a stream of parts of 1 MiB, each ChaCha20-Poly1305 under a key of its own file and backup, bound to its index and to the end of the stream.
- Bounds: at most 100 000 entries, a manifest of 16 MiB, a path of 512 bytes and 24 segments without
.,..,\,:; each file at most 1 TiB; sizes are added with an overflow check; every zip entry must be listed with its size, and every file is hashed as it is read. - A backup with
how: nonehas no secret in it and no MAC: its SHA-256 (shown insys/backups/<id>) is what proves it unchanged.
- Sections:
control(registry, users, flows store and audit: their WAL and snapshot as of one sequence number; always included, needed by the others),keys(CA,state.key,secrets.key,flows.key, gateway keys,secrets.bin, link tokens; sealed, never in clear),dataflows(the flow store; also insidecontrol, listed for restore by itself),storage(the storage tree aswyrm_storageexport plus its redb file),history(day files of a chosen range andindex.redb),links(per chosen link: itsLinkDef, the frameworkexportwhen it has one, its private data dir sealed, its package archive),packages(all package archives),config(a copy ofwyrmd.json5for people to read, never restored; masked by default, see “Decided after the review of PR 72”, 13). - Consistency while running: WAL stores are copied as of one sequence; redb files are copied from inside one read transaction each; history days are copied whole (closed days) or through
Store::changesfor today; the storage journal fixes the storage at onerev. These are the standby’s primitives (control/replication.rs), reused, not copied. - API at
sys/backups(config, audited; the arguments never carry the passphrase into the audit):create {sections, links?, history_days?, passphrase?}→{id}; a job, one at a time;sys/backups/<id>showsstatus,progress,size,sha256,created,expires;download_part {offset, len ≤ 16 MiB}(as ADR 0028),remove;- Secrets leave the broker only when the host allows it (security review, 2026-11-13).
backups.export_secretsinwyrmd.json5, defaultfalse. Whilefalse:keysis refused, apassphraseis refused (the message names the option), link secrets and private data are sealed withhow: brokerand open only on a broker that holds this site’s keys; every other section works. Whiletrue: a passphrase of at least 12 characters (Argon2id, askeys export) seals them;backup_createis audited withkeys: true|falseandsecrets: true|falseand logged atwarn. A caller whose token a limited key signed (an upstream withallow_config) is refusedkeysand a passphrase in both cases: a downstream site’s keys never travel up.sys/backupshas the attributeexport_secrets. Theconfigsection is the configuration as JSON, masked by default (decision 13 below). send {link, connection, path?}onsys/backups/<id>: the broker writes the file through a file-store link (S3, WebDAV, Google Drive, localfs) with its own key. Decided 2026-11-13 (the admin has no signing key links trust, and a grant “to the admin” would need registry state): the host names the links inbackups.send_links(wyrmd.json5, default empty =sendrefused). For those links only, the broker adds one limited key to the link’s trust (LinkConfig.limited_keys, as the flow key and requester keys reach it; embedded links at start, process links inhello): the backup sender key, atwrite, scoped towy/<site>/downstream/<link>, bound to the subjectbroker:backup. The key is a secret the broker makes on first use (secret store entrybroker:backup-sender, no link’s secret, so in no link backup); no registry state, no SCHEMA change.senduploads with the link’s ownupload_begin/upload_part/upload_commit(ADR 0028) in parts of 1 MiB with the backup’s SHA-256, answers{to, upload, parts}once the link took the upload, and goes on in the background:sys/backups/<id>showssent_to,send_status(sending,done,failed),send_progress,send_error; one send at a time.sys/backupshas the attributesend_links.sendis no deputy of its caller (security review ofsend.rs, 2026-11-13). The broker writes with its own key for whoever hasconfigonsys, whatever that caller may do on the link, so the host decides where a backup may land:- An entry of
backups.send_linksis{link, folder}; a plain link id means the folderbackups. One folder a link.folderis relative, of plain names (checked when the broker starts). - The caller names
connection(one name) andpath: a file name, or sub-folders and a file name, of checked segments (not absolute, no.., no empty segment, no\or:); default the backup’s own file name. It is always joined under<connection>/files/<folder>. A path that climbs out is refused by the broker before any call to the link. - Every token of a send is good for
…/<link>/<connection>/files/<folder>/**and for the four keys…/<link>/<connection>/~act/{upload_part, upload_commit, upload_status, upload_abort}only, atwrite. That is as narrow as the file-store key layout allows: those four are actions of the connection node, and they act only on uploads the same subject began, so only on ones begun in the folder. The limited key itself stays scoped to the link’s subtree (a scope is a prefix, and the connection is not known when the link starts). sendnever overwrites:overwrite: falsealways; the link refuses a name that exists (its tree, andIf-None-Match: *at the store), so a send replaces no file.- The admin’s audit record
backup_sendcarries the caller as its subject and, in its detail, the link, the path, the size and the SHA-256 (the backup id is its key), at the start and at the end. The link’s own audit namesclaimed:broker:backup: the upload actions take no note or claimed subject, so the caller is not in the link’s records. - A backup that holds
keysis never sent. A send of any other backup is allowed to a caller from an upstream too: the host named the destination.
- An entry of
- kept under
data_dir/backupsforbackups.keep_days(7) withinbackups.max_mb(oldest removed first; pre-update backups of an unconfirmed update are never removed).
- Link backup:
sys/links/<id>/~act/backup {sections: [settings, data, package, history], history_days?, passphrase?}→ a job insys/backupswithkind: link. Restore:sys/links/~act/install_backup(Add a link ▸ From backup) with the file in parts,id(same or new),accept(its grants and net, asinstall_*),passphrase; replacing an existing link takes a restore point first. Rules of the restore (security review, 2026-11-13): a backup carries a package as its files only, never a registry record; the files are packed again and passpackages::unpack, the validator ofinstall_zip(entry ofComponent::Normalparts and among the files, requester grants throughcheck_grantand the whole-root rule, WASM world and capabilities, SHA-256 of the files), which builds thePackageDef. TheLinkDefpasses the checks of a new link before anything is written:validate_new_link_idfor a new id, the driver,lint_params, the driver’s own validation, every grant throughcheck_grant.acceptcovers the link’s grants and net and the requester grants and net of a package the install brings. Secrets a broker makes for a link’s identity (requester key, agent signing key) are filtered on export and on restore by one predicate; the token is in no link backup. - Restore of a broker backup:
restore_begin/restore_part/restore_check {passphrase}(returns the checks: site, keys, versions, what differs) /restore_apply {sections, mode}:mode: add: live, no restart; only links, dataflows and storage nodes that do not exist yet;mode: replace: a backup of what is replaced is made first, the chosen sections are staged intodata_dir/restore.pending, the broker stops, and the next start applies them before opening any store (and removes the folder).- The
keyssection of another site is refused unlessreplace_keys: true(it changes the site’s identity: peers and process links must enrol again; the check says which). Decided 2026-11-13: “another site” means another CA under the same site name; a backup of another site name is always refused. Thepre-restorebackup holds the old keys only when keys are replaced, under the same passphrase. - Rules of the restore (automated security review of
restore_broker.rs, 2026-11-13; each has a negative test):- Every restore of
keyspasses the gates:backups.export_secrets: true, a caller of this site, the passphrase. The CA does not decide: a backup with this broker’sca.pemand anotherstate.key,secrets.key, gateway key,secrets.binor link token takes the site over as well.replace_keys: trueis needed unless every key file of the backup is byte for byte this broker’s;restore_checkanswerskeys: none | same | differ | otherand lists the files inkeys_differ. - A restore writes only files a section defines. Under
keys/: exactly the key files of the bundle (key_files()),secrets.bin, andlinks/<valid link id>/token.control/<store>/<file>for the four WAL stores;dataflows/artifacts/**;storage/{tree.cbor, export.json};history/index.redb,history/days/<day>.redb;links/<valid link id>/{link.cbor, secrets, files/**};packages/<name>/files/**;config/wyrmd.json. Any other path refuses the whole backup, inrestore_checkand in both modes. Every destination is built from the checked parts (Place), never by joining a path of the archive. - Broker-made link secrets. Without
keys,replaceputs a link’s secrets into this broker’s store and drops the ones a broker makes for a link’s identity, with the predicate ofinstall_backup(broker_made_secret), at staging and again at the start that applies the plan. Withkeys,secrets.bincomes back whole, the broker-made secrets in it: they are the restored site’s own identity and came through the gates of rule 1; filtering them would leave a restored site whose links lost their requester keys for no gain. mode: replaceis refused for a caller from an upstream (allow_config), before the file is read;mode: addstays, with itsaccept. Inreplace, packages passpackages::unpackand what they ask for (requester grants, network) needsaccept, unless this broker has the same version with the same files. The detection of such a caller (Caller.signer.is_some()) is proved by e2echain_of_three_brokers(central calls edge’srestore_apply), the local side bybackup_restores_into_a_fresh_data_dir.addtakeslinksandstorage; flows needreplace(a deploy carries proofs).controlunder other keys goes only withkeys; withstate_anchor_dirit is restored offline. The audit journal is replaced only withstate.key. Audit:restore_applyat the call,restore_appliedat the start that applied it.
- Every restore of
4. Rights and audit
config on sys is not enough for the site’s secrets: see §3.4 (backups.export_secrets, never for an upstream caller). Every action here is config on sys (or on sys/links / sys/packages), only the admin role reaches it through the gateway (ADR 0009), and an upstream only with allow_config. Audit records: package_update, update_rollback, restore_point, update_start, update_confirmed, backup_create, backup_download, backup_send, restore_apply, link_backup, link_restore. A backup is as sensitive as data_dir: Studio says so where it is made and downloaded.
Consequences
- Package updates stop being one-way; the kept previous version and the restore points cost disk (a few MiB per link) for
keep_previous_days. - The package manifest gains
state/reads_state(ADR 0011 format note); older packages read asstate: 1. wyrmdgainsupdate-guard, a release workflow and a signed index; self-update is opt-in (updates.mode: "self") and needs the new install layout.- Backups no longer need the broker stopped;
docs/operations.md§3 keeps the offline copy as the way for a dead broker. - New tests: e2e update of a package with a link that loses keys (rolls back), an update that changes
state, a broker update whose trial fails (guard rolls back, SCHEMA restored;crates/wyrmd/tests/update.rs), backup while writing and restore into a freshdata_dir, a link backup restored on a second broker under a new id.
Decided during the build of §3 (2026-11-13)
Guide: docs/backups.md. Code: wyrm_admin::backup (format), wyrm_admin::control::{backups, restore}.
- Order. Link backup and
install_backup(§3.5) and the job plumbing ofsys/backups(create,download_part,remove) come first; the broker restore (§3.6) andsendfollow. controlholds every WAL once. Registry, flow store, gateway users and audit arecontrol/<store>/wal.…wyw, each copied as of one sequence number and checked against its HMAC chain (wyrm_state::replicate::copy_to, beside the standby’srecords_after). Thedataflowssection adds only the flow artifacts and namescontrol/flowsas its store, so no WAL is in a file twice.- Storage is a tree, not a redb file.
storage/tree.cboris the standby’s full page at one revision (Store::changes_since), withstorage/export.jsonfor people. The redb file is rebuilt from it on restore; a raw copy of an open redb file is never taken. - History, today included, is copied inside one read transaction per file (
Store::copy_day, thencopy_index), not throughStore::changes: the days first and the index last, so the index knows every series and journal number the days hold. - Packages are files, not archives. The original zip is not kept after an install, so a package goes into a backup as its unpacked files (
wyrm-link.jsonamong them) with their execute bits, and nothing else. A restore packs them again (packages::repack, the same bytes for the same files) and runs the install validator; the SHA-256 in the registry is then of that zip. It installs the package only when the broker has no version of it; the same version must hold the same files; another version is refused (§1.8, one version per package). - A link’s
settingsis its definition. The framework’s runtime edits are indata(framework.tree, sealed); the frameworkexportJSON is not added, because the admin holds no key that may call a link’sexport.link.cborcarries no token hash. - Restored under another id, a framework tree is sealed again for the new id with the store key that came with it (
wyrm_link_sdk::driver::persist::rebind): the tree is bound to its link’s id. Secrets a broker makes for a link’s identity (requester key, agent key) and its token are never carried over. - An existing link is replaced in place (stop, restore point, params, data, start), never removed and installed again: the id of a removed remote link is retired (ADR 0006). It must run the same driver in the same mode and not come from
wyrmd.json5. - Without a passphrase secret-bearing parts are sealed for the site (
how: broker);keysis refused. See §3.4. - Uploads (
restore_begin,restore_part,restore_abort) are sequential parts of at most 16 MiB, two open at once, removed after an hour without a part.install_backupalso takes the file itself (file). - Limits.
backups.max_mbdefaults to 2048; the newest backup and a pinned one are never pruned; a failed job is forgotten after a day; a job needs about twice its estimate free on the disk ofdata_dir. - Audit.
backup_create,link_backup(one record at the start, one more if it fails),backup_download(once per download, at offset 0),backup_remove,restore_point,link_restore. The admin writes its own journal (no hash of the arguments), so the passphrase is in no record.
Decided after the review of PR 72 (2026-11-13)
- A rollback applies the restore points its update took. The update stores
(link, point id)of each point in the kept version’s record (PreviousDef.points), and reads the time of the update after the last point. A rollback applies exactly those points. A link without one gets none, never an older point. A record without names (made by the first build) keeps the old rule: the newest point at or beforereplaced. - One operation on a package or a link at a time (§1.9). An update (to the end of its health check), a rollback, an install, a package removal and a restore of a link take the package from their first step (
Control::claim_package); a restore of a link also takes the link (claim_link). The claim is given back when its holder ends, whatever way. While a claim is held,start,stop,remove,updateandrollbackof the link, a backup that copies its data, and a restore withmode: replaceanswerbusy. While a backup copies a link’s data, or areplaceis staged, no claim is given. Each side shows itself first and then looks, so one of the two always sees the other. - A rollback is recorded before it changes anything.
data_dir/restore/.rollback/<package>.cbornames the version, the kept record and each link’s point. A broker that ends in the middle finishes it at its next start, before any link runs (Control::complete_rollbacks); every step may run again. - A link whose data did not come back is held. When the update changed the store format and a link’s restore point does not apply, the link is not started:
data_dir/links/<id>/holdholds the reason,startanswers it,last_update.reasonand the audit name the link. A start of the broker skips a held link. A restore of the link’s data lifts the hold;start {force: true}lifts it by hand. Without a change of the store format the data stays and the link starts, as before. - A restore of a link’s data is all or nothing (§3.5). The steps:
data→data.replaced;data.restoring→data; the new secrets, with the old ones kept beside them in the same save ofsecrets.bin;data.replaced→data.done(the commit); the kept secrets anddata.donego. Until the commit an error, or the next start of the broker (Control::recover_link_data), puts the old data and the old secrets back; after it the new ones stay. The link’s params are applied last. A framework tree is sealed for a new id in the new directory, before the swap. - Key derivation of a backup is bounded for a small host (§3.1). The Argon2id parameters of a manifest run before its MAC can be checked. The reader takes at most 128 MiB, 4 passes and 4 lanes (a broker writes 19 MiB, 2 passes, 1 lane). A restore derives the key once and uses it for every link of the file.
- What a backup opens into is bounded before a byte is extracted (§3.1). The reader already stops each entry at its listed size and takes at most 64 GiB (8 GiB for a link backup). Added: a file may declare at most 200 times its own size plus 64 MiB; one package holds at most 256 MiB, one flow artifact 64 MiB, one link’s private data 8 GiB; and before a restore opens anything, what it will open (plus the largest sealed file once more, plus 64 MiB) must fit on the disk of
data_dir. - A staged restore is all or nothing and never stops the broker (§3.6). The staging parses all that the start will read (the storage is built from its tree, the history files and the secret store are opened, the plan is read back). The start writes what was there (
before.json), sets aside what the plan replaces or removes (restore.pending/old/), and moves the new state in. It commits only after the stores have opened: the folder is renamed torestore.done, then removed. When a step fails, or a store does not open, everything set aside goes back; the folder becomesrestore.failedwithplan.jsonanderror.txtonly, and the broker runs on the state it had. The audit getsrestore_failedonce. Every step, the undo too, may run again after a start that stopped in it. The start fails only when the old state cannot be put back. - The upstream rule holds for a download too (§3.4).
download_partrefuses a caller from an upstream when the backup holdskeysor secrets sealed with a passphrase, whoever made it. A backup sealed for this broker, or without secrets, may be downloaded from above.sendis unchanged: it gives no bytes to its caller, the host names the destination, and a backup withkeysis never sent. - No orphan of an install stays (§1). A start removes, under
data_dir/packages, every.tmp-*and.git-*directory and every version directory that neither a package record nor its kept previous version names. An install or an update of a version removes such a directory first; only the kept previous version with other content is still refused. - A rollback restores the links’ data only when it must, is suspect, or is asked (§1.6).
rollback {restore_data?}. Defaulttruewhen the update changed the store format (falseis then refused), when the update did not endok, or when it lost nodes (gone> 0); the rollback of the health check always restores. Defaultfalsefor an update that ended well: the links keep the data they have, with all that was configured since.last_update.reasonand the audit say which of the two was done. - A restore point is a copy file by file (§1.3). Each file is whole: the portable store,
framework.treeand the agent’s snapshot are written by rename, and a WAL with a torn tail is read up to it. The files of a link that runs are not of one moment. When the update changes the store format, the restore point is the only way back, so the links of the package stop for the copy (their key lists are read first) and start on the new version, or again on the old one when the update fails before the registry is written. For other updates the copy is taken while the links run, as §1.3 says. - The
configsection is masked by default and shown by list (§3.2). A list of names to hide kept leaking (camel case, joined words,name = valueinside a text), so the rule is the other way round. A text ofwyrmd.json5is in clear only when its key path is inCONFIG_SHOWN(wyrmd): fields known to hold no secret. Every other text is replaced by***, whole: every text underlinks.*.paramsanduplink.upstreams, under an unknown section, free text. Nothing is parsed forname=valuepieces. Numbers and flags are kept. Under the list there is a second net, never the only guard: a shown text, URL or Zenoh locator or other, loses everything after its first?or#(a query, a locator’s config) and the userinfo before an@; a PEM private key is masked anywhere; a shown text or a number under a name that says secret is masked. A test reads the config structs from the sources and fails when a text field is on neitherCONFIG_SHOWNnorCONFIG_MASKED. Declaredsecretparams of drivers are not used: the configuration holds bootstrap params only, and under this rule every text of them is masked anyway.
Decided after the audit of PR 152 (2026-11-20)
- What a version in its trial leaves on disk is what the version before it opens. A kill in a trial is followed by the previous version (§2.5), so a new on-disk form may not appear before
update_confirmed. First case: the audit journal’s group commit announces a batch in the anchor (<lsn> <mac> +<n>,state_anchor_dir), which a version from before it refuses with more than one record after the head; the guard then failed three starts of the old version and made the failed new one current again. Whileupdate.jsonsaystrial(from the staging of an update to its confirmation, read atControl::openand at both changes:Control::audit_follows_update), the journal writes record by record with the plain anchor (Journal::one_by_one). The same from the moment a rollback of a confirmed update is asked (rollback_updatewrites who asked intoupdate.json; second audit of PR 152): the predicate is “the previous version may be the next to open these files” (previous_version_may_start:trial, orconfirmedwithrollbackset), every change ofupdate.jsonby the running broker that moves it goes throughControl::save_update, and switching it on returns only when a batch in flight is on disk and the anchor is the plain head, before the action answers. The order matters where the running version is the newer one (third audit of PR 152):rollback_updateswitches the journal first (Control::audit_one_by_one, an error goes to the caller) and writesupdate.jsononly after the writer answered, so a kill finds either no rollback asked or a journal the previous version opens; with the file first, a batch announced between the two was refused by the previous version. A change that lets batches come back (confirmed, rolled back) keeps the file first. Staging an update needs no order: the version that stages is the one the guard goes back to, and it opens its own batches; the new version switches atControl::open, before its first record. Other ways to an older binary were looked at: the guard’s way back after exit 76 or a kill is inside the trial; a standby updates as a broker of its own with its ownupdate.json;restore_applyreplaceis applied by the same version at its next start; a downgrade by hand is a stop. The WAL itself has one form in all versions. A later change of a store’s files follows the same rule: the old form until the confirmation, or a SCHEMA move with the pre-update backup.
Not decided here
- Scheduled backups (a scheduler target can call
sys/backups/~act/createonce this exists; ADR 0022). - Updates of many sites at once from a central broker (one action per site for now).
- Delta backups of history.
ADR 0049 — What the agent link and the gateway need for the Studio Assistant
Status: proposed (2026-11-14). Design: canvas row Assistant (AssistantAsk, Assistant, AssistantRun, AssistantDone, AssistantFailed, AssistantRights, AssistantDrawer). Studio side: studio/docs/design/specs/assistant.md. Extends ADR 0005 (AI surface) and ADR 0033 (agent command line); closes docs/studio.md §10 items 1, 3, 5, 11, 12.
Context
The Studio Assistant (phase 12, docs/studio.md §7.8) is a chat with the agent link (links/agent): ask streams the model’s lines and its reads, the task list follows tasks/* ~val, Reject and Cancel work. The boards show more than the broker can give today:
| Board shows | Broker today |
|---|---|
| The plan with every step, its arguments, level, check result and the model’s why | The plan is in the task’s ~state document; the gateway has no op that reads documents (ws.rs: meta, children, list, subscribe, history, set, invoke, check) |
| Approve signs one token per ticked step with the user’s rights | approve {approvals} wants one human ptok per request key, signed by the approver; a gateway user has no key. The action itself is level config |
| Unticked steps are left out | approve refuses unless every step that needs approval has a token (missing approval for …) |
The assistant asks back with choice cards (AssistantAsk) | No tool for asking the user, no state for it, no answer |
WAIT / EXPECT steps (the plan proves itself) | Agent plans hold set/invoke only; wait/expect exist only in wyrm_mcp::gw::Step (plans of wyrm-agent run / MCP plan_run) |
| Run card with the current step and its answer | ~val of a task is {state}; per-step results are only in ~state |
| Try Slave ID 4, Undo the plan, Make a plan for 2 units | Every ask starts from nothing |
@ modbus/tcp-line2 chips, the Explorer drawer about the selection | ask {task} takes text only |
| Today 182 k of 1 M tokens, API key set · never shown | The budget used is internal; secret names are not readable |
| A warning on a step (Slave ID 3 was used by ahu-old) with fixes | propose returns ok or an error, nothing in between |
Decision
- Documents through the gateway. A gateway op
doc {key, suffix}(suffix∈~state,~def) answers a node’s document with the rights ofliston that node (the agent’stasksfolder isrestricted, so the asker or a config caller). Studio reads a task’s record with it after every state change. - Approvals through the gateway. On
invoke(<agent>/tasks/<id>, approve, {steps: [i…]})from a user, the gateway reads the task’s plan (op 1), mints one user token per listed step for that step’s key and level, exactly asadd_flow_proofsdoes for flow deploys, and refuses (before anything is sent) when the user’s grants do not reach a step. The token’ssubis the user, so the agent’s “approver = signer” check holds. Callers outside the gateway keep sendingapprovals. - Approve at the step’s level.
approvebecomes levelwriteon the task; what a person may approve is decided by the tokens (a token atconfigfor aconfigstep). An engineer withconfigondownstream/modbus/**approves a Modbus plan withoutconfigon the agent link. - Partial approval.
approveaccepts a subset: the steps without a token are markedskipped(log lineskipped by <sub>), never run; a step the model markedafter: [n]is skipped when a step it depends on is.proposetakesafter(default: the previous step on the same key prefix). Approval tokens are keyed by step index (approvals: {"<i>": ptok}), not by request key, so two steps on one key both work; the key form stays accepted. - Asking back. A model tool
ask_user {question, options: [{id, label, detail}], multiple?, free_text?}(≤ 3 questions per turn, ≤ 6 options each, options must name things the model read). The task goes to a new stateawaiting_answer(wire_enum!row in the task states; Studio maps it).tasks/<id>/~act/answer {answers: {<question>: [<option id>] | text}}(levelwrite, asker or config) resumes the model with the answers.~statecarriesquestions[]. - Proof steps. Agent plans take the steps of
wyrm_mcp::gw::Step:wait {key, timeout_s},expect {key, equals | min/max | changes, timeout_s},sleep. They need no approval (read). The plan format of~state.plan[]becomes thewyrm-agent runformat, so Save as a plan is the plan as it stands. - Progress in
~val. A task’s public~valbecomes{state, step, of, last}(last={n, ok, text}of the latest finished step), published at each step.~statekeeps per-stepresult(ok | failed | skipped, text, time). - Checks and warnings on proposed steps.
proposeanswers{ok, check, warn?}:check=now(checked against the live tree) orat_run(depends on an earlier step);warn= text the model must show (a slave id in use, a value at a limit). Studio drawswarnon the step; the model offers fixes as anask_user. - Follow-up asks and context.
ask {task, parent?, context?: [key…]}:parenthands the model the parent task’s ask, plan and results (a retry, an undo, the same for more rows);contextare keys the person attached (@chips, the Explorer selection), read first and within the asker’s rights. Undo is a follow-up ask the model plans like any other; nothing is reversed automatically. - What it may do, readable. The agent root shows
budget_used_today(u64, read).sys/links/<id>showssecrets(names only, levelconfig), so Studio can say set / not set forapi_key_ref(docs/studio.md§10 item 12).
Rules added when it was built (2026-11-14)
The decisions above stand. These rules make them safe; items 2, 3 and 7 are narrower than their first wording.
- The gateway signs only what it read (§2). The plan is the one the agent link stores: the gateway reads
tasks/<id>/~stateitself, with the user’s own token. The client sends{steps: [n…], plan: <hash>}and nothing else of a step. Withapprovalsin the arguments the caller brings its own tokens and the gateway adds nothing. - An approval is for the plan the user saw (§2). The plan’s hash is the SHA-256 (hex) of the canonical CBOR of
~state.plan, each step withoutapproval,check,warn,model_warn,reason,result(model_warnsince the amendment of 2026-11-14). Studio makes it from the plan it shows, the gateway from the plan it reads (never from~state.plan_hash, which it only compares), the link from the plan it holds.approve {plan}is refused when they differ (invalid_parameter, “read it again”). - One token, one step (§2). A token’s subject is the user; its single grant is exactly the step’s request key (
<node>/~set,<node>/~act/<action>);maxis the level the step needs, not the user’s level;argsis the SHA-256 of the step’s request body (spec 04), so it is good for those arguments only;jtiis fresh (single use);expis 5 min. The step’s node must be a plain key of the task’s site: no wildcard, no~segment. - An approval does not wait (§2). A token is made when the person approves and is spent when its step is sent; its life stays short (5 min from the gateway; spec 04 allows at most 15 min and one use). No token is made for later and none is made longer. So the agent link takes no step that needs a person into a plan when the waits before it (
wait/expecttimeouts,sleep) add up to more than 240 s:proposeanswers the model with the reason. Andapproveis refused (invalid_parameter, the task keeps waiting) when a token cannot outlive the waits before its step, among the steps that run, plus 30 s. The person leaves that step out and asks for the rest as a follow-up (§9) when the plan is done; it is approved then. A step that is still late (slow requests before it) fails closed: the target refuses the dead token and the run stops. - Only a person, only an agent link (§2). The gateway signs approvals for a person’s own session alone: a session of an MCP client (
/mcp, ADR 0041) is refused, and the Claude connector (wyrm-mcp --gateway) never sendsapprovefor a task. The level ofapproveiswrite, so the connector’sallow_configswitch would not have stopped aconfigstep. And it signs only forwy/<this site>/downstream/<link>/tasks/<id>where<link>has the driveragentin the broker’s registry (Gateway::set_agent_links, told at every router build): a link that only serves a plan-shaped~stategets no token of the user. - A person is told by the login, not by the transport (§2, 2026-11-14). The gateway treats a session as a person’s only when its frames come over
/api/ws(not the/mcppipe) AND its login method is a person’s:Amr::is_person=PasswordorDevice, an exhaustivematch(OAuth and any later method are not a person until written there). The same helper decides the approve gate,POST /api/ws-ticketand the/api/wsupgrade (403,permission_denied,code: person_required) and every step-up check indevices.rs. It tells how a session was made, not who drives it: a password session that a tool uses (wyrm-mcp --gateway --user) is still a person’s, and that connector’s refusal to sendapprovestays its own rule. - The meta of
approve(§2).approvedeclaresapprovals(not required),stepsandplan, so a client that checks arguments against~metatakes both forms.stepswithoutapprovalsthat reaches the link itself is refused: no gateway signed it. - Never beyond the user’s grants (§2). The gateway checks every named step against the user’s grants before it signs. If one fails, the whole call is refused before anything is sent, and the answer names the step and the right:
step 3 needs config on wy/…/~act/deploy; you have write. The refusal is in the audit (Denied, opapprove); a signed approval is too (approve, the request keys, the count left out). - Who approves (§3).
approveiswriteon the task, so the caller may be a stranger to the task. The asker, or a caller withconfigon the link, decides for the task: a step that needs no human runs with the agent’s key, as it would without an approval. Anybody else decides only for what they sign: every step that changes something needs their own token (the steps the agent would run with its own key too); a step without it isskipped, with the steps that need it, and nothing runs with the agent’s key on their word. So an engineer withconfigondownstream/modbus/**approves a Modbus plan withwriteon the agent link, by signing its steps. - Proof steps (§6) read with the agent’s reader, inside
allowed_prefixes, and take no token. A step on a node that an earlier step makes ischeck: at_run: taken atwrite, and checked against the live~metawhen it runs; a node that then asks for more, or for other arguments, stops the step before it is sent. - The public
~valholds no text (§7).~valis read by anyone who may read the link; the record is restricted. Solastis{n, ok, result}withresultone ofok,failed,skipped: not{n, ok, text}. The text of a result, the value read and the node key are in~state.plan[n].result {status, message, time}, which Studio reads throughdoc. - Asking back (§5). A restart ends a task that waits for an answer (
interrupted by restart), as it ends planning: the model’s turns are in memory.answeris a stream likeask; theaskstream ends withawaiting_answer. - Follow-ups (§9).
parentmust be a task the caller asked, or the caller hasconfigon the link. Acontextkey must be inside what the agent may read and inside what the asker may read (authof the caller’s token). The asker’s rights are read as every evaluator reads grants (spec 04): the first grant that touches the key decides (Caller::perm_on,wyrm_core::ptok::level_on), so anonebefore a wider grant keeps the value out of the model’s prompt. - Secret names (§10) are the action
sys/links/<id>▸secrets(levelconfig, names only), not a value: a~valis read atread. - Task states are the agent link’s own table (
TaskState,wire_enum!, by name in~val.state); they are not inspec/. The gateway’s frame protocol is documented incrates/wyrm-gateway/src/ws.rsanddocs/broker.md; nospec/text changed.
Amendment (2026-11-14): what the model offers next, a replaced plan, fixes on a step
Studio built specs/assistant.md §2 steps 1–4 and found three cards without data: the ways out of a stopped run and the Same for more units? rows (and the second button of the Explorer drawer), the old plan shown as replaced, and the fixes in a step’s warning. The owner delegated the design (ADR 0029). One tool, three record fields and one rule close them; no spec/ text changed.
1. Suggestions. A model tool suggest {label, detail?, changes?, step?, rows?: [{path, label, detail?}]} adds one entry to the task’s record: ~state.suggestions[] = {id, label, detail, changes, step?, rows?: [{key, label, detail}]}.
- It is what the person may ask next: a way out of a run that stopped, the same change for more nodes (
rows, one per node), a fix for the warning of plan stepstep, the drawer’s second button.changesis the model’s count of the changes it would take (0: nothing changes): the tag on the tile, nothing more. - A suggestion is data and runs nothing. The link never acts on one, and the gateway never reads one. A person who picks it sends a follow-up
ask {parent, task, context?}(§9) whose text is what they saw on the card (label,detail, the labels of the ticked rows) and whosecontextis the keys of the ticked rows. What that changes is a new plan, checked as any plan and approved step by step with the person’s own tokens (§2–4). - Bounded. At most 8 suggestions in a task at a time, 16 rows each (the
contextlimit ofask),label≤ 80 bytes,detail≤ 300 bytes (longer text is cut),changes≤ 50.stepmust be a step of the plan so far. - Inside the asker’s rights. A row names a plain node key of the task’s site that the agent may read (
allowed_prefixes,pub/**) and that the asker of the task may read (Caller::perm_on(<node>/~val)over the person’s grants that the token carries asauth, spec 04). Fail closed: the rights are known only from a token withauth(a token without it means unknown rights, and the row is refused, as the flow engine refuses sources), they are kept in memory only (after a restart of the link nobody’s rights are known), and they hold only until that token’sexp. The asker’s own lateranswerorapproveon the task renews them (their newer token); a call of somebody else does not. So a row of a planning turn after a long wait, or of a review after a restart, is refused, and the model offers the way out without rows. Any other row refuses the whole suggestion to the model.ask {context}needsauthin the same way (permission_denied). The follow-upaskchecks itscontextagainst its own caller again. The follow-upaskchecks itscontextagainst its own caller again. - Texts stay in the record. The public
~valgainssuggestions(their count, absent at 0) and no word of them. Studio reads them throughdocwith the reader’s rights. - After a run stopped. The model has no turn in a task that ended, so a run that stops at a step (a step failed; not a reject, a cancel or a restart) gets one: a review, at most
review_turnsLLM calls (param, default 4, 0 = none), with the read tools andsuggestonly. Nopropose, noask_user: nothing is planned and nobody is asked. The model gets the task’s ask, plan with results and error, reads why, and offers ways out. The task staysfailedand itserrorstays the run’s;~valand~stateshowreviewing: truewhile the turn runs; the model’s last words are~state.review(≤ 600 bytes). The turn spends the daily budget like planning; without budget or model it is skipped with a log line.cancel(asker or config) whilereviewingends the turn:reviewinggoes, noreview, the task staysfailedwith the run’s error. A task removed to make room (eviction) ends its review with it. - Suggestions follow the plan they were made for. A task that fails (a stopped run, reject, cancel, replaced, restart) drops what planning offered; after a stopped run the review’s ways out take their place. A task that is
donekeeps them: the Same for more units? table of the result card.
2. A replaced plan. ask {parent} where the parent waits for a person (awaiting_approval or awaiting_answer) takes the parent’s place: under the same lock that creates the new task, the parent goes to failed with error: "replaced by <id>" and the field replaced_by: <id>, in ~state and in the public ~val (a task id the link made, no text). No new state: failed is already how a plan ends that will not run (reject, cancel), so every reader of states stays right.
approveon a replaced task is refused withinvalid_parameter(0x23),task was replaced by <id>: … approve that task. The gateway refuses the same way from the record it reads, before it signs anything.answer,rejectandcancelare refused as for any task that ended.- A parent that is
planning,running,doneorfailedis not touched: a follow-up of it replaces nothing (a run goes on untilcancel; an undo of a done task is a new plan beside it). - If the follow-up fails while planning, the parent stays replaced: the person asks again (the failed follow-up or the old task as
parent). An old plan that came back after another one was asked for could be approved by mistake. - The mark is in the stored record, so it holds after a restart.
3. Fixes on a step. §8 said warn is text and fixes are an ask_user. Two things were missing: only the link could warn (a value at a limit), and nothing tied a fix to a step. Now propose takes warn (≤ 300 bytes), kept in the step’s own field model_warn: warn stays the link’s own finding (a value at a limit), so a reader always tells the link’s words from the model’s, and Studio shows model_warn as the model’s (a different label or style, never as a check of the link). A fix is a suggestion with step: n. Studio draws the suggestions of step n in that step’s warning box. A fix is picked like any suggestion: a follow-up ask {parent}, which replaces the waiting plan (rule 2) with a plan the person approves. So the plan with its warning can be approved as it is, or a fix picked, as the board Assistant shows; the spec’s “each fix = answer” does not hold (an answer exists only in awaiting_answer, where nothing can be approved). warn and model_warn stay outside the plan’s hash (UNHASHED in the link and the gateway, planUnhashed in wyrm_client). A client that still hashes model_warn makes another hash, and its approval is refused (“read it again”): it fails closed.
Old records and old clients. The three fields live in the record’s plan bytes beside questions, parent and context (store schema 1 unchanged); a record without them reads as no suggestions, not replaced, no review (test a_task_written_before_the_suggestions_still_loads, fixed bytes). A link of the version before reads the new records too (an ADR 0048 rollback): it skips the keys it does not know, and a replaced task is failed for it as well. A client that does not know the fields ignores them.
Which card shows which suggestions (specs/assistant.md §6): a PlanStepCard those with step = its number while the task is awaiting_approval; the ResultCard of a done task those with rows; the StoppedCard all of them with review; the Explorer drawer’s second button the first one without step. While the task is awaiting_approval, that button shows the suggestion’s detail as a draft to copy and sends no ask: a follow-up ask {parent} would replace the plan the person still means to approve (rule 2). After the task has ended, it is a follow-up ask like any way out. Picking a fix tile does replace the waiting plan, and the tile says so.
Tests: links/agent/tests/agent.rs a_stopped_run_gets_ways_out_and_a_step_gets_fixes, a_suggestion_is_bounded_and_inside_the_askers_rights, a_follow_up_replaces_a_task_that_waits_for_a_person; crates/wyrm-gateway a_replaced_plan_is_not_signed_and_suggestions_are_read_through_doc and the unit test of approve::Plan::select; dart/wyrm_client/test/agent_test.dart.
Amendment 2 (2026-11-14): what the model found
Studio built specs/assistant.md §2 step 6 and found one more card without data: the rows of What I found in the Explorer drawer (board AssistantDrawer). The model’s findings were only its text. The owner delegated the design (ADR 0029). One tool, one record field and one count close it; no spec/ text changed.
- A model tool
found {path, label, detail?}adds one row to the task’s record:~state.findings[] = {key, label, detail}. It is in the planning turns and in the turn after a stopped run (both only read). One row per node, in the order the model noted them. - The model’s words, no verdict.
labelanddetailare model text: a client shows them as plain text, never as a link, a check or a button. A row carries no mark good or bad. The board’s ✓ and ✕ are drawn by the client from the node’s live value (its quality), read with the viewer’s own rights; without a value the row has no mark. So a mark is never the model’s claim. - Bounded. At most 12 findings in a task;
label≤ 80 bytes,detail≤ 300 bytes (longer text is cut, the…inside the bound; the same for suggestions). One row per node: a second finding on a node replaces the words of its row in place (same order, same count), so the turn after a run corrects what planning noted instead of keeping a stale good. - Inside the asker’s rights, as the rows of a suggestion. The key is a plain node key of the task’s site (no wildcard, no
~segment) that the agent may read (allowed_prefixes,pub/**) and that the asker may read (Caller::perm_on(<node>/~val)≥readover the grants of their token’sauth). Fail closed: unknown rights (a token withoutauth, a restart) or rights past their token’sexprefuse the finding, and the model is told to note none (not to put the node into its answer). The same rule as amendment 1. - Why rows are missing. Each refusal is counted in
~state.findings_refused{rights_unknown | rights_expired | outside_rights | limit | invalid: <count>}: fixed words, no model text. Studio says from it why rows are missing. The rights last as long as the asker’s last call on the task (ask, their ownanswerorapprove): 5 min from the gateway (PTOK_TTL). Nothing renews them on its own (no rights-renewal code, by design), so findings are refused asrights_expiredwhen (1) the turn after a stopped run starts after another person approved the plan (the run’s end starts it, not a person, and that approval does not renew the asker’s rights), or (2) the run took more than about 5 min after the approval. - Texts stay in the record. The public
~valgainsfindings(their count, absent at 0) and no word of them, so a reader of~vallearns that the record changed, not what it says. Studio reads them throughdocwith the reader’s rights. - They stay. A finding says what was read, not what to do: unlike suggestions, findings are kept when the task fails (reject, cancel, replaced, a stopped run). They are no part of the plan and not in its hash.
- Old records.
findingslives in the record’splanbytes beside the fields of amendment 1 (store schema 1 unchanged). A record without it reads as no findings (testa_task_written_before_the_findings_still_loads, fixed bytes of the richest record of the version before). A link of the version before skips the key. The gateway is not touched:docpasses the record through, and no gateway code reads findings.
Tests: links/agent/tests/agent.rs findings_are_bounded_inside_the_askers_rights_and_stay; store unit tests; dart/wyrm_client/test/agent_test.dart (TaskFinding, findingCount).
Consequences
- One gateway op (
doc), one gateway rewrite ofapprove(like flow proofs), and agent link changes instore.rs(task schema:questions,after, per-stepresult; old tasks read with defaults) andlib.rs(ask_user,answer,awaiting_answer,wait/expect,~valprogress). docs/studio.md§10 items 1, 3, 5, 11, 12 close when this is built; §7.8’s “built now” paragraph is replaced bystudio/docs/design/specs/assistant.md.- e2e: ask → ask_user → answer → plan → partial approve (one step skipped, its dependant skipped) → wait/expect → done; approve refused for a user without the level;
docrefused withoutlist.
Not decided here
- Approvals through the gateway for a task on a downstream site. The gateway knows the agent links of its own site only, so
approve {steps}there is refused; Studio must lock Approve with that reason when the viewed site is not the gateway’s own. Open: the downstream broker tells its agent links upward, or the user’s gateway asks the downstream gateway to sign. - A second model for the Assistant (Claude through the user’s own connector, ADR 0041, instead of the agent link’s API key). The Studio screens stay the same; only who writes the plan changes.
- Generated views in the chat (A2UI,
specs/genui-views.md): a later card type.
ADR 0050 — Biometric unlock with device keys, and finding a gateway on the local network
Status: accepted (2026-11-14, owner request); gateway and wyrmd built 2026-11-14, Studio after it. The decisions taken while building are in the last section. Design: canvas rows Log in, part 2 (Unlock*, UnlockApp, UnlockPlatforms, Discover*). Studio side: studio/docs/design/specs/unlock-discover.md. Closes docs/studio.md §10 item 13 (gateway info before login).
Context
Studio logs in to a gateway with a user and a password (POST /api/login, a session of session_ttl). It remembers the gateway URLs and the user, never the password, so every start asks for it. The owner asks (2026-11-14) for:
- Biometric login, covering every case: Touch ID, Face ID, Windows Hello, Android fingerprint or face, computers with no biometrics, fingerprints that change, a device that is lost, and so on.
- Finding a broker on the local network from the log-in page.
Two constraints come from the platform rules. First, biometrics must not become a weaker password: the gateway decides who is in, not the client (principle 6). Second, nothing on the wire carries secrets or opens the broker to people who could not reach it before. A cached password or a long session token in the OS keychain behind a biometric check would also work, but the gateway could not see or revoke it, and a copied keychain item would replay it. So both are refused.
Decision
1. Device keys: the gateway checks a signature, the device checks the person
-
Registration. With a session that used the password within the last 5 minutes, Studio makes a P-256 key pair in the device’s secure hardware: the Secure Enclave on macOS and iOS (access control
biometryCurrentSet), the TPM through Windows Hello, or the Android Keystore withBIOMETRIC_STRONG,setInvalidatedByBiometricEnrollmentand StrongBox when the device has it. Studio then callsPOST /api/devices {name, platform, public_key, attestation?}. The gateway stores the record{id, user, user_generation, name, platform, public_key, added, last_used, password_at}in the users store (users SCHEMA 5), which the standby replicates (ADR 0036). It answers{device}. -
Unlock.
POST /api/device/challenge {device}→{nonce, exp ≤ 60 s}(single use, in memory). The OS prompt unlocks the key and Studio signswyrm-device-login/1 ‖ site ‖ gateway origin ‖ user ‖ device ‖ nonce. ThenPOST /api/device/login {device, nonce, signature}→ the same session as/api/login. The gateway refuses when:- the device is unknown or removed;
- the user’s generation moved (a password change signs every device out);
password_atis older thanpassword_every_days;- devices are off.
Each refusal is a distinct code (
device_removed,password_changed,password_due,devices_off), so Studio can say why (boardUnlockSignedOut).
-
Step-up. When
step_up: config, every request atconfiglevel needs a session confirmed in the last 5 minutes.POST /api/device/confirm {nonce, signature over the request hash}confirms with the device key;POST /api/confirm {password}confirms with the password. A refused request answersconfirm_requiredand Studio showsUnlockStepUp, then sends the request again. -
Idle lock. Local to Studio: after
lock_after_min(the gateway’sidle_lock_max_mincaps it), Studio hides the tree and values. Unlocking signs a fresh challenge withPOST /api/device/login {…, session}, which keeps the session. Without a device key it asks for the password. -
Visible and revocable.
GET /api/deviceslists the user’s own devices.DELETE /api/devices/<id>removes one, for the user or an admin./api/users/<u>/devicesgives an admin everyone’s.- Studio shows the user’s devices in Account › Security and everyone’s in Access › Users.
- Audit records:
device_added,device_login,device_refused,step_up,device_removed.
-
Policy (
wyrmd.json5gateway.devices):{ enabled: true, max_per_user: 5, password_every_days: 30, idle_lock_max_min: 30, step_up: "config" | "none", allow_device_credential: false }GET /api/infocarries it so the log-in page knows what to offer before login. Withallow_device_credential: false, an Android screen PIN or a Mac’s login password never stands in for biometrics; Windows Hello PIN counts as Hello.enabled: falsedoes not delete records; it refuses device logins, and Studio removes its key after the refusal. -
Never offered: Linux (no system prompt binds a key), kiosk sessions (no person), and devices whose biometrics are weak (class 2 face on Android) or not enrolled. A future web build uses passkeys (WebAuthn) against the same records: the record format leaves room for that.
-
Downstream sites are reached through the gateway of the upstream site, as today. A device key is per gateway, user and device. A standby gateway accepts it because the users store is replicated, and its origin is listed with the main one.
2. The gateway announces itself; the log-in page finds it
-
Announce.
wyrmdadvertises its gateway by DNS-SD on every non-loopback interface the gateway listens on: service_wyrm._tcp, instance name = site. Configgateway.announce: {enabled: true, interfaces?: [...]}; hardened sites turn it off. The TXT record has no users and no secrets:TXT key Value vwyrmd version sitesite name tls1or0fpfirst 16 bytes, in hex, of the SHA-256 of the CA certificate the gateway’s certificate chains to roleactiveorstandby(ADR 0036)pairthe other host’s host:portupupstream site, when this broker is a downstream The crate is
mdns-sd(pure Rust, no Avahi or Bonjour dependency). The announcement stops on SIGTERM and moves with a takeover (the new active announcesrole=active). -
GET /api/info(public, rate-limited like/api/login):{site, version, tls, ca_fp, role, pair, devices: {enabled, step_up}, min_studio}. It serves the probe oflogin.md§6, the trust step and the range probe. -
Studio finds.
- Find on this network browses
_wyrm._tcpfor 8 s. It shows one row per site: an active and its standby merge into one row, andupshows downstream sites. Each row is checked with/api/info. - Rows Studio cannot use are shown greyed with the reason: plain
httpoff loopback (insecure_plaintext), or a wyrmd version older thanmin_studio. - Picking a row fills the gateway and its standby.
- Trust. A gateway whose CA the device does not know shows its CA code (
ca_fpin 8 groups of 4). The person compares it with System › Gateway › Certificate code on the broker, or withwyrmd ca fingerprint(a new subcommand). Only after that does Studio pin that CA for that origin. Anything on the network can announce a name, so finding never means trusting. - Nothing found. Studio says why it may be: multicast blocked, local-network permission off, announce off. It offers Probe a range: an opt-in
GET /api/infoper address of a CIDR on one port, 16 at a time, at most 1 024 addresses. It also offers typing the address, or a code from the broker’s System page.
- Find on this network browses
-
Platform permissions:
- iOS:
NSLocalNetworkUsageDescriptionandNSBonjourServices = [_wyrm._tcp]. - macOS 15: the Local Network prompt.
- Android:
CHANGE_WIFI_MULTICAST_STATEand a multicast lock while browsing. - Windows and Linux: none (browsing is outbound).
Flutter package:
bonsoir(all five platforms). - iOS:
Consequences
- Gateway:
devices.rs(records, challenge cache, verify P-256 ECDSA withring::signature::ECDSA_P256_SHA256_ASN1,ringis already in the tree), routes inhttp.rs, users SCHEMA 5,inforoute,confirm_requiredon config requests whenstep_upis on, audit records. wyrmd:gateway.devices,gateway.announcewithmdns-sd,wyrmd ca fingerprint; System › Gateway shows the certificate code and a QR (wyrm://<host:port>?fp=…).- Studio: a platform channel per OS for the key (the
local_authpackage alone cannot bind a key; Studio uses a thin plugin over Security.framework,KeyCredentialManagerandBiometricPrompt+ Keystore),bonsoir, pinned CAs per origin instorage. - Tests:
- device register and login, plus every refusal code;
- a password change signs devices out;
- step-up refused, then confirmed;
- challenge reuse refused;
- announce TXT content and its absence with
enabled: false; /api/infowithout a session;- a standby accepts a device registered on the active.
Not decided here
- Hardware attestation checks (Apple App Attest, Android Key Attestation) as a policy option: recorded when sent, not required.
- Passkeys for a web build.
- Discovery across subnets (an mDNS reflector is the network’s job).
Decisions taken while building (2026-11-14, ADR 0029)
The owner’s request was the decision to build this ADR as written. Where it left a point open, the rule below is the one built; Studio follows it.
-
Refusals on the wire. No new spec-04 status: a refusal has
status: permission_denied(0x21) and a textcode, in the HTTP error body{status, message, code}and in the WebSocketerrormap. Codes:device_removed,password_changed(the user’s generation moved: a new password, Sign out everywhere, or a disable),password_due,devices_off,confirm_required, and three a client acts on:password_required(register needs a fresh password),too_many_devices,bad_password(/api/confirm). An unknown device, a bad signature, an origin the gateway does not serve and a nonce that is unknown, used or older than 60 s all get one bare401without acode, counted by the login limiter (5 per device and address a minute, 20 per address): they tell nobody which device ids exist. A coded refusal comes only after a good signature by the stored key. Rate limits answer429 rate_limited. -
What is signed. Canonical CBOR arrays, the label first, the nonce and hashes as byte strings:
- login:
["wyrm-device-login/1", site, origin, user, device, nonce]; - register:
["wyrm-device-register/1", site, origin, user, nonce, public_key](the key bytes as sent); - step-up:
["wyrm-device-confirm/1", site, origin, user, device, nonce, request].
Test vector (
devices::tests::messages_are_canonical_cbor_arrays): siteplant, originhttps://gw:8443, userolena, deviced1, nonce07070707→86737779726d2d6465766963652d6c6f67696e2f3165706c616e746f68747470733a2f2f67773a38343433656f6c656e616264314407070707. - login:
-
Origins. The gateway checks the signed origin against a list, never against the
Hostheader (a relay sets that).gateway.devices.originslists them; by default they are the DNS and IP names of the gateway’s own certificate on the port it listens on (https), or127.0.0.1,localhostand::1for plain HTTP on loopback. A standby gateway with its own certificate covers its own names; a standby reached under other names lists them. -
Keys. The record carries
alg.es256: ECDSA P-256 with SHA-256, signature in ASN.1 DER, key kept as the 65-byte uncompressed point (SPKI DER, as Android exports it, is accepted and normalised).rs256: RSASSA-PKCS1-v1_5 with SHA-256, at least 2048 bits, key kept as PKCS#1 DER (SPKI accepted): Windows Hello’sKeyCredentialManagermakes RSA-2048 keys only, so Windows uses it. Registration proves the key:POST /api/devicescarries aregisternonce of the same session signed by the new key, so an invalid key or one the device does not hold is refused (401). On Apple and Android platforms that is the person’s first biometric prompt, when they turn the unlock on. -
Calls.
POST /api/device/challenge {device}→{nonce, exp}answers for any id. With a bearer session,{purpose: "register"}gives a nonce bound to that session. A step-up nonce comes only with itsconfirm_requiredrefusal, bound by its MAC to the session and to the hash of the refused request, so a device signs, and the audit keeps, exactly the request the gateway named (review of PR 86, L3). Adevicethat is not a device id (32 lower-case hex digits) is refused with400before any limiter or audit record (review H1). A nonce is 56 opaque bytes,random(16) ‖ exp(8) ‖ HMAC(key, purpose ‖ random ‖ exp), under a key the gateway process makes when it opens. Issuing one stores nothing, so nobody can evict or crowd out another caller’s nonce, and a nonce for an unknown device looks like one for a known device (security review of PR 86). Only a spent nonce is remembered until it would have expired (single use; at most 100 000, thenbusy, which the login limiter does not count; review L2). Every limit counts an IPv6 address by its /64, and a full table of the request limiter drops its oldest record instead of refusing new addresses (review L1). A nonce is good only on the gateway process that made it. 30 challenges per address a minute.POST /api/devices {name, platform, alg, public_key, attestation?, origin, nonce, signature}→{device}(a random 128-bit id in hex).POST /api/device/login {device, origin, nonce, signature, session?}→{session, exp}.POST /api/device/confirm {device, origin, nonce, request, signature},POST /api/confirm {password},GET /api/devices,DELETE /api/devices/{id},GET /api/users/{name}/devices, andPOST /api/me/sign-out(Sign out everywhere: user store opEndSessions, a new generation).GET /api/usersrows gaindevices(the count that can log in). -
password_atmoves when a password login names its device:POST /api/login {user, password, device}.password_duethen clears without a new key. -
Removing. The owner’s
DELETE(Turn off, Forget) deletes the record. An admin’sDELETEof another user’s device leaves a tombstone withremoved_byandremoved_at, so the device hearsdevice_removedand its owner sees who; aDELETEof a tombstone deletes it. A user keeps at most 32 records; past that, the oldest that cannot log in go first. Removing a user removes their devices. A session made by a device login ends when its device is removed, forgotten or signed out. -
Sessions carry
amr(pwd,dev,oauth),auth_at(when the password or the key was last checked at login) anddev(the device of a device login). Tokens from before this ADR read as password logins atiat. Registering needs a session whose password was checked in the last 5 minutes: a password login or/api/confirm. A device session or an MCP token never registers. -
Step-up. Confirmations are kept in memory per session (a restart asks again). A session is confirmed for 5 minutes after its login (password or device), a device confirm or a password confirm; an idle unlock (
/api/device/loginwithsession) confirms the kept session.confirm_requiredcarriesrequestandnonce(aconfirmnonce of that session) to sign.requestis an HMAC-SHA256, under the gateway process’s own key, of the canonical CBOR of the refused request ({op, key, value?, action?, args?}over the WebSocket,{method, path, body}over HTTP) with the fieldspassword,secret,tokenandpassphraseleft out at any depth. So the hash the device signs and the audit keeps cannot test a guessed password (security review of PR 86). Config level is: aseton a point whosewritableisconfig; aninvokewhose actionlevelisconfig(also/api/invokeand flow deploys); user management changes; an admin removing another user’s device; anapproveof an agent’s plan in which a step to be signed is atconfig, and every flow deploy (the gateway signs tokens for both, so the step-up holds before anything is signed; security review of PR 86). A node whose~metacannot be read counts asconfig. Only users who holdconfigthere are asked (the responder refuses the others). An MCP token never passes a step-up: withstep_up: "config", the MCP endpoint gets noconfig. The tokens the gateway mints for a session that is not confirmed reachwriteat most, so a responder that does more for aconfigtoken (a DQL sink query,publish) gets none from it (review M1). Defaultstep_up: "none", so existing clients keep working; hardened sites turn it on. -
/api/infocarries{site, version, tls, role, devices: {enabled, max_per_user, password_every_days, idle_lock_max_min, step_up, allow_device_credential}, min_studio, up, pair?, ca_fp?, ca?, names?}.ca(the CA certificate’s DER, public data) is beyond the list above. It is there because a client only sees the leaf certificate in the handshake, so it cannot pin the CA without it. Studio never trustsca_fpor thefpTXT key, which an untrusted server sends (review M2). It shows the code it computes itself, SHA-256 of the receivedcaDER, first 16 bytes. It then reads/api/infoonce more under that CA alone, so the handshake’s leaf must chain to it, and only then pins it. Whenca_fporfpdiffer from the computed code, Studio refuses the row.names(over TLS) are the DNS and IP names of the gateway’s certificate. A row found by DNS-SD gives an address, and the certificate rarely nameswyrm-<site>.local. So Studio builds the gateway URL from the first ofnames: the address itself when it is listed, else a DNS name. When that name does not resolve, Studio connects to the address and checks the certificate against the name (the pinned CA, the name’s origin for device keys). A certificate that names neither cannot be used from a row; the person types its address instead.min_studiois the oldest Studio the gateway serves (1.0.0). 60 requests per address a minute. ADR 0051 §3 addssetup: truewhile a setup code waits for the first admin (absent otherwise). -
The CA and its code. One function,
wyrmd::gateway_ca, gives the code for/api/info, thefpTXT key andwyrmd ca fingerprint(which prints it in 8 groups of 4 and creates nothing). It takesgateway.tls_ca(new, a PEM path), else the last certificate oftls_certwhen that holds a chain, else the site CA when it issued the gateway’s certificate. Otherwise there is no code. System › Gateway in Studio reads the code from/api/info; nosysvalue was added. -
Updates. The users SCHEMA moves from 4 to 5 and the WAL gains ops 6–11. An update through ADR 0048 restores the users store from its pre-update backup if it rolls back (the guard’s rule for a moved SCHEMA); with
state_anchor_dirset it is an update by hand. In a standby pair, update the standby first: an older standby cannot read the new ops. -
Announce. On by default when the gateway listens off loopback (§2.1: hardened sites turn it off), never on loopback.
gateway.announce {enabled, interfaces, pair}. Only the broker that serves announces, soroleisactive. A following standby runs no gateway; Studio fills the standby frompair, which isannounce.pairor the host ofstandby.peerwith this gateway’s port.uplists every upstream site, joined with commas. A takeover starts the new active’s announcement; a step down and SIGTERM end it with a goodbye. A multicast failure is logged and the broker runs without an announcement.
ADR 0051 — Broker images for boards, and a web image builder
Status: proposed (2026-11-25, owner request). Approach D (OpenWrt) and the answers below chosen by the owner on 2026-11-25. Part 1 (the three wyrmd features of §1 and §3) built on 2026-11-25, see “Built” below; the rest is not built yet.
Context
An integrator or an engineer wants a working broker on a device quickly, without building a Linux system by hand (owner, 2026-11-25). Today wyrmd ships as a static musl binary, as scratch container images (deploy/docker) and as signed releases with self-update (packaging/wyrmd, ADR 0048). There is no operating system image for a board, and no way to make one.
The owner asks for:
- A web page, like start.spring.io: pick a board, the links and a few settings, and download an image to write to an SD card or a USB stick. The device then starts as a WYRM broker.
- Several board implementations, not one. First: Raspberry Pi and Banana Pi BPI-R4 (MediaTek MT7988A).
- Later, a screen in Studio’s login that leads to the same builder, with more detail (links’ settings, standby, upstream, history, flows).
The page lives on wyrm.gencto.uk, the project’s home page, which moves there from a claude.ai artifact (owner, 2026-11-25). That site is a separate piece of work and comes first; this ADR covers the images and the builder.
Approaches
| Base | For | Against | |
|---|---|---|---|
| A | Debian/Armbian per board, systemd | familiar, apt | 400–700 MB, not atomic; no Armbian for BPI-R4 (only the vendor’s Debian/Ubuntu on its own 6.12 kernel) |
| B | Buildroot per board, read-only root, A/B slots (RAUC) | 60–120 MB, atomic OS updates | no Buildroot support found for BPI-R4: we would port the vendor’s kernel and U-Boot ourselves; ~1 h CI per board |
| C | Alpine Linux | small, musl | weak Banana Pi support |
| D | OpenWrt + a WYRM package feed + OpenWrt ImageBuilder | supports both boards today (BPI-R4: target mediatek/filogic, profile bananapi_bpi-r4; Raspberry Pi: target bcm27xx); musl like our binaries; small (squashfs + overlay); the ImageBuilder assembles an image from prebuilt packages in minutes without compiling; OpenWrt’s own Firmware Selector + ASU server is the same “pick and download” pattern, proven on thousands of devices | init is procd, not systemd; sysupgrade replaces the system whole, no A/B rollback of the OS by default; a router OS, less usual on a Raspberry Pi |
Yocto was dropped (heavy for two or three boards), Ubuntu Core and balena too (tied to a vendor store or cloud).
Chosen: D (owner, 2026-11-25, on the maintainer’s recommendation). One build system covers both boards and new boards come almost free; the pick-and-download mechanism exists. Atomic OS updates can come later if needed; wyrmd itself already updates and rolls back through wyrmd-guard (ADR 0048).
Goals
- An integrator goes from “I have a board” to “Studio shows my site” in minutes: open the page, choose, download, write the card, power on, find the broker in Studio.
- The same image works without internet at the plant (links are in the image).
- No secret of the site (CA key, state keys, gateway key, admin password) is made on or passes through our servers.
- Boards are data: adding a board is a row in a board list plus its OpenWrt target/profile, not new code.
- Each image is reproducible: a pinned OpenWrt release, pinned WYRM package versions, recorded in the image.
Non-goals
- Updating the OS in the field (first version).
wyrmdupdates itself; an OS update is a new image written by hand. Recorded for later. - Boards OpenWrt does not support.
- x86 mini PCs (possible later through OpenWrt
x86/64; not asked for now). - A Studio screen in the first version (it comes after the web builder, on the same backend).
Anti-goals
- An image that starts with a default password, a shared CA or keys made by the builder: every device makes its own secrets.
- A builder that needs an account or collects data about the person.
- Forking or patching OpenWrt. We add packages and files; the OpenWrt release is used as published.
Design
1. Packages (the WYRM feed)
- Most links are inside
wyrmdalready: the twelve with the formbuiltininlinks/official.json(modbus, opcua, bacnet, s7, snmp, mqtt, http, prometheus, s3, gdrive, webdav, localfs) and the embedded scheduler, alarm, dql and uplink. For them, choosing a link on the page means a configured instance in the config, not a package. - The seven links that are packages only (postgres, mysql, mongodb, influxdb, dynamodb, telegram, slack) go into the image in their
wasmform: one file for every CPU, no per-architecture build. (maintainer’s call) - OpenWrt gives each target its own package architecture (
bcm2711→aarch64_cortex-a72,bcm2712→aarch64_cortex-a76,filogic→aarch64_cortex-a53).wyrmdis one staticaarch64-unknown-linux-muslbinary that runs on all of them; CI packs it once per package architecture of the boards inboards.json. (maintainer’s call) - Package
wyrmd: the binary (the first version for the self-update layout, §3),wyrmd-guard, a procd init script (/etc/init.d/wyrmd: starts through the guard, stop on SIGTERM aswyrmdexpects,respawn_retryat least 8 as ADR 0048 needs), a default/etc/wyrm/wyrmd.json5. - Seed packages. A package can not be dropped into
data_dir/packagesat build time:data_direxists only after the first boot, andControl::openremoves every package directory without a registry record (packages::clean_orphans). So the image carries link packages as.wyrm-link/zip files in/usr/share/wyrm/seed/with a list of the instances to make; on its first startwyrmdinstalls each through the same checks asinstall_zip(registryPackageDef+LinkDef) and records that the seed is done. New inwyrmd. (maintainer’s call) - The feed is signed with a key of the project (OpenWrt’s own package signing) and published with the release assets.
2. Boards
A list packaging/images/boards.json: per board an id, a title, the OpenWrt target and profile, the storage it boots from (SD/eMMC/USB), the data partition to make, and notes for the page (how to write the card, which slot to boot from). First rows: rpi4 (bcm27xx/bcm2711), rpi5 (bcm27xx/bcm2712, if the pinned release has it), bpi-r4 (mediatek/filogic, bananapi_bpi-r4).
3. Storage and first boot
- OpenWrt keeps its root read-only (squashfs) with a small overlay for
/etc. Broker data (data_dir: stores, history, packages, versions for self-update) goes to a separate ext4 data partition, mounted at/srv/wyrm, made and sized to the rest of the card on first boot.sysupgradekeeps it on both targets (bcm27xxwrites partition by partition while the layout is the same;filogicwrites onlyproduction) as long asROOTFS_PARTSIZEof a board never changes: that value is fixed per board inboards.jsonfor the life of the board. - The self-update layout of ADR 0048 (
versions/<v>/wyrmd,current,bin/wyrmd-guard) lives on the data partition. The packaged binary only seeds the first version; after asysupgradethe guard keeps startingcurrent, even when the new image carries an older binary. (maintainer’s call) - Self-update is off in images (
updates.mode: off) until the project has a release key inRELEASE_KEYS(empty today); then images shipmode: externalwith the project channel. (maintainer’s call) - Time. A Raspberry Pi 4 has no clock and the Pi 5’s needs a battery; without NTP the clock starts near the build date. The first start waits up to 2 minutes for NTP before
wyrmdmakes the CA, then goes on and logs a warning; the CA’snotBeforeis the build date minus one day, so a later correct clock does not void it. The page asks for NTP servers (default: the network’s DHCP option, thenpool.ntp.org). (maintainer’s call) - Secrets. On first boot
wyrmdmakes the site’s CA and its keys, as it already does for a newdata_dir(Pki::open_or_create). Nothing of that is in the image. - Gateway certificate. Today
wyrmddoes not make one: a gateway that listens beyond loopback needstls_cert/tls_key, and without them DNS-SD andca_fpare off too. New inwyrmd:gateway.tls: "site_ca"issues the gateway’s certificate from the site’s CA on first start with the names<hostname>.local,wyrm-<site>.localand the addresses it has, and issues it again when an address changes. (maintainer’s call) - First admin. The page makes a one-time setup code of 128 random bits in the browser (shown as base32 groups and a QR code), shows it once, and puts only a hash of it into the image, in
/etc/wyrm/setup(not inwyrmd.json5, whichwyrmdnever writes and which refuses unknown fields). On its first startwyrmdmoves the hash into the users store as a pending setup and deletes the file (as built: intodata_dir/gateway/setup.hash, 0600, beside the users store and not replicated to a standby, see “Built”); the file is not in thesysupgradekeep list. On the first login Studio asks for the code and the new admin password; the gateway checks it, creates the admin and ends the setup (one use). Until then the gateway accepts no other login. 128 bits make an offline guess of the hash useless. (WYRM_GATEWAY_ADMIN_PASSWORDstays for other installs.) (maintainer’s call) - Discovery. The gateway announces itself by DNS-SD (
_wyrm._tcp, ADR 0050); Studio finds it; the first trust goes through the setup code (answer 3 below).
4. The builder
- Page
wyrm.gencto.uk/start: board, site name, network (DHCP / static address / Wi-Fi where the board has it), links (fromofficial.json, with their category and summary), time zone, NTP servers. It shows the setup code and the steps to write the card. No login. - Assembly in the browser, no build server (owner, 2026-11-26; replaces the build service of the first draft). CI builds one base image per board and release with OpenWrt’s ImageBuilder: OpenWrt,
wyrmd, the guard, and every package-only link in itswasmform under/usr/share/wyrm/seed/. The image has a small reserved config partition (GPT labelwyrm-config, 4 MiB, raw: a length-prefixed archive, no file system to write from JavaScript). The page downloads the base image as a static file, keeps it in the browser’s storage (OPFS or the Cache API, keyed by its SHA-256 from a signed index, checked after download), writes the chosen configuration into the config partition, and hands the person the finished image. Nothing of the person’s choices leaves the browser. On first boot a script reads the partition, writes/etc/wyrm/wyrmd.json5, the network config,seed.json(which of the carried links to install) and the setup hash, then wipes the partition. - Static hosting. The base images and their signed index are plain files; the host must allow the page’s origin to fetch them (CORS) and serve ranges. Where they are hosted is left to the builder (the site’s own origin if sizes allow, else an object store behind the same domain).
- Licences. The page links each image to the source of the OpenWrt release it was built from and to the WYRM tag of its packages (GPL obligations for the kernel, busybox and board firmware). (maintainer’s call)
- Offline:
wyr image build --board <id> --config <file>does the same assembly from a downloaded base image, andwyr image base --board <id>runs the ImageBuilder steps locally (in a container) from the published feed. - Record: each image carries
/etc/wyrm/image.json(board, OpenWrt release, package versions, build date, request hash) so support can tell what is on a device.
5. Studio (later)
A screen in the login flow, “New device”, that drives the same build service with the detailed settings Studio already edits (links’ connections, standby, upstream, history watches, flows), and writes the result into the image’s config. It reuses §3 and §4.
Consequences
- New CI jobs: the feed (per release, per package architecture) and a smoke test that boots OpenWrt
armsr/armv8in QEMU and startswyrmdfrom a package of that target. It checkswyrmdon OpenWrt, not the board packages; those are checked on the boards. docs/operations.mdgains a section “OpenWrt” beside “systemd”: procd script, data partition, logs throughlogread.- No service to run: CI publishes base images; the page is static (§4).
wyrmdgains: the setup-code first admin,gateway.tls: "site_ca", seed packages on first start (each with tests anddocs/operations.md).
Left to the builder
- Package naming inside the feed, the exact procd script, partition layout per board (within §3), the service’s language and hosting, cache size, queue limits.
- How the page writes nothing into the image itself (all goes through the ImageBuilder’s
FILESoverlay).
Built (part 1, 2026-11-25)
The three features wyrmd needed for an image (Consequences, last line). The OpenWrt packages, boards.json, wyr image build, the build service, the page and the Studio screen are not built; the status stays proposed for them.
- Gateway certificate from the site CA (§3).
gateway.tls: "site_ca"(excludestls_cert/tls_key): the broker issues the gateway’s certificate from the site CA with the names<hostname>.local,wyrm-<site>.localand the host’s non-loopback addresses (IPv4 and global IPv6; on Linux without temporary, deprecated or tentative IPv6 addresses, read from/proc/net/if_inet6, sinceif-addrsgives no flags), or only the listen address whengateway.listenis not unspecified. It reads the addresses every 30 s while the gateway serves and issues a new certificate, served from the next connection without a restart, when the names change or less than 30 days are left; a key that does not match its certificate (a torn write) makes a new pair. Files of the operator (tls_cert/tls_key) are read again at each router rebuild; at the start a pair that cannot be read or does not match stops the broker. A certificate the current site CA did not sign is issued again (a key restore from another site’s backup also setsgateway/tls.{pem,key}aside).ca_fp, the DNS-SDfpandwyrmd ca fingerprintname the site CA. Documented indocs/operations.md(“Gateway TLS from the site CA”) anddocs/broker.md. Tests:certificate_follows_the_addresses,a_due_certificate_is_renewedand the other tests ofcrates/wyrmd/src/gateway_tls.rs. - First admin from a one-time setup code (§3).
gateway.setup_filenames a file with the SHA-256 ("wyrm-setup-v1\n"‖ the 16 code bytes, 64 hex digits) of a 128-bit code;wyrmd setup-codemakes a code (26 base32 characters in groups) and its hash. While no user exists, the first start moves the hash intodata_dir/gateway/setup.hash(0600, not replicated to a standby) and deletes the file;GET /api/infoshowssetup: true;POST /api/setup {code, user, password}makes that user an admin once (204;409 no_setup,403 setup_code_wrong,400,429from the login limiter). A setup is void once a user exists (dropped at start). Deviation from §3: the pending hash is kept indata_dir/gateway/setup.hash, not in the users store, so it never reaches a standby or a backup of users. The first trust goes through the code in both directions (answer 3): while a setup is pending and the gateway presents a CA,/api/infoalso carriessetup_proof= HMAC-SHA-256 keyed with the hash over"wyrm-setup-proof-v1\n"and the DER of that CA (ca); a client verifies it from the typed code (wyrm_gateway::setup::verify_setup_proof) and checks that the connection chains to that CA before it sends the code, then pins the CA. The hash is therefore kept like a secret of the image (the device, the image, the build service). Tests:setup_proof_binds_the_presented_ca,setup_proof_is_the_spec.WYRM_GATEWAY_ADMIN_PASSWORDworks as before. Documented indocs/operations.md(“First admin from a setup code”) anddocs/broker.md. Tests:code_is_read_as_typed,setup_is_void_once_a_user_exists,setup_is_rate_limited_like_login. - Seed packages on the first start (§1).
packages.seed_dirnames a directory withseed.json(format: "wyrm-seed/1",links: [{link, file, accept}], ≤ 256 links) and the package zips; each entry is installed once asinstall_zipdoes, subjectbroker:seed, with the same checks. An existing link is skipped; a failed entry does not stop the others.data_dir/seed.progress.jsonrecords each install while the seed runs;data_dir/seed.donerecords the outcomes when it ends, and the seed never runs again. Both files are replicated to a standby. Documented indocs/operations.md(“Seed packages”),docs/links.mdanddocs/broker.md. Tests:a_broken_seed_entry_does_not_stop_the_others,seed_runs_once,seed_skips_an_existing_link.
Answers of the owner (2026-11-25)
The owner accepted the maintainer’s proposals (“в цілому пропозиція зрозуміла”):
- Role on the network: a plain host. DHCP client by default (static address on the page), no DHCP server, no LuCI, firewall open only for the gateway and the peer ports in the config. Root login and SSH are off unless the page is given an SSH public key; then SSH accepts that key only. A router/firewall role for the BPI-R4 (WAN ↔ equipment network) is a later option.
- BPI-R4 storage: the SD card installs onto the eMMC, the device then runs from the eMMC (OpenWrt’s usual path); the data partition is on the eMMC. Both RAM variants are rows in
boards.json(bpi-r44 GBsdcard.img.gz,bpi-r4-8gsdcard_8g.img.gz); the PoE variant (bananapi_bpi-r4-poe) is a row when someone needs it. Raspberry Pi runs from its SD card (or USB where the board boots from it). - First trust: through the setup code. (Since the assembly moved into the browser on 2026-11-26, the setup hash is written there and no server sees it; the sentences below about trusting the build service describe the first draft.) The person trusts the build service, which sees the image (not the code). Studio’s first login proves the code and pins the CA the device presents in the same session. Next step (later): the page writes the setup secret into the downloaded image in the browser, so the service never sees anything of it. The CA code stays visible in Studio and in
wyrmd ca fingerprint(console) for those who compare it.
Not decided here
- OS updates in the field (A/B, or OpenWrt’s attended sysupgrade against our feed).
- Hardware tests on the real boards: neither board has been measured yet.
WYRM spec v0.2
Нормативна частина. Усе, що тут, має тестуватись у кожному SDK (Rust, Dart, C) проти одних і тих самих байтів із fixtures/. Вікі пояснює «чому», spec — «що саме».
| Файл | Зміст |
|---|---|
| 01-keyspace | граматика ключів, суфікси, зарезервовані імена |
| 02-meta | ~meta: цілі ключі, типи, коди, view=list, view=keys, patch |
| 03-val | ~val: {v,q,t}, quality, timestamps |
| 04-attachment | attachment: ключі, статуси, ptok v1 |
| 05-methods | list, resolve, subscribe, set, invoke, стріми, таймаути |
| 06-flow-def | схема dataflows/<id>/~def |
tables.json | машинно-читані таблиці кодів (джерело істини для кодогенерації) |
fixtures/fixtures.json + *.cbor.hex | 22 фікстури: канонічний CBOR, hex, JSON-еквівалент |
Правила spec
- Кодек на дроті — CBOR (RFC 8949), канонічне кодування (RFC 8949 §4.2.1: цілі ключі за зростанням, мінімальна довжина цілих). Decoder мусить приймати неканонічне.
- Невідомі ключі ігноруються у
~meta, attachment,~def. Нові поля додаються без зміни версії. - Ключі — цілі; рядкові ключі дозволені лише всередині
cfg,attr,actions.*.params,patch(користувацький вміст). - Версія протоколу — у
wy/<site>/sys/~meta,attr.proto = 1; клієнт з іншою мажорною версією отримуєinvalid_message. Liveliness-токен брокера —wy/<site>/sys/broker(вузла з цим ключем немає). - Зміна будь-якої таблиці → новий запис у
tables.json→ регенерація фікстур → прогін у всіх SDK. - Глибина вкладення масивів, map і тегів в одному значенні — не більше 32. Decoder відкидає глибше як
invalid_messageі не входить у рекурсію: вхід від будь-кого не може вичерпати стек.
Тест сумісності (контракт для SDK)
Для кожної фікстури:
decode(hex) == json(семантично, з урахуванням float/int)encode(json)канонічно== hexdecode(encode(decode(hex))) == decode(hex)
01 — Key-space
Граматика
key = "wy/" site "/" branch
site = seg
branch = "downstream/" link ("/" path)? ("/" suffix)?
| "downstream/" site ("/connected")? ("/" suffix)? ; downstream broker node
| "upstream/" site ("/connected")? ("/" suffix)? ; upstream broker node
| "dataflows/" flowid ("/" ("~def" | "~meta" | "~val" | "~act/" name | "nodes/" seg "/" suffix))?
| "storage" ("/" path)? ("/" suffix)? ; broker storage (0.2.2)
| "pub/" profile "/~meta"
| "sys/" syspath
path = seg ("/" seg)*
suffix = "~meta" | "~val" | "~set" | "~act/" name | "~state"
seg = 1*( ALPHA / DIGIT / "_" / "-" / "." ) ; без "/", без пробілів, не починається з "~"
link = seg ; = Link id, = cert CN
profile = "wy:" seg ; або "<vendor>:" seg
Зарезервовано
- Суфікси
~meta ~val ~set ~act ~state ~def; будь-який сегмент, що починається з~— помилка валідації в SDK. - Zenoh-спецсимволи
* ** $* ? # @у сегментах заборонені; протокольні імена з ними — percent-encoding (%2A), SDK декодує вdisplay. - Дія
~removeу~act/зарезервована (видалення вузла/атрибута). - Префікси
wy/<site>/sys/іwy/<site>/pub/пише лишеwyrm-admin.
Повні імена
Віртуальних префіксів (remote/) немає: ключ має одне ім’я на всіх брокерах mesh і в UI.
Розділи сайту мають повні імена, без скорочень: downstream, upstream, dataflows, sys, pub (0.2.0; до неї — down, up, flows). Брокер переносить збережені ключі зі старими іменами (гранти, спостереження історії) під нові; збережені потоки треба розгорнути знову, бо їхні proofs підписані для старих ключів.
Сховище брокера
wy/<site>/storage/** — вузли і значення, які створюють люди (як /data брокера DSA, ADR 0017): папки, значення типу string, number, bool, array, map, binary, dynamic з дією ~set, дії add_node, add_value, publish, delete, rename, duplicate, export, import. Кожна дія і ~set потребує write. Брокер зберігає дерево і останні значення між перезапусками. Id лінка storage зарезервований (0.2.2).
Брокери-сусіди
Downstream — те, що підключається до брокера: лінки і брокери нижчих сайтів; їх вузли поруч у downstream/. Брокер сайту d, що підключається до нас, — вузол wy/<site>/downstream/<d>. Upstream — брокери, до яких підключається наш: wy/<site>/upstream/<u>. Ці вузли — посилання, а не копії: is = wy:broker, attr.site, attr.root = "wy/<peer>" і bool-точка connected (liveliness wy/<peer>/sys/broker). Ключі сусіда лишаються під його власним ім’ям (wy/<peer>/…); клієнт іде за attr.root. Id лінка не може збігатися з іменем downstream-сайту.
Запити згори (0.2.3, ADR 0018; 0.2.9): upstream може надсилати ~set і ~act у downstream, dataflows, storage нижчого сайту завжди, а в sys — лише коли нижчий сайт дозволив це для цього upstream (allow_config). Рівень на downstream, dataflows, storage — write; з allow_config — config (дії лінків Export, Edit, Stop тощо), як і на sys. ptok такого запиту має site нижчого сайту і підписаний ключем upstream. Брокер публікує ключі, якими підписують запити до нижчих сайтів, у wy/<site>/sys/signing_keys ({write: {<site>: [hex…]}, config: {…}}: свої і ті, що взяв від своїх upstream; у config — лише від upstream, яким він дозволив config); нижчий сайт довіряє їм лише у своїх межах і на своїх рівнях. Дію hello (ключ лінка, без ptok) згори не пропускає ACL.
Селектори
key?param=value&... — параметри не впливають на маршрутизацію. Визначені:
| Параметр | Де | Значення |
|---|---|---|
view | ~meta | list | keys | full (default full) |
from, limit | ~meta?view=list | пагінація; limit ≤ 1000 |
match | ~meta?view=keys | is:<code>;type:<code>;unit:<str>;tag:<str> (AND) |
depth | ~meta?view=keys | 1..∞ (default ∞) |
rev | ~meta | повернути status=ok,rev без тіла, якщо не змінилось |
field | ~set | cfg.<name> | attr.<name> — запис метаданих замість значення |
history, since | ~val | history=<from>..<to> RFC 3339 (дата — її північ UTC; порожній <to> — зараз) або since=<from> |
agg, window | ~val?history | `avg |
limit | ~val?history | рядків відповіді, 1..100 000 (default 10 000) |
close | ~act/<a> | <rid> — закрити стрім |
check | ~act/<a> | без значення (0.2.33): перевірити виклик, нічого не робити (05 check) |
dry_run | sys/**/~act/* | true |
Запит історії (0.2.35): селектор ~val з history або since містить кожен параметр щонайбільше один раз і лише ці: history або since (не обидва), agg, window, limit. Параметри, назва яких починається з _, належать Zenoh, і historian їх не читає. Повтор чи інший параметр — invalid_parameter: так текст значення не може додати свій limit (огляд 2026-11-15). Requester складає селектор із уже розібраних значень (час, назва rollup, вікно в секундах, число), а не з тексту запиту.
02 — ~meta
Ключі (CBOR map, цілі ключі)
| Ключ | Назва | Тип CBOR | Обов’язк. | Опис |
|---|---|---|---|---|
| 0 | is | uint (is_code) або tstr | так | профіль; uint — код з sys/codes, tstr — повне ім’я (для невідомих клієнту кодів) |
| 1 | type | uint (type_code) | листовий | 0 null, 1 number, 2 string, 3 bool, 4 enum, 5 map, 6 array, 7 binary, 8 dynamic |
| 2 | unit | tstr або uint (unit_code) | ні; також у view=list | одиниця; UI пише її після числового значення (21.5 °C), не після enum, bool чи тексту |
| 3 | enum | array of tstr | type=4 | значення enum; ~val.v = індекс |
| 4 | writable | uint | ні, default 0 | 0 never, 1 config, 2 write |
| 5 | invokable | uint | ні, default 0 | мін. рівень для дій: 0 never, 2 read, 3 write, 4 config |
| 6 | cfg | map (tstr keys) | ні | системні параметри: precision min max interval_ms deadband retention_days restricted auto_group enabled |
| 7 | attr | map (tstr keys) | ні | користувацькі |
| 8 | actions | map name → action | ні | див. нижче |
| 9 | children | array of tstr | контейнер | упорядкований список дітей (тільки view=full) |
| 10 | rev | uint | так | версія meta, монотонна |
| 11 | has_children | bool | view=list | діти є зараз (будь-які) |
| 12 | display | tstr | ні; також у view=list | = attr.display, дубль для view=list: назва вузла для людини (див. «Назви для людей») |
| 13 | has_override | bool | view=list/keys | є відхилення від профілю → варто тягнути full |
| 14 | children_count | uint | контейнер | |
| 15 | q | uint | view=list | поточна quality (щоб UI показав стан без subscribe) |
| 16 | has_history | bool | view=list | attr.history не порожній: вузол записується (UI показує значок історії без ~meta на кожен рядок) |
| 17 | has_nodes | bool | контейнер; також у view=list | є дитина без type (вузол, не значення), яку бачить цей requester: дерево UI малює трикутник лише тоді. Responder публікує ~meta контейнера знову, коли поле змінюється (дитину додано, прибрано, значення стало вузлом), тож list батька дає Changed |
action
{ "params": { <name>: <param-meta> }, "result": type_code | "stream" | "void", "stream": bool, "level": perm,
"timeout_ms": uint, "display": tstr, "group": tstr }
param-meta = { 1: type_code, 3: [enum...], 2: unit, "default": any, "required": bool,
"display": tstr, "description": tstr, "placeholder": tstr, "editor": tstr }
Поля для UI (як $name, $actionGroup, $params у DSA), усі необов’язкові:
displayдії — назва для людини ("Add device"); ключ уactionsлишається сегментом ключа (add_device, spec 01).group— меню, у якому UI показує дію:"new"— дії, що додають дітей;"edit"— дії, що змінюють або видаляють сам вузол; інше ім’я — окреме підменю; безgroup— верхній рівень меню.displayпараметра — підпис поля; ключ параметра лишається ім’ям уargs.description— підказка;placeholder— приклад значення в порожньому полі.editor:"password"— значення приховане, UI не показує його й не підставляє (секрет);"textarea"— багаторядковий текст;"file"— параметр типуbinary, значення — вміст локального файлу, який вибирає користувач (UI може надіслати такий виклик поза WebSocket-кадром, ADR 0011);"daterange"— текст<from>/<to>у RFC 3339, UI пропонує готові проміжки (сьогодні, вчора, останні 7 днів, …) і вибір дати й часу (0.2.4);"date"— одна мить у RFC 3339, вибір дати й часу (0.2.4; такожattr.editorзначення сховища, ADR 0017);"duration"— число секунд, UI дає ввести його в одиниці поруч (с, хв, год, дн) і надсилає секунди (0.2.4). НевідомийeditorUI ігнорує.
Назви для людей (0.2.28, ADR 0042)
Ключ (вузла, дії, параметра) — ім’я на дроті: сегмент шляху або ім’я в args; його не змінюють заради вигляду. Людина бачить display:
- Вузол.
attr.display(і ключ 12 уview=list) — необов’язкова назва вузла для людини (t1→"Supply temperature"). Ніколи не частина шляху: шлях, ключіview=keys, гранти й посилання беруть лише ключ. Ставить responder під час declare; у фреймворку драйверів — також користувач: необов’язковий параметрdisplayуadd_*іeditз’єднання, пристрою й точки (editбезdisplayлишає наявну назву,nullабо""прибирає її;editлише зdisplay— перейменування, параметри лишаються; ≤ 128 байт; ключdisplayзарезервований на цих рівнях). UI показуєdisplay, а без нього — ключ. - Дія й параметр.
displayдії й параметра. Responder SDK заповнює відсутнійdisplayз ключа за правилом нижче, тож у~metaвін є завжди; явнийdisplayлишається як є. Для~metaстарого responder’а безdisplayклієнт може вивести назву з ключа (точне правило —wyrm_core::display). - Правило з ключа (
wyrm_core::display::humanize): токени між_,-,.; перше слово з великої, решта з малої; акроніми й назви — як у списку (url→URL,id→ID,mqtt→MQTT); останній токен-одиниця (ms,s,hz,mb,mib,kib,pct,days,us) — у дужках:timeout_ms→Timeout (ms),unit_id→Unit ID,add_device→Add device. - Стиль явного
display: sentence case, коротко, без крапки в кінці, акроніми великими, одиниці в дужках; дія починається з дієслова (Add connection,Read registers), параметр — іменник (Poll rate (s)). Значення enum (3) іgroup— значення на дроті, не назви: їх UI показує як є або за тим самим правилом.
Успадкування
Відсутнє поле береться з профілю is (рекурсивно через extends у профілі). Профіль (pub/<profile>/~meta) — та сама map, що ~meta, плюс текстовий ключ "extends": tstr (ім’я батьківського профілю); ланцюг ≤ 8, без циклів. cfg, attr, actions зливаються по ключах (власні виграють); is, rev, children і поля view=list не успадковуються. pub/** пише лише wyrm-admin; ?expand=true — профіль з уже злитим ланцюгом. SDK responder’а відповідає розгорнутим ~meta у view=full лише на ?expand=true; за замовчуванням — тільки власні поля (економія).
view=list
Відповідь — CBOR array map’ів дітей з ключами {0,1,2?,4?,10,11,12?,13?,15?,16?,17?} (власні поля дитини, без профілю); порядок = children. Пагінація from/limit.
attr.history
Масив ключів сховищ, що записують цю точку (як @@getHistory у DSA). Ключ під wy/<site>/sys/history/ — історик брокера сайту: для точки свого сайту він відповідає на ключі самої точки (<point>/~val?history=, spec 01/03; права як на читання значення), а на ключі watch (<store>/~val?history=) — для будь-якої своєї точки; точку сайту нижче читають лише там (ADR 0020). Такий attr.history кладе не брокер лінка, а сайт, що записує: його gateway зливає sys/overlays/.sites у meta/list вузлів інших сайтів. Будь-яке інше сховище відповідає на <store>/~val?history= саме. Брокер кладе attr.history поверх ~meta лінка (накладка, ADR 0016); власний attr.history лінка зливається з нею (об’єднання).
view=keys
Відповідь — CBOR array of tstr з префіксною компресією: елемент із суфіксом / = push префікса, порожній "" = pop, інший = повний ключ під поточним префіксом. Фільтр match застосовується responder’ом.
Patch
put ~meta при зміні — {10: rev, "patch": {<key>: <value>, ...}}; відсутність "patch" = повний ~meta. Requester, що бачить rev ≠ last_rev+1, робить get ~meta.
Фікстури: meta_number_full, meta_folder_full, meta_action_ui, meta_profile_only, meta_view_list, meta_view_keys, meta_patch, profile_extends.
03 — ~val
{ 0: v, 1: q, 2: t }
| Ключ | Тип CBOR | Опис |
|---|---|---|
0 v | за ~meta.type: float64/int → number; tstr → string; bool; uint → enum index; map; array; bstr → binary; any → dynamic; null | значення |
1 q | uint | 0 good, 1 uncertain, 2 bad |
2 t | uint | uhlc timestamp джерела, мікросекунди Unix |
Розширений код quality (bad/disconnected, uncertain/stale, …) — не тут, а в attachment ключ 1 (qual), бо потрібен рідко.
Правила
t— час вимірювання, не публікації. Якщо джерело не має часу — час на боці конектора.- Числа: encoder пише найкоротшу форму (int, якщо ціле; float32, якщо точно представиме — опція
cfg.precision; інакше float64). Decoder приймає будь-яку. - Пустий
~val(вузол без значення) не публікується. - Контейнери
~valне мають.
Історія
get ~val?history=... (параметри — 01) → CBOR array рядків [t, v, q] у порядку часу (масив, не map — компактніше для тисяч точок); з agg або window → [t_start, value] (без q; rollup пропускає bad).
- Відповідає історик брокера (
sys/history, ADR 0014), лише для точок, які він записує. Storage на той самий запит віддає останнє значення (map): клієнт бере лише масиви (ConsolidationMode::None). - Відповідь — один або кілька reply, кожен масив (≤ 5000 рядків); клієнт з’єднує їх за часом першого рядка. Точка записується, а в діапазоні рядків нема → один порожній масив. Точку ніхто не записує → жодного масиву.
- Помилка (діапазон,
agg,window, wildcard у ключі, діапазон понад 5 000 000 рядків, зайнятий історик) → reply без payload з attachmentstatus(04). - Права — як у
subscribe: ACL сесії на~valточки;ptokне потрібен (05).
Фікстури: val_*, hist_raw, hist_agg.
04 — Attachment
CBOR map з цілими ключами. Відсутній attachment = {}.
| Ключ | Назва | Тип | Напрям | Опис |
|---|---|---|---|---|
| 0 | status | uint | reply | код; обов’язковий у кожній відповіді на ~set, ~act, ~meta get |
| 1 | qual | tstr | both | розширений код quality bad/disconnected |
| 2 | ts | uint | both | для raw payload без {v,q,t} |
| 3 | refreshed | bool | reply | |
| 4 | ptok | bstr | request | див. нижче |
| 5 | maxperm | uint | request | 0..4 |
| 6 | audit | tstr | reply | |
| 7 | err | tstr | reply | |
| 8 | rev | uint | both | |
| 9 | rid | uint | both | кореляція стріму |
| 10 | seq | uint | reply | |
| 11 | last | bool | reply | |
| 12 | origin | tstr | both | user:<id> | flow:<id> | link:<id> | svc:<id> | broker:<site> — довіряється лише при валідному ptok або CN-сесії; з ptok responder приймає лише origin == sub або <sub>/..., інакше підставляє sub |
| 13 | trace | bstr(16) | both | |
| 14 | enc | tstr | reply | zstd — payload стиснуто |
Статуси
| Код | Ім’я | Код | Ім’я |
|---|---|---|---|
| 0x00 | ok | 0x24 | busy |
| 0x01 | initializing | 0x25 | internal_error |
| 0x02 | refreshed | 0x26 | not_supported |
| 0x08 | not_available | 0x27 | not_found |
| 0x10 | closed | 0x28 | timeout |
| 0x20 | disconnected | 0x29 | out_of_range |
| 0x21 | permission_denied | 0x2A | rate_limited |
| 0x22 | invalid_message | 0x40–0x4F | user-defined |
| 0x23 | invalid_parameter | 0x2B | resource_exhausted |
resource_exhausted — досягнуто межу виконавця (вузли, таймери, підписки, запити в роботі, команди за подію, квота сховища; ADR 0023); повтор не допоможе, поки щось не звільнено. rate_limited — повтор пізніше допоможе. |
Група: < 0x10 — успіх/прогрес; 0x10–0x1F — закриття; ≥ 0x20 — помилка.
ptok v1
ptok = version(1 байт = 0x01) || claims(CBOR) || sig(64 байти, Ed25519 над version||claims)
claims = { "sub": tstr, "roles": [tstr], "grants": [ {"k": key_expr, "p": perm} ],
"max": perm, "iat": uint, "exp": uint, "jti": bstr(16), "site": tstr,
? "auth": [ {"k": key_expr, "p": perm} ], ? "args": bstr(32) }
auth (необов’язковий, з 0.2.10): усі grants викликача на цьому сайті. Його несуть лише токени на дії (~act/*). Він ніколи не дає прав на сам запит — права дає лише grants. Responder, який діє від імені викликача (DQL, scheduler), перевіряє за ним ключі, які викликач назвав у аргументах. SDK обмежує кожен grant з auth так само, як ефективний рівень: min(p, max, attachment.maxperm, cap ключа), а для обмеженого ключа (LimitedKey) лишає тільки ключі в межах його scopes. Токен без auth означає, що права викликача невідомі; responder, якому вони потрібні, відмовляє.
args (необов’язковий, з 0.2.14): SHA-256 тіла запиту (payload ~set або ~act/* байт у байт, як його надіслано). Токен з args дійсний лише для цього тіла: responder SDK рахує SHA-256 отриманого payload і з іншим тілом відповідає permission_denied; такий токен уже використаний (його jti запам’ятовано), друга спроба з ним теж отримує відмову. Так людина погоджує саме ті аргументи, які показав dry run, а не те, що клієнт надішле потім (wyrm-mcp приймає погодження лише з args; wyr token --args-sha256). Без args — будь-яке тіло.
Перевірка responder’ом, у цьому порядку: version == 1 → sig публічним ключем admin’а (kid не потрібен: один активний + один попередній ключ) → exp > now → site == свій → перший grants[i].k, що збігається з ключем запиту (Zenoh key-expr intersect) → jti не в replay-кеші → effective = min(p, max, attachment.maxperm) → effective ≥ required. Будь-яка відмова → permission_denied, без деталей у err (responder може записати причину у свій лог). Відмова, яку responder дає вже після цієї перевірки за власним правилом (ключ поза grants лінка, ключ поза правами автора, дія пише поза вузлом, на який дано право; 0.2.32), каже в err, що саме: так людина може виправити запит.
jti (0.2.11): токен одноразовий для кожного responder’а. Responder пам’ятає jti до exp і вдруге відмовляє. Пам’ять — у процесі: після перезапуску responder’а токен, який він бачив, проходить знову до свого exp. Тому exp не може бути далі ніж 15 хв від now (інакше permission_denied). Коли кеш повний (65 536 токенів, що ще не спливли), responder відмовляє новим токенам, а не забуває старі.
jti (0.2.12): responder запам’ятовує jti лише після того, як знайшов grant для ключа запиту. Токен без такого grant відмовляється і не займає місця в кеші. Один sub займає не більше чверті кешу (16 384 токени, що ще не спливли). Коли його частка повна, responder відмовляє новим токенам цього sub, а інші sub проходять.
Довжина (0.2.36): ptok (version, claims і sig разом) має щонайбільше 65 536 байт. Довший токен responder відмовляє (permission_denied) ще до перевірки підпису: кожен крок перевірки коштує пропорційно довжині, а підпис не названого ключа перевіряється кожним довіреним ключем. Той, хто створює токени, не створює довший.
Фікстури: att_*, ptok_claims_v1, ptok_claims_auth.
05 — Методи
| Метод | Zenoh | Payload запиту | Відповідь | ptok |
|---|---|---|---|---|
list(path, from, limit) | get path/~meta?view=list + subscribe path/*/~meta + liveliness-subscribe path/* | — | array (02-meta) + далі події | лише cfg.restricted |
meta(path) | get path/~meta[?rev=] | — | map або status=ok,rev без тіла | лише cfg.restricted |
resolve(path, match, depth) | get path/~meta?view=keys&match=&depth= | — | array of tstr (стиснуті) | лише cfg.restricted |
subscribe(pattern, qos) | get pattern/~val (storage) + subscribe pattern/~val | — | Stream<Sample{key, v, q, t}> | ні (ACL сесії) |
history(path, from, to, agg?) | get path/~val?history= | — | array (один або кілька reply, 03) | ні (ACL сесії на ~val, як subscribe) |
set(path, v) | get path/~set | {0: v} | attachment status | так |
set_meta(path, field, v) | get path/~set?field= | {0: v} | status | так (config) |
invoke(path, action, args) | get path/~act/<a> | map args (tstr keys) | одна відповідь або стрім | так |
close(path, action, rid) | get path/~act/<a>?close=<rid> | — | status=closed | так |
check(path, action, args) | get path/~act/<a>?check | map args, як invoke | status=ok без тіла, або відмова, як дала б дія | так |
check (0.2.33)
Responder перевіряє виклик так, як його взяла б дія: ptok і рівень, аргументи за ~meta дії, а потім власний розбір аргументів драйвером (форма, права автора, отримувачі). Нічого не робить: ні запису, ні команди, ні зміни стану; усе, що драйвер попросив у host під час перевірки, відкидається. Відмова така сама, як дала б дія (той самий статус і текст); успіх — status=ok без тіла. В аудиті — окремий запис check.
Responder, що відповідає на check, має в ~meta свого кореня (wy/<site>/downstream/<link>, sys, dataflows, storage) attr.check = true. Requester надсилає ?check лише такому: старіший responder не знає параметра і виконав би дію. Без attr.check перевірка закінчується на ~meta дії, на боці requester’а.
WASM-компонент світу wyrm:app 0.3.0 не має виклику перевірки: його перевірка закінчується на ~meta дії (host її робить); власний розбір — з наступним світом.
Стріми (actions.*.stream = true)
mode="reply"(default): N відповідей на один query,ridоднаковий,seqзростає від 0, останняlast=true. Query-таймаут на боці requester’а скидається кожною відповіддю.mode="topic": перша відповідь{status: initializing}з payload{"stream": key}; requester підписується; responder публікує наkey;closeзупиняє; responder видаляє ключ.
Таймаути
Default get — 10 с; initializing продовжує; invoke з actions.*.timeout_ms перевизначає. Відсутність будь-якої відповіді → SDK мапить у disconnected лише якщо liveliness власника відсутній, інакше timeout.
QoS
| Zenoh | ~val | ~meta | ~set/~act | аудит/метрики |
|---|---|---|---|---|
| Priority | Data | DataHigh | InteractiveHigh | Background |
| CongestionControl | Drop | Block | Block | Drop |
| Reliability | per cfg.qos (default BestEffort) | Reliable | Reliable | BestEffort |
| express | false | false | true | false |
Помилки транспорту vs застосунку
Застосунок: status ≥ 0x20 у attachment. Транспорт: відсутність reply / розрив сесії → SDK, не responder.
06 — dataflows/<id>/~def
CBOR map (на дроті) / JSON (у конфігах і UI) — одна схема. Рядкові ключі (користувацький вміст).
{
"id": tstr, // = сегмент ключа
"version": uint, // монотонно; engine ігнорує ≤ поточної
"enabled": bool, // default true
"description": tstr?,
"nodes": { <node_id>: { "type": tstr, ...config, "placement": "local"|"process"|"wasm"? } },
"edges": [ [ "<node>.<port>", "<node>.<port>" ] ],
"policy": { "overflow": "drop_oldest"|"drop_newest"|"block", "queue": uint, "state_flush_s": uint, "restart": {"backoff_max_s": uint} },
"permissions": { "token": tstr, "maxperm": uint / tstr }, ; код (0 none … 3 write) або назва ("write"), 0.2.32
"layout": { <node_id>: [ x, y ] }, // 0.2.5: де редактор малює ноду; компілятор не зважає
"blocks": { <name>: { "description": tstr?, "inputs": [ {"name": tstr, "to": tstr | [tstr], "default": any?, "description": tstr?} ],
"outputs": [ {"name": tstr, "from": tstr, "description": tstr?} ],
"nodes": {…}, "edges": […], "layout": {…}? } } // 0.2.24: власні блоки
}
Порти: <node>.out, <node>.in, іменовані <node>.in.<name> / <node>.out.<name> (у expression — in.<input>; у alarm — out, event).
Поля як виходи (0.2.15, ADR 0038): кожне поле ноди є також виходом, з якого може починатися ребро.
- Параметр
pдає вихідpз ефективним значенням: з конфігу або default, а де є портin.<p>— останній семпл на ньому. Вихід надсилає значення один раз на старті і далі на кожну зміну. - Вхід
x, що не є портом параметра (in,reset,in.0, …), дає вихідx. Він повторює кожен семпл наxдо того, як нода його обробить. - Назва виходу така сама, як у поля:
scale1.input_min,if1.in.0(ребро ділиться на першій крапці: нодаif1, портin.0). - Конфлікт назв: оголошений вихід ноди лишає свою назву; ехо входу йде перед ехо параметра. Тому параметр
resetуlatch(є вхідreset) не має виходу (echo: falseу каталозі). - Тип виходу: ехо входу — тип входу; ехо параметра —
number,bool,mapза типом параметра, інші (string,dynamic,array) —any. Крок 4 валідації перевіряє ці типи, як і решту. - Ехо-вихід, з якого не йде жодне ребро, не будується: runtime не копіює для нього семпл.
Порти параметрів старших типів нод (0.2.17, ADR 0038 §5a): scale — in.k, in.b; alarm — in.high, in.low, in.hysteresis, in.delay_s, in.return_delay_s; delay — in.ms; window — in.size_s; deadband — in.abs, in.pct; timer — in.period_ms. Усі мають тип number. Правило як у логічних блоків: значення з конфігу або default на старті, далі перемагає останній добрий семпл. Семпл, що не є скінченним числом або виходить за межі параметра (period_ms ≥ 10, size_s > 0, ms ≥ 0, delay_s і return_delay_s ≥ 0), ігнорується. Правила конфігу не змінюються (high або low, abs або pct тощо обов’язкові). Новий period_ms, ms, size_s або затримка alarm діє одразу: годинник ноди починається заново через один період після зміни.
Текстові оператори, round.text і case (0.2.21, ADR 0038 §8; повний опис — docs/flow-blocks.md): if.op має ще != (перший вхід не дорівнює жодному з інших), contains, starts_with, ends_with (перший вхід як текст з будь-яким з інших як текстом). round має параметр min_precision (порт in.min_precision) і вихід text: число з precision знаками, кінцеві нулі обрізано до min_precision знаків (default — precision). Новий блок case: вхід in, параметри op (=, !=, >, <, >=, <=, contains, starts_with, ends_with) і else (default null), змінні входи inputs парами (case, then); вихід out — then першої пари, чий case збігається з in за op, інакше else. Порожній текст case нічого не збігає.
Порти решти параметрів блоків (0.2.20): concat — in.strict; if — in.op (лише відомий оператор, інший текст ігнорується); hub — in.ignore_null; trace — in.tracing, in.msg. Тепер кожен параметр логічного блоку має порт, крім value змінних (його замінює вхід in) і inputs.
Константи операндів (0.2.19, ADR 0038 §7): логічний блок має ключ конфігу values: {<port>: <value>}, наприклад {type: "concat", values: {"in.0": "AHU-", "in.1": 2}}. Ключ — операнд блоку: in (якщо блок його має) або in.<name> з його inputs. Не можна: порт параметра, reset у stopwatch, змінні (number, string, bool мають value). Інакше — помилка компіляції values.<port>: not an operand input. Константа — значення входу, доки семпл на цьому вході її не замінить (прив’язка перемагає). З 0.2.30 чистий блок без жодного ребра на вході обчислює один раз на старті зі своїх констант і параметрів (див. «Що обчислюється на старті» нижче). Блок, у якого є хоча б одне вхідне ребро, чекає першого семпла, як і раніше; його константи діють, коли семпл прийде. Deploy, гаряча заміна і перезапуск ніколи не виконують set або invoke через константу. watch, ports і preview показують константу як значення входу від старту. Каталог: values: true у типів, чиї операнди беруть константу. now константи не бере (0.2.30): його in лише запускає; values у конфігу now, збережений раніше, engine читає й ігнорує.
Що обчислюється на старті (0.2.30, звужує правило ADR 0032 §5):
- Змінні (
number,string,bool,table) іconstantнадсилають значення на старті. - Чистий блок без вхідних ребер обчислює один раз на старті зі своїх констант і параметрів. «Без вхідних ребер» означає: жодне ребро не веде в жоден його порт (операнд, порт параметра,
reset). Чисті блоки — функції лише своїх входів і параметрів, без стану, подій і власного годинника: математика, тригонометрія, статистика,not,if,case,select, текст, кодеки,make_object,make_array,get,stats,date_time,date_format,date_parse,date_math,date_rangeі табличні блоки, крімtable_pageіtable_recorder. Повний перелік (83 типи) —docs/flow-blocks.md. - Не чисті (чекають семпла):
counter,toggle,changed,rising_edge,falling_edge,event_gate,sample_and_hold,debounce,throttle,stopwatch,hub,trace,catch_error,router,table_recorder,table_page,now, а також ноди, що не є логічними блоками. nowдає час на старті, якщо йогоinterval_msбільший за 0.- Те, що надсилають правила 2 і 4, — семпл «з констант». Він також «народжений на старті», і runtime переносить обидві позначки на все, що нода надсилає, обробляючи такий семпл. Семпл «з констант» не запускає команду ніде: ні через
trigger,auto_run,arg.<name>, ні черезinуsetтаinvoke. Він лише дає полю значення. Стартове значення змінної — не «з констант»: наinкоманди воно пише, як раніше (УВАГА нижче).
Ключ з порту в межах scope (0.2.22, ADR 0040 §1): subscribe і liveliness мають вхід in.key, вихід error і параметр key_scope.
keyу конфігу — стартовий ключ. Його може не бути, якщо єkey_scope.key_scope— key expression (відносний відwy/<site>/або повний), наприкладdownstream/modbus/line1/**. Він обов’язковий, коли вin.keyвходить ребро: інакше помилка компіляціїnodes.<id>.key_scope: required when in.key is wired. Scope за замовчуванням немає.- Scope лежить у
downstream,dataflowsабоstorageсвого сайту (крок 9). Секція є літеральним префіксом scope. - Deploy:
authдеплоєра даєreadна весь scope. Гранти читаються по порядку: грант нижчеread, що перетинає scope, відмовляє; грантread, що покриває весь scope, дозволяє; грантreadна частину лишає решту наступним грантам.watch,portsіpreviewперевіряють те саме для того, хто викликає. - Runtime приймає значення з порту, лише коли воно: текст; не порожнє; не довше 512 байтів; один конкретний ключ вузла (кожен сегмент
[A-Za-z0-9_.-]+: без*,**,$*, без~meta, без порожніх сегментів); у секціях свого сайту; у межах scope. - Новий ключ: спершу закінчується старе читання,
outнадсилаєnullз якістюuncertainі лишається таким до першого семпла нового ключа. Ефективнийkey(ехо-вихідkey,params.keyуwatch) — ключ, як його написано. - Відмова: нода нічого не читає,
out—null/uncertain, ефективнийkey—null, вихідerrorнесе причину текстом.errorповертається доnullз наступним прийнятим ключем. nullна порту: нода нічого не читає, помилки немає.- Між двома змінами ключа минає щонайменше 100 мс. Значення, що прийшло раніше, чекає; перемагає останнє.
- Цілі команд (
set.path,invoke.path,invoke.action) іpublish.nodeпортів не мають (ADR 0040 §1a). - Каталог:
params[].scope— назва параметра, що тримає scope цього поля (key→"key_scope").
Блок дії та поведінка команд (0.2.23, ADR 0040 §2): invoke і set мають поля поведінки, вхід trigger і виходи-події.
- Аргументи
invoke: кожен ключ мапиargs— аргумент. Значення ключа — константа аргументу. Портarg.<name>замінює її останнім семплом. Не більше 64 аргументів; назва має 1–128 байтів і не починається з__. Константа"$in"означає останнє значення наin. interval_ms(портin.interval_ms, default 0): 0 — вимкнено; інакше 100 … 86 400 000. Нода запускається кожен період, уперше — через повний період після старту. Період пропускається, доки попередній запуск не отримав відповіді.auto_run(портin.auto_run): уinvoke(default false) семпл наarg.<name>, що змінює аргумент, запускає дію. Уset(default true) значення наinзаписується, як раніше;false—inлише тримає значення.enabled(портin.enabled, default true):false— ноду нічого не запускає.run_on_start(bool, default false, без порту):true— нода запускається рівно один раз на кожен старт флоу (deploy, гаряча заміна, reload, перезапуск), через 250 мс після старту ноди. Це єдиний дозволений виняток з правила старту, і його обирають для кожного блоку окремо. Вимкнена нода стартового запуску не робить.setпише значення, якеinотримав до цього моменту, і не пише його вдруге післяauto_run. У preview стартовий запуск — це рядокsinks, а не запис.- Один блок, а не окремий тип на кожну поведінку: поведінку задають поля
trigger,auto_run,interval_ms,enabled,run_on_start. Старийonуinvokeдіє лише дляin, як раніше (changeвідповідаєtriggerзі значенням;rising/falling— блоку фронту передtrigger). - Вхід
trigger: подія{event, id}запускає ноду; інше значення запускає її, коли воно відрізняється від попереднього семпла наtrigger.nullі семпл якостіbad(безallow_bad) нічого не запускають. inпрацює, як раніше:invokeзапускається на кожен семпл, що проходитьon;setбере значення для запису.- Виходи обох типів:
sent(подія: запит пішов),ok(подія: ціль відповіла без помилки),error(подія{event, id, code, message}:code— код статусу spec 04),running(bool),last_run(час останньогоsent, мкс).invokeмає щеresult(останній результат) іout(результат з якістюgoodабо текст помилки з якістюbad, як раніше). - Правило старту: семпл «народжений на старті» ніколи не запускає команду через
triggerабоauto_run. Такими є: стартове значення змінної таconst, стартове значення ехо параметра, тік годинника на старті, перший семпл читання (subscribe,liveliness), а також усе, що нода надсилає, обробляючи такий семпл. Тому deploy, гаряча заміна, reload і перезапуск не виконують команду черезtrigger,auto_runчиinterval_ms.inцього правила не має (див. УВАГА нижче), крім семпла «з констант» (0.2.30): він наinлише дає значення. dataflows/<id>/~act/trigger {node}— рівеньwrite; один запуск нодиinvokeабоsetзадеплоєного флоу, що працює.authтого, хто викликає, дає на ціль ноди (…/~act/<a>або…/~set) рівеньmax(maxperm, write)— той самий, що deploy вимагає від proof деплоєра; інакшеpermission_denied. Інша нода —invalid_parameter; флоу не працює —not_supported.- У preview
setтаinvokeне мають клієнта: вони повідомляють уsinks, що надіслали б, даютьsentіlast_run, і ніколи не даютьok,error,result,out,running. - Каталог:
dyn_inputs.keys: true— параметр є мапою, порти названі її ключами (invoke.args→arg.<name>);trigger: trueу типів, які запускає~act/trigger.
УВАГА: ехо параметра надсилає значення на старті. Ребро з нього до invoke або set виконує команду при deploy. Так само діє стартове значення змінної і перший семпл subscribe на in команди. Чистий блок без вхідних ребер команди не виконує (0.2.30).
layout належить редактору (ADR 0019). Ключ — це node_id або ключ редактора <node>~<name>~<rest> (0.2.26; ~ не може бути в node_id, тому такий ключ не сплутати з нодою). Редактор Studio зберігає так вибір пінів блоку: "<node>~pin~<field>": [1|0, 0]. Значення кожного ключа — два скінченні числа. Engine ключі редактора не читає і не вимагає, щоб нода ключа існувала; він зберігає layout як надіслано. Ліміти: не більше 16 384 записів, ключ не довший за 256 байтів (інакше помилка компіляції layout: …). Те саме правило діє для layout власного блоку. Він не входить до конфігу ноди, тож переміщення ноди не скидає її стан при гарячій заміні.
Каталог типів нод для редактора: dataflows/~act/node_types (рівень read) повертає масив {type, category, description, inputs, outputs, dyn_inputs?, dyn_outputs?, port_types, echo_inputs?, values? (0.2.19), params: [{name, type, required, description, choices?, default?, editor?, port?, scope? (0.2.22), echo, display? (0.2.29)}]}; dyn_inputs/dyn_outputs = {param, prefix, default} — порти, які дає параметр (expression: in.<name> з inputs; wasm: inputs/outputs).
Поля 0.2.15 (ADR 0038, лише додані):
params[].default— типізоване значення для кожного параметра, що його має: число лишається числом,choices— рядком, список імен — масивом (inputsблоків:["0", "1"]). Без default поля немає.params[].port—"in.<p>", коли в параметра є вхідний порт; інакше поля немає.params[].echo—true, коли параметр має вихід своєї назви;falseпри конфлікті назв (див. «Поля як виходи»).port_types—{<port>: <type>}(number,bool,map,any) для фіксованих входів і виходів, для динамічних портів з їхнімиdefaultі для ехо-виходів. Динамічні порти з іншими назвами мають типany.echo_inputs: true— входи типу, що не є портами параметрів, повторюються як виходи. У типів без входів поля немає.
Другий набір блоків (0.2.25, ADR 0040 §4; повний опис — docs/flow-blocks.md)
- Читачі:
load_value(одне читання збереженого значення точки;key, портin.key, scopekey_scope) іlist_children(діти вузла як список рядків{name, path, type?, display?, is?, unit?, writable, has_children}, не більше 1000;path, портin.path, scopepath_scope). Обидва маютьinterval_ms,auto_run(default true: читання на старті і при зміні ключа),enabled, вхідtriggerі виходиout,ok,error({event, id, code, message}),running,last_run. Їхній ключ і scope перевіряються як джерело (крок 9, права deploy іwatch). Читання — не команда: правило старту дляauto_runчитача не діє.list_childrenпоказує рядок кожної дитини, тому deploy,watch,portsіpreviewвимагають читання також<path>/*і<path_scope>/*: одна заборонена дитина відмовляє. - Текст:
substring(start,length),replace(from,to),split(separator; не більше 1000 частин),join(separator). Результат довший за 4 КіБ —nullз якістюbad. - Дані:
make_object(мапа іменованих входів),make_array,get(pathвидуa.b.0),stats(виходиmin,max,avg,sum,countдля чисел списку). - Події і стан:
changed(вихідon_change),rising_edge,falling_edge(вихідon_edge),counter(step,initial, вхідreset),toggle(initial,reset),sample_and_hold(входиin,trigger),select(index). Семпл, народжений на старті, дає блоку значення і нічого не запускає. - Час:
debounceіthrottle(ms, не більше 3 600 000). - Кожен параметр цих блоків має порт
in.<p>, крімinputsі scope. - Число з порту або з конфігу, що не є скінченним (NaN, ±inf), блок числом не вважає; такий семпл на порту параметра ігнорується, і діє останнє добре значення.
msбез числа — 500;substring.length— не більше 4 КіБ;select.indexпоза входами даєnull.
Третій набір блоків (0.2.29, ADR 0044; повний опис — docs/flow-blocks.md)
- Математика:
constant(name:pi,e,sqrt2,ln2,ln10,log2e,log10e; надсилає на старті, як змінна),factorial,log(base),power(exponent),root(degree),bound(min,max; виходиinput_out_of_range,out),round_up,round_down(precision; виходиout,text),format_number(format,decimal_separator,group_separator),parse_number. - Тригонометрія в градусах:
sin,cos,tan,cot,asin,acos,atan(x, default 1),to_degrees,to_radians. - Статистика за змінними входами:
average,median,mode,std_deviation,variance; вхід зі списком дає його числа (не більше 1000). - Текст і кодеки:
left,right(length),trim,base64_encode,base64_decode(виходиout,bytes),url_encode,url_decode,to_camel_case,from_camel_case,hash(algorithm:sha256,sha1,md5),json_parse(виходиout,parse_error; не більше 256 КіБ і 32 рівнів),json_stringify(pretty). - Старі блоки (конфіг без нового поля дає те саме, що раніше):
substringбереend(безlength; від’ємний рахує з кінця),replaceбереregexp(from— шаблон),caseмає операторregexp. Шаблон — не більше 256 байтів і 64 КіБ після компіляції, лінійний час (regex), без backreferences; шаблон, що не компілюється, нічого не знаходить. - Дата і час: дата — це мікросекунди від епохи Unix, як
tсемплу; вхід бере також текст RFC 3339,yyyy-M-d[ H:mm[:ss[.f]]],yyyy/M/d …,M/d/yyyy …(зam/pm).time_zone— назва IANA,UTC(default) або±HH:MM(tzdb зjiff; час у проміжку DST — вперед, повторений — раніший). Блоки:now(поточний час: на старті, кожніinterval_msі на кожен семплin; з 0.2.30 параметрinterval_msз портом, default 1000, 0 — лише на семплin, інакше 100 … 86 400 000; стартове значення — «з констант», наступні тіки — звичайні семпли;inлише запускає і константи не бере),date_time(year…millisecond,time_zone),date_format(format,time_zone, такожauto),date_parse(виходиtime,year,month,day,hour,minute,second,millisecond,weekday: 1 — понеділок),date_math(op:after/before; роки, місяці й дні — за календарем зони, решта — як пройдений час),date_range(входиin,next,previous;format,range_delimiter,keep_special,week_start(defaultmonday),time_zone; виходиstart,end(включно),this_range,next_range,previous_range,formatted,duration).previousN<unit>— період передcurrentN<unit>. Іменований або відносний діапазон рахується знову щосекунди. - Логіка і події:
router(входиin,conditionі змінні входи — значення випадків; виходиout.<name>для кожного випадку іelse;opяк уcase,single_output),event_gate(вхідreset, змінні входи;log_order:none,first_occurrence,last_occurrence,all; виходиon_finish,order),catch_error(змінні входи — подіїerrorабо тексти; виходиout,code,source,on_error). Семпл, народжений на старті, не рахується. - Читачі:
load_history(key,in.key,key_scope;time_range— текст діапазону, як уdate_range, defaulttoday;rollup,window,limit≤ 10 000,time_zone;out— таблиця{t, v, q}; подіяokмаєrowsіtruncated, коли відповідь досяглаlimit) іget_node(виходиout— підсумок вузла,actions— таблиця дій з їхніми параметрами). Обидва перевіряються як джерело (право читання ключа і всьогоkey_scope). Кожен читач (такожload_value,list_children) запускаєdataflows/<id>/~act/trigger {node}; тоді той, хто викликає, має право читання ключа і всього scope читача (дляlist_children— і дітей), а не рівень команди; крім того, для кожної нодиsetчиinvokeнижче за течією від ноди, яку запускають (через усі ребра, транзитивно, з розгорнутими власними блоками), той, хто викликає, має рівеньmax(maxperm, write)на її ціль — так само й для ноди-команди, відповідь якої запускає іншу команду; каталог дає читачамtrigger: true. - Таблиця (значення):
{columns: [<name>…], rows: [{<name>: <cell>…}…]}; вхід бере також список мап і рядки-списки за позицією. Не більше 10 000 рядків, 128 колонок, назва ≤ 256 байтів, ≤ 512 КіБ клітинок; більша —nullз якістюbad. - Таблиці:
table(змінна),table_recorder(рядок{t, <вхід>…}на кожен семпл змінного входу;buffer_size≤ 10 000,time_window_s,ignore_null, вхідreset),table_from_csv,table_to_csv,table_from_json(selector),table_to_json,table_map_columns(mapping: [{name, from}]),table_sort(column,method:number/string/natural,order),table_filter,table_remove_rows,table_edit_rows(expr,cells),table_group_by(column,aggregates: [{column, method, as}]),table_join(входиin,right;column,right_column,join:left/inner/right/full/exclude/union),table_page(входиnext,previous,first,last),table_rollup(time_column,interval<n>s|m|h|d|w|M|y,round_time,method,aggregates,week_start,time_zone),table_aggregate,table_select_rows,table_select_columns,table_columns,table_row_cells,table_add_row,table_transpose,table_from_map. Скрипти рядків — rhai надrowіindex, перевіряються при компіляції (крок 6), разом не довше 100 мс на таблицю. Ці 100 мс — процесорний час потоку, що виконує скрипти таблиці: час, коли хост не давав потоку ядра, не рахується. Де годинника процесорного часу потоку немає, рахується настінний час. - Результат, що не є скінченним числом, —
null. - Каталог:
params[].display— підпис поля для редактора, коли підпис з назви був би хибним (лише додано).
Власні блоки (0.2.24, ADR 0040 §3)
Визначення може мати blocks. Нода типу block:<name> — екземпляр блоку <name>.
inputsіoutputsблоку — списки (редактор малює поля в цьому порядку). Назва —[A-Za-z0-9_]+, унікальна серед входів і виходів разом. Не більше 64 входів і 64 виходів.to— один внутрішній вхід"<inner>.<port>"або список з 1–16 таких;from— внутрішній вихід.- Параметр блоку — це вхід з
default. Окремого списку параметрів немає. - Екземпляр має лише ключ
values: {<input>: <value>}. Його порти — входи й виходи блоку:["x.out", "m1.a"],["m1.out", "y.in"]. Вхід є також виходом своєї назви (ехо першого внутрішнього входу зto). - Компілятор замінює екземпляр внутрішніми нодами з id
<instance>/<inner>(у вкладеному блоці —<instance>/<inner instance>/<inner>). Авторський id не містить/. - Константа входу (
valuesекземпляра, інакшеdefault) стає константою кожного внутрішнього входу зto: порт параметра → конфіг параметра; операнд логічного блоку → йогоvalues;arg.<name>уinvoke→args;inзмінної →value; вхід внутрішнього екземпляра → йогоvalues. Вхід, що не тримає константи (filter.in,set.in), дає помилкуnodes.<id>.values.<input>: <inner>.<port> takes no constant. - Блок може містити екземпляри інших блоків того самого визначення. Глибина — не більше 4. Блок, що містить себе (прямо або через інші блоки), відхиляється до розгортання:
blocks.<name>: a custom block may not contain itself (a → b → a). - Ліміти розгортання (компілятор рахує їх під час розгортання і зупиняється на першому перевищенні): 1000 нод флоу рахують кожну розгорнуту ноду і кожен екземпляр на кожній глибині; не більше 4000 ребер у флоу після розгортання; один блок має не більше 64 екземплярів інших блоків, 1000 нод і 4000 ребер; не більше 64 блоків у визначенні.
publishусередині блоку має одну назву в кожному екземплярі, тому такий блок можна вжити один раз (крок 7a).watch,portsіpreviewпоказують внутрішні ноди під їхніми id:nodes: {"m1/sum": {…}}. Аргументnodesприймає id екземпляра і тоді означає всі його внутрішні ноди. Окремого рядка екземпляр не має.~act/triggerприймає внутрішній id.~defта історія зберігають визначення, як його надіслано, разом зblocks.
Бібліотека блоків сайту (дії на dataflows):
put_block {name, def}— рівеньconfig;def— один блок. Engine перевіряє його, як deploy: сам у пробному флоу, з блоками бібліотеки, які він вживає. Відповідь{name, version}; коженput— наступна версія. Не більше 256 блоків, 256 КіБ на блок.get_block {name}— рівеньread; відповідь{name, version, def, requires: {<name>: def}}з усіма блоками бібліотеки, які він вживає.list_blocks— рівеньread;[{name, version, description?, inputs: [назви], outputs: [назви]}].remove_block {name}— рівеньconfig;not_found, якщо блоку немає.- Флоу копіює блок, а не посилається на нього: редактор бере блок через
get_blockі записує його (таrequires) уblocksвизначення. Engine під час компіляції бібліотеку не читає.
Валідація (порядок, перша помилка зупиняє)
- схема; 2. унікальність
node_id,[A-Za-z0-9_]+; 3. тип ноди є в реєстрі, конфіг за схемою типу; 4. ребра → існуючі порти, сумісні типи; 5. ациклічність (цикл дозволений лише черезdelay); 6. rhai компілюється; 7.permissions.maxperm≥ мін. рівня всіхinvoke/set-нод і ≤write(флоу не робить config-операцій); 8. ліміти пам’яті (window.max_samplesсума; з 0.2.24 — не більше 4000 ребер у флоу з розгорнутими власними блоками; з 0.2.16 — не більше 1000 нод у флоу: кожна нода — це задача і черга під час роботи, у задеплоєному флоу і в preview); 9. (0.2.13)keyкожної нодиsubscribeіlivelinessлежить підwy/<site>/downstream,wy/<site>/dataflowsабоwy/<site>/storageсвого сайту (відносний ключ читається відwy/<site>/): неsys,pub,upstream, не інший сайт. Engine читає через сесію broker’а, якої ACL не бачить, тому правило перевіряє deploy, validate і старт збереженого флоу. З 0.2.22 те саме правило діє дляkey_scope, а крок 4 має додаток 4a: ребро вin.keyпотребуєkey_scopeу конфігу ноди.
Помилка → dataflows/<id>/~val = {state: 2 (error), error: "<path>: <msg>"}; стара версія працює.
~val флоу
{0: {"state": 0 running | 1 stopped | 2 error, "error": tstr?, "version": uint, "since": uint, "deployed_by": tstr?}, 1: q, 2: t}
deployed_by — суб’єкт, що задеплоїв поточну версію (origin запиту або sub токена). Флоу працює далі, навіть якщо деплоєр втратив права (ADR 0008); поле дає оператору знайти такі флоу.
Метрики (0.2.31, ADR 0045)
Мапа ~val має також ключ stats (додатковий: старий читач його пропускає):
"stats": {"nodes": uint, "edges": uint, "samples_in": uint, "samples_out": uint, "dropped": uint,
"restarts": uint, "commands": {"sent": uint, "ok": uint, "error": uint}, "last_sample_t": uint?}
nodes,edges— ноди і ребра скомпільованого флоу (власні блоки розгорнуто).samples_in— семпли, які ноди взяли зі своїх черг: кожен семпл із ребра і кожен семпл, який отримало власне джерело ноди (subscribe,liveliness,const, позначка «власник зник» уsubscribe). Внутрішні повідомлення не є семплами: відповідь команди чи читача, запит читача на читання,~act/trigger.samples_out— семпли, які ноди надіслали на вихід, з якого йде хоча б одне ребро (один раз, скільки б ребер не було). Записpublish,setіinvokeсюди не входить.dropped— семпли, які черги нод відкинули заpolicy.overflow(зокрема джерело, що пише в повну чергу приblock). Семпл, якийpublishпропускає, поки його writer зайнятий, сюди не входить.restarts— перезапуски після panic ноди.commands— подіїsent,okіerrorнодinvokeіset(0.2.23).errorрахує також запуск, відмовлений до надсилання (busy), томуok + errorможе бути більше заsent.last_sample_t— час (µs), коли нода востаннє взяла семпл (як уsamples_in); немає до першого.
Скидання: лічильники належать поточному запуску. Нові лічильники (усі 0) — при кожному deploy (також hot swap і кожен збережений флоу, який engine деплоїть на своєму старті, тобто при кожному старті broker’а і кожному rebuild ACL), при start і при reload. Перезапуск після panic лічильники зберігає (restarts + 1). Зупинений флоу і флоу в error зберігають останні значення. Deploy, що не компілюється, лічильників не змінює.
Публікація: зміна стану (deploy, start, stop, reload, помилка, перезапуск) публікує ~val одразу, як раніше, з лічильниками цього моменту. Між змінами стану engine публікує ~val флоу знову не частіше за один раз на період і лише тоді, коли лічильники відрізняються від тих, що були в останньому ~val. Флоу без руху і зупинений флоу нічого не публікують. Період у wyrmd — metrics_interval_ms (default 10 с), не менше 5 с. Помилку чернетки, що не компілюється (state: 2, error), мають і всі наступні ~val з лічильниками, доки не зміниться стан (deploy, start, stop, reload, перезапуск); стара версія тим часом працює і рахує.
Живі значення (0.2.15, ADR 0038)
dataflows/<id>/~act/watch — рівень read, stream: true, timeout_ms: 30000. Аргументи: nodes (масив id нод; немає або порожній — усі; невідомий id — invalid_parameter), max_hz (число > 0 і ≤ 20, default 4).
Права: auth у ptok того, хто викликає (spec 04), має покривати читання кожного джерела флоу (subscribe, liveliness), як при deploy, і кожної цілі команд (вузол кожної ноди invoke і set, без ~act/<a> чи ~set). Вихід invoke несе відповідь цілі, а вхід set — те, що нода туди пише. Інакше — permission_denied. Помилка engine називає перший ключ, але SDK надсилає цей статус без тексту. Флоу без джерел і без цілей не потребує auth.
Рядки (CBOR map, текстові ключі; [v, q] — значення і код якості, як у ~val):
- перший:
{t, snapshot: true, nodes: {<node>: {in: {<port>: [v, q]}, out: {<port>: [v, q]}, params: {<p>: v}}}}— кожна нода (або зnodes), усі три мапи завжди є;params— ефективне значення кожного параметра, що його має; - далі:
{t, snapshot: false, nodes: {…}}— лише ноди і порти, що змінилися після попереднього рядка; порожніin/out/paramsпропущено. Не більшеmax_hzрядків на секунду; у межах періоду перемагає останнє значення; - heartbeat
{t, nodes: {}}(безsnapshot), коли 10 с не було рядка; - потік закінчується через 30 хв (ttl), при redeploy (останній рядок
{t, redeployed: <version>}), при remove і при зупинці engine (без рядка). Редактор відкриває його знову.
Engine зберігає останній семпл кожного входу і виходу задеплоєного флоу від старту, навіть без відкритого watch (0.2.18). Один слот на порт; новий семпл перезаписує його. Тому змінна, що надіслала значення один раз на старті, є в кожному пізнішому snapshot і в ports. Порт без жодного семпла від старту відсутній у in/out.
Ліміти: ≤ 8 watch на флоу, ≤ 64 на сайт. Engine не бачить, що той, хто викликає, пішов: на ліміті новий watch того самого суб’єкта (origin або sub) закриває його найстаріший watch (на флоу, а на ліміті сайту — будь-який його); watch іншого суб’єкта отримує busy.
dataflows/<id>/~act/ports — рівень read, аргумент nodes, ті самі права; повертає рядок 1 (для інструментів без потоку: wyrm-agent, MCP) з усіма значеннями портів від старту флоу.
Значення ніколи не пишуться в лог вище trace.
Preview чернетки (0.2.16, ADR 0038 §5)
dataflows/~act/preview (на корені dataflows) — рівень read, stream: true, timeout_ms: 30000. Аргументи: def (визначення в тій самій формі, що й для deploy), nodes (масив id нод, як у watch), max_hz (число > 0 і ≤ 20, default 4).
defкомпілюється, як при deploy і validate (усі кроки валідації). Помилка —invalid_parameterз текстом компілятора.maxpermіproofsне потрібні: preview нічого не пише.- Права — як у
watch:authтого, хто викликає, покриває читання кожного джерела і кожної цілі команд. Інакше —permission_denied. - Чернетка працює в пісочниці: справжній runtime без збереження (ні
~def, ні стану нод), без вузла в дереві, з id поза задеплоєними флоу. Чернетка з id задеплоєного флоу не торкається ні цього флоу, ні йогоwatch. Читання йде через клієнт без токенів. - Ноди
set,invokeіpublishу preview — це ноди-записувачі без клієнта: вони не можуть писати за побудовою. Вони застосовують те саме правило, що й задеплоєна нода (allow_bad,on,deadband,$inвargs), і лише повідомляють результат.invokeу preview нічого не надсилає наout. - Рядки — точно як у
watch(snapshot, зміни ≤max_hz, heartbeat{t, nodes: {}}через 10 с). Будь-який рядок може мати ключsinks: [{node, op, key, value}]:op—set,invokeабоpublish;key— повний ключ, куди нода писала б (wy/<site>/<path>/~set,wy/<site>/<path>/~act/<action>,wy/<site>/dataflows/<def.id>/nodes/<node>);value— значення, а дляinvoke— мапа аргументів після$in. Snapshot має останнє від кожної такої ноди; рядок змін — ті, що спрацювали після попереднього рядка, останнє на ноду. Рядок лише зsinks— це рядок змін (snapshot: false,nodes: {}).nodesфільтрує іsinks. - Запис іде від старту: перший рядок чекає (≤ 500 мс), доки всі ноди запустяться і стихнуть. Тому snapshot уже має стартові значення змінних і те, що вони дали далі.
- Preview закінчується через 10 хв (ttl), коли новий preview того самого суб’єкта займає його місце, при panic ноди (потік закінчується зі статусом
internal_error, без перезапуску) і при зупинці engine. Редактор відкриває його знову з останньою чернеткою. Таймери,stopwatch,delay,windowпрацюють як завжди. - Ліміти: ≤ 2 preview на суб’єкта (
originабоsub; третій закриває найстаріший), ≤ 16 на сайт (busyпонад це). Engine не бачить, що той, хто викликає, пішов: preview живе до ttl або до заміни.
spec changelog
- 0.1.0 (2026-10-20): initial — 01–06, tables.json, 22 fixtures.
- 0.1.1 (2026-10-20): 06 —
permissions.maxperm≤write(validation step 7). No fixture change. - 0.1.2 (2026-10-20): 02 — profiles:
"extends"text key, inheritance rules,?expand=true; fixtureprofile_extends. - 0.1.3 (2026-10-20): 04 —
originbound to the token subject (subor<sub>/...). No fixture change. - 0.1.4 (2026-10-21): 06 — flow
~valgets optionaldeployed_by. No fixture change. - 0.1.5 (2026-10-21): 01 — peer broker nodes: downstream sites at
down/<d>, upstream atup/<u>(wy:broker,attr.root,connected);up/is no longer a reserved virtual prefix. No fixture change. - 0.1.6 (2026-10-22): 02 — UI fields: action
display,group; param-metadisplay,description,placeholder,editor(password,textarea); fixturemeta_action_ui. - 0.1.7 (2026-10-22): 02 — param-meta
editor: "file"(binary parameter from a local file). No fixture change. - 0.1.9 (2026-10-22): README rule 4 — the protocol version is
attr.protoofwy/<site>/sys/~meta;wy/<site>/sys/brokerstays the broker’s liveliness token, without a node. No fixture change. - 0.1.8 (2026-10-22): README rule 6 — nesting of arrays, maps and tags in one value is at most 32; deeper input is
invalid_message. No fixture change (every fixture is shallower). - 0.1.10 (2026-10-22): 01, 03, 05 — history:
since=,aggand|or, any<n>s|m|h|d|wwindow,limit≤ 100 000; the answer is one or more arrays from the broker’s historian (ADR 0014), errors as a status attachment; rights assubscribe(session ACL on~val), nohistory:readtoken (owner decision). Fixtureshist_raw,hist_agg(HistRowin both SDKs). - 0.1.11 (2026-10-23): 02 —
view=listsummaries carryunit(key 2) andwritable(key 4, already sent by the SDK); the UI writes the unit after numeric values. Fixturemeta_view_list(first child has2: "°C"). - 0.2.0 (2026-10-23, breaking): 01, 06 — site sections under full names:
down→downstream,up→upstream,flows→dataflows(owner decision, backlog items 3 and 4). Fixtureptok_claims_v1(grant keys). Stored grants and history watches replay under the new names (registry SCHEMA 14, gateway users SCHEMA 4), and the historian’s recorded series are renamed when its store opens; deployed flows must be deployed again (their proofs name the old keys). - 0.2.1 (2026-10-23): 02 —
view=listsummaries carry key 16has_history(true whenattr.historyis not empty);attr.history= array of store keys, a key underwy/<site>/sys/history/answers at the point’s own key (ADR 0016). Fixturemeta_view_list(second child has16: true). - 0.2.2 (2026-10-24): 01 — site section
storage(wy/<site>/storage/**): broker storage of folders and values people create, as a DSA broker’s/data(ADR 0017); link idstorageis reserved. No fixture change. - 0.2.3 (2026-10-24): 01 — commands from upstream sites:
~set/~actondownstream,dataflows,storageof a site below always, onsysonly with that site’sallow_config; tokens carry the target site;wy/<site>/sys/signing_keyslists the keys that sign them (ADR 0018). No fixture change. - 0.2.4 (2026-10-24): 02 — param-meta
editorvaluesdaterange(<from>/<to>in RFC 3339, with preset ranges),date(one instant) andduration(seconds, typed in a chosen unit) for UIs. No fixture change. - 0.2.5 (2026-10-24): 06 —
~def.layout{<node_id>: [x, y]}(editor positions, ignored by the compiler and outside a node’s config) anddataflows/~act/node_types(the node-type catalog for editors). No fixture change. - 0.2.6 (2026-10-28): 02 — key 17
has_nodes(bool, on a container’s~metaand inview=list): a child withouttypeexists, so a tree UI draws a triangle only where it has nodes to show; the responder publishes the container’s~metaagain when it changes. Fixturemeta_view_list(fourth child, a folder with17: true). - 0.2.7 (2026-10-28): 02 — a site’s historian also answers at each watch key (
wy/<site>/sys/history/<group>/<watch>/~val?history=); a downstream site’s point that it records is read there, and itsattr.historycomes from the recording site (sys/overlays/.sites, merged by that site’s gateway; ADR 0020). No fixture change. - 0.2.8 (2026-10-28): 04 — status 0x2B
resource_exhausted(a bound of the callee reached; ADR 0023). No fixture change. - 0.2.9 (2026-10-31): 01 —
allow_configof an upstream opensconfigon the whole site below (downstream,dataflows,storageandsys), not onsysalone (owner decision, ADR 0018 amendment): link actions such as Export, Edit, Stop run from above. No fixture change. - 0.2.10 (2026-10-31): 04 — optional
ptokclaimauth: the caller’s full grant set on this site, sent only on~act/*tokens, never used to authorize the request; a responder that acts for the caller (DQL, ADR 0025 item 4, owner decision) checks the keys the caller names against it, capped as the effective level and to a limited key’s scopes; noauth= refused where it is needed. Fixtureptok_claims_auth. - 0.2.11 (2026-10-31): 04 —
jtiis single-use per responder (remembered untilexp, in memory: a responder restart forgets it),expat most 15 min ahead, a full cache refuses new tokens (ADR 0029, decision 3). No fixture change. - 0.2.12 (2026-11-01): 04 — the grant lookup comes before the replay check: a token with no grant for the request key is refused and never remembered; one
subholds at most a quarter of the replay cache (16 384 live tokens), so one caller cannot lock out the others (security review, ADR 0029 decision 3). No fixture change. - 0.2.13 (2026-11-01): 06 — validation step 9: a
subscribeorlivelinesssource reads the own site’sdownstream,dataflowsorstorageonly (security review, ADR 0031). No fixture change. - 0.2.14 (2026-11-01): 04 — optional
ptokclaimargs: SHA-256 of the request payload; the responder refuses another payload (permission_denied).wyrm-mcptakes human approvals only with it (security review, ADR 0031). Fixtureptok_claims_args. - 0.2.15 (2026-11-08): 06 — fields as outputs: every parameter
pof a node is also an outputp(its effective value, at start and on each change) and every inputxthat is not a parameter’s port an outputx(each sample, before the node handles it); a declared output keeps its name, an input’s echo comes before a parameter’s (latch.reset); an unwired echo is never built.node_typesadds (additive)params[].port, a typedparams[].default,params[].echo,port_types,echo_inputs.dataflows/<id>/~act/watch(stream: snapshot, changes at mostmax_hz≤ 20, heartbeat 10 s, ttl 30 min,{redeployed}on a redeploy; ≤ 8 per flow, ≤ 64 per site, the same caller’s oldest ends at a cap) and~act/ports(one snapshot), bothreadwith the caller’sauthcovering every source and every command target (ADR 0038). No fixture change. - 0.2.16 (2026-11-08): 06 —
dataflows/~act/preview {def, nodes?, max_hz?}(levelread, stream): a draft compiled as for deploy runs in a sandbox (nothing persists, no tree node, reads without tokens) withset/invoke/publishas capture nodes that cannot write; rows aswatch’s plus an optionalsinks: [{node, op, key, value}](what a sink would do, latest per node), recorded from the start; rights aswatch; ttl 10 min, ≤ 2 per subject (a third ends the oldest), ≤ 16 per site (busy). Validation step 8: at most 1000 nodes per flow (deploy and validate too). ADR 0038 §5. No fixture change. - 0.2.17 (2026-11-08): 06 — parameter ports of the older node types (ADR 0032 §2 style: config or default first, the last good sample wins):
scalein.k,in.b;alarmin.high,in.low,in.hysteresis,in.delay_s,in.return_delay_s;delayin.ms;windowin.size_s;deadbandin.abs,in.pct;timerin.period_ms, allnumber; a sample that is not a finite number in the parameter’s bounds is ignored; a new period or delay takes effect at once.node_typeslists them ininputsand asparams[].port(ADR 0038 §5a). No fixture change. - 0.2.18 (2026-11-08): 06 — the engine keeps the last sample of every input and output of a deployed flow from the start, watched or not (one slot per port), so
watch’s snapshot andportsshow what variables sent once at deploy; the 5 s keep time after the last watch is gone (ADR 0038 §6). No fixture change. - 0.2.19 (2026-11-08): 06 — operand constants: a logic block’s config key
values: {<port>: <value>}(operand inputs only:in,in.<inputs>; not a parameter’s port, notstopwatch.reset, not the variables) gives an input its value until a sample replaces it; a constant calculates nothing, so a deploy never fires a command through one;watch/ports/previewshow it as the input’s value from the start;node_typesaddsvalues: trueper type (ADR 0038 §7). No fixture change. - 0.2.20 (2026-11-08): 06 — ports for the remaining block parameters:
concatin.strict,ifin.op(a known operator only),hubin.ignore_null,tracein.tracing,in.msg;node_typeslists them ininputsandparams[].port(ADR 0038 §5b). No fixture change. - 0.2.21 (2026-11-08): 06 — text operators,
round.textandcase:if.op!=,contains,starts_with,ends_with;round.min_precision(portin.min_precision) and outputtext; new blockcase(in,op,else, variable inputs in pairs of case and then, constants invalues; noregexp) (ADR 0038 §8). No fixture change. - 0.2.22 (2026-11-09): 06 — a key from a port inside a scope:
subscribeandlivelinessget the inputin.key, the outputerrorand the parameterkey_scope(a key expression inside this site’sdownstream,dataflowsorstorage; required whenin.keyis wired, validation step 4a; no default). The deployer’sauthreads all of the scope (a grant belowreadthat touches it refuses, a read grant on a part leaves the rest to later grants);watch,portsandpreviewask the same of their caller. At run time a value is taken only as one concrete node key (text, ≤ 512 bytes, segments[A-Za-z0-9_.-]+) inside the scope; a new key ends the old read first (outnull/uncertainuntil its first sample), a refused value reads nothing and gives a text onerror,nullreads nothing; changes ≥ 100 ms apart, the latest wins. Command targets keep no port.node_typesaddsparams[].scope(ADR 0040 §1). No fixture change. - 0.2.23 (2026-11-09): 06 — the action block:
invoke.argskeys are fields with portsarg.<name>(constant, then the last sample; ≤ 64);invokeandsetgetinterval_ms(0 or 100 … 86 400 000; first run one full period after the start),auto_run(invokefalse: a changed argument runs it;settrue: today’s write onin),enabled, the inputtrigger(an event, or a value that differs from the last one) and the outputssent,ok,error({event, id, code, message}),running,last_run,invokealsoresult(outkept). A sample born at the start (a variable’s orconst’s start value, a parameter echo’s start value, a clock’s first tick, the first sample of a read, and what a node sends while it handles one) never runs a command throughtriggerorauto_run.dataflows/<id>/~act/trigger {node}(levelwrite; the caller’sauthholdsmax(maxperm, write)on the block’s target, as the deployer’s proof; a running flow only).run_on_start(bool, default false, no port; owner decision 2026-11-09: one action block whose fields set its behaviour, no block type per behaviour): true runs the block exactly once at each start of the flow, 250 ms after the node started, the one sanctioned exception to the start rule. In a preview the command blocks reportsentand never an answer.node_typesaddsdyn_inputs.keysandtrigger(ADR 0040 §2). No fixture change. - 0.2.24 (2026-11-09): 06 — custom blocks:
~def.blocks: {<name>: {description?, inputs: [{name, to, default?}], outputs: [{name, from}], nodes, edges, layout?}}and a node of typeblock:<name>withvalues: {<input>: <value>}. The compiler replaces an instance by the block’s nodes (<instance>/<inner>), rewires the edges and puts an input’s constant where the inner input keeps one; nesting ≤ 4, ≤ 64 blocks, ≤ 64 instances inside one block, a block that contains itself is refused before expansion; the 1000 nodes count every expanded node and every instance, and a flow has at most 4000 edges with its blocks expanded (step 8), both charged while the definition is expanded; validation step 7a (apublishinside a block: one use).watch/ports/previewshow the inner nodes under their ids, andnodestakes an instance id. Library ondataflows:put_block {name, def}andremove_block {name}(config),get_block {name}→{name, version, def, requires}andlist_blocks(read); a flow copies a block into its definition, the engine never reads the library at compile (ADR 0040 §3). No fixture change. - 0.2.25 (2026-11-10): 06 — the second set of blocks: readers
load_value(key/in.key/key_scope) andlist_children(path/in.path/path_scope; rows{name, path, type?, display?, is?, unit?, writable, has_children}, ≤ 1000) withtrigger,interval_ms,auto_run(default true: at the start and on a new key),enabledand outputsout,ok,error,running,last_run, checked as sources; textsubstring,replace,split,join; datamake_object,make_array,get,stats; events and statechanged,rising_edge,falling_edge,counter,toggle,sample_and_hold,select; timedebounce,throttle. A port for every parameter; the event blocks never act on a sample born at the start.node_typeslists 55 types (ADR 0040 §4). No fixture change. - 0.2.26 (2026-11-10): 06 — a
layoutkey is a node id or an editor key<node>~<name>~<rest>(~cannot occur in a node id; the Studio editor keeps pin choices as<node>~pin~<field>: [1|0, 0]); values stay two finite numbers; the engine ignores editor keys and does not ask the node to exist; bounds (new):layout≤ 16 384 entries, a key ≤ 256 bytes (decided under ADR 0029). No fixture change. - 0.2.27 (2026-11-10): 06 —
list_childrenis read with its children: deploy,watch,portsandpreviewask read on<path>/*and<path_scope>/*too (one denied child refuses it). A float that is not finite is no number for a block, from a port or from the config; such a sample on a parameter’s port is ignored (security review, ADR 0040 §4). No fixture change. - 0.2.28 (2026-11-11): 02 — names people read (ADR 0042):
attr.display/ key 12 is the node’s optional human name, never part of a path; the driver framework takes it as the optionaldisplayofadd_*andediton connections, devices and points (the keydisplayis reserved there). A responder SDK fills a missing action or param-metadisplayfrom the key by one rule (wyrm_core::display::humanize: sentence case, acronym list, a unit token in brackets); a client may derive one from the key for older responders. Explicitdisplaytexts are in sentence case. Fixturemeta_action_ui("Add Device"→"Add device"). - 0.2.29 (2026-11-11): 06 — the third set of blocks (ADR 0044): math
constant,factorial,log,power,root,bound,round_up,round_down,format_number,parse_number; trigonometry in degreessin,cos,tan,cot,asin,acos,atan,to_degrees,to_radians; statisticsaverage,median,mode,std_deviation,variance; text and codecsleft,right,trim,base64_encode,base64_decode,url_encode,url_decode,to_camel_case,from_camel_case,hash,json_parse,json_stringify;substring.end,replace.regexpandcaseoperatorregexp(bounded patterns; an older config gives the same output); date and timenow,date_time,date_format,date_parse,date_math,date_range(dates in microseconds,time_zoneIANA/UTC/±HH:MM, defaultUTC;week_start;previousNis the period beforecurrentN); readersload_history(a table{t, v, q},truncatedinok) andget_node(summary and actions), every reader runs on~act/triggerwith a read check on its key and scope (trigger: trueinnode_types); the table value{columns, rows}with its bounds; logicrouter(outputsout.<case>andelse;node_typesgives them asdyn_outputswith prefixout.),event_gate,catch_error; tablestable,table_recorder,table_from_csv,table_to_csv,table_from_json,table_to_json,table_map_columns,table_sort,table_filter,table_remove_rows,table_edit_rows,table_group_by,table_join,table_page,table_rollup,table_aggregate,table_select_rows,table_select_columns,table_columns,table_row_cells,table_add_row,table_transpose,table_from_map(per-row rhai overrow,index, checked at compile step 6).~act/triggerasksmax(maxperm, write)on the target of every command block downstream of the node it runs.node_typesaddsparams[].display. No fixture change. - 0.2.30 (2026-11-11): 06 — what calculates at start: a pure logic block (math, trigonometry, statistics,
not,if,case,select, text, codecs,make_object,make_array,get,stats, the date blocks butnow, the table blocks buttable_pageandtable_recorder; 83 types) with no edge into any of its ports calculates once at start from its constants and parameters; a block with a wired input waits for its first sample as before. What it sends is made of constants, a mark the runtime carries on as it carries “born at the start”: such a sample runs no command, not even throughinofset/invoke(a variable’s start value still does).nowgetsinterval_ms(port, default 1000, 0 = only onin, else 100 … 86 400 000): the time at start (made of constants), then every period as ordinary samples, and on each sample ofin; itsintakes no constant (values: truedropped from its catalog entry; a storedvaluesis read and ignored). Anowstored before 0.2.30 has nointerval_msand so also sends every second after the upgrade;interval_ms: 0keeps the old behaviour. Thelivelinesscatalog entry gets its ownkeydescription (a node whose presence is read). No fixture change (no wire format change). - 0.2.31 (2026-11-12): 06 — flow metrics:
~valgets the text keystats{nodes, edges, samples_in, samples_out, dropped, restarts, commands: {sent, ok, error}, last_sample_t?}(additive; old readers ignore it).samples_in= samples a node takes from an edge or from its own source (answers, read requests and triggers are not samples);samples_out= samples sent on a wired output;dropped= inbox drops ofpolicy.overflow;commands= thesent/ok/errorevents ofinvoke/set. Counters reset at each deploy (so at every engine start and ACL rebuild),startandreload, and are kept across a restart after a panic (restarts+ 1) and while stopped. A refused draft’sstate: 2anderrorstay in the later~vals until the next state change. A state change publishes~valat once as before; otherwise~valgoes out again only when the counters moved, at most once per period (wyrmd:metrics_interval_ms, at least 5 s) (ADR 0045). No fixture change. - 0.2.32 (2026-11-13): 04 — the “no details in
err” rule covers the token check and the level check of the request; a refusal the responder gives after them by its own rule (a key outside a link’s grants or its author’s rights, an action that writes outside the node granted) says why inerr. The responder logs the reason of every refusal. No fixture change. 06 —permissions.maxpermis a code or a name ("write"), as the engine already read it; its refusal names both (2 (read) < 3 (write)). No fixture change. - 0.2.33 (2026-11-13): 01, 05 —
~act/<a>?check: the responder checks a call as the action would take it (token, level, arguments against the meta, its driver’s own parsing) and does nothing; the answer isokor the refusal the action would give; the audit recordscheck. A responder that answers it hasattr.check = trueon its root~meta; a requester sends?checkonly there (an older responder would run the action). A WASM component of world 0.3.0 checks against the meta only (ADR 0047). No fixture change. - 0.2.34 (2026-11-14): 06 — the 100 ms of a table’s per-row scripts are CPU time of the thread that runs them; time the host keeps that thread off a core does not count, and the wall clock counts only where the platform has no thread CPU clock. No fixture change.
- 0.2.35 (2026-11-15): 01 — a
~valselector withhistoryorsincenames each ofhistory|since(not both),agg,window,limitat most once and no other parameter; names that start with_are Zenoh’s and are not read; a duplicate or another parameter isinvalid_parameter(typing audit 2026-11-15: afromtext could add its ownlimitto the gateway’s selector, and the historian took the first). A requester makes the selector from parsed values only. No fixture change. - 0.2.36 (2026-11-20): 04 — a
ptokis at most 65 536 bytes; a responder refuses a longer one (permission_denied) before it checks the signature, and a minter makes none (security audit of PR #150: the cost of a refused token grows with its length times the number of trusted keys). The wire format does not change. No fixture change.