From bde407b93b3ab5e25f5101f5f55ed0546a169b39 Mon Sep 17 00:00:00 2001 From: Vitor Babo Date: Sun, 25 Oct 2026 14:34:50 +0000 Subject: [PATCH] fix(ENG-573): pin coreflux-skills to GA tag 2.22.0 and refuse RC pins The public coreflux-skills repo will carry GA tags only; its RC tags are removed once consumers stop pinning them. Move the pin from 2.21.16-rc.186 to 2.22.0 (adds broker-operations) and make sync-skills.mjs refuse branches and release candidates. --- CHANGELOG.md | 4 +- CONTRIBUTING.md | 3 +- plugins/coreflux/README.md | 8 +- .../skills/broker-operations/SKILL.md | 274 ++++++++++++++++++ plugins/coreflux/skills/broker-tools/SKILL.md | 9 +- plugins/coreflux/skills/lot-actions/SKILL.md | 84 +++++- plugins/coreflux/skills/lot-agents/SKILL.md | 2 +- plugins/coreflux/skills/lot-models/SKILL.md | 38 ++- plugins/coreflux/skills/lot-panels/SKILL.md | 41 ++- plugins/coreflux/skills/lot-routes/SKILL.md | 196 ++++++++++++- plugins/coreflux/skills/lot-rules/SKILL.md | 7 +- plugins/coreflux/skills/lot-themes/SKILL.md | 2 +- plugins/coreflux/skills/lot-things/SKILL.md | 2 +- .../coreflux/skills/python-scripts/SKILL.md | 2 +- plugins/coreflux/skills/skills.json | 6 +- scripts/sync-skills.mjs | 19 +- 16 files changed, 660 insertions(+), 37 deletions(-) create mode 100644 plugins/coreflux/skills/broker-operations/SKILL.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 8095cb4..5afd0d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,10 +28,12 @@ All notable changes to the Coreflux plugin for Cursor are documented here. The f ### Changed - The LoT and broker skills are now a pinned copy of - [coreflux-skills](https://github.com/CorefluxCommunity/coreflux-skills) (tag `2.21.16-rc.186`), + [coreflux-skills](https://github.com/CorefluxCommunity/coreflux-skills) (GA tag `2.22.0`), generated from the broker: `broker-tools`, `lot-actions`, `lot-models`, `lot-routes`, `lot-rules`, `lot-agents`, `lot-things`, `lot-panels`, `lot-themes`, `python-scripts`. `npm run skills:sync` updates the copy and `npm run skills:check` (in CI) fails on drift. +- Bundled Coreflux skills updated to 2.22.0 (GA), adding `broker-operations`. The pin must be a + GA tag: `npm run skills:sync` refuses branches and release candidates (ENG-573). ### Removed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3723dcf..9ae9d58 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -65,7 +65,8 @@ npm run e2e # deploys throw-away entities, drives them, removes them synced from [coreflux-skills](https://github.com/CorefluxCommunity/coreflux-skills), which is generated from the broker. Do not edit them here; `npm run skills:check` fails on any drift. Fix the skill in the broker (`src/CorefluxCentral/Agents/Skills/*.md`, `audience: [broker, external]`), - then, once a broker release has tagged coreflux-skills, run `npm run skills:sync -- --ref `. + then, once a broker GA release has tagged coreflux-skills, run `npm run skills:sync -- --ref `. + Pin GA tags only (`MAJOR.MINOR.PATCH`); the sync script refuses branches and release candidates. - Plugin-only guidance (this plugin's MCP tools, hooks, profiles) goes in `skills/coreflux-cursor-tools`, a rule, an agent or a command. - Keep examples copy-pastable. Prefer realistic names (`PackagingLine`, `PLC_Modbus`) over diff --git a/plugins/coreflux/README.md b/plugins/coreflux/README.md index 51c7d11..a527413 100644 --- a/plugins/coreflux/README.md +++ b/plugins/coreflux/README.md @@ -54,13 +54,15 @@ workspace file `active` → user file `active` → `default` → `workspace` → The LoT and broker skills are a pinned copy of [CorefluxCommunity/coreflux-skills](https://github.com/CorefluxCommunity/coreflux-skills), which is -generated from the broker and tagged per broker release; the tag in use is `brokerVersion` in -`skills/skills.json`. Do not edit them here — fix the broker's skill and move the pin with -`npm run skills:sync -- --ref `. CI fails when the bundle drifts from the pinned tag. +generated from the broker and tagged per broker GA release; the tag in use is `brokerVersion` in +`skills/skills.json`. Only GA tags are pinned, never a branch or a release candidate. Do not edit +them here — fix the broker's skill and move the pin with `npm run skills:sync -- --ref `. +CI fails when the bundle drifts from the pinned tag. | Skill | Source | Use | |-------|--------|-----| | `broker-tools` | coreflux-skills | The broker's tool surfaces, registry commands, safe deploy workflow | +| `broker-operations` | coreflux-skills | Operating a broker over MQTT: `$SYS/Coreflux/Command` payloads and replies | | `lot-actions` / `lot-models` / `lot-routes` / `lot-rules` | coreflux-skills | LoT syntax per entity kind | | `lot-agents` / `lot-things` | coreflux-skills | `DEFINE AGENT`, `DEFINE THING` | | `lot-panels` / `lot-themes` | coreflux-skills | LoTV dashboards | diff --git a/plugins/coreflux/skills/broker-operations/SKILL.md b/plugins/coreflux/skills/broker-operations/SKILL.md new file mode 100644 index 0000000..ae953e4 --- /dev/null +++ b/plugins/coreflux/skills/broker-operations/SKILL.md @@ -0,0 +1,274 @@ +--- +name: broker-operations +description: "Operating a Coreflux broker over MQTT: the $SYS/Coreflux/Command payload and the Command/Output reply envelope, the $SYS/Coreflux topic map, route status and action trace JSON, a triage playbook, users, groups and permission flags, env vs secrets, and projects and .lotnb notebooks." +--- + +# Broker Operations — Commands, $SYS Topics, Users, Projects + +Every broker command (`-addAction`, `-listRoutes`, `-loadProject`, …) is reachable two ways: + +- **Over MCP** it is a registry tool of the same name in snake_case (`-listRoutes` → + `list_routes`); see `broker-tools`. The tool's `argument` is what follows the token. +- **Over raw MQTT** an external client (a script, `mosquitto_pub`, an IDE plugin, another + broker) publishes the command to `$SYS/Coreflux/Command` and reads the reply on + `$SYS/Coreflux/Command/Output`. The rest of this skill is about that path. + +## 1. Command payload + +The payload is a **plain UTF-8 string**, never a JSON wrapper: + +``` +-commandName [-requestId ] +``` + +| Rule | Detail | +|------|--------| +| Spellings | Every command also has a `--kebab-case` form (`-listRoutes` = `--list-routes`). Aliases: `-addConnector` = `-addRoute`, `-addVisu` = `-addPanel`, `-listConnectors` = `-listRoutes`, `-connectorCode` = `-routeCode`, … | +| Plain arguments | Split into quote-aware tokens; the quotes are stripped. Quote a name with spaces: `-loadProject "Traceability System"` | +| LoT bodies | `-addAction` / `-addModel` / `-addRoute` / `-addRule` / `-addAgent` / `-addPanel` / `-addTheme` / `-addThing` take the `DEFINE …` block **unquoted**, newlines and indentation preserved. Send one block per add command | +| `--dryRun` | After `-addAction`/`-addModel`/`-addRoute`/`-addRule`/`-addThing`: validate only (the first four reply as `ValidateLot`) | +| `-runAction` JSON | The JSON after the action name is kept verbatim (quotes intact) | +| Comments | `//`, `/* */` and `-- ` comments outside string literals are stripped from the payload before parsing | +| `-requestId` | Must be the **last** token. Echoed back as `requestId`; use it to match replies, because every allowed subscriber sees the same Output topic | +| Identity | The caller is the MQTT session's username. The broker appends `-requestUser` itself — never send it | + +Example payloads: + +``` +-listRoutes -requestId r1 +-addAction DEFINE ACTION Heartbeat +ON EVERY 10 SECONDS DO + PUBLISH TOPIC "system/heartbeat" WITH TIMESTAMP "ISO" -requestId a1 +-setSecret PG_PASSWORD= -requestId s1 +``` + +## 2. Reply envelope (`$SYS/Coreflux/Command/Output`) + +Not retained, JSON, camelCase. Null fields are omitted. + +| Field | When | Meaning | +|-------|------|---------| +| `success` | always | `true` / `false` | +| `command` | always | PascalCase command name (`AddRoute`, `ListRoutes`) | +| `requestId` | if you sent one | Your correlation id | +| `message` | always | Human-readable summary | +| `entityType` / `entityName` | single-entity commands | e.g. `Action` / `Heartbeat` | +| `data` | **always** | Structured result (`{}` when none). List/status commands put their JSON here | +| `errors[]` | failures only | `{ code?, message, line?, column?, sourceLines?, suggestions? }`. Parse context (line, column, `sourceLines` map of line → text, `suggestions`) is on the first error | +| `warnings[]` | when any | Non-fatal problems — e.g. a project load that skipped entities still has `success: true` | + +A failure with a stable code (`ROUTE_INIT_FAILED`, `ROUTE_ACTION_LIMIT_EXCEEDED`) carries it in +`errors[0].code` and `data.error.code`. Branch on the code, not the message. + +**Reading silence and odd replies:** + +| You see | Cause | +|---------|-------| +| `Unknown command: -x` | Not a registered token — a typo | +| `Permission denied: You are not allowed to execute …` | Your user fails `CommandCall` or the command's own scope (section 6) | +| `Command blocked: …` | The payload matched the broker's command-injection filter | +| **No reply at all** | (a) the publish to `$SYS/Coreflux/Command` was dropped — `PublishSys` is default-deny and your user holds none of the three flags; (b) you may not subscribe to `Command/Output`, so the reply exists but you never see it; (c) the command has no MQTT reply: `-updateData` | + +## 3. `-runAction` + +| Form | For | Returns in `data` | +|------|-----|-------------------| +| `-runAction ` | Any action — runs it once, no trigger context | `action`, `traceId` | +| `-runAction {"a":1,"b":2}` | A callable action: the object binds its `INPUT` parameters | the run result | +| `-runAction {"topic":"sensors/line1/temp","payload":72.5}` | An `ON TOPIC` / `ON CHANGE` action, as if that message arrived. `topic` must match the trigger pattern; a non-string `payload` is passed as raw JSON text | `action`, `traceId`, `status` (`success`/`error`/`no_trace_captured`), `published[]` (`{topic, payload}`), `durationMs`, `error` | + +The topic form runs synchronously with tracing forced on, so `published[]` is the fastest way +to see what an action does with a given input. **It is not a dry run**: every PUBLISH really +goes out. A disabled action is refused. Needs `ActionManagementRun`. + +## 4. `$SYS/Coreflux` topic map + +All topics below are prefixed `$SYS/Coreflux/`. Periodic ones are republished about every 7 s; +`-updateData` forces a republish now. + +| Topic | Retained | Content | +|-------|:-------:|---------| +| `Command` | — | Inbound commands (section 1) | +| `Command/Output` | no | Replies (section 2) | +| `Actions/` | yes | Action LoT source (appears on the next periodic cycle after `-addAction`) | +| `Actions//Description` | yes | Action description | +| `Actions//Error` | yes | Last runtime error: `timestamp`, `action`, `error`, `trigger.{topic,clientId}` | +| `Actions//Trace` | no | Trace records, only while tracing is on (`-actionTrace`, 5 min auto-expiry) | +| `Models/` | yes | Model LoT source | +| `Rules/` | no | Rule LoT source (periodic) | +| `Routes/` | yes | Connector LoT source | +| `Routes//status` | no | Connector status JSON (section 5), periodic | +| `Routes//Tools` | yes | MCP connector: discovered tools | +| `Routes//Certificates` | yes | Certificate stores, `pendingCount`, `pending[]` (rejected peer certs awaiting trust), `activeThumbprints` | +| `Routes//Events//Trigger` | — | Inbound: publish here to fire a connector event (needs a `PublishSys` rule) | +| `VoT/Panels/` | no | Panel source | +| `VoT/Themes/` | yes | Compiled theme | +| `Projects/list`, `Projects/active` | yes | Project names; the active project | +| `Projects//status`, `Projects//manifest` | yes | Git status; content manifest | +| `Projects//download` | **no** | `zip64:` from `-getProject` — subscribe **before** sending it | +| `Entities/ownership` | yes | Which project/file/cell owns each entity | +| `Comms/Logins` | no | One JSON per connect attempt: `ClientId`, `Endpoint`, `Username`, `CleanSession`, `ReasonCode` | +| `Comms/Sessions` | no | Connected sessions, periodic | +| `Comms/PacketTrace//In` · `/Out` | no | Raw packets while `mqtt_packet_trace` is on | +| `Log/Traces/<…>` | no | Log lines matching an `-addTraceLog` trace point | +| `Version` | yes | Broker version | +| `License` | yes | Licence and enrollment status (not `License/Status`) | +| `Cluster/Role`, `IsLeader`, `Leader`, `Term`, `Members` | yes | Only when clustering is on. `Members` is a count | + +## 5. Route status and action trace JSON + +**`Routes//status`**: `name`, `type`, `connection` (`Disconnected` | `Connecting` | +`Connected` | `Reconnecting`), `health` (`Green` | `Yellow` | `Red`), +`errors.{total, consecutive, rate}`, `messages.{total, succeeded, failed}`, `lastActivity`, +`lastSuccess`, `lastError`, `uptime`, `connectedSince`, `timestamp`, and `warning` when degraded. + +| Health | When | +|--------|------| +| Red | Disconnected, **or** ≥ 3 consecutive failures, **or** > 30 % failures in the last 20 operations | +| Yellow | Connecting/Reconnecting, an operational warning (`warning` field), or 0–30 % failures in the last 20 operations | +| Green | Connected, no failures in the window | + +`errors.consecutive > 0` while `connection` is `Connected` means the endpoint answers but rejects +the operations: a bad query, wrong register or node, or missing write rights. + +**`Actions//Trace`**: `action`, `traceId`, `timestamp`, +`trigger.{topic, payload (first 512 chars), clientId}`, `timing.{startUtc, endUtc, durationMs}`, +`published[]` (`{topic, payload}`), `result` (`success` | `error`), `error`. + +## 6. Users, groups and permissions + +| Command | Arguments | +|---------|-----------| +| `-addUser` | ` ` — a new user has no flags and no groups | +| `-removeUser` | `` | +| `-changeUserPassword` | ` ` | +| `-changeUserSettings` | ` `, e.g. `operator1 AllowedUserManagement true` | +| `-addUserToGroup` / `-removeUserFromGroup` | ` ` | +| `-listUserGroups` | `` | + +A group exists once a user is in it; there is no create step. Use groups plus rules for data +access (`lot-rules`), and the three flags — `AllowedSystemConfiguration`, +`AllowedUserManagement`, `AllowedLogManagement` — only for administration. A fresh broker has +one user, `root`, with a default password and `AllowedSystemConfiguration`: change it with +`-changeUserPassword` before the broker is reachable from a network. + +**Who passes the locked built-in gates** (user rules cannot change these; see `lot-rules`): + +| Gate | Passes | +|------|--------| +| Publish to `$SYS/Coreflux/Command` | any of the three flags; `root` | +| Subscribe `Command/Output`, `Projects/#` | `AllowedSystemConfiguration`, `AllowedUserManagement`, `root`, `admin` | +| Subscribe any other `$SYS/#` | `AllowedSystemConfiguration`, `root`, `admin` | +| `CommandCall` — **every** MQTT command checks this first | `AllowedSystemConfiguration`, `AllowedUserManagement`, `root`, `admin` | + +Then the command's own scope: + +| Commands | Scope | Passes | +|----------|-------|--------| +| Projects (`-addProject`, `-loadProject`, `-unloadProject`, `-removeProject`, `-duplicateProject`, `-projectCheckout/Pull/Push`), `-setEnv`/`-removeEnv`, `-setSecret`/`-removeSecret`, `-restoreRules`, `-auditQuery`, `-decryptAudit` | SystemConfiguration | `AllowedSystemConfiguration`, `root` | +| `-addRule`, `-removeRule`, `-removeAllProjectRules` | Rule… | `AllowedSystemConfiguration`, `root` | +| User commands, MCP tokens | UserManagement… | `AllowedUserManagement`, `AllowedSystemConfiguration`, `root` | +| `-addTraceLog`, `-listTraceLogs`, `-removeTraceLog` | LogManagement… | `AllowedLogManagement`, `AllowedSystemConfiguration`, `root` | +| Add/remove/enable/disable actions, connectors, agents, things; remove models; python, panels, themes | …Creation / …Remove | `AllowedSystemConfiguration`, `root`, `admin` | +| `-addModel`, `-runAction` | ModelManagementCreation, ActionManagementRun | same, but their built-in rule sits at 1000000, so a user rule overrides it | +| Everything else (`-list*`, `-get*`, `-validate*`, `-routeCode`, `-actionTrace`, `-auditStatus`, …) | CommandCall | the CommandCall gate only | + +`AllowedLogManagement` alone can publish a command but fails `CommandCall` and cannot read +`Command/Output`; pair it with another flag. **Anti-lockout:** `root` always passes Connect, +CommandCall, rule add/remove and the Command/Output topics, whatever rules exist. Before +deploying a Connect or deny rule, keep root's credentials safe and test the rule with a second +account; `-restoreRules` resets the three shipped seed rules. + +Audit: `-auditStatus`, `-auditQuery `, `-decryptAudit `. Transport +defaults: MQTT 1883, MQTT over TLS 8883. Connector PKI: `-routeCertificates cert64:` +(op `stores` / `list` / `inspect` / `trust` / `delete` / `export` / `import`). + +## 7. Env vs secrets + +| | `-setEnv NAME=value` | `-setSecret NAME=value` | +|-|-|-| +| Stored | plain `.env` file | encrypted (AES-256-GCM) | +| Listed by | `-listEnv` — **names and values**, to anyone passing CommandCall | `-listSecrets` — names only | +| In LoT | `GET ENV "NAME"`, `{env.NAME}` | `GET SECRET "NAME"`, `{secret.NAME}` | +| Use for | hosts, ports, database names, flags | passwords, API keys, tokens | + +Never put a credential value from chat into a command you compose. Tell the operator which +names to set and let them run `-setSecret` themselves. + +## 8. Projects and `.lotnb` notebooks + +A project is a folder of `.lotnb` notebooks (subfolders included) under the broker's projects +directory. + +**Notebook format** — a JSON **array** of cells, no wrapper object: + +```json +[ + { "kind": 1, "language": "markdown", "value": "# Line 1 telemetry" }, + { "kind": 2, "language": "lot", "value": "DEFINE MODEL …\n\nDEFINE ACTION …" }, + { "kind": 2, "language": "python", "value": "# Script Name: LineMath\ndef oee(a, p, q):\n return a * p * q" } +] +``` + +- Only `kind: 2` (code) cells load; every other kind is skipped. +- `lot` cells may hold several DEFINE blocks. `python` cells need a `# Script Name: ` + comment (or a `scriptName` field). Any other language, e.g. `shellscript`, is documentation. +- A duplicate entity name keeps the first occurrence and reports a warning. + +**Load order is by kind, not by file:** models → actions → connectors → agents → rules → +python → themes → panels → Things. Pending dependencies (an action whose `CALL PYTHON` script +loads later) are resolved once loading ends; anything still stuck shows in `-getPendingStatus`. + +| Command | Notes | +|---------|-------| +| `-addProject [branch]` | Clones; the name comes from the URL | +| `-addProject ` | Copies a folder on the broker host; the name is the folder name | +| `-addProject > [name] [load]` | Extracts; `load` loads it at once | +| `-loadProject ` | Replaces the previous project's entities and is remembered across restarts. Reply `data`: `project`, `entities[]` (`type`, `name`, `origin`), `counts`, `load`. Entities that failed are in `warnings[]` | +| `-unloadProject` | Removes the project's entities and clears the remembered project | +| `-listEntities` | Every entity with `origin`: `{kind:"adhoc"}` or `{kind:"project", project, file, cell}` | +| `-getProject ` | Publishes `zip64:` on `Projects//download` | +| `-listProjects`, `-removeProject`, `-duplicateProject `, `-projectCheckout `, `-projectPull`, `-projectPush`, `-projectStatus`, `-projectManifest` | Git-backed project management | +| `-validateLotnb ` / `-validateLotnb --project ` | Validate without deploying | + +Entities added ad hoc with `-addX` survive `-unloadProject` and a later `-loadProject`. The +broker CLI flag `--project ` (with `--branch`) loads a project at startup. + +Suggested layout: numbered notebooks by concern (`01-models.lotnb`, `02-actions.lotnb`, +`03-connectors.lotnb`, …) for readers — the numbers do not change load order — and a README +listing every `GET ENV` / `GET SECRET` name the operator must set. + +## 9. Triage playbook + +**Action deployed, nothing published** +1. `-runAction {"topic":"","payload":…}`: a topic mismatch is reported; + `published: []` means an IF or a cast never reached PUBLISH. +2. Read the retained `Actions//Error`. +3. `-getPendingStatus`: the action may be waiting for a model, script or connector. +4. Check the trigger's `+` / `#` shape against the topics that really arrive. + +**Connector connected, data missing** +1. `Routes//status`: `errors.consecutive` and `lastError`. +2. `-checkRouteConnection `. +3. OT tag values arrive on `/`, not on `DESTINATION_TOPIC`. +4. Events fire on PUBLISH; KEEP TOPIC never triggers a connector. + +**Connector disconnected** +1. Every `GET ENV` / `GET SECRET` name exists (`-listEnv`, `-listSecrets`). +2. `Routes//Certificates`: `pendingCount > 0` means a peer certificate awaits trust. + +## Do not + +- Wrap the command in JSON, or quote a LoT body. +- Send `-requestUser`, or put `-requestId` anywhere but last. +- Expect a reply from `-updateData`. +- Send `-loadFolder` over MQTT: it is refused there, because it would read any folder on the broker + host. Use `-addProject` / `-loadProject`, or `--project` at startup. +- Read `License/Status` or `Stats` — use `License`; there is no live `Stats` topic. +- Wait for `Projects//download` after sending `-getProject` — it is not retained. +- Treat `-runAction` with a topic envelope as a dry run. +- Use `USER HAS` with a flag other than the three that exist (it is silently false). +- Try to widen `SubscribeSys` or `CommandCall` with a user rule; the locked built-ins decide. +- Put secrets in `-setEnv`; anyone who can run commands can list env values. +- Run without confirming: `-removeAll*`, `-removeProject`, `-removeUser`, `-unloadProject` + while a project is active, `-restoreRules` (resets edits to the three seed rules). diff --git a/plugins/coreflux/skills/broker-tools/SKILL.md b/plugins/coreflux/skills/broker-tools/SKILL.md index 54911bd..757f33b 100644 --- a/plugins/coreflux/skills/broker-tools/SKILL.md +++ b/plugins/coreflux/skills/broker-tools/SKILL.md @@ -1,6 +1,6 @@ --- name: broker-tools -description: Complete reference for the tools you can call on a Coreflux broker: the MCP tool surface the Hub assistant and MCP clients use (validate_lot, deploy_lot, explore_topics, diagnose, provision_data_source and one tool per registry command), the broker__ tools a DEFINE AGENT is granted (read_mqtt, write_mqtt, read_lot, create_lot, execute_routes, execute_actions), Insight vs Agent mode, and the mandatory workflow for deploying LoT safely. +description: "Complete reference for the tools you can call on a Coreflux broker: the MCP tool surface the Hub assistant and MCP clients use (validate_lot, deploy_lot, explore_topics, diagnose, provision_data_source and one tool per registry command), the broker__ tools a DEFINE AGENT is granted (read_mqtt, write_mqtt, read_lot, create_lot, execute_routes, execute_actions), Insight vs Agent mode, and the mandatory workflow for deploying LoT safely." --- # Broker Tools — Complete Reference @@ -74,7 +74,12 @@ Which skill to load before each kind: (and `get_route_template("TYPE")` over MCP) · Rule → `lot-rules` · Panel → `lot-panels` · Theme → `lot-themes` · Agent → `lot-agents` · Python script → `python-scripts` - Before explaining or changing a DEFINE THING, or an entity it owns → `lot-things` -- A vendor REST API (Airtable, ServiceNow, SAP, …) → `rest-api-connectors` +- A vendor REST API (Airtable, ServiceNow, SAP, …) → `rest-api-connectors` on the Hub and in + a DEFINE AGENT. Elsewhere that skill is not available; get the same information from + `list_route_templates` (REST API apps carry `connector: true`) and + `get_route_template("")` (`-routeCode ` over MQTT) +- Raw MQTT commands on `$SYS/Coreflux/Command`, the `$SYS` topic map, users and permission + flags, env vs secrets, projects and `.lotnb` notebooks → `broker-operations` --- diff --git a/plugins/coreflux/skills/lot-actions/SKILL.md b/plugins/coreflux/skills/lot-actions/SKILL.md index 44f7c8a..d95f4cb 100644 --- a/plugins/coreflux/skills/lot-actions/SKILL.md +++ b/plugins/coreflux/skills/lot-actions/SKILL.md @@ -1,6 +1,6 @@ --- name: lot-actions -description: How to write LOT actions: triggers, variables, topic operations, control flow, callable actions, and integrations (Python, MCP, LLM). +description: "How to write LOT actions: triggers, variables, topic operations, control flow, callable actions, and integrations (Python, MCP, LLM)." --- # LOT Actions — Complete Reference @@ -175,6 +175,9 @@ ON TOPIC "sensors/+/data" DO ``` Use `+` for single-level wildcard in topic patterns. PAYLOAD gives the message content. TOPIC POSITION N extracts segment N (1-based). +PAYLOAD exists only in ON TOPIC and ON CHANGE actions. In ON EVERY, ON START, session triggers and +callable actions there is no message: a bare PAYLOAD fails to compile, and a typed `PAYLOAD AS DOUBLE` +compiles but never holds data. Read the last value with `GET TOPIC "…"` instead. ### ON CHANGE (MQTT-triggered only when payload bytes change) ``` @@ -193,6 +196,42 @@ ON START DO ``` In a cluster, ON START runs once per cluster start, on one node, at most once. A node that restarts, or a definition deployed later, does not run it again. +### ON CONNECT / ON DISCONNECT / ON SUBSCRIBE (client session events) +``` +DEFINE ACTION AuditConnect +ON CONNECT DO + PUBLISH TOPIC "audit/connect/" + CLIENTID WITH USER + "@" + ENDPOINT + KEEP TOPIC "sessions/" + CLIENTID + "/clean" WITH CLEANSESSION + +DEFINE ACTION AuditDisconnect +ON DISCONNECT DO + PUBLISH TOPIC "audit/disconnect/" + CLIENTID WITH DISCONNECTREASON + +DEFINE ACTION AuditSensorSubscriptions +ON SUBSCRIBE "sensors/#" DO + PUBLISH TOPIC "audit/subscriptions" WITH CLIENTID + " -> " + SUBSCRIBETOPIC + " qos=" + SUBSCRIBEQOS +``` +ON CONNECT runs after the broker accepts a client's CONNECT; ON DISCONNECT when the client goes away +(clean, unclean or session takeover); ON SUBSCRIBE after the subscribe permission check allows a +subscription. `ON SUBSCRIBE "pattern"` fires when the subscribed topic filter matches the pattern +(`+`/`#` allowed); bare `ON SUBSCRIBE DO` fires for every allowed subscription. + +Session keywords (no braces — they are keywords, not variables): + +| Keyword | Value | +|---------|-------| +| CLIENTID | The client that connected, disconnected or subscribed | +| USER | That client's username (`USER IN GROUP "g"` / `USER IS "name"` work too) | +| ENDPOINT | Client address (`ip:port`) | +| CLEANSESSION | `"true"` / `"false"` from the CONNECT packet | +| DISCONNECTREASON | ON DISCONNECT only, e.g. `Clean (NormalDisconnection)`, `NotClean`, `Takeover` | +| SUBSCRIBETOPIC | ON SUBSCRIBE only: the topic filter the client subscribed to | +| SUBSCRIBEQOS | ON SUBSCRIBE only: the granted QoS (0, 1, 2); -1 elsewhere | + +These actions have no triggering message: PAYLOAD fails to compile in them and TOPIC POSITION is +empty. The broker +only runs the session hooks while at least one action uses them, so there is no cost when unused. + ### Callable actions (INPUT / RETURN / OUTPUT) Callable actions have no MQTT trigger. Use INPUT lines, DO body, then RETURN with one OUTPUT per line (one variable each). Comma-separated RETURN OUTPUT and single-line RETURN OUTPUT result are rejected. @@ -315,6 +354,19 @@ payload with PUBLISH MODEL (below) or return a dict from CALL PYTHON. Do not han JSON with escaped quotes (`"{\"a\": 1}"`) — a `\"` in a string literal fails to compile. RETAIN / QOS apply to PUBLISH TOPIC only, never to KEEP TOPIC. +### PAYLOAD AS BYTES — forward binary payloads unchanged +``` +DEFINE ACTION ForwardCameraFrame +ON TOPIC "cameras/+/frame" DO + SET "cam" WITH TOPIC POSITION 2 + PUBLISH TOPIC "archive/cameras/" + {cam} + "/frame" WITH PAYLOAD AS BYTES + KEEP TOPIC "state/cameras/" + {cam} + "/last" WITH PAYLOAD AS BYTES +``` +Plain PAYLOAD goes through a UTF-8 string, which corrupts images, protobuf and other binary data. +`WITH PAYLOAD AS BYTES` on PUBLISH TOPIC or KEEP TOPIC passes the bytes through bit for bit. A string +transformation after it (`PAYLOAD AS BYTES TRIM`, FILTER, REPLACE) is a parse error, and an empty +payload is not published or kept. + ### KEEP TOPIC — stored without broadcast, readable by GET TOPIC from any action ``` KEEP TOPIC "state/mode" WITH "running" @@ -439,7 +491,19 @@ All timestamps are UTC; there is no local-time format. An unrecognised string is ``` CALL ACTION "CalcAvg" WITH value1 = {a}, value2 = {b} RETURN avg ``` -The callable must be deployed first (deploy fails with "Callable action … not found"). +Unlike CALL PYTHON, the one-line form is valid here. For long argument lists, WITH and RETURN may also go +on indented lines; several outputs are comma-separated after RETURN: +``` +DEFINE ACTION CheckBoilerTemp +ON TOPIC "boiler/+/temp" DO + SET "temp" WITH PAYLOAD AS DOUBLE + CALL ACTION AnalyzeReading + WITH value = {temp}, threshold = 85 + RETURN is_above, difference, percentage + IF {is_above} == TRUE THEN + PUBLISH TOPIC "boiler/" + TOPIC POSITION 2 + "/alarm" WITH "over by " + {difference} +``` +(`AnalyzeReading` is the callable from "Callable actions" above.) The callable must be deployed first (deploy fails with "Callable action … not found"). Calling the same callable twice in one action currently fails to compile — split it. ### CALL PYTHON — invoke a Python function @@ -459,7 +523,13 @@ CALL MCP "MyMcpRoute.search" WITH (query = "test") RETURN AS {result} ``` -"RouteName.ToolName" in one string; named arguments inside parentheses. +"RouteName.ToolName" in one string; named arguments inside parentheses. There is no TOOL keyword: +`CALL MCP "MyMcpRoute" TOOL "search"` is rejected (the string must contain exactly one dot). + +To find the tool names and their parameters, read the retained topics the MCP connector publishes once +it connects: `$SYS/Coreflux/Routes//Tools` (summary with the `tools` list) and +`$SYS/Coreflux/Routes//Tools/` (description and `parameters`). Its `usage_example` and +`trigger_example` fields are ready to paste. ### CALL LLM — invoke an LLM route ``` @@ -477,9 +547,9 @@ CALL AGENT "MyAgent.execute" ### TRIGGER — trigger a route event ``` -TRIGGER "MyDB" WITH "sensor1" FOR "ReadSensors" +TRIGGER "MyDB" TO "sensor1" FOR "ReadSensors" ``` -Order: route name, WITH the data to send, FOR the route event/mapping name. +Order: connector name, TO the data to send, FOR the route event/mapping name. `WITH` is accepted in place of `TO`, but the data still comes before `FOR`. Writing the event name first and the data after `FOR` still parses, but sends the event name as the data to an event named after the data. ## PUBLISH MODEL — publish a model instance ``` @@ -497,6 +567,7 @@ JSON reshaping, external library math, or multi-step data processing. Every script MUST have `# Script Name: ` in the first 10 lines. Deploy with `broker.add_python(argument=...)` — the argument is the whole script, header included; the name is read from the header (letters, digits, `_`; must not start with a digit). +In a project (`.lotnb`), Python cells load after the actions; project loading is covered by `broker-operations`. ```python # Script Name: SensorUtils @@ -659,6 +730,9 @@ RETURN | SWITCH {x} / CASE | IF … ELSE IF … ELSE | SWITCH is not an action statement | | PAYLOAD AND_THEN TRIM | PAYLOAD TRIM, or FILTER … AND THEN TRIM | Chain keyword is AND THEN (two words) | | WITH { "k": {v} } | PUBLISH MODEL, or a dict from CALL PYTHON | No JSON object literal | +| PAYLOAD inside ON EVERY / ON START / ON CONNECT | GET TOPIC "…" AS DOUBLE | Only ON TOPIC / ON CHANGE have a message | +| CALL MCP "Route" TOOL "search" | CALL MCP "Route.search" (WITH / RETURN AS indented) | There is no TOOL keyword | +| PUBLISH … WITH PAYLOAD (binary data) | PUBLISH … WITH PAYLOAD AS BYTES | Plain PAYLOAD is decoded as UTF-8 text | ### Trigger indentation - the most common AI mistake diff --git a/plugins/coreflux/skills/lot-agents/SKILL.md b/plugins/coreflux/skills/lot-agents/SKILL.md index 66e02f2..522c6f3 100644 --- a/plugins/coreflux/skills/lot-agents/SKILL.md +++ b/plugins/coreflux/skills/lot-agents/SKILL.md @@ -1,6 +1,6 @@ --- name: lot-agents -description: How to write a DEFINE AGENT: the TYPE LLM connector it uses, required clauses, ADD TOOL grants scoped to topics or targets, delegation peers, CALL AGENT from actions, and how agents are added, updated and removed. +description: "How to write a DEFINE AGENT: the TYPE LLM connector it uses, required clauses, ADD TOOL grants scoped to topics or targets, delegation peers, CALL AGENT from actions, and how agents are added, updated and removed." --- # LOT Agents — DEFINE AGENT diff --git a/plugins/coreflux/skills/lot-models/SKILL.md b/plugins/coreflux/skills/lot-models/SKILL.md index 4e5812a..f825f9f 100644 --- a/plugins/coreflux/skills/lot-models/SKILL.md +++ b/plugins/coreflux/skills/lot-models/SKILL.md @@ -1,6 +1,6 @@ --- name: lot-models -description: How to write LOT models: data schemas, field types, MQTT topic bindings, triggers, behaviors (Default, Keep, Collapsed), storage, and inheritance. +description: "How to write LOT models: data schemas, field types, MQTT topic bindings, triggers, behaviors (Default, Keep, Collapsed), storage, and inheritance." --- # LOT Models — Complete Reference @@ -51,6 +51,23 @@ Models define data schemas that map MQTT topics to typed fields. `ADD JSON "x"` and `ADD TIMESTAMP "x"` are parse errors — use OBJECT and STRING. The type may be omitted (`ADD "x" WITH TOPIC "t"`); it is then inferred from the value. +To embed JSON you received (not a string of it), assign the JSON text to an OBJECT or ARRAY field in +PUBLISH MODEL. The text is parsed into the document; text that is not valid JSON becomes `{}` / `[]`. +``` +DEFINE MODEL GatewayEnvelope COLLAPSED + ADD STRING "gateway" + ADD OBJECT "data" + ADD STRING "received" WITH TIMESTAMP "ISO" + +DEFINE ACTION WrapGatewayData +ON TOPIC "gateways/+/raw" DO + SET "gw" WITH TOPIC POSITION 2 + PUBLISH MODEL GatewayEnvelope TO "gateways/" + {gw} + "/envelope" WITH + gateway = {gw} + data = (GET JSON "data" IN PAYLOAD AS STRING) +``` +`GET JSON … AS STRING` on a nested object returns its JSON text, so `data` is published as an object. + ## Field Bindings ### WITH TOPIC — bind field to an MQTT topic @@ -65,6 +82,24 @@ ADD DOUBLE "temperature" WITH TOPIC "sensors/temp" AS TRIGGER When a message arrives on the trigger topic, the model re-evaluates and publishes. At least one field must be AS TRIGGER for the model to auto-publish. +Several fields may be AS TRIGGER; a message on any one of them publishes the model, with the other +fields at their last known values: +``` +DEFINE MODEL MachineSnapshot COLLAPSED WITH TOPIC "machines/press1/snapshot" + ADD DOUBLE "temperature" WITH TOPIC "machines/press1/temp" AS TRIGGER + ADD DOUBLE "pressure" WITH TOPIC "machines/press1/pressure" AS TRIGGER + ADD STRING "timestamp" WITH TIMESTAMP "ISO" +``` + +### WITH COLLECTION TO TOPIC — build an array from numbered subtopics +``` +DEFINE MODEL LineOrders COLLAPSED WITH TOPIC "line1/orders/summary" + ADD STRING "line" WITH TOPIC "line1/orders/updated" AS TRIGGER + ADD ARRAY "orders" WITH COLLECTION TO TOPIC "line1/orders/item" +``` +The array is read from `line1/orders/item/0`, `line1/orders/item/1`, … and stops at the first missing +index. Declare the field ARRAY, and publish one JSON object per index. + ### WITH (static or computed default) — NO VALUE keyword Static defaults use WITH directly. Never use WITH VALUE — the parser rejects it for anything but a plain literal. ``` @@ -324,6 +359,7 @@ ON TOPIC "machines/+/cycle" DO | ADD STRING "ok" WITH VALUE "ok" | ADD STRING "ok" WITH "ok" — VALUE only takes a literal; drop it | | No AS TRIGGER on any field (topic-bound model) | At least one field must have AS TRIGGER | | ADD JSON "cfg" / ADD TIMESTAMP "ts" | ADD OBJECT "cfg" / ADD STRING "ts" WITH TIMESTAMP "ISO" | +| ADD STRING "data" for received JSON (published as an escaped string) | ADD OBJECT "data" — JSON text assigned to it is parsed | | DEFINE MODEL Device / DEFINE MODEL Event | Keyword names are rejected — DeviceInfo, EventRecord | | DEFINE child before parent | Define parent model first | | COLLAPSED when subtopics are needed | Only use COLLAPSED when you want one JSON blob | diff --git a/plugins/coreflux/skills/lot-panels/SKILL.md b/plugins/coreflux/skills/lot-panels/SKILL.md index e0c5cc8..a85747c 100644 --- a/plugins/coreflux/skills/lot-panels/SKILL.md +++ b/plugins/coreflux/skills/lot-panels/SKILL.md @@ -1,6 +1,6 @@ --- name: lot-panels -description: How to write LoTV panel definitions: DEFINE PANEL, ADD COMPONENT, BIND, ON events, WITH VISIBILITY, WITH INTERACT, and the mandatory workflow for deploying panels via broker.add_panel. +description: "How to write LoTV panel definitions: DEFINE PANEL, ADD COMPONENT, BIND, ON events, WITH VISIBILITY, WITH INTERACT, and the mandatory workflow for deploying panels via broker.add_panel." --- # LoTV Panel Authoring — Coreflux Visual Language @@ -710,6 +710,7 @@ Ask these questions in order. Stop at the first YES that applies: "show a button to start machine" WITH TYPE "button" + ON CLICK DO PUBLISH (only if user explicitly asked for a control) "show a switch to turn on light" WITH TYPE "switch" + ON TOGGLE DO PUBLISH ... WITH STATE (only if user explicitly asked; NEVER auto-add next to an indicator) "navigate between screens" WITH TYPE "button" + ON CLICK DO NAVIGATE + "button that asks an agent" WITH TYPE "button" + SET AWAIT "AnswerText" (+ "text" with SET MARKDOWN true) ### Quick reference — layout and navigation @@ -1675,6 +1676,44 @@ DEFINE PANEL "LineOverview" clicking user. It is refused (logged, not run) for an event whose name starts with `_` and for an agent route. +### Slow answers — `SET AWAIT` on a button, `SET MARKDOWN` on text + +When a button starts something that answers later on another topic (an agent +brief, a route reply), name the components that answer lands in with +`SET AWAIT`. When the answer is markdown (agent output usually is), add +`SET MARKDOWN true` to the `text` component that shows it. + +```lot +ADD COMPONENT "Briefing" WITH TYPE "card" + SET TITLE "Coordinator briefing" + ADD COMPONENT "BriefingText" WITH TYPE "text" + SET MARKDOWN true + BIND CONTENT TO TOPIC "site/out/briefing" + ADD COMPONENT "AskBriefing" WITH TYPE "button" + SET LABEL "Brief me now" + SET AWAIT "BriefingText" + SET AWAIT_TIMEOUT 300 + ON CLICK DO + PUBLISH TOPIC "site/requests/briefing" WITH "operator request from the panel" +``` + +- `SET AWAIT "Id[, Id…]"` (buttons only): on click the Hub disables the button + with a spinner and marks each named component as waiting (dimmed, spinner and + elapsed seconds; an empty `text` shows a skeleton instead of `---`). A + component settles on the next message on any topic it is bound to, even an + identical payload. The button frees up once every named component settled. +- `SET AWAIT_TIMEOUT ` (default 120, 1–3600): after it the button frees + up and a component that is still waiting shows "No update after N s" until its + next value. Set it a little above the agent's `TASK_TIMEOUT` or the route's + worst case. +- Every `AWAIT` id must be a component of the same panel with a `BIND`; the + parser warns otherwise. If the action can skip publishing (a cooldown, a + guard), publish something on the awaited topic in that branch too, or the + panel waits until the timeout. +- `SET MARKDOWN true` renders bold, italics, lists, headings, links and code. + Raw HTML is never rendered (it shows as text) and images are dropped. Without + it, text stays plain. + --- ## Visibility Decision Tree diff --git a/plugins/coreflux/skills/lot-routes/SKILL.md b/plugins/coreflux/skills/lot-routes/SKILL.md index 1df350e..6d4f906 100644 --- a/plugins/coreflux/skills/lot-routes/SKILL.md +++ b/plugins/coreflux/skills/lot-routes/SKILL.md @@ -1,6 +1,6 @@ --- name: lot-routes -description: How to write LOT connectors: database, OT (Modbus, S7, OPC UA, EtherNet/IP, ADS, Allen-Bradley, Fins), REST API, AI (LLM, MCP), MQTT bridge/cluster, Kafka/REST integrations, email, barcode, video, events, mappings, and OT TAG blocks. +description: "How to write LOT connectors: database, OT (Modbus, S7, OPC UA, EtherNet/IP, ADS, Allen-Bradley, Fins), REST API, AI (LLM, MCP), MQTT bridge/cluster, Kafka/REST integrations, email, barcode, video, events, mappings, and OT TAG blocks." --- # LOT Connectors — Complete Reference @@ -152,16 +152,20 @@ shared connector channel is saturated (and, on a cluster, where the connector ru broker-wide default. ``` -DEFINE ROUTE CloudBridge WITH TYPE MQTT_BRIDGE +DEFINE ROUTE HistorianDB WITH TYPE POSTGRESQL ADD ROUTE_CONFIG - WITH OVERLOAD_POLICY "lossless" + WITH OVERLOAD_POLICY "balanced" WITH OVERLOAD_TIMEOUT 200 WITH OVERLOAD_CAPACITY 20000 - ADD SOURCE_CONFIG - WITH BROKER SELF - ADD DESTINATION_CONFIG - WITH BROKER_ADDRESS "broker.example.com" - WITH BROKER_PORT 8883 + ADD SQL_CONFIG + WITH SERVER GET ENV "PG_HOST" + WITH PORT 5432 + WITH DATABASE "historian" + WITH USERNAME GET ENV "PG_USER" + WITH PASSWORD GET SECRET "PG_PASSWORD" + ADD EVENT StoreReading + WITH SOURCE_TOPIC "sensors/store" + WITH QUERY "INSERT INTO readings (device, value) VALUES ('{payload.json.device}', CAST('{payload.json.value}' AS DOUBLE PRECISION))" ``` | Setting | Values | Description | @@ -175,6 +179,11 @@ DEFINE ROUTE CloudBridge WITH TYPE MQTT_BRIDGE sheds once exhausted, which would silently break the "lossless never sheds" guarantee. Declaring both logs an error and the connector runs with capacity forced back to unbounded; lossless always wins. +The broker-wide default (what a connector without ADD ROUTE_CONFIG inherits) comes from two environment +variables read at broker start: `COREFLUX_ROUTE_OVERLOAD_POLICY` (`lossless` / `balanced` / `realtime`, +default `balanced`) and `COREFLUX_ROUTE_CHANNEL_FULL_TIMEOUT_MS` (the `balanced` wait, default 50). +`COREFLUX_ROUTE_CHANNEL_CAPACITY` sizes the shared connector channel (default 100000, minimum 1024). + ## Environment Variables and Secrets Use GET ENV and GET SECRET for sensitive configuration: @@ -194,17 +203,20 @@ DEFINE ROUTE MyDB WITH TYPE POSTGRESQL ADD EVENT ReadSensor WITH SOURCE_TOPIC "sensors/+/read" WITH DESTINATION_TOPIC "sensors/{topic.2}/result" - WITH QUERY "SELECT * FROM sensors WHERE id = '{payload}'" + WITH QUERY "SELECT * FROM sensors WHERE id = '{payload.json.id}'" ``` +`{payload.json.id}` (with a payload like `{"id": "s1"}`) is used rather than `'{payload}'`, which is inserted +unescaped; see the SQL injection note under PostgreSQL. ### Query Placeholders | Placeholder | Value | |-------------|-------| | {payload} | Raw MQTT message payload | +| {payload.json} / {value.json} | The whole payload (same text as {payload}) | | {payload.json.key} | Nested JSON extraction | | {topic} | Full MQTT topic | | {topic.N} | Topic segment by position (1-based) | -| {timestamp} | ISO 8601 timestamp | +| {timestamp} / {timestamp.iso} | ISO 8601 timestamp | | {timestamp.unix} | Unix seconds | | {timestamp.unix_ms} / {timestamp.utc} | Unix milliseconds / `yyyy-MM-dd HH:mm:ss` UTC | | {payload.csv.N} | Nth CSV field of the payload (0-based) | @@ -253,6 +265,11 @@ ADD MAPPING ControlSetpoint Read value publishes on **factory/plc1/control/setpoint**; publishing to **factory/plc1/control/setpoint/write** writes the value to the PLC. +Value options on an OT **ADD TAG** (all optional): **SCALING** and **OFFSET** give `raw × SCALING + OFFSET`; +**MIN_VALUE** / **MAX_VALUE** clamp it; **DECIMAL_PLACES** rounds it (default 2); **DEADBAND** is the minimum +change before a new value is published (default 0 = every poll); **UNIT** is a label. These take a plain number; +OFFSET, MIN_VALUE and MAX_VALUE may be negative (`WITH OFFSET -40`). + ## Database Connector Examples ### PostgreSQL @@ -268,11 +285,16 @@ DEFINE ROUTE ProductionDB WITH TYPE POSTGRESQL ADD EVENT GetOrders WITH SOURCE_TOPIC "orders/query" WITH DESTINATION_TOPIC "orders/result" - WITH QUERY "SELECT * FROM orders WHERE status = '{payload}'" + WITH QUERY "SELECT * FROM orders WHERE status = '{payload.json.status}'" ADD EVENT InsertReading - WITH SOURCE_TOPIC "sensors/+/store" - WITH QUERY "INSERT INTO readings (device, value, ts) VALUES ('{topic.2}', {payload}, NOW())" + WITH SOURCE_TOPIC "sensors/store" + WITH QUERY "INSERT INTO readings (device, value, ts) VALUES ('{payload.json.device}', CAST('{payload.json.value}' AS DOUBLE PRECISION), NOW())" ``` +**SQL injection:** QUERY is built by text substitution; there are no bound parameters. Only `{payload.json.key}` and +`{payload.csv.N}` values have their single quotes doubled, so put those inside `'…'` and CAST numbers in SQL. +Raw `{payload}`, `{value.json}` and `{topic.N}` are inserted unescaped: a `'` in a payload or topic segment +(both are client-controlled) breaks or rewrites the statement. Never use them inside a query, and limit who may +publish to SOURCE_TOPIC with a rule (`lot-rules`). Give the connector's database user only the rights it needs. ### MongoDB ``` @@ -315,6 +337,30 @@ connector deploys but every poll fails with `Unsupported address type`. A plain offset (`WITH ONE_BASED_ADDRESSES true` on MODBUS_CONFIG makes `1` the first register). Only six-digit Modicon addresses (`400001`, `300001`, `100001`) are converted; `"40001"` is register offset 40001, not the first holding register. +### Modbus RTU (MODBUS_SERIAL) +``` +DEFINE ROUTE BoilerRtu WITH TYPE MODBUS_SERIAL + ADD MODBUS_CONFIG + WITH COM_PORT "/dev/ttyUSB0" + WITH BAUD_RATE 19200 + WITH PARITY "EVEN" + WITH DATA_BITS 8 + WITH STOP_BITS "ONE" + WITH SLAVE_ID 3 + ADD MAPPING Boiler + WITH SOURCE_TOPIC "boiler/rtu" + WITH EVERY 2 SECONDS + ADD TAG "WaterTemp" + WITH ADDRESS "0" + WITH ADDRESS_TYPE "INPUT_REGISTER" + WITH DATA_TYPE "INT16" + WITH SCALING 0.1 + WITH DEADBAND 0.5 +``` +The serial port is **COM_PORT** (`COM3` on Windows, `/dev/ttyUSB0` on Linux), not PORT. MODBUS_SERIAL is serial +by its type, so CONNECTION_TYPE is not needed. BAUD_RATE must be at least 300; PARITY is NONE/ODD/EVEN/MARK/SPACE; DATA_BITS 7 or 8; +STOP_BITS ONE/TWO/ONEPOINTFIVE; SLAVE_ID 1–247 on a serial line. + ### BACnet/IP ``` DEFINE ROUTE BMS WITH TYPE BACNET @@ -352,6 +398,8 @@ DEFINE ROUTE S7PLC WITH TYPE SIEMENS_S7 WITH ADDRESS "DB1.DBD0" WITH DATA_TYPE "REAL" ``` +CPU_TYPE is one of `S7200`, `S7300`, `S7400`, `S71200` (default) or `S71500` (`S7-1200` / `S7-1500` also +accepted). Anything else, such as `LOGO`, fails validation. SLOT is usually 1 for S7-1200/1500 and 2 for S7-300. ### OPC UA ``` @@ -367,6 +415,64 @@ DEFINE ROUTE OpcServer WITH TYPE OPCUA WITH DATA_TYPE "DOUBLE" ``` +### EtherNet/IP (CIP explicit messaging) +``` +DEFINE ROUTE PackagingLine WITH TYPE ETHERNETIP + ADD ETHERNETIP_CONFIG + WITH IP "192.168.10.20" + WITH PORT 44818 + ADD MAPPING LineStatus + WITH SOURCE_TOPIC "packaging/eip" + WITH EVERY 1 SECONDS + ADD TAG "CycleCount" + WITH ADDRESS "4.100.3.0" + WITH DATA_TYPE "DINT" +``` +ADDRESS is `ClassID.InstanceID.AttributeID.AttributeIndex` (an optional fifth part selects a bit), not a +Logix tag name. IP is required; PORT defaults to 44818. + +### Beckhoff ADS / TwinCAT +``` +DEFINE ROUTE Press1 WITH TYPE ADS + ADD ADS_CONFIG + WITH TARGET_NET_ID "192.168.1.50.1.1" + WITH TARGET_IP "192.168.1.50" + WITH TARGET_PORT 851 + ADD MAPPING PressState + WITH SOURCE_TOPIC "press1/ads" + WITH EVERY 500 MILLISECONDS + ADD TAG "Force" + WITH ADDRESS "GVL_Press.rForce" + WITH ADDRESS_TYPE "SYMBOL" + WITH DATA_TYPE "REAL" +``` +The target is addressed by its AMS Net ID (**TARGET_NET_ID**) and **TARGET_PORT** (851 for TwinCAT 3, 801 for +TwinCAT 2); there is no AMS_NET_ID key. The connector goes through the local AMS router and does not create AMS +routes, so set up the route between this host and the PLC yourself. LOCAL_NET_ID, LOCAL_ROUTE_TO_TARGET, +TARGET_ROUTE_TO_LOCAL, TARGET_USER and TARGET_PASSWORD are accepted but not used. A SYMBOL tag's ADDRESS is the PLC symbol path; ADDRESS_TYPE "INDEX" +takes `"indexGroup,indexOffset"`. + +### Omron FINS +``` +DEFINE ROUTE Oven1 WITH TYPE FINS + ADD FINS_CONFIG + WITH IP "192.168.1.60" + WITH PORT 9600 + WITH PROTOCOL "TCP" + WITH LOCAL_NODE 10 + WITH REMOTE_NODE 60 + ADD MAPPING OvenData + WITH SOURCE_TOPIC "oven1/fins" + WITH EVERY 1 SECONDS + ADD TAG "ZoneTemp" + WITH ADDRESS "100" + WITH MEMORY_TYPE "DM" + WITH DATA_TYPE "INT" + WITH SCALING 0.1 +``` +Nodes are **LOCAL_NODE** / **REMOTE_NODE** (not PC_NODE / PLC_NODE); PROTOCOL is TCP (default) or UDP. A tag's +ADDRESS is the word address and **MEMORY_TYPE** the area (DM default; CIO, WR, HR, AR, CNT, TIM, EM). + ### OT server connectors (MODBUS_SERVER, OPCUA_SERVER) The broker is the device: it serves registers (Modbus) or nodes (OPC UA) to external masters/clients, and the values come from MQTT. The direction is the reverse of an OT client: publishing to a tag's **SOURCE_TOPIC** @@ -423,6 +529,55 @@ Each event with METHOD + ENDPOINT is an HTTP endpoint: the request body is publi **REPLY_TOPIC** the server waits for a message there and returns it (504 after REPLY_TIMEOUT seconds); without it the request is answered `200 accepted` at once. `{session}` is a per-request id. +## MQTT Bridge Connector + +``` +DEFINE ROUTE CloudBridge WITH TYPE MQTT_BRIDGE + ADD SOURCE_CONFIG + WITH BROKER SELF + ADD DESTINATION_CONFIG + WITH BROKER_ADDRESS "mqtt.example.com" + WITH BROKER_PORT 8883 + WITH CLIENT_ID "plant1-bridge" + WITH USE_TLS true + WITH USERNAME GET ENV "CLOUD_MQTT_USER" + WITH PASSWORD GET SECRET "CLOUD_MQTT_PASSWORD" + ADD MAPPING TelemetryUp + WITH SOURCE_TOPIC "plant1/telemetry/#" + WITH DESTINATION_TOPIC "sites/plant1/telemetry/#" + WITH DIRECTION "out" + ADD MAPPING CommandsDown + WITH SOURCE_TOPIC "plant1/commands/#" + WITH DESTINATION_TOPIC "sites/plant1/commands/#" + WITH DIRECTION "in" +``` +`WITH BROKER SELF` makes a side this broker; otherwise each side takes BROKER_ADDRESS, BROKER_PORT (default 1883), +CLIENT_ID, USERNAME, PASSWORD, USE_TLS (plus ALLOW_UNTRUSTED_CERTS and certificate paths). Each mapping's +DIRECTION is `out` (SOURCE_TOPIC on the source side → DESTINATION_TOPIC on the destination), `in` (DESTINATION_TOPIC +on the destination → SOURCE_TOPIC on the source) or `both` (default); `+` and `#` carry over by position. At least +one ADD MAPPING is required, and MQTT_CONFIG is not accepted in place of SOURCE_CONFIG. + +## Email Connector + +``` +DEFINE ROUTE AlertMail WITH TYPE EMAIL + ADD SMTP_CONFIG + WITH HOST "smtp.example.com" + WITH PORT 587 + WITH USERNAME GET ENV "SMTP_USER" + WITH PASSWORD GET SECRET "SMTP_PASSWORD" + WITH USE_TLS true + ADD EVENT SendAlarm + WITH SOURCE_TOPIC "alarms/email" + WITH DESTINATION_TOPIC "alarms/email/status" + WITH SUBJECT "Alarm on {payload.json.machine}" + WITH RECIPIENT "maintenance@example.com" +``` +SMTP_CONFIG needs HOST, USERNAME and PASSWORD (PORT defaults to 587, USE_TLS to true); USERNAME is also the From +address. Each message on SOURCE_TOPIC sends one email to RECIPIENT. The payload is the HTML body unless the event +sets TEMPLATE_PATH to an HTML file. SUBJECT and RECIPIENT accept placeholders; DESTINATION_TOPIC receives the send +status. There are no SERVER, FROM or TO keys. + ## AI Connectors ### LLM Connector @@ -434,6 +589,19 @@ DEFINE ROUTE LocalLLM WITH TYPE LLM WITH TEMPERATURE 0.7 ``` +Cloud provider (PROVIDER `openai`, `anthropic`, or `compatible` for an OpenAI-compatible BASE_URL; default `ollama`): +``` +DEFINE ROUTE Claude WITH TYPE LLM + ADD LLM_CONFIG + WITH PROVIDER "anthropic" + WITH MODEL "claude-sonnet-4-5" + WITH API_KEY GET SECRET "ANTHROPIC_API_KEY" + WITH MAX_TOKENS 1024 +``` +MODEL is required. Cloud providers use their own endpoint when BASE_URL is omitted. MAX_TOKENS caps each +completion (default 2048); SYSTEM_PROMPT applies to CALL LLM; PRICE_INPUT / PRICE_OUTPUT (per million tokens) +turn on cost reporting. + ### MCP Client Connector — stdio transport IMPORTANT: SERVER_ARGUMENTS is COMMA-SEPARATED — each argument is a separate comma-delimited token. @@ -508,6 +676,8 @@ SQLSERVER/MSSQL, MONGODB, CRATEDB, SNOWFLAKE, OPENSEARCH, FILE_STORAGE and REST_ ## Common Mistakes - **WRONG:** DEFINE MODEL (or broker.add_model) for a new Modbus/OPC/S7/device point **RIGHT:** **ADD TAG** inside **ADD MAPPING** on the OT connector; deploy full connector with **broker.add_route** - **WRONG:** Using **DESTINATION_TOPIC** on an OT **ADD MAPPING** as the topic where polled tag data appears **RIGHT:** Data is on **SOURCE_TOPIC** / **`/`** (subscribe or read those topics) +- **WRONG:** **ADD TAG** directly under **DEFINE ROUTE** **RIGHT:** every **ADD TAG** sits inside an **ADD MAPPING** (otherwise: "Unexpected token TAG in route components") +- **WRONG:** MODBUS_SERIAL with **WITH PORT "COM3"** **RIGHT:** **WITH COM_PORT "COM3"** - **NEVER use ADD METADATA in connector definitions.** `ADD METADATA` blocks (WITH IMAGE, WITH DESCRIPTION, WITH DOCLINK) appear in connector *templates* returned by `broker.get_route_template` for documentation purposes only. The LOT parser does **not** support `ADD METADATA` in deployed connectors. Including it in a `DEFINE ROUTE` block will cause a parse error. Always strip `ADD METADATA` and everything under it when generating connector LoT from a template. - Missing WITH TYPE after the connector name - Config block type must match the connector type (e.g., SQL_CONFIG for POSTGRESQL) diff --git a/plugins/coreflux/skills/lot-rules/SKILL.md b/plugins/coreflux/skills/lot-rules/SKILL.md index aa31433..f5ddad3 100644 --- a/plugins/coreflux/skills/lot-rules/SKILL.md +++ b/plugins/coreflux/skills/lot-rules/SKILL.md @@ -1,6 +1,6 @@ --- name: lot-rules -description: How to write LOT permission rules: ALLOW/DENY, topic patterns, user/group conditions, priority-based evaluation, and operation scopes. +description: "How to write LOT permission rules: ALLOW/DENY, topic patterns, user/group conditions, priority-based evaluation, and operation scopes." --- # LOT Rules — Complete Reference @@ -138,6 +138,11 @@ rules): in-flight, trigger payload, live cache (KEEP or PUBLISH; last write wins MQTT retain as a restart fallback. Use TOPIC EXISTS when the grant must be an MQTT retained message. +A permission check has no side effects: GET TOPIC on a topic with no stored value is simply false. +Unlike GET TOPIC in an action, it does not start tracking that topic, so a rule never waits for or +subscribes to a missing allow-list topic. Write the grant (KEEP or a retained publish) before the +client needs it. + ## Topic Patterns Use MQTT wildcards: diff --git a/plugins/coreflux/skills/lot-themes/SKILL.md b/plugins/coreflux/skills/lot-themes/SKILL.md index fd299a6..5fd1b8c 100644 --- a/plugins/coreflux/skills/lot-themes/SKILL.md +++ b/plugins/coreflux/skills/lot-themes/SKILL.md @@ -1,6 +1,6 @@ --- name: lot-themes -description: How to write LoTV theme definitions: DEFINE THEME with design tokens (colors, typography, spacing), EXTENDS inheritance, WHEN MODE light/dark, DEFINE THEME_VARIANT for component overrides, and deployment via broker.add_theme. +description: "How to write LoTV theme definitions: DEFINE THEME with design tokens (colors, typography, spacing), EXTENDS inheritance, WHEN MODE light/dark, DEFINE THEME_VARIANT for component overrides, and deployment via broker.add_theme." --- # LoTV Theme Authoring — Design Token System diff --git a/plugins/coreflux/skills/lot-things/SKILL.md b/plugins/coreflux/skills/lot-things/SKILL.md index 88b9226..39445d7 100644 --- a/plugins/coreflux/skills/lot-things/SKILL.md +++ b/plugins/coreflux/skills/lot-things/SKILL.md @@ -1,6 +1,6 @@ --- name: lot-things -description: How DEFINE THING works: templates and roots, WITH clauses, {{param}} placeholders, references, expanded child names, and why a Thing-owned child must be changed through its Thing. +description: "How DEFINE THING works: templates and roots, WITH clauses, {{param}} placeholders, references, expanded child names, and why a Thing-owned child must be changed through its Thing." --- # LOT Things — DEFINE THING diff --git a/plugins/coreflux/skills/python-scripts/SKILL.md b/plugins/coreflux/skills/python-scripts/SKILL.md index a640abf..77c90b5 100644 --- a/plugins/coreflux/skills/python-scripts/SKILL.md +++ b/plugins/coreflux/skills/python-scripts/SKILL.md @@ -1,6 +1,6 @@ --- name: python-scripts -description: How to write and manage Python scripts: naming conventions, function structure, add/remove scripts, CALL PYTHON from LOT, available modules. +description: "How to write and manage Python scripts: naming conventions, function structure, add/remove scripts, CALL PYTHON from LOT, available modules." --- # Python Scripts — Complete Reference diff --git a/plugins/coreflux/skills/skills.json b/plugins/coreflux/skills/skills.json index b160538..9580030 100644 --- a/plugins/coreflux/skills/skills.json +++ b/plugins/coreflux/skills/skills.json @@ -1,7 +1,11 @@ { "source": "CorefluxCommunity/coreflux-broker-evo", - "brokerVersion": "2.21.16-rc.186", + "brokerVersion": "2.22.0", "skills": [ + { + "name": "broker-operations", + "description": "Operating a Coreflux broker over MQTT: the $SYS/Coreflux/Command payload and the Command/Output reply envelope, the $SYS/Coreflux topic map, route status and action trace JSON, a triage playbook, users, groups and permission flags, env vs secrets, and projects and .lotnb notebooks." + }, { "name": "broker-tools", "description": "Complete reference for the tools you can call on a Coreflux broker: the MCP tool surface the Hub assistant and MCP clients use (validate_lot, deploy_lot, explore_topics, diagnose, provision_data_source and one tool per registry command), the broker__ tools a DEFINE AGENT is granted (read_mqtt, write_mqtt, read_lot, create_lot, execute_routes, execute_actions), Insight vs Agent mode, and the mandatory workflow for deploying LoT safely." diff --git a/scripts/sync-skills.mjs b/scripts/sync-skills.mjs index 7d5292d..b56b5b1 100644 --- a/scripts/sync-skills.mjs +++ b/scripts/sync-skills.mjs @@ -2,13 +2,16 @@ // Bundle the Coreflux agent skills into plugins/coreflux/skills/. // // CorefluxCommunity/coreflux-skills is generated from the broker (its source of truth) and tagged -// per broker release. This copies one tag of it into the plugin. The tag in use is recorded as +// per broker GA release. This copies one tag of it into the plugin. The tag in use is recorded as // `brokerVersion` in plugins/coreflux/skills/skills.json, so a plain run re-syncs the pinned tag. // Skill directories not listed in that manifest (coreflux-cursor-tools) belong to the plugin and // are left alone. Never edit a synced skill here: fix it in the broker and bump the tag. // +// GA tags only: the pin must be a broker GA tag (MAJOR.MINOR.PATCH), never a branch or a release +// candidate. --ref and the synced skills.json are both checked. +// // node scripts/sync-skills.mjs re-sync the pinned tag -// node scripts/sync-skills.mjs --ref 2.21.17 move the pin to another tag +// node scripts/sync-skills.mjs --ref 2.22.0 move the pin to another GA tag // node scripts/sync-skills.mjs --from ../coreflux-skills use a local checkout // node scripts/sync-skills.mjs --check fail if the bundle differs from the pinned tag @@ -19,6 +22,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; const REPO = "https://github.com/CorefluxCommunity/coreflux-skills.git"; +const GA_TAG = /^\d+\.\d+\.\d+$/; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const dest = path.join(root, "plugins", "coreflux", "skills"); const manifestPath = path.join(dest, "skills.json"); @@ -38,7 +42,11 @@ let tmp; if (!source) { const ref = option("--ref") ?? current?.brokerVersion; if (!ref) { - console.error("no pinned tag in plugins/coreflux/skills/skills.json; pass --ref "); + console.error("no pinned tag in plugins/coreflux/skills/skills.json; pass --ref "); + process.exit(1); + } + if (!GA_TAG.test(ref)) { + console.error(`${ref} is not a GA tag (MAJOR.MINOR.PATCH); pin coreflux-skills to GA tags only`); process.exit(1); } tmp = fs.mkdtempSync(path.join(os.tmpdir(), "coreflux-skills-")); @@ -64,6 +72,9 @@ function bundleFiles(dir, manifest) { try { const incoming = readManifest(path.join(source, "skills.json")); + if (!GA_TAG.test(incoming?.brokerVersion ?? "")) { + throw new Error(`coreflux-skills brokerVersion "${incoming?.brokerVersion}" is not a GA version; pin GA tags only`); + } const sourceLayout = { root: path.join(source, "skills"), at: (rel) => (rel === "skills.json" || rel === "LICENSE" ? path.join(source, rel) : path.join(source, "skills", rel)) }; if (check) { @@ -91,7 +102,7 @@ try { for (const skill of incoming.skills) fs.cpSync(path.join(source, "skills", skill.name), path.join(dest, skill.name), { recursive: true }); fs.copyFileSync(path.join(source, "skills.json"), manifestPath); fs.copyFileSync(path.join(source, "LICENSE"), path.join(dest, "LICENSE")); - console.log(`bundled ${incoming.skills.length} skills (broker ${incoming.brokerVersion || "main"}) into plugins/coreflux/skills`); + console.log(`bundled ${incoming.skills.length} skills (broker ${incoming.brokerVersion}) into plugins/coreflux/skills`); } } finally { if (tmp) fs.rmSync(tmp, { recursive: true, force: true });