Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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.

Links connect devices and services to the broker. This table comes from links/official.json.

LinkCategorySummaryForms
ModbusEquipmentModbus TCP, RTU over TCP and serial RTU devices, as a master or as a slavebuiltin, process
OPC UA clientEquipmentNodes of OPC UA servers as points: batched reads, typed writes, browsebuiltin, process
BACnet/IPEquipmentBACnet/IP devices: Who-Is discovery, batched reads, writes with priorities, BBMDbuiltin, process
Siemens S7EquipmentS7-300/400/1200/1500 PLCs over S7comm (ISO-on-TCP)builtin, process
SNMPEquipmentSNMP v2c and v3 agents: batched GET, table columns, SET, walkbuiltin, process
MQTTEquipmentMQTT topics as points (JSON, raw, Sparkplug B)builtin, process
HTTP / RESTEquipmentJSON APIs polled on a schedule, JSONPath selectors as points, JSON writesbuiltin, process
PrometheusEquipmentPrometheus and OpenMetrics endpoints scraped into pointsbuiltin, process
S3 and compatiblesFile storesA bucket of AWS S3, MinIO, R2, Wasabi, B2 or GCS as a tree of folders and filesbuiltin, process
Google DriveFile storesA Google Drive folder or shared drive as a tree of folders and filesbuiltin, process
WebDAVFile storesA folder of Nextcloud, ownCloud or another WebDAV server as a treebuiltin, process
Local folderFile storesA directory of the host (disk, USB/SD card, network mount) as a treebuiltin, process
PostgreSQL / TimescaleDBHistory syncSends the historian’s journal to PostgreSQL or TimescaleDBprocess, wasm
MySQL / MariaDBHistory syncSends the historian’s journal to MySQL or MariaDBprocess, wasm
MongoDBHistory syncSends the historian’s journal to MongoDBprocess, wasm
InfluxDB 2.x / 3.xHistory syncSends the historian’s journal to InfluxDBprocess, wasm
DynamoDBHistory syncSends the historian’s journal to Amazon DynamoDBprocess, wasm
SchedulerAppsWeekly schedules and special days that write values to pointsprocess, wasm
AlarmsAppsAlarm classes on points, records, acknowledgement and exportprocess, wasm
DQL queriesAppsStanding and ad-hoc queries over the tree, as tablesprocess, wasm
Platform upstreamsAppsLive values to MQTT/UNS, Sparkplug B, ThingsBoard, Azure IoT Hub, AWS IoT Coreprocess, wasm
TelegramMessagingTelegram bots: templates, recipients, paired chat usersprocess, wasm
SlackMessagingSlack bots: templates and recipients, send onlyprocess, wasm
Assistant agentAppsAn AI agent that plans changes for a person to approvebuiltin
Mock deviceTestSimulated devices on the driver framework, for trials and testsbuiltin, process

Latest architecture decisions

All decisions: architecture decisions.

Latest specification changes

  • 0.2.36 (2026-11-20): 04 — a ptok is 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 ~val selector with history or since names each of history | since (not both), agg, window, limit at most once and no other parameter; names that start with _ are Zenoh’s and are not read; a duplicate or another parameter is invalid_parameter (typing audit 2026-11-15: a from text could add its own limit to 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 is ok or the refusal the action would give; the audit records check. A responder that answers it has attr.check = true on its root ~meta; a requester sends ?check only 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 in err. The responder logs the reason of every refusal. No fixture change. 06 — permissions.maxperm is 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: ~val gets the text key stats {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 of policy.overflow; commands = the sent/ok/error events of invoke/set. Counters reset at each deploy (so at every engine start and ACL rebuild), start and reload, and are kept across a restart after a panic (restarts + 1) and while stopped. A refused draft’s state: 2 and error stay in the later ~vals until the next state change. A state change publishes ~val at once as before; otherwise ~val goes 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

ci

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 live list, subscribe, set and invoke. 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 every set and invoke (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 .wasm file (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 /mcp on the gateway (claude, mcp). The wyrm-agent CLI runs checked plans, and the agent link runs only plans a person approves (agent).
  • SDKs: Rust (wyrm-client, wyrm-link-sdk, portable links on wyrm-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, get and subscribe on 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
  1. 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.
  2. Log in to a site’s gateway with user admin and password wyrm-demo-1 (or $WYRM_GATEWAY_ADMIN_PASSWORD). The gateways are central http://127.0.0.1:8445, edge :8444 and plant :8446.
  3. 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
  1. Put the printed key into admin_keys in examples/wyrmd.json5.
  2. Start the Modbus simulator, which the example’s plc1 link talks to:
    cargo run -p wyrm-link-modbus --features bin --bin wyrm-modbus-sim &
    
  3. Start the broker:
    target/release/wyrmd -c examples/wyrmd.json5
    
  4. 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:

  1. Uncomment the gateway line in the config.
  2. Start wyrmd once with WYRM_GATEWAY_ADMIN_PASSWORD set. 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

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

PathWhat
crates/wyrmdthe broker binary
crates/wyrm-corewire types, canonical CBOR codec, key-space helpers
crates/wyrm-link-sdkthe link SDK and the driver framework (connection → device → point; ADR 0004)
crates/wyrm-client, crates/wyrm-gateway-clientclients of the tree and of the user gateway
crates/wyrm-admin, wyrm-state, wyrm-gatewaycontrol plane, WAL state, user gateway
crates/wyrm-flow, wyrm-wasm-hostdataflow engine and WebAssembly host
crates/wyrm-history, wyrm-history-sync, wyrm-storage, wyrm-schedule, wyrm-dql, wyrm-messenger, wyrm-filestorethe cores of the historian, the sync links, storage, schedules, DQL, messengers and file stores
crates/wyrm-link-api, wyrm-link-portable, wyrm-link-guestportable links that run natively or as WASM components
crates/wyrm-ffiC 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-mcpthe 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: update spec/fixtures/gen.py, regenerate the 28 fixtures, make every SDK’s fixture test pass, and add a line to spec/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

Apache-2.0

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

GuideRead it when you want to
broker.mdlook 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.mdinstall 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.mdrecord points, read their history, keep broker storage (storage)
scheduler.mdswitch equipment on a weekly schedule, with special days and overrides
dql.mdcollect values from many points into one table, or write them on to a target
alarm.mdraise alarms from points (range, boolean, staleness, quality), acknowledge them, send the records to a central database
uplink.mdsend live values to an MQTT broker (UNS), a Sparkplug B host, ThingsBoard, Azure IoT Hub or AWS IoT Core
messenger.mdsend 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/dockerrun the broker and links in minimal scratch containers; image sizes and memory
filestores.mdconnect S3, Google Drive, WebDAV or a local directory and move files
claude.mdconnect Claude Desktop to the broker network as a gateway user (one-file extension, no API key)
mcp.mdlet an AI assistant read the tree and propose changes for a person to approve
agent.mdwork on the broker network from the command line (wyrm-agent), or run the AI agent link
flow-blocks.mdcalculate in a dataflow with its 125 blocks; start from a ready-made flow in examples/flows
operations.mdrun wyrmd under systemd or a container, know what a restart recovers and how fast, back up and restore data_dir
studio.mdbuild WYRM Studio, the Flutter app: layout, rules, the frx commands of each phase, every screen’s broker calls
GuideDevices or services
modbus.mdModbus TCP and RTU, as a master or as a slave
bacnet.mdBACnet/IP devices
opcua.mdOPC UA servers
s7.mdSiemens S7 PLCs
snmp.mdSNMP v2c and v3 agents
http.mdHTTP/REST services that answer JSON
prometheus.mdPrometheus 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.md is the typing audit of 2026-11-15, with the status and order of work of each finding.
  • security/threats.md lists the threats and what answers each one.
  • backlog.md lists 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.

NodeActions / value
sysvalues 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/linksInstall 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/upstreambrokers 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/enrollopen 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_deniedrouter access-control drops (with the other broker status values: uptime, links, sessions, CPU, memory, disk)
sys/historyembedded 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/brokerliveliness 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:

  1. at once with a token from its sys/tokens ▸ Add Token, when edge relays no sites;
  2. at once with sys/allow_all_links on, when edge relays no sites;
  3. else edge waits in sys/quarantine/edge (kind: broker): compare its key with edge’s sys/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

WhatWhereHow longWho reads it
The last value of every point (wy/**/~val)Zenoh storage, memory volume, in RAMuntil the broker stopsevery subscribe (the stored value first, then live), get ~val
History of the points you watchdata_dir/history, one file per UTC dayuntil retention_days or auto_purge deletes the daysys/history/<group>/<watch> ▸ Get History
Control-plane state (links, ACL, flows, settings)data_dir/state (WAL + snapshot)alwaysthe 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:

TypeType it asExample
numbera number; a unit after it is ignored21.5
boolchoose true or false
stringtextnorth wing
mapa JSON object{"mode": "eco", "limit": 40}
arraya JSON array[1, 2, 3]
binaryhex bytes, 0x before them is optional0x0a1b
dynamicJSON, 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.

  1. ▸ Add Watch Group: Name, Logging Type, Interval, Buffer Flush Time.
  2. Open the group ▸ Add Watch Path: Path. Write downstream/<link>/<point> (this site), or the full key wy/<site>/downstream/… (this site or a downstream site). Flow outputs (dataflows/<flow>/…) work too.
  3. The watch appears as w1, w2, … with the point key as its name.
  4. The point itself shows that it is recorded: its ~meta gets attr.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 TypeRecords
Nonenothing (the group is paused)
Intervalthe last value of each point every Interval seconds, changed or not
All Dataevery update
Point Changean 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 enabled pauses 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):

FieldMeaning
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/.
Intervalnone, or a number and s, m, h, d, w: 5m, 1h, 1d. One row per interval, starting at from.
Rolluphow 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.
Rowsat 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) and value. Rollups skip bad samples; 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):

WhereHow
Explorerthe 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)
Zenohget 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])
RustWyrmClient::history(node, &HistoryQuery::from_text(from, to, agg, window, limit)?); HistoryQuery holds parsed values (TimeUs, Rollup, Window, NonZeroUsize)
Dartapi.history(key, from: …, to: …, agg: …, window: …) (gateway and FFI)
CLIwyr values wy/<site>/downstream/mock/g0/p0 --from 2026-10-22 --agg avg --window 1h
Gateway WSop history, args {from, to, agg, window, limit}; needs read on the point
  • Parameters: history=<from>..<to> (an empty end is now) or since=<from>; agg and window as Rollup and Interval above; limit rows (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 is invalid_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.

SettingDefaultEffect
auto_purgeonEvery minute: while the disk has less free space than disk_space_remaining, delete the oldest day.
disk_space_remaining1024 MiBThe free space auto_purge keeps.
retention_days0 (keep)Every minute: delete days older than this.
keep_after_sync_days90With 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_days and auto_purge never wait for a sink: the equipment keeps recording while the cloud may be down. Rows a sink had not confirmed are counted in its rows_dropped_unsent.
  • ▸ Purge {Timerange} on sys/history deletes 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

WhatLimit
Watch groups64
Watches10 000 in all, one point each (no wildcards), never sys
Rows in memory200 000 for all groups; more are dropped (Rows Dropped)
Sample timethe source’s time; more than 5 min ahead of the broker’s clock or more than 31 days back: dropped (Rows Dropped)
Get History10 000 rows per call (~val?history=: 100 000)
One readat 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 rebuildabout a second: samples then are not recorded
Sinks16; 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.

  1. Install the link that sends the rows.
  2. On sys/history/sinks ▸ Add Sink {Name, Link, Groups, From}: the watch groups it takes, comma separated (empty: all); From start sends everything on disk, now only 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.
  3. 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 with after = next. That after confirms 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.

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:

  1. 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’s net list (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 world wyrm:app@0.3.0 (every wyr link pack since 2026-11-01, ADR 0030); one built for 0.2.0 answers not_supported to TLS: rebuild it or use the process package.
  2. ▸ Set Password: the password or token, kept in the link’s sealed store (never a param: the registry keeps params in the clear).
  3. 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):

  1. The link writes that batch again one row at a time.
  2. It skips each row the database refuses alone, logs its key and time (never the value) at warn, and counts it in rows_refused; error names the reason.
  3. It confirms the batch, so the cursor moves past the skipped rows.
  4. When the very first rows since the link started are all refused, the link stops as failed instead: 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.

LinkParamsWrites
influxdburl (https://host[:port][/base]; http:// only to loopback unless insecure_plaintext), org, bucket, measurement (default wyrm), ca_pem, timeout_msv2 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

WordMeaning
ScheduleA value that changes with time: a default, a time zone, events and targets. Its value now is <s>/current.
DefaultThe value when no event is active.
EventA value for a time: a window (start < end) or a moment (start = end), once or with a recurrence.
WindowThe event’s value counts from start up to end; at end the next value takes over.
MomentThe 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.
Priority1 (highest) to 9; 0 = none, the lowest. Decides between events active at the same time (section 6).
Special dayA 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.
TransitionA change of the schedule’s state: its value or the occurrence it comes from. Each transition writes the targets.
TargetA 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.

ModeWhereHow you get it
Embedded (the default)wy/<site>/downstream/schedulerEvery wyrmd runs it. wyrmd.json5 scheduler: { enabled: true, store_mb: 64 } (both optional) turns it off or sizes its store (1–64 MiB).
WASM packagewy/<site>/downstream/<id>Package scheduler (a component), Install Link ▸ from Repository / Zip / Url. Store 16 MiB (capabilities).
Process packagewy/<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 scheduler belongs to the embedded instance. A new link cannot take it, and wyrmd refuses to start with a stored link of that id (as with storage). The embedded scheduler is not in sys/links.
  • Default zone. The param default_tz (an IANA name, default UTC) is the zone of a schedule added without tz and of a DSA import. The embedded scheduler takes the system zone (UTC when the system zone has no IANA name). A package uses its param: add default_tz to the link’s params, beside its capabilities, with the link’s update (sys/links/<id> or wyr update). An update replaces the params: give the others again, as sys/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 no component). Without store_mb the 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), wyrmd logs it at error and 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 write on 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_target fails with permission_denied (no message).

3. Make a schedule

In the explorer, open wy/<site>/downstream/scheduler.

  1. ▸ Add Schedule: Id lobby, Default false, Time Zone Europe/Kyiv (empty: default_tz).
  2. Open lobby ▸ Add Event: Value true, Start 2026-11-02T08:00, End 2026-11-02T17:00, Recurrence FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR. The result is the event’s id, e1.
  3. lobby ▸ Add Target: Point wy/<site>/downstream/modbus/line1/ahu1/fan, Confirm read_back. This needs config (section 10). The target writes the state now at once.
  4. lobby/current shows true from 08:00 to 17:00 on weekdays, else false. 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, end and UNTIL are local wall-clock times in the schedule’s zone: YYYY-MM-DDTHH:MM or YYYY-MM-DDTHH:MM:SS, no offset. Text with an offset or Z is 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:
CaseWhat 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 dayIt 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 yearThat occurrence is skipped, never rolled into the next month.
A window across midnight, the hour or the weekAllowed; every occurrence is the same window.
  • Instants in the tree and in get_events are 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).

PartValues
FREQHOURLY, DAILY, WEEKLY, MONTHLY, YEARLY (required)
INTERVAL1 to 1 000 (default 1)
COUNT1 to 10 000 occurrences, or
UNTILa local time: the last occurrence starts at or before it (not with COUNT)
BYDAYMO,TU,…,SU; with MONTHLY and YEARLY an ordinal in the month, 1 to 5 or -1 to -5: 1MO (first Monday), -1FR (last Friday)
BYMONTHDAY1 to 31, or -1 (the last day of the month)
BYMONTH1 to 12

How the BY… parts act:

FREQBYDAYBYMONTHDAYBYMONTH
HOURLY, DAILYfilter (no ordinals)filterfilter
WEEKLYthe days in each week (Monday first)filterfilter
MONTHLYthe days in each monththe days in each month; with BYDAY both must matchfilter
YEARLYthe days in each month of the yearthe days in each monththe months (default: the start’s month)

Examples:

RecurrenceOccurs
FREQ=DAILYevery day
FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FRweekdays
FREQ=WEEKLY;INTERVAL=2;BYDAY=SAevery second Saturday
FREQ=HOURLY;INTERVAL=3every 3 hours from the start
FREQ=MONTHLY;BYMONTHDAY=1,15,-1the 1st, the 15th and the last day of each month
FREQ=MONTHLY;BYDAY=-1FRthe last Friday of each month
FREQ=YEARLY;BYMONTH=12;BYMONTHDAY=25December 25
FREQ=DAILY;COUNT=10the next 10 days
FREQ=DAILY;UNTIL=2026-12-31T23:59every day up to the end of 2026
FREQ=DAILY;BYMONTH=6,7,8every 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:

  1. On a special day only special events count, for the whole local day.
  2. Among the active windows, the highest priority wins (1 > 2 > … > 9 > 0).
  3. On equal priority, the occurrence that started later wins.
  4. On an equal start, the lower event id wins (e2 before e10).
  5. 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):

PathValueAttributes
<s>folderdisplay, tz, source (default or the event id), next_time (RFC 3339 or null), next_value
<s>/currentthe schedule’s value now (read-only)
<s>/defaultwritable value; saved
<s>/enabledwritable bool; saved
<s>/events/<e>folderdisplay, 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_time and next_value are 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.
  • enabled off: the schedule shows its value but wakes and writes nothing. Turned on, it is a transition: every target is written.
  • Writing default changes 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.

NodeActionLevelParamsResult
rootadd_schedulewriteid (required), display, tz, default (required), enabled (default true)—
rootimportconfigjson (required), id, overwrite{id}
<s>add_eventwritevalue, start, end (required), display, recurrence, priority (default 0), special (default false){id} (e<n>)
<s>get_eventsreadtimerange (required), limit (1 000, at most 5 000)rows {start, end, event, value, priority, special}
<s>exportread—{json}
<s>editwritedisplay, tz, default—
<s>removewrite— (refused while it has targets: remove them first, at config)—
<s>add_targetconfigpoint, confirm (required), feedback, map, feedback_map, tolerance{id} (t<n>)
<s>/events/<e>editwritethe fields of add_event; absent or null keeps a field; an empty recurrence makes it once—
<s>/events/<e>removewrite——
<s>/targets/<t>editconfigthe fields of add_target; absent keeps a field—
<s>/targets/<t>enable, disable, removeconfig——
  • Ids. A schedule id is 1 to 64 of A-Z a-z 0-9 _ -. Event ids e<n> and target ids t<n> come from the link and are never used again in that schedule.
  • get_events timerange is <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 at from is in.
  • confirm is an enum: an action takes the index of the choice (0 read_back, 1 feedback, 2 ack; the explorer sends it); an import JSON takes the text.
  • map and feedback_map are JSON object text (or a map).
  • Edits that change the state now (an event added, edited or removed, a new default or tz) are a transition. An edit that leaves the state as it was writes nothing.

Errors (the status, then <field>: <rule>):

StatusWhen
invalid_parameterA 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_exhaustedA 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_foundNo such schedule, event or target.
busyimport, 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_supportedNo such action on that node.
permission_deniedThe 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:

ConfirmConfirmed when
read_backthe point’s value equals what was written
feedbackthe 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.
ackthe target link answers ok
  • Equal means: numbers within tolerance (default 1e-6, relative; absolute when the expected value is 0); true/false and 1/0 are equal; other values exactly.
  • A value with quality uncertain or bad (a device offline) confirms nothing, and the link forgets the key’s last value: a later ok does not confirm on a value from before it.
  • map keys 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 for true. 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 the ok. No matching value 10 s after the ok: 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. In ack mode 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 override and not ack. Targets that confirm on the same key share one.

The target node’s value is its state:

StateMeaning
pendingwaiting to write (in the queue, or waiting for a first sample at start)
writingwritten, waiting for the reply and the confirmation
confirmedthe point shows the value
retryingthe write failed; last_error says why, attempts counts
overridechanged by hand after it was confirmed
disabledthe 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 schedulerAllows
readsee the tree, get_events, export
writeschedules and events: add_schedule, add_event, edit, remove (a schedule without targets), default, enabled
configtargets 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):

  1. The scheduler keeps the caller’s own rights (the token’s auth, spec 04) with each target it adds, edits or imports.
  2. It refuses a target whose point the caller may not write, or whose feedback key the caller may not read (permission_denied, “outside the rights of the target’s author”).
  3. It checks the point again before every write.
  4. A token without auth (an old client, a flow) cannot define targets.
  5. The editor of a target becomes its author: created_by and the rights are the editor’s from then on.
  6. The export leaves the rights out. An import takes the importer’s.
  7. 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:

RoleCan
viewerread
operatormake and edit schedules and events, turn them on and off; not add targets
engineer, adminall, targets and import too
  • The agent link is capped at write: it edits schedules and events, it cannot add targets.
  • Users of an upstream site (ADR 0018) write at write on 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 under wy/<site>/downstream, only with the subject link: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, so add_target accepts such a point; its writes fail with permission_denied and the target stays retrying. Do not do that.
  • Removing a schedule. remove is at write, its targets are at config: a schedule with targets is refused until someone with config removes 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 targetAt 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; ackwritten
none, for another state, or past its valid_until; read_back/feedbackwaits 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 no valid_until and 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 confirmed and override; 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:

  • id names the new schedule; default: the export’s id (DSA: its name, when that is a valid id, else id is required).
  • A schedule with that id exists: refused, unless overwrite: true replaces 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_by becomes the importer.
  • Export and import round-trip: an import of an export gives the same rows in get_events. Remove targets to copy a schedule (each point has one writer).

DSA mapping:

DSAWYRM
namedisplay (and the id when id is not given)
valuedefault
—tz = the link’s default_tz; enabled = true
events[]events e1, e2, … in file order
events[].name, value, priority, specialdisplay, value, priority, special
timeRange.sDate + sTimestart (the date of sDate, the time of sTime)
timeRange.eTime − sTimethe window length: end = start + it; equal times = a moment
timeRange.freq 0once
timeRange.freq 1–5FREQ=HOURLY, DAILY, WEEKLY, MONTHLY, YEARLY, INTERVAL=1, UNTIL = the date of eDate with the time of sTime
times with Z or an offsetconverted to the zone; times without one are local

DSA has no targets: add them after the import.

13. Limits

WhatLimit
Events per schedule100
Targets per schedule20
Nodes of the link9 500 (6 per schedule, 1 per event, 1 per target): 1 000 schedules with 2 events and 1 target each fit
Subscriptions1 000 (one per confirm key)
Writes waiting for a reply50; the rest wait in the queue
COUNT10 000
INTERVAL1 to 1 000
Next transition366 days ahead; with none, evaluated again 365 days on
get_events5 000 rows (1 000 without limit)
Storeembedded 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
Requests50 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 × eventsstate_at p50next_transition p50
any × 10.21 µs0.62–0.67 µs
any × 105.5 µs11.6 µs
any × 10053.7 µs113 µs
  • The evaluator’s cold start (Compiled::new + state_at), 1 000 schedules × 10 events: p50 8.96 ms.
  • occurrences over a year, 10 events (7 198 rows): p50 0.83 ms.
  • The worst COUNT compile (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):

Confirmstart eventtree completelast write sentall confirmed
ack1.71 / 1.94 ms26.22 / 29.96 ms40.34 / 45.50 ms40.85 / 46.03 ms
read_back1.67 / 1.76 ms25.84 / 26.53 ms44.27 / 45.02 ms44.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):

MeasurementResult
Samples in 60 s at idle, 1 000 schedules0 (target 0); 3 000 stored values at subscribe
Making and removing the 1 000 schedules47.1 s and 42.8 s (50 requests per second per caller)
Transition latency, 100 moments, currentp50 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_statusconfirmed 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.
  • rustls is pinned to 0.23.45: zenoh-link-tls 1.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 edit cannot 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 feedback key may be another target’s point; only the written points are checked for one writer.
  • permission_denied has no message: a missing grant shows only the status.

16. Try it in the demo

  1. Run examples/demo/run.sh. Every site (central, edge, plant) has its embedded scheduler.
  2. Log in to the edge gateway (http://127.0.0.1:8444, user admin) and open wy/edge/downstream/scheduler. Make a schedule as in section 3 with the target modbus/line1/ahu1/fan, Confirm feedback, Feedback Point wy/edge/downstream/modbus/line1/ahu1/fan_status.
  3. Write false to fan by hand: the target turns override.
  4. wyr probe --gateway http://127.0.0.1:8444 --site edge scheduler runs the built-in scenario (links/probe/scenarios/scheduler.json).
  5. examples/demo/scheduler-load.sh runs the measurements of section 14 on edge and removes what it made (N=3 MOMENTS=5 IDLE_S=5 for 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

ModeWhatRights
Embedded (default)wy/<site>/downstream/dql in every wyrmdreads this site’s downstream, dataflows, storage, upstream and the readable sections of downstream sites; sinks write only this site’s downstream
WASM package dqlthe same link, installed from a repository or zipwhat an operator grants (sys/links/<id>/~act/grant): read on each root, write on each sink target
Process package dql-processthe same link as a processas the WASM package
wyr query "<text>"the same engine in the terminal, nothing storedyour own token

wyrmd.json5: dql: { enabled: true, store_mb: 16 } (both optional). The id dql is reserved.

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 after ttl_s (300 s, at most 3 600) unless get_table or run with the same text renews them. The same text shares one query. With id a dataflow can subscribe a fixed key: …/dql/<id>/table (with publish).
  • The table is read with get_table, which gives each caller the rows it may read itself. With publish: true (needs config) it is also the live value <id>/table, published at most every publish_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: collecting until every list it opened answered once, then ready (disabled, error when its text no longer parses);
  • lists, lists_pending, depth (deepest level reached), sites, collect_ms (start to ready);
  • error: why the table may be incomplete — max_rows, max_lists, a refused list, or incomplete: 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

CommandMeaning
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 map row (row["value.timestamp"]);
  • its meta: path, name, type, unit, writable, is, display, quality, attr (map), actions (list of names), and all of it as meta.

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 read is no row; a value they may not read is not taken.
  • A set or invoke whose target the author may not write is refused when it would fire: it counts in errors and error names the key.
  • An edit of the text, an import or a run takes 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 write grant listed after a wider read grant gives read only, at the gateway, at the target link and in a query alike (ADR 0031).
  • get_table gives 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 needs config. 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 config on the DQL link (the gateway’s engineer, admin); write (operator, the agent, dataflows) may define queries without sinks only. The same holds for changing a sink query: switching it on, edit, run with its id and another text, remove; write may switch it off (stop its writes).
  • Nothing fires on start: the first complete arguments of a row (after a start, a restart, an edit, enabled on, or when the row appears) are its baseline. A call goes out only when they change. A row whose arguments hold null sends nothing (unless invoke_allow_null).
  • One call in flight per row and sink; changes meanwhile wait and the newest goes next. throttle_ms spaces a row’s calls. At most 50 calls in flight for the link.
  • A failed call counts in errors and is logged at info (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]+$'), not name.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 null in 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:

DSAWYRM
list /downstream/System/*list wy/<site>/downstream/System/**
?*
list *list wy/<site>/downstream/**
list brokerslist 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

WordMeaning
ClassA group of watches and their records (line1, comms, safety), with its escalation times.
WatchA source point (or a subtree) and an algorithm that says when it is in alarm.
RecordOne 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.
ActiveThe record’s condition still holds (no normal yet).
OpenActive, or not yet acknowledged. Closed: normal and acknowledged.
Typealert, warning or fault (as DSA).
Inhibitto_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.
EscalationA record nobody acknowledged within escalation1_s is at level 1, within escalation2_s at level 2.
SinkA 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.

ModeWhereHow you get it
Embedded (the default)wy/<site>/downstream/alarmEvery wyrmd runs it. wyrmd.json5 alarm: { enabled: true, store_mb: 64, retention_days: 365, max_records: 100000 } (all optional).
WASM packagewy/<site>/downstream/<id>Package alarm (a component), Install Link ▸ from Repository / Zip / Url. Store 16 MiB.
Process packagewy/<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 alarm belongs to the embedded instance (as scheduler and dql): a new link cannot take it, and wyrmd refuses to start with a stored link of that id.
  • The embedded link reads this site’s downstream, dataflows and storage. 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 read on 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 shows error: permission_denied; Disable and Enable it once the grant is there.
  • Params of a package: retention_days (365, at most 3 650) and max_records (100 000, at most 1 000 000), beside the capabilities, with the link’s update.

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:

algorithmIn alarm while …Parameters
booleanthe 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_rangethe 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
stalenessno sample came for stale_s seconds. The next sample ends it.stale_s
qualitythe 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 under dataflows or storage), or a subtree wy/<site>/downstream/<link>/**: one subscription, one state per key, one record per key (at most 2 000 keys; beyond, the watch shows error). keys and in_alarm count 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_watch is config (it subscribes a point), and the watch keeps its author’s rights (ADR 0029): a token without auth (a dataflow’s) cannot add one; a source the author may not read is 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 new source takes 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 a boolean, out_of_range or quality watch judges nothing and makes no record (there is no value and no quality to judge). A staleness watch on a point counts from the start, and its record, before the first sample as after a later silence, has value null and quality bad ({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 is null / bad too. The watch’s own value (watches/<w>) is the state of the watch, not of its source: normal means “no record and no wait”, so a watch whose key has sent nothing yet is normal. A key that may go silent needs a staleness watch.

5. Records

  • raise {class, source, type?, message?} makes a record no watch owns: a dataflow’s invoke sink, the agent or a person says there is a problem with source (a key of this site). normal {id} ends it; a watch’s record ends by its point. raise needs write on the link and no auth.
  • 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_note and ack_all need the caller’s auth (the gateway, wyr and the agent give it) and answer only records whose source the caller may read. A class’s alarms table and the counts are for whoever may read those nodes: a role with read on the alarm link reads the site’s alarms.
  • get_alarms: state is open (default), active, unacked, closed or all; 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; closed and all read the store, at most 256 pages (16 384 records) per call: complete: false and scanned_to (the oldest creation time read) say where to go on with a narrower timerange.
  • Escalation: a record nobody acknowledged within the class’s escalation1_s goes to level 1 (escalation), within escalation2_s to 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_days or the store holds more than max_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 staleness watch 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"}'.

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

ModeWhatRights and network
Embedded (default)wy/<site>/downstream/uplink in every wyrmdreads this site’s downstream, dataflows, storage and the readable sections of downstream sites; network from uplink.net
WASM package uplinkthe same link, installed from a repository or zipwhat 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-processthe same link as a processas 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.

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
  • failed means the platform refused the credentials (or a secret is missing): nothing is tried again until Edit, Set Password or Enable. waiting means a network error: the link connects again after a back-off (1 s, ×2, up to retry_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

FieldMeaning
nameone key segment: the upstream’s node
urlmqtt://host:1883, mqtts://host:8883 (Azure: made from hub when empty; AWS: https://<endpoint>:8443)
selectfull 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_hzat most this many values per point per second, the latest kept while over; 0 = every change
queue_maxvalues held while the platform is slower than the site (10 000; up to 100 000); the oldest go, counted in dropped
flush_mshow often queued values are sent (250)
ca_pemtrust only this CA (TLS)
timeout_ms, retry_sa connect or request; the longest wait between attempts
insecure_plaintextsend 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, wyr and wyrm-agent give it); a select key the caller may not read is refused; under a selected root, points the author may not read never go up. An Edit takes the editor’s rights. Entries of wyrmd.json5 send what they select (the operator wrote them). An upstream kept without rights (made before 2026-11-05) is failed until an Edit.
  • The secret stays with its endpoint. An Edit that changes the host, the port, TLS, insecure_plaintext or ca_pem deletes 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

  1. A block keeps the last sample of each input port.
  2. 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.
  3. Blocks with variable inputs take the config list inputs (default ["0", "1"], at most 64 names [A-Za-z0-9_]+). Each name is a port in.<name>. A name may not be a parameter’s name.
  4. Any sample on an input calculates the block.
  5. An operand input (in, in.<name>) can hold a constant: the config key values: {"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, reset and the variables take no constant (a parameter’s config is its constant). now takes none either: its in is only a trigger (spec 06 0.2.30). When a block calculates from its constants alone, see “What calculates at start”.
  6. An output is sent only when its value or its quality changed. Events (on_change, on_loop) are always sent: {event: <port>, id: <n>}.
  7. 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):

  1. The variables (number, string, bool, table) and constant send their value at start, as const does.
  2. 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 reset count.
  3. 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.
  4. now gives the time at start when its interval_ms is above 0 (see “Date and time”).
  5. 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:

SectionTypes
Mathadd, subtract, multiply, divide, max, min, abs, round, modulo, stats, factorial, log, power, root, bound, round_up, round_down
Trigonometrysin, cos, tan, cot, asin, acos, atan, to_degrees, to_radians
Statisticsaverage, median, mode, std_deviation, variance
Logicnot, if, case, select
Textconcat, length, substring, replace, split, join, format_number, parse_number, left, right, trim
Codecsbase64_encode, base64_decode, url_encode, url_decode, to_camel_case, from_camel_case, hash, json_parse, json_stringify
Datamake_object, make_array, get
Date and timedate_time, date_format, date_parse, date_math, date_range
Tablestable_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, round to 0 places and modulo’s quotient. On an overflow the result is a float.
  • divide always 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). true is 1 and false is 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 or 0, else true. null is false. A list or a map is true.

The blocks

Parameter names are snake_case, as every other node type’s.

Variables

TypeInputsOutputsParameters
numberinoutvalue (default 0)
stringinoutvalue (default empty)
boolinoutvalue (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

TypeInputsOutputsWhat it gives
addin.<inputs>outThe sum; no number at all gives 0.
subtractin.<inputs>outThe first minus the others; no number gives null.
multiplyin.<inputs>outThe product; no number gives null.
dividein.<inputs>outThe first divided by the others, as a float.
max, minin.<inputs>outThe largest or the smallest number.
absinoutThe absolute value.
roundin, in.precision, in.min_precisionout, textRounded 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).
moduloin, in.moduloquotient, remainderThe quotient as a whole number toward 0, and a remainder that is never negative (-7 by 3: -2 and 2). By 0: both null.
scalein, in.input_min, in.input_max, in.output_min, in.output_maxout, input_out_of_rangeSee 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

TypeInputsOutputsParameters
notinout—
ifin.op, in.then, in.else, in.<inputs>outop, then (default true), else (default false), inputs
hubin.ignore_null, in.<inputs>out, index, on_changeignore_null (default true), inputs
stopwatchreset, in.enabled, in.interval, in.step, in.modulo, in.loop, in.reset_valueout, on_loopthe same names
tracein.tracing, in.msg, in.<inputs>—tracing (default true), msg (default trace), inputs
casein, in.op, in.else, in.<inputs> (pairs)outop (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" and 5);
  • 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 (a null other 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:

  1. Every interval seconds (at least 0.05; its clock ticks every 50 ms) it adds step to the count and sends it on out.
  2. With modulo above 0, a count that reaches modulo starts again from the remainder and sends an event on on_loop. With loop false it stops at modulo and switches itself off until enabled comes again.
  3. Any sample on reset sets the count to reset_value and sends it at once.
  4. 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

TypeInputsOutputsWhat it gives
concatin.strict, in.<inputs>outThe 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.
lengthinoutThe 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>.

TypeInputsOutputsParameters and what it gives
substringinoutstart (default 0), length (default: to the end), counted in characters.
replaceinoutfrom, to: every from in the text becomes to. Plain text, no pattern. An empty from replaces nothing.
splitinoutseparator (default ,): a list of texts, at most 1000. An empty separator gives one item.
joinin (a list)outseparator (default ,): the items as one text.
make_objectin.<inputs>outA map: each input’s name is a key. Use it for a map argument of an action.
make_arrayin.<inputs>outA list of the inputs, in their order.
getinoutpath (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.
statsin (a list)min, max, avg, sum, countThe numbers of the list. An empty list gives count 0 and null for the others.
changedinon_changeAn event when in differs from the sample before. The first sample only starts it.
rising_edgeinon_edgeAn event when in becomes true. Nothing before counts as false.
falling_edgeinon_edgeAn event when in becomes false after it was true.
counterin, resetoutstep (default 1), initial (default 0): each sample on in adds step; a true reset goes back to initial.
togglein, resetoutinitial (default false): each sample on in flips the bool.
sample_and_holdin, triggeroutThe value in has when a sample comes on trigger.
selectin.<inputs>outindex (default 0): the input at that position, from 0; null when there is none.
debounceinoutms (default 500): the last value, once ms passed without another.
throttleinoutms (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 split of more than 1000 parts, is null with quality bad.
  • changed, rising_edge, falling_edge, counter, toggle and sample_and_hold do not act on a value that exists because the flow started (a variable’s start value, the first sample of a subscribe). Such a value only gives the block where it starts from. So these blocks are safe in front of a trigger.
  • counter and toggle keep 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.
  • debounce and throttle send their value at most a quarter of ms late (5 to 50 ms).

Readers:

TypeInputsOutputsParameters
load_valuetrigger, in.key, in.interval_ms, in.auto_run, in.enabledout, ok, error, running, last_runkey, key_scope, interval_ms (default 0), auto_run (default true), enabled (default true)
list_childrentrigger, in.path, in.interval_ms, in.auto_run, in.enabledout, ok, error, running, last_runpath, path_scope, interval_ms, auto_run, enabled
  • load_value reads the stored value of a point once. out carries it with its quality and time. A point without a stored value gives error with not_found.
  • list_children gives a list of rows, one per child: {name, path, type, display, is, unit, writable, has_children} (type, display, is and unit only 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_run reads at the start and when the key changes. A read is no command, so it may run at deploy. trigger reads on an event or a changed value; interval_ms reads every period.
  • key and path take another key on their port inside key_scope or path_scope, as subscribe does (see “A key from a port”). A refused key is an error event with invalid_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

TypeInputsOutputsParameters and what it gives
constant—outname (default pi; e, sqrt2, ln2, ln10, log2e, log10e). Sent at start, as a variable.
factorialinoutn! of the whole part of in. Below 1: 1. An integer up to 20!, a float up to 170!, above that null.
loginoutbase (default 10). in at most 0: null.
powerinoutexponent (default 2). An integer stays an integer while it fits.
rootinoutdegree (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).
boundininput_out_of_range, outmin, max (none: that side is open). max applies first, then min, so min wins when it is above max.
round_up, round_downinout, textprecision (0…20, default 0). text has exactly precision places.
format_numberinoutformat (default #,##0.###), decimal_separator (default .), group_separator (default ,).
parse_numberinoutThe 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:

  • 0 is a digit that is always shown; # a digit shown only when it is not a leading or a trailing zero. 0.5 with #.## is .5, with 0.00 0.50.
  • A comma in the whole part sets the group size: the digits after the last comma (#,##0 groups by 3).
  • % in the text around the number multiplies by 100: 0.0% gives 25.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_separator gives no groups. A pattern without # or 0 gives null.

Trigonometry (degrees)

TypeWhat it gives
sin, cos, tan, cotThe function of in degrees. cot 0 is null.
asin, acosThe angle in degrees; outside −1…1 null.
atanThe angle in degrees of the point (x, in); x defaults to 1, so it is the arc tangent of in.
to_degrees, to_radiansThe 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.

  • median of an even count is the mean of the two middle numbers.
  • variance and std_deviation are of the population (÷ n).
  • mode is 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

TypeInputsOutputsParameters and what it gives
left, rightinoutlength (default 0): the first or the last characters of in as text.
triminoutThe text without spaces at its start and end. null gives empty text.
base64_encodeinoutA text (as UTF-8) or bytes as Base64. Another value gives null.
base64_decodeinout, bytesBase64 (standard or URL alphabet, padding optional): out as text (UTF-8; a bad sequence is U+FFFD), bytes as bytes. No Base64: null.
url_encodeinoutA URL component: every byte but A–Z a–z 0–9 - _ . ! ~ * ' ( ) as %XX.
url_decodeinout+ is a space, %XX a byte, a bad or cut % stays as it is (100% → 100%).
to_camel_caseinoutHello World-foo → helloWorldFoo; abc 2nd → abc2Nd.
from_camel_caseinoutHelloWorld → hello world (each capital becomes a space and the small letter).
hashinoutalgorithm (sha256 default, sha1, md5): the digest of a text (as UTF-8) or of bytes in lower-case hex.
json_parseinout, parse_errorA JSON text as a value. A value that is no text passes as it is. No JSON: out null, parse_error true.
json_stringifyinoutpretty (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 null with quality bad. JSON texts (json_parse in, json_stringify out) are at most 256 KiB, a parsed value at most 32 levels deep.
  • md5 and sha1 are 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):

  • substring takes end: without length, the part ends before the character end; below 0 counts from the end (start 1, end -1 on [abc] gives abc). length wins over end. An overrun still clamps.
  • replace takes regexp (default false): from is then a pattern. to is taken as it is: $1 is no group.
  • case takes the operator regexp: in as 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.

TypeInputsOutputsParameters and what it gives
nowin, in.interval_msoutThe 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_timethe parameter portsoutyear (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_formatinoutformat (default yyyy-MM-dd'T'HH:mm:ss), time_zone (also auto: the offset written in the input text).
date_parseintime, year, month, day, hour, minute, second, millisecond, weekdaytime_zone. weekday 1 is Monday, 7 Sunday. A text that is no date gives null on every output.
date_mathinoutop (after default, before), year, month, day, hour, minute, second, millisecond, time_zone.
date_rangein, next, previousstart, end, this_range, next_range, previous_range, formatted, durationformat, 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:

TextRange
today, yesterdaythe day, from 00:00 to 23:59:59.999999
thisWeek, lastWeekseven days from week_start
thisMonth, lastMonth, thisYear, lastYearthe 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-29the 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).
  • start and end are microseconds, end inclusive. duration is end − start + 1. this_range is start/end as yyyy-MM-ddTHH:mm:ss in time_zone.
  • next_range and previous_range are the texts of the neighbours: today ↔ yesterday, thisX ↔ lastX, currentN ↔ previousN, the next and the previous year, month or day, an a/b range shifted by its length.
  • A sample on next or previous (not one born at the start) moves the block to that neighbour. A new value on in drops the move.
  • A named or a relative range is calculated again every second, so today rolls over at midnight and current1hours moves with the clock. A change goes out only when an output changed.

Logic and events

TypeInputsOutputsParameters and what it gives
routerin, condition, in.<inputs> (the cases)out.<inputs>, elseop (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_gatereset, in.<inputs>on_finish, orderlog_order (none default, first_occurrence, last_occurrence, all), inputs. An event once every input changed at least once since the last reset.
catch_errorin.<inputs>out, code, source, on_errorinputs. 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 in values.
  • single_output: true sets the output routed before back to null when the route changes. Without it each output keeps its last value.
  • router routes on any sample on in, condition or 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.
  • order lists the input names joined with commas; with all it keeps the last 1000 changes. order names 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

TypeInputsOutputsParameters
load_historytrigger, in.key, in.interval_ms, in.auto_run, in.enabled, in.time_range, in.rollup, in.window, in.limit, in.time_zoneout, ok, error, running, last_runkey, 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_nodetrigger, in.key, in.interval_ms, in.auto_run, in.enabledout, actions, ok, error, running, last_runkey, key_scope, interval_ms, auto_run (default true), enabled

load_history reads the historian (~val?history=, docs/history.md):

  • time_range is a range text as date_range reads it: today, lastWeek, current24hours, 2026-10, <a>/<b>. Wire date_range.this_range into in.time_range for a fixed or a named range a user moves with next and previous.
  • For a sliding range (current24hours), write the text itself into time_range and set interval_ms. this_range of a sliding range changes every second: wired into in.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) and rollup (avg, min, max, sum, count, first, last, delta, and, or) give one row per window.
  • out is a table (ADR 0044 §2) with the columns t (microseconds), v and q (the quality code; null for a rollup row).
  • limit is 1 … 10 000. An answer that reached the limit may have more rows: the ok event then carries truncated: true and rows. A table larger than 512 KiB is an error with resource_exhausted.
  • A changed query field (in.time_range, …) reads again when auto_run is true. A history read has 30 s to answer.

get_node reads a node’s ~meta:

  • out is its summary: {name, display, type, unit, enum, writable, is, has_children}.
  • actions is a table {name, display, group, level, params}; params is 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}]}
  • columns gives the order; each row is a map. A cell a row lacks is null.
  • Every table input also takes a list of maps, as list_children and load_history give 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 null with quality bad.
  • The parsers check their bounds while they read, not after: table_from_csv refuses (parse_error true) 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_json and json_parse read 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 in and 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 a table_recorder, or write it to broker storage with set.

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).

TypeInputsOutputsParameters and what it gives
tableinoutvalue: a table, sent at start as a variable.
table_recorderreset, in.<inputs>outenabled, 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_csvinout, parse_errorwith_header (default true), delimiter (default ,). Cells are texts.
table_to_csvinoutwith_header, delimiter.
table_from_jsoninout, parse_errorselector (data.items, a[0].b). A list of objects (nested keys as a/b), one object, or {columns, rows}.
table_to_jsoninoutpretty. The rows as JSON objects.
table_map_columnsinout, errorretain_columns, mapping: [{name, from}]; from is a column, = expr (a value), + expr (a number), & expr (a bool).
table_sortinoutcolumn, method (number, string, natural), order. No value sorts last either way; equal keys keep their order.
table_filterinout, errorexpr: the rows for which it is true.
table_remove_rowsinout, errorexpr: the rows for which it is false.
table_edit_rowsinout, errorexpr, cells ({<column>: <value>}): each matching row gets the cells.
table_group_byinoutcolumn, include_blank, nested (a column rows with each group’s table), aggregates.
table_joinin, rightoutcolumn, right_column (default: column), join (left, inner, right, full, exclude, union).
table_pagein, next, previous, first, lastout, current_page, total_pagespage_size (default 10; below 0: all), page (from 0).
table_rollupinouttime_column (default t), interval (default 1h), round_time (default true), method, aggregates, week_start, time_zone.
table_aggregateinoutcolumn, method. One value.
table_select_rowsinoutindexes: 0,2,5, a list or a number.
table_select_columnsinoutcolumns: name,zone or a list.
table_columnsinoutA table {name, type}; type is number, string, bool, map, list, bytes, mixed or null.
table_row_cellsinout, countrow: that row as a map; count: the rows. Wire get for one cell.
table_add_rowinoutrow: a map appended (a make_object gives one; a new key adds its column).
table_transposeinoutheader_column, include_headers, header_prefix (default c), ignore_columns.
table_from_mapinoutA 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:

  • interval is a number and a unit: s, m (minutes), h, d, w, M (months), y. The names fiveMinutes, oneHour, day, … are taken too.
  • round_time: true starts the buckets on round times in time_zone (15m: :00, :15, …; 1d: midnight; 1w: week_start); false starts 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 by method.
// 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.

TypeParameter ports
scalein.k, in.b (and the range ports in.input_min … in.output_max)
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
  • 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_ms at least 10, size_s above 0, ms, delay_s and return_delay_s at least 0), is ignored: the last good value stays.
  • The config rules stay: alarm still needs high or low in its config, deadband abs or pct. The config gives the start value.
  • A new period_ms, ms, size_s or alarm delay takes effect at once. The node’s clock starts again one period after the change. A sample that a delay already 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):

  1. 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, null and a missing field are not valid.
  2. A quality that is not valid is bad. It is never good.
  3. expression with quality: custom: the result must be a map {v, q}. The output is v with the quality of q (rule 2). A missing q, and a result that is not a map with v, give bad.
  4. A reader or a command whose answer failed gives the event error with an error code (spec 04 status group error, 0x20 and above). A code that is not valid, or that is not in the error group (ok, a progress or a closed code), is internal_error (0x25). A failure never reads as a success.
  5. A command passes a user-defined error code (0x40 … 0x4F) and an unknown error-group code in the event error as it is (CONTRIBUTING “Wire enums” rule 3). A reader gives internal_error for 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.

TypeInputsOutputsParameters
subscribein.keyout, errorkey (the start key; may be absent with a scope), key_scope
livelinessin.keyout, errorkey, key_scope
  1. Give the node key_scope, a key expression of the keys the port may name: downstream/modbus/line1/**. The compiler refuses an edge into in.key without it.
  2. Deploy. The deployer must read all of the scope. watch, ports and preview ask the same of their caller.
  3. 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 under sys and a value that is not a text are refused.
  • A new key ends the old read first. out is null with quality uncertain until the new key’s first sample.
  • A refused value reads nothing. error carries the reason as a text and goes back to null with the next good key.
  • null on 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.
  • liveliness sends 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).

TypeInputsOutputsParameters
invokein, trigger, in.interval_ms, in.auto_run, in.enabled, arg.<name>out, result, sent, ok, error, running, last_runpath, action, args, on, allow_bad, interval_ms (default 0), auto_run (default false), enabled (default true), run_on_start (default false)
setin, trigger, in.interval_ms, in.auto_run, in.enabledsent, ok, error, running, last_runpath, on, deadband, allow_bad, interval_ms (default 0), auto_run (default true), enabled (default true), run_on_start (default false)

Arguments of invoke:

  1. Each key of args is one argument. Its value is the argument’s constant: args: {setpoint: 21.5, mode: "auto"}.
  2. Each argument has the port arg.<name>. A sample there replaces the constant. Use null as the constant of an argument that only a wire gives.
  3. "$in" as a constant stands for the last value on in.

What runs a command:

Causeinvokeset
a sample on inevery sample that passes onthe value, when auto_run is true and it passes on/deadband
triggeran event, or a value that differs from the last onethe same: it writes the value that in holds
auto_runa sample on arg.<name> that changes the argumentsee in
interval_ms above 0every periodevery period: the held value again
the action dataflows/<id>/~act/trigger {node}one runone write of the held value
run_on_start: trueone run, 250 ms after each start of the flowone write of the value in got by then
  • enabled: false stops every cause.
  • interval_ms is 0 (off) or 100 … 86 400 000. A period is skipped while the run before it has not answered.
  • sent fires when the request leaves, ok when the target answered, error when it refused: {event: "error", id, code, message} with the status code of spec 04. running is true between the two. last_run is the time of the last sent in microseconds.
  • invoke.result is the last result. invoke.out stays: the result, or the error text with quality bad.

УВАГА: 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.
  • values gives an input its constant for this instance. A wire replaces it.
  • The compiler replaces the instance by the inner nodes m1/sum and m1/div. watch, ports and preview show 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, in of a variable.
  • A block with a publish inside can be used once in a flow.

The library keeps blocks for every flow of the site:

  1. Store a block: dataflows/~act/put_block {name, def} (level config).
  2. Read it: get_block {name} gives {name, version, def, requires}.
  3. Copy def and every block of requires into blocks of the flow.
  4. 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 p is an output p. It sends the parameter’s effective value: the config value or the default, replaced by the last sample on in.<p> where that port exists. It sends once when the node starts and then on every change. A stopwatch that stops at modulo sends enabled false.
  • An input x that is not a parameter’s port is an output x. It repeats every sample on x, before the node handles it.
  • The output has the field’s name: ["scale1.input_min", "add1.in.0"] reads the parameter input_min of scale1; ["if1.in.0", "show.in"] repeats the input in.0 of if1.
  • A declared output keeps its name. An input’s echo comes before a parameter’s: latch has the input reset and the parameter reset, so its parameter has no output.
  • Types: an input’s echo has the input’s type. A parameter’s echo is number, bool or map as the parameter, else any.
  • 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:

KeyWhat it counts
nodes, edgesthe size of the compiled flow, custom blocks expanded
samples_insamples the nodes took in from an edge or from their own source (subscribe, liveliness, const)
samples_outsamples the nodes sent on a wired output
droppedsamples the node queues dropped (policy.queue, policy.overflow)
restartsrestarts after a node panic
commands.sent, .ok, .errorthe events of the invoke and set blocks; error also counts a run refused as busy
last_sample_twhen a node last took in a sample (µs); absent before the first one

How to read them:

  • samples_in stands still while the flow runs: no source sends. Check the source keys and the links behind them.
  • dropped grows: a node is slower than its input. Make policy.queue bigger, or reduce the input with throttle, deadband or window.
  • commands.error grows: open a watch on the command block. Its error output 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 p of a block is the parameter p ∪ its input in.<p> ∪ its echo output p (ADR 0038 §1);
  • the main value of a variable block (number, string, bool, const: input in, parameter value, output out) is ONE field Value;
  • 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:

  1. A row reads a human label: the catalog’s display, else an override, else sentence case with a unit suffix in brackets. Numbered inputs in.0, in.1 read Input 1, Input 2. Names a user or a device gave (points, expression variables, wasm ports, invoke arguments) stay as given. The engine name is the row’s tooltip and stands under the label in the inspector.
  2. 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.
  3. Order: fixed operands, then the parameters, then the variable inputs, then the parameters drawn after them (tailParams: if then, else; concat strict; hub ignore null), then the results. A sink names what it writes before the value.
  4. 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 (deadband abs/pct, alarm high/low). Maps, lists and the list of variable inputs (inputs) are edited in the inspector only.
  5. In the inspector a parameter with choices is a dropdown, a bool a toggle, anything else a text field typed as the parameter’s type (a number, text, JSON).
  6. 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 bound mark in the inspector). The wire and the source row light when the pointer is over the field; the inspector’s link menu has Go to source and Unbind. A bound field with nothing known yet shows nothing, not the typed value the binding replaces.
  7. An operand of a type with catalog values: true holds a typed value: the node’s config values: {"<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.reset or a variable’s in. case reads its variable inputs as pairs: Case 1, Then 1, … A typed value is read as JSON (5 is a number), except the text operands in of table_from_csv, split, replace and json_parse and 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.
  8. 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, a preview tag; 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.
  9. 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). A set repeats what it writes on its point’s row.
  10. A key field takes a wire inside a scope (ADR 0040 §1; the catalog’s params[].scope). When Point (subscribe, liveliness, load_value) or Node (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 (inside downstream, dataflows or storage of this site). Save writes key_scope; Cancel takes the wire away. The scope then shows as the row Scope; unbinding keeps it. The deployer’s and the watcher’s rights on the scope (for list_children also on its children, <scope>/*) are checked by the engine, not by the editor.
  11. A block with behaviours (invoke, set, load_value, list_children: a trigger input 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 unbound Trigger of a command block is a Run button: the engine’s dataflows/<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, error with its code and message. In a preview the block’s trigger row reads would send ….
  12. An action dragged from the Tree tab becomes an invoke with path, action and 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 ~meta and choose each argument’s editor.
  13. 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’s blocks, and drawn as one block per instance. Its inside opens on the canvas (Open inside, Edit custom block) with an Inputs block and an Outputs block: a wire from Inputs.<a> to an inner field is the to of input a, a wire from an inner output into Outputs.<x> the from of output x. 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).
  14. On a broker without ADR 0040 (no scope in the catalog, no type with trigger: true, list_blocks not answered) the editor draws the older shape and says why a thing is off: a key field takes no wire (This broker cannot bind …), Run is off, My blocks and the custom-block items of the menu are off.
TypeFields on the block, in orderField ← engineInspector onlyEditors
number, string, boolValue ⇄Value = in → value → out—number box; text; toggle
constValue →Value = value → out—JSON or text
subscribePoint ⇄ · 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
livelinessNode ⇄ · Scope · Alive → · Error → (as subscribe)in.key → key; key_scope; out (true while the node is there); error—as subscribe
timerPeriod (ms) ⇄ · Count →in.period_ms → period_ms; out——
expressionExpression → · Trigger → · Quality → · <name> ⇄ … · Output →in.<name> ⇄Inputs (list)Trigger, Quality dropdowns
filterInput ⇄ · Expression → · Output →in; expr——
latchInput ⇄ · Reset ⇄ · Reset mode · Output →in, reset (operands); reset parameter (no echo: the input took the name)—Reset mode dropdown
delayInput ⇄ · Delay (ms) ⇄ · Output →in; in.ms → ms——
scale, form k × in + bInput ⇄ · Factor ⇄ · Offset ⇄ · Output →in; in.k → k, in.b → b; outFormForm dropdown
scale, form RangeInput ⇄ · Input min ⇄ · Input max ⇄ · Output min ⇄ · Output max ⇄ · Output → · Input out of range →in.input_min → input_min, …FormForm dropdown
deadbandInput ⇄ · Absolute change ⇄ · Percent change ⇄ · Output →in; in.abs → abs, in.pct → pct——
windowInput ⇄ · Size (s) ⇄ · Kind → · Function → · Max samples → · Output →in; in.size_s → size_s; the others config only—Kind, Function dropdowns
alarmInput ⇄ · 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
publishValue name · Value ←inMeta—
set<point> ⇄ (a behaviour that is set shows too)in → its echo inTarget: 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 runRun button (~act/trigger); toggles; Every: a number and its unit; Run on start asks first with the catalog’s warning
invokeheader <node> · <action> · <required argument> ⇄ … · Trigger ⇄ · Ok → · Error → (a behaviour that is set shows too)arg.<name> ⇄ (constant in args); trigger; ok, errorTarget: 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 runan argument as its action types it (choices, toggle, number, text); Run button; Every: a number and its unit; Run on start asks first
wasmArtifact → · <input> ⇄ … · <output> → …ports named by inputs/outputsConfig, Fuel, Memory (MB)—
add, subtract, multiply, divide, max, minInput 1 ⇄ · Input 2 ⇄ · … · Output → (− / +, at least 2)in.0, in.1, …; out—operands typed (values)
abs, not, lengthInput ⇄ · Output →in; out—in typed (values)
roundInput ⇄ · Precision ⇄ · Min precision ⇄ · Output → · Text →in; in.precision → precision, in.min_precision → min_precision; out, text—in typed (values)
moduloInput ⇄ · Modulo ⇄ · Quotient → · Remainder →in; in.modulo → modulo——
ifOperation ⇄ · 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
caseInput ⇄ · 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)
hubInput 1 ⇄ · Input 2 ⇄ · … · Ignore null ⇄ · Output → · Index → · On change →in.<n>; in.ignore_null → ignore_null; outputs—Ignore null toggle; operands typed
stopwatchReset ⇄ · Enabled ⇄ · Interval (s) ⇄ · Step ⇄ · Modulo ⇄ · Loop ⇄ · Reset value ⇄ · Output → · On loop →reset; in.<p> → p—Enabled, Loop toggles
traceTracing ⇄ · Message ⇄ · Input 1 ⇄ · Input 2 ⇄ · …in.tracing → tracing, in.msg → msg; in.<n>—Tracing toggle; operands typed
concatInput 1 ⇄ · Input 2 ⇄ · … · Strict ⇄ · Output →in.<n>; in.strict → strict; out—Strict toggle; inputs typed (values)
load_valuePoint ⇄ · Scope · Trigger ⇄ · Error → · Output →in.key → key; key_scope; trigger; error, outBehaviour: Auto run, Every, Enabled · Events: Ok · State: Running, Last runas subscribe for Point and Scope; Run button (~act/trigger, the caller reads the key and the scope)
list_childrenNode ⇄ · Scope · Trigger ⇄ · Error → · Output →in.path → path; path_scope; trigger; error, outas load_valueas load_value
substring, replace, split, join, getInput ⇄ · <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; outInputs (list)inputs typed (values)
statsInput ⇄ · Min → · Max → · Average → · Sum → · Count →in; min, max, avg, sum, count——
changed, rising_edge, falling_edgeInput ⇄ · On change → / On edge →in; on_change / on_edge (an event: the row reads when it fired)——
counter, toggleInput ⇄ · Reset ⇄ · Step ⇄ · Initial ⇄ · Output →in, reset; in.<p> → <p>; out—Initial: a number / a toggle
sample_and_holdInput ⇄ · Trigger ⇄ · Output →in, trigger; out——
debounce, throttleInput ⇄ · Quiet time (ms) ⇄ / Period (ms) ⇄ · Output →in; in.ms → ms; out——
block:<name> (an instance of a custom block)header MY · <input> ⇄ … · <output> → … · Open insidean 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)
constantName ⇄ · Value →in.name → name; out—Name dropdown
factorial, parse_number, sin, cos, tan, cot, asin, acos, to_degrees, to_radiansInput ⇄ · Output →in; out—in typed (values)
log, power, root, atanInput ⇄ · Base / Exponent / Degree / X ⇄ · Output →in; in.<p> → <p>; out——
boundInput ⇄ · Min ⇄ · Max ⇄ · Input out of range → · Output →in; in.min, in.max; outputs——
round_up, round_downInput ⇄ · Precision ⇄ · Output → · Text →in; in.precision; out, text——
format_numberInput ⇄ · Format ⇄ · Decimal separator ⇄ · Group separator ⇄ · Output →in; in.<p>; out——
average, median, mode, std_deviation, varianceInput 1 ⇄ · Input 2 ⇄ · … · Output → (− / +)in.<n>; out—operands typed (values)
left, rightInput ⇄ · Length ⇄ · Output →in; in.length; out——
trim, base64_encode, url_encode, url_decode, to_camel_case, from_camel_caseInput ⇄ · Output →in; out—in typed (values)
base64_decodeInput ⇄ · Output → · Bytes →in; out, bytes——
hashInput ⇄ · Algorithm ⇄ · Output →in; in.algorithm; out—Algorithm dropdown
json_parseInput ⇄ · Output → · Parse error →in; out, parse_error——
json_stringifyInput ⇄ · Pretty ⇄ · Output →in; in.pretty; out—Pretty toggle
nowInput ⇄ (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_timeYear ⇄ · 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_formatInput ⇄ (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_parseInput ⇄ · Time zone ⇄ · Time → (a date and time) · Year → · … · Weekday →in; in.time_zone; the parts—Time zone: the zone menu
date_mathInput ⇄ · 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_rangeInput ⇄ · ▸ 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
routerInput ⇄ · 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); elseInputs (list)Operation dropdown; cases typed (values)
event_gateReset ⇄ · Log order ⇄ · Input 1 ⇄ · … · On finish → · Order →reset; in.log_order; in.<n>; outputs—Log order dropdown
catch_errorInput 1 ⇄ · … · Output → · Code → · Source → · On error →in.<n>; outputs——
load_historyPoint ⇄ · Scope · Time range ⇄ · Rollup ⇄ · Window ⇄ · Trigger ⇄ · Error → · Output →in.key → key; in.<p>; trigger; error, outBehaviour: Auto run, Every, Enabled · Limit, Time zone · Events: Ok · State: Running, Last runas 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_nodeNode ⇄ · Scope · Trigger ⇄ · Error → · Output → · Actions →in.key → key; trigger; error, out, actionsas load_valueas load_value
tableValue ⇄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_recorderReset ⇄ · Input 1 ⇄ · … · Enabled ⇄ · Buffer size ⇄ · Time window (s) ⇄ · Ignore null ⇄ · Output →reset; in.<n>; in.<p>; outInputs (list)—
table_from_csv, table_to_csv, table_from_json, table_to_jsonInput ⇄ · <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_columnsInput ⇄ · Retain columns ⇄ · Output → · Error →in; in.retain_columns; outputsMapping (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_mapInput ⇄ · <parameter> ⇄ … · Output →in; in.<p>; outputs—Method / Order dropdowns
table_filter, table_remove_rows, table_edit_rowsInput ⇄ · (Cells ⇄) · Output → · Error →in; (in.cells); outputsExpressionExpression: multi-line
table_group_by, table_rollupInput ⇄ · <parameter> ⇄ … · Output →in; in.<p>; outAggregates (list of column/method/as)Aggregates: rows of column, method, as
table_joinInput ⇄ · Right ⇄ · Column ⇄ · Right column ⇄ · Join ⇄ · Output →in, right; in.<p>; out—Join dropdown
table_pageInput ⇄ · ▸ 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:

  • const has no input: it sends its value once, at the start.
  • delay has no mode: for a window or a wait use throttle or debounce.
  • concat has no separator.
  • An instance of a custom block has no row of its own in watch (ADR 0040, deferred).
  • load_history gives t in microseconds and fixed column names; a table_map_columns renames them.
  • table_from_json keeps a nested list as one cell.
  • table_join renames no columns; a table_map_columns does.

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
RoleWhat Claude can do
viewerread devices and storage
operatorread, write points, run write-level actions, read flows
engineeralso config-level work: add/edit devices, deploy flows (needs Allow config-level changes too)

2. Install the extension

  1. Get wyrm-<version>-darwin.mcpb (macOS) or wyrm-<version>-win32.mcpb (Windows) from the CI run of claude-desktop (Actions → claude-desktop → Artifacts; the workflow is packaging/claude-desktop/ci-workflow.yml, copied to .github/workflows/claude-desktop.yml), or build it yourself:
    packaging/claude-desktop/build.sh --universal
    
    The file goes to dist/claude-desktop/. On Windows, run bash packaging/claude-desktop/build.sh from Git Bash.
  2. Double-click the file, or in Claude Desktop open Settings → Extensions → Install Extension….
  3. Fill in the form:
SettingValue
Gateway URLhttps://<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 / Passwordthe user from step 1. Claude Desktop keeps the password in the system keychain.
Gateway CA certificatethe 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-onlyrefuses every change
Allow config-level changesoff 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.
  1. Start a chat and ask “who are you on WYRM?”. Claude calls whoami and 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: ok or the refusal the action would give, ADR 0047); an older link is checked against its ~meta only. 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/temp means 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

MessageCause
wrong user or password, or the user is disabledFix the settings under Settings → Extensions → WYRM.
TLS: invalid peer certificate: UnknownIssuerSet Gateway CA certificate to the PEM of the broker CA or of the self-signed certificate.
plain HTTP only on loopbackUse 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 refusedThe gateway is not running, or the port is wrong (gateway.listen in wyrmd.json5).
refused_by_connector: … allow_configA 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_deniedThe user’s role does not allow it.
… takes no file: invoke it over the WebSocket, with arguments under 60 KiBA 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.

  1. In wyrmd.json5:
    gateway: {
      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)
      },
    },
    
    Restart wyrmd. https://broker.example:8445/.well-known/oauth-protected-resource now answers with JSON.
  2. On claude.ai, open Settings → Connectors → Add custom connector, name it WYRM, and set the URL to https://broker.example:8445/mcp. No client ID or secret is needed: Claude registers itself.
  3. 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_invoke and flow_apply default to dry_run: true: they validate against ~meta (type, enum, bounds, action schema, level) and return what would be sent.
  • Config-level operations (writable = config, action level config, anything under sys/**, flow deploys) need approval: a base64 ptok minted by a human for exactly that key and exactly those arguments (≤ 15 min, subject not ai:). It is sent instead of the service token, so the link checks the human’s rights. flow_apply also 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:
    1. Run the tool with dry_run (the default). Read would_send (for flow_apply: the definition and the proofs) and copy args_sha256.
    2. Mint the approval for that key and that hash: wyr --key admin.key token <key> --subject user:<you> --args-sha256 <hash> [--ttl-s 300].
    3. Run the tool again with the same arguments, dry_run: false and approval.
  • The MCP server refuses an approval without args or 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.

  1. Run cargo build --release -p wyrm-mcp.
  2. 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:

  1. 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.
  2. The agent driver: 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).

CommandWhat 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 when unless exists, and done when the action is refused with a message that holds ok_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, with timeout_s: waits until the value passes;
  • {"sleep_s": N}.
  1. 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").
  2. 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

  1. A user with write on the link calls ▸ Ask {task}. The link creates tasks/<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).
  2. The model reads the tree with read-only tools. It may ask back (ask_user): the task waits in awaiting_answer until ▸ Answer {answers}.
  3. The model proposes a plan. set and invoke steps change the site. wait, expect and sleep steps only read: they prove the plan and need no approval.
  4. The link checks every step against ~meta, allowed_prefixes and the level the step needs.
  5. With approval needed, the task waits in awaiting_approval. The record is the task’s ~state document (restricted: the reader needs list): plan[] holds every step in the wyrm-agent run format with its number n, level, after, check, warn and reason. ▸ Approve {approvals: {"<n>": <token>}, plan} takes one human token per step, at the level of that step. write on the task is enough to call it.
  6. 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 (warn is the link’s finding, model_warn the 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.

  • label and detail are 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.
  • key is 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’s auth, only until its exp. Without them the finding is refused.
  • Limits: 12 findings in a task, label 80 bytes, detail 300 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:

  1. 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.
  2. 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 config on the link: a write step that needs no approval runs with the agent’s own key (ai:<link>, at most write, only under allowed_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 sends approve for 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/expect timeouts, 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

KeyWho readsWhat
tasks/<id>/~valread 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>/~statelist on the taskthe ask, owner, plan with results, questions, suggestions, findings, replaced_by, review, log, error
budget_used_todayread on the linkLLM tokens used this UTC day
sys/links/<id> ▸ secretsconfigthe names of the link’s secrets, never a value

Params

ParamDefaultMeaning
modelclaude-sonnet-5-5The model.
budget_tokens_day1 000 000LLM tokens per UTC day; Ask is refused at the limit.
allowed_prefixesnoneKeys under which the agent may propose changes. Empty: nothing.
require_approvalwriteWhich steps need a human (below).
api_key_refanthropic_api_keyThe link secret with the API key (▸ Set Secret).
api_basehttps://api.anthropic.comWhere the API key is sent.
max_turns, max_tokens, llm_timeout_s, fallbacksBounds of one planning run.
review_turns4LLM 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.
  • config and never: only config steps need a human; write steps 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).

ModeWhere the code runsWhere the code comes fromIsolationTypical use
embeddedin the broker processa driver built into wyrmdnone: same processthe built-in drivers
processa child process the broker starts and watchesa built-in driver (wyrmd link <driver>) or a process packageown process, mTLS identity, ACL on its own branch, rlimits, cleared environmentyour own driver in Rust
WASMin the broker process, in a sandboxa 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 limitssmall protocol drivers, computed points, portable links (section 9)
externalon another machineanything that speaks the link protocol with a certificate from the broker’s CAmTLS identity, ACL on its own branchgateways 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 refusalStatus
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 answertimeout
The connection is brokendisconnected

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_DATE and EDITOR_DURATION are gone. Use wyrm_core::meta::Editor::{Password, Textarea, File, Daterange, Date, Duration}.
  • ParamMeta::editor takes an Editor (it took text), and the field ParamMeta.editor is an Option<OrUnknown<Editor>>; ask with ParamMeta::has_editor(Editor::File).
  • Link::on_check takes its arguments by value (args: Value, it was &Value), like on_invoke. App::on_check of a portable link is as it was.
  • ParamSpec.editor is an Option<Editor> and ParamSpec::editor takes an Editor. #[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 display out when the key says it: the SDK derives one with wyrm_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 display you 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 as wyrm_core::display::WORDS writes them (URL, ID, TLS, CA, MQTT). A product name that is not in WORDS, NAMES or PHRASES goes there.
  • Nodes. NodeMeta::display(..) sets attr.display, shown instead of the key (key 12 in view=list). On the driver framework the user sets it: add_* and edit of a connection, device or point take an optional display (“Display name”), so point t1 reads “Supply temperature”. Edit without it keeps the name, "" clears it; Edit with display alone renames and keeps every param. A new name restarts nothing. display is reserved: no driver param may use that name.
  • Enum values and group are 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) and portable-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 with Add/Edit/Remove actions) and process::run for a link that runs as its own binary.
  • WASM host and WIT (crates/wyrm-wasm-host/wit/link/point.wit): the component worlds wyrm:link/point and wyrm:link/driver.
  • Example links (examples/links): a responder (the mockdev driver 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.sh packages them with wyr link pack and makes a repository with wyr repo add (ADR 0021).
  • Scheduler (links/scheduler, ADR 0022): schedules of events that write values to points at times. Every broker runs one at wy/<site>/downstream/scheduler; it is also a portable link in the packages scheduler (WASM) and scheduler-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 at wy/<site>/downstream/alarm; also the packages alarm (WASM) and alarm-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 at wy/<site>/downstream/uplink (uplink.net lists the platforms); it is also a portable link in the packages uplink (WASM) and uplink-process. Guide: docs/uplink.md.
  • Telegram (links/telegram) and Slack (links/slack), ADR 0039: one link per chat platform on the shared core crates/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, /do within their level, their inviter’s rights and the link’s grants. Not embedded: packages telegram, telegram-process, slack, slack-process. Guides: docs/messenger.md, docs/telegram.md, docs/slack.md.
  • Modbus (links/modbus, built-in driver modbus, package modbus): 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_dsa takes a dslink-java-modbus tree. Its Scaling multiplies where DSA’s divides: read the guide first, docs/modbus.md.
  • HTTP (links/http, driver http): JSON REST APIs polled on the driver framework. Guide: docs/http.md.
  • BACnet (links/bacnet): BACnet/IP devices (driver bacnet, package bacnet). Guide: docs/bacnet.md.
  • OPC UA client (links/opcua, driver opcua, package opcua): nodes of OPC UA servers as points, with security and certificates. Guide: docs/opcua.md.
  • Prometheus (links/prometheus, driver and package prometheus): 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 packages s3, 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.

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).

ItemFieldsWhat it does
from DriverLink ID, Driver (the drivers this broker hosts, as choices), Mode, ParamsA built-in driver as embedded, process or external.
from ZipName, Zip (a file you choose)Installs the package in the zip and runs it as link Name.
from UrlName, UrlDownloads a package zip, then as from Zip.
from GitName, Url, RefClones a repository that holds a built package, then as from Zip.
from RepositoryName, PackageTakes a package from the index in packages.repository, checks its SHA-256, then as from Zip.
from WASMName, 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

  1. 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 1 over HTTPS. from Zip and from WASM take the file you chose.
  2. 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.json at the zip root, valid (section 6);
    • wyrm_link equal to the broker’s link protocol version;
    • the entry for this host present (process), or the .wasm entry present (wasm);
    • wasm: the component’s world, read from its exports (app, driver or point), matches world if the manifest has one; capabilities only for an app, within their bounds (section 9).
  3. Rights the package asks for. A new link of the package gets its network allowlist (capabilities.net) and its requester grants. Without Accept Requested Rights (accept: true) such an install answers success: false with 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).
  4. Move into place with one rename: <data_dir>/packages/<name>/<version>/. A failed install leaves nothing.
  5. 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 gets package_install with the SHA-256 and the source.
  6. Start the link with driver pkg:<package>:
    • process package: 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.
    • wasm package: the broker copies the component to <data_dir>/packages/.wasm/<package>.wasm and starts an embedded link: a driver or point component on the wasm driver with one connection main; an app component on the driver app with its capabilities as params (section 9).
  7. Answer success: true and a message such as package 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 doResult
Install the same package (same version, same bytes) under another NameA second link of the same package. The files are reused.
Install the same version with other bytesRefused: … 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> ▸ RemoveThe 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> ▸ RemoveRefused 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

ValueMeaning
versionThe installed version.
latestThe version in the repository index (section 12). Empty for a custom package: one the index does not list.
update_availablelatest 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_stateThe update to latest changes the store format (below).
stateThe store format the installed version writes.
previousThe version kept for a rollback: {version, keep_until, changes_state}; an empty map when none is kept. keep_until is unix seconds.
last_updateThe 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

PackageAction
In the repositorysys/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.
CustomInstall 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:

  1. Unpack and check the new version beside the old one (section 4, steps 1–2). Nothing runs it yet.
  2. 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’s net param (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.
  3. Store format. If the new version does not read the installed state (section 6), the update changes the store format: with restore_point: false it is refused.
  4. Restore points, before anything stops. For every link of the package: its key list (~meta?view=keys of its root, as a reader without a token sees it) and, with restore_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 from secrets.key: it needs no passphrase and no backups.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.
  5. Install. The new version goes to <data_dir>/packages/<name>/<version>/; the old directory stays, and the registry keeps it as previous until keep_until (packages.keep_previous_days, default 7, 1 to 365). One previous version is kept: the one before it is deleted.
  6. Restart every link of the package (hot start for an app component), and answer. The message ends with the links are being checked ….
  7. Health check, in the background; last_update.result is checking and its counts move while it runs. Every link must answer and have every key it had. kept, new and gone count the keys (as <link>/<path>; new_keys and gone_keys hold 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_s is over and a key is gone or a link did not come back: the broker rolls back by itself (result: rolled_back, reason says which link and how many nodes; audit update_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, with gone and a reason when keys are missing. A link that does not answer in 120 s makes it failed; the new version stays.

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.

  1. Every link of the package stops.
  2. The registry names the kept version again (from its kept directory).
  3. 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).
  4. The links start; the directory of the version that was rolled back is deleted.
  5. last_update becomes {from, to} of the update that was undone, with result: rolled_back, reason (rolled back by <who>) and its counts. Nothing is kept after a rollback: previous is 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"
}
FieldRequiredMeaning
nameyesPackage name: a key segment (as a link id).
versionyes1–32 of A–Z a–z 0–9 . _ - +, not starting with ..
descriptionnoShown under sys/packages/<name>.
wyrm_linkyesThe link protocol version the package was built for (LINK_PROTOCOL in wyrm-link-sdk; now 1). Another value is refused.
kindyesprocess or wasm.
entriesprocessExecutable per host, as <os>-<arch>: linux-x86_64, linux-aarch64, macos-aarch64, macos-x86_64. One zip can carry several hosts.
argsnoArguments for the executable.
requesternoGrants 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.
entrywasmThe component file.
worldnowasm: 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.
capabilitiesnoA 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).
statenoThe 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_statenoThe 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:

VariableValue
WYRM_SITE, WYRM_LINK_IDSite and link id.
WYRM_ENDPOINTThe 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_SWith several endpoints: seconds a router without the site’s broker is kept before the next endpoint (15 by default).
WYRM_CA, WYRM_CERT, WYRM_KEYmTLS files: broker CA, the link’s certificate (CN = link id) and key.
WYRM_TOKEN_FILEThe link token for hello.
WYRM_DATA_DIRThe link’s private directory (<data_dir>/links/<id>/data, mode 0700).
WYRM_PARENT_PIDThe broker; the link exits when it is gone.
WYRM_LIMIT_MEMORY_MB, WYRM_LIMIT_OPEN_FILESLimits 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.

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.

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):

LevelParameterMeaning
ConnectionPackage (component)The WASM package that runs (set by the install).
ConnectionNetwork (net)Where the component may connect, see below. Empty: no network.
ConnectionConfig (config)JSON, given to init as CBOR.
ConnectionCall ms (call_ms)Time of one call, network included: 2000 by default, 10–10000.
DeviceNoteDevices only group points (no ping).
PointType (value)number (default), bool, text or any: the value type the app shows and sends on set.
PointPoint config (cfg)JSON, given to read and write as CBOR.
PointPoll s, Writable, UnitHow 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 in connect.
  • 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, in tcp_connect, tls_connect, and tls_upgrade (TLS on an open connection, as PostgreSQL’s and MySQL’s SSLRequest). 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).
  • connect passes 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/0 does 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 config can 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.

A portable link (ADR 0023) is one Rust source, an App from wyrm-link-api, that runs in three modes with the same behaviour:

ModeHowBuilt with
Embeddedwyrm_link_portable::Portable<App>, compiled into a brokerthe crate as a dependency
Processwyrm_link_sdk::process::main::<Portable<App>>(), supervised--features process
WASMa 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):

WorldAdds
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:

  1. runs cargo build --release --lib --target wasm32-unknown-unknown --features wasm (strip = true is fine: it keeps the component type, a custom section of the module);
  2. makes the module a component in-process (wit-component) and checks that its world is app;
  3. writes one zip for every host, <name>-<version>.zip, with world: "wyrm:app@0.3.0" (the version the component was built for) and the capabilities in wyrm-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:

CapabilityDefaultBoundsMeaning
netnoneentries as in section 8Where the app may connect (tcp_connect, tls_connect).
store_mb10–64Size of the store; 0 refuses every write.
memory_mb641–512Linear memory of one instance (all its memories together).
call_ms20001–10000Time 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.

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:

LevelThe link can
listlist the nodes under the path (~meta) and see them come and go
readalso 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)
writealso 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 most read), or wy/{site}/storage[/…] (the site’s storage, ADR 0046: read anywhere in it, write only on a folder below it, wy/{site}/storage/<folder>[/…], never on all of it). Plain segments only: no wildcards, no ~ suffixes, never sys. A grant covers the path and everything under it. config is 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 /set on the points of storage/<bot>/cmd (grant write on wy/{site}/storage/<bot>/cmd, read on wy/{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 with sys/links/<id> ▸ Grant Access {path, level} (none removes). sys ▸ Get Permissions lists them (source link), and sys/links/<id> shows them as attr grants ({path, level}) beside net, the hosts a portable link may reach (administrators read sys; the link’s own ~meta never 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(), and wyrm_client::WyrmClient over it. The router ACL lets the link’s certificate reach the granted paths. For set and actions the client signs a ptok with 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 subject link:<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 set and actions.
  • A requester key never opens sys/**, never deploys a flow, and never passes config.

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.

StreamWhen 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’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, resolve of wy/<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, in Refreshed and in Added. 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 ~meta of each link on a task of its own, all at once, and gives each read at most LIST_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 first Refreshed comes after at most one window, however many links are silent. An Added of 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 Added when it answers. If its token goes first, the list sends nothing for it. children of 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: default or a level. For an embedded link it sets the level of its lines alone; for a process link it sets its RUST_LOG and restarts it. Saved in the registry.
  • The broker’s own: sys/log_level and sys ▸ Get Log (filter by link to see one embedded link).
  • A process package should log with tracing-subscriber (as the crates in examples/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).

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 config on wy/<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 under sys/packages and 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

WhatLimit
Package zip64 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 index4 MiB, 1000 packages
Install action120 s
Update: health check (auto_rollback_s)default 120 s, 0 (report only) to 600 s
Restore point8 GiB of private data, 50 000 files; kept packages.keep_previous_days (7, 1 to 365)
last_update200 keys of new and of gone
git clone120 s, depth 1, HTTPS only, needs git on the broker host
WASM component16 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 storestore_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 network4 connections, 64 KiB per send or receive, IP literals only (host names: TLS of portable apps)

15. When an install fails

MessageMeaning
no wyrm-link.json at the zip rootThe manifest is missing or in a subdirectory.
built for link protocol N, this broker speaks MRebuild 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 allowedThe zip has a path that leaves its directory, or a symlink.
… is installed with other contentSame version, different bytes: raise the version.
link … exists and runs …Name is taken by another link.
process links need a tls/ listener on the brokerAdd a tls/ listener to listen in wyrmd.json5.
url: no credentials in the URLRemove user:token@ from the URL.
… plain http only to a loopback addressUse HTTPS.
repository unreachable: …The index could not be fetched; check packages.repository.
the broker is restarting; try againAnother install rebuilt the router; repeat the action.
the update of … is being checkedThe 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 contentThe 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

  1. Run examples/packages/build.sh. It builds every link of links/official.json from 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 to examples/packages/out/. build.sh telegram s7 builds only those official links (and the examples). Run it again after a link changes.
  2. Run examples/demo/run.sh. It serves out/ on 127.0.0.1:18070; the packages.repository of 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.
  3. Log in to the edge gateway (http://127.0.0.1:8444, user admin).
  4. Open wy/edge/sys/links ▸ Install Link ▸ from Zip, choose example-link-<os>-<arch>.zip, Name example, Invoke. Then open wy/edge/downstream/example ▸ Add Connection, Add Device, Add Point.
  5. Install Link ▸ from WASM, choose register.wasm, Name reg. Open wy/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 under out/<name>/<version>/, the official links’ in out/.
  6. Install Link ▸ from Repository, Package register, Name reg2.
  7. Install Link ▸ from Repository, Package portable-echo, Name echo (the portable link as WASM), and Package portable-echo-process, Name echop (the same app as a process). Install Link ▸ from Driver, Driver portable-echo, Name echoe (embedded). In each, set n, ▸ Ping, then sys/links/<id> ▸ Stop and ▸ Start: n comes back from the store and starts goes up by one.
  8. Install Link ▸ from Repository, Package recorder, Name rec (a requester), and ▸ from Url http://127.0.0.1:18070/average/1.0.0/average-1.0.0-<os>-<arch>.zip, Name avg (both). See examples/links/README.md for 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 attributeDSA meaningOur form labelOur key (json5, ~def, export)Our meaning
offsetregister or bit addressOffsetaddrregister or bit address
scalingdivisor: raw / scalingScalingscalemultiplier: raw × scale
scaling offsetadded after the divisionScaling Offsetoffsetadded after the multiplication
write of vv × 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 offset is the added offset, not the address. The address is addr.
  • 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_dsa sets scale = 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 offset is 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 / scaling is not exact in binary: with scaling = 10, raw 3 shows 0.30000000000000004 where DSA showed 0.3, and raw 7 shows 0.7000000000000001. Trends and equality tests in flows see this. Writes to integer types are not affected: the raw value is rounded.
  • scale = 0 is refused (scale: must not be 0); DSA scaling = 0 is 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).

NodeActionsLevel
link rootadd_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
connectionadd_device, edit, remove, copy, restart, stop / start, export, import (a device branch)config
master connectionscan_unitsconfig
deviceadd_point, add_folder, edit, remove, copy, restart, stop / start, export, import (a folder branch)config
master deviceread_registers, read_device_idread
folderadd_point, add_folder (while less than 4 deep), remove, copy, export, import (a folder branch)config
pointedit, remove, copyconfig
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)

KeyLabelDefaultBoundsNotes
hostHost(required)name or IP literal; the first address it resolves to
portPort5020…65535
transportTransport Typetcptcp, rtu_over_tcprtu_over_tcp: RTU frames (CRC, no MBAP header), as serial-to-Ethernet gateways send
timeout_msTimeout (ms)1000100…10000bound on each request
write_modeWrite Modeautoauto, single, multiplesection 6
retriesRetries00…5repeats after a timeout only (section 7)

Serial connection (serial_connection)

KeyLabelDefaultBoundsNotes
serial_portSerial 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_rateBaud Rate9600300…4000000
data_bitsData Bits85…8
stop_bitsStop Bits11…2
parityParitynonenone, odd, even
timeout_msTimeout (ms)1000100…10000
write_modeWrite Modeautoas above
retriesRetries00…51 is a good value on RS485

Slave connections (ip_slave, serial_slave)

KeyLabelDefaultBoundsNotes
listen_hostListen Host127.0.0.1ip_slave: every address the name resolves to (section 13)
listen_portListen Port5021…65535ip_slave; 502 needs privileges on Linux; 0 is refused (the system would pick a port no master can know)
master_idle_sMaster Idle Timeout (s)601…86400ip_slave: a master that sends no complete request for this long is closed (section 13)
serial_port, baud_rate, data_bits, stop_bits, parityas the serial connectionserial_slave

Device

KeyLabelDefaultBoundsNotes
unitSlave ID10…2550 and 255 are ordinary units on Modbus TCP; on RTU 0 is the broadcast address and is refused (section 6)
pingPingprobeprobe, fc17, noneprobe reads probe_table/probe_addr, and an exception reply means alive; fc17 sends Report Server ID (often unsupported); none sends no ping
probe_tableProbe Tableholdingcoil, discrete, input, holding
probe_addrProbe Address00…65535
ping_sPing Rate (s)5.00.1…3600
contiguous_onlyContiguous Batch Reads Onlyfalsefalse: a read may span gaps between points
max_regsMax Registers per Read1251…1251 = each register point read alone
max_bitsMax Bits per Read20001…20001 = each bit point read alone
republish_sRepublish Unchanged Values (s)00…36000 = publish on a change only; DSA republishes every 60 s

Point

KeyLabelDefaultBoundsNotes
tableObject Type(required)coil, discrete, input, holding
addrOffset(required)0…65535the value may not run past 65535
dtypeData Typeu16; binary on coil and discretesection 4a bit table holds binary only
bitBit00…15the bit of a register for binary on input/holding
regsNumber of Registers11…125registers of a char/varchar value
poll_sPoll Rate (s)1.00.01…86400
scaleScaling1.0not 0multiplier (section 1)
offsetScaling Offset0.0added after scale
writableWritablefalsecoil and holding only
unitUnit""shown beside the value
writable_by_masterWritable by Masterfalseslave connections only (coil and holding)
  • writable_by_master shows in every point form but does nothing under a master connection.
  • Under a slave connection poll_s and writable do nothing, and so do the device’s ping, probe_table, probe_addr, ping_s, contiguous_only, max_regs, max_bits and republish_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 as downstream/** 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:

OrderRegistersOur suffix
ABCD0x1122 0x3344none
CDAB0x3344 0x1122_wswap
BADC0x2211 0x4433_bswap
DCBA0x4433 0x2211_wbswap
OursRegistersValueDSA name
binarya bit, or bit bit of 1boolBOOLEAN (any type on a coil or discrete table)
bits161array of 16 bools, bit 0 firstBOOLEAN with bit = -1 on a register
u16, i161numberUINT16, INT16
u16_bswap, i16_bswap1numberUINT16SWAP, INT16SWAP
u32, i322numberUINT32, INT32
u32_wswap, i32_wswap2numberUINT32SWAP, INT32SWAP
u32_wbswap, i32_wbswap2numberUINT32SWAPSWAP, INT32SWAPSWAP
u32_bswap, i32_bswap2numbernone
u32_m10k, i32_m10k2hi × 10000 + loUINT32M10K, INT32M10K
u32_m10k_wswap, i32_m10k_wswap2as above, words swappedUINT32M10KSWAP, INT32M10KSWAP
f322IEEE 754FLOAT32
f32_wswap2FLOAT32SWAP
f32_wbswap2none
u64, i64, f644UINT64, INT64, FLOAT64
u64_wswap, i64_wswap, f64_wswap4the four words reversedUINT64SWAP, INT64SWAP, FLOAT64SWAP
bcd1614 BCD digitsBCD16
bcd3228 BCD digitsBCD32
bcd32_wswap2words swappedBCD32SWAP
charregsASCII, trailing spaces and NULs cutCHARSTRING
varcharregsASCII up to the first NULVARCHARSTRING
  • An unscaled integer (scale 1, offset 0) publishes exactly as an unsigned or signed integer; 64-bit values never pass through a float. A scaled value publishes as a float.
  • bits16, char and varchar ignore scale, offset and bit (without an error).
  • m10k: lo must be 0…9999 for the unsigned types and −9999…9999 for the signed ones, else the point shows bad/device_error. The signed types read both words as i16, 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_regs registers or max_bits bits; gaps are read too unless contiguous_only. There is no batch switch: max_regs = 1 and max_bits = 1 read 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 go uncertain/stale (then bad/comm_fail), and the device stays Connected. 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.

Pointautosinglemultiple
coilFC5FC5FC15
holding, 1 registerFC6FC6FC16
holding, more registersFC16a series of FC6, lowest address first (DSA “Never”)FC16
binary bit of a holding registerFC22 mask write; if the unit answers Illegal Function, read and FC6 from then on (remembered per unit while the connection lives)samesame
  • The read-modify-write of a bit always sends FC6, also in multiple mode.
  • One FC16 carries at most 123 registers. A writable char/varchar point with more regs loads 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 single mode 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-modbus 0.17 always waits for a reply, so such a device sends nothing. It is accepted at add (the device does not know its connection’s kind), then shows Failed with broadcast (unit 0) is not supported on RTU; a write answers the same.
  • A set during scan_units on the same connection answers busy at 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. During read_registers or read_device_id (level read, one bounded request each) a set waits for that one action and then runs. The wait holds the link for up to 5 s: a read_registers to a unit that does not answer, with timeout_ms above about 4 s, outlasts it, and the set answers timeout and is not written. Keep timeout_ms low on lines where operators run read_registers while 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_ms and retries, and its read-back can take longer than a client waits (10 s by default). The client then gets timeout; the point still shows what the read-back finds. A write or action that arrives during a configuration change of the same connection answers busy: send it again.

7. Timeouts, retries and RTU timing

  • Every request is bounded by timeout_ms. After a timeout it is sent again up to retries times; 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-modbus cannot 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 the reopens diagnostic.
  • 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 poll timeout_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 happenedValueQuality
readthe value readgood
first poll of the device missed (timeout)last valueuncertain/stale
3 polls missedlast value; the device Failedbad/comm_fail
one batch of the device timed out while its other batches answeredlast value; the device stays Connecteduncertain/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 valueuncertain/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 errorbad/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 decodelast valuebad/device_error
connection downlast value; devices Stopped by Parentbad/disconnected
slave: the tree’s value does not fit the point after an editlast valuebad/config_error
the next good readthe value readgood

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_ms that fits the slowest device on the line; the whole line waits for it.
  • Stop devices that are gone (section 7).
  • serial_slave must 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 no edit (no rename: ids are keys of history watches, ACL rules and flows; copy and remove move 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 status or error, a diagnostics leaf name (section 12) or an action name.
  • remove of 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 the renamed map (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. name renames the top node; overwrite: true replaces a node of that name. It replies {name, reenter}: reenter lists the secrets to enter again with edit (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

KeyHolds
createdthe connections imported
reentersecrets 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

DSAOurs
scaling, scaling offset, offsetscale = 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), retriestimeout_ms (100…10000), retries (0…5)
use multiple write commands Always / Never / As Appropriatewrite_mode multiple / single / auto
max read register count, max read bit count (connection)max_regs, max_bits (each device)
use batch polling falsemax_regs = 1, max_bits = 1
data typessection 4
foldersfolders; 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 duration and Timeout are stored in ms by DSA.
  • Missing attributes get the defaults DSA restores with, not ours: Timeout 500 ms, retries 2, contiguous batch requests only true, use batch polling true; each is reported. A new connection made here has timeout_ms 1000 and retries 0.
  • Not imported, reported in dropped with the connection’s devices: UDP and ASCII transports, parity MARK and SPACE, 1.5 stop bits (section 14). No node is made, so a start cannot run them on another framing.
  • Not carried, reported in dropped: zero on failed poll set (section 8), discard data delay above 0, max write register count (one write carries up to 123 registers), values outside our bounds (clamped), local slaves (“setup local slave”: add an ip_slave by 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 (COM3 on Linux or macOS): edit its serial_port, then start; 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 in renamed.
  • A name clash refuses the whole import (a connection of that name exists): remove it, or give name for 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 ~meta or a leaf’s).
  • A connection’s counts start at 0 when it starts or restarts, a device’s on its own start and restart. A reconnect after a failure keeps them.
  • They are ordinary values: the historian can watch them.

Commissioning actions (master connections)

ActionNodeLevelArgsReply
read_registersdevicereadtable, 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_iddevicereadFC43/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_unitsconnectionconfigfrom (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_registers and read_device_id send each request once at the connection’s timeout_ms; the action is bounded by 12 s. A device that does not support FC43 answers not_supported.
  • One action at a time per connection. Another action of the same connection, from any caller, answers busy at once while one is queued or running; a set does during scan_units and waits during a read action (section 6). So actions delay the polls of the connection by one action at most, even when a read caller sends them without a pause.
  • scan_units sends 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 shorter timeout_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), and good again at the first poll after the scan. Sets answer busy meanwhile (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 (binary points with different bit on 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 as bad/config_error until it is set again.

Answers

RequestAnswer
an address no point coversexception 2 (illegal data address)
a write touching a point without writable_by_masterexception 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 infiniteexception 3; nothing changes
more registers or bits than one request carriesexception 3
a read touching a point without a valueexception 4
FC22 on a register whose points’ bits are not all knownexception 4
FC8, FC17, FC23, FC43 and every function code but FC1–6, 15, 16 and 22exception 1 (illegal function)
a unit no device servesTCP: 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 sTCP: 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) writeapplied to every served unit that takes it, no reply; counted once on the connection
RTU broadcast readignored
  • Many TCP masters send unit 255 or 0 by default. They get 0x0B unless a device has that unit: add a device with unit 255 (or 0), or set the master’s unit id. Unit 0 is refused under serial_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_host is 127.0.0.1 by default. Another address is allowed: the link logs a warning at warn when the listener opens and shows it as attr.warning on the connection’s status leaf. 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; raise master_idle_s for it. There is no limit per source address.
  • ip_slave listens on every address the host name resolves to (localhost: ::1 and 127.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 Failed with “Permission denied”. Use a port above 1023 (for example 1502) and point the master there, or give the binary CAP_NET_BIND_SERVICE.
  • serial_slave must be the only slave on its line (point to point to one master). The tokio-modbus 0.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_slave binds 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 goes Failed with 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

WhatWhyInstead
Modbus ASCII, Modbus UDPtokio-modbus has neither; rare in the fielda gateway to TCP or RTU
parity MARK and SPACE, 1.5 stop bitsthe serial library lacks them
renameids are keys: history watches, ACL rules and flows would breakcopy, then remove
“zero on failed poll”a dishonest value at good qualitythe quality ladder (section 8)
a batch polling switchmax_regs = 1, max_bits = 1
RTU broadcast writes from a master (unit 0)tokio-modbus 0.17 always waits for a replywrite each unit
serial_slave on a shared RS485 busthe 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 UDPip_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 needs config.
  • 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 Failed and editable, and a refused add or edit answers invalid_parameter naming 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’s data_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 a UINT64 above 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 link modbus.
  • The probe scenario modbus (links/probe/scenarios/modbus.json) runs on every site that has the link modbus with line1/ahu1 and skips the others (a modbus that 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 diagslave or 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

ModeHow
Built inInstall Link ▸ from Driver, driver bacnet; or wyrmd link bacnet as a process link.
Packagebacnet (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)

ParamDefaultBoundsMeaning
bind_host0.0.0.0IPv4 addressLocal address of the UDP socket.
bind_port478080–65535Local UDP port (0 = any).
broadcast255.255.255.255:47808IPv4[:port]Where Who-Is goes (the subnet’s broadcast address), when no BBMD is set.
bbmdemptyIPv4[:port]Register as a foreign device at this BBMD. Empty = no registration.
bbmd_ttl_s30030–65535Time to live of the registration. The link renews it at half of it.
apdu_timeout_ms3000100–60000Bound on each confirmed request.
apdu_retries10–5Repeats of a request after a timeout (not after an error reply).
max_apdu147650–1476The largest reply the link accepts.

Device (add_device)

ParamDefaultBoundsMeaning
instancerequired0–4194302Device instance.
addressemptyIPv4[:port]Address of the device, or of its BACnet router. Empty = find the device by Who-Is. Port default 47808.
network00–65534Network number of a device behind a BACnet router (MS/TP behind an IP router). 0 = on this IP network. Needs address and mac.
macempty1–7 hex octetsMAC address of the device on that network (MS/TP: one octet, 0A).
use_rpmtrueRead with ReadPropertyMultiple. false = ReadProperty per property.
max_apdu00 or 50–1476Largest APDU the device takes. 0 = from its I-Am (480 if it does not answer Who-Is).
ping_s100–3600Ping period. 0 = no ping.
republish_s00–3600Publish unchanged values again after this long. 0 = on change only.

Point (add_point)

ParamDefaultBoundsMeaning
object_typerequiredsee belowObject type.
instancerequired0–4194303Object instance (4194303 = the device object’s wildcard).
propertypresent_valuesee belowProperty to read.
property_id00–4194303Property identifier, only with property = other.
array_index-1-1–4294967294Array index; -1 = the whole property. Index 0 is the array length.
dtypeautosee section 4Type of the value.
check_statustrueRead status-flags beside present_value (section 6).
poll_s50.05–86400Poll period.
scale, offset1, 0scale ≠ 0Read: value × scale + offset. Write: the reverse. Numbers only.
writablefalseThe point takes ~set (level write).
priority161–16Write priority (1 is the highest).
unitemptyUnit 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 / propertyBACnet tagWYRM value
analog_*, loop, pulse_converter, averaging: present_value, relinquish_default, limits, cov_incrementREALnumber (float)
large_analog_valueDOUBLEnumber (float)
binary_*: present_valueENUMERATED inactive/activebool
multi_state_*, accumulator, command, positive_integer_valueUNSIGNEDnumber (whole)
integer_valueSIGNEDnumber (whole, signed)
calendar, out_of_serviceBOOLEANbool
characterstring_value, object_name, descriptionCHARACTER STRINGstring
status_flagsBIT STRINGmap {in_alarm, fault, overridden, out_of_service}
reliability, units, event_state, system_statusENUMERATEDnumber
priority_array, other, schedule and device present_valueanydynamic: 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, not 0.10000000149011612).
  • With scale or offset, 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

  • ~set on a point with writable = true sends WriteProperty with the point’s priority. A SimpleACK is success; the framework then reads the point back. The link never updates ~val itself.
  • 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_flags and bit strings cannot be writable.
  • Relinquish (NULL at a priority):
    • A point with property = relinquish (on the object, with writable and the priority to free) is a bool. It reads true while that slot of the priority array is empty. Writing true writes NULL to the object’s present-value at that priority; false is 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 level config (a write user must not free, for example, priority 1, life safety).

6. Errors and quality

What happensResult
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 propertiesEach property is read again with ReadProperty, so one bad point does not fail the others.
Reject unrecognized-service (or Error services) for RPMThe device is read with ReadProperty from then on.
Abort segmentation-not-supported, buffer-overflow or apdu-too-long for an RPMThe 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_retriesA 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 doOnly 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 answerThe 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}]. low and high go together; wait_ms is 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. Narrow low…high then.
  • 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 fixed address.
  • 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 one apdu_timeout_ms and gets 480. Set max_apdu to 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 while bbmd is empty: who_is and devices without an address then see the local subnet only. For devices on other subnets, set bbmd (foreign-device registration) or give each device a fixed address.
  • 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

NodeActionLevelResult
connectionwho_is {low?, high?, wait_ms}configDevices that answered (section 7).
devicelist_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.
deviceread_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.
devicerelinquish {object_type, instance, priority = 16}configNULL 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.0 and bind_port = 47808 for 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 another bind_port and a fixed address for each device then.
  • Devices on other subnets need bbmd or a fixed address: without bbmd, 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 unit param, not from the device: ~meta is fixed by the params. list_objects and read_property show 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)

ParamDefaultBoundsMeaning
endpointrequiredopc.tcp://host:port/path; no user info, query or fragmentThe endpoint URL. The link connects to this URL even when the server advertises another host or port (NAT, relays).
security_policyNoneNone, Basic256Sha256, Aes128_Sha256_RsaOaep, Aes256_Sha256_RsaPssSecurity policy of the secure channel.
security_modenonenone, sign, sign_and_encryptnone goes only with policy None; sign/sign_and_encrypt only with the others.
identityanonymousanonymous, username, certificateThe user identity token.
username""required for usernameA user identity to another host needs security mode sign or sign_and_encrypt (section 5).
password""secret
user_cert_pem""PEMThe X.509 user certificate (certificate).
user_key_pem""secret, PEMIts 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""PEMThe application instance certificate. Empty: the link makes a self-signed one (section 5).
key_pem""secret, PEMIts RSA key. With cert_pem or not at all. Written to a plain-text file while the connection opens (section 5).
server_cert_pem""PEMPin: only this server certificate is trusted.
trust_on_first_usefalseTrust the first server certificate seen, then only that one.
application_uriurn:wyrm:opcua:clienta URIThe client’s application URI (in the certificate it makes).
session_timeout_ms6000010000…3600000Requested session timeout. Keep-alive reads run every third of it (1…30 s).
request_timeout_ms5000100…60000Bound on each service request (Read, Write, Browse).
connect_timeout_ms150001000…120000Bound 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)

ParamDefaultBoundsMeaning
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_read5001…10000Nodes per Read request. The link lowers it to the server’s MaxNodesPerRead (read at connect, i=11705).
ping_s5.00.1…3600Ping period: a Read of Server_ServerStatus_State (i=2259).

Point (add_point)

ParamDefaultBoundsMeaning
node_idrequiredns=2;s=Line1.Temp, ns=3;i=1001, nsu=<uri>;s=…, g=<guid>, b=<base64>, or s=… / i=… in the device’s namespace.
poll_s1.00.01…86400Poll period. Points with one period on one device are read together.
writablefalse~set allowed.
scale1.0not 0Value = raw × scale + offset (numbers and arrays of numbers).
offset0.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 UAWYRM
Booleanbool
SByte, Int16, Int32, Int64integer (Int, or UInt when ≥ 0)
Byte, UInt16, UInt32, UInt64UInt
Float, Doublefloat
Stringstring (null string → null)
DateTimeRFC 3339 string
ByteStringbytes
LocalizedTextits text
NodeId, ExpandedNodeId, QualifiedName, Guidtheir text form
StatusCodeUInt (the code)
arrays of thesearray (a matrix is flattened)
emptynull
ExtensionObject, XmlElement, DataValue, DiagnosticInfopoint 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:

  1. 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.
  2. It undoes scale/offset: raw = (value − offset) / scale.
  3. It converts and refuses lossy conversions with invalid_parameter and 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).
  4. 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/:

PathContent
own/app-<hash>.der, private/app-<hash>.pemThe 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>.pemcert_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, …/rejectedServer 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-okMarks 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 with trust_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):

SettingWhat is trusted
server_cert_pem (pin)Only that certificate.
trust_on_first_use: trueThe 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 has tofu-ok, the link empties trusted/ 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 at info (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 username or certificate identity, 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 policy None works (the error says so).
  • A user identity (username or certificate) to another host needs security mode sign or sign_and_encrypt; add_connection/edit refuse it with mode none, 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 sign channel (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_encrypt has no such limit: the channel encrypts the token.
  • key_pem must be the key of cert_pem, and user_key_pem the key of user_cert_pem (a test signature must verify with the certificate); add_connection/edit refuse another key.
  • endpoint is 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 none to another host shows a warning on its status leaf (attr.warning): values travel unsigned and unencrypted.

6. Errors and quality

What happensResult
The item’s status is Goodthe 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 serverthat point bad/device_error
One Read request of a poll times out (request_timeout_ms) while another answersthe 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 outdevice 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 Readthose 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

NodeActionLevelArgsResult
devicebrowseconfignode (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)
connectionget_endpointsconfig—[{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 error leaf, 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.https or WebSockets transports, only opc.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”, rsa 0.9 under async-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 sign and sign_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_uri shares; 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 own application_uri (so its own key), or its own cert_pem/key_pem. Basic128Rsa15 (PKCS#1 v1.5 padding, the classic padding oracle) is not offered. When cargo audit or cargo deny runs in CI, this advisory needs a tracked ignore with this rationale (neither runs in CI today).

  • The bound on one poll is (request_timeout_ms + 1 s) per Read request. It counts the requests with the server’s MaxNodesPerRead as the last open of that endpoint read it (the framework’s poll_timeout gets 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 reports PLC 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) or 0x03 (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

ParamDisplayDefaultBoundsMeaning
hostHost(required)IP address or host name of the PLC or its CP
portPort1020…65535ISO-on-TCP port
rackRack00…7rack of the CPU
slotSlot10…31slot of the CPU: 1 for S7-1200/1500, 2 for S7-300, as configured for S7-400
conn_typeConnection Typepgpg, op, s7_basicconnection resource of the remote TSAP (PG 0x01, OP 0x02, S7 basic 0x03)
timeout_msTimeout (ms)2000100…10000bound on each request and on each step of connecting
pdu_sizePDU Size480240…960the 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

ParamDisplayDefaultBoundsMeaning
pingPingszlszl, read, noneszl: read SZL 0x0011 (module identification); read: read 1 byte at ping_address; none: no ping
ping_addressPing AddressMB0an addressthe byte that ping = read reads
ping_sPing Rate (s)50.1…3600time between pings
max_gapMax Gap (bytes)40…256points of one area and DB at most this many bytes apart are read as one item; 0 = only touching ones
max_itemsMax Items per Read201…20items in one Read Var request
tz_offset_minPLC Clock Offset (min)0−720…840the offset of the PLC clock from UTC, for DATE_AND_TIME values
republish_sRepublish Unchanged Values (s)00…3600publish 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

ParamDisplayDefaultBoundsMeaning
addressAddress(required)see belowwhere the value is
dtypeData Typeautosee belowthe data type
poll_sPoll Rate (s)10.01…86400time between reads
scaleScaling1not 0published = raw × scale + offset (numbers only)
offsetScaling Offset0
writableWritablefalsethe point takes ~set (not on inputs, timers and counters)
unitUnit“”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.

AreaBitByteWordDouble word
Data blockDB10.DBX4.3DB10.DBB5DB10.DBW6DB10.DBD8
Bit memoryM1.0, MX1.0MB1MW20MD24
Inputs (I or E)I0.1, IX0.1, E0.1IB0IW2ID4
Outputs (Q or A)Q1.0, QX1.0, A1.0QB1QW2QD4
TimersT5
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.

dtypeSuffixBytesWidthPublished as
boolBOOL1 bitXbool
byteBYTE1Bnumber 0…255
wordWORD2W, B, T, Cnumber 0…65535
dwordDWORD4D, Bnumber 0…4294967295
intINT2W, Bnumber −32768…32767
dintDINT4D, Bnumber
realREAL4D, Bnumber (the shortest decimal of the float: 0.1, not 0.10000000149)
lrealLREAL8Bnumber
stringSTRING[n], STRINGn + 2Btext; 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
s5timeS5TIME2W, B, Tseconds (number)
timeTIME4D, Bseconds (number; TIME is DINT milliseconds)
date_and_timeDATE_AND_TIME, DT8BRFC 3339 text
counterCOUNTER2Cnumber 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 n is less than the PLC’s maximum, the text is cut to n characters.
  • 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 (Z for 0, else +02:00 and so on). A write takes any RFC 3339 time (Z or an offset, T or 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 with dtype = word the raw timer word.
  • Counters (C3): with dtype = word (the default) the raw counter word; with C3:COUNTER the 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. Use word and compare with the PLC before you use counter.
  • scale and offset apply 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:

  1. merges the points of one area and DB into spans when they are at most max_gap bytes apart (timers and counters: max_gap / 2 numbers);
  2. cuts a span that is longer than one reply item into several items (a reply item carries at most PDU − 18 bytes);
  3. packs the items into Read Var requests. A request carries at most max_items items, and both the request (12 + 12 × items bytes) 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, whatever n says.
  • A value longer than one request (a long STRING on a small PDU) goes in parts of at most PDU − 28 bytes, 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 not writable refuses ~set.

Errors and quality

What happensError classResult
I/O error, closed socket, COTP disconnect, garbled frametransportthe 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_msdevicethe 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…)pointthe points of that request are bad; the device stays connected
item return code (PLC item error 0x…)pointthat 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.

NodeActionLevelArgumentsResult
connectionconnection_info (Connection Info)read{pdu_size, max_amq_calling, max_amq_called, local_tsap, remote_tsap, late_replies}
deviceread_szl (Read SZL)configid (number), index (number, 0){id, index, record_length, records, more}, and order_code for SZL 0x0011
deviceread_address (Read Address)configaddress, 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)

ParamDefaultBoundsMeaning
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.
port1611…65535Agent UDP port.
community— (required, secret)Community string. Entered in add_snmp_v2c/edit, kept sealed; never shown.
timeout_ms1000100…10000Bound on each request.
retries10…5Repeats of a request after a timeout.

Connection snmp_v3 (Add SNMP v3)

ParamDefaultBoundsMeaning
host, port—, 1611…65535As above.
user— (required)1…32 charactersUSM user name.
auth_protocolsha256sha1, sha256usmHMACSHAAuthProtocol (HMAC-SHA-96) or usmHMAC192SHA256AuthProtocol (RFC 7860).
auth_passphrase— (required, secret)≥ 8 charactersAuthentication passphrase.
priv_protocolaes128aes128, noneAES-128-CFB (RFC 3826), or none for authNoPriv.
priv_passphrase"" (secret)≥ 8 characters with aes128Privacy 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, retries1000, 1as 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

ParamDefaultBoundsMeaning
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_varbinds201…100Scalars per GET request.
max_repetitions251…100Rows per GETBULK request (table columns, walk).
max_pages201…200GETBULK requests per table column and poll.
pingtruePing the device.
ping_s100.1…3600Ping period (s).
republish_s00…3600Publish an unchanged value again after this long (0 = on a change only).

Point

ParamDefaultBoundsMeaning
oid— (required)≤ 128 arcsNumeric 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.
kindscalarscalar, table_columnscalar: GET of oid. table_column: the cell oid.index, read by GETBULK.
index""dotted numbersRow index of a table_column point (3, 1.4.192.0.2.1); refused on a scalar.
convautosee §3Value conversion.
scale, offset1, 0scale ≠ 0value = raw × scale + offset, numeric conversions only.
unit""Shown in ~meta.unit.
poll_s100.01…86400Poll period (s).
writablefalseThe point takes ~set (SET).
set_typeintegerinteger, octet_string, gauge32SMI 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

convTakesGives
autoanyINTEGER → 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.
counter32Counter32the raw counter
counter64Counter64 or Counter32the raw counter
rate_per_sCounter32 or Counter64(new − old) / seconds between two polls; see below
gaugeGauge32, INTEGER, TimeTicks, countersthe number
timeticks_sTimeTicksseconds (hundredths / 100)
stringany but NULLtext, as auto gives it
ipIpAddress, OCTET STRING of 4 or 16 octetsIPv4 or IPv6 text
macOCTET STRING of 6 octets00: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_varbinds per 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_pages requests per column and poll. Rows the column does not have are point errors (noSuchInstance).
  • An answer with tooBig splits 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, noSuchInstance and endOfMibView fail 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:

CounterCounts
late_repliesAnswers 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_repliesv3 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_repliesDatagrams 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 happensResult
noSuchObject / noSuchInstance / endOfMibView, a conversion that does not fit, a value whose encoding does not fit its type, an error status for one varbindThat point bad; the device stays connected.
No answer within timeout_ms × (1 + retries) to any request of a pollA 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 answeredThe points of that request uncertain/stale, after 3 polls in a row bad/comm_fail; the device stays connected.
authorizationError on a poll or pingThe device failed: “authorizationError: the agent’s access control (VACM) refuses this request; check the community, user or context”.
v3 report usmStatsWrongDigests, usmStatsUnknownUserNames, usmStatsUnsupportedSecLevels, usmStatsDecryptionErrorsWhen 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 snmpUnknownContextsThe 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 idThe 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 hasNot 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 opensThe 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’s data_dir, never in ~meta, export, replies or logs. No datagram is ever logged (a v2c datagram holds the community). Bootstrap params in wyrmd.json5 are 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.warning of its status leaf; use snmp_v3 with aes128 beyond a trusted network. A v3 connection with priv_protocol: none beyond 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’s snmpEngineID, e.g. from snmpget -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 in engine_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 show stopped_by_parent for a moment), learns the clock again, and the warning on its status clears. 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 (or wyrmd for an embedded link) forgets it too.
  • Walk is a config action: 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 a read or write caller 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

ObjectOIDPoint
sysDescr1.3.6.1.2.1.1.1.0scalar, string
sysUpTime1.3.6.1.2.1.1.3.0scalar, timeticks_s
sysName1.3.6.1.2.1.1.5.0scalar
ifDescr1.3.6.1.2.1.2.2.1.2table_column, index = ifIndex
ifOperStatus1.3.6.1.2.1.2.2.1.8table_column (1 up, 2 down, …)
ifInOctets / ifOutOctets1.3.6.1.2.1.2.2.1.10 / .16table_column, rate_per_s (Counter32)
ifName1.3.6.1.2.1.31.1.1.1.1table_column
ifHCInOctets / ifHCOutOctets1.3.6.1.2.1.31.1.1.1.6 / .10table_column, rate_per_s, scale: 8 for bit/s
hrProcessorLoad (HOST-RESOURCES-MIB)1.3.6.1.2.1.25.3.3.1.2table_column, gauge, unit %
hrStorageUsed / hrStorageSize1.3.6.1.2.1.25.2.3.1.6 / .5table_column, gauge (× hrStorageAllocationUnits .4)
upsBatteryStatus (UPS-MIB)1.3.6.1.2.1.33.1.2.1.0scalar (2 normal, 3 low, 4 depleted)
upsEstimatedChargeRemaining1.3.6.1.2.1.33.1.2.4.0scalar, unit %
upsInputVoltage1.3.6.1.2.1.33.1.3.3.1.3table_column, index 1, unit V
upsOutputPercentLoad1.3.6.1.2.1.33.1.4.4.1.5table_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_s uses the link’s clock at each answer, not the agent’s sysUpTime deltas; 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>
LevelIsExample
ConnectionA base URL with its authentication, TLS, default headers and rate limit.https://10.0.1.20/api, bearer token
DeviceOne request below the base URL: method, path, query, body.GET /v1/status
PointA 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)

ParamDefaultBoundsMeaning
base_urlrequired—http:// or https://, host, port, path prefix. No user, password, query or fragment in it.
timeout_ms5000100…60000Bound on connecting, and on each request (reply and body).
authnonenone, basic, bearer, api_keyHow requests authenticate.
username""—User for basic.
password""secretPassword for basic.
token""secretThe token for bearer; the key for api_key.
api_key_inheaderheader, queryWhere api_key puts the key.
api_key_nameX-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""secretThe private key of cert_pem (PEM).
insecure_skip_verifyfalse—https: accept any server certificate. The handshake signatures are still checked.
insecure_plaintextfalse—Allow credentials over http:// to a host that is not loopback.
headers""32 lines, 8 KiBDefault 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""secretIts value.
rate_limit50.1…1000Requests per second on this connection (all its devices and actions).
max_body_kib40961…65536A longer reply is a device error.

Rules (an add_* or edit that breaks one is refused with invalid_parameter and changes nothing):

  • basic needs username (no : in it); bearer and api_key need token.
  • ca_pem, cert_pem and insecure_skip_verify only with https://; ca_pem and insecure_skip_verify not together; cert_pem needs key_pem. A PEM that does not parse is refused at once.
  • Credentials are never sent over http:// to a host that is not loopback, unless insecure_plaintext is set. The connection then shows a warning on its status leaf (attr.warning), as with insecure_skip_verify.
  • headers may not set Host, 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 sends Accept-Encoding: identity), Authorization, Proxy-Authorization, Cookie, the API key header or the secret header, nor a header whose name holds auth, token, key, secret, session, cookie, password, passwd or credential: headers is not secret (it shows in ~meta and export, and it is not masked). Credentials belong in auth, or in secret_header_name and secret_header_value.
  • secret_header_name needs secret_header_value, and it may not be a framing header, the API key header, or Authorization with basic or bearer. A secret header counts as credentials for the plaintext rule.
  • The device query and a point’s write_path are not secret either: never put a key in them (use api_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)

ParamDefaultBoundsMeaning
methodgetget, postThe 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 KiBJSON body, post only (sent as is, with Content-Type: application/json).
expect_status200-299100…599, 16 rangesStatus codes that count as a good reply: 200-299,304.

Point (add_point)

ParamDefaultBoundsMeaning
pathrequired512 characters, 32 segmentsSelector into the reply (section 3).
typenumbernumber, bool, stringThe value type (section 4).
aggregatenonenone, first, sum, max, min, avg, countHow several matches become one value. none = exactly one match.
scale1≠ 0Numbers: value = raw × scale + offset.
offset0—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_s100.1…86400Poll period. Points of a device with one period share one request.
writablefalse—The point takes ~set (level write).
write_methodputput, post, patchMethod of a write.
write_path""—Path and query of a write below the base URL; empty = the device’s.
write_body{{value}}64 KiBJSON 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:

SelectorSelects
$the whole reply
$.a.bmember 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")].vv 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

typeFrom JSONResult
numbernumber; string with a number (" 230.1 "); true/false as 1/0float, × scale + offset
booltrue/false; number (≠ 0 = true); string: bool_true/bool_false, or "true"/"false" (any case) when they are emptybool
stringstring; a number, bool, object or array as its JSON textstring

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 of bool_true/bool_false as 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 happensClassEffect
Connection refused, DNS, TLS failure, a broken sockettransportThe connection goes failed with error, its devices stopped_by_parent, points bad/disconnected; reconnect with backoff (1 s…60 s).
No reply within timeout_msdevice missFirst miss: points uncertain/stale; after 3 misses the device failed with error, points bad/comm_fail.
Status outside expect_status (4xx, 5xx, …)device missAs 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 hostdevice missAs 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”)pointThat 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 PIN 0123 hides the number 123 (and the text "0123"), but not 1234 or 51234.5. The values 0 to 9 are too common and are never matched as numbers (the PIN 0000 leaves the reading 0 alone; the text "0000" is still hidden). A matched number shows as "***";
  • a number point whose match is masked fails with “value hidden: it holds a connection secret” (quality bad). This also happens to a reading that equals a numeric secret by chance, as long as it holds that value: with the PIN 0100, a level of 100 goes bad each time it is 100 (an explicit error, never a wrong value). A count of masked matches is not hidden;
  • a point whose filter compared a masked value ([?(@.id == 1234)] with the PIN 1234, [?(@.level > 50)] on a level equal to it) fails with “value hidden: a filter compared a value that holds a connection secret” (test_selector gives it as error), never a count one too low or another element;
  • member names in what is shown (a string point of an object, try_request, test_selector values) 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 a try_request body;
  • a bool shows 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, Authorization and 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). bytes is the reply’s length, or the masked text’s length when masked; a masked reply shows the allowlisted headers only (section 6), and hidden_headers counts the others. A JSON reply is also kept for test_selector.
  • Test Selector (test_selector {path, type?, aggregate?}): runs a selector against the last JSON reply of the device’s request (a poll’s or try_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, with type, value (a string cut at 8 KiB) or error as 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 answers not_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:

EndpointReply
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/echothe request’s headers and query
GET /api/resource, PUT/POST/PATCH /api/resourcea 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/donewrites redirected with 301, 302, 307 (nothing applied); done merges, then 303
GET /redirect/<n>, GET /offsiteredirect 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_period sees only the point). Points of a device with different poll_s send 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-Encoding is not sent); no proxies; no cookies or sessions (a Cookie header 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 (administrator with the password admin shows ***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 0100 and a level of 100), and so does a point whose filter compares such a reading: the point flaps bad. 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 config user who can put candidates into a device’s query or headers on 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 a config user of an echoing server.
  • Member names stay raw for selectors (so $.adminState works). 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 (%2f in lower case, + for a space) or HTML entities in an error page.
  • System CAs (ca_pem empty) are loaded once per process, at the first https:// 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_FILE and SSL_CERT_DIR work in an embedded link; a process link gets a cleared environment, so there they do not apply: give ca_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 (raw or rate_per_s) and a function (value or histogram_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

  1. Install the driver: sys/links ▸ Install Link ▸ from Driver, driver prometheus (or the package prometheus from a repository).
  2. On the link ▸ Add Connection: name, URL, and the other params in section 3.
  3. On the connection ▸ List Series shows what the endpoint serves.
  4. On the connection ▸ Add Device: name, Label Filter (empty = all series).
  5. 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

ParamDefaultBoundsMeaning
url(required)http:// or https://, no user infoThe endpoint. IPv6 as [::1].
timeout_ms5000100 … 60 000Bound on one scrape: connect, TLS, headers and body.
scrape_s151 … 3600Time between two scrapes.
username""no :Basic auth user.
password""secretBasic auth password.
bearer_token""secretAuthorization: Bearer … instead of basic auth.
ca_pem""PEMCA certificates for https; empty = the system roots.
cert_pem""PEMClient certificate for mutual TLS.
key_pem""secret, PEMPrivate key of cert_pem.
insecure_skip_verifyfalseAccept any server certificate. For tests only: the status leaf shows a warning while it is on.
headers""at most 32Extra request headers, one Name: value per line. Not for credentials.
gziptrueSend Accept-Encoding: gzip and decode gzip bodies.
max_body_mib81 … 64Bound 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_series100 0001 … 1 000 000Bound 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_pem and insecure_skip_verify need an https:// URL. cert_pem and key_pem go together. A PEM that does not parse is refused.
  • Give username/password or bearer_token, not both. A password needs a username.
  • Credentials are never sent in plaintext to a host that is not loopback: use https://.
  • headers may not set Authorization, Proxy-Authorization, Cookie, Host, Content-Length, Transfer-Encoding, Connection, Accept-Encoding or TE.

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

ParamDefaultMeaning
labels""Label matchers applied to every point of the device, with or without braces: instance="a", job=~"node.*". Empty = all series.

Point

ParamDefaultBoundsMeaning
selector(required)a metric name is requiredname or name{matchers}.
aggregatenonenone, sum, max, min, avg, countHow the matching series become one value.
moderawraw, rate_per_srate_per_s: increase per second between two scrapes.
functionvaluevalue, histogram_quantilehistogram_quantile: the q quantile from the _bucket series.
q0.50 … 1The quantile for histogram_quantile.
scale1The point value is value · scale + offset.
offset0
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:

aggregateValueNo series matches
nonethe one matching series; more than one is a point errorpoint error
sum, max, min, avgover all matching seriespoint error
countthe number of matching series0

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 happensClassEffect
connect refused, DNS, TLS or I/O error, broken responseconnectionconnection 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 memoryconnectionas above; the error names the param
no complete response within timeout_msdevice misspoints 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 missas 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)pointthat point bad; its device stays connected
histogram_quantile with rate_per_s: a new bucket, or no observations in the intervalnoneno 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)nonethe 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}, level config: 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_ms and series, each with name, type (from # TYPE), labels and value ("NaN", "+Inf", "-Inf" as text). match is a selector (empty = all), limit 1 … 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:

  1. Start the simulator (above).
  2. Add a link with driver prometheus and a connection with URL http://127.0.0.1:9101/metrics and scrape_s 5.
  3. Run ▸ List Series on the connection.
  4. Add a device with Label Filter instance="a", and a point with Selector sim_temperature_celsius.
  5. Add a point with Selector sim_requests_total, Aggregate sum, Mode rate_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: no by/without grouping, no arithmetic between series, no range functions other than the rate between two scrapes, no offset.
  • 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_mib of 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 names max_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): keep max_body_mib at 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. # TYPE and # UNIT lines past max_series names 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)StoresCrate
s3AWS S3, MinIO, Ceph RGW, Cloudflare R2, Wasabi, Backblaze B2, DigitalOcean Spaces, Google Cloud Storage (HMAC keys)links/s3
gdriveGoogle Drive: My Drive, a folder shared with a service account, a shared drivelinks/gdrive
webdavNextcloud, ownCloud, Synology, QNAP, Apache/nginx DAV, rclone serve, pCloud, Yandex Disk, …links/webdav
localfsa directory of the host: a local disk, a USB stick or SD card, an NFS / SMB / sshfs mount, a NAS volume, a sync folderlinks/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 attr holds name, path (below the root), modified, etag and content_type when 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

NodeActionLevelWhat it does
rootAdd S3 Bucket / Google Drive / WebDAV Folder (add_connection)configa new connection: its name and params (below)
connectionEdit, Remove, Stop / Startconfigsecrets left empty in Edit keep the stored ones (while the destination stays the same)
connectionRefreshreadread the whole tree again → {entries, truncated}
folder (and files)Refreshreadread 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
folderDelete {recursive?}writewithout recursive the store itself is asked whether the folder is empty (not the tree, which may miss hidden names, deep levels and new files)
fileDownload {text?}readthe bytes (or UTF-8 text with text)
fileDeletewrite

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):

ParamDefaultRange
refresh_s3000, 5–86 4000 = only on Refresh
max_entries20001–9000more are left out; the connection says truncated
max_depth81–12folder levels shown
max_upload_mib321–64Upload File in one request
max_file_mib40961–65 536a 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_kib10241–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)

ParamDefault
endpointhttps://s3.amazonaws.comAWS https://s3.<region>.amazonaws.com; MinIO https://minio:9000; R2 https://<account>.r2.cloudflarestorage.com; GCS https://storage.googleapis.com
regionus-east-1R2 and GCS: auto
bucket—
addressingautoauto = 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_ms10000
ca_pem, insecure_skip_verify, insecure_plaintextTLS; 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)

ParamDefault
authservice_accountor 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_idrootthe 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
trashtrueDelete moves to the trash; false deletes for good
timeout_ms15000
api_url, token_urlGoogle’sa 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)

ParamDefault
url—the collection: Nextcloud https://<host>/remote.php/dav/files/<user>/<folder>
authbasicnone, basic, bearer
username, password (secret)—Nextcloud and ownCloud: an app password
token (secret)—auth: bearer
timeout_ms10000
ca_pem, insecure_skip_verify, insecure_plaintextas 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):

NodeActionLevel
folder (and files)Upload in Parts (upload_begin {name, size, part_size?, content_type?, overwrite?, sha256?})write→ {upload, part_size, parts}
connectionupload_part {upload, index, data}writeone part, from index 0; any order, again after a cut
connectionupload_status {upload}writestate (receiving, committing, done with result, failed with error), missing parts
connectionupload_commit {upload}write→ committing; the file goes to the store in the background
connectionupload_abort {upload}writedrops it and its parts
filedownload_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_size bytes. A file is at most max_file_mib (4 GiB by default). Send parts through the gateway’s POST /api/invoke (data is editor: 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 WebDAV PUT, a copy for localfs. Memory holds one part, not the file.
  • The link keeps 1 GiB free on the disk of its spool. upload_begin refuses a file larger than the free space minus 1 GiB (resource_exhausted). Each upload_part checks 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 sha256 at 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 206 reply must carry a Content-Range that 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}. size is the file’s real size: from the 416 reply of S3, Google Drive and WebDAV (Content-Range: bytes */<size>), or from the disk for localfs. Refresh the folder to see the new size. A 416 without 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).

ParamDefault
root—an absolute path: /srv/plant/reports, /mnt/usb, /Volumes/NAS/share, D:\reports, \\nas\share
create_rootfalsecreate it (and its parents) when missing
read_onlyfalserefuse Create Folder, Upload File and Delete
show_hiddenfalseshow names starting with .; while off they are not written either
follow_symlinksfalseshow symbolic links that resolve inside root (others are never shown)
fsynctruesync each upload and its folder (power loss; slower on SD cards)
timeout_ms10000bound 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 of root are never shown or followed; deleting a link deletes the link, not its target.
  • root may 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 `/ \ < >
    “ | ? *, no CON, NUL, COM1…, no.` or space at the end.
  • An upload with overwrite goes 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 answer timeout at 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 connection Failed with the error leaf; 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 disconnected or timeout and 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, keys AKIASIM / 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, user alice, password sim-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.

LinkPackagesGuideCan
telegramtelegram (WASM), telegram-processtelegram.mdsend; chat users with /get, /set, /do; command buttons
slackslack (WASM), slack-processslack.mdsend; 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):

  1. sys/links ▸ Install Link ▸ from Repository: telegram / slack (WASM) or the -process package.
  2. Give it network: api.telegram.org:443 or slack.com:443 in the link’s net.
  3. Grant what templates (and chat users) may name (sys/links/<id>/~act/grant): read on, say, wy/<site>/downstream/**; write on the points chat users may /set or /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 (limit above): the Send form has a field for it; one the send leaves out shows as n/a (Preview shows it so too).
  • {{alias}} — a live value from values ({{alias:.1}} decimals, {{alias.q}} quality, {{alias.t}} time); n/a until it has one, and for a key the template’s author may not read (.q then says bad). 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; /command runs a chat command for whoever presses it, within that person’s own pairing.
  • Slack: blocks takes Block Kit JSON; put placeholders inside JSON strings ("text": "*{{who}}* is at {{temp:.1}}"). text is the notification fallback.
  • photo / document: media is an https:// URL (Telegram also takes a file_id); text is 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} and recipients/<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 need chat_id);
  • forwardMessage, forwardMessages, copyMessage, copyMessages (need chat_id and from_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.

  1. ▸ Invite User {name, level, select} (config). level: read (/get) or write (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.
  2. The answer shows a pairing code once, valid 15 minutes, single use. Give it to that person only (not in a group chat).
  3. 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>/status becomes active.

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>/rejected and 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 &amp;, &lt;, &gt;) 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 (&amp;, &lt;, &gt;) 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:

WhatWhere it comes from after a startLost by a kill (SIGKILL, power)
Links, ACL, PKI, tokens, peers, profiles, flow definitions, users, history settingsthe control-plane WAL (state/, flows/, gateway/, audit/), every append fsynced; a snapshot only speeds the start upnothing; 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 ~valthe links: each one re-declares its subtree and its last values when it sees the broker’s liveliness token wy/<site>/sys/broker againnothing; values are back as soon as each link polls again
Values of storage, scheduler events, alarm records, DQL queries, uplinks, runtime edits of driverstheir redb files and sealed stores in data_dir (every write is synced)nothing
History rowshistory/days/*.redbthe rows still in the write buffer: up to buffer_flush_time of each watch group (5 s by default)
Gateway sessionsnothing: users log in again (the explorer’s client reconnects and reopens its streams)all
A set or an action in flightnothing: the caller gets an error and repeats itthat one request
The audit journalaudit/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 fsync that covers its record; a failed write is logged as audit write failed.
  • A record a link reports for its own set/invoke was 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>: “n records 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.json says trial, §2: from the moment the update is staged until update_confirmed), the journal writes record by record: one write, one fsync, 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 one fsync per record for those minutes (the rate of before); after the confirmation it writes batches again. The same holds from the moment rollback_update is asked for a confirmed update (update.json names 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 run wyrmd verify and then wyrmd 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 fsync that 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 with the store takes no more writes until it is opened again, an audit record is logged as audit 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_dir must belong to the user the broker runs as. The broker makes it 0700 when wyrmd keys import writes state.key and the other key files into it, and a standby does the same when it copies secrets.bin and 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 (below data_dir), or that another user owns, is refused with its path, and the broker does not write keys into it. data_dir itself may be a symlink the operator set up (/var/lib/wyrm → /srv/wyrm).
  • wyrmd stops 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 a KillMode of control-group is a belt on top of braces.
  • Restart=always with RestartSec=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/StartLimitBurst in [Unit] stop that if you prefer a loud failure. wyrmd -c … check validates a configuration before a restart.
  • WYRM_GATEWAY_ADMIN_PASSWORD is 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=always the 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.
  • wyrmd as a container: one container per broker, data_dir on a volume, restart: unless-stopped (compose) or a restart policy of the orchestrator, stop_grace_period of 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 CN gateway:<site> and writes it to data_dir/gateway/tls.pem and tls.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) when listen is 0.0.0.0 or [::], else only the listen address. On Linux (OpenWrt too) the broker reads /proc/net/if_inet6 and 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, set listen to one address. The host name is cut at its first dot; a host whose name cannot be read uses wyrm-<site>. While the host has no usable address (before DHCP), the certificate names only the .local names; 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/info names and the device-key origins follow the new certificate at the same time.
  • Clients trust data_dir/pki/ca.pem. ca_fp in GET /api/info, the fp key of the DNS-SD announce and wyrmd ca fingerprint are 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: wyrmd does 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.
  • tls excludes tls_cert/tls_key. A certificate from a public CA (for the remote MCP connector, claude.md) still goes in tls_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.

  1. 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 no wyrmd.json5.

  2. 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" },
    
  3. 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.

  4. Start the broker. While no user exists, it moves the hash into data_dir/gateway/setup.hash (0600) and deletes setup_file. The log says gateway: setup code taken in.

  5. The person opens Studio. GET /api/info shows setup: 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:

  1. Read GET /api/info over TLS, accepting the certificate for now. With a setup pending and TLS on, the answer holds ca (the DER of the CA) and setup_proof: HMAC-SHA-256 keyed with the setup hash over "wyrm-setup-proof-v1\n" and the bytes of ca.
  2. Compute the hash from the typed code and verify setup_proof against the ca it was shown (wyrm_gateway::setup::verify_setup_proof). Check that the certificate of the connection chains to that ca. 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.
  3. Only then send POST /api/setup {code, user, password} on a connection that trusts that ca alone.
  4. Pin that ca for 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 reason setup_code_wrong; the first admin as a user added by setup. Neither the code nor its hash is logged.
  • Once a user exists, a setup is void. A setup_file is then ignored and deleted, and a setup.hash (a restored backup, a crash between the new admin and the removal) is deleted at the next start. /api/setup answers 409 no_setup.
  • A setup_file that is not 64 hex digits (white space around them aside) stays where it is, with a warning in the log that names it. A setup_file that cannot be deleted is a warning too; it is void once a user exists.
  • A damaged data_dir/gateway/setup.hash with no user is logged at start with its path and reason, and /api/info shows no setup. To recover, stop the broker, make a new code with wyrmd setup-code, write its hash into setup_file, and start again: the new hash replaces the damaged file.
  • WYRM_GATEWAY_ADMIN_PASSWORD still 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 own setup_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 its setup_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" }
  ]
}
  • format must be wyrm-seed/1. An unknown field is an error. link is the id of the new link. file is a package zip (as for install_zip) in the same directory. accept (default false) is the Accept requested rights of install_zip: without it, a package that asks for a network allowlist or grants is not installed.
  • file is 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 for install_zip (64 MiB).
  • On the first start, once the router listens, the broker installs each entry as sys/links ▸ install_zip does, with the same checks, as the subject broker: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 with install_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 says seed: link <id> installed, … skipped (exists), or a warning with the message.
  • The seed runs at the first start that finds seed.json and no seed.done. Normally that is the first start. A broker that has run for a long time without a seed (a seed_dir with no seed.json) also installs the links of a seed.json that an image update adds, at its next start.
  • To run the seed again, delete both data_dir/seed.done and data_dir/seed.progress.json and restart. Links that exist are skipped, failed entries are tried again. With seed.progress.json left 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.done and 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 when seed.done is written. A run that stops before seed.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: … in seed.done and does not install it again. Check the link and its package: install it again with install_zip, or remove it;
    • the other entries are tried.
  • A warm standby (ADR 0036) receives seed.done and seed.progress.json with 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 as skipped: the link exists (the registry has the link, the copied progress file does not) or as started and not finished on 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 as started and not finished at the next run. The link is there; check it as above.
  • A seed.json that is missing or cannot be read (bad JSON, another format, a link listed twice, more than 256 links) installs nothing and writes no seed.done. The broker logs a warning and tries again at every start. A seed.progress.json that cannot be read does the same.

Recovery time

The recovery time (RTO) of a restart is the sum of:

  1. the supervisor’s delay (RestartSec);
  2. the router build: the state is read from the snapshot and the WAL tail, the ACL generated, the listeners opened — one to three seconds;
  3. embedded links: started at once with the router;
  4. 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 connect warning per start) and its next one comes 1 s later; then it opens its mTLS session and sends hello. A refused connect and hello are 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);
  5. 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_ENDPOINT takes 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 token wy/<site>/sys/broker: a router without the token, or whose token has been gone for WYRM_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 its client() 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:

  1. Both wyrmd.json5 files are the same but for the addresses, and both have a QUIC peer listener and a standby section naming the other host (tls_names must 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: true on one host only: it takes over after takeover_s, the other after three times that, and when both are active after a network split, the other steps down.

    witness is 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 of takeover_s, before the other side can take over. Keep takeover_s at 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 arbiter the broker logs a warning at start.

  2. 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
    
  3. On host B, with an empty data_dir:

    WYRM_KEYS_PASSPHRASE='…' wyrmd -c wyrmd.json5 keys import site-keys.wykb
    

    then delete the file on both hosts: it is the site.

  4. Start wyrmd on host B as on host A (section 2). It logs standby: following; host A shows sys/standby_connected 1 and sys/standby_lag 0 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> (and flows/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’s export action, for import).

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.arbiter grants 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:

  1. 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
    
  2. Copy the directory to the third host and run the arbiter under a supervisor, as wyrmd itself:
    wyrmd arbiter serve --dir arbiter-demo --listen 0.0.0.0:7450
    
  3. Add arbiter: ["10.0.0.3:7450"] to the standby section 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.json5 files the same. A link named in host A’s links and not in host B’s is gone after a failover.
  • The standby’s data_dir is 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 in WYRM_ENDPOINT.
  • With state_anchor_dir on the standby, the follower keeps the anchors at its head; a history that forked (a record the standby never got) is moved aside as state.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 shows sys/latest, sys/update_available and, in sys/update_hint, what to run. It never replaces itself: update is refused with that text. Change the image tag where the container is defined and run docker compose pull && docker compose up -d, or install the new package and systemctl restart wyrmd. Make a backup first (section 3).
  • self: sys/~act/update replaces 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
  1. As root, make the layout from the binary you have: wyrmd install-layout /opt/wyrm. It prints the unit lines and names that binary in bin/trusted.json.
  2. 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
    
  3. 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=always
    
    Restart=always is 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 in RestartPreventExitStatus, 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.
  4. systemctl daemon-reload && systemctl restart wyrmd. sys/update_hint is empty when the layout and the guard are in place; else it says what is missing, and update is 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 current at another release that the key did sign and that is still in versions/ (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.

  1. 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 than data_dir holds or that names a store this version does not know is refused.
  2. 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.
  3. 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 live data_dir is not touched.
  4. A backup of the control plane is made (sys/backups, kind pre-update, sealed for this broker, kept while a rollback is possible).
  5. data_dir/update.json is written, current is switched, the broker stops with code 0, and systemd starts the new version.
  6. The trial lasts trial_s seconds 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_state is then confirmed.
  7. 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 current back, and the old version serves: sys/update_state is rolled_back, sys/update_last.reason says 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_state is failed, the reason is in sys/update_last.reason and in the audit (update_rollback with 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:

  1. Look at the file: ls -l <data_dir>/update.seen and its content. It must be a plain file of the broker’s user, mode 0600, with one number.
  2. If only the owner or the mode is wrong, set them right.
  3. If the content is lost, write the sequence of the index that the channel serves now (the sequence in its index text), when you trust that the channel is current. Then run check_updates.
  4. 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:

  1. Upload wyrmd-<v>-<target>.tar.gz in parts: sys/backups/~act/restore_begin {size}, then restore_part {upload, offset, data}.
  2. Call sys/~act/update {upload, release, signature, confirm_site} with the text of wyrmd-<v>.release.json and of its .sig file.

A standby pair

The standby goes first. It runs no router, so the active carries the order:

  1. Set updates.mode: "self", the same updates.keys, the layout and the unit on both hosts.
  2. 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_update shows ordered <v>, then <v> trial, then <v> confirmed (or rolled_back / failed), and sys/standby_version the version it runs.
  3. When the standby is confirmed, call update for the active (the same arguments without target). It is refused while the standby runs another version or is not confirmed. without_standby: true updates 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:

PathWhat it isWithout it
state/, state.keythe control-plane WAL and the key of its HMAC chainno 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 certificatesevery link, operator, downstream broker and process link needs a new certificate; upstreams must trust the new CA
secrets.bin, secrets.keylink secrets, store keys of every link, the keys of sealed peerslinks lose their credentials; the sealed stores of links and runtime driver edits cannot be opened
gateway/users, roles, the gateway’s signing keyusers gone; whoever holds gateway.key is an administrator, so the backup is as sensitive as data_dir
flows/, flows.keyflow definitions and their signing keyflows 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 storagehistory and stored values gone
audit/the audit journalthe 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 certificatesreinstall, 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 replaceda 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 .metaa 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-backup while 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 with download_part, or let the broker write it into a file store with send (the host names the link and the folder in backups.send_links). One link goes with sys/links/<id>/~act/backup. The keys section and a passphrase need backups.export_secrets: true on the host; without it a backup holds no keys and its link secrets open only on a broker with this site’s keys. Restore with sys/backups/~act/restore_check and restore_apply: mode: add works live; mode: replace restarts the broker once, is refused for a caller that comes through an upstream, and restores keys only with export_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, copy data_dir whole, keep its modes (cp -a, tar --same-permissions), start again. wyrmd -c … verify on 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 cp of a running data_dir may copy a redb file in the middle of a write: do not restore from such a copy without verify and 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:

  1. Stop the broker; move the damaged data_dir aside.
  2. Copy the backup to the configured data_dir, owner the broker’s user, mode 0700 for the directory and the key files.
  3. wyrmd -c … verify. With state_anchor_dir set (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, run wyrmd -c … init-anchors once, with the broker stopped, on a store you trust.
  4. 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.

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:

  1. 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.
  2. Check the files: (cd mirror && sha256sum -c SHA256SUMS).
  3. Write an index with relative URLs: wyr repo index --manifest mirror/official.json --zips mirror --out mirror/index.json.
  4. 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).
  5. 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 a data_dir with this binary (what a broker does with a newer version before it updates to it); it never opens the live data_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>/state and error per link, sys/history/disk_space_remaining; per flow dataflows/<id> (~val: state and the counters stats.samples_in, dropped, commands.error, ADR 0045, flow-blocks.md). The liveliness token wy/<site>/sys/broker is what links and peers watch; a monitor can watch it too (wyr sub).
  • sys/~act/get_log and per-link get_log hold the recent log ring; the level is sys/log_level (RUST_LOG at 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’s secrets, token and files/**, and a link backup’s data. 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 from secrets.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: falseexport_secrets: true
section keysrefusedmade with a passphrase
a passphraserefused, the message names the optionseals keys, link secrets and private data
link secrets and private datasealed for the sitesealed for the site, or with the passphrase
everything elseworksworks
  • A caller whose authority comes from another site (an upstream with allow_config) never gets keys or 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_create carries keys: true|false and secrets: true|false, and the broker logs a warning for a passphrase-sealed backup.
  • sys/backups has the attribute export_secrets for UIs.
  • A refusal by these two rules is permission_denied, with the reason in the message: create, a link’s backup, download_part, and restore_apply (§4; restore_check only reads the file and refuses nothing by rights). No other argument of the same caller passes. A wrong argument is invalid_parameter: keys without a passphrase, a short passphrase, keys that differ without replace_keys. A denied call is counted and logged as every permission_denied of the broker (refused: … in sys ▸ 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 config section is wyrmd.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 of backups, and the like; CONFIG_SHOWN in wyrmd). Every other text is ***, whole: every text under a link’s params, under uplink.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

NodeActionResult
sys/backupsestimate {sections, links?, history_days?}{sections: {name: bytes}, total} before compression
sys/backupscreate {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:

SectionHoldsConsistent because
control (always)the WALs of the registry, the flow store, the gateway users and the auditeach is copied as of one sequence number, checked against its HMAC chain
keysthe site CA, state.key, secrets.key, flows.key, the gateway keys, the flow signing key, secrets.bin, link tokens; all sealedneeds the passphrase
dataflowsthe flow engine’s artifacts; the flow store itself is control/flowscontent-addressed files
storagethe storage tree (tree.cbor) and its JSON exportthe whole tree at one revision
historythe day files of the last history_days days (all without it) and the indexeach file is copied inside one read transaction; days first, the index last
linksper link of links (all without it): link.cbor (its definition, without the token hash), its secrets and private data, sealedfiles as the standby copies them
packagesevery installed package as its files (wyrm-link.json among them). Without this section, the packages of the chosen links still go inversions are immutable
configwyrmd.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.

  1. On the host, name the link and the folder in wyrmd.json5, then restart the broker:
    backups: { send_links: [{ link: "files", folder: "site/backups" }] },
    
    A link id alone (send_links: ["files"]) means the folder backups. One folder for each link. The default is an empty list: send is refused. sys/backups shows the list as the attribute send_links ([{link, folder}]).
  2. Make the folder in the store (Create Folder on the link, or in the store itself). send does not create it.
  3. Call send with link (one of the list) and connection (a connection of that link). The file goes to <connection>/files/<folder>/ under the backup’s own file name.
  4. To give another name or a sub-folder, set path: nightly.wyrm-backup, or 2026/nightly.wyrm-backup (the sub-folder must exist).
  5. The broker begins an upload on the link (upload_begin with the size and SHA-256), answers {to, upload, parts}, and sends the parts (1 MiB each) in the background, then upload_commit.
  6. Read send_status of sys/backups/<id>: sending (with send_progress), done, or failed (with send_error). sent_to is <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. path is a file name or a sub-path of plain names. An absolute path, .., an empty segment, \ or : is refused before the link is called. connection is one name.
  • A narrow token. The broker signs these calls with its backup sender key. Only the links in send_links trust that key (at write, on their own subtree, for the subject broker: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_send in 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 under claimed: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 keys section 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 (busy beyond). A backup that is being sent is not removed or pruned. If the broker stops during a send, start send again.
  • 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.

sys/links/<id>/~act/backup {sections, history_days?, passphrase?} → {id}: a job in sys/backups with kind: link.

SectionHolds
settings (always)the link’s definition: driver, mode, params, grants
dataits 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
packagethe package it runs, as its files
historythe 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}.

  1. Give the file as file (up to 64 MiB through the gateway’s POST /api/invoke), or upload it in parts: sys/backups/~act/restore_begin {size} → {upload, part_size}, then restore_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 by POST /api/invoke, which takes it because data is editor: file), and give upload. restore_abort {upload} drops it. An upload without a new part for an hour is removed.
  2. id is the new link’s id. Without it, the id in the backup is used.
  3. accept: true is needed when the link has requester grants or a network allowlist. Without it, the answer lists them and nothing is installed.
  4. 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. accept covers 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.
  5. 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 remove does, 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 another id. A package that the restore installed stays in both cases.
  6. An existing link of that id must 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 in sys/links/<id>/restore_points and pruned after packages.keep_previous_days. Then the link is stopped, replaced in place and started. To go back, install that file with install_backup on 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:

ActionResult
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: add works live. Sections links and storage. Links that do not exist are installed as install_backup does; storage nodes that do not exist are added. Nothing is replaced. dataflows is skipped with a note: a flow is deployed with proofs of its deployer.
  • mode: replace takes control, keys, dataflows, storage, history, links, packages. A caller whose authority comes from an upstream (allow_config) is refused replace altogether, before the file is read: it would replace this site’s control state, links and packages. add stays open to it, with its accept.
    1. The broker makes a pre-restore backup of the same sections.
    2. 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.
    3. It answers, then stops. The supervisor starts it again (Restart=always).
    4. 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.
    5. 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 gets restore_failed once. If a store did not open, the start that tried ends with a message and the next start runs on the old state.
  • A backup of another site name is refused. Set site in wyrmd.json5 to the backup’s first.
  • A backup whose store SCHEMA is newer than this broker reads is refused.
  • The keys section is restored only through three gates, whatever the keys are (also the keys of this very broker): backups.export_secrets: true on the host, a caller of this site, and the passphrase.
  • replace_keys: true is needed too unless every key file of the backup is byte for byte this broker’s. restore_check answers keys: 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 in keys_differ. With another CA, the certificates it issued are removed; link processes, operators and peer brokers enrol again. The pre-restore backup 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.bin and links/<link id>/token; control/<store>/<file> of the four WAL stores; dataflows/artifacts/**; storage/tree.cbor and export.json; history/index.redb and history/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 control section 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 under control/ 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 of replace checks 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 replace pass the validator of every install (packages::unpack). What a package asks for (requester grants, network) needs accept: 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 in install_backup. With keys, secrets.bin of the backup comes back whole, the broker-made ones among them: they are that site’s own identity, restored under the gates above.
  • control of a backup under other keys is restored only together with keys.
  • With state_anchor_dir set, control is restored offline (docs/operations.md §3).
  • links with control restores the private data of every link of the backup; without control, of the links this broker has.
  • The audit journal is replaced only when state.key is.

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 to path, sealed for this broker (no passphrase, no export_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 .meta beside 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’s info.skipped counts 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.

ADRTitleStatus
0001Zenoh as transport, WYRM as semanticsaccepted · 2026-10-19
0002One wire codec: canonical CBOR via minicboraccepted · 2026-10-20
0003The broker owns only itselfaccepted · 2026-10-20
0004Driver framework inside wyrm-link-sdkaccepted · 2026-10-20
0005AI surface: MCP over the tree, agent as a connectoraccepted · 2026-10-20
0006ACL changes rebuild the router runtimeaccepted · 2026-10-20
0007Peer brokers: QUIC + mTLS, read-only upstreamaccepted · 2026-10-20
0008Flow engine trust and deploy proofsaccepted · 2026-10-20
0009User gateway: sessions, per-request ptok, trust boundaryaccepted · 2026-10-20
0010WASM host for flow nodes (and later drivers)accepted · 2026-10-20
0011Installing links at runtime (packages, process and WASM)accepted · 2026-10-22
0012Network for WASM links (wyrm:link/tcp)accepted · 2026-10-22
0013Links as requesters (link grants)accepted · 2026-10-22
0014Embedded historian (sys/history)accepted · 2026-10-22
0015Downstream brokers admitted by the upstream’s CAaccepted · 2026-10-23
0016Broker-held meta overlays; attr.historyaccepted · 2026-10-23
0017Broker storage: wy/<site>/storageaccepted · 2026-10-24
0018Requests from upstream sitesaccepted · 2026-10-24
0019Dataflow editor in the exploreraccepted · 2026-10-24
0020History of a downstream site’s point, as seen through this siteaccepted · 2026-10-28
0021Link packaging from Cargo, one package format, per-host assets in the repositoryaccepted · 2026-10-28
0022Scheduler link: broker-side schedules that drive equipmentaccepted · 2026-10-29
0023Portable links: one link API for embedded, process and WASM (WASM world v2)accepted · 2026-10-28
0024Server kinds in the driver framework (Modbus slave)accepted · 2026-10-30
0025DQL link: standing queries over the tree, as a portable linkaccepted · 2026-10-30
0026History sync to external databasesaccepted · 2026-10-31
0027File store links (S3, Google Drive, WebDAV, local directories) on the raw layeraccepted · 2026-10-31
0028File transfers in parts (file store links)accepted · 2026-10-31
0029Decisions delegated by the owneraccepted · 2026-10-31
0030World wyrm:app@0.3.0: TLS and a random source for WASM appsaccepted · 2026-11-01
0032Logic blocks in the flow engineaccepted · 2026-11-01
0033wyrm-agent: a command line for operators and AI assistantsaccepted · 2026-11-01
0034Alarm link: broker-side alarms, records that survive, export through the history sync linksaccepted · 2026-11-04
0035Platform upstreams: live data to MQTT/UNS, Sparkplug B, ThingsBoard, Azure IoT Hub and AWS IoT Coreproposed · 2026-11-04
0036Broker fault tolerance: supervised restart, endpoint lists with liveliness arbitration, warm standby by WAL replicationaccepted · 2026-11-05
0037WYRM Studio: the Flutter app as an AsyncRedux monorepo made with frxaccepted · 2026-11-08
0038Flow fields and live valuesproposed · 2026-11-08
0039Messenger links: Telegram and Slack, templates as nodes, chat users by pairingproposed · 2026-11-07
0040Flow behaviours: keys from a port, the action block, custom blocksproposed · 2026-11-09
0041Claude connector: MCP through the user gatewayaccepted · 2026-11-10
0042Names people read: one rule for actions, parameters and nodesaccepted · 2026-11-11
0043The official links manifest: one checked-in list, one published indexaccepted · 2026-11-11
0044Flow blocks, third set: computation on the serveraccepted · 2026-11-11
0045Flow metrics in ~valaccepted · 2026-11-12
0046Link grants on the site’s storageaccepted · 2026-11-13
0047Checking an action without running it (~act/<a>?check)accepted · 2026-11-13
0048Updates, restore points and backups from Studioproposed · 2026-11-13
0049What the agent link and the gateway need for the Studio Assistantproposed · 2026-11-14
0050Biometric unlock with device keys, and finding a gateway on the local networkaccepted · 2026-11-14
0051Broker images for boards, and a web image builderproposed · 2026-11-25

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:

  1. Raw layer — trait Link, LinkCtx, NodeTree, one queryable per link, liveliness, ptok check. For drivers with their own topology (MQTT, OPC UA browse, gateways).
  2. 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

ConcernDesign
ParametersOne 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 semanticsValidate 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 & livenessTyped 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.
SchedulingPer-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 %).
PollingPoints 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
QualityTimeout → 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).
PersistenceAmended 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 modeOptional trait 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. Replaced by ADR 0024 (2026-10-30): a server is a connection kind (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).
ActionsAdd <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).
ObservabilityPer-node metrics (rtt_ms, errors, polls), rate-limited logs with link=/node= fields, state transitions audited. Amended 2026-10-30 (ruling 12, P11): diagnostics are opt-in per driver (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.
FoldersAdded 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/mock is the first framework driver; links/modbus the first real one. BACnet/DLMS reuse the same kinds with discovery actions.
  • The framework adds iteration-1 scope; wyrm-link-sdk is delivered in two steps: raw layer, then driver module before links/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 over wyrm-client (stdio and HTTP) exposing tree_list/resolve/meta, value_get/history, node_set/action_invoke (always dry_run first; config-level only with approval_id), profiles/device_models, flow_*, link_*, spec. Runs with a service-account ptok; audit origin=ai:<agent>.
  • links/agent: an ordinary connector exposing tasks as nodes (tasks/<id>/~val state machine planning → awaiting_approval → running → done|failed, ~act/approve|reject|cancel). Uses an LLM + the same MCP tools + a device-model catalog under pub/models/<vendor>/<model>. Human approval is enforced by ptok.maxperm, not by prompt.
  • Flow node llm for small in-flow tasks with token budget and caching.
  • wyr gains dev commands: new link|flow, dev (hot-reload), sim, replay, ai, mcp. Repo ships .claude/skills/wyrm-link and wyrm-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 approve call Control::schedule_reload, which waits 300 ms (so the current reply leaves first) and sends a signal on the reload channel. Daemon::run_until stops the current Broker and 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 admin Control (registry, audit, CA, link secrets, supervisor with its child processes), the FlowHost (flow store, flow signing key) and the Gateway (user store, signing key, sessions, WebSocket tickets). What is rebuilt is the Broker: 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), then session.close() before runtime.close().
  • Process links are not restarted. Attached::stop leaves processes running; on the next attach Supervisor::start is a no-op for a live process. The processes reconnect by themselves and re-publish ~meta/~val when the wy/<site>/sys/broker liveliness token returns (LinkConfig::republish_on).
  • Coalescing is partial. After the old broker has stopped, run_until drains 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 on wy/<site>/downstream/<id>/**, query/reply on its own sys/links/<id>/~act/hello, ingress put on sys/audit/<id>, and liveliness on sys/broker (broker-watch).
    • Loopback (tcp, unixsock-stream) in prod and operator CNs (over tls) are requesters only: they ask (query, subscribe, liveliness) and receive (put, delete, reply, liveliness token) on wy/<site>/** and on wy/<d>/** of every downstream site, but cannot put, serve queries or declare tokens outside **/@adv/sub/** (advanced subscriber bookkeeping; @adv/pub belongs to the owning link only).
    • In dev, loopback has full rights on wy/<site>/**.
    • Peer brokers get the rules of ADR 0007.
    • In-process sessions (admin, embedded links, flow engine, gateway, plugins) bypass the ACL.
  • 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_links skips held CNs. Remove still retires.
  • Authorize (DSA form, 2026-10-22): sys/quarantine/~act/authorize {dsid, group, name, driver, params}; dsid is an enum of the quarantined CNs, re-declared on every change (as are the link list of Deauthorize and the role list of group). name is the link’s display name (the id stays the CN, which the ACL matches). group gives that gateway role write on wy/{site}/downstream/<id>/** (as Update Permissions, audited). Each quarantine/<cn> node keeps its own approve with 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 put sys/quarantine/<cn>”). approve installs it as an external link and triggers a rebuild. Only sessions on the tls link 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 as config values sys/allow_all_links (default off) and sys/enable_quarantine (default on), audited (set_option). With allow_all_links an 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 (audit auto_install), then the runtime rebuilds; the link token goes only to links/<id>/token on the broker, and the operator copies it to the device as after approve. With both off, unknown CNs are ignored. Setting an option does not rebuild by itself. The broker logs a warning at start while allow_all_links is 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 (was sys/metrics/broker/acl_denied_total until 2026-10-22) = sum of zenoh_{rx,tx}_network_message_dropped_payload_bytes_count{reason="access-control"} read from @/<zid>/router/metrics (gzip). It needs the Zenoh stats feature 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 ~val storage 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 a ReconnectingClient, which opens a new socket with a fresh ticket, opens its list and subscribe streams again (a list starts over with refreshed), lets reads wait and go again, and fails a set or invoke cut 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::shutdown stops the supervised children; they are not adopted by PID on the next start. The wiki wants process links to survive a broker restart (systemd KillMode=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_until calls Control::shutdown also when Broker::start/stop fails.
  • 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 ptok on ~set/~act, but cannot stop a session from publishing into another link’s ~val or 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.json5 gets a peers section (PeersSection in crates/wyrmd/src/lib.rs):
    peers: {
      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
    }
    
    Validation: sites are valid segments, unique and not our own; endpoints are quic/<host>:<port> without #/?; CA paths are UTF-8 without ;#? (they become endpoint parameters); listen and downstream come together; upstream_val_hz > 0.
  • Transport: QUIC + mTLS. Any non-empty peers turns on broker certificates. The broker has CN broker:<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_certificate stays 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.listen endpoint gets data_dir/pki/peer-trust.pem (a bundle of all downstream CAs, written by Control::configure_zenoh on every broker build);
    • each upstream connect endpoint gets that site’s ca file. The main tls/ listener for links and operators therefore never trusts a peer CA.
  • ACL (access_control_with_peers in crates/wyrm-admin/src/acl.rs). Peer subjects match cert_common_names: ["broker:<site>"] and link_protocols: ["quic"]; link and operator subjects are tls only. The two cannot overlap.
    • Upstream sites are read-only on our wy/<site>/{downstream,dataflows}/**: ingress declare_subscriber, declare_liveliness_subscriber, liveliness_query; ingress query only on …/**/{~meta,~val,~def,~state}; egress put, delete, reply, liveliness_token, declare_queryable, declare_subscriber. No ~set/~act query passes, and nothing under sys/** 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, list and subscribe on wy/<d>/**, checked under the user’s roles for the own site (wy/<d>/x as wy/<site>/x) and sent without a ptok, which the downstream links would not trust; set/invoke there are refused by the gateway (test read_sites_map_to_own_roles_without_a_token).
    • Requesters (direct Zenoh sessions): Loopback and operator requester rules extend to wy/<d>/** (and wy/<d>/**/@adv/sub/**). The downstream broker’s own ACL keeps them read-only there.
  • 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, is wy/<site>/upstream/<u>. Each is a reference node served by the admin (wyrm_admin::peers): wy:broker, @site, @root = wy/<peer> and a bool point connected, fed by the peer’s liveliness token wy/<peer>/sys/broker. The ACL lets only that liveliness pass between peers, split by direction: a peer may watch our sys/broker token and declare its own, never ours (per upstream site: presence-<u>-token-in on wy/<u>/sys/broker only; per downstream site: presence-<d>-watch-in, presence-<d>-token-out). Links get the same split (broker-watch ingress, broker-token egress). sys/** data stays closed. Test: presence_tokens_by_direction. A client follows @root to 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 and install refuse it). Test: two_brokers_over_quic.
  • Egress downsampling. With upstream_val_hz, the router config gets one Zenoh downsampling item (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 for wy/<site>/downstream/**/~val gave all links one shared budget. With upstream_val_hz set, 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/upstream that edits server.json). sys/upstream/~act/add {name, url, ca, enabled} and sys/downstream/~act/add {name, ca} (level config) store a peer in the registry (Op::AddPeer, SCHEMA 6) with that site’s CA certificate as PEM; upstream/<site>/enabled (writable) and remove change or drop it. Peers from wyrmd.json5 are 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 to data_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.listen may now stand alone in wyrmd.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 sys and upstream; chains of brokers (2026-10-22, owner decision, as a DSA upstream that browses its downstream broker whole). The upstream may also read wy/<site>/sys/** and wy/<site>/upstream/**: queries, subscriptions and the data sent up (put, delete, reply) cover only **/~meta and **/~val there (upstream-sub, upstream-data), so nothing else published under sys, such as the audit records of sys/audit/<link>, leaves the site; declarations and liveliness cover the sections whole. ~set and ~act stay closed everywhere, so no sys action (Get Log, Install, Purge, …) runs from above. A chain plant → edge → central works through via: a downstream entry lists the sites that broker relays from further down (downstream: [{ site: "edge", ca, via: ["plant"] }], also sys/downstream/~act/add {via}, PeerDef::via, registry SCHEMA 13). The upstream’s site-<d> rule then covers wy/<d>/** and wy/<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 their via lists (wyrmd.json5 validation, sys/downstream Add and the registry refuse a peer named like a relayed site, and a site relayed twice). wy/<site>/upstream is 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, reads sys/upstream below, receives plant samples; set and a sys action below fail).
  • Test. two_brokers_over_quic in crates/wyrmd/tests/e2e.rs: central (downstream edge) and edge (upstream central, mock link, upstream_val_hz: 50). A client on central lists wy/edge/downstream, receives samples of wy/edge/downstream/mock/g0/p0, and its set on that point fails at the edge ACL.

Consequences

  • No write across sites. An upstream site cannot set/invoke on a downstream site, even with a valid ptok: the edge ACL drops the query before it reaches the SDK. Reading is open on downstream, dataflows, sys and upstream (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 if listen ever contains quic/) 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 (TimeState in interceptor/downsampling.rs) and picks one matching rule per key (so the rules must not overlap). Each link gets upstream_val_hz samples/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 (dev profile 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 under upstream_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 mint broker:<other-downstream> (and receive that site’s site-<d> rule) or broker:<upstream> (and read our downstream/** and dataflows/**). 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 a tls/ main listener is not covered by a test yet. two_brokers_isolation covers the rest between real brokers: no upstream read of sys/**, no upstream invoke, no downstream put or query outside its wy/<d>/**, and no peer from an untrusted CA.
  • A change of peers needs a broker restart (the section is read at Daemon::open); peer CA files are re-read on every broker build.

Alternatives

  • Broker links on a separate tls/…:7448 listener (the wiki’s design). Rejected: link, operator and broker subjects would all be tls, so a peer CA could mint a CN that matches a link rule. QUIC keeps the subjects apart by link_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 ptok checks 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).
  • ~def is read-only. dataflows/<id>/~def is served as a document; there is no put deploy, because a bare put carries no verified caller. Deploying goes through dataflows/~act/deploy only (level config, ptok, audit).
  • deploy {def, proofs}. Before compiling, the engine checks (crates/wyrm-flow/src/engine.rs):
    1. caller_covers: permissions.maxperm ≤ the deployer’s effective permission on the deploy action.
    2. proves_targets: for every command target of the definition (command_targets: full keys of …/~act/<a> and …/~set, relative keys resolved under wy/<site>/):
      • the target is an exact key under wy/<site>/downstream/ or, since ADR 0017, wy/<site>/storage/ (no *, no $, so no sys/**, no dataflows/**, no other site);
      • proofs[target] is a ptok for 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 is permission_denied (or invalid_parameter for a bad target) and nothing is stored.
  • 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 deploy builds {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/remove it. 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 ~val shows it as deployed_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_covers is weak by itself (the deploy action already needs config); 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-gateway runs inside wyrmd when wyrmd.json5 has a gateway section (GatewaySection: listen, tls_cert/tls_key, session_ttl_s clamped to 60 s … 7 d, admin_user default admin). TLS (rustls) is required off loopback, checked in both Config::from_json5 and Gateway::open. State lives in data_dir/gateway/: hmac.key, users/ (wyrm-state WAL + snapshot, ADR 0003) and gateway.key (Ed25519, 0600). The Gateway survives 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/users for users with config on wy/<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 from hmac.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 same gen; grants come from the user’s roles now, not from the token.
  • Generation counter is store-wide. UserDb.next_gen only grows and survives RemoveUser. 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_for signs one token per request with gateway.key: subject user:<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 as Denied.
  • 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 with config on wy/<site>/sys/** (the default admin role) pass; viewer, operator and engineer get permission_denied. Each action is audited with user:<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: Bearer is 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 level none removes it; a new role starts empty. The stored list of a role (users store Op::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 with config on wy/<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_PASSWORD is set and admin_user does not exist, that user is created with the admin role. The variable is removed from the process environment right after reading, and the supervisor starts link processes with a cleared environment (env_clear plus RUST_LOG, RUST_BACKTRACE, TZ, LANG, LC_ALL, PATH). The password never comes from wyrmd.json5.
  • Login rate limit. At most 5 failed logins per (user, ip) and 20 per ip over 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 through Control::record: logins and refusals with subject user:<name>, user changes with the acting user’s name as subject. They never carry passwords or tokens.

Consequences

  • A stolen gateway key gives write/config on 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 inside wyrmd with the same data_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 the admin role’s config, 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 client proofs with 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 gen gives 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.4 until 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 only wyrm:flow/node components without imports. A ~def node 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 runs init; 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, features runtime, cranelift, component-model, std as before: no WASI, async, cache, GC, threads or profiling. The wasm-tools crates (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-version went 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, Store limiter, fuel, epochs, component::Linker, bindgen!) did not change. Two calls of the wasm-tools crates did: an import or export name is now a structure (full_name()), and embed_component_metadata takes canonical_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 gc cargo feature removes only the GC types and exceptions. So with a default Config a guest could use typed function references (call_ref), function subtypes, ref.test, ref.cast, i31 and i64.add128, none of which 36 took. That is the path of RUSTSEC-2026-0570 (a guest aborts the process of a build without gc; 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_FEATURES in crates/wyrm-wasm-host/src/lib.rs) and Host::new turns these on and every other feature off (Config::wasm_features with 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 with funcref only, 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 without threads) 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 default Config), 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) and portable-echo of wyr link pack, all built with wyrm-link-guest (wit-bindgen 0.57.1) for wyrm:app@0.3.0, load on the host. The test built_packages_load repeats 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 add uses 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 links wyrm-link-sdk and calls process::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 world wyrm:link/point (ADR 0010), hosted in-process by the framework driver wasm under fuel, memory and time limits. The component has no I/O until host imports exist (a later ADR: net:tcp gated by capabilities), so its points are computed.
  • Package = a zip with wyrm-link.json at its root: { name, version, description?, wyrm_link: <protocol>, kind: "process" | "wasm", entries?: { "<target triple>": "<path>" }, args?: [..], entry?: "<path>.wasm" }.
    • wyrm_link is the link protocol version of wyrm-link-sdk (hello reply shape, trust lists). A package built for another version is refused (success: false), so it cannot misread the trust lists.
    • A process package lists one executable per target triple; args are its arguments (for example ["link", "mock"]). Process mode needs the broker’s tls/ listener (link_endpoint); without it the install answers success: 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 driver pkg:<name>.
    • sys/packages/<name> shows version, kind, source and SHA-256; remove refuses while a link uses the package.
  • Sources (actions of sys/links, in the group “Install Link”, each with name = the new link id; each declares a timeout_ms long enough for a fetch and unpack):
    • from Driver {id, driver, mode, params}: the current install (same action id, so wyr install and wyrm-mcp keep working; only its display and group change).
    • from Zip {name, zip}: the zip as a binary parameter with the file editor (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> with GIT_TERMINAL_PROMPT=0 and no hooks; a url or ref that starts with - is refused. The checkout root must hold wyrm-link.json with built artifacts: the broker does not compile.
    • from Repository {name, package}: an index at packages.repository in wyrmd.json5 (as DSA’s linkRepositoryUrl), JSON [{name, version, description, url, sha256}]. It is fetched in the background, never on the start path; package becomes an enum once it arrives (declared again like the quarantine lists). Without the index the action answers success: false, "repository unreachable". The download must match sha256.
    • from WASM {name, wasm}: one wyrm:link/driver component (ADR 0012), wrapped as a wasm package; a wasm package zip from any other source works the same.
  • 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 CBOR args map, at most 64 MiB). Before the body is read it checks the key (downstream sites stay read-only), that the action has an editor: "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 Dart FrameClient sends 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): every binary parameter that can be larger than a frame is editor: "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 Rust wyrm-gateway-client takes the same route for arguments over 60 KiB, with Expect: 100-continue, so a refusal comes before the body; a string or map argument 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, wyrmd closes 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 answers busy (“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; plain http:// only to loopback. git runs with a cleared environment, no system or global config, and file:// only in the dev profile (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 is success: false with the reason, not an error status.
  • Trust (owner decision 2026-10-22): no package signing; level config is enough, as in DSA. A process package 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.json requester: [{path, level}] (at most write, never sys). Each new link of the package gets them at install; the install message lists them.

Consequences

  • A config user (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 in docs/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 git on 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 config level 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.0 gets interface tcp and world driver:
    • connect(addr: string, port: u16, timeout-ms: u32) -> result<u32, string> — addr is 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 = world point (init, read, write) plus import tcp. A point component (no imports) runs as a driver too. 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. connect passes only when the address is inside one entry and the port is that entry’s port. IP literals only, in the list and in connect: std resolution 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, NAT64 64:ff9b::/96 and 64:ff9b:1::/48, 6to4 2002::/16) and cloud metadata (169.254.169.254 is link-local; fd00:ec2::/32). So 0.0.0.0/0 or [::]/0 never reaches the broker’s own listeners (in dev, 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 wasm framework driver (net). The framework’s add_* and edit actions need config (ADR 0004), so only config widens 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 blocking recv cannot 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 it read/write requests over a bounded channel. No async in wasmtime, no blocked tokio workers.
  • Driver wasm (links/wasm, a framework driver, embedded): connection params component (the package name: the admin puts each wasm package’s entry at data_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 to init as CBOR), call_ms; device note (devices only group points: no ping); point value (number, bool, text, any: the node type, so an app sends the right type on set), cfg (JSON, passed to read/write as CBOR), poll_s, writable, unit. A wasm package (or one component through “Install Link ▸ from WASM”, wrapped as package <name>, version 0+<sha256 prefix>) installs as an embedded link with driver pkg:<name> and one connection main; its devices and points come from the connection’s Add actions 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[/…] or wy/{site}/dataflows[/…], plain segments only (no wildcards, no suffixes), never sys/**. Levels: list, read, write; config stays with people (MAX_LINK_GRANT), and dataflows grants stop at read.
  • Set with sys/links/<id>/~act/grant {path, level} (the caller needs config; level none removes), audited (link_grant), shown in sys/~act/get_permissions (source link). A package asks for its grants in wyrm-link.json requester: [{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 → ~meta queries and liveliness under the path; read → also ~val queries and subscriptions; write → any query (~set, ~act) under the path; the answers flow back (egress put, 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 (hello for a process link). Every link trusts it as one LimitedKey per grant: up to that grant’s level, only under that grant’s path, and only for the subject link:<id> (LimitedKey::subject; Verifier takes the highest cap among the keys that cover a request and accept its sub), so the audit names the real caller. hello sends such keys in bound_keys ([key, cap, scopes, subject]); a link built before this ignores the field and does not trust them. The link signs its ptoks with it (LinkCtx::requester_key, subject link:<id>); reads of ~meta/~val need no token.
  • A grant change rebuilds the router (ACL) and so every link’s trust list (embedded links restart, process links say hello again).

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); tests link_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/**/~val in the memory volume: 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 .so plugins, 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 under wy/<site>/sys/history; its settings are control-plane state in the registry (Registry::historian, ops PutWatchGroup, 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 in data_dir/history/days/YYYY-MM-DD.redb, plus index.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 Type None / Interval (the last value every interval, changed or not) / All Data (every update) / Point Change (value or quality changed), and Buffer Flush Time (rows wait in memory, then one transaction per day file). A watch follows <key>/~val on the broker’s in-process session with wyrm-client’s subscribe (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 Control and outlives a router rebuild; attach binds it to each new session, detach flushes 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>/… or wy/<site>/dataflows/<flow>/… of this site or of a downstream site (its data arrives over the peer link); never sys, 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): sys would republish point values to everyone who may read sys.
    • 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 skip bad samples. 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 config on sys/**: the rows are point values, and a role with read on sys need not have read on the points. Through the gateway only the admin role reaches sys/** (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/history grows 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 verify does not check it.
  • Read path (D2, spec 0.1.10): the historian answers get <point>/~val?history=… with a queryable on wy/<site>/{downstream,dataflows}/**/~val beside the memory storage; it ignores selectors without history/since and 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::history keeps the arrays. Rights as subscribe (owner decision 2026-10-22): the session ACL on ~val, no history:read token; the gateway’s op history needs read on the point. Bounds: limit ≤ 100 000, 5 000 000 rows scanned (refused beyond, never cut), 4 reads at a time. Clients: Rust history, wyr values, Dart history (gateway and FFI wyrm_history), explorer “View History” (chart and rows).
  • The CLAUDE.md layout named history/{rocksdb,influxdb} as HistoryStore backends. 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>; with allowAllLinks it goes there too; with quarantine on it waits in /sys/quarantine until Authorize; otherwise it is refused;
  • Deauthorize lists every connection under /downstream, brokers included; there is no install step and no /sys/links entry 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.listen trusts only this broker’s CA, as the link listener does; peer-trust.pem and per-site downstream CAs are gone. The listener opens whenever peers.listen is 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: query wy/<site>/sys/~act/enroll and its reply (rule enroll, a subject without a CN, so it also matches every QUIC broker, which gains nothing). The admin answers it as an open action (as hello): no ptok, 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}:
    • url is the upstream’s enrollment endpoint; ca its CA (PEM, required: the downstream trusts nothing it was not given); token optional, a secret parameter, never shown back.
    • The downstream makes its own key (sealed in the SecretStore as peer:<site>, written 0600 for Zenoh; it never leaves the site) and sends {site, csr, token, via} (csr for CN broker:<own site>, via the sites it relays). It asks again every 10 s while the answer is pending.
    • The answer issued carries the certificate and the port of peers.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> shows url, 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) and certificate (subject, valid until).
  • The upstream admits it as DSA does. For an enrollment request, in this order:
    1. a downstream already admitted with the same key gets its certificate again; another key is refused;
    2. a held name (Deauthorized) waits in quarantine for a manual Authorize;
    3. 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);
    4. allow_all_links signs at once (owner decision: as DSA’s allowAllLinks) when every via site is free; otherwise the request goes to quarantine;
    5. with enable_quarantine the request waits in sys/quarantine/<site> (kind: broker, key, via); Authorize {key, via} signs it — key must 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;
    6. 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 or via changes); 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, and sys/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 another via).
  • wyrmd.json5 keeps an offline path: peers.downstream: [{ site, via }] on the upstream and wyrmd ca issue data_dir/peers/<d>/broker.{pem,key}; the downstream’s peers.upstream entry names ca, cert, key. A name in peers.downstream is not enrolled at runtime.
  • Invariants (each with a test):
    1. 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.
    2. A Deauthorized broker does not come back by itself (held; Reject: never).
    3. 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).
    4. A session without a certificate on the enrollment listener reaches sys/~act/enroll only (enroll_listener_reaches_one_key).
  • 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_links on, anyone who reaches the enrollment port gets a broker certificate for a free name and may serve wy/<name>/** on this broker (read-only for our upstream, never our own keys). This is the DSA behaviour the owner chose; keep allow_all_links off 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.
  • via is fixed at admission; to change it, Deauthorize and Authorize again with the new list.
  • Old configs with peers.downstream[].ca fail 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 (a put, kept by the router’s memory storage; a name that is gone is deleted): there is no sys/overlays node, 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 the view=list summary; a change bumps the node’s rev (and its parent’s, whose list changed) and republishes ~meta.
  • Today’s only source is the historian, and the content is derived. attr.history of 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 own attr.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 rewrite display or anything else. Only the admin writes sys/** in prod; each process or external link may query and subscribe its own overlay key and nothing else under sys.
  • Spec 02 0.2.1: view=list summaries carry key 16 has_history (true when attr.history is not empty), so a tree or a Metrics row shows the icon without a ~meta per row. attr.history is an array of store keys: a key under wy/<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 ~meta by rev see the change: the overlay bumps rev.

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 inside wyrmd (crate wyrm-storage, a link with root wy/<site>/storage, link id storage). 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 (writable write), 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, dynamic takes any. editor (none, textarea, date) is kept as attr.editor for UIs. No password editor: anyone with read reads a storage value, and secrets never go in the tree (principle 6).
    • delete of a folder with children needs recursive (as DSA). rename and duplicate refuse a name a sibling has.
    • publish creates the missing folders and a dynamic value at the end of path (relative to storage), then sets the value; a path through a value, or to a folder, is refused. No timestamp and no open stream (DSA’s CloseStream).
    • export answers the subtree as JSON text ({"<child>": {"$type": "number", "@editor": "textarea", "?value": 21.5}, "<folder>": {...}}, as DSA); binary values are {"$hex": "…"}. import replaces a folder’s children with such a JSON, given as text (data) or as a file (file, editor: file, so the gateway takes it over POST /api/invoke when 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. type and editor travel as text, as every action’s choices.
  • Rights as in DSA: every action and every ~set needs write on the node. Trusted keys: the admin keys; the user gateway’s (users’ grants decide; default roles: viewer read, operator write, engineer config); the flow engine’s at write (a flow’s set/invoke sinks may target wy/<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 adds storage grants 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). wyrmd opens 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, publish and import count 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, but wyrmd refuses to start: the link would share the storage’s audit records, overlays and logs. Remove it with the previous wyrmd first.
  • History: the historian can watch storage values (wy/<site>/storage/…), and they get attr.history (ADR 0016).

Consequences

  • Anyone with write on storage can grow it up to the limits; the SDK’s rate limits apply to ~set and actions (50 per second per caller, burst 100). A flow is one caller: all its set and invoke sinks into storage share that budget, and requests above it are refused (rate_limited) and counted in the next audit record.
  • Every ~set and 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); editor comes from add_value and import.

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 write on wy/<d>/downstream/**, wy/<d>/dataflows/** and wy/<d>/storage/** (the broker storage of ADR 0017 is device-like data; DSA’s group covers /data too);
    • config on wy/<d>/sys/**, and config instead of write on downstream, dataflows and storage (link actions such as Export, Edit, Stop, Restart; amended 2026-10-31), only with allow_config on that upstream: wyrmd.json5 peers.upstream[].allow_config, or sys/upstream/<u>/allow_config (writable at config) for one added at runtime. A change rebuilds the broker (the ACL changes).
  • Router ACL on the downstream. For the own site and the sites it relays: ingress query and egress reply on …/{downstream,dataflows,storage}/**/~set and …/**/~act/* for every upstream (upstream-write-in/-out); the same on …/sys/** only for an upstream with allow_config (upstream-<u>-config-in/-out, subject upstream-<u>), with a deny on …/sys/links/*/~act/hello (it checks a link token, not a ptok, and answers with the link’s secrets: only the link’s own session asks it; deny wins in a Zenoh policy, and no other policy of a peer session allows it). A relayed site’s sys needs allow_config at 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 d carries site = d and is signed at the upstream (its gateway, or an operator’s admin key). The upstream’s admin answers wy/<u>/sys/signing_keys = {write: {<site>: [key…]}, config: {…}} from a queryable on that one key (the router’s ~val storage and the admin’s sys/** queryable do not cross brokers): for write, 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); for config, its own keys and the config keys of the upstreams it allows config, so a key reaches config below 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/-in here, signers-<d>-in/-out there, 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: write keys by links under wy/<d>/downstream, the flow engine under wy/<d>/dataflows, the storage under wy/<d>/storage; config keys at config by all four (the admin under wy/<d>/sys, links, flow engine and storage under their sections), only from an upstream with allow_config. Process links get them in hello after the rebuild. The token’s own grants and max still apply: the effective right is the smaller of the user’s grant at the upstream and the downstream’s cap.
  • Gateway on the upstream. set and invoke on a downstream site are allowed (WebSocket and POST /api/invoke). The user’s grants are checked as for the own site (wy/<d>/x as wy/<u>/x, as reads already were), and the token is minted for site d with the own-site grants rewritten to wy/<d>/… (wy/** grants stay) and the subject user:<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 write trusts 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>, subject user:<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>")); wyr keeps the own site by default.
  • Rotating a key at the upstream reaches the downstream within about 10 s, with one rebuild.
  • A sys action from an upstream without allow_config is dropped by the ACL: the caller waits for its timeout instead of getting permission_denied.
  • A config action on a link from an upstream without allow_config reaches the link (the ACL lets every ~act on downstream through) and gets permission_denied, without detail (spec 04).

Alternatives

  • Keys in the enrollment answer (ADR 0015): wyrmd.json5 upstreams 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 Dataflow on a flow node (dataflows/<id>) and New Dataflow on dataflows open 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 (level read) answers the catalog (wyrm_flow::catalog): type, category, description, ports (fixed, or named by a parameter: expression in.<name>, wasm ports), parameters with type, choices, default and editor hint. A test checks every type’s sample configuration against nodes::ports, so the catalog cannot drift from the compiler.
  • Load, check, deploy: the current definition is the last item of dataflows/<id>/~act/history (level read); every edit is checked with dataflows/~act/validate (debounced) and the error shown; Deploy sends the whole definition with version + 1 through dataflows/~act/deploy (the gateway adds the deployer’s proofs for set/invoke targets, ADR 0008). A flow with a set or invoke node gets permissions.maxperm: write when it has none. Fields the editor does not know (policy, …) are kept.

Consequences

  • Deploying needs config on dataflows (as before); validate, history and node_types need read, 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>]}}. .sites cannot 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, children and list of a key of another site, it merges attr.history (union) and has_history (spec 02 key 16). A change of the map sends changed for each affected child of an open list, 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: a sys/history store of another site’s point is read at its own key.
  • Rights are the DSA double check, in the gateway: a history read at a watch key in this map needs Read on the point’s ~val (as reading it at the point); any other key under sys keeps 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 read sys/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-sdk feature package: 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) and sha256_hex. The broker checks installs with it; wyr builds 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’s Cargo.toml holds 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.json is generated, never written by hand.
  • wyr link pack builds 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 --version packs 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. A url without 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.sh runs wyr link pack and wyr 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;
  • next shows 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

  1. 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.
  2. Writes to equipment, confirmed, with retries, visible state per target, audit.
  3. A manual change after a confirmed write wins until the next transition.
  4. 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).
  5. Zero messages between transitions at idle; one timer for all schedules.
  6. 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 flow set, 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_schedule takes the link param default_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 param default_tz (IANA name, default UTC). The embedded scheduler gets the system zone from wyrmd (jiff::tz::TimeZone::system().iana_name(), else UTC); packages use their params. Zones come from the tz database bundled in wyrm-schedule (jiff, tzdb-bundle-always); a native build may read the host’s newer database first.
  • Event: id (stable, generated e<n>, never reused in a schedule), display, value, priority (0–9, integer, validated), special (bool), start and end as local wall-clock date-times in the schedule’s zone (the first occurrence’s window), and recurrence.
  • Recurrence: an RRULE subset — FREQ (HOURLY|DAILY|WEEKLY|MONTHLY|YEARLY), INTERVAL (1 … 1 000), COUNT (≤ 10 000) or UNTIL (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 expands BYDAY within the week (Monday first); MONTHLY expands BYMONTHDAY and BYDAY (both given: their intersection); YEARLY expands BYMONTH (default the start’s month), then BYMONTHDAY/BYDAY within each month; BYMONTH (and BYMONTHDAY with WEEKLY) filter otherwise (ruling R5). At most 100 events per schedule. The caps are constants of wyrm-schedule, which validates them; the link re-exports them (ruling R1). DSA’s Single/Hourly/…/Yearly import as FREQ with INTERVAL=1. A moment event (DSA “Add Moment Event”) is an event with start == 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=-1 gives 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, current keeps 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_at is the window state only (Default or Event) and never returns a past moment; next_transition returns 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 after t where state_at changes (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 at from is included (ruling R6).
    • Bounded work: scanning stops at the horizon of next_transition (366 days ahead, then “none”). COUNT is 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. A BYDAY ordinal is 1…5 (or −1…−5) with MONTHLY and YEARLY: it counts within a month.
    • Instants are i64 microseconds since the Unix epoch, UTC. The crate reads no clock and no OS zone and builds for wasm32-unknown-unknown.
  • 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_timer for the earliest; on on_timer, compute state_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_timer is 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): start declares 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 in 0 ms timer events. A continuation more than 30 s late counts as a clock step: the link goes to state_at(now) and does not replay the lag (ruling R11). Writes beyond 50 in flight wait in a FIFO queue drained by on_reply. While schedules are still loading, import and the target actions answer busy.
  • 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, enabled turned 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_until is still ahead is left alone; the others are written: an ack target at once, a read_back/feedback target 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 carries valid_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 good confirms nothing and clears the key’s last value, so an ok reply 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) and h/<schedule> (the held moment, R17), written by store_put in the event that accepts the edit, so it is durable before the action replies. Keys at most 1 + 2 × schedules + targets: 8 031 within the node budget, below the host’s 10 000. A store that refuses a write fails the action with resource_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 action confirm is the enum index (0, 1, 2), in an import the text.
  • On each transition (and at start), for each enabled target: ~set the value (mapped if map). Confirmation:
    • read_back: the next ~val of the same point equals it (numbers within tolerance, default 1e-6 relative);
    • feedback: a ~val of another key equals the expected value (feedback_map may name it, else the written value) — for devices whose write register is not the one read back (Modbus coil written, status register read);
    • ack: an ok reply to the ~set is enough (no feedback path). A matching sample counts while the write waits for its reply or after an ok; none 10 s after the ok fails the write. Links publish a value only when it changes, so a key whose last sample already shows the value confirms on the ok. A target holds a subscription on its confirm key while it is enabled, not override and not ack; targets that confirm on the same key share one; at most 1 000 subscriptions (an add over that, or one the host refuses, fails with resource_exhausted or the host’s error).
  • Retry until confirmed: exponential backoff 1 s → 60 s cap, jitter ±20 % from an FNV-1a 64 hash of now_us and the target id, not rand (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 ~val on its confirm point that differs from the expected value marks it override (the person wins); the link does not write it again until the next transition. In ack mode 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), attempts are attributes.
  • Audit (ruling 2): the Host API has no audit call and the wyrm:app@0.1.0 WIT stays frozen. Every write is a ~set, audited by the target link’s responder (sys/audit/<target link>, subject link:<scheduler id>) as any ~set. Confirmations and overrides go to the link log at info (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_target check the caller’s own write on the target point from the request’s ptok. 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_target says nothing about the caller’s rights on …/plc/fan. Targets are configuration: add_target, a target’s edit/enable/disable/remove, and import (it carries targets) are config actions, and the responder enforces the level before the app runs. Schedules and events stay at write. Who has config on the scheduler may point it at any device the scheduler can reach (embedded: all of wy/<site>/downstream; packages: their grants). The gateway’s operator role has write and cannot add targets; engineer and admin can (ruling R12). The agent link (capped at write) and upstream sites (ADR 0018, at write) can edit events but cannot add targets. The app does not read Who grants; 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_target refuses 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 LimitedKey at write, scoped to wy/<site>/downstream, bound to the subject link:scheduler; the key is not in sys/signing_keys. Package grants (ruling 10): a package carries no requester grants (a package cannot ask for a root); an operator grants write on each target link with sys/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 first hello (ruling R13); WASM links get it with the router rebuild. Without a grant, add_target fails with permission_denied and no message: the SDK strips the detail of that status (ruling R14). Ruling R21: the embedded scheduler does not trust its own key (its own LinkConfig leaves 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, so add_target cannot refuse such a point; its writes fail with permission_denied and 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)
  • remove of a schedule is at write and is refused while the schedule has targets (invalid_parameter, “remove its targets first”; ruling R20): targets are configuration (ruling 6), and a write caller must not drop them. import with overwrite is at config already.
  • Writable values are only default and enabled, and they are saved. enabled turned on is always a transition: the targets are written even with the same state (ruling R10). Event fields change only through edit (one validated, saved step; DSA’s unsaved writable fields are not repeated).
  • import {json, id?, overwrite?}: without id the export’s id is used, for a DSA export its name when that is a valid id, else it is refused (ruling R9). A schedule with that id is refused unless overwrite replaces it as a whole. The targets of an own export are checked as by add_target; created_by becomes the importer.
  • Every action validates fully before saving: ids, zone name, RRULE, priority range, end >= start, window not longer than its period, targets under wy/<site>/downstream/. Errors name the field and the rule.
  • get_events uses editor: 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 at wy/<site>/downstream/scheduler, started with the router like the storage link, grants and key from wyrmd (ADR 0023, embedded built-in apps); not an operator-created driver instance. Ruling 9: scheduler joins the reserved ids of new links, and Daemon::open refuses a stored link with it, as with storage; it is not in sys/links (not a registry link) but is in the broker’s overlays (publish_overlays), so history marks show on its nodes. wyrmd.json5 scheduler: { enabled: true, store_mb: 64 } (both optional) turns it off or sizes its store; peers.downstream cannot name a site scheduler. Ruling R22: when the admin cannot save the scheduler’s keys (ensure_builtin_keys), it logs that at error and 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 by wyr link pack --kind process --name scheduler-process (ADR 0021); wyrmd link scheduler runs the same app as a process link. No requester grants: an operator grants each target link (ruling 10).
  • WASM package scheduler — the same App built with --features wasm on world wyrm:app/app, store 16 MiB (capabilities); targets work as in the other modes (requests within its grants). The wyrm-schedule crate builds for wasm32-unknown-unknown (no std time; tz data compiled in). examples/packages/build.sh packs 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; BYDAY ordinals; three or more overlaps; special days; DST spring-forward and fall-back in Europe/Kyiv and America/New_York (window boundaries, the missing and the repeated hour); clock step forward and backward. next_transition agrees with state_at sampled every 5 minutes.
  • cargo bench -p wyrm-schedule --bench eval (Apple M4 Max, release), per call: state_at p50 0.21 µs (E = 1), 5.5 µs (E = 10), 53.7 µs (E = 100); next_transition p50 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. occurrences over a year, 10 events (7 198 rows): p50 0.83 ms. Worst COUNT compile (100 events whose rule never matches): 17–84 ms.
  • cargo bench -p wyrm-link-scheduler --bench cold_start: the link’s cold start on SimHost, 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 of Scheduler::start, p50 / max: ack — start event 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: start answered 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 (ack target): p50 16.9 ms, p99 24.8 ms, max 27.6 ms;
    • a target on the Modbus simulator (plc1/line1/ahu1/fan) with feedback on fan_status: confirmed after 390 ms, override 973 ms after a manual write of false, written true again and confirmed at the next transition.

Left to the builder (as built)

  • Crate layout: crates/wyrm-schedule (model, rrule, occur, eval, convert, dsa) and links/scheduler (lib (schedules, events, the wake loop), targets, tree, store, wake, limits: the link’s constants, one place each). The tz library is jiff with 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, freq 0 … 5 → once or FREQ with INTERVAL=1 and UNTIL = the date of eDate with the time of sTime; instants with Z or an offset are converted to default_tz.

Consequences

  • The link id scheduler is reserved like storage.
  • Spec 02 does not change (only existing editors and value types are used).
  • Built-in probe scenario links/probe/scenarios/scheduler.json; user guide docs/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);
    • rustls is pinned to =0.23.45: zenoh-link-tls 1.10.1 gives its reader and writer one TlsStream, 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

  1. One link source builds as an embedded link, a process package and a WASM component (cargo features), with the same behaviour.
  2. 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.
  3. Every capability is granted explicitly at install; nothing else is reachable.
  4. 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.
  5. Building a WASM link needs only cargo and wyr (no external wasm-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 tcp interface of ADR 0012 is reused as it is.

Decision

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, and store_get sees the event’s own earlier store_put/store_delete (read your writes). store_put is durable when the event’s commands are applied and before the reply to a set/invoke leaves. 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/invoke gets 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 sees resource_exhausted from the Host call itself where it can (set_timer, subscribe, set, invoke, store_put return Result).
  • Replies: on_invoke answers 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_timer counts elapsed time, unaffected by clock steps); now_us is 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-client subscribe), then changes. A full event queue coalesces on_value per subscription (the newest sample wins); set/invoke are never dropped: when the queue is full they get busy.
  • Errors carry a WYRM status and a message (AppError { status, msg }); who carries 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> in wyrm-link-sdk implements trait Link: one task owns A; SDK callbacks, tokio timers, subscriptions and replies become events; commands map to LinkCtx; 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’s data_dir (one record per key, atomic replace), as driver::persist.
    • Embedded: registered in wyrmd as any driver (Portable<A>).
    • Process: process::main::<Portable<A>>() (ADR 0021).
  • WASM host (new world, driver app in links/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 through LinkCtx. Imports are the host interface below and, when granted, tcp (ADR 0012).
  • Guest crate wyrm-link-guest: implements Host over the imports and exports the world for an App with 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: the tcp allowlist entries (ADR 0012 syntax) or [];
  • requester: grants on other points (ADR 0013 syntax; the existing top-level field, not inside capabilities);
  • 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 hello reply (process) and in LinkConfig (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 a read grant 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 wyrmd at start, not from an operator: the scheduler gets write on wy/<site>/downstream and 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 calls start. Timers and subscriptions of the dead instance are dropped; the store is kept.
  • The tree: before calling start again the host keeps the old tree but marks its values bad/comm_fail; nodes the new start does 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 attributes status (running | restarting | stuck) and error; 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: start gets the link’s params (a CBOR map; the app validates it and fails start with invalid_parameter naming the field). A change of params is a stop and a start (no reconfigure).
  • Hot start: a new component (package upgrade, “Install ▸ from WASM” again) goes through stop on the old instance (bounded 2 s), then the new one starts; the store carries over; requests in flight get busy. On an upgrade of an app package the broker swaps the code inside each running link of the package (links/wasm reload_component): the link is not stopped, its tree stays (nodes the new start does not declare again go by the sweep), audit op hot_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 fails declare_action (the event) or invoke with invalid_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 fails store_put with resource_exhausted. A write that does not grow the store passes even over a smaller store_mb, so the app can shrink it; store_mb: 0 refuses every write.
  • Memory: memory_mb bounds the instance, all its linear memories together.
  • Call time and the caller: the SDK’s bound on one set/invoke of a portable link is call_ms + 1 s (it raises LinkConfig.driver_timeout, and an app action’s own timeout_ms, to that), so the caller is not answered timeout while the call still runs. A request that waits in the event queue until its caller got timeout is dropped, not run later (a retry would run it twice); that includes an invoke the 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 less call_ms (LinkCtx::driver_timeout − call_ms, at least 1 s) is answered timeout and not run: call_ms more 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 pack for kind = "wasm": cargo build --release --target wasm32-unknown-unknown --lib --features wasm, then turns the core module into a component in-process with the wit-component crate (bindings from wit-bindgen in wyrm-link-guest carry the component type), then packs it (ADR 0021). One zip for every host.
  • rust-toolchain.toml adds the target wasm32-unknown-unknown.
  • wyr new link <name> --app scaffolds such a crate (lib with the App, src/bin for process, the wasm feature, 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, set on 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 through Host. That ADR is updated when this one is accepted.
  • wyrm-link-sdk gains the adapter; links/wasm gains the app driver next to wasm (point/driver worlds unchanged).
  • wyrm-core must keep building for wasm32-unknown-unknown (CI checks it).

Left to the builder

  • Crate names and module layout; whether Portable<A> lives in wyrm-link-sdk or its own crate.
  • The exact CBOR of who and of AppError; 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 (default false) marks it; the Modbus link adds the kinds ip_slave {listen_host, listen_port} and serial_slave {serial params} beside ip_connection and serial_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, export and import work 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 param writable_by_master (Modbus) and attr.warning on a connection’s status leaf (below). open returns the running server; dropping the transport closes it.
  • Not polled, not pinged. A server connection gets no tickers. Its devices are Connected while it runs, except those the server refuses (Driver::serve returns them with why; they show Failed: Modbus refuses unit 0 under serial_slave, the RTU broadcast address).
  • Values from the tree. Every point of a server takes ~set at level write, whatever the driver’s point_meta says (Modbus: input registers and discrete inputs too, which a master cannot write). Driver::write puts 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: an f32, 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 as bad/config_error with the old value kept, also when the point is bad already (bad/disconnected while 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 ~val with 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::remote takes it (cancel-safe: it awaits only the receipt), Driver::apply_remote answers it under the plan’s read lock once the server has the plan in force. The framework passes since, 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 no sys/audit record (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 a config action). The server listens on every address the host name resolves to (localhost: ::1 and 127.0.0.1), and the bound addresses are checked: one that is not loopback is logged at warn when the server opens and shown as attr.warning on the connection’s status leaf (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_actions instead of Driver::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_master defaults to false; it does nothing under a master connection, and poll_s and 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_slave is supported only as the only slave on its line (point to point to one master, ruling P27). The tokio-modbus 0.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 ServerKind trait beside Driver, 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 error leaf: 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;
  • /query is $invokable: read, and invoke runs 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, one list per visited node, one subscription per row and column, unbounded rows, columns and invokes; one query can stall the broker;
  • expression is 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; sublist removes 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;
  • invoke fires 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

  1. A query is configuration: stored, validated, running on the broker offline for months, back by itself after a restart (as a schedule, ADR 0022).
  2. One language core for every way DQL runs: the link (embedded, process, WASM) and the CLI.
  3. Results are ordinary nodes: anyone with read subscribes to a query’s table; a dataflow, the explorer, the MCP server and an upstream site use it with no new protocol.
  4. Bounded cost: per query and per link limits on rows, lists, subscriptions and sink calls; zero messages at idle when nothing changes.
  5. A query cannot do more than its author may do; reading results never gives more rights than defining the query.
  6. DSA queries import with a converter (/downstream/X/* → wy/<site>/downstream/X/**).

Non-goals

  • SQL, joins between queries, aggregation over time (history has Get History with 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 invoke repeated 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, as wyrm-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 crate cel-interpreter (0.10, features regex, chrono; checked 2026-10-30 to build for wasm32-unknown-unknown); regular expressions are CEL matches() (RE2 syntax, crate regex). Our own code is only the pipeline parser and the row engine. CEL is not Turing-complete (no loops, no recursion; macros like all/exists are 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 5 maps 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 is null. 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 with too 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 through convert_dsa {text, site} (? → *, a trailing * → **, /downstream/… → wy/<site>/downstream/…).

The language (WYRM dialect; DSA names kept where they map)

CommandWYRM 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 sitesRows 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>]]… / childvalue (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::Value maps to CEL values one to one (map, list, int, uint, double, string, bytes, bool, null; the sample time as a CEL timestamp). No functions of our own in the first version. An expression that fails on a row (a type error, a missing key) gives null in that column and a count in the query’s errors, not the end of the query; a text that does not compile is refused at add_query/run with 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 (as wyrm-client list): App::on_list(sub, key, change) with change = Refreshed(children) | Added(child) | Changed(child) | Removed(name) | Disconnected, a child = (name, NodeMeta). Needs read on the key; ended by unsubscribe; counts toward a new bound max_lists (2 000 per instance). A full queue coalesces a list’s changes into a Refreshed.
  • Host::subscribe(key) accepts one final /** segment: one subscription for a subtree (fan-in); read on the prefix; each sample comes with its node key (on_value already has it). No other wildcard.
  • WIT: wyrm:app@0.1.0 stays frozen (ADR 0022 ruling 2), so components built on it keep loading. A new wyrm:app@0.2.0 world is a superset: import list, export on-list; the WASM host tells the two worlds apart by their exports (as it tells point from driver). The scheduler moves to 0.2.0 only when it is rebuilt.
<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: table is published when it changed, at most every publish_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_table pages 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): run returns the id and the table key of a temporary query with ttl_s (default 300 s, ≤ 3 600); get_table or run again with the same text renews it; identical text shares one (DSA QueryManager). With id the 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 flow invoke sink calls run {id, text} (or the engineer defines a standing query) and a flow subscribe source reads <id>/table, waiting for status: ready when it needs a complete table. A one-shot query {text, timeout_ms} -> rows that 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) and q/<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; list runs only on the levels the pattern can reach.
  • Bounds (constants of links/dql, one place each, refused with resource_exhausted before the host would fail the event): 200 queries; rows per query max_rows (default 1 000, ≤ 5 000; over it the query shows error: max_rows and 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 in 0 ms timer events (ADR 0022 ruling 5); nodes 5 per query (1 000 queries’ worth below the 10 000-node host bound).
  • Sinks (D3, D5): set and invoke fire when the values they use change, and not for a row whose values are null (unless invoke_allow_null). After a start (a restart, an edit, enabled on, 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 in errors and logged at info (ids only, never values); it is not retried (an action is not idempotent).
  • Rights (D2; as ADR 0022 ruling 6): a ptok carries 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::scoped keeps the level). So:
    • a query without sinks (add_query, run, edit, remove) is write: engineers, the agent (capped at write) and dataflows (the flow key is trusted at write; a deploy proof per target, ADR 0008) may define and run them; whoever has write on the DQL link may read what the link reads — the guide says so, and roles that must not see the whole site get no write on it;
    • a query with a sink (set, invoke) needs the caller’s effective level config on the action key: the app checks who and refuses with permission_denied otherwise. The SDK must give the app the effective level (the claim capped by a LimitedKey’s limit), so a flow or agent key never passes as config; the builder checks who_of and fixes it if it passes the raw claim. Flows therefore cannot create sink queries (they have their own set/invoke sinks). Switching a sink query on (enabled), editing it, replacing it by run with its id, and removing it need config too; write may 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);
    • import is config (it may carry sinks); reading results (table, get_table, explain) is read. A query keeps running after its author loses rights (as flows and schedules); created_by = who.subject. The full-grants claim in ptok (the scheduler’s open item) would allow checks against the author’s own rights on every key; not in this version.
  • Grants of the link: embedded — read on wy/<site>/{downstream,dataflows,storage,upstream} and write on wy/<site>/downstream (sinks), signed with its own admin-made key (subject link:dql), trusted by links as a LimitedKey at write, and not by itself (no query writing its own nodes in a loop, ADR 0022 ruling R21). Packages carry no requester grants; an operator grants each root (sys/links/<id>/~act/grant, ADR 0013). A query on keys outside the grants shows status: error with the host’s permission_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: collecting until every list the query started gave its first Refreshed (or failed), then ready; a change later keeps ready. timeout_s (default 30 s, ≤ 600) marks a query ready with error: 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 to ready), 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/**, not wy/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 at wy/<site>/downstream/dql, dql: { enabled: true, store_mb: 16 } in wyrmd.json5; the id dql reserved (validate_new_link_id, Daemon::open refuses a stored link with it, peers.downstream cannot name a site dql); 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 dql runs the same app as a process link.
  • WASM package dql — the same App, --features wasm, world wyrm:app@0.2.0, capabilities = { store_mb = 4 }.
  • CLI wyr query "<text>" — the same engine over wyrm-client with 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 MCP query tool and a flow source node (DSA “DQL as an embedded library”).

Tests and benchmarks

  • Parser fixtures: DSA’s statement_grammar.yaml cases converted, every example of the DSA README converted by convert_dsa and 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, DSA filter → CEL translation.
  • The app on all three hosts with one scenario (as scheduler_three_modes): a query over mock, its table, a restart (definition back, table rebuilt, no repeated invoke), a sink outside the grants.
  • Probe scenario links/probe/scenarios/dql.json; user guide docs/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_ms for depth 2, 4, 8 and fan-out 10, 100 under mock, on this site and across the demo chain (central querying plant through edge).

Consequences

  • ADR 0023 gains Host::list, App::on_list, the /** subscribe pattern and the wyrm:app@0.2.0 world; wyrm-link-api, wyrm-link-portable, wyrm-link-guest, wyrm-wasm-host, links/wasm change; the 0.1.0 world and its components are untouched.
  • New crates crates/wyrm-dql, links/dql; wyr query; the id dql is reserved like storage and scheduler.
  • Spec 02 does not change (existing value types and editors; the table is an array of maps).
  • examples/packages/build.sh packs dql and dql-process.

Rulings of the build (B1 …)

  • B1 — CEL crate: cel 0.15 (cel-rust, the maintained successor of cel-interpreter), features regex only. cel-interpreter 0.10 panics on some invalid texts (1 +: an antlr unreachable!), which would restart the instance; 0.15 answers them as errors. No chrono (its tz database is large in WASM): no CEL timestamp/duration; sample times are microseconds (value.timestamp).
  • B2 — full meta on demand: view=list summaries carry no attr and no actions, which DSA filters use (@mytag). Host::list(key, full): with full the host fetches each child’s whole ~meta (one request more per child). A query asks for it only when a stage reads attr, actions or meta (or list sites).
  • B3 — lists per query: 1 000 (not 500): a site of 900 devices under one pattern fits; over it the query is ready with error: max_lists ….
  • B4 — other sites in the host: BufferHost let a portable link reach only its own site. subscribe and list now reach another site’s keys under an explicit grant; set and invoke stay on the link’s own site (owner decision 8). The embedded link gets read on downstream, dataflows, storage of every site Peers::reachable names, per router build.
  • B5 — effective level in Who: the portable runtime gave the app the raw ptok grants; it now caps each at the request’s effective level (Caller.perm, a LimitedKey’s limit), so a flow or agent token never shows config.
  • B6 — counters: the link root belongs to the host (ADR 0023), so the DQL counters are values under stats/ (stats is 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: as list, a pattern without a wildcard lists that node’s children (sublist ./temp = the children of temp).
  • 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 in wyrm-wasm-host, and e2e dql_embedded_queries_the_tree (the embedded link through a real router: a live table, its publication, a set sink only after a change); scheduler_three_modes and one_app_three_modes pass with guests built on 0.2.0.
  • B10 — the grant a request carries: a ptok carries the first configured grant that covers its key, so a read grant on downstream listed before the write one sent sink writes at read (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, no rhai here (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 effective config.
  • D3 — set sink: 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 on wyrm:app@0.1.0, which lacks on-list. Changing 0.1.0 in place would make the broker expect on-list from every component and refuse the installed scheduler until it is rebuilt and reinstalled everywhere. A new wyrm:app@0.2.0 beside 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_ms 100): the link’s collect_ms 29–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–2 publish_ms later.
  • Across peers (1 000 points, fanout 10, depth 2): collect_ms 55 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 ptok on ~act/* carries the optional claim auth (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 as Who::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, import and an edit of 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 not read, takes no value of a key they may not read, and refuses a sink target they may not write when it would fire (.. may climb out of a root): the query’s errors count it and error names 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 shows status: error until 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 query runs the engine without a bound: the user’s own token reads and writes there.

  • Who reads a table (owner decision 2026-10-31): get_table answers each caller with the rows it may read itself (its own auth; no auth is refused), so the author’s rights make the table and the reader’s decide what of it they see. The live value <id>/table exists only for a query with publish: true (set with config on add_query, run, edit or import): 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’s NetPolicy. 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 as subscribe, at most 5 000 rows per reply, 4 reads at a time) or Get History on sys/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 wyrmd would 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 config on sys.

  • 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. seq is one counter for the store, kept in index.redb and taken in blocks so a crash leaves gaps, never repeats. A row written again (same key, a late or replaced value) gets a new seq, so it is sent again. Each day file records its lowest and highest seq; 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, ops PutSink/RemoveSink, SCHEMA 19); the cursor (confirmed_seq) in the history store’s index.redb, as it moves with every batch. Values link, 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 with seq > after of its watch groups, oldest seq first, at most max (≤ 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 after next, 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, subject link:<id>); the admin trusts that key at read on that sink’s node alone, and refuses next from 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/next only (sinks-<id>-in/-out). Adding or editing a sink makes the link’s requester key, starts a process link again (it takes the key in hello) 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_unsent on 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 highest seq and the day is older than that many days. 0 keeps 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’s tcp-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 only DatabaseProvider (createDbAction, createDb, dbPermission, deleteRange) and Database (performConnect, write, query, queryFirst, queryLast, close, initExtensions). Here wyrm-history-sync owns 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> (crate wyrm-history-sync, done 2026-10-31) runs a target as an App: params sink (the sink’s key), batch (≤ 5 000), idle_s, retry_s, the rest the target’s; nodes status, 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 over Net: 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, its Params, 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 answers not_supported by default) and deleteRange (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 on Services): the host resolves the name on a thread of its own within the call’s time, connects to the first address NetPolicy::allows_named accepts (an IP entry, or a listed name db.example.com:5432 / *.example.com:443 resolving 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 for host against the system roots, or only against ca_pem, with rustls (ring) that wyrmd already links. The connection then takes tcp_send/tcp_recv/tcp_close like 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), and tcp_connect takes 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 imports tls-connect and tls-upgrade came with the world wyrm:app@0.3.0 (ADR 0030, 2026-11-01), with random-bytes for SCRAM nonces: a WASM package built for 0.3.0 has TLS through the same host code; one built for 0.2.0 still gets not_supported.

TargetProtocolTLSIdempotent writeOur client covers
InfluxDB (v2, v3)HTTP, line protocolcloud: yessame measurement, tags and time overwriteHTTP/1.1 request and status only
PostgreSQLv3 wire protocol (own), SCRAM-SHA-256, TLS by SSLRequestusuallyINSERT … ON CONFLICT (key, t) DO UPDATE, one (key, t) per statementstartup, auth, one multi-row insert per batch, ping
DynamoDBHTTPS, JSON, SigV4, BatchWriteItem (25 items, 16 MiB)alwayspartition key site/key, sort key t; TTL attribute as DSASigV4 signing, retry of UnprocessedItems
MySQLprotocol 41 (own), TLS by SSLRequestusuallyINSERT … ON DUPLICATE KEY UPDATE, primary key (key, t), text as hex literalshandshake, caching_sha2_password over TLS only (no RSA exchange), multi-row insert, ping
MongoDBOP_MSG, own bounded BSON, SCRAM-SHA-256Atlas: always_id {k, t}, update of replace-upserts with ordered: false; TTL index on tshello, auth, insert, ping
  • Order of work. 1) journal, sinks and the feed in wyrm-history and the admin, with e2e (late row resent, resend after a lost reply, keep_after_sync_days); 2) tls-connect in world wyrm:app; 3) wyrm-history-sync and 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 (with tls_upgrade in the host). Step 4 done: DynamoDB, MySQL, MongoDB (SigV4 and SCRAM shared in wyrm-history-sync, with http::Client). Done 2026-11-01 (ADR 0030): the WIT imports tls-connect, tls-upgrade and random-bytes in wyrm: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 from Host::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_rows grows and rows_dropped_unsent counts 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_days higher 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 wyrmd for 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

  1. 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.
  2. keep_after_sync_days default — decided 2026-10-31: 90 days.
  3. What a sink takes — decided 2026-10-31: a list of watch groups per sink, empty = all; e.g. InfluxDB takes energy and diagnostics, DynamoDB only energy.

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 implements wyrm_filestore::Backend (probe, scan, mkdir, put, get, delete) and runs as FileStore<B>, a raw-layer Link in crates/wyrm-filestore. Each is its own driver, package and process binary; none adds a dependency the workspace did not have (SigV4 and the JWT on ring, XML by a small reader in the toolkit, Drive JSON on serde_json as store data, not the wire).
  • Raw layer, the framework’s conventions. Connections come from add_connection (the backend’s params plus refresh_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 the dest fields stay the same, as the framework’s keep_secrets), remove, stop/start. They are kept sealed in data_dir/filestore.conns with the link’s store key, bootstrap params win when they change — the framework’s persist, reimplemented on the public seal. A connection node has the framework’s status enum leaf (wy:df-status) and the error leaf while there is one, and entries, total_bytes, last_refresh.
  • The tree is the store’s, re-declared on every read (principle 3). <conn>/files is the root folder; a folder node per folder, a leaf per file (value = size in bytes, at the file’s time; attr name, 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 is display.
  • Bounded reads. A read stops at max_entries (≤ 9 000) and max_depth (≤ 12) and says truncated; S3 reads at most 500 pages, a whole read at most 10 minutes. Uploads at most 64 MiB (the gateway’s POST /api/invoke body), downloads at most 16 MiB.
  • Levels. Reads (refresh, download) at read, changes of the store (create_folder, upload, delete) at write, connections at config. 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.get of the root, WebDAV PROPFIND 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 overwrite sends If-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 unless insecure_plaintext; Drive’s API and token URLs must be https:// off loopback.

Consequences

  • Big buckets show in part (truncated); people set prefix (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) or download through invoke sinks 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 provider enum: 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::fs only, every call on the blocking pool under timeout_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’s data_dir on add, edit and start; localfs refuses 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_new otherwise, fsync of 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): without recursive the backend checks the store itself (localfs remove_dir, S3 a list of two keys under the prefix, WebDAV PROPFIND Depth: 1, Drive the folder’s children) and answers “not empty”; the tree may miss hidden names, deep levels, entries over max_entries and new files.
  • localfs needs allowed_roots (Backend::link_options: bootstrap params beside connections, set by the admin; checked by store::validate::<B> in wyrmd and on start). Empty = no directory; /proc, /sys, /dev never; Backend::check_place(data_dir, options) also runs before every probe. Built-in roles with config on downstream/** (engineer) can no longer point it at any host path.
  • Bounded concurrency. One tree read per connection (busy otherwise), two transfers per connection; upload bytes are taken out of the args, not copied.
  • One hung call per connection (localfs Gate): while a timed-out blocking call still runs, new calls answer timeout at once.
  • Files by their real name (View::child_named): Overwrite never patches another file whose path form is the same (Drive a/b.txt vs a_b.txt); an entry a request made whose path another id holds gets the id in its path; Drive lists by name,createdTime and 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_new write 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_s 0 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 gets disconnected, and nothing more of it reaches the store (a recursive S3 delete stops before the next key). A blocking localfs call already in the kernel still ends there.
  • Still open: localfs resolve-then-act races on shared mounts (openat2(RESOLVE_BENEATH) / O_NOFOLLOW are 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 for allowed_roots and the broker’s data directory. Before, a missing root kept its raw path, so allowed/link/.ssh with create_root (where allowed/link leads out) passed the check and create_dir_all followed the link out. The probe checks the place again on the root as it resolves after create_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_place is async; localfs runs it on the blocking pool behind its Gate, so a hung mount never blocks a tokio worker. The Gate’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 as mode & 0o777.
  • WebDAV delete without recursive fails closed: any PROPFIND Depth: 1 response 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_folder and delete unbounded); a narrowed allowed_roots takes effect on the link’s restart (no reconfigure).

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’s upload_begin {name, size, part_size?, content_type?, overwrite?, sha256?} (level write) answers {upload, part_size, parts}. The connection’s upload_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 .. below uploads). Parts may come in any order, and again after a cut; upload_status {upload} lists the missing ones (at most 1000). upload_commit {upload} answers committing at once and sends the spool file to the store in the background (a large file takes longer than a request may wait); upload_status then says done with the Upload File answer, or failed with why. upload_abort drops it. Parts are 64 KiB … 16 MiB (default 4 MiB); a file is at most max_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 with If-None-Match: * unless it overwrites, AbortMultipartUpload on a failure.
    • Drive: a resumable session (uploadType=resumable, PATCH to replace), chunks of upload_chunk_kib (a multiple of 256 KiB) with Content-Range, resumed from Drive’s Range on 308. The session URL must be on the API’s origin.
    • WebDAV: one PUT whose 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.

  • Downloads in parts: a file’s download_part {offset, length?} (level read, length ≤ 16 MiB, default 4 MiB) answers {data, offset, size, eof}, through Backend::get_range: an HTTP Range request (S3, Drive, WebDAV; a store that ignores Range for an offset past 0 is refused rather than read whole), a seek and a read (localfs).

  • Ownership and bounds. An upload belongs to the ptok subject that began it: another subject’s request answers not_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. A sha256 given 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_mib bounds it, and upload_begin refuses 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 etag where 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). Every binary parameter that can be larger than a frame carries it: restore_part.data, a connection’s upload_part.data, the flow engine’s put_artifact.bytes, sys/profiles ▸ put.profile, as install_zip, install_wasm, install_backup, a folder’s upload and storage import already 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. A string or map argument (a branch import, import_dsa, a flow def) cannot take the route and stays within a frame; rule for link authors in docs/links.md §1.
  • A refusal reaches the client. A declared Content-Length over 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 sent Expect: 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 a WyrmException (disconnected, “the gateway closed the connection while <action> sent <n> bytes …”) instead of a SocketException.
  • Tests: wyrm-gateway http_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), wyrmd e2e uploads_in_parts_through_the_gateway (a backup read through the gateway, restore_begin + restore_part by POST /api/invoke + restore_check; upload_begin + upload_part + upload_commit to a localfs store), Dart bulk_invoke_test.dart and 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::invoke sends encoded args over 60 KiB (MAX_FRAME_ARGS) by POST /api/invoke on the endpoint and session of its login, with the same TLS roots, and smaller ones in a frame. It sends Expect: 100-continue and the body only after 100 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, as Error::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 with Error::TooLarge before anything is sent.
  • No frame over 64 KiB leaves the client. A set, check, history or any other request over MAX_FRAME is Error::TooLarge at 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. A Conn::from_raw connection (the gateway’s own /mcp, in process) has no HTTP route: an invoke over 60 KiB is TooLarge there.
  • A large string or map argument has no route; the limit stays. A branch import {json}, import_dsa {json}, a flow def (deploy, validate, put_block) and a storage publish value must fit 60 KiB. They are not marked editor: file: spec 02 makes that a binary parameter 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 with editor: file takes more”. When a real case needs more, that action gets a binary editor: file parameter beside the text one, as storage import {data | file} has; the gateway and the clients need no change.
  • wyrm-agent invoke takes --args-file <path> and --file <param>=<path> (the bytes of a file as a binary parameter, at most 64 MiB + 64 KiB).
  • Tests: wyrm-gateway rust_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; TooLarge over the limit and for a set/check over a frame, the socket still open; 401 with “log in again” after the user is disabled), wyrm-mcp a_large_file_argument_goes_by_http (300 KiB $bytes over TLS with --gateway-ca, the dry run, a text argument refused), wyrmd e2e uploads_in_parts_through_the_gateway (now restore_part and upload_part by the Rust client, a 100 KiB storage value refused with the text), wyrm-agent invoke_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.

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 ~set waits behind a running read action (read_registers, scan_units) on the same connection for at most the driver timeout (5 s) and may answer timeout (Modbus parity plan, ruling P33; docs/modbus.md).
  • ip_slave binds its port when the connection starts. If the router still holds the port during a rebuild, the connection goes Failed and 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 206 reply must carry a Content-Range that starts at the asked offset; otherwise the part is refused, not used.
  • A 416 reply for an offset at or past the end of a file answers {data: [], eof: true} with the size from Content-Range: bytes */<size>.
  • upload_begin refuses 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_period with connection and device params, the sample time from the driver, ~meta from device data, a driver-owned connection leaf) are work items in docs/backlog.md, not decisions.
  • The wyrm:app world 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. A wyrm:app/host version 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 BufferHost of the call, and so to the RuntimeServices that the native engine uses. The net allowlist (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 outside net gives permission_denied, as for tcp-connect. The keys stay in the host: the guest sees a connection id and plain bytes through tcp-send / tcp-recv.

  • Random bytes. Host::random_bytes(n) and Services::random_bytes(n), with a default not_supported. BufferHost refuses n above MAX_RANDOM_BYTES (1024) with invalid_parameter, before the services see it. RuntimeServices fills the bytes from the OS (getrandom, already in the workspace).

  • The SCRAM nonce (wyrm_history_sync::scram::nonce(host, conn)) takes random_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 with Retry (amended 2026-11-15, audit of #125: any error fell back to the clock before).

  • The guest and the packages. wyrm-link-guest builds components of 0.3.0, so the scheduler, DQL, the five history sync links and examples/links/portable build as 0.3.0. wyr link pack writes the version into the manifest: world: "wyrm:app@0.3.0". The broker checks a versioned world against the component’s version. A plain app still 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 app or wyrm: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_loads and an_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 (wyrmd e2e: 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 beside wyrm: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

  1. 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::ports and nodes::build ask it first. The catalog lists them for the editor.
  2. 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 list inputs (default 0, 1, at most 64), ports in.<name>; a name may not be a parameter’s.
  3. 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.
  4. 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}.
  5. 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.
  6. Numbers as in the prototype where it matters: integers stay integers while they fit, divide gives a float, non-finite results are null, modulo’s quotient goes toward 0 and its remainder is never negative, round to 0 places gives an integer.
  7. scale keeps its meaning. k × in + b stays; the range form (input_min … output_max, output input_out_of_range) applies only once a range parameter is set or arrives. An existing scale with no config stays the identity.
  8. stopwatch runs on a 50 ms clock (the runtime reads tick_every once), counts at most every 0.05 s, and keeps its count across a hot swap.
  9. trace logs at trace only: its lines hold values.
  10. The editor draws fixed ports and named ports together (if: in.then, in.else, then in.0, …); dyn_inputs adds to inputs instead of replacing it.
  11. Texts a block makes are at most 4 KiB (concat, string), as the expression engine’s strings; a longer one is null (concat: quality bad). A concat in a loop through a delay would otherwise grow without end (automated review of e89b1d4).

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

  1. wyrm-agent is a binary of links/agent (feature cli). 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.
  2. JSON lines out, so an assistant reads the answers without parsing text.
  3. Plans: run <plan> checks each step against the live ~meta (action, argument schema, value bounds, through wyrm_mcp::check) and prints what it would do; --apply runs the steps in order and stops at the first failure. A step on a node an earlier step creates is checked when it runs. unless makes a plan safe to run again; deploy raises the flow’s version itself; wait and expect let a plan prove its own result.
  4. The password only from the environment (WYR_GATEWAY_PASSWORD), never an argument.
  5. Skill .claude/skills/wyrm-agent tells 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.json by 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

  1. An alarm comes from the live tree (a watch’s condition) or from a caller (raise: a dataflow’s invoke sink, the agent, a person); the record is on disk before the event that made it ends.
  2. 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.
  3. Bounded: nodes, subscriptions, open records, records on disk, rows per answer, work per event; zero messages at idle.
  4. 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 next as the historian’s.
  5. 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.
  6. 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 alarms table.
  • 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

  • Class: id (key segment), display, escalation1_s, escalation2_s (0 = off), created_by, its watches.
  • Watch: id (w<n>, never reused), source (a key wy/<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 equals alarm_value (default true; a number is true when not 0, text true/false);
    • out_of_range: in alarm while the value is below min or above max (either may be absent); back to normal only inside by deadband (hysteresis; a value that is not a number is ignored);
    • staleness: in alarm when no sample came for stale_s; the next sample ends it;
    • quality: in alarm while the sample’s quality is bad, or also uncertain with include_uncertain.
  • Record: id (one counter for the link, never reused), class, watch (none for raise), 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 (no normal) 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_s before a record is made and be gone to_normal_s before 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’s t (links stamp samples on their own clocks).
  • Escalation: a record unacknowledged escalation1_s after it was created is at level 1, escalation2_s after 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 with resource_exhausted before 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 shows error); 10 000 open records (over it, the oldest record that is normal but unacknowledged is acknowledged by system: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 in 0 ms 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>: page n of records, ids 64n … 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 page n, the ids of the records that changed, entry seq = 256n + i (CBOR array). Every creation and change appends one entry; sinks read from a cursor on seq. 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) and page_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), so meta is not written per record and a crash between a page and meta loses nothing. After a purge of every page the ids go on after the pages that went (first_page × 64).
  • Retention: retention_days (365) and max_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_exhausted and leaves the state as before; for a record made from a sample it is logged at error and the record is dropped (counted in stats/dropped): nothing is half-saved.
  • sinks/<name> on the link, added with add_sink {name, link, classes?, from: start | now} (config): the link id that reads it (it signs as link:<id> with its requester key), the classes it takes (empty = all), and where its cursor starts. Its node’s value is confirmed_seq; attributes link, classes, lag_entries, rows_sent, dropped_unsent, last_request. Actions next {after?, max?} (read; refused for any subject but link:<its link>: a person who ran it would confirm rows the database never got), edit, reset {from}, remove (config).
  • next answers exactly as sys/history/sinks/<name> does: {rows: [{seq, key, t, v, q}], next}, after confirms every entry up to it, at most max (≤ 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’s created, 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 later Target of wyrm-history-sync; nothing here changes for it.
  • wyrm-history-sync takes a sink param of either shape, wy/<site>/sys/history/sinks/<name> or wy/<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, read on the sink’s key, ADR 0013); a sink’s link must be a link id, and the admin’s audit of the next call names it.

Rights (ADR 0022 ruling 6, ADR 0025 item 4, ADR 0029)

  • add_class, a class’s edit/remove, raise, acknowledge, normal, add_note, ack_all: write. get_alarms, get_alarm, get_notes, a class’s export: read. add_watch, a watch’s edit/enable/disable/remove, import, add_sink and 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_watch and import refuse a caller whose token carries no auth (DQL’s rule), refuse a source the author may not read, 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_note and ack_all check the caller’s auth for read on the record’s source, and refuse a caller without auth (their rights are unknown). raise needs none beyond write on the link (a dataflow’s token carries no auth); its source must be a key of this site’s tree. A class’s table value <class>/alarms and the counters are for whoever may read those nodes (as a published DQL table): an engineer who gives a role read on the alarm link gives it the site’s alarms.
  • The embedded link reads wy/<site>/downstream, dataflows and storage (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 grants read on 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).

  • 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: start declares 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 in 0 ms 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 for enum params, as the scheduler’s confirm); 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 for normal.
  • Run modes: embedded in wyrmd at wy/<site>/downstream/alarm (alarm: { enabled: true, store_mb: 64 }; the id reserved like scheduler and dql; its store key and requester key made by the admin, R22 on failure); process package alarm-process (wyrmd link alarm); WASM package alarm on world wyrm:app@0.3.0, store 16 MiB.

Consequences

  • The id alarm is reserved like storage, scheduler and dql; wyrmd.json5 gains alarm.
  • wyrm-history-sync accepts 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’s dataflows and storage too: the verifier caps a caller’s auth to its signer’s scopes, so a watch on storage/… was refused (found on the demo, 2026-11-05). These links answer only under downstream/<id>, so no request they accept widens.
  • A link grant at read lets the router pass <path>/**/~act/next (a sink’s next) as well, as sinks-<id>-in does for the historian’s sinks; no other action, never ~set (a read action can still hand out data: a file store’s Download). Found on the demo (2026-11-05, Docker run with PostgreSQL): a postgres-process link with read on alarm/sinks/<name> could not reach next through the router ACL, while a WASM package (in the broker’s process, no ACL) could. Decided under ADR 0029 and written into docs/links.md § 10.
  • Open items: an alarm target with one column per field (a Target of wyrm-history-sync for 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 at wy/<site>/downstream/uplink in every wyrmd (uplink: {enabled, store_mb, net, upstreams}; id reserved as scheduler and dql are; packages uplink (WASM, world wyrm:app@0.3.0) and uplink-process for a broker that runs it elsewhere). It only reads: read on this site’s downstream, dataflows, storage and on the sections of the downstream sites this broker reads (as the DQL link), never sys. 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 with name, url, enabled, the keys to send (select) and the platform’s own fields; set_password keeps 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} with edit, set_password, test_connection, remove; enabled is writable. Entries from wyrmd.json5 (uplink.upstreams) show with origin: config, read-only but for set_password, as sys/upstream shows 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: select is 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 point max_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 counts dropped. 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 below wy/<site>/), payload JSON {"v": …, "q": "<quality>", "t": <µs>} or the value alone (payload: value), retain on by default, qos 0 or 1.
    • sparkplug (Sparkplug B 3.0): spBv1.0/<group>/NBIRTH|NDATA|NDEATH/<edge node> and DBIRTH|DDATA|DDEATH/<device>; the edge node is the site (edge_node_id), a device is a link (downstream/<link>; dataflows, storage as 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; seq 0..255; bdSeq from 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/Rebirth on NCMD (and DCMD) 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_prefix changes the site part).
    • azure: IoT Hub over MQTT with a SAS token from the device key (HMAC-SHA256, sr=<hub>/devices/<id>, renewed before sas_ttl_s runs out by connecting again), username <hub>/<id>/?api-version=2021-04-12, topic devices/<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 in tls_connect.
    • aws: IoT Core’s HTTPS publish (POST https://<endpoint>:8443/topics/<topic>?qos=1, Signature V4 for iotdata with 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 in tls_connect.
  • Flushing. One timer per upstream: flush_ms (250 by default) while connected and anything is queued, a back-off (1 s ×2 up to retry_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) is failed until Edit, Set Password or Resume.
  • Network. The embedded link’s net comes from wyrmd.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 without auth and a select outside the caller’s read, 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_max samples, 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 with uplink: {enabled: false}.

Alternatives

  • A node under sys/upstream with a kind. 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.
  • rumqttc or 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/broker before it starts, trusts no key while the token is gone, and repeats hello and 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 by lsn.
  • 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):

SystemModelWhat it tells us
IOT-DSANo cluster; upstream/downstream hierarchy, dslinks reconnect, HA at the VM levelWhere WYRM is today
Sparkplug BAn 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 meanwhileOption 2, one to one, with sys/broker as STATE
IgnitionMaster/backup pair, full state sync over its own channel, warm or cold backup, clients and drivers follow the activeOption 3; “warm” = configuration ready, devices not polled
OPC UA Part 4Non-transparent redundancy: cold/warm/hot, the client knows the ServerUriArray and fails over itself; transparent redundancy at the network levelThe cold/warm/hot vocabulary
EMQX, HiveMQ, VerneMQReal clusters: metadata in Mnesia/Mria or CRDTs, sessions sharded by consistent hashing, clients behind a load balancer, their own split-brain rulesOption 5, for cloud MQTT, not for a site broker
MosquittoNo cluster: a bridge, or active/passive with keepalived and a mirrored persistence fileOption 1 plus a VIP
NATS JetStream, Kafka, RabbitMQ quorum queuesRaft-replicated logs, 3 or 5 replicas, leader electionOption 5
Zenoh itselfA mesh of routers, a client with a list of connect/endpoints and retry, storage replication through an aligner (needs timestamping); no consensus, no leader electionOptions 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 restart2. Endpoint lists + liveliness arbitration3. Warm standby, WAL replication4. Mesh of two routers5. Raft cluster, 3 nodes
Effort, days2–35–840–60+10–15 on top of 390–130
Extra hardwarenonenone+1 host of the same board+1 host (the one of 3)+2 hosts
CPU/RAM of the standby00base wyrmd without links, ~1 % CPUthe whole ~val flow on the second router: a second memory storage, inter-router traffic = every sampleas 4 plus consensus on every write
Network between hosts00WAL: bytes per operation, rarely; history ≈ write rate × ~40 B per rowall of ~val, alwayslog + heartbeats
Operationsa systemd unit, a data_dir backupnothing newkey sharing, a VIP or arbitration, replication lag monitoringone more ACL subject, two gatewaysquorum, 3 hosts, runbooks
RTO5–40 s (restart 1–3 s; link back-off today up to 30 s)only with 3 or 410–30 s (detection T + router build + hello)~0 s for readers, as 3 for commands5–15 s
RPO, control plane0 (every WAL append fsynced)0≈ 0 (asynchronous: the last operation may not have arrived)as 30
RPO, history and ~valhistory rows pending a flush at SIGKILL; ~val until re-publicationthe samethe same plus replication lagthe same0 for replicated stores
CoversF1, F5, F6F5 (which router)F1, F2, F3, F6; F4 only with fencingF5 for readersF1–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 ~val flow 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)

  • wyrmd is run under a supervisor (systemd Restart=always, or the container runtime); docs/operations.md documents the unit, the data_dir backup (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_rto kills 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 to docs/backlog.md beside the wyr bench figures 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_ENDPOINT takes a comma-separated list; wyrm_client::endpoint (shared by wyr, the FFI and Dart) takes a list too, and the Dart WyrmGateway.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 hello only on a router where the liveliness token wy/<site>/sys/broker is 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’s STATE rule 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.json5 gets standby: { of: "quic/<active>:7448", ca, enroll } on the standby and peers.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 in secrets.bin and 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 import on the standby), never over the network. The standby then enrolls on the active’s peers.enroll listener as ADR 0015 brokers do and gets a certificate with CN standby:<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, answering next {after: lsn, max} with the raw WAL records from lsn + 1 (the HMAC chain comes with them: the standby verifies every record with the shared state.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 the Ops 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 and sys/standby/{status, lag_records, lag_ms, last_lsn} on the standby show it. Secrets go the same way: secrets.bin records are already ciphertext under secrets.key, so the active ships (seq, name, ciphertext) from sys/replication/secrets and the standby writes them as they are.
  • Promotion and demotion (stage A). The standby keeps a liveliness subscriber on wy/<site>/sys/broker through its QUIC session to the active. When the token is gone for standby.takeover_s (default 10 s; the session loss itself counts), it promotes itself: opens the router with the full configuration, declares sys/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 a Promoted {from_lsn} record into the WAL and the audit journal. The former active, when it comes back, first looks for sys/broker on its standby peer; if the token is there it starts as the standby of that host (Demoted record) 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 second broker:<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, only standby.of as 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) and standby: { peer: "quic/<other>:7449", takeover_s: 10, primary }. There is no peers.standby on the active and no standby.of: either host may be the active one, and wyrmd decides at start. Both wyrmd.json5 files should otherwise be the same (links, gateway, admin_keys): a promotion opens the daemon on the followed data_dir with 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 empty data_dir; WYRM_KEYS_PASSPHRASE or 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.key and the gateway’s hmac.key and gateway.key, so the standby issues itself a standby:<site> certificate from the CA (data_dir/standby/). Import refuses to overwrite any of those files. The ACL subject standby (CN standby:<site>, QUIC) exists whenever peers.listen is 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’s LOCK. It applies nothing: a promotion is Daemon::open, which replays the WAL as after any restart. The audit journal is not replicated (it stays on the host that wrote it). With state_anchor_dir the 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 every links/<id>/token (the plaintext a link’s hello carries; its argon2 hash is in the registry) are listed by sys/replication/files [{name, sha256}] and fetched by sys/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 Delete of wy/<site>/sys/broker, or from a failed connect. A primary: true host takes over after takeover_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, promoted and demoted by system, 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 more host:port on 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 of takeover_s (isolated, audit demoted “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; without standby.arbiter it 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 by wyrmd arbiter issue --host <h> --out <d> on a broker of the pair (the site CA certificate, arbiter:<site> for h, the site name; no private key of the site). TLS over TCP with the site CA on both ends; the arbiter takes only a standby:<site> client certificate. One request per connection, u32 length + canonical CBOR: {op: hold|release, holder, ttl_ms} → {state: granted|held|recovering|released, holder?, left_ms}; holder is the host’s own random id (standby/host.id, not replicated) joined with a hash of its standby.peer (a data_dir copied from the other host still gives another name). The broker checks that the arbiter’s certificate is arbiter:<site> (the site CA signs links and lower brokers too), builds its TLS client from the current standby:<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_s on 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 with follow_with). The lease lasts half of takeover_s within 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 real wyrmd process: 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-storage JSON); 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 as sys/replication/forked/<t_ms>/<what>/<count>/<n> (kept in standby/forks until answered; any answer counts, an older active answers with an error), and the active writes one audit record standby_forked (key = the set, detail = the place on the other host) per (t_ms, what) and counts them in sys/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 mark active seq → local last_seq after 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 in standby_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 as hold_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) and sys/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 real wyrmd process: 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).
  • 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.bin carries), 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 and uploads/ 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 from secrets.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’s seed.done and seed.progress.json (top level of data_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::Store keeps a revision counter with an epoch (set at open) and a journal of its last 20 000 changes, and the active answers storage/<epoch>/<since>/<max> with the changes after since as {epoch, rev, full, put: [[path, rec]], delete: [path]}, the whole tree when since is 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.bin with 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 name standby-<id>, where id is the active store’s identity (meta/id in index.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 committed sequence; store_put/store_delete get a journal (seq, key, ciphertext) under the store key, served as sys/replication/stores/<link> with next {after, max}; the framework’s driver::persist writes join the same journal for framework links. The standby writes the ciphertext files as they are. Storage (wyrm-storage) gets a seq per change and the same next, served as sys/replication/storage.
  • History (stage C). The standby is one more history sink reader: a Target of wyrm-history-sync that writes into the standby’s own wyrm-history store (crates/wyrm-history-sync, ADR 0026), reading sys/history/sinks/standby with next {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 own setup_file, and since users replicate, the other host’s setup is void once an admin exists), packages in data_dir/packages (stage B copies package files by SHA-256 through sys/replication/packages, since a link install is an Op that 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; a set works), old_active_demotes (it comes back and becomes the standby; its stale WAL tail after the fork point is refused and archived as wal.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_dir is 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_s plus a router build plus every link’s hello and re-publication. On F4 the links serve whichever broker they reach; two reachable brokers with two tokens are an operator error visible in sys/standby/status and in the audit, not a data corruption: each link serves one.
  • Base RAM of wyrmd without 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_dir at 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 ~val on 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 hello and 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

  1. studio/ is the app, created by frx create wyrm_studio --org uk.gencto --title 'WYRM Studio' --without http_client (frx 0.3.7). Its own CLAUDE.md, .claude/skills and hook come with it; work on Studio from studio/.
  2. dart/wyrm_flutter is removed. Its code stays in git history (6199482) as a reference for the tree’s lazy loading, editor: file uploads and the ADR 0019 editor.
  3. dart/wyrm_core, wyrm_client, wyrm_ffi stay where they are, outside the Studio workspace, so the fixture job in CI keeps running with plain dart. studio/business depends on wyrm_client by path; it takes the place of the template’s http_client (the gateway has four REST routes; everything else is CBOR frames over one WebSocket).
  4. Every artifact is made with frx, by hand only inside bodies. The scaffold is declared as batch files in studio/docs/batches/ (checked with frx 0.3.7: applied in order on a fresh project, frx doctor reports only the codegen it has not run). After a hand edit: frx doctor, then dart analyze.
  5. 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.
  6. 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 and args verbatim (security review).
  7. The look comes from the design canvas: its tokens replace the template’s _Brand/_Neutrals constants and AppColors; IBM Plex Sans/Mono are bundled (no font download at run time: edge machines are often offline); icons are the canvas’s SVG paths in ui/assets/svg/icons/.

The plan, phase by phase with the commands, is docs/studio.md.

Consequences

  • Studio targets desktop and mobile first. wyrm_client uses dart: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 frx sources, its CI) is not in this repository; frx is installed as a binary (frx upgrade).

Alternatives

  • Keep wyrm_flutter and 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 get in dart/wyrm_core would 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 ~val and the publish nodes’ values; nothing per port (runtime.rs run_node only routes outputs);
  • lets a logic block’s parameter be config and port in.<p> (ADR 0032 §2), last sample wins, but node_types does not say which parameter has a port, gives default only 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 p of a node: an output port p carrying the parameter’s effective value (config or default, replaced by the last sample on in.<p> where that port exists). It sends once when the node starts and then on every change.
  • For each input port x that is not a parameter’s port (in, in.0, in.1, …): an output port x that repeats every sample the node receives on x, 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.rs endpoint), so a.in.0 is node a, port in.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: latch has the input reset and the parameter reset, 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), default as a typed value for every parameter that has one (a number stays a number; choices keep their string), echo (true unless §1’s clash rule removes it);
  • per node type: port_types: {<port>: <type name>} for inputs and outputs (number, bool, string, any, … as PortType::name), and echo_inputs: true when inputs repeat as outputs.

3. dataflows/<id>/~act/watch — live values of a deployed flow

  • Level read on dataflows/<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 ptok auth (spec 04, as DQL queries) must cover reading every source (subscribe, liveliness) and every command target (the node of each invoke/set) of the flow; otherwise permission_denied naming the first key the caller cannot read. The values of a flow are derived from its sources, an invoke node’s output carries its target’s answer and a set node’s input is what it writes there (security review 2026-11-08).
  • Rows:
    1. 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;
    2. then: the same shape with snapshot: false and only what changed since the last row, at most max_hz rows per node per second (the latest value wins inside a period);
    3. a heartbeat {t, nodes: {}} when nothing changed for 10 s (the gateway’s idle wait per reply is timeout_ms + 5 s);
    4. 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.
  • 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 (busy beyond).
  • 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 dataflows root: level read, stream: true, timeout_ms: 30000. Args: def (a spec 06 definition, the shape deploy takes), 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 wasm artifacts included); an error is invalid_parameter with the compiler’s message. version, enabled and permissions.maxperm are not checked against anything: nothing is deployed, and no proofs are needed, because nothing is written.
  • Rights: as watch (§3): the caller’s auth covers read on every source (subscribe, liveliness) and every command target (the node of each invoke/set); otherwise permission_denied. A read user may preview a draft with a set it 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 which set, invoke and publish are capture nodes. A capture node holds no client, no writer task and no ctx, and never reads its Io. It applies the deployed node’s own rule (allow_bad, on, deadband, $in in args; one function for both modes) and reports the result. An invoke capture sends nothing on out (there is no answer).
  • Rows: exactly watch’s (§3: snapshot row, change rows at most max_hz per node, heartbeat {t, nodes: {}} after 10 s), and any row may carry sinks: [{node, op, key, value}]:
    • op is set, invoke or publish;
    • key is the full key it would write: wy/<site>/<path>/~set, wy/<site>/<path>/~act/<action>, wy/<site>/dataflows/<def.id>/nodes/<node>;
    • value is the value it would write, or for invoke the 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 with nodes: {} and snapshot: false). nodes filters 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 with internal_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, delay and window run as in a deployed flow.
  • Caps: at most 2 previews per subject (origin, else sub; a third ends that subject’s oldest) and 16 per site (busy beyond). 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 ~set of 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): scale k, b; alarm high, low, hysteresis, delay_s, return_delay_s; delay ms; window size_s; deadband abs, pct; timer period_ms. Each is a number port, listed in the catalog’s inputs and as the parameter’s port. 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 (high or low, abs or pct, period_ms, size_s, ms required): 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. A delay sample 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, bool or map as the parameter’s catalog type, every other type (string, dynamic, array) any. Every parameter has an echo, inputs/outputs/args included, and every node type, wasm included (there a declared output keeps its name over an echo at compile time).
  • port_types lists the fixed inputs and outputs, the dynamic ports of their default names (in.0, in.1) and every echo output; dynamic ports of other names are any.
  • A parameter’s echo sends at start, so an edge from it to invoke/set fires a command at deploy (the one exception to ADR 0032’s rule; docs/flow-blocks.md warns).
  • 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, else sub) ends that subject’s oldest watch (on the flow; at the site cap, anywhere on the site); another subject’s watch is busy. An editor that reopens on every start stays within the caps.
  • permission_denied travels 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_ctl has variables feeding concat1; a variable sends once at deploy, so a watch opened later showed in/out empty 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 and ports show 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 s KEEP time is gone.
  • Ends: ttl, remove and an engine stop end the stream without a row; a redeploy ends it with {t, redeployed: <version>}. nodes absent or empty = every node; an unknown id is invalid_parameter; max_hz outside (0, 20] is invalid_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: subscribe and liveliness keep 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 InUse on a restart of peak_shaving_hot_swap_and_restart): the store (FlowHost, its WAL and LOCK) is free when the link’s stop returns, so a restarted engine opens it at once (ADR 0036 restarts). Rules: (1) an aborted task is awaited after abort(): 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 its watch and ports tasks 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 answers Cmd::Stop (before, LinkHandle::stop could 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), SDK stop_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": 5 keys: 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) or in.<name> of its inputs; never a parameter’s port (that parameter’s config is its constant), never stopwatch.reset (an event), and not the variables (number, string, bool: their value is the constant). Anything else is a compile error nodes.<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/preview show 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 set or invoke because 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 a set does 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, in included, so a variable feeding a set keeps 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 and docs/flow-blocks.md “What calculates at start”.
  • Scope: the logic blocks (crate::blocks). Not expression and the older types (their single in is the sample they act on).
  • Catalog: per type values: true when its operand inputs (fixed inputs and the dyn_inputs ports that are not a parameter’s port) take a constant.

8. Text operators, round.text and case (2026-11-08, spec 06 0.2.21)

  • if.op gains != (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; a null other never matches; a null first is empty text). Names are snake_case (ADR 0032 §3): camelCase spellings are refused at compile.
  • round.min_precision (port in.min_precision, no default = precision) and a new output text: a rounded number is often shown as text with its places; WYRM keeps out a number (its port type, its edges) and adds text with precision places, trailing zeros trimmed down to min_precision places.
  • A case block: input in; op (=, !=, >, <, >=, <=, contains, starts_with, ends_with, default =) and else (default null), both with ports; the variable inputs inputs are pairs (case value, then value), usually given as constants in values (§7). It sends the then of the first pair whose case matches in, else else; it calculates on any sample, as every block. An empty case text matches nothing in the text operators. regexp is 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:

  1. 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 with write could send to any chat the bot is in; nothing is reusable or reviewable.
  2. 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.
  3. 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 at write whose 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-messenger holds what every chat platform shares — bots, recipients, templates and their escaping, the queue and its pacing, pairing, chat commands and the three bounds — as Messenger<C>, a portable App over a Platform description: the API’s paths, request bodies and reply classes, the token’s shape, chat and thread ids, the send_raw allowlist, 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>, packages telegram and telegram-process) and links/slack (Messenger<Slack>, packages slack and slack-process). What a platform cannot do is not declared in its tree (a Slack bot has no users, no Invite User, no commands). Another messenger (Teams, Discord, Mattermost, Viber, Signal…) is one more crate with one Platform; a feature only one platform has is a field of Platform or an action of that link, never a branch on the platform’s name in the core. The test kit (wyrm-messenger feature testkit) 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", a read grant on the roots templates and chat users name, write for /set and /do). Root action add_bot (config); a bot is <bot>/{status, error, username, sent, failed, dropped, queued, rejected, last_sent, enabled} with set_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_url defaults to the public API and may name a local Telegram Bot API server; plain http only to loopback.
  • Option 3: nodes for configuration, actions for sending.
    • recipients/<r> (config): the only chats a bot writes to — a Telegram chat id, @channel or user:<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 (Telegram html / markdown = MarkdownV2 / plain; Slack mrkdwn / plain, or Block Kit blocks JSON), text with {{placeholders}}, media, lat/lon, buttons (rows of Label | https://… or, on Telegram, Label | /command), silent, protect, preview, default to, and values (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 own send and preview (write) whose parameters are the template’s variables: a flow or the alarm link calls templates/high_temp ▸ send {limit: 80} and needs no knowledge of the API. A template keeps its author’s rights (ADR 0029): values outside them are refused at Add/Edit and never rendered after.
    • <bot> ▸ send {to, text, kind, format, media, lat, lon, silent} and recipients/<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: Telegram chat_id, from_chat_id, user_id, sender_chat_id; Slack channel, 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, Slack file, file_comment), refuses the request. getUpdates, webhooks, logOut, close are 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; 429 holds the whole bot for retry_after; network errors and 5xx back off (1 s ×2 to 60 s) and keep the message (5 attempts); a refused message (400, 403, channel_not_found) is dropped and counted failed; a message whose markup does not parse is sent once more as plain text; a refused token (401/404, invalid_auth, …) makes the bot failed until 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.
    1. 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.
    2. WYRM levels. Defining bots, recipients, templates, users and raw requests is config; sending is write; the host checks the action’s level. Definitions keep their author’s rights (ADR 0029); a token without auth cannot define anything that acts later.
    3. 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 counted rejected; nothing from it is acted on.
    4. 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_code re-pairs (a lost phone) and needs the caller to hold the user’s rights; so do edit and enable (amended 2026-11-09: enable hands the rights back to the paired account, the rights kept with the user stay the inviter’s); disable/remove at 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.
    5. Every command within three bounds at once: the user’s own level and select (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 has commands: true and 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 user rate_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, /command buttons and invite_user. The pairing model carries over unchanged (Slack user id + team id instead of the Telegram id).
  • Updates by polling, not webhooks. getUpdates with timeout=0 every poll_s (3 s) — no inbound port, no public URL, works behind NAT; the next offset is kept in the store so a restart never replays commands. A webhook set by someone else on the same token makes Telegram answer 409, 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_raw reaches them at config, 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: false turns 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 messenger link for every platform (the first version, 2026-11-07). Refused by the owner: one package and one release for platforms that differ in features, an add_<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; write would mean “any chat”. Kept as send_raw at config.
  • 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.key and liveliness.key get the input port in.key. The config key stays the start value and may be absent.
  • Scope. A node whose in.key is wired must carry key_scope: a key expression, relative to wy/<site>/ or absolute, for example downstream/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, dataflows or storage, as a static source (spec 06 step 9). The section is a literal prefix of the scope, so no wildcard of it can reach sys, pub, upstream or another site. Checked by deploy, validate, preview and the start of a stored flow.
  • Deploy. The deployer’s auth (spec 04) must give read on all of the scope, as it must on a static key. reads_key walks the grants in the responder’s order: a grant below read that 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::admit takes 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/~val suffix, no empty segment, no selector); inside this site’s downstream, dataflows or storage; and included by the scope. A static key of the config may still be a pattern; a key from a port never is.
  • A new key. The old read ends first. out sends null with quality uncertain, and stays so until the new key’s first sample. The node’s effective key (its echo output and params.key in watch) 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. out is null/uncertain, the effective key is null, and the new output error carries the reason as a text. error goes back to null with the next admitted key. The refused value is never logged.
  • null on 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 …/~set or …/~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):

FieldPortDefaultMeaning
interval_msin.interval_ms0Above 0: a run every period. 0 is off; else 100 … 86 400 000. A value from the port outside these is ignored.
auto_runin.auto_runinvoke: false · set: trueinvoke: a sample on arg.<name> that changes the argument runs the action. set: a value on in is written (today’s behaviour).
enabledin.enabledtrueFalse: 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.

OutputTypeWhen
senteventThe request leaves the engine.
okeventThe target answered without an error.
errorevent {event, id, code, message}The target, the transport or the node’s queue refused. code is the status code (spec 04), message its text.
resultanyinvoke only: the last result.
runningboolTrue from the first run handed to the writer until the last one answered.
last_runnumberThe time of the last sent, µs since the epoch.
outanyinvoke 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:

  1. 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 (timer sends 1 at once), the first sample of a read (subscribe, liveliness, also after a new key: the value that was already there);
  2. everything a node sends while it handles a sample with the mark. The runtime carries the mark on, not the blocks: variable → add → trigger is 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 write on dataflows/<id>. The caller’s auth (spec 04) must also give max(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 to maxperm, so a caller with less would run through the flow what it may not run itself (security review 2026-11-09). The compiler caps maxperm at write today (spec 06 step 7), so the level is write; the gate follows maxperm so 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 than maxperm. The flow’s token only says that the deployer could; a button is pressed by a person, and that person needs the right. No auth: permission_denied.
  • node is an invoke or set of the flow (the catalog marks these types trigger: true); another node is invalid_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 trigger is 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> }? } }
  • inputs and outputs are 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 for params; 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’s default) that a wire can replace, as every field since ADR 0038 §7.
  • An instance takes values only. 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 an invoke → args; in of a variable → value; an input of an inner instance → that instance’s values. 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). validate and preview compile a draft at level read, 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 for expression and filter. A definition of 1000 expression nodes 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 publish inside a block has the same node name in every instance, so such a block can be used once per flow (validation step 7a).
  • ~def and the history keep the definition as it was sent, with blocks.

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).

ActionLevelArgsAnswer
put_blockconfigname, def (one block, the shape above){name, version}; each put is the next version
get_blockreadname{name, version, def, requires: {<name>: def}}: with every library block it uses
list_blocksread—[{name, version, description?, inputs: [names], outputs: [names]}]
remove_blockconfigname— (not_found when absent)
  • put_block checks the block as a deploy would: alone in a probe flow with the library blocks it uses (invalid_parameter with 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_block and writes it (and its requires) into the definition’s blocks. 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. version tells the editor that a newer one exists.
  • A block holds config, not values; read is the level of history, 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. Fields key (port in.key, scope key_scope), interval_ms, auto_run (default true), enabled; input trigger; outputs out (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: error resource_exhausted). Fields path (port in.path, scope path_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 an error event with invalid_parameter.
  • list_children reads 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 of watch, ports and preview, 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. trigger still ignores a sample born at the start (the start read covers it). The latest read wins; a read without an answer after 5 s is error timeout. load_value reads the broker’s value storage: a point that has no stored value is not_found.
  • The trigger action (§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.

CandidateWhy not now
json_parse, CSV parser and writer, table to JSONPrinciple 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_numberThe variables do it: a number or string block converts what comes on in.
string_format, format_number, trim, left, rightconcat, round.text and substring cover the common cases; a format language is a design of its own.
now, format_time, time_range, the date blocksThey 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 sourcetimer exists; interval_ms on the block is the direct way.
min_max_avgIt 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, boundexpression (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 blocksThey 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/action from a port): §1a. Needs pattern proofs in spec 04.
  • A reader’s button: the trigger action for load_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_start on 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-agent do 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 account ai:<agent> with at most write. 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/me site). 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 returns would_send, plus refused_by_connector when a local switch would stop it.
  • MCP annotations: reads are readOnlyHint, changes are destructiveHint, 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_only refuses every change.
  • allow_config (off by default) lets config-level changes through: a ~set on writable = config, an action of level config, anything under wy/<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 ~meta before 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 from WYR_GATEWAY_PASSWORD, serves stdio. Without --gateway, wyrm-mcp works as before.
  • wyrm-gateway-client speaks https://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. Plain http:// 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; settings gateway_url, user, password (sensitive: kept in the OS keychain by Claude Desktop), gateway_ca, read_only, allow_config), pack.py (the zip) and build.sh (this machine; --universal gives one macOS binary). CI workflow packaging/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 for true/1/yes/on, so an unfilled allow_config is 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-resource and /.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: the client_id is a sealed token of the redirect URIs and the name. Redirect URIs are limited to an allowlist in gateway.mcp.redirect_uris: by default Claude’s two callbacks and loopback (any port on 127.0.0.1/localhost/::1, RFC 8252);
  • /oauth/authorize with 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’s read_only/allow_config. The page is no-store, X-Frame-Options: DENY, and frame-ancestors 'none'. A bad client or redirect shows an error page and never redirects. The redirect carries code, state and iss (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 key wyrm-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, Host limited to the public name) checks the bearer on every request and resolves the user as now. It runs the same GatewayMcp tools 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_json at 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 in wyrm-mcp now. A fix there reaches both the CLI and the connector.
  • wyrm-gateway-client is no longer loopback only. Tools that used it (probe, tests) are unchanged: they still pass http://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 in view=list rows (spec 02 from 0.1.0; fixture meta_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, Url beside URL, Id beside ID.

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 of WORDS written as listed (url → URL, id → ID, mqtt → MQTT, bacnet → BACnet); a last token of UNITS (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 explicit display: sentence case, no _, no trailing dot, acronyms as WORDS writes them, names only from WORDS, NAMES (one word) and PHRASES (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).

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).

  • wyrm_core::display unit tests: the derive rule with acronyms and units, sentence case, the check.
  • wyrmd e2e every_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/**, storage and dataflows; it walks every node and fails on any action or parameter whose display breaks the check (433 actions, 1 122 parameters today).
  • The test hosts of the apps that wyrmd does 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" } } ] }
  • id is the link’s name in lists; crate the workspace crate it is built from.
  • forms: builtin (a driver compiled into wyrmd, its install name), wasm (a package name: one component for every host), process (a package name: one zip per host of hosts). At least one.
  • version is the crate’s; wyrm_link the link protocol (LINK_PROTOCOL); min_broker the 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). Not releases/latest/download/…: “latest” follows any newest release of the repository (a future wyrmd release 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).

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):

keyvalue
iddriver:<code> or package:<code> (Studio’s CatalogItem.id)
codethe name install (driver) or install_repo (package) takes
linkthe official link id, empty when none
title, summary, categorya driver: from the embedded manifest; a package: from its index entry only. Missing: the name, empty, empty
versiona driver: the broker’s version; a package: the index entry’s
formbuiltin, wasm or process
officiala 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.toml and in links/official.json together, 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 read attr.catalog; until it does, both agree because both come from the same names.
  • Windows and macos-x86_64 hosts are not built (no broker host key for Windows; Intel Macs are not a target). Adding a host = one line in hosts and 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}]}
  • columns gives the order; a row is a map. A cell that a row lacks is null.
  • Every table input also takes a list of maps (the rows of list_children, of a split, of make_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 row column: 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 null with quality bad.
  • 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 through table_recorder or keeps it in broker storage.
  • Per-row scripts (table_filter, table_map_columns, table_edit_rows, table_remove_rows) are rhai over the variables row (the row as a map) and index. 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: null and the reason on error), each row the engine’s 10 000 operations.

3. Time

  • A date value is a number of microseconds since the Unix epoch, as t of every sample, HistRow.t and last_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 is UTC, 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 is jiff’s bundled tzdb, as in wyrm-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 relative date_range) reads it once per calculation through the runtime’s clock; the pure functions take now as an argument, so tests are exact. A relative range is calculated again on a clock of 1 s while its input is relative, so today rolls over.
  • date_range takes week_start (default monday) and time_zone; previousN<unit> is the period before currentN<unit>.

4. Readers

  • load_history reads the historian (~val?history=, ADR 0014) through WyrmClient::history: its rows {t, v, q} as a table, at most limit (1 … 10 000) rows. An answer that reached limit may have more: the ok event says truncated: true and rows, so the cut is never silent. A table past 512 KiB is an error event with resource_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_history each (the same window) and table_join on t: one key per reader keeps the scope rules as they are.
  • get_node reads 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, as load_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 (level read), instead of a command target’s max(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 every set and invoke downstream 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: const with null stands 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 default is 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 born rule covers the start of a flow.
  • No block panics; a bad input gives null (quality bad where the input was valid but too large).
  • median of an even count is the mean of the two middle numbers; date_math counts years, months and days on the calendar of time_zone, so a day over a DST change keeps the wall time.
  • modulo’s remainder is never negative, max/min of no number are null, scale does not clamp, split gives a list, substring clamps 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 a max_rows in 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, watch and preview; catch_error takes 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 (port in.interval_ms, default 1000; 0: only on samples of in; 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, now sends the time once at start, made of constants (it runs no command), and then every period; those ticks are ordinary samples, as a timer’s. A sample of in gives the time at once too.
  • in is only a trigger: it takes no constant (values: true is dropped from its catalog entry). A values saved before is read and ignored, so a stored flow still compiles.
  • ОБЕРЕЖНО: a now stored before 0.2.30 has no interval_ms, so after the upgrade it also sends every second (the default). Its ticks are ordinary samples: a now wired to in of a set or an invoke, or to a trigger, then runs that command every second. Set interval_ms: 0 to keep the old behaviour (only on samples of in). No deployed flow of the demo has a now (checked 2026-11-11).

Consequences

  • node_types lists the new types; the catalog gains display per 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:

  • ~val of dataflows/** 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_in counts 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 a subscribe). Internal messages are not samples: a command’s or a reader’s answer, a reader’s own read request and ~act/trigger.
  • samples_out counts each sample a node sends on an output that has at least one edge (once, however many edges leave it). Writes of publish, set and invoke leave the flow through commands (or the published node), not here.
  • commands counts the events sent, ok and error of the invoke and set blocks (spec 06 0.2.23). error includes a run refused before it was sent (busy: the call queue is full), so ok + error may exceed sent.
  • dropped counts the inbox drops of drop_oldest/drop_newest and of a source that pushes into a full inbox under block. A publish that 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 start and at reload;
  • kept across the supervisor’s restart after a node panic (restarts grows);
  • 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 ~val at 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 ~val only when its counters differ from what its last ~val carried. An idle or stopped flow publishes nothing.
  • The period is FlowHost::set_stats_every. wyrmd sets it to metrics_interval_ms (the sys metrics 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: 2 and its error while 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 ~val would 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.ok against commands.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 ~val now 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_t changes 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-mcp returns stats with a flow’s state. Studio and wyr flow do 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/stats instead 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

  1. check_grant takes wy/{site}/storage[/…] as a third root.
    • list and read on any path in it, the root included.
    • write only 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.
    • config stays for people, as everywhere.
  2. The router ACL needs no change: grant rules are built from the path (grant-<id>-*).
  3. 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.
  4. A package may ask for storage in requester with 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 write on 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), e2e link_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

  1. Spec 05 0.2.33: get path/~act/<a>?check with the action’s arguments. The responder checks the call as the action would take it: ptok and 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 is status=ok without a payload, or the refusal the action would give (same status, same text). The audit records check.
  2. A responder that answers check says so: attr.check = true on 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 ?check only where the root says so; without it the check ends at the action’s meta on the requester’s side, as before.
  3. SDK: Link::on_check(path, action, args, who), default Ok (the SDK’s checks are all there is). Portable links: App::on_check, default Ok; 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).
  4. A WASM component of world wyrm:app 0.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).
  5. Gateway op check {key, action, args} (rights as invoke); WyrmClient::invoke_check; wyrm-gateway-client::Conn::check. The MCP connector’s dry runs of action_invoke and of a plan’s invoke steps ask the link when it says it can and show checked_by_link.

Consequences

  • A dry run catches what the link would refuse, before anything runs.
  • Links built before this have no attr.check and are never asked; they behave as before.
  • check costs 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, e2e a_check_does_nothing, wyrm-mcp gateway test (dry run with checked_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_package unpacks 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. wyrmd is 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_dir with the broker stopped (docs/operations.md §3), plus wyrmd keys export for 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

  1. sys/packages/<name> shows version, latest (from the repository index; empty for custom packages), update_available (bool), previous (the version kept for a rollback, with keep_until) and last_update (a map: from, to, at, result = ok | rolled_back | failed, kept, new, gone counts and up to 200 keys of new and gone). sys/links gains updates_available (count) so Studio can badge it.
  2. Action sys/packages/<name>/~act/update {version?, accept, restore_point = true, auto_rollback_s = 120} (config, audited): installs version (default latest) from the repository with its SHA-256, the same flow as install_repo. A custom package is updated by the existing install_zip / install_url / install_git with the same package name; they take the same three new arguments.
  3. 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=keys of its root). Restore points are listed at sys/links/<id>/restore_points (at, version, size) and pruned after packages.keep_previous_days (default 7).
  4. The previous version’s directory is kept (no remove_dir_all) until keep_until; the registry’s PackageDef keeps previous.
  5. Health after the restart: every link of the package must say hello and declare at least every key it had, within auto_rollback_s. Keys that do not come back are gone; new ones are new. With auto_rollback_s > 0 and anything gone (or a link that never says hello), the broker rolls back by itself (§1.6) and audits update_rollback with the reason. With 0, it keeps the new version and reports.
  6. sys/packages/<name>/~act/rollback {to?} (config): reinstalls previous from 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 in last_update.
  7. Store format: the package manifest gains state (integer, default 1) and reads_state (list, default [state]). An update whose reads_state does not contain the installed state is 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.
  8. 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_update are value nodes of sys/packages/<name> (they move while an update runs), beside state and changes_state (the update to latest changes the store format). previous is {version, keep_until, changes_state}; times are unix seconds. last_update carries the counts kept, new, gone, the lists new_keys and gone_keys (<link>/<path>, ≤ 200 each), reason, links, changes_state, restore_point. Its result has a fourth, passing value: checking, while the health check runs. updates_available is an attribute of sys/links, beside catalog (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_available compares 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 hello is one of its actions, so the health check runs after the action answered ({success, message}, like an install); Studio follows last_update. Until it ends, installs of the package, its Remove and its links’ Start/Stop/Remove answer busy; rollback stops it and rolls back.
  • Health. A link is back when it answers ~meta?view=keys of 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_s is 0 to 600. With 0 the report is made when every link answers and its keys are stable for 3 s (ok, with gone and a reason), or failed after 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 leaves failed at the next start; the new version stays.
  • Rights. accept covers grants and net entries 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-link and <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 by Control::link_backup_to’s code with the sections settings and data (no history, no package: the package a link ran is kept once, as the package’s previous version of §1.4, not once more in every link’s restore point). It is sealed how: broker (a key from secrets.key), so a restore point needs no passphrase and no backups.export_secrets, and never leaves the broker by itself; install_backup on 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_point keeps 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 with O_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 is wyrm_admin::nofollow, and every copy of a link’s private data into a backup goes through it (a link backup, the links section 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 through install_backup takes the same kind of restore point first (§3.5), listed in restore_points and 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: previous is 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_state has 1 to 32 entries and must hold the package’s own state. The repository index may carry both (wyr repo add and the official index copy them from a manifest that names them), so changes_state is known before the fetch; the manifest in the zip decides. restore_point: false is refused when the format changes, and such a rollback is refused for a link that has no restore point.

2. Broker updates

  1. 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 runs ExecStartPre=<prefix>/bin/wyrmd-guard update-guard and ExecStart=<prefix>/current/wyrmd. docs/operations.md gains the layout and the unit.
  2. 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; keys adds others (a company mirror). external (containers, distribution packages) refuses update with a message and shows how to update outside.
  3. Releases: a new release workflow publishes wyrmd-<version>-<target>.tar.gz, a signed release document with its SHA-256, and a signed releases.json (version, date, notes URL, targets, min from version, schemas it writes, replication protocol version). Until that workflow exists, update {file} takes an uploaded archive with its signature (parts, as ADR 0028).
  4. sys shows update_available, latest, update_state (none | staged | trial | confirmed | rolled_back) and update_last (map). Action sys/~act/update {version, confirm_site} (config, audited; confirm_site must equal the site name):
    1. download into versions/<v>.part, check signature and SHA-256;
    2. run versions/<v>/wyrmd check -c <config> (the new binary checks this configuration);
    3. pre-update backup of the control plane and keys (§3 sections control and keys, sealed with a key derived from secrets.key, so no passphrase is needed) into data_dir/backups/pre-update-<v>.wyrm-backup;
    4. write data_dir/update.json {from, to, state: "trial", attempts: 0, deadline, backup}, point current at versions/<v>, copy the running binary to bin/wyrmd-guard, and stop cleanly (exit 0; systemd Restart=always starts the new one).
  5. Trial: the new wyrmd increments attempts first thing. It is healthy when the router is up, the gateway listens, the admin answers and every link that was connected before the update says hello (process links get trial_s). Healthy → state: confirmed, audit update_confirmed, the guard binary is replaced by the new one. Not healthy by deadline, or attempts ≥ 3: it exits with code 76.
  6. update-guard (the previous binary) runs before every start: with state: trial and (attempts ≥ 3 or the deadline passed or a 76 recorded), it points current back at from, restores the control-plane files from the pre-update backup when the new version moved a SCHEMA, sets state: rolled_back and lets systemd start the old binary. Audit update_rollback is written by the old binary at start.
  7. sys/~act/rollback_update (config) after a confirmed update, until keep_days: same as §2.6, on purpose. Changes made after the update are lost (the pre-update backup is restored); the review says so.
  8. Standby pair (ADR 0036): update refuses 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 own sys, reached via the peer link). The same action reaches a downstream broker through its upstream with allow_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.mode is off by default: nothing is fetched, update is refused. external needs updates.channel, reads the index and shows latest, update_available and, in update_hint, what to run outside the broker; update is refused with that text. self is refused with the reason (update_hint shows it too) when the running binary is not <prefix>/versions/<its version>/wyrmd with <prefix>/current a symbolic link to that version and a file <prefix>/bin/wyrmd-guard, and when the guard did not run before this start (it leaves data_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’s file, size, sha256, url and bin_sha256 (the SHA-256 of the binary in the archive). Its signature is detached: Ed25519 over wyrmd-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 over wyrmd-releases-v1\n + its bytes. The two domains keep an index signature from signing a release. updates.channel serves 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) and updates.keys; with no key pinned nothing is trusted. No key is ever read from a release file. The archive is .tar.gz (the workspace has flate2, no zstd).
  • Freshness of the index (review of PR 74, point 5). sequence goes up by one with every index published and is under the index’s signature. A broker keeps the highest sequence it has read in data_dir/update.seen and 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 whose data_dir is 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 a u64) 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 in docs/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 (environment wyrmd-release), which builds its tool from the tagged source itself and has contents: read; the job publish has contents: write and no key. release doc checks each archive against its description and the binary in it against the hash that is signed.
  • The channel holds no credential. updates.channel is https:// (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 in sys and 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_update is the only way back. min_from must 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 what data_dir holds. A release (or a running version) that names a store other than registry, audit, users, flows is refused: the guard of this version could not put such a store back (review of PR 74, point 1); it is installed by hand. With state_anchor_dir set, 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 to versions/<v> when all of it is on disk. Plain files only, by plain name (no directory, no .., no leading .), at most 9, the binary wyrmd among them and executable in the archive; symbolic and hard links, devices, pipes, directories and extension headers refuse the whole archive, and so do the names release.json and release.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 the bin_sha256 of 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-info must 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 is data_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/backups with kind: pre-update, pinned, of the section control alone, sealed for this broker (how: broker: its manifest carries a MAC under a key from secrets.key). Decided: no keys section (§2.4.3 said both). An update replaces a binary, never a key file, the guard restores WALs only, and keys without a passphrase is refused by §3.4. The guard checks the file’s SHA-256 against update.json, the manifest’s MAC with secrets.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.
  • update answers 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 follows update_state (none, staged, trial, confirmed, rolled_back, failed) and update_last (from, to, result, at, by, reason, attempts, deadline, keep_until, restored, without_s, links, backup, schemas_moved; step while one is prepared: fetching, checking, staged, backup). An update that ends before the switch leaves update_state: none, update_last.result: failed with the reason, an audit record, and no version directory. update?check (ADR 0047) refuses what update refuses before it fetches the archive; it answers ok or 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), then update {upload, release, signature, confirm_site} with the release document and its signature as text. check_updates reads the index now.
  • One job at a time. update and rollback_update are refused with busy while 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 with mode: replace takes (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.json is 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), current is switched by one rename of a new symbolic link, update_start is audited, the broker stops with code 0. A broker that stops between the file and the switch is found by the guard (current still 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_s in update.json every 5 s and the trial ends when ran_s reaches trial_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. deadline in update.json and update_last is 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 on sys through the router, the gateway accepts a connection (if it is configured) and every link of update.json that 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 into update.json and the process ends with code 76 (Restart=always starts the guard). update_confirmed is never written before the version ran trial_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 when rollback_update asked. It never asks the clock. Where the update moved a SCHEMA (told by the two sets in update.json), it first puts those stores back from the pre-update backup (release::restore_control): a store that existed before the update (update.json stores) is replaced by the backup’s; one that did not (the gateway’s users on a broker that had no gateway) is moved into data_dir/update.aside and left out. Everything is read into data_dir/update.restore first, so an error up to there changes nothing; then the directories are swapped, and a swap that fails is undone. Then current goes back by one rename and the state is rolled_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 in update.json, update_last.reason and the audit (update_rollback, status internal_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 marks update.json settled and the guard leaves current alone from then on. When the old version’s directory is gone the new version stays (failed). Errors of writing update.json are 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 of versions/<v>/wyrmd (a plain file, no link) is the bin_sha256 that 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 that bin/trusted.json names <v> with that hash (a version put there by hand with wyrmd install-layout has no signed release). A binary that fails is never started: the guard makes the other version of the update current when that one verifies (state failed, 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.json or a backup, and gain code execution that survives restarts. Mitigation, in docs/operations.md §2: <prefix> owned by root with the sticky bit, bin/ and the configuration owned by root, versions/ and current by 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 pointing current at an unsigned one is stopped. Not stopped, also with it: current pointed at another release the key did sign and that is still in versions/ (the check proves a signed release, not which one; update.json is the broker’s to write); everything in data_dir (the site’s keys, the control plane, the backups: the seal of the pre-update backup is under secrets.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: marks update.json, stops; the guard does the rest. Refused for a caller that comes through an upstream, as restore_apply replace is: it puts the control plane back.
  • How long a confirmed update can be rolled back (review of PR 74, point 2). keep_until is 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 past keep_until at two starts of the broker, or for a full hour of one run (UpdateFile::expire); a clock that is before keep_until again forgets the starts counted. Never during a trial, and after a rollback only once the version it left current came up.
  • update through 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 own sys”. 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 in data_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, runs release-info and check --state on its followed stores, writes update.json with role: 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). update for the active is then allowed only when the standby is connected and reports that version, confirmed; without_standby: true allows 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 audits update_start and update_confirmed / update_rollback with the key standby and shows sys/standby_version and sys/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, and update was 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 status internal_error when an update ends before the switch), update_confirmed, update_rollback (at the call of rollback_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 in update.json is of the finished file. sys/replication/update and update_part: the queryable is the standby’s alone (ACL subject standby, a certificate standby:<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 (as without_standby does). Exit code 76 under the documented unit: Restart=always starts 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 of update?check; the link’s wyrm_link protocol 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

  1. Format: .wyrm-backup, a zip with manifest.json first: wyrm_backup: 1, site, broker (version), created, schemas (registry, users, flows, audit), sealed (how keys and secrets are sealed: passphrase with Argon2id parameters, or broker), and sections[], each with its files, sizes and SHA-256. A link backup is the same format with kind: "link", extension .wyrm-link. The format lives in wyrm_admin::backup (wyrmd reaches it too). Rules of the sealed field and of the reader (2026-11-13, after the security review of the first commit):
    • sealed: {how, kdf?, check, id, mac}. how is none, passphrase (Argon2id, parameters in kdf, bounded by the reader) or broker (a key derived from secrets.key). id is 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. mac is HMAC-SHA-256 over the whole manifest (every path, size, SHA-256, sealed and exec flag, every info) under a key from the master key and id.
    • A manifest with how: passphrase | broker and no id, check or mac is 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; in links each link’s secrets, token and files/**; every file of a link backup’s data. A manifest that lists one of them with sealed: false is refused, and so is any such file in a backup with how: none. link.cbor holds 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: none has no secret in it and no MAC: its SHA-256 (shown in sys/backups/<id>) is what proves it unchanged.
  2. 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 inside control, listed for restore by itself), storage (the storage tree as wyrm_storage export plus its redb file), history (day files of a chosen range and index.redb), links (per chosen link: its LinkDef, the framework export when it has one, its private data dir sealed, its package archive), packages (all package archives), config (a copy of wyrmd.json5 for people to read, never restored; masked by default, see “Decided after the review of PR 72”, 13).
  3. 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::changes for today; the storage journal fixes the storage at one rev. These are the standby’s primitives (control/replication.rs), reused, not copied.
  4. 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> shows status, 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_secrets in wyrmd.json5, default false. While false: keys is refused, a passphrase is refused (the message names the option), link secrets and private data are sealed with how: broker and open only on a broker that holds this site’s keys; every other section works. While true: a passphrase of at least 12 characters (Argon2id, as keys export) seals them; backup_create is audited with keys: true|false and secrets: true|false and logged at warn. A caller whose token a limited key signed (an upstream with allow_config) is refused keys and a passphrase in both cases: a downstream site’s keys never travel up. sys/backups has the attribute export_secrets. The config section is the configuration as JSON, masked by default (decision 13 below).
    • send {link, connection, path?} on sys/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 in backups.send_links (wyrmd.json5, default empty = send refused). 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 in hello): the backup sender key, at write, scoped to wy/<site>/downstream/<link>, bound to the subject broker:backup. The key is a secret the broker makes on first use (secret store entry broker:backup-sender, no link’s secret, so in no link backup); no registry state, no SCHEMA change. send uploads with the link’s own upload_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> shows sent_to, send_status (sending, done, failed), send_progress, send_error; one send at a time. sys/backups has the attribute send_links.
    • send is no deputy of its caller (security review of send.rs, 2026-11-13). The broker writes with its own key for whoever has config on sys, whatever that caller may do on the link, so the host decides where a backup may land:
      1. An entry of backups.send_links is {link, folder}; a plain link id means the folder backups. One folder a link. folder is relative, of plain names (checked when the broker starts).
      2. The caller names connection (one name) and path: 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.
      3. 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, at write. 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).
      4. send never overwrites: overwrite: false always; the link refuses a name that exists (its tree, and If-None-Match: * at the store), so a send replaces no file.
      5. The admin’s audit record backup_send carries 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 names claimed:broker:backup: the upload actions take no note or claimed subject, so the caller is not in the link’s records.
      6. A backup that holds keys is never sent. A send of any other backup is allowed to a caller from an upstream too: the host named the destination.
    • kept under data_dir/backups for backups.keep_days (7) within backups.max_mb (oldest removed first; pre-update backups of an unconfirmed update are never removed).
  5. Link backup: sys/links/<id>/~act/backup {sections: [settings, data, package, history], history_days?, passphrase?} → a job in sys/backups with kind: 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, as install_*), 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 pass packages::unpack, the validator of install_zip (entry of Component::Normal parts and among the files, requester grants through check_grant and the whole-root rule, WASM world and capabilities, SHA-256 of the files), which builds the PackageDef. The LinkDef passes the checks of a new link before anything is written: validate_new_link_id for a new id, the driver, lint_params, the driver’s own validation, every grant through check_grant. accept covers 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.
  6. 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 into data_dir/restore.pending, the broker stops, and the next start applies them before opening any store (and removes the folder).
    • The keys section of another site is refused unless replace_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. The pre-restore backup 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):
      1. Every restore of keys passes the gates: backups.export_secrets: true, a caller of this site, the passphrase. The CA does not decide: a backup with this broker’s ca.pem and another state.key, secrets.key, gateway key, secrets.bin or link token takes the site over as well. replace_keys: true is needed unless every key file of the backup is byte for byte this broker’s; restore_check answers keys: none | same | differ | other and lists the files in keys_differ.
      2. A restore writes only files a section defines. Under keys/: exactly the key files of the bundle (key_files()), secrets.bin, and links/<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, in restore_check and in both modes. Every destination is built from the checked parts (Place), never by joining a path of the archive.
      3. Broker-made link secrets. Without keys, replace puts a link’s secrets into this broker’s store and drops the ones a broker makes for a link’s identity, with the predicate of install_backup (broker_made_secret), at staging and again at the start that applies the plan. With keys, secrets.bin comes 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.
      4. mode: replace is refused for a caller from an upstream (allow_config), before the file is read; mode: add stays, with its accept. In replace, packages pass packages::unpack and what they ask for (requester grants, network) needs accept, unless this broker has the same version with the same files. The detection of such a caller (Caller.signer.is_some()) is proved by e2e chain_of_three_brokers (central calls edge’s restore_apply), the local side by backup_restores_into_a_fresh_data_dir. add takes links and storage; flows need replace (a deploy carries proofs). control under other keys goes only with keys; with state_anchor_dir it is restored offline. The audit journal is replaced only with state.key. Audit: restore_apply at the call, restore_applied at the start that applied it.

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 as state: 1.
  • wyrmd gains update-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 fresh data_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}.

  1. Order. Link backup and install_backup (§3.5) and the job plumbing of sys/backups (create, download_part, remove) come first; the broker restore (§3.6) and send follow.
  2. control holds every WAL once. Registry, flow store, gateway users and audit are control/<store>/wal.…wyw, each copied as of one sequence number and checked against its HMAC chain (wyrm_state::replicate::copy_to, beside the standby’s records_after). The dataflows section adds only the flow artifacts and names control/flows as its store, so no WAL is in a file twice.
  3. Storage is a tree, not a redb file. storage/tree.cbor is the standby’s full page at one revision (Store::changes_since), with storage/export.json for people. The redb file is rebuilt from it on restore; a raw copy of an open redb file is never taken.
  4. History, today included, is copied inside one read transaction per file (Store::copy_day, then copy_index), not through Store::changes: the days first and the index last, so the index knows every series and journal number the days hold.
  5. 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.json among 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).
  6. A link’s settings is its definition. The framework’s runtime edits are in data (framework.tree, sealed); the framework export JSON is not added, because the admin holds no key that may call a link’s export. link.cbor carries no token hash.
  7. 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.
  8. 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.
  9. Without a passphrase secret-bearing parts are sealed for the site (how: broker); keys is refused. See §3.4.
  10. 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_backup also takes the file itself (file).
  11. Limits. backups.max_mb defaults 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 of data_dir.
  12. 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)

  1. 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 before replaced.
  2. 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, update and rollback of the link, a backup that copies its data, and a restore with mode: replace answer busy. While a backup copies a link’s data, or a replace is staged, no claim is given. Each side shows itself first and then looks, so one of the two always sees the other.
  3. A rollback is recorded before it changes anything. data_dir/restore/.rollback/<package>.cbor names 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.
  4. 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>/hold holds the reason, start answers it, last_update.reason and 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.
  5. 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 of secrets.bin; data.replaced → data.done (the commit); the kept secrets and data.done go. 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.
  6. 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.
  7. 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.
  8. 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 to restore.done, then removed. When a step fails, or a store does not open, everything set aside goes back; the folder becomes restore.failed with plan.json and error.txt only, and the broker runs on the state it had. The audit gets restore_failed once. 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.
  9. The upstream rule holds for a download too (§3.4). download_part refuses a caller from an upstream when the backup holds keys or secrets sealed with a passphrase, whoever made it. A backup sealed for this broker, or without secrets, may be downloaded from above. send is unchanged: it gives no bytes to its caller, the host names the destination, and a backup with keys is never sent.
  10. 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.
  11. A rollback restores the links’ data only when it must, is suspect, or is asked (§1.6). rollback {restore_data?}. Default true when the update changed the store format (false is then refused), when the update did not end ok, or when it lost nodes (gone > 0); the rollback of the health check always restores. Default false for an update that ended well: the links keep the data they have, with all that was configured since. last_update.reason and the audit say which of the two was done.
  12. A restore point is a copy file by file (§1.3). Each file is whole: the portable store, framework.tree and 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.
  13. The config section is masked by default and shown by list (§3.2). A list of names to hide kept leaking (camel case, joined words, name = value inside a text), so the rule is the other way round. A text of wyrmd.json5 is in clear only when its key path is in CONFIG_SHOWN (wyrmd): fields known to hold no secret. Every other text is replaced by ***, whole: every text under links.*.params and uplink.upstreams, under an unknown section, free text. Nothing is parsed for name=value pieces. 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 neither CONFIG_SHOWN nor CONFIG_MASKED. Declared secret params 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. While update.json says trial (from the staging of an update to its confirmation, read at Control::open and 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_update writes who asked into update.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, or confirmed with rollback set), every change of update.json by the running broker that moves it goes through Control::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_update switches the journal first (Control::audit_one_by_one, an error goes to the caller) and writes update.json only 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 at Control::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 own update.json; restore_apply replace is 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/create once 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 showsBroker today
The plan with every step, its arguments, level, check result and the model’s whyThe 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 rightsapprove {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 outapprove 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 unitsEvery ask starts from nothing
@ modbus/tcp-line2 chips, the Explorer drawer about the selectionask {task} takes text only
Today 182 k of 1 M tokens, API key set · never shownThe budget used is internal; secret names are not readable
A warning on a step (Slave ID 3 was used by ahu-old) with fixespropose returns ok or an error, nothing in between

Decision

  1. Documents through the gateway. A gateway op doc {key, suffix} (suffix ∈ ~state, ~def) answers a node’s document with the rights of list on that node (the agent’s tasks folder is restricted, so the asker or a config caller). Studio reads a task’s record with it after every state change.
  2. 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 as add_flow_proofs does for flow deploys, and refuses (before anything is sent) when the user’s grants do not reach a step. The token’s sub is the user, so the agent’s “approver = signer” check holds. Callers outside the gateway keep sending approvals.
  3. Approve at the step’s level. approve becomes level write on the task; what a person may approve is decided by the tokens (a token at config for a config step). An engineer with config on downstream/modbus/** approves a Modbus plan without config on the agent link.
  4. Partial approval. approve accepts a subset: the steps without a token are marked skipped (log line skipped by <sub>), never run; a step the model marked after: [n] is skipped when a step it depends on is. propose takes after (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.
  5. 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 state awaiting_answer (wire_enum! row in the task states; Studio maps it). tasks/<id>/~act/answer {answers: {<question>: [<option id>] | text}} (level write, asker or config) resumes the model with the answers. ~state carries questions[].
  6. 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 the wyrm-agent run format, so Save as a plan is the plan as it stands.
  7. Progress in ~val. A task’s public ~val becomes {state, step, of, last} (last = {n, ok, text} of the latest finished step), published at each step. ~state keeps per-step result (ok | failed | skipped, text, time).
  8. Checks and warnings on proposed steps. propose answers {ok, check, warn?}: check = now (checked against the live tree) or at_run (depends on an earlier step); warn = text the model must show (a slave id in use, a value at a limit). Studio draws warn on the step; the model offers fixes as an ask_user.
  9. Follow-up asks and context. ask {task, parent?, context?: [key…]}: parent hands the model the parent task’s ask, plan and results (a retry, an undo, the same for more rows); context are 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.
  10. What it may do, readable. The agent root shows budget_used_today (u64, read). sys/links/<id> shows secrets (names only, level config), so Studio can say set / not set for api_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>/~state itself, with the user’s own token. The client sends {steps: [n…], plan: <hash>} and nothing else of a step. With approvals in 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 without approval, check, warn, model_warn, reason, result (model_warn since 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>); max is the level the step needs, not the user’s level; args is the SHA-256 of the step’s request body (spec 04), so it is good for those arguments only; jti is fresh (single use); exp is 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/expect timeouts, sleep) add up to more than 240 s: propose answers the model with the reason. And approve is 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 sends approve for a task. The level of approve is write, so the connector’s allow_config switch would not have stopped a config step. And it signs only for wy/<this site>/downstream/<link>/tasks/<id> where <link> has the driver agent in the broker’s registry (Gateway::set_agent_links, told at every router build): a link that only serves a plan-shaped ~state gets 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 /mcp pipe) AND its login method is a person’s: Amr::is_person = Password or Device, an exhaustive match (OAuth and any later method are not a person until written there). The same helper decides the approve gate, POST /api/ws-ticket and the /api/ws upgrade (403, permission_denied, code: person_required) and every step-up check in devices.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 send approve stays its own rule.
  • The meta of approve (§2). approve declares approvals (not required), steps and plan, so a client that checks arguments against ~meta takes both forms. steps without approvals that 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, op approve); a signed approval is too (approve, the request keys, the count left out).
  • Who approves (§3). approve is write on the task, so the caller may be a stranger to the task. The asker, or a caller with config on 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 is skipped, with the steps that need it, and nothing runs with the agent’s key on their word. So an engineer with config on downstream/modbus/** approves a Modbus plan with write on 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 is check: at_run: taken at write, and checked against the live ~meta when it runs; a node that then asks for more, or for other arguments, stops the step before it is sent.
  • The public ~val holds no text (§7). ~val is read by anyone who may read the link; the record is restricted. So last is {n, ok, result} with result one of ok, 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 through doc.
  • 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. answer is a stream like ask; the ask stream ends with awaiting_answer.
  • Follow-ups (§9). parent must be a task the caller asked, or the caller has config on the link. A context key must be inside what the agent may read and inside what the asker may read (auth of 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 a none before a wider grant keeps the value out of the model’s prompt.
  • Secret names (§10) are the action sys/links/<id> ▸ secrets (level config, names only), not a value: a ~val is read at read.
  • Task states are the agent link’s own table (TaskState, wire_enum!, by name in ~val.state); they are not in spec/. The gateway’s frame protocol is documented in crates/wyrm-gateway/src/ws.rs and docs/broker.md; no spec/ 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 step step, the drawer’s second button. changes is 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 whose context is 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 context limit of ask), label ≤ 80 bytes, detail ≤ 300 bytes (longer text is cut), changes ≤ 50. step must 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 as auth, spec 04). Fail closed: the rights are known only from a token with auth (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’s exp. The asker’s own later answer or approve on 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} needs auth in the same way (permission_denied). The follow-up ask checks its context against its own caller again. The follow-up ask checks its context against its own caller again.
  • Texts stay in the record. The public ~val gains suggestions (their count, absent at 0) and no word of them. Studio reads them through doc with 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_turns LLM calls (param, default 4, 0 = none), with the read tools and suggest only. No propose, no ask_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 stays failed and its error stays the run’s; ~val and ~state show reviewing: true while 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) while reviewing ends the turn: reviewing goes, no review, the task stays failed with 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 done keeps 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.

  • approve on a replaced task is refused with invalid_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, reject and cancel are refused as for any task that ended.
  • A parent that is planning, running, done or failed is not touched: a follow-up of it replaces nothing (a run goes on until cancel; 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. label and detail are 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) ≥ read over the grants of their token’s auth). Fail closed: unknown rights (a token without auth, a restart) or rights past their token’s exp refuse 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 own answer or approve): 5 min from the gateway (PTOK_TTL). Nothing renews them on its own (no rights-renewal code, by design), so findings are refused as rights_expired when (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 ~val gains findings (their count, absent at 0) and no word of them, so a reader of ~val learns that the record changed, not what it says. Studio reads them through doc with 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. findings lives in the record’s plan bytes beside the fields of amendment 1 (store schema 1 unchanged). A record without it reads as no findings (test a_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: doc passes 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 of approve (like flow proofs), and agent link changes in store.rs (task schema: questions, after, per-step result; old tasks read with defaults) and lib.rs (ask_user, answer, awaiting_answer, wait/expect, ~val progress).
  • docs/studio.md §10 items 1, 3, 5, 11, 12 close when this is built; §7.8’s “built now” paragraph is replaced by studio/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; doc refused without list.

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:

  1. 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.
  2. 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

  1. 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 with BIOMETRIC_STRONG, setInvalidatedByBiometricEnrollment and StrongBox when the device has it. Studio then calls POST /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}.

  2. Unlock. POST /api/device/challenge {device} → {nonce, exp ≤ 60 s} (single use, in memory). The OS prompt unlocks the key and Studio signs wyrm-device-login/1 ‖ site ‖ gateway origin ‖ user ‖ device ‖ nonce. Then POST /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_at is older than password_every_days;
    • devices are off. Each refusal is a distinct code (device_removed, password_changed, password_due, devices_off), so Studio can say why (board UnlockSignedOut).
  3. Step-up. When step_up: config, every request at config level 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 answers confirm_required and Studio shows UnlockStepUp, then sends the request again.

  4. Idle lock. Local to Studio: after lock_after_min (the gateway’s idle_lock_max_min caps it), Studio hides the tree and values. Unlocking signs a fresh challenge with POST /api/device/login {…, session}, which keeps the session. Without a device key it asks for the password.

  5. Visible and revocable.

    • GET /api/devices lists the user’s own devices.
    • DELETE /api/devices/<id> removes one, for the user or an admin.
    • /api/users/<u>/devices gives 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.
  6. Policy (wyrmd.json5 gateway.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/info carries it so the log-in page knows what to offer before login. With allow_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: false does not delete records; it refuses device logins, and Studio removes its key after the refusal.

  7. 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.

  8. 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

  1. Announce. wyrmd advertises its gateway by DNS-SD on every non-loopback interface the gateway listens on: service _wyrm._tcp, instance name = site. Config gateway.announce: {enabled: true, interfaces?: [...]}; hardened sites turn it off. The TXT record has no users and no secrets:

    TXT keyValue
    vwyrmd version
    sitesite name
    tls1 or 0
    fpfirst 16 bytes, in hex, of the SHA-256 of the CA certificate the gateway’s certificate chains to
    roleactive or standby (ADR 0036)
    pairthe other host’s host:port
    upupstream 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 announces role=active).

  2. 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 of login.md §6, the trust step and the range probe.

  3. Studio finds.

    • Find on this network browses _wyrm._tcp for 8 s. It shows one row per site: an active and its standby merge into one row, and up shows downstream sites. Each row is checked with /api/info.
    • Rows Studio cannot use are shown greyed with the reason: plain http off loopback (insecure_plaintext), or a wyrmd version older than min_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_fp in 8 groups of 4). The person compares it with System › Gateway › Certificate code on the broker, or with wyrmd 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/info per 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.
  4. Platform permissions:

    • iOS: NSLocalNetworkUsageDescription and NSBonjourServices = [_wyrm._tcp].
    • macOS 15: the Local Network prompt.
    • Android: CHANGE_WIFI_MULTICAST_STATE and a multicast lock while browsing.
    • Windows and Linux: none (browsing is outbound).

    Flutter package: bonsoir (all five platforms).

Consequences

  • Gateway: devices.rs (records, challenge cache, verify P-256 ECDSA with ring::signature::ECDSA_P256_SHA256_ASN1, ring is already in the tree), routes in http.rs, users SCHEMA 5, info route, confirm_required on config requests when step_up is on, audit records.
  • wyrmd: gateway.devices, gateway.announce with mdns-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_auth package alone cannot bind a key; Studio uses a thin plugin over Security.framework, KeyCredentialManager and BiometricPrompt + Keystore), bonsoir, pinned CAs per origin in storage.
  • 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/info without 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.

  1. Refusals on the wire. No new spec-04 status: a refusal has status: permission_denied (0x21) and a text code, in the HTTP error body {status, message, code} and in the WebSocket error map. 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 bare 401 without a code, 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 answer 429 rate_limited.

  2. 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): site plant, origin https://gw:8443, user olena, device d1, nonce 07070707 → 86737779726d2d6465766963652d6c6f67696e2f3165706c616e746f68747470733a2f2f67773a38343433656f6c656e616264314407070707.

  3. Origins. The gateway checks the signed origin against a list, never against the Host header (a relay sets that). gateway.devices.origins lists them; by default they are the DNS and IP names of the gateway’s own certificate on the port it listens on (https), or 127.0.0.1, localhost and ::1 for plain HTTP on loopback. A standby gateway with its own certificate covers its own names; a standby reached under other names lists them.

  4. 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’s KeyCredentialManager makes RSA-2048 keys only, so Windows uses it. Registration proves the key: POST /api/devices carries a register nonce 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.

  5. 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 its confirm_required refusal, 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). A device that is not a device id (32 lower-case hex digits) is refused with 400 before 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, then busy, 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, and POST /api/me/sign-out (Sign out everywhere: user store op EndSessions, a new generation). GET /api/users rows gain devices (the count that can log in).

  6. password_at moves when a password login names its device: POST /api/login {user, password, device}. password_due then clears without a new key.

  7. Removing. The owner’s DELETE (Turn off, Forget) deletes the record. An admin’s DELETE of another user’s device leaves a tombstone with removed_by and removed_at, so the device hears device_removed and its owner sees who; a DELETE of 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.

  8. Sessions carry amr (pwd, dev, oauth), auth_at (when the password or the key was last checked at login) and dev (the device of a device login). Tokens from before this ADR read as password logins at iat. 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.

  9. 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/login with session) confirms the kept session. confirm_required carries request and nonce (a confirm nonce of that session) to sign. request is 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 fields password, secret, token and passphrase left 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: a set on a point whose writable is config; an invoke whose action level is config (also /api/invoke and flow deploys); user management changes; an admin removing another user’s device; an approve of an agent’s plan in which a step to be signed is at config, 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 ~meta cannot be read counts as config. Only users who hold config there are asked (the responder refuses the others). An MCP token never passes a step-up: with step_up: "config", the MCP endpoint gets no config. The tokens the gateway mints for a session that is not confirmed reach write at most, so a responder that does more for a config token (a DQL sink query, publish) gets none from it (review M1). Default step_up: "none", so existing clients keep working; hardened sites turn it on.

  10. /api/info carries {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 trusts ca_fp or the fp TXT key, which an untrusted server sends (review M2). It shows the code it computes itself, SHA-256 of the received ca DER, first 16 bytes. It then reads /api/info once more under that CA alone, so the handshake’s leaf must chain to it, and only then pins it. When ca_fp or fp differ 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 names wyrm-<site>.local. So Studio builds the gateway URL from the first of names: 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_studio is the oldest Studio the gateway serves (1.0.0). 60 requests per address a minute. ADR 0051 §3 adds setup: true while a setup code waits for the first admin (absent otherwise).

  11. The CA and its code. One function, wyrmd::gateway_ca, gives the code for /api/info, the fp TXT key and wyrmd ca fingerprint (which prints it in 8 groups of 4 and creates nothing). It takes gateway.tls_ca (new, a PEM path), else the last certificate of tls_cert when 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; no sys value was added.

  12. 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_dir set it is an update by hand. In a standby pair, update the standby first: an older standby cannot read the new ops.

  13. 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, so role is active. A following standby runs no gateway; Studio fills the standby from pair, which is announce.pair or the host of standby.peer with this gateway’s port. up lists 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:

  1. 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.
  2. Several board implementations, not one. First: Raspberry Pi and Banana Pi BPI-R4 (MediaTek MT7988A).
  3. 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

BaseForAgainst
ADebian/Armbian per board, systemdfamiliar, apt400–700 MB, not atomic; no Armbian for BPI-R4 (only the vendor’s Debian/Ubuntu on its own 6.12 kernel)
BBuildroot per board, read-only root, A/B slots (RAUC)60–120 MB, atomic OS updatesno Buildroot support found for BPI-R4: we would port the vendor’s kernel and U-Boot ourselves; ~1 h CI per board
CAlpine Linuxsmall, muslweak Banana Pi support
DOpenWrt + a WYRM package feed + OpenWrt ImageBuildersupports 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 devicesinit 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). wyrmd updates 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 wyrmd already: the twelve with the form builtin in links/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 wasm form: 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). wyrmd is one static aarch64-unknown-linux-musl binary that runs on all of them; CI packs it once per package architecture of the boards in boards.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 as wyrmd expects, respawn_retry at least 8 as ADR 0048 needs), a default /etc/wyrm/wyrmd.json5.
  • Seed packages. A package can not be dropped into data_dir/packages at build time: data_dir exists only after the first boot, and Control::open removes 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 start wyrmd installs each through the same checks as install_zip (registry PackageDef + LinkDef) and records that the seed is done. New in wyrmd. (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. sysupgrade keeps it on both targets (bcm27xx writes partition by partition while the layout is the same; filogic writes only production) as long as ROOTFS_PARTSIZE of a board never changes: that value is fixed per board in boards.json for 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 a sysupgrade the guard keeps starting current, 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 in RELEASE_KEYS (empty today); then images ship mode: external with 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 wyrmd makes the CA, then goes on and logs a warning; the CA’s notBefore is 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, then pool.ntp.org). (maintainer’s call)
  • Secrets. On first boot wyrmd makes the site’s CA and its keys, as it already does for a new data_dir (Pki::open_or_create). Nothing of that is in the image.
  • Gateway certificate. Today wyrmd does not make one: a gateway that listens beyond loopback needs tls_cert/tls_key, and without them DNS-SD and ca_fp are off too. New in wyrmd: gateway.tls: "site_ca" issues the gateway’s certificate from the site’s CA on first start with the names <hostname>.local, wyrm-<site>.local and 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 in wyrmd.json5, which wyrmd never writes and which refuses unknown fields). On its first start wyrmd moves the hash into the users store as a pending setup and deletes the file (as built: into data_dir/gateway/setup.hash, 0600, beside the users store and not replicated to a standby, see “Built”); the file is not in the sysupgrade keep 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_PASSWORD stays 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 (from official.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 its wasm form under /usr/share/wyrm/seed/. The image has a small reserved config partition (GPT label wyrm-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, and wyr 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/armv8 in QEMU and starts wyrmd from a package of that target. It checks wyrmd on OpenWrt, not the board packages; those are checked on the boards.
  • docs/operations.md gains a section “OpenWrt” beside “systemd”: procd script, data partition, logs through logread.
  • No service to run: CI publishes base images; the page is static (§4).
  • wyrmd gains: the setup-code first admin, gateway.tls: "site_ca", seed packages on first start (each with tests and docs/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 FILES overlay).

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" (excludes tls_cert/tls_key): the broker issues the gateway’s certificate from the site CA with the names <hostname>.local, wyrm-<site>.local and 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, since if-addrs gives no flags), or only the listen address when gateway.listen is 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 sets gateway/tls.{pem,key} aside). ca_fp, the DNS-SD fp and wyrmd ca fingerprint name the site CA. Documented in docs/operations.md (“Gateway TLS from the site CA”) and docs/broker.md. Tests: certificate_follows_the_addresses, a_due_certificate_is_renewed and the other tests of crates/wyrmd/src/gateway_tls.rs.
  • First admin from a one-time setup code (§3). gateway.setup_file names a file with the SHA-256 ("wyrm-setup-v1\n" ‖ the 16 code bytes, 64 hex digits) of a 128-bit code; wyrmd setup-code makes a code (26 base32 characters in groups) and its hash. While no user exists, the first start moves the hash into data_dir/gateway/setup.hash (0600, not replicated to a standby) and deletes the file; GET /api/info shows setup: true; POST /api/setup {code, user, password} makes that user an admin once (204; 409 no_setup, 403 setup_code_wrong, 400, 429 from the login limiter). A setup is void once a user exists (dropped at start). Deviation from §3: the pending hash is kept in data_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/info also carries setup_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_PASSWORD works as before. Documented in docs/operations.md (“First admin from a setup code”) and docs/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_dir names a directory with seed.json (format: "wyrm-seed/1", links: [{link, file, accept}], ≤ 256 links) and the package zips; each entry is installed once as install_zip does, subject broker:seed, with the same checks. An existing link is skipped; a failed entry does not stop the others. data_dir/seed.progress.json records each install while the seed runs; data_dir/seed.done records the outcomes when it ends, and the seed never runs again. Both files are replicated to a standby. Documented in docs/operations.md (“Seed packages”), docs/links.md and docs/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 (“в цілому пропозиція зрозуміла”):

  1. 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.
  2. 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-r4 4 GB sdcard.img.gz, bpi-r4-8g sdcard_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).
  3. 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-attachmentattachment: ключі, статуси, ptok v1
05-methodslist, resolve, subscribe, set, invoke, стріми, таймаути
06-flow-defсхема dataflows/<id>/~def
tables.jsonмашинно-читані таблиці кодів (джерело істини для кодогенерації)
fixtures/fixtures.json + *.cbor.hex22 фікстури: канонічний CBOR, hex, JSON-еквівалент

Правила spec

  1. Кодек на дроті — CBOR (RFC 8949), канонічне кодування (RFC 8949 §4.2.1: цілі ключі за зростанням, мінімальна довжина цілих). Decoder мусить приймати неканонічне.
  2. Невідомі ключі ігноруються у ~meta, attachment, ~def. Нові поля додаються без зміни версії.
  3. Ключі — цілі; рядкові ключі дозволені лише всередині cfg, attr, actions.*.params, patch (користувацький вміст).
  4. Версія протоколу — у wy/<site>/sys/~meta, attr.proto = 1; клієнт з іншою мажорною версією отримує invalid_message. Liveliness-токен брокера — wy/<site>/sys/broker (вузла з цим ключем немає).
  5. Зміна будь-якої таблиці → новий запис у tables.json → регенерація фікстур → прогін у всіх SDK.
  6. Глибина вкладення масивів, map і тегів в одному значенні — не більше 32. Decoder відкидає глибше як invalid_message і не входить у рекурсію: вхід від будь-кого не може вичерпати стек.

Тест сумісності (контракт для SDK)

Для кожної фікстури:

  • decode(hex) == json (семантично, з урахуванням float/int)
  • encode(json) канонічно == hex
  • decode(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~metalist | keys | full (default full)
from, limit~meta?view=listпагінація; limit ≤ 1000
match~meta?view=keysis:<code>;type:<code>;unit:<str>;tag:<str> (AND)
depth~meta?view=keys1..∞ (default ∞)
rev~metaповернути status=ok,rev без тіла, якщо не змінилось
field~setcfg.<name> | attr.<name> — запис метаданих замість значення
history, since~valhistory=<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_runsys/**/~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Обов’язк.Опис
0isuint (is_code) або tstrтакпрофіль; uint — код з sys/codes, tstr — повне ім’я (для невідомих клієнту кодів)
1typeuint (type_code)листовий0 null, 1 number, 2 string, 3 bool, 4 enum, 5 map, 6 array, 7 binary, 8 dynamic
2unittstr або uint (unit_code)ні; також у view=listодиниця; UI пише її після числового значення (21.5 °C), не після enum, bool чи тексту
3enumarray of tstrtype=4значення enum; ~val.v = індекс
4writableuintні, default 00 never, 1 config, 2 write
5invokableuintні, default 0мін. рівень для дій: 0 never, 2 read, 3 write, 4 config
6cfgmap (tstr keys)нісистемні параметри: precision min max interval_ms deadband retention_days restricted auto_group enabled
7attrmap (tstr keys)нікористувацькі
8actionsmap name → actionнідив. нижче
9childrenarray of tstrконтейнерупорядкований список дітей (тільки view=full)
10revuintтакверсія meta, монотонна
11has_childrenboolview=listдіти є зараз (будь-які)
12displaytstrні; також у view=list= attr.display, дубль для view=list: назва вузла для людини (див. «Назви для людей»)
13has_overrideboolview=list/keysє відхилення від профілю → варто тягнути full
14children_countuintконтейнер
15quintview=listпоточна quality (щоб UI показав стан без subscribe)
16has_historyboolview=listattr.history не порожній: вузол записується (UI показує значок історії без ~meta на кожен рядок)
17has_nodesboolконтейнер; також у 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). Невідомий editor UI ігнорує.

Назви для людей (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 quint0 good, 1 uncertain, 2 bad
2 tuintuhlc 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 з attachment status (04).
  • Права — як у subscribe: ACL сесії на ~val точки; ptok не потрібен (05).

Фікстури: val_*, hist_raw, hist_agg.

04 — Attachment

CBOR map з цілими ключами. Відсутній attachment = {}.

КлючНазваТипНапрямОпис
0statusuintreplyкод; обов’язковий у кожній відповіді на ~set, ~act, ~meta get
1qualtstrbothрозширений код quality bad/disconnected
2tsuintbothдля raw payload без {v,q,t}
3refreshedboolreply
4ptokbstrrequestдив. нижче
5maxpermuintrequest0..4
6audittstrreply
7errtstrreply
8revuintboth
9riduintbothкореляція стріму
10sequintreply
11lastboolreply
12origintstrbothuser:<id> | flow:<id> | link:<id> | svc:<id> | broker:<site> — довіряється лише при валідному ptok або CN-сесії; з ptok responder приймає лише origin == sub або <sub>/..., інакше підставляє sub
13tracebstr(16)both
14enctstrreplyzstd — payload стиснуто

Статуси

КодІм’яКодІм’я
0x00ok0x24busy
0x01initializing0x25internal_error
0x02refreshed0x26not_supported
0x08not_available0x27not_found
0x10closed0x28timeout
0x20disconnected0x29out_of_range
0x21permission_denied0x2Arate_limited
0x22invalid_message0x40–0x4Fuser-defined
0x23invalid_parameter0x2Bresource_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 — Методи

МетодZenohPayload запитуВідповідь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>?checkmap args, як invokestatus=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аудит/метрики
PriorityDataDataHighInteractiveHighBackground
CongestionControlDropBlockBlockDrop
Reliabilityper cfg.qos (default BestEffort)ReliableReliableBestEffort
expressfalsefalsetruefalse

Помилки транспорту 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):

  1. Змінні (number, string, bool, table) і constant надсилають значення на старті.
  2. Чистий блок без вхідних ребер обчислює один раз на старті зі своїх констант і параметрів. «Без вхідних ребер» означає: жодне ребро не веде в жоден його порт (операнд, порт параметра, 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.
  3. Не чисті (чекають семпла): 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, а також ноди, що не є логічними блоками.
  4. now дає час на старті, якщо його interval_ms більший за 0.
  5. Те, що надсилають правила 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, scope key_scope) і list_children (діти вузла як список рядків {name, path, type?, display?, is?, unit?, writable, has_children}, не більше 1000; path, порт in.path, scope path_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 (default monday), 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, default today; 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 під час компіляції бібліотеку не читає.

Валідація (порядок, перша помилка зупиняє)

  1. схема; 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):

  1. перший: {t, snapshot: true, nodes: {<node>: {in: {<port>: [v, q]}, out: {<port>: [v, q]}, params: {<p>: v}}}} — кожна нода (або з nodes), усі три мапи завжди є; params — ефективне значення кожного параметра, що його має;
  2. далі: {t, snapshot: false, nodes: {…}} — лише ноди і порти, що змінилися після попереднього рядка; порожні in/out/params пропущено. Не більше max_hz рядків на секунду; у межах періоду перемагає останнє значення;
  3. heartbeat {t, nodes: {}} (без snapshot), коли 10 с не було рядка;
  4. потік закінчується через 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; fixture profile_extends.
  • 0.1.3 (2026-10-20): 04 — origin bound to the token subject (sub or <sub>/...). No fixture change.
  • 0.1.4 (2026-10-21): 06 — flow ~val gets optional deployed_by. No fixture change.
  • 0.1.5 (2026-10-21): 01 — peer broker nodes: downstream sites at down/<d>, upstream at up/<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-meta display, description, placeholder, editor (password, textarea); fixture meta_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.proto of wy/<site>/sys/~meta; wy/<site>/sys/broker stays 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=, agg and|or, any <n>s|m|h|d|w window, limit ≤ 100 000; the answer is one or more arrays from the broker’s historian (ADR 0014), errors as a status attachment; rights as subscribe (session ACL on ~val), no history:read token (owner decision). Fixtures hist_raw, hist_agg (HistRow in both SDKs).
  • 0.1.11 (2026-10-23): 02 — view=list summaries carry unit (key 2) and writable (key 4, already sent by the SDK); the UI writes the unit after numeric values. Fixture meta_view_list (first child has 2: "°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). Fixture ptok_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=list summaries carry key 16 has_history (true when attr.history is not empty); attr.history = array of store keys, a key under wy/<site>/sys/history/ answers at the point’s own key (ADR 0016). Fixture meta_view_list (second child has 16: 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 id storage is reserved. No fixture change.
  • 0.2.3 (2026-10-24): 01 — commands from upstream sites: ~set/~act on downstream, dataflows, storage of a site below always, on sys only with that site’s allow_config; tokens carry the target site; wy/<site>/sys/signing_keys lists the keys that sign them (ADR 0018). No fixture change.
  • 0.2.4 (2026-10-24): 02 — param-meta editor values daterange (<from>/<to> in RFC 3339, with preset ranges), date (one instant) and duration (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) and dataflows/~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 ~meta and in view=list): a child without type exists, so a tree UI draws a triangle only where it has nodes to show; the responder publishes the container’s ~meta again when it changes. Fixture meta_view_list (fourth child, a folder with 17: 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 its attr.history comes 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_config of an upstream opens config on the whole site below (downstream, dataflows, storage and sys), not on sys alone (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 ptok claim auth: 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; no auth = refused where it is needed. Fixture ptok_claims_auth.
  • 0.2.11 (2026-10-31): 04 — jti is single-use per responder (remembered until exp, in memory: a responder restart forgets it), exp at 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 sub holds 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 subscribe or liveliness source reads the own site’s downstream, dataflows or storage only (security review, ADR 0031). No fixture change.
  • 0.2.14 (2026-11-01): 04 — optional ptok claim args: SHA-256 of the request payload; the responder refuses another payload (permission_denied). wyrm-mcp takes human approvals only with it (security review, ADR 0031). Fixture ptok_claims_args.
  • 0.2.15 (2026-11-08): 06 — fields as outputs: every parameter p of a node is also an output p (its effective value, at start and on each change) and every input x that is not a parameter’s port an output x (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_types adds (additive) params[].port, a typed params[].default, params[].echo, port_types, echo_inputs. dataflows/<id>/~act/watch (stream: snapshot, changes at most max_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), both read with the caller’s auth covering 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?} (level read, stream): a draft compiled as for deploy runs in a sandbox (nothing persists, no tree node, reads without tokens) with set/invoke/publish as capture nodes that cannot write; rows as watch’s plus an optional sinks: [{node, op, key, value}] (what a sink would do, latest per node), recorded from the start; rights as watch; 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): 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, all number; 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_types lists them in inputs and as params[].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 and ports show 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, not stopwatch.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/preview show it as the input’s value from the start; node_types adds values: true per type (ADR 0038 §7). No fixture change.
  • 0.2.20 (2026-11-08): 06 — ports for the remaining block parameters: concat in.strict, if in.op (a known operator only), hub in.ignore_null, trace in.tracing, in.msg; node_types lists them in inputs and params[].port (ADR 0038 §5b). No fixture change.
  • 0.2.21 (2026-11-08): 06 — text operators, round.text and case: if.op !=, contains, starts_with, ends_with; round.min_precision (port in.min_precision) and output text; new block case (in, op, else, variable inputs in pairs of case and then, constants in values; no regexp) (ADR 0038 §8). No fixture change.
  • 0.2.22 (2026-11-09): 06 — a key from a port inside a scope: subscribe and liveliness get the input in.key, the output error and the parameter key_scope (a key expression inside this site’s downstream, dataflows or storage; required when in.key is wired, validation step 4a; no default). The deployer’s auth reads all of the scope (a grant below read that touches it refuses, a read grant on a part leaves the rest to later grants); watch, ports and preview ask 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 (out null/uncertain until its first sample), a refused value reads nothing and gives a text on error, null reads nothing; changes ≥ 100 ms apart, the latest wins. Command targets keep no port. node_types adds params[].scope (ADR 0040 §1). No fixture change.
  • 0.2.23 (2026-11-09): 06 — the action block: invoke.args keys are fields with ports arg.<name> (constant, then the last sample; ≤ 64); invoke and set get interval_ms (0 or 100 … 86 400 000; first run one full period after the start), auto_run (invoke false: a changed argument runs it; set true: today’s write on in), enabled, the input trigger (an event, or a value that differs from the last one) and the outputs sent, ok, error ({event, id, code, message}), running, last_run, invoke also result (out kept). A sample born at the start (a variable’s or const’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 through trigger or auto_run. dataflows/<id>/~act/trigger {node} (level write; the caller’s auth holds max(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 report sent and never an answer. node_types adds dyn_inputs.keys and trigger (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 type block:<name> with values: {<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 (a publish inside a block: one use). watch/ports/preview show the inner nodes under their ids, and nodes takes an instance id. Library on dataflows: put_block {name, def} and remove_block {name} (config), get_block {name} → {name, version, def, requires} and list_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) and list_children (path/in.path/path_scope; rows {name, path, type?, display?, is?, unit?, writable, has_children}, ≤ 1000) with trigger, interval_ms, auto_run (default true: at the start and on a new key), enabled and outputs out, ok, error, running, last_run, checked as sources; text substring, replace, split, join; data make_object, make_array, get, stats; events and state changed, rising_edge, falling_edge, counter, toggle, sample_and_hold, select; time debounce, throttle. A port for every parameter; the event blocks never act on a sample born at the start. node_types lists 55 types (ADR 0040 §4). No fixture change.
  • 0.2.26 (2026-11-10): 06 — a layout key 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_children is read with its children: deploy, watch, ports and preview ask 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 optional display of add_* and edit on connections, devices and points (the key display is reserved there). A responder SDK fills a missing action or param-meta display from 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. Explicit display texts are in sentence case. Fixture meta_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 degrees sin, cos, tan, cot, asin, acos, atan, to_degrees, to_radians; statistics average, median, mode, std_deviation, variance; text and codecs left, right, trim, base64_encode, base64_decode, url_encode, url_decode, to_camel_case, from_camel_case, hash, json_parse, json_stringify; substring.end, replace.regexp and case operator regexp (bounded patterns; an older config gives the same output); date and time now, date_time, date_format, date_parse, date_math, date_range (dates in microseconds, time_zone IANA/UTC/±HH:MM, default UTC; week_start; previousN is the period before currentN); readers load_history (a table {t, v, q}, truncated in ok) and get_node (summary and actions), every reader runs on ~act/trigger with a read check on its key and scope (trigger: true in node_types); the table value {columns, rows} with its bounds; logic router (outputs out.<case> and else; node_types gives them as dyn_outputs with prefix out.), event_gate, catch_error; tables table, 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 over row, index, checked at compile step 6). ~act/trigger asks max(maxperm, write) on the target of every command block downstream of the node it runs. node_types adds params[].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 but now, the table blocks but table_page and table_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 through in of set/invoke (a variable’s start value still does). now gets interval_ms (port, default 1000, 0 = only on in, else 100 … 86 400 000): the time at start (made of constants), then every period as ordinary samples, and on each sample of in; its in takes no constant (values: true dropped from its catalog entry; a stored values is read and ignored). A now stored before 0.2.30 has no interval_ms and so also sends every second after the upgrade; interval_ms: 0 keeps the old behaviour. The liveliness catalog entry gets its own key description (a node whose presence is read). No fixture change (no wire format change).
  • 0.2.31 (2026-11-12): 06 — flow metrics: ~val gets the text key stats {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 of policy.overflow; commands = the sent/ok/error events of invoke/set. Counters reset at each deploy (so at every engine start and ACL rebuild), start and reload, and are kept across a restart after a panic (restarts + 1) and while stopped. A refused draft’s state: 2 and error stay in the later ~vals until the next state change. A state change publishes ~val at once as before; otherwise ~val goes 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 in err. The responder logs the reason of every refusal. No fixture change. 06 — permissions.maxperm is 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 is ok or the refusal the action would give; the audit records check. A responder that answers it has attr.check = true on its root ~meta; a requester sends ?check only 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 ~val selector with history or since names each of history | since (not both), agg, window, limit at most once and no other parameter; names that start with _ are Zenoh’s and are not read; a duplicate or another parameter is invalid_parameter (typing audit 2026-11-15: a from text could add its own limit to 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 ptok is 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.